@rr0/ufoathome 0.141.0 → 0.142.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/dist-embed-scene/ReferenceSystem-DOCydyPG.js +1 -0
- package/dist-embed-scene/rr0-scene.mjs +100 -100
- package/dist-embed-sighting/ReferenceSystem-DKmWxtY-.js +1 -0
- package/dist-embed-sighting/SightingMessages_es-DBRW6jG0.js +1 -0
- package/dist-embed-sighting/SightingMessages_fr-Dwkll3ZY.js +1 -0
- package/dist-embed-sighting/SightingMessages_it-CS1pKPSh.js +1 -0
- package/dist-embed-sighting/rr0-sighting.mjs +13 -13
- package/dist-embed-sighting-editor/GhostSearchView-BiyITIC7.js +1 -0
- package/dist-embed-sighting-editor/PictureFetch-X3UpM6JV.js +1 -0
- package/dist-embed-sighting-editor/ReferenceSystem-D30Dc7NR.js +1 -0
- package/dist-embed-sighting-editor/SightingEditorMessages_es-BXrXCsmJ.js +12 -0
- package/dist-embed-sighting-editor/SightingEditorMessages_fr-DtMIkYvz.js +12 -0
- package/dist-embed-sighting-editor/SightingEditorMessages_it-Cii6z1Lk.js +12 -0
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +248 -240
- package/package.json +1 -1
- package/dist-embed-scene/ReferenceSystem-BdF5Ptvm.js +0 -1
- package/dist-embed-sighting/ReferenceSystem-CEn7MuVP.js +0 -1
- package/dist-embed-sighting/SightingMessages_es-BL3yAPR5.js +0 -1
- package/dist-embed-sighting/SightingMessages_fr-DYXapaAN.js +0 -1
- package/dist-embed-sighting/SightingMessages_it-3b421_Dl.js +0 -1
- package/dist-embed-sighting-editor/GhostSearchView-wZJh23C7.js +0 -1
- package/dist-embed-sighting-editor/ReferenceSystem-8Nl1IFkX.js +0 -1
- package/dist-embed-sighting-editor/SightingEditorMessages_es-DtYML4wO.js +0 -12
- package/dist-embed-sighting-editor/SightingEditorMessages_fr-Bt-2qm0Z.js +0 -12
- package/dist-embed-sighting-editor/SightingEditorMessages_it-DK9cF3wW.js +0 -12
|
@@ -2398,18 +2398,18 @@ canvas[data-cursor="rotate"] {
|
|
|
2398
2398
|
}
|
|
2399
2399
|
`;class $c{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||e.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(e.length===0){const i=t.event.place?.[0];if(!i)return;e.push({t:0,lat:i.lat,lng:i.lng})}return new $c(e)}static TRAVEL_M=50;get travels(){return this.spanM>$c.TRAVEL_M}get moved(){return this.spanM>$c.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,i=(t.west+t.east)/2;return Math.max(Math.abs(ae(e,t.east,e,t.west).x),Math.abs(ae(t.north,i,t.south,i).z))}get center(){const t=this.box;return{lat:(t.south+t.north)/2,lng:(t.west+t.east)/2}}boundsAround(t,e){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+e),t)/2;return{north:fs(0,-s,i,n).lat,south:fs(0,s,i,n).lat,east:fs(s,0,i,n).lng,west:fs(-s,0,i,n).lng}}get box(){const t=this.points.map(i=>i.lat),e=this.points.map(i=>i.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class xs{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t){const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>xs.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new xs(Math.max(1-(t.instrument.stabilization??0),xs.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*e+d),[s,r,a,c,l,h]=xs.HZ;return{eastM:i*xs.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*xs.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*xs.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*xs.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*xs.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*xs.DRIFT_ROLL_DEG*n(s,2.9)}}}class Xe{constructor(t,e){this.stretches=t,this.rotationPassed=e}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(t){const e=$c.of(t);if(!e||e.points.length<2)return;const i=[];let n=0;for(let s=1;s<e.points.length;s++){const r=e.points[s-1],a=e.points[s],c=(a.t-r.t)/1e3;if(c<=0)continue;const l=ae(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=Xe.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?h/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new Xe(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=Xe.of(t)?.offsetAt(e)??Xe.STILL;return i?n:Xe.add(n,xs.of(t)?.offsetAt(e))}static stepHzFor(t){return t<Xe.SLOWEST_WALK_M_PER_S||t>Xe.FASTEST_WALK_M_PER_S?0:Xe.REFERENCE_STEP_HZ*Math.pow(t/Xe.REFERENCE_SPEED_M_PER_S,Xe.CADENCE_EXPONENT)}offsetAt(t){return Xe.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/Xe.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>Xe.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/Xe.JOLT_DECAY_S)*Math.sin(2*Math.PI*Xe.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=e.rampsOut?n(t-e.endMs,Xe.STOP_LURCH_M,Xe.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,Xe.START_LURCH_M,Xe.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(t,e){return e?{eastM:t.eastM+e.eastM,northM:t.northM+e.northM,upM:t.upM+e.upM,rollDeg:t.rollDeg+e.rollDeg,pitchDeg:t.pitchDeg+e.pitchDeg,yawDeg:t.yawDeg+e.yawDeg}:t}cycleAt(t){const e=this.stretches.find(c=>t>=c.startMs&&t<=c.endMs);if(!e||e.stepHz===0)return Xe.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=Xe.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/Xe.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:Xe.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:Xe.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:Xe.HEAD_YAW_DEG*a*Math.cos(n/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,n=Math.min(i,(t.endMs-t.startMs)/2);if(n<=0)return 1;const s=e-t.startMs,r=t.endMs-e,a=Math.min(t.rampsIn?s/n:1,t.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class RS{constructor(t,e){this.timeline=t,this.onFrame=e}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const t=()=>{if(this.state!=="playing")return;const e=performance.now();if(this.currentT+=(e-this.lastWallTime)*this.playbackRate,this.lastWallTime=e,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(t){this.currentT=Math.max(0,Math.min(t,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(t){const e=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}this.onFrame(t,e)}}const Ry=["nw","n","ne","e","se","s","sw","w"],IS=24,qh=8,DS=3,CS=8;function Kh(o,t,e){const i=o.x-t.x,n=o.y-t.y,s=Math.cos(e),r=Math.sin(e);return{x:t.x+i*s-n*r,y:t.y+i*r+n*s}}function Sl(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const OS={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class hs{static handlePointsFor(t){const{x:e,y:i,width:n,height:s}=t.bounds,r={nw:{x:e,y:i},n:{x:e+n/2,y:i},ne:{x:e+n,y:i},e:{x:e+n,y:i+s/2},se:{x:e+n,y:i+s},s:{x:e+n/2,y:i+s},sw:{x:e,y:i+s},w:{x:e,y:i+s/2},rotate:{x:e+n/2,y:i-IS}},a=Sl(t.bounds),c={};for(const l of Object.keys(r))c[l]=Kh(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...Ry,"rotate"]){const s=hs.handlePointsFor(t);for(const r of n)if(Math.hypot(e.x-s[r].x,e.y-s[r].y)<=i)return r}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const n=((hs.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(t,e,i,n){const s=Sl(t),r=Kh(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=OS[i];let d=a,f=c,p=a+l,g=c+h;return u.left&&(d=Math.min(r.x,p-qh)),u.right&&(p=Math.max(r.x,d+qh)),u.top&&(f=Math.min(r.y,g-qh)),u.bottom&&(g=Math.max(r.y,f+qh)),{x:d,y:f,width:p-d,height:g-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=hs.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:r};const a=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*a,y:l.y*c}))}}static rotateShape(t,e){const i=Sl(t.bounds),n=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:n}}static groupBoundsFor(t){const e=Math.min(...t.map(r=>r.x)),i=Math.min(...t.map(r=>r.y)),n=Math.max(...t.map(r=>r.x+r.width)),s=Math.max(...t.map(r=>r.y+r.height));return{x:e,y:i,width:n-e,height:s-i}}static vertexPointsFor(t){const e=Sl(t.bounds);return t.points.map(i=>Kh({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=CS){const n=hs.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const l=Math.hypot(e.x-a.x,e.y-a.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(t,e){const i=Sl(t.bounds),n=Kh(e,i,-t.angle);return{x:n.x-t.bounds.x,y:n.y-t.bounds.y}}static moveVertex(t,e,i){const n=t.points.map((u,d)=>d===e?hs.toLocalPoint(t,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),a=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=hs.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const l=n[c],h=n[(c+1)%n.length],u=hs.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const a=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...t,points:a}}static distanceToSegment(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((t.x-e.x)*n+(t.y-e.y)*s)/r)),c=e.x+a*n,l=e.y+a*s;return Math.hypot(t.x-c,t.y-l)}static deleteVertex(t,e){return t.points.length<=DS?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Op=6,Zh=Op/2,K1=20,Z1=24,J1=9,j1=6,Q1=7,tv=6,js=4;class ol{constructor(t){this.ctx=t}starPoints=0;roll=0;clear(t,e){this.ctx.clearRect(0,0,t,e)}static paintExtent(t){const{x:e,y:i,width:n,height:s}=t.bounds,r=e+n/2,a=i+s/2,c=t.angle%(2*Math.PI)!==0,l=Math.hypot(n,s)/2,h=c?l:n/2,u=c?l:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+J1*f),tv*f)-d:0,g=f>0?d*(1+Q1*f)-d:0,m=3*Z1*(t.blur??0)+1.5*K1*t.haloScale,v=Math.max(p,g,0)+m+2;return{x:r-h-v,y:a-u-v,width:2*(h+v),height:2*(u+v)}}paintInto(t,e,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const s=t.selected?{...t,selected:!1}:t;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(t){this.ctx.save(),this.ctx.globalAlpha=1-t.transparency;const e=t.blur??0;e>0&&(this.ctx.filter=`blur(${(Z1*e).toFixed(2)}px)`);const i=t.brightness??0;i>0&&this.paintDazzle(t,i),t.haloScale>0&&this.paintHalo(t),this.paintBase(t),this.ctx.restore(),t.selected&&this.paintSelectionHandles(t)}setStarPoints(t){this.starPoints=Math.max(0,Math.floor(t))}setRoll(t){this.roll=t}paintDazzle(t,e){const{x:i,y:n,width:s,height:r}=t.bounds,a=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+J1*e),tv*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,h);for(let d=0;d<=j1;d++){const f=d/j1,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(t.color,p*e*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(a,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+Q1*e);this.ctx.lineWidth=Math.max(1,l*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,g=a+Math.cos(p)*d,m=c+Math.sin(p)*d,v=this.ctx.createLinearGradient(a,c,g,m);v.addColorStop(0,this.withAlpha(t.color,e*.55)),v.addColorStop(.35,this.withAlpha(t.color,e*.22)),v.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(a,c),this.ctx.lineTo(g,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:i,width:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=K1*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(hs.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of hs.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,js,js,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(hs.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const n=this.ctx;if(n.save(),t&&t.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(t[0].x,t[0].y);for(const s of t.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of e){const r=ol.landmarkColour(s.residualDeg),a=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=a+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,js+2,js+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,js,js,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,js+2,js+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+js+5,s.picture.y-js-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const a=r.measureText(t).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(e-3,i-2,a+6,s+4),r.fillStyle=n,r.fillText(t,e,i),r.restore()}paintGroupHandles(t){this.paintHandleFrame(hs.handlePointsFor({bounds:t,angle:0}),{includeRotate:!0})}paintOutline(t){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(t.nw.x,t.nw.y),this.ctx.lineTo(t.ne.x,t.ne.y),this.ctx.lineTo(t.se.x,t.se.y),this.ctx.lineTo(t.sw.x,t.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(t,{includeRotate:e}){this.paintOutline(t),this.ctx.fillStyle="lightgray";for(const i of Ry){const n=t[i];this.ctx.fillRect(n.x-Zh,n.y-Zh,Op,Op)}e&&(this.ctx.beginPath(),this.ctx.moveTo(t.n.x,t.n.y),this.ctx.lineTo(t.rotate.x,t.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(t.rotate.x,t.rotate.y,Zh+1,Zh+1,0,0,2*Math.PI),this.ctx.fill())}}const ev=.05,iv=.08,nv=2,sv=3,PS=14,LS=.02;class NS{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}Io.unlock(this.context)}setSound(t){if(this.requested=t,!this.context)return;const e=this.keyFor(t);if(!e){this.silence();return}if(this.voice?.key!==e){this.stopVoice();const i=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,i):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const i=this.context;if(!t||!i)return;const n=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,n,ev);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,ev)}buildSynthesizedVoice(t,e){const i=this.context;if(i)switch(t.kind){case"hum":return this.buildHum(i,e);case"whistle":return this.buildWhistle(i,e);case"rumble":return this.buildRumble(i,e);case"crackle":return this.buildCrackle(i,e);default:return}}buildHum(t,e){const i=t.createOscillator();i.type="sawtooth";const n=t.createOscillator();n.type="sawtooth";const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=t.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const n=t.createOscillator();n.type="sine",n.frequency.value=5;const s=t.createGain(),r=t.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=t.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(t)),i.start(),{key:e,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=t.createGain();s.gain.value=0;const r=t.createBufferSource();r.buffer=this.crackleEnvelope(t),r.loop=!0;const a=t.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(t)),i.start(),r.start(),{key:e,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(t)}catch(c){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",c);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:e,nodes:[a],sources:[r],volumeParam:a.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(t){const e=this.context;if(!e)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*nv),t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*nv),t.sampleRate),i=e.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*sv),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(LS*t.sampleRate)),s=Math.round(sv*PS);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],c*(1-l/n))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const i=e.currentTime;t.volumeParam.cancelScheduledValues(i),t.volumeParam.setTargetAtTime(0,i,iv/3);const n=i+iv;for(const s of t.sources){s.onended=()=>{s.disconnect();for(const r of t.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of t.nodes)r.disconnect()}}}}class or{static KINDS=["beams","launches","reentries"];static isEmpty(t){return!t||or.KINDS.every(e=>!t[e]?.length)}static written(t){if(or.isEmpty(t))return;const e={};for(const i of or.KINDS)t[i]?.length&&(e[i]=t[i]);return e}static read(t,e){const i=e,n={};for(const r of or.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&or.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=or.isReading(l)?l:void 0}return{skyEvents:or.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function ih(o){return[...o].sort((t,e)=>t.t-e.t)}function Zf(o,t){let e;for(const i of ih(o)){if(i.t>t)break;e=i}return e}const Jf=Math.PI/180,Jh=180/Math.PI;class yr{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*Jf/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new yr(t.projection,e,i)}degToPx(t){const e=t*Jf;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jh:2*Math.atan(t/(2*this.focalPx))*Jh}angleDegToRadiusPx(t){const e=t*Jf;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*Jh:Math.atan(t/this.focalPx)*Jh}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(Ze.angularWidthDeg(t))}}class In{static fovOf(t,e){return ze(t,e)?.fovDeg??Bi.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<In.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<In.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=yr.of(t.instrument,Ze.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,ze(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=ze(t,s.t),c=yr.of(t.instrument,Ze.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([m,v])=>m!=="bounds"&&m!=="points"&&JSON.stringify(v)!==JSON.stringify(u[m]))),p={...d,...f},g=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);In.near(g,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=In.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:Bi.frameWidthPx(t.instrument,Ze.CANVAS_HEIGHT_PX)/2,y:Ze.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=In.OFF_CANVAS_DEG?Math.sign(e)*In.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=Bi.frameWidthPx(e,Ze.CANVAS_HEIGHT_PX)/2,s=Bi.frameWidthPx(t.instrument,Ze.CANVAS_HEIGHT_PX)/2,r=Ze.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=yr.of(e,Ze.CANVAS_HEIGHT_PX,l),u=yr.of(t.instrument,Ze.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,g=f.y+f.height/2-r,m=Math.hypot(p,g),v=m===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,y={...f,x:s+p*v-f.width/2,y:r+g*v-f.height/2};return{...d,shape:{...d.shape,bounds:y}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=ze(t,n.t),r=this.fovOf(t,n.t),a=yr.of(t.instrument,Ze.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}function kS(o){return Fn.restore(US(o),o.provenance)}function US(o){return In.toAngular(o),In.toAim(o),{version:1,id:o.id,time:o.event.time,endTime:o.event.endTime,durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:o.event.place,observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:o.timeline.toJSON(),observerTrack:o.observerTrack.toJSON(),weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:o.decor,milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,lens:o.lens,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:o.interpretation,variants:o.variants.length>0?o.variants:void 0,skyEvents:or.written(o.skyEvents),frozen:o.frozen}}function FS(o){ro.check(o,"sighting");const{recording:t,provenance:e}=Fn.strip(o),i=zS(t);return i.provenance=e,i}function zS(o){const t=[],e=new Rf({eventType:"sighting",time:o.time,endTime:o.endTime,durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:o.place,description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Sf.fromJSON(o.timeline,t),o.observerTrack?yh.fromJSON(o.observerTrack):new yh,o.weatherTrack?xh.fromJSON(o.weatherTrack):new xh,o.soundTrack?bh.fromJSON(o.soundTrack):new bh,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,o.decor??[],o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),ih(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.lens=o.lens,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle;const i=or.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.frozen=o.frozen,e.loadIssues=t,In.toBounds(e),In.toPosition(e),e}class cl{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=cl.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${cl.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
2400
2400
|
${i.join(`
|
|
2401
|
-
`)}`)}}class Ls{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!Ls.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Ls.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(Ls.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):Ls.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:Ls.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=Ls.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Ls.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:Ls.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return Ls.isObject(t)&&"value"in t&&Object.keys(t).every(e=>e==="value"||e==="basis"||e==="rationale")}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class Fs{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?Fs.travelDegOver(t,e,i,i+n*1e3)/s/Fs.PIXELS_PER_INSTANT:0,a=Fs.flashesOver(t,n)*Fs.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(Fs.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=Fs.directionAt(r,e,i),c=Fs.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=Er(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}const fg=["en","fr","es","it"],BS={en:()=>we(()=>Promise.resolve().then(()=>YS),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>we(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>we(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>we(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function HS(o){return BS[o]()}const GS={en:()=>we(()=>Promise.resolve().then(()=>NO),void 0,import.meta.url).then(o=>o.sightingMessages_en),fr:()=>we(()=>import("./SightingMessages_fr-DYXapaAN.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>we(()=>import("./SightingMessages_es-BL3yAPR5.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>we(()=>import("./SightingMessages_it-3b421_Dl.js"),[],import.meta.url).then(o=>o.sightingMessages_it)};function VS(o){return GS[o]()}const WS={en:()=>we(()=>Promise.resolve().then(()=>kO),void 0,import.meta.url).then(o=>o.shareMessages_en),fr:()=>we(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>we(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>we(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(o=>o.shareMessages_it)};function XS(o){return WS[o]()}function $S(o){switch(o){case"fr":return we(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return we(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return we(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}function Iy(o){switch(o){case"fr":return we(()=>import("./SceneNames_fr-DixomaFq.js"),[],import.meta.url).then(t=>t.sceneNames_fr);case"es":return we(()=>import("./SceneNames_es-CPCIUfgZ.js"),[],import.meta.url).then(t=>t.sceneNames_es);case"it":return we(()=>import("./SceneNames_it-BTNeU7-M.js"),[],import.meta.url).then(t=>t.sceneNames_it);default:return Promise.resolve(void 0)}}const Dy={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:cl.EN},YS=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:Dy},Symbol.toStringTag,{value:"Module"})),Cy=Math.PI/180,qS=180/Math.PI,KS=256,Oy=19,ZS=1.25;function Py(o,t){return 156543.03392*Math.cos(o*Cy)/2**t}function Ly(o,t){return Py(o,t)*KS}function JS(o,t){let e=0;for(;e<Oy&&Ly(o,e+1)>=t;)e++;return e}function Ny(o,t){return Ly(o,t)}function jS(o,t){const e=t*ZS;let i=0;for(;i<Oy&&Py(o,i)>e;)i++;return i}function ad(o){const t=o*Cy;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function ky(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:ad(t)*i}}function Uy(o,t,e){const i=ad(o.north),n=ad(o.south);return{x:(t-o.west)/(o.east-o.west),y:(ad(e)-i)/(n-i)}}function QS(o,t,e){const{x:i,y:n}=ky(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function tE(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=rv(o.y,t);return{south:rv(o.y+1,t),north:n,west:e,east:i}}function rv(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*qS}function Fy(o,t,e,i){const n=QS(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(tE),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const eE="#2ec4ff";class eo{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=Uy(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??eE;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:eo.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,eo.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=ae(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=eo.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?eo.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(ae(r,t.east,r,t.west).x)/this.width,l=eo.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class Qe{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(t,e){return Qe.including(t.boundsAround(Qe.MIN_SPAN_M,Qe.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(Qe.MAX_ZOOM,Math.max(Qe.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=Qe.mercatorY01(e.north),s=Qe.mercatorY01(e.south),r=Qe.mercatorY01(i.north),a=Qe.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=Qe.mercatorY01(n.north),r=Qe.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(Qe.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=Qe.mercatorY01(t.north),n=Qe.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:Qe.latitudeAt(i+(this.centerY-e)*(n-i)),south:Qe.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=ae(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=ae(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:fs(0,-a,n,s).lat,south:fs(0,a,n,s).lat,east:fs(a,0,n,s).lng,west:fs(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=Qe.mercatorY01(t.north),s=Qe.mercatorY01(t.south);return{lat:Qe.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const Ms=256,av=3,iE=32768;class nE{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(ae(i,t.east,i,t.west).x),r=Math.abs(ae(t.north,n,t.south,n).z),a=JS(i,Math.max(s,r)),{tiles:c}=Fy(n,i,a,av),l=av*Ms,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let g=0;g<e.width;g++){const m=t.west+(t.east-t.west)*(g/(e.width-1));d[f*e.width+g]=this.sampleAt(p,m,a,u,h,l)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=Ms,c.height=Ms;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,Ms,Ms),u=(t.x-e.x)*Ms,d=(t.y-e.y)*Ms;for(let f=0;f<Ms;f++)for(let p=0;p<Ms;p++){const g=(f*Ms+p)*4,m=h[g]*256+h[g+1]+h[g+2]/256-iE,v=u+p,y=d+f;i[y*n+v]=m}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=ky(e,t,i),l=(a-n.x)*Ms,h=(c-n.y)*Ms,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),g=l-u,m=h-d,v=s[d*r+u],y=s[d*r+f],x=s[p*r+u],M=s[p*r+f],b=v+(y-v)*g,S=x+(M-x)*g;return b+(S-b)*m}}class Df{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const y=i+2+v*12;s.set(e.getUint16(y,!0),{type:e.getUint16(y+2,!0),count:e.getUint32(y+4,!0),value:e.getUint32(y+8,!0)})}const r=(v,y)=>{const x=s.get(v);if(x===void 0){if(y===void 0)throw new Error(`TIFF without tag ${v}`);return y}return x.type===3?x.value&65535:x.value},a=v=>{const y=s.get(v);if(y===void 0)throw new Error(`TIFF without tag ${v}`);const x=y.type===3?2:4,M=[];if(y.count*x<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,y.value,!0);for(let S=0;S<y.count;S++)M.push(x===2?b.getUint16(S*2,!0):b.getUint32(0,!0))}else for(let b=0;b<y.count;b++)M.push(x===2?e.getUint16(y.value+b*2,!0):e.getUint32(y.value+b*4,!0));return M};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),g=new Uint8Array(c*l*h*(u/8));let m=0;for(let v=0;v<f.length&&m<g.length;v++){const y=Math.min(p[v],g.length-m);g.set(new Uint8Array(t,f[v],y),m),m+=y}if(m<g.length)throw new Error("Truncated TIFF");return new Df(c,l,h,d?new Float32Array(g.buffer):g)}}class aa extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class sE{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class Re{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Re.WMS,this.wfs=t.wfsEndpoint??Re.WFS}static radius(t){return Math.min(t,Re.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Re.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Re.lidarRadius(e),n=Math.ceil(2*i/Re.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Re.HEIGHT_LAYER),this.raster(t,i,n,Re.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new aa("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Re.NO_DATA))throw new aa("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new sE(a,c,l,n,h)}}async laserDate(t){return Re.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Re.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=Re.radius(e),n=Math.min(Re.MAX_PHOTO_PIXELS,Math.ceil(2*i/Re.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Re.PHOTO_LAYER);if(s.samples<3)throw new aa("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=Re.radius(e),s=n/Re.METRES_PER_DEGREE,r=n/(Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,Re.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),g=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],m=[...f,...g];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:m,zones:p,mapDate:Re.latest(m.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=Re.MAX_WHOLE_M/Re.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,g]=Re.extent(u);if(d>=n&&f>=s&&p<=r&&g<=a)continue;const m=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(g,a+c)];l=l?[Math.min(l[0],m[0]),Math.min(l[1],m[1]),Math.max(l[2],m[2]),Math.max(l[3],m[3])]:m}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Re.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/Re.METRES_PER_DEGREE,r=e/(Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new aa("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new aa("unreachable",`The survey answered ${c.status}`);try{return Df.parse(await c.arrayBuffer())}catch(l){throw new aa("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new aa("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new aa("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class ba{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>ae(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ae(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/ba.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,g=ba.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);g.distanceM>ba.NEAR_M||ba.angleBetween(d,g.heading)<=ba.ALIGNED_DEG&&(r+=h/u)}}return r>=ba.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class xe{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??xe.WMS,this.timeoutMs=t.timeoutMs??xe.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??xe.MAX_WINDOW_M,this.geoplatform=new Re({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Re.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ae(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ae(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/xe.METRES_PER_DEGREE,north:t.north+c.y/xe.METRES_PER_DEGREE,west:t.west-c.x/(xe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(xe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=g=>Math.min(xe.MAX_PIXELS,Math.max(xe.MIN_PIXELS,Math.ceil(g/xe.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>xe.COARSE_METRES_PER_PIXEL;for(const g of p?[...xe.LAYERS].reverse():xe.LAYERS)try{const m=await this.heights(l,u,g);g===xe.LAYERS[0]&&await this.layBridgeDecks(m,l,u,i?.route);const v=this.sample(m,e,t,l,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${g} does not cover this place`)}catch(m){f=m}throw f}finer(t,e,i){if(t.width<xe.MESH_FROM_VERTICES||t.height<xe.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/xe.FINE_SPACING_M),c=Math.max(r-1,Math.min(xe.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return Df.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>xe.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>ba.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,xe.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(m,[v,y,x])=>s.values[m*s.samples]===v&&s.values[m*s.samples+1]===y&&s.values[m*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let m=0;m<l.length;m++)r(m,xe.DECK)&&(l[m]=1,h=!0);if(!h)return;const u=xe.DECK_END_PIXELS,d=[];for(let m=0;m<l.length;m++){if(l[m]!==1)continue;const v=m%a,y=(m-v)/a;for(let x=-u;x<=u;x++)for(let M=-u;M<=u;M++){const b=v+M,S=y+x;if(b<0||S<0||b>=a||S>=c)continue;const E=S*a+b;l[E]===0&&r(E,xe.NO_CLASS)&&d.push(E)}}for(const m of d)l[m]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(m=>m===0))return;const g=await this.heights(e,i,xe.SURFACE_LAYER);if(g.width!==a||g.height!==c)return;for(let m=0;m<p.length;m++){if(p[m]===0)continue;const v=g.values[m];Number.isFinite(v)&&v>xe.NO_DATA_BELOW&&v>t.values[m]&&(t.values[m]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*xe.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*xe.METRES_PER_DEGREE,h=c/s,u=l/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,y:(i.north-v.lat)/(i.north-i.south)*l}),f=(v,y)=>{const x=Math.floor(v/h),M=Math.floor(y/u);if(x<0||M<0||x>=s||M>=r)return;const b=e[M*s+x];return Number.isFinite(b)&&b>xe.NO_DATA_BELOW?b:void 0},p=xe.DECK_HALF_WIDTH_M,g=xe.DECK_APPROACH_M,m=(v,y)=>{const x=Math.hypot(v.x-y.x,v.y-y.y)||1,M={x:(v.x-y.x)/x,y:(v.y-y.y)/x},b=[0,g/2,g].map(S=>f(v.x+M.x*S,v.y+M.y*S)).filter(S=>S!==void 0);return b.length>0?Math.max(...b):void 0};for(const v of xe.chains(n.map(y=>y.map(d)))){const y=[0];for(let I=1;I<v.length;I++)y.push(y[I-1]+Math.hypot(v[I].x-v[I-1].x,v[I].y-v[I-1].y));const x=y[y.length-1];if(x<1||x>xe.DECK_STRAIGHT_MAX_M)continue;const M=m(v[0],v[1]),b=m(v[v.length-1],v[v.length-2]);if(M===void 0||b===void 0)continue;const S=p+g,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-S)/h)),w=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+S)/h)),_=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-S)/u)),D=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+S)/u));for(let I=_;I<=D;I++)for(let O=E;O<=w;O++){const L=xe.nearestAlong(v,y,{x:(O+.5)*h,y:(I+.5)*u});if(L.distance>p||L.s<-g||L.s>x+g)continue;const N=M+(b-M)*Math.min(1,Math.max(0,L.s/x)),P=I*s+O;e[P]>=N||(t.values[P]=N)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let g=0;g<=p;g++){const m=Math.floor(h+(d-h)*g/p),v=Math.floor(u+(f-u)*g/p);for(let y=-1;y<=1;y++)for(let x=-1;x<=1;x++){const M=m+x,b=v+y;M>=0&&b>=0&&M<i&&b<n&&(s[b*i+M]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let g=-1;g<=1;g++){const m=d+g,v=f+p;if(m<0||v<0||m>=i||v>=n)continue;const y=v*i+m;t[y]===1&&r[y]===0&&(r[y]=1,l.push(y))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const g=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),m=(n.north-g)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const x=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,M=u>1||d>1?this.tent(t,x,m,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,m),b=p*a+v;M===void 0?f++:(l[b]=M,h[b]=1)}}if(!(f===a*c||f/(a*c)>xe.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let g=u;g<=d;g++){const m=p*(1-Math.abs(g-e)/n);if(m<=0)continue;c+=m;const v=t.at(g,f);!Number.isFinite(v)||v<xe.NO_DATA_BELOW||(r+=m*v,a+=m)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const m of[h,u,d,f])if(!Number.isFinite(m)||m<xe.NO_DATA_BELOW)return;const p=h+(u-h)*c,g=d+(f-d)*c;return p+(g-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,g=c+f;p<0||g<0||p>=n||g>=i||!e[p*i+g]||(h+=t[p*i+g],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class rE{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const od=256,aE=5;async function zy(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ae(n,o.east,n,o.west).x),a=Math.abs(ae(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=oE(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Fy(s,n,l,h),f=h*od,p=document.createElement("canvas");p.width=f,p.height=f;const g=p.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async M=>{const b=e(M),S=await i(b);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${b}`);const E=await createImageBitmap(await S.blob());g.drawImage(E,(M.x-m.x)*od,(M.y-m.y)*od)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const y=document.createElement("canvas");y.width=v,y.height=v;const x=y.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,v,v),{source:y,width:v,height:v,bounds:d}}function oE(o,t,e){let i=jS(o,t/Math.max(1,e)),n=ov(o,i,t);for(;n>aE&&i>0;)i--,n=ov(o,i,t);return{zoom:i,gridSize:n,mPerPixel:Ny(o,i)/od}}function ov(o,t,e){const i=Math.ceil(e/2/Ny(o,t));return Math.max(3,2*i+1)}class By{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(t,e){return zy(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Zn{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=Zn.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=Zn.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Zn.FRANCE_ENDPOINT,...e.filter(d=>d!==Zn.FRANCE_ENDPOINT)]:[...e]}fetchImpl;endpoints;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.endpoints=t.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(t){return this.queued(()=>this.ask(t))}queued(t){const e=Zn.queue.then(t,t);return Zn.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Zn.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Zn.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,Zn.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class wa{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(t={}){this.client=new Zn(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${wa.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:wa.surfaceOf(s),widthM:wa.widthOf(s),...wa.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:wa.WIDTH_M[t.highway]??wa.DEFAULT_WIDTH_M}static surfaceOf(t){const e=t.surface;return e==="dirt"||e==="earth"||e==="mud"?"dirt":e==="gravel"||e==="fine_gravel"||e==="compacted"||e==="ground"||e==="sand"||e==="unpaved"?"gravel":e?"paved":t.highway==="track"?"gravel":"paved"}}const jf="https://ufoathome.org/roads/index.json";class Cc{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Cc.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2402
|
-
`);let e=Cc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Cc.shared.set(t,e),e.then(i=>{i.length===0&&Cc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.
|
|
2403
|
-
`);let e=Oc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Oc.shared.set(t,e),e.then(i=>{i.length===0&&Oc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.141.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Qf?[e,Qf]:[Qf]).map(i=>i+t)}}class Xn{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Xn.key(t);let i=Xn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Xn.asked.set(e,i),i.catch(()=>Xn.asked.delete(e))),structuredClone(await i)}static forget(){Xn.asked.clear()}static key(t){return`v${Xn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Xn.openCache(),n=Xn.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<Xn.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Xn.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-Xn.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Ta{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Re(t)}static covers(t){return Re.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Ta.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Ta.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Ta.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Ta.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Ta.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class pn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Zn(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=pn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ae(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of pn.samples(a)){u++;const y=pn.waysAt(d,v);if(y.length===0)continue;const[x]=y;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const M of new Set(y.flatMap(b=>b.services)))h.set(M,(h.get(M)??0)+1)}const f=v=>[...v.entries()].sort((y,x)=>x[1]-y[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,y)=>y[1]-v[1]||v[0].localeCompare(y[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=pn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=pn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=pn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=pn.SAMPLE_M/2;a<n;a+=pn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(pn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=pn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Pc{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Zn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Pc.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=pn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=pn.voltageOf(r),l=Pc.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Pc.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:Pc.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class hE{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!Ta.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class Xi{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=Xi.key(t);let i=Xi.asked.get(e)??Xi.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},Xi.asked.set(e,i),n.catch(()=>Xi.asked.delete(e))}return structuredClone(await i.answer)}static forget(){Xi.asked.clear(),Xi.failedAt=-1/0}static key(t){return`v${Xi.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of Xi.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await Xi.openCache(),n=Xi.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<Xi.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-Xi.failedAt<Xi.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(Xi.failedAt=this.now(),s)return s;throw a}return i&&Xi.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-Xi.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xi.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const t0="https://ufoathome.org/railways/index.json";class Lc{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Lc.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2404
|
-
`);let e=Lc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Lc.shared.set(t,e),e.then(i=>{i.length===0&&Lc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.141.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==t0?[e,t0]:[t0]).map(i=>i+t)}}function Hy(){return{elevation:uE(),imagery:Gy(),roads:dE(),water:fE(),railways:pE()}}function uE(){return new rE(new xe,new nE)}function Gy(){return new By}function dE(){return new Cc({fallback:new cE(new _a,new wa)})}function fE(){return new Oc({fallback:new Xn(new lE(new Eh,new io))})}function pE(){return new Lc({fallback:new Xi(new hE(new Ta,new Pc))})}const mE=new Set,Ar="show-observer-map",_r="hide-milestones",bo="minified";class Le extends HTMLElement{static get observedAttributes(){return["src",Ar,_r,bo]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Qe;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Rf.create();issues=[];issueCheck=0;sightingAudio=new NS;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Le.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=Dy;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Le.setIcon(this.moreButton,t?qt.UNFOLDED:qt.FOLDED);const e=t?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Le.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Qe.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Qe.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Le.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=Qe.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${TS}</style>${_S}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new ol(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new eo(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Ar&&this.applyObserverMapDefault(),t===_r&&this.setMilestonesShown(!this.hasAttribute(_r)),t===bo){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(bo)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Wy)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await Na.recording(t)}get sightingData(){return kS(this.currentSighting)}set sightingData(t){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=FS(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await we(async()=>{const{default:r}=await import("./sightingSchema-t3YCF0eV.js");return{default:r}},[],import.meta.url);n=new Ls(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],cl.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(gE,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=this.messages.recordingIssues.replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=cl.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages.referenceOpacity,l.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Le.setIcon(this.referencesButton,i?qt.PICTURES_ON:qt.PICTURES_OFF);const n=e?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Le.setIcon(this.tracesButton,this.tracesShownState?qt.TRACES_ON:qt.TRACES_OFF);const t=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?ih(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Le.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Le.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?Zf(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new ol(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Le.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Zf(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=Fs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Le.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Le.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Le.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Le.EXPOSURE_STEP_PX),s=Math.min(Le.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Bi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:mE;this.canvasRenderer.setStarPoints(Bi.starPointsOf(this.sighting.instrument));const n=(ze(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?hs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(wy(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new RS(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Le.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?qt.PLAY:qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Le.icons.get(t)!==e&&(Le.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Le.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Le.setIcon(this.playPauseButton,t?qt.PAUSE:qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Ar),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Le.setIcon(this.observerMapButton,t?qt.MAP_ON:qt.MAP_OFF);const e=t?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=$c.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Qe.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?Qe.expand(t,Le.OBSERVER_MAP_IMAGERY_AHEAD):t,n=Qe.IMAGERY_PX*(e?1+2*Le.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:Gy();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?Qe.expand(t,Le.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(t){t!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Le.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ze(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Le.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Zf(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ih(this.currentSighting.milestones):[]){const a=ze(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?yr.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Bi.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ih(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages.moments,Le.setIcon(this.milestonesButton,this.milestonesShown?qt.MILESTONES_ON:qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=ze(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Er(i,t),{lat:s,lng:r}=fs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=ze(this.currentSighting,this.currentTime),s=yr.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return Xe.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Le.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Le.setIcon(this.miniMuteButton,this.mutedState?qt.MUTED:qt.VOLUME);const e=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Le.setIcon(this.muteButton,qt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Le.setIcon(this.muteButton,this.mutedState?qt.MUTED:qt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Le.setIcon(this.fullscreenButton,t?qt.EXIT_FULLSCREEN:qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Es(ka.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=dg(ka.preferencesFor(this),fg);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await HS(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=this.messages.currentPosition+e,this.timeEndLabel.title=this.messages.duration+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=by(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Dp(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return oa(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?lv(cv(this.realStartMs+i)):oa(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?oa(t):oa(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return oa(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return oa(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?oa(this.currentSighting.timeline.duration):this.canShowClockTime?lv(cv(this.realStartMs+this.realDurationMs)):oa(this.realDurationMs)}}function cv(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function lv(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function oa(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Pp="rr0-ufo";function Vy(){customElements.get(Pp)||customElements.define(Pp,Le)}const gE="recordingissues",Wy="minifiedreset";/**
|
|
2401
|
+
`)}`)}}class Ls{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!Ls.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Ls.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(Ls.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):Ls.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:Ls.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=Ls.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Ls.typeOf(t)});return;default:typeof t!==e.type&&n.push({kind:"wrong-type",path:i,expected:e.type,found:Ls.typeOf(t)})}}static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return Ls.isObject(t)&&"value"in t&&Object.keys(t).every(e=>e==="value"||e==="basis"||e==="rationale")}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class Fs{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?Fs.travelDegOver(t,e,i,i+n*1e3)/s/Fs.PIXELS_PER_INSTANT:0,a=Fs.flashesOver(t,n)*Fs.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(Fs.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=Fs.directionAt(r,e,i),c=Fs.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=Er(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}const fg=["en","fr","es","it"],BS={en:()=>we(()=>Promise.resolve().then(()=>YS),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>we(()=>import("./UfoMessages_fr-Cs2GCHEt.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>we(()=>import("./UfoMessages_es-BRCWkzr3.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>we(()=>import("./UfoMessages_it-B2hvjhgb.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function HS(o){return BS[o]()}const GS={en:()=>we(()=>Promise.resolve().then(()=>kO),void 0,import.meta.url).then(o=>o.sightingMessages_en),fr:()=>we(()=>import("./SightingMessages_fr-Dwkll3ZY.js"),[],import.meta.url).then(o=>o.sightingMessages_fr),es:()=>we(()=>import("./SightingMessages_es-DBRW6jG0.js"),[],import.meta.url).then(o=>o.sightingMessages_es),it:()=>we(()=>import("./SightingMessages_it-CS1pKPSh.js"),[],import.meta.url).then(o=>o.sightingMessages_it)};function VS(o){return GS[o]()}const WS={en:()=>we(()=>Promise.resolve().then(()=>UO),void 0,import.meta.url).then(o=>o.shareMessages_en),fr:()=>we(()=>import("./ShareMessages_fr-DyOB2E5o.js"),[],import.meta.url).then(o=>o.shareMessages_fr),es:()=>we(()=>import("./ShareMessages_es-BM5hHumO.js"),[],import.meta.url).then(o=>o.shareMessages_es),it:()=>we(()=>import("./ShareMessages_it-C9F8UHk_.js"),[],import.meta.url).then(o=>o.shareMessages_it)};function XS(o){return WS[o]()}function $S(o){switch(o){case"fr":return we(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(t=>t.tagNames_fr);case"es":return we(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(t=>t.tagNames_es);case"it":return we(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(t=>t.tagNames_it);default:return Promise.resolve({})}}function Iy(o){switch(o){case"fr":return we(()=>import("./SceneNames_fr-DixomaFq.js"),[],import.meta.url).then(t=>t.sceneNames_fr);case"es":return we(()=>import("./SceneNames_es-CPCIUfgZ.js"),[],import.meta.url).then(t=>t.sceneNames_es);case"it":return we(()=>import("./SceneNames_it-BTNeU7-M.js"),[],import.meta.url).then(t=>t.sceneNames_it);default:return Promise.resolve(void 0)}}const Dy={play:"Play",clickToPlay:"Click to play",pause:"Pause",noDuration:"No observation duration",currentPosition:"Current position",duration:"Duration",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",mute:"Mute",unmute:"Unmute",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:cl.EN},YS=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:Dy},Symbol.toStringTag,{value:"Module"})),Cy=Math.PI/180,qS=180/Math.PI,KS=256,Oy=19,ZS=1.25;function Py(o,t){return 156543.03392*Math.cos(o*Cy)/2**t}function Ly(o,t){return Py(o,t)*KS}function JS(o,t){let e=0;for(;e<Oy&&Ly(o,e+1)>=t;)e++;return e}function Ny(o,t){return Ly(o,t)}function jS(o,t){const e=t*ZS;let i=0;for(;i<Oy&&Py(o,i)>e;)i++;return i}function ad(o){const t=o*Cy;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function ky(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:ad(t)*i}}function Uy(o,t,e){const i=ad(o.north),n=ad(o.south);return{x:(t-o.west)/(o.east-o.west),y:(ad(e)-i)/(n-i)}}function QS(o,t,e){const{x:i,y:n}=ky(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function tE(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=rv(o.y,t);return{south:rv(o.y+1,t),north:n,west:e,east:i}}function rv(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*qS}function Fy(o,t,e,i){const n=QS(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(tE),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const eE="#2ec4ff";class eo{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const n=Uy(t,i,e);return{x:n.x*this.width,y:n.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const n=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??eE;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:n.x,y:n.y,radius:eo.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,eo.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=ae(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=eo.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?eo.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(ae(r,t.east,r,t.west).x)/this.width,l=eo.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class Qe{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(t,e){return Qe.including(t.boundsAround(Qe.MIN_SPAN_M,Qe.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const n=Math.min(Qe.MAX_ZOOM,Math.max(Qe.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),n=Qe.mercatorY01(e.north),s=Qe.mercatorY01(e.south),r=Qe.mercatorY01(i.north),a=Qe.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=Qe.mercatorY01(n.north),r=Qe.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(Qe.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=Qe.mercatorY01(t.north),n=Qe.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:Qe.latitudeAt(i+(this.centerY-e)*(n-i)),south:Qe.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=ae(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=ae(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:fs(0,-a,n,s).lat,south:fs(0,a,n,s).lat,east:fs(a,0,n,s).lng,west:fs(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=Qe.mercatorY01(t.north),s=Qe.mercatorY01(t.south);return{lat:Qe.latitudeAt(n+i*(s-n)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const Ms=256,av=3,iE=32768;class nE{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,n=(t.west+t.east)/2,s=Math.abs(ae(i,t.east,i,t.west).x),r=Math.abs(ae(t.north,n,t.south,n).z),a=JS(i,Math.max(s,r)),{tiles:c}=Fy(n,i,a,av),l=av*Ms,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let g=0;g<e.width;g++){const m=t.west+(t.east-t.west)*(g/(e.width-1));d[f*e.width+g]=this.sampleAt(p,m,a,u,h,l)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=Ms,c.height=Ms;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,Ms,Ms),u=(t.x-e.x)*Ms,d=(t.y-e.y)*Ms;for(let f=0;f<Ms;f++)for(let p=0;p<Ms;p++){const g=(f*Ms+p)*4,m=h[g]*256+h[g+1]+h[g+2]/256-iE,v=u+p,y=d+f;i[y*n+v]=m}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=ky(e,t,i),l=(a-n.x)*Ms,h=(c-n.y)*Ms,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),g=l-u,m=h-d,v=s[d*r+u],y=s[d*r+f],x=s[p*r+u],M=s[p*r+f],b=v+(y-v)*g,S=x+(M-x)*g;return b+(S-b)*m}}class Df{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const y=i+2+v*12;s.set(e.getUint16(y,!0),{type:e.getUint16(y+2,!0),count:e.getUint32(y+4,!0),value:e.getUint32(y+8,!0)})}const r=(v,y)=>{const x=s.get(v);if(x===void 0){if(y===void 0)throw new Error(`TIFF without tag ${v}`);return y}return x.type===3?x.value&65535:x.value},a=v=>{const y=s.get(v);if(y===void 0)throw new Error(`TIFF without tag ${v}`);const x=y.type===3?2:4,M=[];if(y.count*x<=4){const b=new DataView(new ArrayBuffer(4));b.setUint32(0,y.value,!0);for(let S=0;S<y.count;S++)M.push(x===2?b.getUint16(S*2,!0):b.getUint32(0,!0))}else for(let b=0;b<y.count;b++)M.push(x===2?e.getUint16(y.value+b*2,!0):e.getUint32(y.value+b*4,!0));return M};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),g=new Uint8Array(c*l*h*(u/8));let m=0;for(let v=0;v<f.length&&m<g.length;v++){const y=Math.min(p[v],g.length-m);g.set(new Uint8Array(t,f[v],y),m),m+=y}if(m<g.length)throw new Error("Truncated TIFF");return new Df(c,l,h,d?new Float32Array(g.buffer):g)}}class aa extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class sE{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}class Re{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Re.WMS,this.wfs=t.wfsEndpoint??Re.WFS}static radius(t){return Math.min(t,Re.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Re.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Re.lidarRadius(e),n=Math.ceil(2*i/Re.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Re.HEIGHT_LAYER),this.raster(t,i,n,Re.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new aa("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Re.NO_DATA))throw new aa("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new sE(a,c,l,n,h)}}async laserDate(t){return Re.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Re.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=Re.radius(e),n=Math.min(Re.MAX_PHOTO_PIXELS,Math.ceil(2*i/Re.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Re.PHOTO_LAYER);if(s.samples<3)throw new aa("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=Re.radius(e),s=n/Re.METRES_PER_DEGREE,r=n/(Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,Re.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),g=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],m=[...f,...g];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:m,zones:p,mapDate:Re.latest(m.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[n,s,r,a]=i,c=Re.MAX_WHOLE_M/Re.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,g]=Re.extent(u);if(d>=n&&f>=s&&p<=r&&g<=a)continue;const m=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(g,a+c)];l=l?[Math.min(l[0],m[0]),Math.min(l[1],m[1]),Math.max(l[2],m[2]),Math.max(l[3],m[3])]:m}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Re.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,n){const s=e/Re.METRES_PER_DEGREE,r=e/(Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new aa("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new aa("unreachable",`The survey answered ${c.status}`);try{return Df.parse(await c.arrayBuffer())}catch(l){throw new aa("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new aa("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new aa("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class ba{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],n=e.map(a=>ae(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>ae(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/ba.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,g=ba.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);g.distanceM>ba.NEAR_M||ba.angleBetween(d,g.heading)<=ba.ALIGNED_DEG&&(r+=h/u)}}return r>=ba.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class xe{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??xe.WMS,this.timeoutMs=t.timeoutMs??xe.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??xe.MAX_WINDOW_M,this.geoplatform=new Re({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Re.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(ae(n.lat,t.east,n.lat,t.west).x),r=Math.abs(ae(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/xe.METRES_PER_DEGREE,north:t.north+c.y/xe.METRES_PER_DEGREE,west:t.west-c.x/(xe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(xe.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=g=>Math.min(xe.MAX_PIXELS,Math.max(xe.MIN_PIXELS,Math.ceil(g/xe.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>xe.COARSE_METRES_PER_PIXEL;for(const g of p?[...xe.LAYERS].reverse():xe.LAYERS)try{const m=await this.heights(l,u,g);g===xe.LAYERS[0]&&await this.layBridgeDecks(m,l,u,i?.route);const v=this.sample(m,e,t,l,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${g} does not cover this place`)}catch(m){f=m}throw f}finer(t,e,i){if(t.width<xe.MESH_FROM_VERTICES||t.height<xe.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/xe.FINE_SPACING_M),c=Math.max(r-1,Math.min(xe.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return Df.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>xe.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>ba.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,xe.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(m,[v,y,x])=>s.values[m*s.samples]===v&&s.values[m*s.samples+1]===y&&s.values[m*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let m=0;m<l.length;m++)r(m,xe.DECK)&&(l[m]=1,h=!0);if(!h)return;const u=xe.DECK_END_PIXELS,d=[];for(let m=0;m<l.length;m++){if(l[m]!==1)continue;const v=m%a,y=(m-v)/a;for(let x=-u;x<=u;x++)for(let M=-u;M<=u;M++){const b=v+M,S=y+x;if(b<0||S<0||b>=a||S>=c)continue;const E=S*a+b;l[E]===0&&r(E,xe.NO_CLASS)&&d.push(E)}}for(const m of d)l[m]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(m=>m===0))return;const g=await this.heights(e,i,xe.SURFACE_LAYER);if(g.width!==a||g.height!==c)return;for(let m=0;m<p.length;m++){if(p[m]===0)continue;const v=g.values[m];Number.isFinite(v)&&v>xe.NO_DATA_BELOW&&v>t.values[m]&&(t.values[m]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*xe.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*xe.METRES_PER_DEGREE,h=c/s,u=l/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,y:(i.north-v.lat)/(i.north-i.south)*l}),f=(v,y)=>{const x=Math.floor(v/h),M=Math.floor(y/u);if(x<0||M<0||x>=s||M>=r)return;const b=e[M*s+x];return Number.isFinite(b)&&b>xe.NO_DATA_BELOW?b:void 0},p=xe.DECK_HALF_WIDTH_M,g=xe.DECK_APPROACH_M,m=(v,y)=>{const x=Math.hypot(v.x-y.x,v.y-y.y)||1,M={x:(v.x-y.x)/x,y:(v.y-y.y)/x},b=[0,g/2,g].map(S=>f(v.x+M.x*S,v.y+M.y*S)).filter(S=>S!==void 0);return b.length>0?Math.max(...b):void 0};for(const v of xe.chains(n.map(y=>y.map(d)))){const y=[0];for(let I=1;I<v.length;I++)y.push(y[I-1]+Math.hypot(v[I].x-v[I-1].x,v[I].y-v[I-1].y));const x=y[y.length-1];if(x<1||x>xe.DECK_STRAIGHT_MAX_M)continue;const M=m(v[0],v[1]),b=m(v[v.length-1],v[v.length-2]);if(M===void 0||b===void 0)continue;const S=p+g,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-S)/h)),w=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+S)/h)),_=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-S)/u)),D=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+S)/u));for(let I=_;I<=D;I++)for(let O=E;O<=w;O++){const L=xe.nearestAlong(v,y,{x:(O+.5)*h,y:(I+.5)*u});if(L.distance>p||L.s<-g||L.s>x+g)continue;const N=M+(b-M)*Math.min(1,Math.max(0,L.s/x)),P=I*s+O;e[P]>=N||(t.values[P]=N)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let g=0;g<=p;g++){const m=Math.floor(h+(d-h)*g/p),v=Math.floor(u+(f-u)*g/p);for(let y=-1;y<=1;y++)for(let x=-1;x<=1;x++){const M=m+x,b=v+y;M>=0&&b>=0&&M<i&&b<n&&(s[b*i+M]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let g=-1;g<=1;g++){const m=d+g,v=f+p;if(m<0||v<0||m>=i||v>=n)continue;const y=v*i+m;t[y]===1&&r[y]===0&&(r[y]=1,l.push(y))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const g=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),m=(n.north-g)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const x=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,M=u>1||d>1?this.tent(t,x,m,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,m),b=p*a+v;M===void 0?f++:(l[b]=M,h[b]=1)}}if(!(f===a*c||f/(a*c)>xe.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let g=u;g<=d;g++){const m=p*(1-Math.abs(g-e)/n);if(m<=0)continue;c+=m;const v=t.at(g,f);!Number.isFinite(v)||v<xe.NO_DATA_BELOW||(r+=m*v,a+=m)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const m of[h,u,d,f])if(!Number.isFinite(m)||m<xe.NO_DATA_BELOW)return;const p=h+(u-h)*c,g=d+(f-d)*c;return p+(g-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=a+d,g=c+f;p<0||g<0||p>=n||g>=i||!e[p*i+g]||(h+=t[p*i+g],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class rE{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const od=256,aE=5;async function zy(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(ae(n,o.east,n,o.west).x),a=Math.abs(ae(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=oE(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=Fy(s,n,l,h),f=h*od,p=document.createElement("canvas");p.width=f,p.height=f;const g=p.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async M=>{const b=e(M),S=await i(b);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${b}`);const E=await createImageBitmap(await S.blob());g.drawImage(E,(M.x-m.x)*od,(M.y-m.y)*od)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const y=document.createElement("canvas");y.width=v,y.height=v;const x=y.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,v,v),{source:y,width:v,height:v,bounds:d}}function oE(o,t,e){let i=jS(o,t/Math.max(1,e)),n=ov(o,i,t);for(;n>aE&&i>0;)i--,n=ov(o,i,t);return{zoom:i,gridSize:n,mPerPixel:Ny(o,i)/od}}function ov(o,t,e){const i=Math.ceil(e/2/Ny(o,t));return Math.max(3,2*i+1)}class By{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(t,e){return zy(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Zn{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=Zn.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=Zn.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Zn.FRANCE_ENDPOINT,...e.filter(d=>d!==Zn.FRANCE_ENDPOINT)]:[...e]}fetchImpl;endpoints;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.endpoints=t.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(t){return this.queued(()=>this.ask(t))}queued(t){const e=Zn.queue.then(t,t);return Zn.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Zn.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Zn.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,Zn.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class wa{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(t={}){this.client=new Zn(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${wa.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:wa.surfaceOf(s),widthM:wa.widthOf(s),...wa.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:wa.WIDTH_M[t.highway]??wa.DEFAULT_WIDTH_M}static surfaceOf(t){const e=t.surface;return e==="dirt"||e==="earth"||e==="mud"?"dirt":e==="gravel"||e==="fine_gravel"||e==="compacted"||e==="ground"||e==="sand"||e==="unpaved"?"gravel":e?"paved":t.highway==="track"?"gravel":"paved"}}const jf="https://ufoathome.org/roads/index.json";class Cc{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Cc.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2402
|
+
`);let e=Cc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Cc.shared.set(t,e),e.then(i=>{i.length===0&&Cc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.142.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==jf?[e,jf]:[jf]).map(i=>i+t)}}class _a{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new Re(t)}static covers(t){return Re.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,n)=>_a.wayOf(i,n))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const n=String(t.properties.nature??""),s=_a.BY_NATURE[n]??_a.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=_a.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=_a.KINDS[n],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class cE{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(t){if(_a.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Eh{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Re(t)}static covers(t){return Re.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,n)=>Eh.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>Eh.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class io{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Zn(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return io.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=io.rings(a("inner"));for(const[l,h]of io.rings(a("outer")).entries()){const u=c.filter(d=>io.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of io.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class lE{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Eh.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const Qf="https://ufoathome.org/water/index.json";class Oc{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Oc.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2403
|
+
`);let e=Oc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Oc.shared.set(t,e),e.then(i=>{i.length===0&&Oc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.142.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==Qf?[e,Qf]:[Qf]).map(i=>i+t)}}class Xn{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=Xn.key(t);let i=Xn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),Xn.asked.set(e,i),i.catch(()=>Xn.asked.delete(e))),structuredClone(await i)}static forget(){Xn.asked.clear()}static key(t){return`v${Xn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await Xn.openCache(),n=Xn.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<Xn.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&Xn.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-Xn.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Ta{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Re(t)}static covers(t){return Re.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,n)=>Ta.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Ta.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Ta.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Ta.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>Ta.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class pn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Zn(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=pn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>ae(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of pn.samples(a)){u++;const y=pn.waysAt(d,v);if(y.length===0)continue;const[x]=y;x.name&&c.set(x.name,(c.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const M of new Set(y.flatMap(b=>b.services)))h.set(M,(h.get(M)??0)+1)}const f=v=>[...v.entries()].sort((y,x)=>x[1]-y[1])[0]?.[0],p=r.name??f(c),g=r.voltageV??(r.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,y)=>y[1]-v[1]||v[0].localeCompare(y[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const n=pn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=pn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=pn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>ae(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=pn.SAMPLE_M/2;a<n;a+=pn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(pn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=pn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class Pc{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Zn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${Pc.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=pn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=pn.voltageOf(r),l=Pc.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=Pc.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:Pc.levelOf(r),points:s.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class hE{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!Ta.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class Xi{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=Xi.key(t);let i=Xi.asked.get(e)??Xi.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},Xi.asked.set(e,i),n.catch(()=>Xi.asked.delete(e))}return structuredClone(await i.answer)}static forget(){Xi.asked.clear(),Xi.failedAt=-1/0}static key(t){return`v${Xi.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of Xi.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await Xi.openCache(),n=Xi.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<Xi.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-Xi.failedAt<Xi.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(Xi.failedAt=this.now(),s)return s;throw a}return i&&Xi.store(i,n,{savedAt:this.now(),lines:r}),r}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-Xi.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Xi.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const t0="https://ufoathome.org/railways/index.json";class Lc{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Lc.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
2404
|
+
`);let e=Lc.shared.get(t);return e||(e=this.fetchFirstAvailable(),Lc.shared.set(t,e),e.then(i=>{i.length===0&&Lc.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.142.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==t0?[e,t0]:[t0]).map(i=>i+t)}}function Hy(){return{elevation:uE(),imagery:Gy(),roads:dE(),water:fE(),railways:pE()}}function uE(){return new rE(new xe,new nE)}function Gy(){return new By}function dE(){return new Cc({fallback:new cE(new _a,new wa)})}function fE(){return new Oc({fallback:new Xn(new lE(new Eh,new io))})}function pE(){return new Lc({fallback:new Xi(new hE(new Ta,new Pc))})}const mE=new Set,Ar="show-observer-map",_r="hide-milestones",bo="minified";class Le extends HTMLElement{static get observedAttributes(){return["src",Ar,_r,bo]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Qe;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Rf.create();issues=[];issueCheck=0;sightingAudio=new NS;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>Le.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=Dy;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Le.setIcon(this.moreButton,t?qt.UNFOLDED:qt.FOLDED);const e=t?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Le.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=Qe.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Qe.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Le.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const n=Qe.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${TS}</style>${_S}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new ol(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new eo(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Ar&&this.applyObserverMapDefault(),t===_r&&this.setMilestonesShown(!this.hasAttribute(_r)),t===bo){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(bo)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(Wy)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages.clickToPlay:this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await Na.recording(t)}get sightingData(){return kS(this.currentSighting)}set sightingData(t){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=FS(t),this.observerMapFrozenSource&&(this.observerMapFrozen=this.observerMapFrozenSource(this.currentSighting.frozen)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let n=[];try{const{default:s}=await we(async()=>{const{default:r}=await import("./sightingSchema-t3YCF0eV.js");return{default:r}},[],import.meta.url);n=new Ls(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],cl.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(gE,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=this.messages.recordingIssues.replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=cl.text(i,this.messages.issueTemplates),n}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const t=this.currentSighting.references;!this.referenceOpacityTouched&&t.length>0&&(this.referenceOpacityInput.value=String(t[0].opacity));for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages.referenceOpacity,l.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Le.setIcon(this.referencesButton,i?qt.PICTURES_ON:qt.PICTURES_OFF);const n=e?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Le.setIcon(this.tracesButton,this.tracesShownState?qt.TRACES_ON:qt.TRACES_OFF);const t=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?ih(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Le.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Le.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?Zf(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new ol(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const n=Le.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Zf(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=Fs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Le.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Le.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Le.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Le.EXPOSURE_STEP_PX),s=Math.min(Le.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Bi.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}onFrame(t,e){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:mE;this.canvasRenderer.setStarPoints(Bi.starPointsOf(this.sighting.instrument));const n=(ze(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?hs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(wy(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new RS(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Le.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?qt.PLAY:qt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Le.icons.get(t)!==e&&(Le.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Le.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Le.setIcon(this.playPauseButton,t?qt.PAUSE:qt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages.pause:this.messages.play:this.messages.noDuration;this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Ar),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Le.setIcon(this.observerMapButton,t?qt.MAP_ON:qt.MAP_OFF);const e=t?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages.zoomMapIn],[this.mapZoomOutButton,this.messages.zoomMapOut],[this.mapFitButton,this.messages.fitMap]];for(const[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=$c.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Qe.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapFrozenImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?Qe.expand(t,Le.OBSERVER_MAP_IMAGERY_AHEAD):t,n=Qe.IMAGERY_PX*(e?1+2*Le.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapFrozenImagery,r=s?void 0:Gy();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?Qe.expand(t,Le.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapFrozen(t){t!==this.observerMapFrozenImagery&&(this.observerMapFrozenImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapFrozen(){return this.observerMapFrozenImagery}observerMapFrozenImagery;observerMapFrozenSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Le.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ze(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Le.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Zf(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?ih(this.currentSighting.milestones):[]){const a=ze(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?yr.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Bi.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ih(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages.moments,Le.setIcon(this.milestonesButton,this.milestonesShown?qt.MILESTONES_ON:qt.MILESTONES_OFF);const t=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=ze(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Er(i,t),{lat:s,lng:r}=fs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const n=ze(this.currentSighting,this.currentTime),s=yr.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return Xe.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Le.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Le.setIcon(this.miniMuteButton,this.mutedState?qt.MUTED:qt.VOLUME);const e=this.mutedState?this.messages.unmute:this.messages.mute;if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Le.setIcon(this.muteButton,qt.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}Le.setIcon(this.muteButton,this.mutedState?qt.MUTED:qt.VOLUME);const i=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Le.setIcon(this.fullscreenButton,t?qt.EXIT_FULLSCREEN:qt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Es(ka.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=dg(ka.preferencesFor(this),fg);if(t===this.messagesLanguage||t==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=t;const e=await HS(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=this.messages.currentPosition+e,this.timeEndLabel.title=this.messages.duration+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const t=this.currentSighting.event,e=by(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?Dp(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return oa(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?lv(cv(this.realStartMs+i)):oa(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?oa(t):oa(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return oa(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return oa(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?oa(this.currentSighting.timeline.duration):this.canShowClockTime?lv(cv(this.realStartMs+this.realDurationMs)):oa(this.realDurationMs)}}function cv(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function lv(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function oa(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Pp="rr0-ufo";function Vy(){customElements.get(Pp)||customElements.define(Pp,Le)}const gE="recordingissues",Wy="minifiedreset";/**
|
|
2405
2405
|
* @license
|
|
2406
2406
|
* Copyright 2010-2026 Three.js Authors
|
|
2407
2407
|
* SPDX-License-Identifier: MIT
|
|
2408
|
-
*/const pg="185",vE=0,hv=1,ME=2,nh=1,yE=2,Kl=3,za=0,xi=1,Bn=2,ms=0,Ua=1,nn=2,uv=3,dv=4,Fo=5,$r=100,xE=101,bE=102,wE=103,SE=104,xr=200,zo=201,EE=202,AE=203,Wd=204,Ah=205,_E=206,TE=207,RE=208,IE=209,DE=210,CE=211,OE=212,PE=213,LE=214,Lp=0,Np=1,kp=2,ll=3,Up=4,Fp=5,zp=6,Bp=7,mg=0,NE=1,kE=2,Ir=0,Xy=1,$y=2,Yy=3,qy=4,Ky=5,Zy=6,Jy=7,fv="attached",UE="detached",jy=300,Bo=301,hl=302,e0=303,i0=304,Cf=306,Ho=1e3,Oi=1001,Hp=1002,ei=1003,FE=1004,jh=1005,ye=1006,n0=1007,Xs=1008,Hn=1009,Qy=1010,tx=1011,_h=1012,gg=1013,Ts=1014,Dn=1015,Be=1016,vg=1017,Mg=1018,Th=1020,ex=35902,ix=35899,nx=1021,sx=1022,Ki=1023,Jr=1026,wo=1027,ul=1028,yg=1029,Go=1030,xg=1031,bg=1033,cd=33776,ld=33777,hd=33778,ud=33779,Gp=35840,Vp=35841,Wp=35842,Xp=35843,$p=36196,Yp=37492,qp=37496,Kp=37488,Zp=37489,Xd=37490,Jp=37491,jp=37808,Qp=37809,tm=37810,em=37811,im=37812,nm=37813,sm=37814,rm=37815,am=37816,om=37817,cm=37818,lm=37819,hm=37820,um=37821,dm=36492,fm=36494,pm=36495,mm=36283,gm=36284,$d=36285,vm=36286,rx=2200,zE=2201,BE=2202,Yd=2300,Mm=2301,s0=2302,pv=2303,Nc=2400,kc=2401,qd=2402,wg=2500,HE=2501,HO=0,GO=1,VO=2,GE=3200,Kd=0,VE=1,Ra="",vn="srgb",Zd="srgb-linear",Jd="linear",$e="srgb",ec=7680,mv=519,WE=512,XE=513,$E=514,Sg=515,YE=516,qE=517,Eg=518,KE=519,ym=35044,jd="300 es",Tr=2e3,Rh=2001;function ZE(o){for(let t=o.length-1;t>=0;--t)if(o[t]>=65535)return!0;return!1}function JE(o){return ArrayBuffer.isView(o)&&!(o instanceof DataView)}function Ih(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function jE(){const o=Ih("canvas");return o.style.display="block",o}const gv={};function Qd(...o){const t="THREE."+o.shift();console.log(t,...o)}function ax(o){const t=o[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=o[1];e&&e.isStackTrace?o[0]+=" "+e.getLocation():o[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return o}function Nt(...o){o=ax(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...o)}}function te(...o){o=ax(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...o)}}function Yc(...o){const t=o.join(" ");t in gv||(gv[t]=!0,Nt(...o))}function QE(o,t,e){return new Promise(function(i,n){function s(){switch(o.clientWaitSync(t,o.SYNC_FLUSH_COMMANDS_BIT,0)){case o.WAIT_FAILED:n();break;case o.TIMEOUT_EXPIRED:setTimeout(s,e);break;default:i()}}setTimeout(s,e)})}const t3={[Lp]:Np,[kp]:zp,[Up]:Bp,[ll]:Fp,[Np]:Lp,[zp]:kp,[Bp]:Up,[Fp]:ll};class Ha{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i===void 0?!1:i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const i=this._listeners;if(i===void 0)return;const n=i[t];if(n!==void 0){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const i=e[t.type];if(i!==void 0){t.target=this;const n=i.slice(0);for(let s=0,r=n.length;s<r;s++)n[s].call(this,t);t.target=null}}}const xn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let vv=1234567;const sh=Math.PI/180,dl=180/Math.PI;function _s(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(xn[o&255]+xn[o>>8&255]+xn[o>>16&255]+xn[o>>24&255]+"-"+xn[t&255]+xn[t>>8&255]+"-"+xn[t>>16&15|64]+xn[t>>24&255]+"-"+xn[e&63|128]+xn[e>>8&255]+"-"+xn[e>>16&255]+xn[e>>24&255]+xn[i&255]+xn[i>>8&255]+xn[i>>16&255]+xn[i>>24&255]).toLowerCase()}function oe(o,t,e){return Math.max(t,Math.min(e,o))}function Ag(o,t){return(o%t+t)%t}function e3(o,t,e,i,n){return i+(o-t)*(n-i)/(e-t)}function i3(o,t,e){return o!==t?(e-o)/(t-o):0}function rh(o,t,e){return(1-e)*o+e*t}function n3(o,t,e,i){return rh(o,t,1-Math.exp(-e*i))}function s3(o,t=1){return t-Math.abs(Ag(o,t*2)-t)}function r3(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function a3(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function o3(o,t){return o+Math.floor(Math.random()*(t-o+1))}function c3(o,t){return o+Math.random()*(t-o)}function l3(o){return o*(.5-Math.random())}function h3(o){o!==void 0&&(vv=o);let t=vv+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function u3(o){return o*sh}function d3(o){return o*dl}function f3(o){return(o&o-1)===0&&o!==0}function p3(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function m3(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function g3(o,t,e,i,n){const s=Math.cos,r=Math.sin,a=s(e/2),c=r(e/2),l=s((t+i)/2),h=r((t+i)/2),u=s((t-i)/2),d=r((t-i)/2),f=s((i-t)/2),p=r((i-t)/2);switch(n){case"XYX":o.set(a*h,c*u,c*d,a*l);break;case"YZY":o.set(c*d,a*h,c*u,a*l);break;case"ZXZ":o.set(c*u,c*d,a*h,a*l);break;case"XZX":o.set(a*h,c*p,c*f,a*l);break;case"YXY":o.set(c*f,a*h,c*p,a*l);break;case"ZYZ":o.set(c*p,c*f,a*h,a*l);break;default:Nt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Vs(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function qe(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const WO={DEG2RAD:sh,RAD2DEG:dl,generateUUID:_s,clamp:oe,euclideanModulo:Ag,mapLinear:e3,inverseLerp:i3,lerp:rh,damp:n3,pingpong:s3,smoothstep:r3,smootherstep:a3,randInt:o3,randFloat:c3,randFloatSpread:l3,seededRandom:h3,degToRad:u3,radToDeg:d3,isPowerOfTwo:f3,ceilPowerOfTwo:p3,floorPowerOfTwo:m3,setQuaternionFromProperEuler:g3,normalize:qe,denormalize:Vs};class it{static{it.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(oe(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),n=Math.sin(e),s=this.x-t.x,r=this.y-t.y;return this.x=s*i-r*n+t.x,this.y=s*n+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ts{constructor(t=0,e=0,i=0,n=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=n}static slerpFlat(t,e,i,n,s,r,a){let c=i[n+0],l=i[n+1],h=i[n+2],u=i[n+3],d=s[r+0],f=s[r+1],p=s[r+2],g=s[r+3];if(u!==g||c!==d||l!==f||h!==p){let m=c*d+l*f+h*p+u*g;m<0&&(d=-d,f=-f,p=-p,g=-g,m=-m);let v=1-a;if(m<.9995){const y=Math.acos(m),x=Math.sin(y);v=Math.sin(v*y)/x,a=Math.sin(a*y)/x,c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+g*a}else{c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+g*a;const y=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=y,l*=y,h*=y,u*=y}}t[e]=c,t[e+1]=l,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,i,n,s,r){const a=i[n],c=i[n+1],l=i[n+2],h=i[n+3],u=s[r],d=s[r+1],f=s[r+2],p=s[r+3];return t[e]=a*p+h*u+c*f-l*d,t[e+1]=c*p+h*d+l*u-a*f,t[e+2]=l*p+h*f+a*d-c*u,t[e+3]=h*p-a*u-c*d-l*f,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,n){return this._x=t,this._y=e,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,n=t._y,s=t._z,r=t._order,a=Math.cos,c=Math.sin,l=a(i/2),h=a(n/2),u=a(s/2),d=c(i/2),f=c(n/2),p=c(s/2);switch(r){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:Nt("Quaternion: .setFromEuler() encountered an unknown order: "+r)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,n=Math.sin(i);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],n=e[4],s=e[8],r=e[1],a=e[5],c=e[9],l=e[2],h=e[6],u=e[10],d=i+a+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(s-l)*f,this._z=(r-n)*f}else if(i>a&&i>u){const f=2*Math.sqrt(1+i-a-u);this._w=(h-c)/f,this._x=.25*f,this._y=(n+r)/f,this._z=(s+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-i-u);this._w=(s-l)/f,this._x=(n+r)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-i-a);this._w=(r-n)/f,this._x=(s+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(oe(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const n=Math.min(1,e/i);return this.slerp(t,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,n=t._y,s=t._z,r=t._w,a=e._x,c=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+n*l-s*c,this._y=n*h+r*c+s*a-i*l,this._z=s*h+r*l+i*c-n*a,this._w=r*h-i*a-n*c-s*l,this._onChangeCallback(),this}slerp(t,e){let i=t._x,n=t._y,s=t._z,r=t._w,a=this.dot(t);a<0&&(i=-i,n=-n,s=-s,r=-r,a=-a);let c=1-e;if(a<.9995){const l=Math.acos(a),h=Math.sin(l);c=Math.sin(c*l)/h,e=Math.sin(e*l)/h,this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this._onChangeCallback()}else this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(t),n*Math.cos(t),s*Math.sin(e),s*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class R{static{R.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Mv.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Mv.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6]*n,this.y=s[1]*e+s[4]*i+s[7]*n,this.z=s[2]*e+s[5]*i+s[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=t.elements,r=1/(s[3]*e+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*e+s[4]*i+s[8]*n+s[12])*r,this.y=(s[1]*e+s[5]*i+s[9]*n+s[13])*r,this.z=(s[2]*e+s[6]*i+s[10]*n+s[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,a=t.z,c=t.w,l=2*(r*n-a*i),h=2*(a*e-s*n),u=2*(s*i-r*e);return this.x=e+c*l+r*u-a*h,this.y=i+c*h+a*l-s*u,this.z=n+c*u+s*h-r*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[4]*i+s[8]*n,this.y=s[1]*e+s[5]*i+s[9]*n,this.z=s[2]*e+s[6]*i+s[10]*n,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this.z=oe(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this.z=oe(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,n=t.y,s=t.z,r=e.x,a=e.y,c=e.z;return this.x=n*c-s*a,this.y=s*r-i*c,this.z=i*a-n*r,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return r0.copy(this).projectOnVector(t),this.sub(r0)}reflect(t){return this.sub(r0.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(oe(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const n=Math.sin(e)*t;return this.x=n*Math.sin(i),this.y=Math.cos(e)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const r0=new R,Mv=new ts;class ie{static{ie.prototype.isMatrix3=!0}constructor(t,e,i,n,s,r,a,c,l){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l)}set(t,e,i,n,s,r,a,c,l){const h=this.elements;return h[0]=t,h[1]=n,h[2]=a,h[3]=e,h[4]=s,h[5]=c,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[3],c=i[6],l=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],g=n[0],m=n[3],v=n[6],y=n[1],x=n[4],M=n[7],b=n[2],S=n[5],E=n[8];return s[0]=r*g+a*y+c*b,s[3]=r*m+a*x+c*S,s[6]=r*v+a*M+c*E,s[1]=l*g+h*y+u*b,s[4]=l*m+h*x+u*S,s[7]=l*v+h*M+u*E,s[2]=d*g+f*y+p*b,s[5]=d*m+f*x+p*S,s[8]=d*v+f*M+p*E,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*s*h+i*a*c+n*s*l-n*r*c}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=h*r-a*l,d=a*c-h*s,f=l*s-r*c,p=e*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return t[0]=u*g,t[1]=(n*l-h*i)*g,t[2]=(a*i-n*r)*g,t[3]=d*g,t[4]=(h*e-n*c)*g,t[5]=(n*s-a*e)*g,t[6]=f*g,t[7]=(i*c-l*e)*g,t[8]=(r*e-i*s)*g,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,n,s,r,a){const c=Math.cos(s),l=Math.sin(s);return this.set(i*c,i*l,-i*(c*r+l*a)+r+t,-n*l,n*c,-n*(-l*r+c*a)+a+e,0,0,1),this}scale(t,e){return Yc("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(a0.makeScale(t,e)),this}rotate(t){return Yc("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(a0.makeRotation(-t)),this}translate(t,e){return Yc("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(a0.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<9;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}}const a0=new ie,yv=new ie().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),xv=new ie().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function v3(){const o={enabled:!0,workingColorSpace:Zd,spaces:{},convert:function(n,s,r){return this.enabled===!1||s===r||!s||!r||(this.spaces[s].transfer===$e&&(n.r=Kr(n.r),n.g=Kr(n.g),n.b=Kr(n.b)),this.spaces[s].primaries!==this.spaces[r].primaries&&(n.applyMatrix3(this.spaces[s].toXYZ),n.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===$e&&(n.r=qc(n.r),n.g=qc(n.g),n.b=qc(n.b))),n},workingToColorSpace:function(n,s){return this.convert(n,this.workingColorSpace,s)},colorSpaceToWorking:function(n,s){return this.convert(n,s,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===Ra?Jd:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,s=this.workingColorSpace){return n.fromArray(this.spaces[s].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,s,r){return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,s){return Yc("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(n,s)},toWorkingColorSpace:function(n,s){return Yc("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(n,s)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],i=[.3127,.329];return o.define({[Zd]:{primaries:t,whitePoint:i,transfer:Jd,toXYZ:yv,fromXYZ:xv,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:vn},outputColorSpaceConfig:{drawingBufferColorSpace:vn}},[vn]:{primaries:t,whitePoint:i,transfer:$e,toXYZ:yv,fromXYZ:xv,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:vn}}}),o}const De=v3();function Kr(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function qc(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}let ic;class M3{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{ic===void 0&&(ic=Ih("canvas")),ic.width=t.width,ic.height=t.height;const n=ic.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),i=ic}return i.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=Ih("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const n=i.getImageData(0,0,t.width,t.height),s=n.data;for(let r=0;r<s.length;r++)s[r]=Kr(s[r]/255)*255;return i.putImageData(n,0,0),e}else if(t.data){const e=t.data.slice(0);for(let i=0;i<e.length;i++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[i]=Math.floor(Kr(e[i]/255)*255):e[i]=Kr(e[i]);return{data:e,width:t.width,height:t.height}}else return Nt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let y3=0;class _g{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:y3++}),this.uuid=_s(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let r=0,a=n.length;r<a;r++)n[r].isDataTexture?s.push(o0(n[r].image)):s.push(o0(n[r]))}else s=o0(n);i.url=s}return e||(t.images[this.uuid]=i),i}}function o0(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?M3.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(Nt("Texture: Unable to serialize Texture."),{})}let x3=0;const c0=new R;class Mn extends Ha{constructor(t=Mn.DEFAULT_IMAGE,e=Mn.DEFAULT_MAPPING,i=Oi,n=Oi,s=ye,r=Xs,a=Ki,c=Hn,l=Mn.DEFAULT_ANISOTROPY,h=Ra){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:x3++}),this.uuid=_s(),this.name="",this.source=new _g(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new it(0,0),this.repeat=new it(1,1),this.center=new it(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ie,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(c0).x}get height(){return this.source.getSize(c0).y}get depth(){return this.source.getSize(c0).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(i===void 0){Nt(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Nt(`Texture.setValues(): property '${e}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==jy)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case Ho:t.x=t.x-Math.floor(t.x);break;case Oi:t.x=t.x<0?0:1;break;case Hp:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case Ho:t.y=t.y-Math.floor(t.y);break;case Oi:t.y=t.y<0?0:1;break;case Hp:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}Mn.DEFAULT_IMAGE=null;Mn.DEFAULT_MAPPING=jy;Mn.DEFAULT_ANISOTROPY=1;class _e{static{_e.prototype.isVector4=!0}constructor(t=0,e=0,i=0,n=1){this.x=t,this.y=e,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,n,s;const c=t.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],g=c[2],m=c[6],v=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-g)<.01&&Math.abs(p-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+g)<.1&&Math.abs(p+m)<.1&&Math.abs(l+f+v-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const x=(l+1)/2,M=(f+1)/2,b=(v+1)/2,S=(h+d)/4,E=(u+g)/4,w=(p+m)/4;return x>M&&x>b?x<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(x),n=S/i,s=E/i):M>b?M<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(M),i=S/n,s=w/n):b<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(b),i=E/s,n=w/s),this.set(i,n,s,e),this}let y=Math.sqrt((m-p)*(m-p)+(u-g)*(u-g)+(d-h)*(d-h));return Math.abs(y)<.001&&(y=1),this.x=(m-p)/y,this.y=(u-g)/y,this.z=(d-h)/y,this.w=Math.acos((l+f+v-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this.z=oe(this.z,t.z,e.z),this.w=oe(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this.z=oe(this.z,t,e),this.w=oe(this.w,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class b3 extends Ha{constructor(t=1,e=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ye,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=i.depth,this.scissor=new _e(0,0,t,e),this.scissorTest=!1,this.viewport=new _e(0,0,t,e),this.textures=[];const n={width:t,height:e,depth:i.depth},s=new Mn(n),r=i.count;for(let a=0;a<r;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(t={}){const e={minFilter:ye,generateMipmaps:!1,flipY:!1,internalFormat:null};t.mapping!==void 0&&(e.mapping=t.mapping),t.wrapS!==void 0&&(e.wrapS=t.wrapS),t.wrapT!==void 0&&(e.wrapT=t.wrapT),t.wrapR!==void 0&&(e.wrapR=t.wrapR),t.magFilter!==void 0&&(e.magFilter=t.magFilter),t.minFilter!==void 0&&(e.minFilter=t.minFilter),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.anisotropy!==void 0&&(e.anisotropy=t.anisotropy),t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),t.internalFormat!==void 0&&(e.internalFormat=t.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(e)}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}set depthTexture(t){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),t!==null&&(t.renderTarget=this),this._depthTexture=t}get depthTexture(){return this._depthTexture}setSize(t,e,i=1){if(this.width!==t||this.height!==e||this.depth!==i){this.width=t,this.height=e,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=t,this.textures[n].image.height=e,this.textures[n].image.depth=i,this.textures[n].isData3DTexture!==!0&&(this.textures[n].isArrayTexture=this.textures[n].image.depth>1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e<i;e++){this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const n=Object.assign({},t.textures[e].image);this.textures[e].source=new _g(n)}return this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,t.depthTexture!==null&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this.multiview=t.multiview,this.useArrayDepthTexture=t.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ai extends b3{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class ox extends Mn{constructor(t=null,e=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=ei,this.minFilter=ei,this.wrapR=Oi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class cx extends Mn{constructor(t=null,e=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=ei,this.minFilter=ei,this.wrapR=Oi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class he{static{he.prototype.isMatrix4=!0}constructor(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m)}set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m){const v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=s,v[5]=r,v[9]=a,v[13]=c,v[2]=l,v[6]=h,v[10]=u,v[14]=d,v[3]=f,v[7]=p,v[11]=g,v[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new he().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),i.set(0,0,1),this):(t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){if(t.determinantAffine()===0)return this.identity();const e=this.elements,i=t.elements,n=1/nc.setFromMatrixColumn(t,0).length(),s=1/nc.setFromMatrixColumn(t,1).length(),r=1/nc.setFromMatrixColumn(t,2).length();return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=0,e[4]=i[4]*s,e[5]=i[5]*s,e[6]=i[6]*s,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,n=t.y,s=t.z,r=Math.cos(i),a=Math.sin(i),c=Math.cos(n),l=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(t.order==="XYZ"){const d=r*h,f=r*u,p=a*h,g=a*u;e[0]=c*h,e[4]=-c*u,e[8]=l,e[1]=f+p*l,e[5]=d-g*l,e[9]=-a*c,e[2]=g-d*l,e[6]=p+f*l,e[10]=r*c}else if(t.order==="YXZ"){const d=c*h,f=c*u,p=l*h,g=l*u;e[0]=d+g*a,e[4]=p*a-f,e[8]=r*l,e[1]=r*u,e[5]=r*h,e[9]=-a,e[2]=f*a-p,e[6]=g+d*a,e[10]=r*c}else if(t.order==="ZXY"){const d=c*h,f=c*u,p=l*h,g=l*u;e[0]=d-g*a,e[4]=-r*u,e[8]=p+f*a,e[1]=f+p*a,e[5]=r*h,e[9]=g-d*a,e[2]=-r*l,e[6]=a,e[10]=r*c}else if(t.order==="ZYX"){const d=r*h,f=r*u,p=a*h,g=a*u;e[0]=c*h,e[4]=p*l-f,e[8]=d*l+g,e[1]=c*u,e[5]=g*l+d,e[9]=f*l-p,e[2]=-l,e[6]=a*c,e[10]=r*c}else if(t.order==="YZX"){const d=r*c,f=r*l,p=a*c,g=a*l;e[0]=c*h,e[4]=g-d*u,e[8]=p*u+f,e[1]=u,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=f*u+p,e[10]=d-g*u}else if(t.order==="XZY"){const d=r*c,f=r*l,p=a*c,g=a*l;e[0]=c*h,e[4]=-u,e[8]=l*h,e[1]=d*u+g,e[5]=r*h,e[9]=f*u-p,e[2]=p*u-f,e[6]=a*h,e[10]=g*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(w3,t,S3)}lookAt(t,e,i){const n=this.elements;return ss.subVectors(t,e),ss.lengthSq()===0&&(ss.z=1),ss.normalize(),ca.crossVectors(i,ss),ca.lengthSq()===0&&(Math.abs(i.z)===1?ss.x+=1e-4:ss.z+=1e-4,ss.normalize(),ca.crossVectors(i,ss)),ca.normalize(),Qh.crossVectors(ss,ca),n[0]=ca.x,n[4]=Qh.x,n[8]=ss.x,n[1]=ca.y,n[5]=Qh.y,n[9]=ss.y,n[2]=ca.z,n[6]=Qh.z,n[10]=ss.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[4],c=i[8],l=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],g=i[6],m=i[10],v=i[14],y=i[3],x=i[7],M=i[11],b=i[15],S=n[0],E=n[4],w=n[8],_=n[12],D=n[1],I=n[5],O=n[9],L=n[13],N=n[2],P=n[6],z=n[10],B=n[14],Y=n[3],j=n[7],K=n[11],nt=n[15];return s[0]=r*S+a*D+c*N+l*Y,s[4]=r*E+a*I+c*P+l*j,s[8]=r*w+a*O+c*z+l*K,s[12]=r*_+a*L+c*B+l*nt,s[1]=h*S+u*D+d*N+f*Y,s[5]=h*E+u*I+d*P+f*j,s[9]=h*w+u*O+d*z+f*K,s[13]=h*_+u*L+d*B+f*nt,s[2]=p*S+g*D+m*N+v*Y,s[6]=p*E+g*I+m*P+v*j,s[10]=p*w+g*O+m*z+v*K,s[14]=p*_+g*L+m*B+v*nt,s[3]=y*S+x*D+M*N+b*Y,s[7]=y*E+x*I+M*P+b*j,s[11]=y*w+x*O+M*z+b*K,s[15]=y*_+x*L+M*B+b*nt,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[12],r=t[1],a=t[5],c=t[9],l=t[13],h=t[2],u=t[6],d=t[10],f=t[14],p=t[3],g=t[7],m=t[11],v=t[15],y=c*f-l*d,x=a*f-l*u,M=a*d-c*u,b=r*f-l*h,S=r*d-c*h,E=r*u-a*h;return e*(g*y-m*x+v*M)-i*(p*y-m*b+v*S)+n*(p*x-g*b+v*E)-s*(p*M-g*S+m*E)}determinantAffine(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[1],r=t[5],a=t[9],c=t[2],l=t[6],h=t[10];return e*(r*h-a*l)-i*(s*h-a*c)+n*(s*l-r*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=e,n[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=t[9],d=t[10],f=t[11],p=t[12],g=t[13],m=t[14],v=t[15],y=e*a-i*r,x=e*c-n*r,M=e*l-s*r,b=i*c-n*a,S=i*l-s*a,E=n*l-s*c,w=h*g-u*p,_=h*m-d*p,D=h*v-f*p,I=u*m-d*g,O=u*v-f*g,L=d*v-f*m,N=y*L-x*O+M*I+b*D-S*_+E*w;if(N===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const P=1/N;return t[0]=(a*L-c*O+l*I)*P,t[1]=(n*O-i*L-s*I)*P,t[2]=(g*E-m*S+v*b)*P,t[3]=(d*S-u*E-f*b)*P,t[4]=(c*D-r*L-l*_)*P,t[5]=(e*L-n*D+s*_)*P,t[6]=(m*M-p*E-v*x)*P,t[7]=(h*E-d*M+f*x)*P,t[8]=(r*O-a*D+l*w)*P,t[9]=(i*D-e*O-s*w)*P,t[10]=(p*S-g*M+v*y)*P,t[11]=(u*M-h*S-f*y)*P,t[12]=(a*_-r*I-c*w)*P,t[13]=(e*I-i*_+n*w)*P,t[14]=(g*x-p*b-m*y)*P,t[15]=(h*b-u*x+d*y)*P,this}scale(t){const e=this.elements,i=t.x,n=t.y,s=t.z;return e[0]*=i,e[4]*=n,e[8]*=s,e[1]*=i,e[5]*=n,e[9]*=s,e[2]*=i,e[6]*=n,e[10]*=s,e[3]*=i,e[7]*=n,e[11]*=s,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,n))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,a=t.y,c=t.z,l=s*r,h=s*a;return this.set(l*r+i,l*a-n*c,l*c+n*a,0,l*a+n*c,h*a+i,h*c-n*r,0,l*c-n*a,h*c+n*r,s*c*c+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,n,s,r){return this.set(1,i,s,0,t,1,r,0,e,n,1,0,0,0,0,1),this}compose(t,e,i){const n=this.elements,s=e._x,r=e._y,a=e._z,c=e._w,l=s+s,h=r+r,u=a+a,d=s*l,f=s*h,p=s*u,g=r*h,m=r*u,v=a*u,y=c*l,x=c*h,M=c*u,b=i.x,S=i.y,E=i.z;return n[0]=(1-(g+v))*b,n[1]=(f+M)*b,n[2]=(p-x)*b,n[3]=0,n[4]=(f-M)*S,n[5]=(1-(d+v))*S,n[6]=(m+y)*S,n[7]=0,n[8]=(p+x)*E,n[9]=(m-y)*E,n[10]=(1-(d+g))*E,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,e,i){const n=this.elements;t.x=n[12],t.y=n[13],t.z=n[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),e.identity(),this;let r=nc.set(n[0],n[1],n[2]).length();const a=nc.set(n[4],n[5],n[6]).length(),c=nc.set(n[8],n[9],n[10]).length();s<0&&(r=-r),Ds.copy(this);const l=1/r,h=1/a,u=1/c;return Ds.elements[0]*=l,Ds.elements[1]*=l,Ds.elements[2]*=l,Ds.elements[4]*=h,Ds.elements[5]*=h,Ds.elements[6]*=h,Ds.elements[8]*=u,Ds.elements[9]*=u,Ds.elements[10]*=u,e.setFromRotationMatrix(Ds),i.x=r,i.y=a,i.z=c,this}makePerspective(t,e,i,n,s,r,a=Tr,c=!1){const l=this.elements,h=2*s/(e-t),u=2*s/(i-n),d=(e+t)/(e-t),f=(i+n)/(i-n);let p,g;if(c)p=s/(r-s),g=r*s/(r-s);else if(a===Tr)p=-(r+s)/(r-s),g=-2*r*s/(r-s);else if(a===Rh)p=-r/(r-s),g=-r*s/(r-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=g,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,n,s,r,a=Tr,c=!1){const l=this.elements,h=2/(e-t),u=2/(i-n),d=-(e+t)/(e-t),f=-(i+n)/(i-n);let p,g;if(c)p=1/(r-s),g=r/(r-s);else if(a===Tr)p=-2/(r-s),g=-(r+s)/(r-s);else if(a===Rh)p=-1/(r-s),g=-s/(r-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=p,l[14]=g,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<16;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const nc=new R,Ds=new he,w3=new R(0,0,0),S3=new R(1,1,1),ca=new R,Qh=new R,ss=new R,bv=new he,wv=new ts;class jr{constructor(t=0,e=0,i=0,n=jr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,n=this._order){return this._x=t,this._y=e,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const n=t.elements,s=n[0],r=n[4],a=n[8],c=n[1],l=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(e){case"XYZ":this._y=Math.asin(oe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-r,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-oe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(oe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-oe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(oe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-oe(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,f),this._y=0);break;default:Nt("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return bv.makeRotationFromQuaternion(t),this.setFromRotationMatrix(bv,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return wv.setFromEuler(this),this.setFromQuaternion(wv,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}jr.DEFAULT_ORDER="XYZ";class Tg{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}}let E3=0;const Sv=new R,sc=new ts,Nr=new he,tu=new R,El=new R,A3=new R,_3=new ts,Ev=new R(1,0,0),Av=new R(0,1,0),_v=new R(0,0,1),Tv={type:"added"},T3={type:"removed"},rc={type:"childadded",child:null},l0={type:"childremoved",child:null};class bi extends Ha{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:E3++}),this.uuid=_s(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=bi.DEFAULT_UP.clone();const t=new R,e=new jr,i=new ts,n=new R(1,1,1);function s(){i.setFromEuler(e,!1)}function r(){e.setFromQuaternion(i,void 0,!1)}e._onChange(s),i._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new he},normalMatrix:{value:new ie}}),this.matrix=new he,this.matrixWorld=new he,this.matrixAutoUpdate=bi.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Tg,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return sc.setFromAxisAngle(t,e),this.quaternion.multiply(sc),this}rotateOnWorldAxis(t,e){return sc.setFromAxisAngle(t,e),this.quaternion.premultiply(sc),this}rotateX(t){return this.rotateOnAxis(Ev,t)}rotateY(t){return this.rotateOnAxis(Av,t)}rotateZ(t){return this.rotateOnAxis(_v,t)}translateOnAxis(t,e){return Sv.copy(t).applyQuaternion(this.quaternion),this.position.add(Sv.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Ev,t)}translateY(t){return this.translateOnAxis(Av,t)}translateZ(t){return this.translateOnAxis(_v,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(Nr.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?tu.copy(t):tu.set(t,e,i);const n=this.parent;this.updateWorldMatrix(!0,!1),El.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Nr.lookAt(El,tu,this.up):Nr.lookAt(tu,El,this.up),this.quaternion.setFromRotationMatrix(Nr),n&&(Nr.extractRotation(n.matrixWorld),sc.setFromRotationMatrix(Nr),this.quaternion.premultiply(sc.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(te("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Tv),rc.child=t,this.dispatchEvent(rc),rc.child=null):te("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(T3),l0.child=t,this.dispatchEvent(l0),l0.child=null),this}removeFromParent(){const t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),Nr.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),Nr.multiply(t.parent.matrixWorld)),t.applyMatrix4(Nr),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Tv),rc.child=t,this.dispatchEvent(rc),rc.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,n=this.children.length;i<n;i++){const r=this.children[i].getObjectByProperty(t,e);if(r!==void 0)return r}}getObjectsByProperty(t,e,i=[]){this[t]===e&&i.push(this);const n=this.children;for(let s=0,r=n.length;s<r;s++)n[s].getObjectsByProperty(t,e,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(El,t,A3),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(El,_3,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const t=this.pivot;if(t!==null){const e=t.x,i=t.y,n=t.z,s=this.matrix.elements;s[12]+=e-s[0]*e-s[4]*i-s[8]*n,s[13]+=i-s[1]*e-s[5]*i-s[9]*n,s[14]+=n-s[2]*e-s[6]*i-s[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].updateMatrixWorld(t)}updateWorldMatrix(t,e,i=!1){const n=this.parent;if(t===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),e===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0,i)}}toJSON(t){const e=t===void 0||typeof t=="string",i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),this.static!==!1&&(n.static=this.static),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(a=>({...a})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(t),n.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(t)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];s(t.shapes,u)}else s(t.shapes,c)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(t.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(s(t.materials,this.material[c]));n.material=a}else n.material=s(t.materials,this.material);if(this.children.length>0){n.children=[];for(let a=0;a<this.children.length;a++)n.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){n.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];n.animations.push(s(t.animations,c))}}if(e){const a=r(t.geometries),c=r(t.materials),l=r(t.textures),h=r(t.images),u=r(t.shapes),d=r(t.skeletons),f=r(t.animations),p=r(t.nodes);a.length>0&&(i.geometries=a),c.length>0&&(i.materials=c),l.length>0&&(i.textures=l),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function r(a){const c=[];for(const l in a){const h=a[l];delete h.metadata,c.push(h)}return c}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let i=0;i<t.children.length;i++){const n=t.children[i];this.add(n.clone())}return this}}bi.DEFAULT_UP=new R(0,1,0);bi.DEFAULT_MATRIX_AUTO_UPDATE=!0;bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Oe extends bi{constructor(){super(),this.isGroup=!0,this.type="Group"}}const R3={type:"move"};class h0{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Oe,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Oe,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Oe,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,i){let n=null,s=null,r=null;const a=this._targetRay,c=this._grip,l=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(l&&t.hand){r=!0;for(const g of t.hand.values()){const m=e.getJointPose(g,i),v=this._getHandJoint(l,g);m!==null&&(v.matrix.fromArray(m.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=m.radius),v.visible=m!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else c!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,i),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(n=e.getPose(t.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(R3)))}return a!==null&&(a.visible=n!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=r!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const i=new Oe;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const lx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},la={h:0,s:0,l:0},eu={h:0,s:0,l:0};function u0(o,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+(t-o)*6*e:e<1/2?t:e<2/3?o+(t-o)*6*(2/3-e):o}class st{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(e===void 0&&i===void 0){const n=t;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=vn){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,De.colorSpaceToWorking(this,e),this}setRGB(t,e,i,n=De.workingColorSpace){return this.r=t,this.g=e,this.b=i,De.colorSpaceToWorking(this,n),this}setHSL(t,e,i,n=De.workingColorSpace){if(t=Ag(t,1),e=oe(e,0,1),i=oe(i,0,1),e===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=u0(r,s,t+1/3),this.g=u0(r,s,t),this.b=u0(r,s,t-1/3)}return De.colorSpaceToWorking(this,n),this}setStyle(t,e=vn){function i(s){s!==void 0&&parseFloat(s)<1&&Nt("Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const r=n[1],a=n[2];switch(r){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:Nt("Color: Unknown color model "+t)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=n[1],r=s.length;if(r===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(r===6)return this.setHex(parseInt(s,16),e);Nt("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=vn){const i=lx[t.toLowerCase()];return i!==void 0?this.setHex(i,e):Nt("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Kr(t.r),this.g=Kr(t.g),this.b=Kr(t.b),this}copyLinearToSRGB(t){return this.r=qc(t.r),this.g=qc(t.g),this.b=qc(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=vn){return De.workingToColorSpace(bn.copy(this),t),Math.round(oe(bn.r*255,0,255))*65536+Math.round(oe(bn.g*255,0,255))*256+Math.round(oe(bn.b*255,0,255))}getHexString(t=vn){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=De.workingColorSpace){De.workingToColorSpace(bn.copy(this),e);const i=bn.r,n=bn.g,s=bn.b,r=Math.max(i,n,s),a=Math.min(i,n,s);let c,l;const h=(a+r)/2;if(a===r)c=0,l=0;else{const u=r-a;switch(l=h<=.5?u/(r+a):u/(2-r-a),r){case i:c=(n-s)/u+(n<s?6:0);break;case n:c=(s-i)/u+2;break;case s:c=(i-n)/u+4;break}c/=6}return t.h=c,t.s=l,t.l=h,t}getRGB(t,e=De.workingColorSpace){return De.workingToColorSpace(bn.copy(this),e),t.r=bn.r,t.g=bn.g,t.b=bn.b,t}getStyle(t=vn){De.workingToColorSpace(bn.copy(this),t);const e=bn.r,i=bn.g,n=bn.b;return t!==vn?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(t,e,i){return this.getHSL(la),this.setHSL(la.h+t,la.s+e,la.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(la),t.getHSL(eu);const i=rh(la.h,eu.h,e),n=rh(la.s,eu.s,e),s=rh(la.l,eu.l,e);return this.setHSL(i,n,s),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,n=this.b,s=t.elements;return this.r=s[0]*e+s[3]*i+s[6]*n,this.g=s[1]*e+s[4]*i+s[7]*n,this.b=s[2]*e+s[5]*i+s[8]*n,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const bn=new st;st.NAMES=lx;class Rg{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new st(t),this.near=e,this.far=i}clone(){return new Rg(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Ys extends bi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new jr,this.environmentIntensity=1,this.environmentRotation=new jr,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Cs=new R,kr=new R,d0=new R,Ur=new R,ac=new R,oc=new R,Rv=new R,f0=new R,p0=new R,m0=new R,g0=new _e,v0=new _e,M0=new _e;class As{constructor(t=new R,e=new R,i=new R){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,n){n.subVectors(i,e),Cs.subVectors(t,e),n.cross(Cs);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(t,e,i,n,s){Cs.subVectors(n,e),kr.subVectors(i,e),d0.subVectors(t,e);const r=Cs.dot(Cs),a=Cs.dot(kr),c=Cs.dot(d0),l=kr.dot(kr),h=kr.dot(d0),u=r*l-a*a;if(u===0)return s.set(0,0,0),null;const d=1/u,f=(l*c-a*h)*d,p=(r*h-a*c)*d;return s.set(1-f-p,p,f)}static containsPoint(t,e,i,n){return this.getBarycoord(t,e,i,n,Ur)===null?!1:Ur.x>=0&&Ur.y>=0&&Ur.x+Ur.y<=1}static getInterpolation(t,e,i,n,s,r,a,c){return this.getBarycoord(t,e,i,n,Ur)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,Ur.x),c.addScaledVector(r,Ur.y),c.addScaledVector(a,Ur.z),c)}static getInterpolatedAttribute(t,e,i,n,s,r){return g0.setScalar(0),v0.setScalar(0),M0.setScalar(0),g0.fromBufferAttribute(t,e),v0.fromBufferAttribute(t,i),M0.fromBufferAttribute(t,n),r.setScalar(0),r.addScaledVector(g0,s.x),r.addScaledVector(v0,s.y),r.addScaledVector(M0,s.z),r}static isFrontFacing(t,e,i,n){return Cs.subVectors(i,e),kr.subVectors(t,e),Cs.cross(kr).dot(n)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,e,i,n){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Cs.subVectors(this.c,this.b),kr.subVectors(this.a,this.b),Cs.cross(kr).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return As.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return As.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,n,s){return As.getInterpolation(t,this.a,this.b,this.c,e,i,n,s)}containsPoint(t){return As.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return As.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,n=this.b,s=this.c;let r,a;ac.subVectors(n,i),oc.subVectors(s,i),f0.subVectors(t,i);const c=ac.dot(f0),l=oc.dot(f0);if(c<=0&&l<=0)return e.copy(i);p0.subVectors(t,n);const h=ac.dot(p0),u=oc.dot(p0);if(h>=0&&u<=h)return e.copy(n);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return r=c/(c-h),e.copy(i).addScaledVector(ac,r);m0.subVectors(t,s);const f=ac.dot(m0),p=oc.dot(m0);if(p>=0&&f<=p)return e.copy(s);const g=f*l-c*p;if(g<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(oc,a);const m=h*p-f*u;if(m<=0&&u-h>=0&&f-p>=0)return Rv.subVectors(s,n),a=(u-h)/(u-h+(f-p)),e.copy(n).addScaledVector(Rv,a);const v=1/(m+g+d);return r=g*v,a=d*v,e.copy(i).addScaledVector(ac,r).addScaledVector(oc,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class hn{constructor(t=new R(1/0,1/0,1/0),e=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(Os.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(Os.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=Os.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const i=t.geometry;if(i!==void 0){const s=i.getAttribute("position");if(e===!0&&s!==void 0&&t.isInstancedMesh!==!0)for(let r=0,a=s.count;r<a;r++)t.isMesh===!0?t.getVertexPosition(r,Os):Os.fromBufferAttribute(s,r),Os.applyMatrix4(t.matrixWorld),this.expandByPoint(Os);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),iu.copy(t.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),iu.copy(i.boundingBox)),iu.applyMatrix4(t.matrixWorld),this.union(iu)}const n=t.children;for(let s=0,r=n.length;s<r;s++)this.expandByObject(n[s],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Os),Os.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Al),nu.subVectors(this.max,Al),cc.subVectors(t.a,Al),lc.subVectors(t.b,Al),hc.subVectors(t.c,Al),ha.subVectors(lc,cc),ua.subVectors(hc,lc),Wa.subVectors(cc,hc);let e=[0,-ha.z,ha.y,0,-ua.z,ua.y,0,-Wa.z,Wa.y,ha.z,0,-ha.x,ua.z,0,-ua.x,Wa.z,0,-Wa.x,-ha.y,ha.x,0,-ua.y,ua.x,0,-Wa.y,Wa.x,0];return!y0(e,cc,lc,hc,nu)||(e=[1,0,0,0,1,0,0,0,1],!y0(e,cc,lc,hc,nu))?!1:(su.crossVectors(ha,ua),e=[su.x,su.y,su.z],y0(e,cc,lc,hc,nu))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Os).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(Os).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Fr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Fr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Fr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Fr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Fr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Fr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Fr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Fr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Fr),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Fr=[new R,new R,new R,new R,new R,new R,new R,new R],Os=new R,iu=new hn,cc=new R,lc=new R,hc=new R,ha=new R,ua=new R,Wa=new R,Al=new R,nu=new R,su=new R,Xa=new R;function y0(o,t,e,i,n){for(let s=0,r=o.length-3;s<=r;s+=3){Xa.fromArray(o,s);const a=n.x*Math.abs(Xa.x)+n.y*Math.abs(Xa.y)+n.z*Math.abs(Xa.z),c=t.dot(Xa),l=e.dot(Xa),h=i.dot(Xa);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}const Yr=I3();function I3(){const o=new ArrayBuffer(4),t=new Float32Array(o),e=new Uint32Array(o),i=new Uint32Array(512),n=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(i[c]=0,i[c|256]=32768,n[c]=24,n[c|256]=24):l<-14?(i[c]=1024>>-l-14,i[c|256]=1024>>-l-14|32768,n[c]=-l-1,n[c|256]=-l-1):l<=15?(i[c]=l+15<<10,i[c|256]=l+15<<10|32768,n[c]=13,n[c|256]=13):l<128?(i[c]=31744,i[c|256]=64512,n[c]=24,n[c|256]=24):(i[c]=31744,i[c|256]=64512,n[c]=13,n[c|256]=13)}const s=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)r[c]=c<<23;r[31]=1199570944,r[32]=2147483648;for(let c=33;c<63;++c)r[c]=2147483648+(c-32<<23);r[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(a[c]=1024);return{floatView:t,uint32View:e,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:r,offsetTable:a}}function D3(o){Math.abs(o)>65504&&Nt("DataUtils.toHalfFloat(): Value out of range."),o=oe(o,-65504,65504),Yr.floatView[0]=o;const t=Yr.uint32View[0],e=t>>23&511;return Yr.baseTable[e]+((t&8388607)>>Yr.shiftTable[e])}function C3(o){const t=o>>10;return Yr.uint32View[0]=Yr.mantissaTable[Yr.offsetTable[t]+(o&1023)]+Yr.exponentTable[t],Yr.floatView[0]}class ps{static toHalfFloat(t){return D3(t)}static fromHalfFloat(t){return C3(t)}}const Wi=new R,ru=new it;let O3=0;class ce extends Ha{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:O3++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=i,this.usage=ym,this.updateRanges=[],this.gpuType=Dn,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[t+n]=e.array[i+n];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,i=this.count;e<i;e++)ru.fromBufferAttribute(this,e),ru.applyMatrix3(t),this.setXY(e,ru.x,ru.y);else if(this.itemSize===3)for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyMatrix3(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyMatrix4(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyNormalMatrix(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.transformDirection(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=Vs(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=qe(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=Vs(e,this.array)),e}setX(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=Vs(e,this.array)),e}setY(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=Vs(e,this.array)),e}setZ(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=Vs(e,this.array)),e}setW(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,n){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array),s=qe(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this.array[t+3]=s,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(t.name=this.name),this.usage!==ym&&(t.usage=this.usage),t}dispose(){this.dispatchEvent({type:"dispose"})}}class hx extends ce{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class Ig extends ce{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class le extends ce{constructor(t,e,i){super(new Float32Array(t),e,i)}}const P3=new hn,_l=new R,x0=new R;class ea{constructor(t=new R,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;e!==void 0?i.copy(e):P3.setFromPoints(t).getCenter(i);let n=0;for(let s=0,r=t.length;s<r;s++)n=Math.max(n,i.distanceToSquared(t[s]));return this.radius=Math.sqrt(n),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;_l.subVectors(t,this.center);const e=_l.lengthSq();if(e>this.radius*this.radius){const i=Math.sqrt(e),n=(i-this.radius)*.5;this.center.addScaledVector(_l,n/i),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(x0.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(_l.copy(t.center).add(x0)),this.expandByPoint(_l.copy(t.center).sub(x0))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let L3=0;const ys=new he,b0=new bi,uc=new R,rs=new hn,Tl=new hn,an=new R;class ne extends Ha{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:L3++}),this.uuid=_s(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(ZE(t)?Ig:hx)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new ie().getNormalMatrix(t);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(t),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return ys.makeRotationFromQuaternion(t),this.applyMatrix4(ys),this}rotateX(t){return ys.makeRotationX(t),this.applyMatrix4(ys),this}rotateY(t){return ys.makeRotationY(t),this.applyMatrix4(ys),this}rotateZ(t){return ys.makeRotationZ(t),this.applyMatrix4(ys),this}translate(t,e,i){return ys.makeTranslation(t,e,i),this.applyMatrix4(ys),this}scale(t,e,i){return ys.makeScale(t,e,i),this.applyMatrix4(ys),this}lookAt(t){return b0.lookAt(t),b0.updateMatrix(),this.applyMatrix4(b0.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(uc).negate(),this.translate(uc.x,uc.y,uc.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const i=[];for(let n=0,s=t.length;n<s;n++){const r=t[n];i.push(r.x,r.y,r.z||0)}this.setAttribute("position",new le(i,3))}else{const i=Math.min(t.length,e.count);for(let n=0;n<i;n++){const s=t[n];e.setXYZ(n,s.x,s.y,s.z||0)}t.length>e.count&&Nt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new hn);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){te("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let i=0,n=e.length;i<n;i++){const s=e[i];rs.setFromBufferAttribute(s),this.morphTargetsRelative?(an.addVectors(this.boundingBox.min,rs.min),this.boundingBox.expandByPoint(an),an.addVectors(this.boundingBox.max,rs.max),this.boundingBox.expandByPoint(an)):(this.boundingBox.expandByPoint(rs.min),this.boundingBox.expandByPoint(rs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&te('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new ea);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){te("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new R,1/0);return}if(t){const i=this.boundingSphere.center;if(rs.setFromBufferAttribute(t),e)for(let s=0,r=e.length;s<r;s++){const a=e[s];Tl.setFromBufferAttribute(a),this.morphTargetsRelative?(an.addVectors(rs.min,Tl.min),rs.expandByPoint(an),an.addVectors(rs.max,Tl.max),rs.expandByPoint(an)):(rs.expandByPoint(Tl.min),rs.expandByPoint(Tl.max))}rs.getCenter(i);let n=0;for(let s=0,r=t.count;s<r;s++)an.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(an));if(e)for(let s=0,r=e.length;s<r;s++){const a=e[s],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)an.fromBufferAttribute(a,l),c&&(uc.fromBufferAttribute(t,l),an.add(uc)),n=Math.max(n,i.distanceToSquared(an))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&te('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){te("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.position,n=e.normal,s=e.uv;let r=this.getAttribute("tangent");(r===void 0||r.count!==i.count)&&(r=new ce(new Float32Array(4*i.count),4),this.setAttribute("tangent",r));const a=[],c=[];for(let w=0;w<i.count;w++)a[w]=new R,c[w]=new R;const l=new R,h=new R,u=new R,d=new it,f=new it,p=new it,g=new R,m=new R;function v(w,_,D){l.fromBufferAttribute(i,w),h.fromBufferAttribute(i,_),u.fromBufferAttribute(i,D),d.fromBufferAttribute(s,w),f.fromBufferAttribute(s,_),p.fromBufferAttribute(s,D),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const I=1/(f.x*p.y-p.x*f.y);isFinite(I)&&(g.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(I),m.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(I),a[w].add(g),a[_].add(g),a[D].add(g),c[w].add(m),c[_].add(m),c[D].add(m))}let y=this.groups;y.length===0&&(y=[{start:0,count:t.count}]);for(let w=0,_=y.length;w<_;++w){const D=y[w],I=D.start,O=D.count;for(let L=I,N=I+O;L<N;L+=3)v(t.getX(L+0),t.getX(L+1),t.getX(L+2))}const x=new R,M=new R,b=new R,S=new R;function E(w){b.fromBufferAttribute(n,w),S.copy(b);const _=a[w];x.copy(_),x.sub(b.multiplyScalar(b.dot(_))).normalize(),M.crossVectors(S,_);const I=M.dot(c[w])<0?-1:1;r.setXYZW(w,x.x,x.y,x.z,I)}for(let w=0,_=y.length;w<_;++w){const D=y[w],I=D.start,O=D.count;for(let L=I,N=I+O;L<N;L+=3)E(t.getX(L+0)),E(t.getX(L+1)),E(t.getX(L+2))}this._transformed=!0}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(e!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==e.count)i=new ce(new Float32Array(e.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new R,s=new R,r=new R,a=new R,c=new R,l=new R,h=new R,u=new R;if(t)for(let d=0,f=t.count;d<f;d+=3){const p=t.getX(d+0),g=t.getX(d+1),m=t.getX(d+2);n.fromBufferAttribute(e,p),s.fromBufferAttribute(e,g),r.fromBufferAttribute(e,m),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),a.fromBufferAttribute(i,p),c.fromBufferAttribute(i,g),l.fromBufferAttribute(i,m),a.add(h),c.add(h),l.add(h),i.setXYZ(p,a.x,a.y,a.z),i.setXYZ(g,c.x,c.y,c.z),i.setXYZ(m,l.x,l.y,l.z)}else for(let d=0,f=e.count;d<f;d+=3)n.fromBufferAttribute(e,d+0),s.fromBufferAttribute(e,d+1),r.fromBufferAttribute(e,d+2),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)an.fromBufferAttribute(t,e),an.normalize(),t.setXYZ(e,an.x,an.y,an.z)}toNonIndexed(){function t(a,c){const l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let g=0,m=c.length;g<m;g++){a.isInterleavedBufferAttribute?f=c[g]*a.data.stride+a.offset:f=c[g]*h;for(let v=0;v<h;v++)d[p++]=l[f++]}return new ce(d,h,u)}if(this.index===null)return Nt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new ne,i=this.index.array,n=this.attributes;for(const a in n){const c=n[a],l=t(c,i);e.setAttribute(a,l)}const s=this.morphAttributes;for(const a in s){const c=[],l=s[a];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=t(d,i);c.push(f)}e.morphAttributes[a]=c}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,c=r.length;a<c;a++){const l=r[a];e.addGroup(l.start,l.count,l.materialIndex)}return e}toJSON(){const t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(t[l]=c[l]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const c in i){const l=i[c];t.data.attributes[c]=l.toJSON(t.data)}const n={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(t.data))}h.length>0&&(n[c]=h,s=!0)}s&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;i!==null&&this.setIndex(i.clone());const n=t.attributes;for(const l in n){const h=n[l];this.setAttribute(l,h.clone(e))}const s=t.morphAttributes;for(const l in s){const h=[],u=s[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(e));this.morphAttributes[l]=h}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let l=0,h=r.length;l<h;l++){const u=r[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=t.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ux{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=ym,this.updateRanges=[],this.version=0,this.uuid=_s()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let n=0,s=this.stride;n<s;n++)this.array[t+n]=e.array[i+n];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=_s()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(e,this.stride);return i.setUsage(this.usage),i}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=_s()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const On=new R;class tf{constructor(t,e,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=e,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,i=this.data.count;e<i;e++)On.fromBufferAttribute(this,e),On.applyMatrix4(t),this.setXYZ(e,On.x,On.y,On.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)On.fromBufferAttribute(this,e),On.applyNormalMatrix(t),this.setXYZ(e,On.x,On.y,On.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)On.fromBufferAttribute(this,e),On.transformDirection(t),this.setXYZ(e,On.x,On.y,On.z);return this}getComponent(t,e){let i=this.array[t*this.data.stride+this.offset+e];return this.normalized&&(i=Vs(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=qe(i,this.array)),this.data.array[t*this.data.stride+this.offset+e]=i,this}setX(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){let e=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(e=Vs(e,this.array)),e}getY(t){let e=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(e=Vs(e,this.array)),e}getZ(t){let e=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(e=Vs(e,this.array)),e}getW(t){let e=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(e=Vs(e,this.array)),e}setXY(t,e,i){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this}setXYZ(t,e,i,n){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array),s=qe(s,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this.data.array[t+3]=s,this}clone(t){if(t===void 0){Qd("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return new ce(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new tf(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(t===void 0){Qd("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let N3=0;class Pr extends Ha{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:N3++}),this.uuid=_s(),this.name="",this.type="Material",this.blending=Ua,this.side=za,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Wd,this.blendDst=Ah,this.blendEquation=$r,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new st(0,0,0),this.blendAlpha=0,this.depthFunc=ll,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=mv,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ec,this.stencilZFail=ec,this.stencilZPass=ec,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const i=t[e];if(i===void 0){Nt(`Material: parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Nt(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Ua&&(i.blending=this.blending),this.side!==za&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Wd&&(i.blendSrc=this.blendSrc),this.blendDst!==Ah&&(i.blendDst=this.blendDst),this.blendEquation!==$r&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ll&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==mv&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ec&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ec&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ec&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const r=[];for(const a in s){const c=s[a];delete c.metadata,r.push(c)}return r}if(e){const s=n(t.textures),r=n(t.images);s.length>0&&(i.textures=s),r.length>0&&(i.images=r)}return i}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new st().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let i=t.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new it().fromArray(i)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new it().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(e!==null){const n=e.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class dd extends Pr{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new st(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let dc;const Rl=new R,fc=new R,pc=new R,mc=new it,Il=new it,dx=new he,au=new R,Dl=new R,ou=new R,Iv=new it,w0=new it,Dv=new it;class Cl extends bi{constructor(t=new dd){if(super(),this.isSprite=!0,this.type="Sprite",dc===void 0){dc=new ne;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new ux(e,5);dc.setIndex([0,1,2,0,2,3]),dc.setAttribute("position",new tf(i,3,0,!1)),dc.setAttribute("uv",new tf(i,2,3,!1))}this.geometry=dc,this.material=t,this.center=new it(.5,.5),this.count=1}raycast(t,e){t.camera===null&&te('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),fc.setFromMatrixScale(this.matrixWorld),dx.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),pc.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&fc.multiplyScalar(-pc.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const r=this.center;cu(au.set(-.5,-.5,0),pc,r,fc,n,s),cu(Dl.set(.5,-.5,0),pc,r,fc,n,s),cu(ou.set(.5,.5,0),pc,r,fc,n,s),Iv.set(0,0),w0.set(1,0),Dv.set(1,1);let a=t.ray.intersectTriangle(au,Dl,ou,!1,Rl);if(a===null&&(cu(Dl.set(-.5,.5,0),pc,r,fc,n,s),w0.set(0,1),a=t.ray.intersectTriangle(au,ou,Dl,!1,Rl),a===null))return;const c=t.ray.origin.distanceTo(Rl);c<t.near||c>t.far||e.push({distance:c,point:Rl.clone(),uv:As.getInterpolation(Rl,au,Dl,ou,Iv,w0,Dv,new it),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function cu(o,t,e,i,n,s){mc.subVectors(o,e).addScalar(.5).multiply(i),n!==void 0?(Il.x=s*mc.x-n*mc.y,Il.y=n*mc.x+s*mc.y):Il.copy(mc),o.copy(t),o.x+=Il.x,o.y+=Il.y,o.applyMatrix4(dx)}const zr=new R,S0=new R,lu=new R,da=new R,E0=new R,hu=new R,A0=new R;class zh{constructor(t=new R,e=new R(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,zr)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=zr.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(zr.copy(this.origin).addScaledVector(this.direction,e),zr.distanceToSquared(t))}distanceSqToSegment(t,e,i,n){S0.copy(t).add(e).multiplyScalar(.5),lu.copy(e).sub(t).normalize(),da.copy(this.origin).sub(S0);const s=t.distanceTo(e)*.5,r=-this.direction.dot(lu),a=da.dot(this.direction),c=-da.dot(lu),l=da.lengthSq(),h=Math.abs(1-r*r);let u,d,f,p;if(h>0)if(u=r*c-a,d=r*a-c,p=s*h,u>=0)if(d>=-p)if(d<=p){const g=1/h;u*=g,d*=g,f=u*(u+r*d+2*a)+d*(r*u+d+2*c)+l}else d=s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d=-s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-r*s+a)),d=u>0?-s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-s,-c),s),f=d*(d+2*c)+l):(u=Math.max(0,-(r*s+a)),d=u>0?s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l);else d=r>0?-s:s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(S0).addScaledVector(lu,d),f}intersectSphere(t,e){zr.subVectors(t.center,this.origin);const i=zr.dot(this.direction),n=zr.dot(zr)-i*i,s=t.radius*t.radius;if(n>s)return null;const r=Math.sqrt(s-n),a=i-r,c=i+r;return c<0?null:a<0?this.at(c,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return i===null?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,n,s,r,a,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,n=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,n=(t.min.x-d.x)*l),h>=0?(s=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(s=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||s>n||((s>i||isNaN(i))&&(i=s),(r<n||isNaN(n))&&(n=r),u>=0?(a=(t.min.z-d.z)*u,c=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,c=(t.min.z-d.z)*u),i>c||a>n)||((a>i||i!==i)&&(i=a),(c<n||n!==n)&&(n=c),n<0)?null:this.at(i>=0?i:n,e)}intersectsBox(t){return this.intersectBox(t,zr)!==null}intersectTriangle(t,e,i,n,s){E0.subVectors(e,t),hu.subVectors(i,t),A0.crossVectors(E0,hu);let r=this.direction.dot(A0),a;if(r>0){if(n)return null;a=1}else if(r<0)a=-1,r=-r;else return null;da.subVectors(this.origin,t);const c=a*this.direction.dot(hu.crossVectors(da,hu));if(c<0)return null;const l=a*this.direction.dot(E0.cross(da));if(l<0||c+l>r)return null;const h=-a*da.dot(A0);return h<0?null:this.at(h/r,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class es extends Pr{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new st(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.combine=mg,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Cv=new he,$a=new zh,uu=new ea,Ov=new R,du=new R,fu=new R,pu=new R,_0=new R,mu=new R,Pv=new R,gu=new R;class bt extends bi{constructor(t=new ne,e=new es){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(t,e){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(n,t);const a=this.morphTargetInfluences;if(s&&a){mu.set(0,0,0);for(let c=0,l=s.length;c<l;c++){const h=a[c],u=s[c];h!==0&&(_0.fromBufferAttribute(u,t),r?mu.addScaledVector(_0,h):mu.addScaledVector(_0.sub(e),h))}e.add(mu)}return e}raycast(t,e){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),uu.copy(i.boundingSphere),uu.applyMatrix4(s),$a.copy(t.ray).recast(t.near),!(uu.containsPoint($a.origin)===!1&&($a.intersectSphere(uu,Ov)===null||$a.origin.distanceToSquared(Ov)>(t.far-t.near)**2))&&(Cv.copy(s).invert(),$a.copy(t.ray).applyMatrix4(Cv),!(i.boundingBox!==null&&$a.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(t,e,$a)))}_computeIntersections(t,e,i){let n;const s=this.geometry,r=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(r))for(let p=0,g=d.length;p<g;p++){const m=d[p],v=r[m.materialIndex],y=Math.max(m.start,f.start),x=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let M=y,b=x;M<b;M+=3){const S=a.getX(M),E=a.getX(M+1),w=a.getX(M+2);n=vu(this,v,t,i,l,h,u,S,E,w),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=m.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),g=Math.min(a.count,f.start+f.count);for(let m=p,v=g;m<v;m+=3){const y=a.getX(m),x=a.getX(m+1),M=a.getX(m+2);n=vu(this,r,t,i,l,h,u,y,x,M),n&&(n.faceIndex=Math.floor(m/3),e.push(n))}}else if(c!==void 0)if(Array.isArray(r))for(let p=0,g=d.length;p<g;p++){const m=d[p],v=r[m.materialIndex],y=Math.max(m.start,f.start),x=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let M=y,b=x;M<b;M+=3){const S=M,E=M+1,w=M+2;n=vu(this,v,t,i,l,h,u,S,E,w),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=m.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),g=Math.min(c.count,f.start+f.count);for(let m=p,v=g;m<v;m+=3){const y=m,x=m+1,M=m+2;n=vu(this,r,t,i,l,h,u,y,x,M),n&&(n.faceIndex=Math.floor(m/3),e.push(n))}}}}function k3(o,t,e,i,n,s,r,a){let c;if(t.side===xi?c=i.intersectTriangle(r,s,n,!0,a):c=i.intersectTriangle(n,s,r,t.side===za,a),c===null)return null;gu.copy(a),gu.applyMatrix4(o.matrixWorld);const l=e.ray.origin.distanceTo(gu);return l<e.near||l>e.far?null:{distance:l,point:gu.clone(),object:o}}function vu(o,t,e,i,n,s,r,a,c,l){o.getVertexPosition(a,du),o.getVertexPosition(c,fu),o.getVertexPosition(l,pu);const h=k3(o,t,e,i,du,fu,pu,Pv);if(h){const u=new R;As.getBarycoord(Pv,du,fu,pu,u),n&&(h.uv=As.getInterpolatedAttribute(n,a,c,l,u,new it)),s&&(h.uv1=As.getInterpolatedAttribute(s,a,c,l,u,new it)),r&&(h.normal=As.getInterpolatedAttribute(r,a,c,l,u,new R),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:c,c:l,normal:new R,materialIndex:0};As.getNormal(du,fu,pu,d.normal),h.face=d,h.barycoord=u}return h}const Ol=new _e,Lv=new _e,Nv=new _e,U3=new _e,kv=new he,Mu=new R,T0=new ea,Uv=new he,R0=new zh;class XO extends bt{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=fv,this.bindMatrix=new he,this.bindMatrixInverse=new he,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new hn),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,Mu),this.boundingBox.expandByPoint(Mu)}computeBoundingSphere(){const t=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new ea),this.boundingSphere.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,Mu),this.boundingSphere.expandByPoint(Mu)}copy(t,e){return super.copy(t,e),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}raycast(t,e){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),T0.copy(this.boundingSphere),T0.applyMatrix4(n),t.ray.intersectsSphere(T0)!==!1&&(Uv.copy(n).invert(),R0.copy(t.ray).applyMatrix4(Uv),!(this.boundingBox!==null&&R0.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(t,e,R0)))}getVertexPosition(t,e){return super.getVertexPosition(t,e),this.applyBoneTransform(t,e),e}bind(t,e){this.skeleton=t,e===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new _e,e=this.geometry.attributes.skinWeight;for(let i=0,n=e.count;i<n;i++){t.fromBufferAttribute(e,i);const s=1/t.manhattanLength();s!==1/0?t.multiplyScalar(s):t.set(1,0,0,0),e.setXYZW(i,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.bindMode===fv?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===UE?this.bindMatrixInverse.copy(this.bindMatrix).invert():Nt("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(t,e){const i=this.skeleton,n=this.geometry;Lv.fromBufferAttribute(n.attributes.skinIndex,t),Nv.fromBufferAttribute(n.attributes.skinWeight,t),e.isVector4?(Ol.copy(e),e.set(0,0,0,0)):(Ol.set(...e,1),e.set(0,0,0)),Ol.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){const r=Nv.getComponent(s);if(r!==0){const a=Lv.getComponent(s);kv.multiplyMatrices(i.bones[a].matrixWorld,i.boneInverses[a]),e.addScaledVector(U3.copy(Ol).applyMatrix4(kv),r)}}return e.isVector4&&(e.w=Ol.w),e.applyMatrix4(this.bindMatrixInverse)}}class F3 extends bi{constructor(){super(),this.isBone=!0,this.type="Bone"}}class gs extends Mn{constructor(t=null,e=1,i=1,n,s,r,a,c,l=ei,h=ei,u,d){super(null,r,a,c,l,h,n,s,u,d),this.isDataTexture=!0,this.image={data:t,width:e,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Fv=new he,z3=new he;class fx{constructor(t=[],e=[]){this.uuid=_s(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(t.length*16),e.length===0)this.calculateInverses();else if(t.length!==e.length){Nt("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new he)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const i=new he;this.bones[t]&&i.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&i.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const t=this.bones,e=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,r=t.length;s<r;s++){const a=t[s]?t[s].matrixWorld:z3;Fv.multiplyMatrices(a,e[s]),Fv.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new fx(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(this.bones.length*4);t=Math.ceil(t/4)*4,t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const i=new gs(e,t,t,Ki,Dn);return i.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=i,this}getBoneByName(t){for(let e=0,i=this.bones.length;e<i;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let i=0,n=t.bones.length;i<n;i++){const s=t.bones[i];let r=e[s];r===void 0&&(Nt("Skeleton: No bone found with UUID:",s),r=new F3),this.bones.push(r),this.boneInverses.push(new he().fromArray(t.boneInverses[i]))}return this.init(),this}toJSON(){const t={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,i=this.boneInverses;for(let n=0,s=e.length;n<s;n++){const r=e[n];t.bones.push(r.uuid);const a=i[n];t.boneInverses.push(a.toArray())}return t}}class zv extends ce{constructor(t,e,i,n=1){super(t,e,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}const gc=new he,Bv=new he,yu=[],Hv=new hn,B3=new he,Pl=new bt,Ll=new ea;class $O extends bt{constructor(t,e,i){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new zv(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,B3)}computeBoundingBox(){const t=this.geometry,e=this.count;this.boundingBox===null&&(this.boundingBox=new hn),t.boundingBox===null&&t.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,gc),Hv.copy(t.boundingBox).applyMatrix4(gc),this.boundingBox.union(Hv)}computeBoundingSphere(){const t=this.geometry,e=this.count;this.boundingSphere===null&&(this.boundingSphere=new ea),t.boundingSphere===null&&t.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,gc),Ll.copy(t.boundingSphere).applyMatrix4(gc),this.boundingSphere.union(Ll)}copy(t,e){return super.copy(t,e),this.instanceMatrix.copy(t.instanceMatrix),t.morphTexture!==null&&(this.morphTexture=t.morphTexture.clone()),t.instanceColor!==null&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}getColorAt(t,e){return this.instanceColor===null?e.setRGB(1,1,1):e.fromArray(this.instanceColor.array,t*3)}getMatrixAt(t,e){return e.fromArray(this.instanceMatrix.array,t*16)}getMorphAt(t,e){const i=e.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,r=t*s+1;for(let a=0;a<i.length;a++)i[a]=n[r+a]}raycast(t,e){const i=this.matrixWorld,n=this.count;if(Pl.geometry=this.geometry,Pl.material=this.material,Pl.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Ll.copy(this.boundingSphere),Ll.applyMatrix4(i),t.ray.intersectsSphere(Ll)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,gc),Bv.multiplyMatrices(i,gc),Pl.matrixWorld=Bv,Pl.raycast(t,yu);for(let r=0,a=yu.length;r<a;r++){const c=yu[r];c.instanceId=s,c.object=this,e.push(c)}yu.length=0}}setColorAt(t,e){return this.instanceColor===null&&(this.instanceColor=new zv(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),e.toArray(this.instanceColor.array,t*3),this}setMatrixAt(t,e){return e.toArray(this.instanceMatrix.array,t*16),this}setMorphAt(t,e){const i=e.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new gs(new Float32Array(n*this.count),n,this.count,ul,Dn));const s=this.morphTexture.source.data.data;let r=0;for(let l=0;l<i.length;l++)r+=i[l];const a=this.geometry.morphTargetsRelative?1:1-r,c=n*t;return s[c]=a,s.set(i,c+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const I0=new R,H3=new R,G3=new ie;class Sa{constructor(t=new R(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,n){return this.normal.set(t,e,i),this.constant=n,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const n=I0.subVectors(i,e).cross(H3.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e,i=!0){const n=t.delta(I0),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/s;return i===!0&&(r<0||r>1)?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||G3.getNormalMatrix(t),n=this.coplanarPoint(I0).applyMatrix4(t),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Ya=new ea,V3=new it(.5,.5),xu=new R;class Dg{constructor(t=new Sa,e=new Sa,i=new Sa,n=new Sa,s=new Sa,r=new Sa){this.planes=[t,e,i,n,s,r]}set(t,e,i,n,s,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(n),a[4].copy(s),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=Tr,i=!1){const n=this.planes,s=t.elements,r=s[0],a=s[1],c=s[2],l=s[3],h=s[4],u=s[5],d=s[6],f=s[7],p=s[8],g=s[9],m=s[10],v=s[11],y=s[12],x=s[13],M=s[14],b=s[15];if(n[0].setComponents(l-r,f-h,v-p,b-y).normalize(),n[1].setComponents(l+r,f+h,v+p,b+y).normalize(),n[2].setComponents(l+a,f+u,v+g,b+x).normalize(),n[3].setComponents(l-a,f-u,v-g,b-x).normalize(),i)n[4].setComponents(c,d,m,M).normalize(),n[5].setComponents(l-c,f-d,v-m,b-M).normalize();else if(n[4].setComponents(l-c,f-d,v-m,b-M).normalize(),e===Tr)n[5].setComponents(l+c,f+d,v+m,b+M).normalize();else if(e===Rh)n[5].setComponents(c,d,m,M).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Ya.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Ya.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Ya)}intersectsSprite(t){Ya.center.set(0,0,0);const e=V3.distanceTo(t.center);return Ya.radius=.7071067811865476+e,Ya.applyMatrix4(t.matrixWorld),this.intersectsSphere(Ya)}intersectsSphere(t){const e=this.planes,i=t.center,n=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const n=e[i];if(xu.x=n.normal.x>0?t.max.x:t.min.x,xu.y=n.normal.y>0?t.max.y:t.min.y,xu.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(xu)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class W3 extends Pr{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new st(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}}const ef=new R,nf=new R,Gv=new he,Nl=new zh,bu=new ea,D0=new R,Vv=new R;class px extends bi{constructor(t=new ne,e=new W3){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[0];for(let n=1,s=e.count;n<s;n++)ef.fromBufferAttribute(e,n-1),nf.fromBufferAttribute(e,n),i[n]=i[n-1],i[n]+=ef.distanceTo(nf);t.setAttribute("lineDistance",new le(i,1))}else Nt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Line.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),bu.copy(i.boundingSphere),bu.applyMatrix4(n),bu.radius+=s,t.ray.intersectsSphere(bu)===!1)return;Gv.copy(n).invert(),Nl.copy(t.ray).applyMatrix4(Gv);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=i.index,d=i.attributes.position;if(h!==null){const f=Math.max(0,r.start),p=Math.min(h.count,r.start+r.count);for(let g=f,m=p-1;g<m;g+=l){const v=h.getX(g),y=h.getX(g+1),x=wu(this,t,Nl,c,v,y,g);x&&e.push(x)}if(this.isLineLoop){const g=h.getX(p-1),m=h.getX(f),v=wu(this,t,Nl,c,g,m,p-1);v&&e.push(v)}}else{const f=Math.max(0,r.start),p=Math.min(d.count,r.start+r.count);for(let g=f,m=p-1;g<m;g+=l){const v=wu(this,t,Nl,c,g,g+1,g);v&&e.push(v)}if(this.isLineLoop){const g=wu(this,t,Nl,c,p-1,f,p-1);g&&e.push(g)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function wu(o,t,e,i,n,s,r){const a=o.geometry.attributes.position;if(ef.fromBufferAttribute(a,n),nf.fromBufferAttribute(a,s),e.distanceSqToSegment(ef,nf,D0,Vv)>i)return;D0.applyMatrix4(o.matrixWorld);const l=t.ray.origin.distanceTo(D0);if(!(l<t.near||l>t.far))return{distance:l,point:Vv.clone().applyMatrix4(o.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:o}}const Wv=new R,Xv=new R;class YO extends px{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[];for(let n=0,s=e.count;n<s;n+=2)Wv.fromBufferAttribute(e,n),Xv.fromBufferAttribute(e,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+Wv.distanceTo(Xv);t.setAttribute("lineDistance",new le(i,1))}else Nt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class qO extends px{constructor(t,e){super(t,e),this.isLineLoop=!0,this.type="LineLoop"}}class xm extends Pr{constructor(t){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new st(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const $v=new he,bm=new zh,Su=new ea,Eu=new R;class Jn extends bi{constructor(t=new ne,e=new xm){super(),this.isPoints=!0,this.type="Points",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Points.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Su.copy(i.boundingSphere),Su.applyMatrix4(n),Su.radius+=s,t.ray.intersectsSphere(Su)===!1)return;$v.copy(n).invert(),bm.copy(t.ray).applyMatrix4($v);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=i.index,u=i.attributes.position;if(l!==null){const d=Math.max(0,r.start),f=Math.min(l.count,r.start+r.count);for(let p=d,g=f;p<g;p++){const m=l.getX(p);Eu.fromBufferAttribute(u,m),Yv(Eu,m,c,n,t,e,this)}}else{const d=Math.max(0,r.start),f=Math.min(u.count,r.start+r.count);for(let p=d,g=f;p<g;p++)Eu.fromBufferAttribute(u,p),Yv(Eu,p,c,n,t,e,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function Yv(o,t,e,i,n,s,r){const a=bm.distanceSqToPoint(o);if(a<e){const c=new R;bm.closestPointToPoint(o,c),c.applyMatrix4(i);const l=n.ray.origin.distanceTo(c);if(l<n.near||l>n.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:r})}}class mx extends Mn{constructor(t=[],e=Bo,i,n,s,r,a,c,l,h){super(t,e,i,n,s,r,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class ia extends Mn{constructor(t,e,i,n,s,r,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ba extends Mn{constructor(t,e,i=Ts,n,s,r,a=ei,c=ei,l,h=Jr,u=1){if(h!==Jr&&h!==wo)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:t,height:e,depth:u};super(d,n,s,r,a,c,h,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new _g(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class X3 extends Ba{constructor(t,e=Ts,i=Bo,n,s,r=ei,a=ei,c,l=Jr){const h={width:t,height:t,depth:1},u=[h,h,h,h,h,h];super(t,t,e,i,n,s,r,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class gx extends Mn{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class Pi extends ne{constructor(t=1,e=1,i=1,n=1,s=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:n,heightSegments:s,depthSegments:r};const a=this;n=Math.floor(n),s=Math.floor(s),r=Math.floor(r);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,e,t,r,s,0),p("z","y","x",1,-1,i,e,-t,r,s,1),p("x","z","y",1,1,t,i,e,n,r,2),p("x","z","y",1,-1,t,i,-e,n,r,3),p("x","y","z",1,-1,t,e,i,n,s,4),p("x","y","z",-1,-1,t,e,-i,n,s,5),this.setIndex(c),this.setAttribute("position",new le(l,3)),this.setAttribute("normal",new le(h,3)),this.setAttribute("uv",new le(u,2));function p(g,m,v,y,x,M,b,S,E,w,_){const D=M/E,I=b/w,O=M/2,L=b/2,N=S/2,P=E+1,z=w+1;let B=0,Y=0;const j=new R;for(let K=0;K<z;K++){const nt=K*I-L;for(let at=0;at<P;at++){const $t=at*D-O;j[g]=$t*y,j[m]=nt*x,j[v]=N,l.push(j.x,j.y,j.z),j[g]=0,j[m]=0,j[v]=S>0?1:-1,h.push(j.x,j.y,j.z),u.push(at/E),u.push(1-K/w),B+=1}}for(let K=0;K<w;K++)for(let nt=0;nt<E;nt++){const at=d+nt+P*K,$t=d+nt+P*(K+1),de=d+(nt+1)+P*(K+1),Gt=d+(nt+1)+P*K;c.push(at,$t,Gt),c.push($t,de,Gt),Y+=6}a.addGroup(f,Y,_),f+=Y,d+=B}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Pi(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}class Cg extends ne{constructor(t=1,e=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:i,thetaLength:n},e=Math.max(3,e);const s=[],r=[],a=[],c=[],l=new R,h=new it;r.push(0,0,0),a.push(0,0,1),c.push(.5,.5);for(let u=0,d=3;u<=e;u++,d+=3){const f=i+u/e*n;l.x=t*Math.cos(f),l.y=t*Math.sin(f),r.push(l.x,l.y,l.z),a.push(0,0,1),h.x=(r[d]/t+1)/2,h.y=(r[d+1]/t+1)/2,c.push(h.x,h.y)}for(let u=1;u<=e;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new le(r,3)),this.setAttribute("normal",new le(a,3)),this.setAttribute("uv",new le(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Cg(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class Cn extends ne{constructor(t=1,e=1,i=1,n=32,s=1,r=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:i,radialSegments:n,heightSegments:s,openEnded:r,thetaStart:a,thetaLength:c};const l=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],f=[];let p=0;const g=[],m=i/2;let v=0;y(),r===!1&&(t>0&&x(!0),e>0&&x(!1)),this.setIndex(h),this.setAttribute("position",new le(u,3)),this.setAttribute("normal",new le(d,3)),this.setAttribute("uv",new le(f,2));function y(){const M=new R,b=new R;let S=0;const E=(e-t)/i;for(let w=0;w<=s;w++){const _=[],D=w/s,I=D*(e-t)+t;for(let O=0;O<=n;O++){const L=O/n,N=L*c+a,P=Math.sin(N),z=Math.cos(N);b.x=I*P,b.y=-D*i+m,b.z=I*z,u.push(b.x,b.y,b.z),M.set(P,E,z).normalize(),d.push(M.x,M.y,M.z),f.push(L,1-D),_.push(p++)}g.push(_)}for(let w=0;w<n;w++)for(let _=0;_<s;_++){const D=g[_][w],I=g[_+1][w],O=g[_+1][w+1],L=g[_][w+1];(t>0||_!==0)&&(h.push(D,I,L),S+=3),(e>0||_!==s-1)&&(h.push(I,O,L),S+=3)}l.addGroup(v,S,0),v+=S}function x(M){const b=p,S=new it,E=new R;let w=0;const _=M===!0?t:e,D=M===!0?1:-1;for(let O=1;O<=n;O++)u.push(0,m*D,0),d.push(0,D,0),f.push(.5,.5),p++;const I=p;for(let O=0;O<=n;O++){const N=O/n*c+a,P=Math.cos(N),z=Math.sin(N);E.x=_*z,E.y=m*D,E.z=_*P,u.push(E.x,E.y,E.z),d.push(0,D,0),S.x=P*.5+.5,S.y=z*.5*D+.5,f.push(S.x,S.y),p++}for(let O=0;O<n;O++){const L=b+O,N=I+O;M===!0?h.push(N,N+1,L):h.push(N+1,N,L),w+=3}l.addGroup(v,w,M===!0?1:2),v+=w}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Cn(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class vl extends Cn{constructor(t=1,e=1,i=32,n=1,s=!1,r=0,a=Math.PI*2){super(0,t,e,i,n,s,r,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:r,thetaLength:a}}static fromJSON(t){return new vl(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Lr{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Nt("Curve: .getPoint() not implemented.")}getPointAt(t,e){const i=this.getUtoTmapping(t);return this.getPoint(i,e)}getPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return e}getSpacedPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPointAt(i/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let i,n=this.getPoint(0),s=0;e.push(0);for(let r=1;r<=t;r++)i=this.getPoint(r/t),s+=i.distanceTo(n),e.push(s),n=i;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e=null){const i=this.getLengths();let n=0;const s=i.length;let r;e?r=e:r=t*i[s-1];let a=0,c=s-1,l;for(;a<=c;)if(n=Math.floor(a+(c-a)/2),l=i[n]-r,l<0)a=n+1;else if(l>0)c=n-1;else{c=n;break}if(n=c,i[n]===r)return n/(s-1);const h=i[n],d=i[n+1]-h,f=(r-h)/d;return(n+f)/(s-1)}getTangent(t,e){let n=t-1e-4,s=t+1e-4;n<0&&(n=0),s>1&&(s=1);const r=this.getPoint(n),a=this.getPoint(s),c=e||(r.isVector2?new it:new R);return c.copy(a).sub(r).normalize(),c}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new R,n=[],s=[],r=[],a=new R,c=new he;for(let f=0;f<=t;f++){const p=f/t;n[f]=this.getTangentAt(p,new R)}s[0]=new R,r[0]=new R;let l=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=l&&(l=h,i.set(1,0,0)),u<=l&&(l=u,i.set(0,1,0)),d<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],a),r[0].crossVectors(n[0],s[0]);for(let f=1;f<=t;f++){if(s[f]=s[f-1].clone(),r[f]=r[f-1].clone(),a.crossVectors(n[f-1],n[f]),a.length()>Number.EPSILON){a.normalize();const p=Math.acos(oe(n[f-1].dot(n[f]),-1,1));s[f].applyMatrix4(c.makeRotationAxis(a,p))}r[f].crossVectors(n[f],s[f])}if(e===!0){let f=Math.acos(oe(s[0].dot(s[t]),-1,1));f/=t,n[0].dot(a.crossVectors(s[0],s[t]))>0&&(f=-f);for(let p=1;p<=t;p++)s[p].applyMatrix4(c.makeRotationAxis(n[p],f*p)),r[p].crossVectors(n[p],s[p])}return{tangents:n,normals:s,binormals:r}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Og extends Lr{constructor(t=0,e=0,i=1,n=1,s=0,r=Math.PI*2,a=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=r,this.aClockwise=a,this.aRotation=c}getPoint(t,e=new it){const i=e,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const r=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(r?s=0:s=n),this.aClockwise===!0&&!r&&(s===n?s=-n:s=s-n);const a=this.aStartAngle+t*s;let c=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=c-this.aX,f=l-this.aY;c=d*h-f*u+this.aX,l=d*u+f*h+this.aY}return i.set(c,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}class $3 extends Og{constructor(t,e,i,n,s,r){super(t,e,i,i,n,s,r),this.isArcCurve=!0,this.type="ArcCurve"}}function Pg(){let o=0,t=0,e=0,i=0;function n(s,r,a,c){o=s,t=a,e=-3*s+3*r-2*a-c,i=2*s-2*r+a+c}return{initCatmullRom:function(s,r,a,c,l){n(r,a,l*(a-s),l*(c-r))},initNonuniformCatmullRom:function(s,r,a,c,l,h,u){let d=(r-s)/l-(a-s)/(l+h)+(a-r)/h,f=(a-r)/h-(c-r)/(h+u)+(c-a)/u;d*=h,f*=h,n(r,a,d,f)},calc:function(s){const r=s*s,a=r*s;return o+t*s+e*r+i*a}}}const qv=new R,Kv=new R,C0=new Pg,O0=new Pg,P0=new Pg;class Y3 extends Lr{constructor(t=[],e=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=i,this.tension=n}getPoint(t,e=new R){const i=e,n=this.points,s=n.length,r=(s-(this.closed?0:1))*t;let a=Math.floor(r),c=r-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/s)+1)*s:c===0&&a===s-1&&(a=s-2,c=1);let l,h;this.closed||a>0?l=n[(a-1)%s]:(Kv.subVectors(n[0],n[1]).add(n[0]),l=Kv);const u=n[a%s],d=n[(a+1)%s];if(this.closed||a+2<s?h=n[(a+2)%s]:(qv.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=qv),this.curveType==="centripetal"||this.curveType==="chordal"){const f=this.curveType==="chordal"?.5:.25;let p=Math.pow(l.distanceToSquared(u),f),g=Math.pow(u.distanceToSquared(d),f),m=Math.pow(d.distanceToSquared(h),f);g<1e-4&&(g=1),p<1e-4&&(p=g),m<1e-4&&(m=g),C0.initNonuniformCatmullRom(l.x,u.x,d.x,h.x,p,g,m),O0.initNonuniformCatmullRom(l.y,u.y,d.y,h.y,p,g,m),P0.initNonuniformCatmullRom(l.z,u.z,d.z,h.z,p,g,m)}else this.curveType==="catmullrom"&&(C0.initCatmullRom(l.x,u.x,d.x,h.x,this.tension),O0.initCatmullRom(l.y,u.y,d.y,h.y,this.tension),P0.initCatmullRom(l.z,u.z,d.z,h.z,this.tension));return i.set(C0.calc(c),O0.calc(c),P0.calc(c)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new R().fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function Zv(o,t,e,i,n){const s=(i-t)*.5,r=(n-e)*.5,a=o*o,c=o*a;return(2*e-2*i+s+r)*c+(-3*e+3*i-2*s-r)*a+s*o+e}function q3(o,t){const e=1-o;return e*e*t}function K3(o,t){return 2*(1-o)*o*t}function Z3(o,t){return o*o*t}function ah(o,t,e,i){return q3(o,t)+K3(o,e)+Z3(o,i)}function J3(o,t){const e=1-o;return e*e*e*t}function j3(o,t){const e=1-o;return 3*e*e*o*t}function Q3(o,t){return 3*(1-o)*o*o*t}function tA(o,t){return o*o*o*t}function oh(o,t,e,i,n){return J3(o,t)+j3(o,e)+Q3(o,i)+tA(o,n)}class vx extends Lr{constructor(t=new it,e=new it,i=new it,n=new it){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new it){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(oh(t,n.x,s.x,r.x,a.x),oh(t,n.y,s.y,r.y,a.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class eA extends Lr{constructor(t=new R,e=new R,i=new R,n=new R){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new R){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(oh(t,n.x,s.x,r.x,a.x),oh(t,n.y,s.y,r.y,a.y),oh(t,n.z,s.z,r.z,a.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class Mx extends Lr{constructor(t=new it,e=new it){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new it){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new it){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class iA extends Lr{constructor(t=new R,e=new R){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=t,this.v2=e}getPoint(t,e=new R){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new R){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class yx extends Lr{constructor(t=new it,e=new it,i=new it){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new it){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(ah(t,n.x,s.x,r.x),ah(t,n.y,s.y,r.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class nA extends Lr{constructor(t=new R,e=new R,i=new R){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new R){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(ah(t,n.x,s.x,r.x),ah(t,n.y,s.y,r.y),ah(t,n.z,s.z,r.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class xx extends Lr{constructor(t=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=t}getPoint(t,e=new it){const i=e,n=this.points,s=(n.length-1)*t,r=Math.floor(s),a=s-r,c=n[r===0?r:r-1],l=n[r],h=n[r>n.length-2?n.length-1:r+1],u=n[r>n.length-3?n.length-1:r+2];return i.set(Zv(a,c.x,l.x,h.x,u.x),Zv(a,c.y,l.y,h.y,u.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new it().fromArray(n))}return this}}var Jv=Object.freeze({__proto__:null,ArcCurve:$3,CatmullRomCurve3:Y3,CubicBezierCurve:vx,CubicBezierCurve3:eA,EllipseCurve:Og,LineCurve:Mx,LineCurve3:iA,QuadraticBezierCurve:yx,QuadraticBezierCurve3:nA,SplineCurve:xx});class sA extends Lr{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);if(!t.equals(e)){const i=t.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Jv[i](e,t))}return this}getPoint(t,e){const i=t*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const r=n[s]-i,a=this.curves[s],c=a.getLength(),l=c===0?0:1-r/c;return a.getPointAt(l,e)}s++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,n=this.curves.length;i<n;i++)e+=this.curves[i].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const r=s[n],a=r.isEllipseCurve?t*2:r.isLineCurve||r.isLineCurve3?1:r.isSplineCurve?t*r.points.length:t,c=r.getPoints(a);for(let l=0;l<c.length;l++){const h=c[l];i&&i.equals(h)||(e.push(h),i=h)}}return this.autoClose&&e.length>1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,i=this.curves.length;e<i;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(new Jv[n.type]().fromJSON(n))}return this}}class jv extends sA{constructor(t){super(),this.type="Path",this.currentPoint=new it,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,i=t.length;e<i;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const i=new Mx(this.currentPoint.clone(),new it(t,e));return this.curves.push(i),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,i,n){const s=new yx(this.currentPoint.clone(),new it(t,e),new it(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(t,e,i,n,s,r){const a=new vx(this.currentPoint.clone(),new it(t,e),new it(i,n),new it(s,r));return this.curves.push(a),this.currentPoint.set(s,r),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),i=new xx(e);return this.curves.push(i),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,i,n,s,r){const a=this.currentPoint.x,c=this.currentPoint.y;return this.absarc(t+a,e+c,i,n,s,r),this}absarc(t,e,i,n,s,r){return this.absellipse(t,e,i,i,n,s,r),this}ellipse(t,e,i,n,s,r,a,c){const l=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(t+l,e+h,i,n,s,r,a,c),this}absellipse(t,e,i,n,s,r,a,c){const l=new Og(t,e,i,n,s,r,a,c);if(this.curves.length>0){const u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);const h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class wm extends jv{constructor(t){super(t),this.uuid=_s(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,n=this.holes.length;i<n;i++)e[i]=this.holes[i].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,i=this.holes.length;e<i;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(new jv().fromJSON(n))}return this}}function rA(o,t,e=2){const i=t&&t.length,n=i?t[0]*e:o.length;let s=bx(o,0,n,e,!0);const r=[];if(!s||s.next===s.prev)return r;let a,c,l;if(i&&(s=hA(o,t,s,e)),o.length>80*e){a=o[0],c=o[1];let h=a,u=c;for(let d=e;d<n;d+=e){const f=o[d],p=o[d+1];f<a&&(a=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-a,u-c),l=l!==0?32767/l:0}return Dh(s,r,e,a,c,l,0),r}function bx(o,t,e,i,n){let s;if(n===bA(o,t,e,i)>0)for(let r=t;r<e;r+=i)s=Qv(r/i|0,o[r],o[r+1],s);else for(let r=e-i;r>=t;r-=i)s=Qv(r/i|0,o[r],o[r+1],s);return s&&fl(s,s.next)&&(Oh(s),s=s.next),s}function Vo(o,t){if(!o)return o;t||(t=o);let e=o,i;do if(i=!1,!e.steiner&&(fl(e,e.next)||Ai(e.prev,e,e.next)===0)){if(Oh(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function Dh(o,t,e,i,n,s,r){if(!o)return;!r&&s&&mA(o,i,n,s);let a=o;for(;o.prev!==o.next;){const c=o.prev,l=o.next;if(s?oA(o,i,n,s):aA(o)){t.push(c.i,o.i,l.i),Oh(o),o=l.next,a=l.next;continue}if(o=l,o===a){r?r===1?(o=cA(Vo(o),t),Dh(o,t,e,i,n,s,2)):r===2&&lA(o,t,e,i,n,s):Dh(Vo(o),t,e,i,n,s,1);break}}}function aA(o){const t=o.prev,e=o,i=o.next;if(Ai(t,e,i)>=0)return!1;const n=t.x,s=e.x,r=i.x,a=t.y,c=e.y,l=i.y,h=Math.min(n,s,r),u=Math.min(a,c,l),d=Math.max(n,s,r),f=Math.max(a,c,l);let p=i.next;for(;p!==t;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&Zl(n,a,s,c,r,l,p.x,p.y)&&Ai(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function oA(o,t,e,i){const n=o.prev,s=o,r=o.next;if(Ai(n,s,r)>=0)return!1;const a=n.x,c=s.x,l=r.x,h=n.y,u=s.y,d=r.y,f=Math.min(a,c,l),p=Math.min(h,u,d),g=Math.max(a,c,l),m=Math.max(h,u,d),v=Sm(f,p,t,e,i),y=Sm(g,m,t,e,i);let x=o.prevZ,M=o.nextZ;for(;x&&x.z>=v&&M&&M.z<=y;){if(x.x>=f&&x.x<=g&&x.y>=p&&x.y<=m&&x!==n&&x!==r&&Zl(a,h,c,u,l,d,x.x,x.y)&&Ai(x.prev,x,x.next)>=0||(x=x.prevZ,M.x>=f&&M.x<=g&&M.y>=p&&M.y<=m&&M!==n&&M!==r&&Zl(a,h,c,u,l,d,M.x,M.y)&&Ai(M.prev,M,M.next)>=0))return!1;M=M.nextZ}for(;x&&x.z>=v;){if(x.x>=f&&x.x<=g&&x.y>=p&&x.y<=m&&x!==n&&x!==r&&Zl(a,h,c,u,l,d,x.x,x.y)&&Ai(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;M&&M.z<=y;){if(M.x>=f&&M.x<=g&&M.y>=p&&M.y<=m&&M!==n&&M!==r&&Zl(a,h,c,u,l,d,M.x,M.y)&&Ai(M.prev,M,M.next)>=0)return!1;M=M.nextZ}return!0}function cA(o,t){let e=o;do{const i=e.prev,n=e.next.next;!fl(i,n)&&Sx(i,e,e.next,n)&&Ch(i,n)&&Ch(n,i)&&(t.push(i.i,e.i,n.i),Oh(e),Oh(e.next),e=o=n),e=e.next}while(e!==o);return Vo(e)}function lA(o,t,e,i,n,s){let r=o;do{let a=r.next.next;for(;a!==r.prev;){if(r.i!==a.i&&MA(r,a)){let c=Ex(r,a);r=Vo(r,r.next),c=Vo(c,c.next),Dh(r,t,e,i,n,s,0),Dh(c,t,e,i,n,s,0);return}a=a.next}r=r.next}while(r!==o)}function hA(o,t,e,i){const n=[];for(let s=0,r=t.length;s<r;s++){const a=t[s]*i,c=s<r-1?t[s+1]*i:o.length,l=bx(o,a,c,i,!1);l===l.next&&(l.steiner=!0),n.push(vA(l))}n.sort(uA);for(let s=0;s<n.length;s++)e=dA(n[s],e);return e}function uA(o,t){let e=o.x-t.x;if(e===0&&(e=o.y-t.y,e===0)){const i=(o.next.y-o.y)/(o.next.x-o.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=i-n}return e}function dA(o,t){const e=fA(o,t);if(!e)return t;const i=Ex(e,o);return Vo(i,i.next),Vo(e,e.next)}function fA(o,t){let e=t;const i=o.x,n=o.y;let s=-1/0,r;if(fl(o,e))return e;do{if(fl(o,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const u=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>s&&(s=u,r=e.x<e.next.x?e:e.next,u===i))return r}e=e.next}while(e!==t);if(!r)return null;const a=r,c=r.x,l=r.y;let h=1/0;e=r;do{if(i>=e.x&&e.x>=c&&i!==e.x&&wx(n<l?i:s,n,c,l,n<l?s:i,n,e.x,e.y)){const u=Math.abs(n-e.y)/(i-e.x);Ch(e,o)&&(u<h||u===h&&(e.x>r.x||e.x===r.x&&pA(r,e)))&&(r=e,h=u)}e=e.next}while(e!==a);return r}function pA(o,t){return Ai(o.prev,o,t.prev)<0&&Ai(t.next,o,o.next)<0}function mA(o,t,e,i){let n=o;do n.z===0&&(n.z=Sm(n.x,n.y,t,e,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==o);n.prevZ.nextZ=null,n.prevZ=null,gA(n)}function gA(o){let t,e=1;do{let i=o,n;o=null;let s=null;for(t=0;i;){t++;let r=i,a=0;for(let l=0;l<e&&(a++,r=r.nextZ,!!r);l++);let c=e;for(;a>0||c>0&&r;)a!==0&&(c===0||!r||i.z<=r.z)?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,c--),s?s.nextZ=n:o=n,n.prevZ=s,s=n;i=r}s.nextZ=null,e*=2}while(t>1);return o}function Sm(o,t,e,i,n){return o=(o-e)*n|0,t=(t-i)*n|0,o=(o|o<<8)&16711935,o=(o|o<<4)&252645135,o=(o|o<<2)&858993459,o=(o|o<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,o|t<<1}function vA(o){let t=o,e=o;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==o);return e}function wx(o,t,e,i,n,s,r,a){return(n-r)*(t-a)>=(o-r)*(s-a)&&(o-r)*(i-a)>=(e-r)*(t-a)&&(e-r)*(s-a)>=(n-r)*(i-a)}function Zl(o,t,e,i,n,s,r,a){return!(o===r&&t===a)&&wx(o,t,e,i,n,s,r,a)}function MA(o,t){return o.next.i!==t.i&&o.prev.i!==t.i&&!yA(o,t)&&(Ch(o,t)&&Ch(t,o)&&xA(o,t)&&(Ai(o.prev,o,t.prev)||Ai(o,t.prev,t))||fl(o,t)&&Ai(o.prev,o,o.next)>0&&Ai(t.prev,t,t.next)>0)}function Ai(o,t,e){return(t.y-o.y)*(e.x-t.x)-(t.x-o.x)*(e.y-t.y)}function fl(o,t){return o.x===t.x&&o.y===t.y}function Sx(o,t,e,i){const n=_u(Ai(o,t,e)),s=_u(Ai(o,t,i)),r=_u(Ai(e,i,o)),a=_u(Ai(e,i,t));return!!(n!==s&&r!==a||n===0&&Au(o,e,t)||s===0&&Au(o,i,t)||r===0&&Au(e,o,i)||a===0&&Au(e,t,i))}function Au(o,t,e){return t.x<=Math.max(o.x,e.x)&&t.x>=Math.min(o.x,e.x)&&t.y<=Math.max(o.y,e.y)&&t.y>=Math.min(o.y,e.y)}function _u(o){return o>0?1:o<0?-1:0}function yA(o,t){let e=o;do{if(e.i!==o.i&&e.next.i!==o.i&&e.i!==t.i&&e.next.i!==t.i&&Sx(e,e.next,o,t))return!0;e=e.next}while(e!==o);return!1}function Ch(o,t){return Ai(o.prev,o,o.next)<0?Ai(o,t,o.next)>=0&&Ai(o,o.prev,t)>=0:Ai(o,t,o.prev)<0||Ai(o,o.next,t)<0}function xA(o,t){let e=o,i=!1;const n=(o.x+t.x)/2,s=(o.y+t.y)/2;do e.y>s!=e.next.y>s&&e.next.y!==e.y&&n<(e.next.x-e.x)*(s-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==o);return i}function Ex(o,t){const e=Em(o.i,o.x,o.y),i=Em(t.i,t.x,t.y),n=o.next,s=t.prev;return o.next=t,t.prev=o,e.next=n,n.prev=e,i.next=e,e.prev=i,s.next=i,i.prev=s,i}function Qv(o,t,e,i){const n=Em(o,t,e);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function Oh(o){o.next.prev=o.prev,o.prev.next=o.next,o.prevZ&&(o.prevZ.nextZ=o.nextZ),o.nextZ&&(o.nextZ.prevZ=o.prevZ)}function Em(o,t,e){return{i:o,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function bA(o,t,e,i){let n=0;for(let s=t,r=e-i;s<e;s+=i)n+=(o[r]-o[s])*(o[s+1]+o[r+1]),r=s;return n}class wA{static triangulate(t,e,i=2){return rA(t,e,i)}}class ch{static area(t){const e=t.length;let i=0;for(let n=e-1,s=0;s<e;n=s++)i+=t[n].x*t[s].y-t[s].x*t[n].y;return i*.5}static isClockWise(t){return ch.area(t)<0}static triangulateShape(t,e){const i=[],n=[],s=[];tM(t),eM(i,t);let r=t.length;e.forEach(tM);for(let c=0;c<e.length;c++)n.push(r),r+=e[c].length,eM(i,e[c]);const a=wA.triangulate(i,n);for(let c=0;c<a.length;c+=3)s.push(a.slice(c,c+3));return s}}function tM(o){const t=o.length;t>2&&o[t-1].equals(o[0])&&o.pop()}function eM(o,t){for(let e=0;e<t.length;e++)o.push(t[e].x),o.push(t[e].y)}class Of extends ne{constructor(t=[new it(0,-.5),new it(.5,0),new it(0,.5)],e=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:i,phiLength:n},e=Math.floor(e),n=oe(n,0,Math.PI*2);const s=[],r=[],a=[],c=[],l=[],h=1/e,u=new R,d=new it,f=new R,p=new R,g=new R;let m=0,v=0;for(let y=0;y<=t.length-1;y++)switch(y){case 0:m=t[y+1].x-t[y].x,v=t[y+1].y-t[y].y,f.x=v*1,f.y=-m,f.z=v*0,g.copy(f),f.normalize(),c.push(f.x,f.y,f.z);break;case t.length-1:c.push(g.x,g.y,g.z);break;default:m=t[y+1].x-t[y].x,v=t[y+1].y-t[y].y,f.x=v*1,f.y=-m,f.z=v*0,p.copy(f),f.x+=g.x,f.y+=g.y,f.z+=g.z,f.normalize(),c.push(f.x,f.y,f.z),g.copy(p)}for(let y=0;y<=e;y++){const x=i+y*h*n,M=Math.sin(x),b=Math.cos(x);for(let S=0;S<=t.length-1;S++){u.x=t[S].x*M,u.y=t[S].y,u.z=t[S].x*b,r.push(u.x,u.y,u.z),d.x=y/e,d.y=S/(t.length-1),a.push(d.x,d.y);const E=c[3*S+0]*M,w=c[3*S+1],_=c[3*S+0]*b;l.push(E,w,_)}}for(let y=0;y<e;y++)for(let x=0;x<t.length-1;x++){const M=x+y*t.length,b=M,S=M+t.length,E=M+t.length+1,w=M+1;s.push(b,S,w),s.push(E,w,S)}this.setIndex(s),this.setAttribute("position",new le(r,3)),this.setAttribute("uv",new le(a,2)),this.setAttribute("normal",new le(l,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Of(t.points,t.segments,t.phiStart,t.phiLength)}}class Gn extends ne{constructor(t=1,e=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};const s=t/2,r=e/2,a=Math.floor(i),c=Math.floor(n),l=a+1,h=c+1,u=t/a,d=e/c,f=[],p=[],g=[],m=[];for(let v=0;v<h;v++){const y=v*d-r;for(let x=0;x<l;x++){const M=x*u-s;p.push(M,-y,0),g.push(0,0,1),m.push(x/a),m.push(1-v/c)}}for(let v=0;v<c;v++)for(let y=0;y<a;y++){const x=y+l*v,M=y+l*(v+1),b=y+1+l*(v+1),S=y+1+l*v;f.push(x,M,S),f.push(M,b,S)}this.setIndex(f),this.setAttribute("position",new le(p,3)),this.setAttribute("normal",new le(g,3)),this.setAttribute("uv",new le(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Gn(t.width,t.height,t.widthSegments,t.heightSegments)}}class Lg extends ne{constructor(t=new wm([new it(0,.5),new it(-.5,-.5),new it(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const i=[],n=[],s=[],r=[];let a=0,c=0;if(Array.isArray(t)===!1)l(t);else for(let h=0;h<t.length;h++)l(t[h]),this.addGroup(a,c,h),a+=c,c=0;this.setIndex(i),this.setAttribute("position",new le(n,3)),this.setAttribute("normal",new le(s,3)),this.setAttribute("uv",new le(r,2));function l(h){const u=n.length/3,d=h.extractPoints(e);let f=d.shape;const p=d.holes;ch.isClockWise(f)===!1&&(f=f.reverse());for(let m=0,v=p.length;m<v;m++){const y=p[m];ch.isClockWise(y)===!0&&(p[m]=y.reverse())}const g=ch.triangulateShape(f,p);for(let m=0,v=p.length;m<v;m++){const y=p[m];f=f.concat(y)}for(let m=0,v=f.length;m<v;m++){const y=f[m];n.push(y.x,y.y,0),s.push(0,0,1),r.push(y.x,y.y)}for(let m=0,v=g.length;m<v;m++){const y=g[m],x=y[0]+u,M=y[1]+u,b=y[2]+u;i.push(x,M,b),c+=3}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON(),e=this.parameters.shapes;return SA(e,t)}static fromJSON(t,e){const i=[];for(let n=0,s=t.shapes.length;n<s;n++){const r=e[t.shapes[n]];i.push(r)}return new Lg(i,t.curveSegments)}}function SA(o,t){if(t.shapes=[],Array.isArray(o))for(let e=0,i=o.length;e<i;e++){const n=o[e];t.shapes.push(n.uuid)}else t.shapes.push(o.uuid);return t}class Gi extends ne{constructor(t=1,e=32,i=16,n=0,s=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:s,thetaStart:r,thetaLength:a},e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));const c=Math.min(r+a,Math.PI);let l=0;const h=[],u=new R,d=new R,f=[],p=[],g=[],m=[];for(let v=0;v<=i;v++){const y=[],x=v/i,M=r+x*a,b=t*Math.cos(M),S=Math.sqrt(t*t-b*b);let E=0;v===0&&r===0?E=.5/e:v===i&&c===Math.PI&&(E=-.5/e);for(let w=0;w<=e;w++){const _=w/e,D=n+_*s;u.x=-S*Math.cos(D),u.y=b,u.z=S*Math.sin(D),p.push(u.x,u.y,u.z),d.copy(u).normalize(),g.push(d.x,d.y,d.z),m.push(_+E,1-x),y.push(l++)}h.push(y)}for(let v=0;v<i;v++)for(let y=0;y<e;y++){const x=h[v][y+1],M=h[v][y],b=h[v+1][y],S=h[v+1][y+1];(v!==0||r>0)&&f.push(x,M,S),(v!==i-1||c<Math.PI)&&f.push(M,b,S)}this.setIndex(f),this.setAttribute("position",new le(p,3)),this.setAttribute("normal",new le(g,3)),this.setAttribute("uv",new le(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Gi(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class Ng extends ne{constructor(t=1,e=.4,i=12,n=48,s=Math.PI*2,r=0,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:s,thetaStart:r,thetaLength:a},i=Math.floor(i),n=Math.floor(n);const c=[],l=[],h=[],u=[],d=new R,f=new R,p=new R;for(let g=0;g<=i;g++){const m=r+g/i*a;for(let v=0;v<=n;v++){const y=v/n*s;f.x=(t+e*Math.cos(m))*Math.cos(y),f.y=(t+e*Math.cos(m))*Math.sin(y),f.z=e*Math.sin(m),l.push(f.x,f.y,f.z),d.x=t*Math.cos(y),d.y=t*Math.sin(y),p.subVectors(f,d).normalize(),h.push(p.x,p.y,p.z),u.push(v/n),u.push(g/i)}}for(let g=1;g<=i;g++)for(let m=1;m<=n;m++){const v=(n+1)*g+m-1,y=(n+1)*(g-1)+m-1,x=(n+1)*(g-1)+m,M=(n+1)*g+m;c.push(v,y,M),c.push(y,x,M)}this.setIndex(c),this.setAttribute("position",new le(l,3)),this.setAttribute("normal",new le(h,3)),this.setAttribute("uv",new le(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Ng(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class KO extends ne{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},t!==null){const e=[],i=new Set,n=new R,s=new R;if(t.index!==null){const r=t.attributes.position,a=t.index;let c=t.groups;c.length===0&&(c=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,h=c.length;l<h;++l){const u=c[l],d=u.start,f=u.count;for(let p=d,g=d+f;p<g;p+=3)for(let m=0;m<3;m++){const v=a.getX(p+m),y=a.getX(p+(m+1)%3);n.fromBufferAttribute(r,v),s.fromBufferAttribute(r,y),iM(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}}else{const r=t.attributes.position;for(let a=0,c=r.count/3;a<c;a++)for(let l=0;l<3;l++){const h=3*a+l,u=3*a+(l+1)%3;n.fromBufferAttribute(r,h),s.fromBufferAttribute(r,u),iM(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}this.setAttribute("position",new le(e,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}function iM(o,t,e){const i=`${o.x},${o.y},${o.z}-${t.x},${t.y},${t.z}`,n=`${t.x},${t.y},${t.z}-${o.x},${o.y},${o.z}`;return e.has(i)===!0||e.has(n)===!0?!1:(e.add(i),e.add(n),!0)}function pl(o){const t={};for(const e in o){t[e]={};for(const i in o[e]){const n=o[e][i];if(nM(n))n.isRenderTargetTexture?(Nt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[e][i]=null):t[e][i]=n.clone();else if(Array.isArray(n))if(nM(n[0])){const s=[];for(let r=0,a=n.length;r<a;r++)s[r]=n[r].clone();t[e][i]=s}else t[e][i]=n.slice();else t[e][i]=n}}return t}function Pn(o){const t={};for(let e=0;e<o.length;e++){const i=pl(o[e]);for(const n in i)t[n]=i[n]}return t}function nM(o){return o&&(o.isColor||o.isMatrix3||o.isMatrix4||o.isVector2||o.isVector3||o.isVector4||o.isTexture||o.isQuaternion)}function EA(o){const t=[];for(let e=0;e<o.length;e++)t.push(o[e].clone());return t}function Ax(o){const t=o.getRenderTarget();return t===null?o.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:De.workingColorSpace}const AA={clone:pl,merge:Pn};var _A=`void main() {
|
|
2408
|
+
*/const pg="185",vE=0,hv=1,ME=2,nh=1,yE=2,Kl=3,za=0,xi=1,Bn=2,ms=0,Ua=1,nn=2,uv=3,dv=4,Fo=5,$r=100,xE=101,bE=102,wE=103,SE=104,xr=200,zo=201,EE=202,AE=203,Wd=204,Ah=205,_E=206,TE=207,RE=208,IE=209,DE=210,CE=211,OE=212,PE=213,LE=214,Lp=0,Np=1,kp=2,ll=3,Up=4,Fp=5,zp=6,Bp=7,mg=0,NE=1,kE=2,Ir=0,Xy=1,$y=2,Yy=3,qy=4,Ky=5,Zy=6,Jy=7,fv="attached",UE="detached",jy=300,Bo=301,hl=302,e0=303,i0=304,Cf=306,Ho=1e3,Oi=1001,Hp=1002,ei=1003,FE=1004,jh=1005,ye=1006,n0=1007,Xs=1008,Hn=1009,Qy=1010,tx=1011,_h=1012,gg=1013,Ts=1014,Dn=1015,Be=1016,vg=1017,Mg=1018,Th=1020,ex=35902,ix=35899,nx=1021,sx=1022,Ki=1023,Jr=1026,wo=1027,ul=1028,yg=1029,Go=1030,xg=1031,bg=1033,cd=33776,ld=33777,hd=33778,ud=33779,Gp=35840,Vp=35841,Wp=35842,Xp=35843,$p=36196,Yp=37492,qp=37496,Kp=37488,Zp=37489,Xd=37490,Jp=37491,jp=37808,Qp=37809,tm=37810,em=37811,im=37812,nm=37813,sm=37814,rm=37815,am=37816,om=37817,cm=37818,lm=37819,hm=37820,um=37821,dm=36492,fm=36494,pm=36495,mm=36283,gm=36284,$d=36285,vm=36286,rx=2200,zE=2201,BE=2202,Yd=2300,Mm=2301,s0=2302,pv=2303,Nc=2400,kc=2401,qd=2402,wg=2500,HE=2501,GO=0,VO=1,WO=2,GE=3200,Kd=0,VE=1,Ra="",vn="srgb",Zd="srgb-linear",Jd="linear",$e="srgb",ec=7680,mv=519,WE=512,XE=513,$E=514,Sg=515,YE=516,qE=517,Eg=518,KE=519,ym=35044,jd="300 es",Tr=2e3,Rh=2001;function ZE(o){for(let t=o.length-1;t>=0;--t)if(o[t]>=65535)return!0;return!1}function JE(o){return ArrayBuffer.isView(o)&&!(o instanceof DataView)}function Ih(o){return document.createElementNS("http://www.w3.org/1999/xhtml",o)}function jE(){const o=Ih("canvas");return o.style.display="block",o}const gv={};function Qd(...o){const t="THREE."+o.shift();console.log(t,...o)}function ax(o){const t=o[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=o[1];e&&e.isStackTrace?o[0]+=" "+e.getLocation():o[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return o}function Nt(...o){o=ax(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...o)}}function te(...o){o=ax(o);const t="THREE."+o.shift();{const e=o[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...o)}}function Yc(...o){const t=o.join(" ");t in gv||(gv[t]=!0,Nt(...o))}function QE(o,t,e){return new Promise(function(i,n){function s(){switch(o.clientWaitSync(t,o.SYNC_FLUSH_COMMANDS_BIT,0)){case o.WAIT_FAILED:n();break;case o.TIMEOUT_EXPIRED:setTimeout(s,e);break;default:i()}}setTimeout(s,e)})}const t3={[Lp]:Np,[kp]:zp,[Up]:Bp,[ll]:Fp,[Np]:Lp,[zp]:kp,[Bp]:Up,[Fp]:ll};class Ha{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i===void 0?!1:i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const i=this._listeners;if(i===void 0)return;const n=i[t];if(n!==void 0){const s=n.indexOf(e);s!==-1&&n.splice(s,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const i=e[t.type];if(i!==void 0){t.target=this;const n=i.slice(0);for(let s=0,r=n.length;s<r;s++)n[s].call(this,t);t.target=null}}}const xn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let vv=1234567;const sh=Math.PI/180,dl=180/Math.PI;function _s(){const o=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(xn[o&255]+xn[o>>8&255]+xn[o>>16&255]+xn[o>>24&255]+"-"+xn[t&255]+xn[t>>8&255]+"-"+xn[t>>16&15|64]+xn[t>>24&255]+"-"+xn[e&63|128]+xn[e>>8&255]+"-"+xn[e>>16&255]+xn[e>>24&255]+xn[i&255]+xn[i>>8&255]+xn[i>>16&255]+xn[i>>24&255]).toLowerCase()}function oe(o,t,e){return Math.max(t,Math.min(e,o))}function Ag(o,t){return(o%t+t)%t}function e3(o,t,e,i,n){return i+(o-t)*(n-i)/(e-t)}function i3(o,t,e){return o!==t?(e-o)/(t-o):0}function rh(o,t,e){return(1-e)*o+e*t}function n3(o,t,e,i){return rh(o,t,1-Math.exp(-e*i))}function s3(o,t=1){return t-Math.abs(Ag(o,t*2)-t)}function r3(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*(3-2*o))}function a3(o,t,e){return o<=t?0:o>=e?1:(o=(o-t)/(e-t),o*o*o*(o*(o*6-15)+10))}function o3(o,t){return o+Math.floor(Math.random()*(t-o+1))}function c3(o,t){return o+Math.random()*(t-o)}function l3(o){return o*(.5-Math.random())}function h3(o){o!==void 0&&(vv=o);let t=vv+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function u3(o){return o*sh}function d3(o){return o*dl}function f3(o){return(o&o-1)===0&&o!==0}function p3(o){return Math.pow(2,Math.ceil(Math.log(o)/Math.LN2))}function m3(o){return Math.pow(2,Math.floor(Math.log(o)/Math.LN2))}function g3(o,t,e,i,n){const s=Math.cos,r=Math.sin,a=s(e/2),c=r(e/2),l=s((t+i)/2),h=r((t+i)/2),u=s((t-i)/2),d=r((t-i)/2),f=s((i-t)/2),p=r((i-t)/2);switch(n){case"XYX":o.set(a*h,c*u,c*d,a*l);break;case"YZY":o.set(c*d,a*h,c*u,a*l);break;case"ZXZ":o.set(c*u,c*d,a*h,a*l);break;case"XZX":o.set(a*h,c*p,c*f,a*l);break;case"YXY":o.set(c*f,a*h,c*p,a*l);break;case"ZYZ":o.set(c*p,c*f,a*h,a*l);break;default:Nt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Vs(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return o/4294967295;case Uint16Array:return o/65535;case Uint8Array:return o/255;case Int32Array:return Math.max(o/2147483647,-1);case Int16Array:return Math.max(o/32767,-1);case Int8Array:return Math.max(o/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function qe(o,t){switch(t.constructor){case Float32Array:return o;case Uint32Array:return Math.round(o*4294967295);case Uint16Array:return Math.round(o*65535);case Uint8Array:return Math.round(o*255);case Int32Array:return Math.round(o*2147483647);case Int16Array:return Math.round(o*32767);case Int8Array:return Math.round(o*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const XO={DEG2RAD:sh,RAD2DEG:dl,generateUUID:_s,clamp:oe,euclideanModulo:Ag,mapLinear:e3,inverseLerp:i3,lerp:rh,damp:n3,pingpong:s3,smoothstep:r3,smootherstep:a3,randInt:o3,randFloat:c3,randFloatSpread:l3,seededRandom:h3,degToRad:u3,radToDeg:d3,isPowerOfTwo:f3,ceilPowerOfTwo:p3,floorPowerOfTwo:m3,setQuaternionFromProperEuler:g3,normalize:qe,denormalize:Vs};class it{static{it.prototype.isVector2=!0}constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6],this.y=n[1]*e+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(oe(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),n=Math.sin(e),s=this.x-t.x,r=this.y-t.y;return this.x=s*i-r*n+t.x,this.y=s*n+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ts{constructor(t=0,e=0,i=0,n=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=n}static slerpFlat(t,e,i,n,s,r,a){let c=i[n+0],l=i[n+1],h=i[n+2],u=i[n+3],d=s[r+0],f=s[r+1],p=s[r+2],g=s[r+3];if(u!==g||c!==d||l!==f||h!==p){let m=c*d+l*f+h*p+u*g;m<0&&(d=-d,f=-f,p=-p,g=-g,m=-m);let v=1-a;if(m<.9995){const y=Math.acos(m),x=Math.sin(y);v=Math.sin(v*y)/x,a=Math.sin(a*y)/x,c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+g*a}else{c=c*v+d*a,l=l*v+f*a,h=h*v+p*a,u=u*v+g*a;const y=1/Math.sqrt(c*c+l*l+h*h+u*u);c*=y,l*=y,h*=y,u*=y}}t[e]=c,t[e+1]=l,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,i,n,s,r){const a=i[n],c=i[n+1],l=i[n+2],h=i[n+3],u=s[r],d=s[r+1],f=s[r+2],p=s[r+3];return t[e]=a*p+h*u+c*f-l*d,t[e+1]=c*p+h*d+l*u-a*f,t[e+2]=l*p+h*f+a*d-c*u,t[e+3]=h*p-a*u-c*d-l*f,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,n){return this._x=t,this._y=e,this._z=i,this._w=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,n=t._y,s=t._z,r=t._order,a=Math.cos,c=Math.sin,l=a(i/2),h=a(n/2),u=a(s/2),d=c(i/2),f=c(n/2),p=c(s/2);switch(r){case"XYZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"YXZ":this._x=d*h*u+l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"ZXY":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u-d*f*p;break;case"ZYX":this._x=d*h*u-l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u+d*f*p;break;case"YZX":this._x=d*h*u+l*f*p,this._y=l*f*u+d*h*p,this._z=l*h*p-d*f*u,this._w=l*h*u-d*f*p;break;case"XZY":this._x=d*h*u-l*f*p,this._y=l*f*u-d*h*p,this._z=l*h*p+d*f*u,this._w=l*h*u+d*f*p;break;default:Nt("Quaternion: .setFromEuler() encountered an unknown order: "+r)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,n=Math.sin(i);return this._x=t.x*n,this._y=t.y*n,this._z=t.z*n,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],n=e[4],s=e[8],r=e[1],a=e[5],c=e[9],l=e[2],h=e[6],u=e[10],d=i+a+u;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(h-c)*f,this._y=(s-l)*f,this._z=(r-n)*f}else if(i>a&&i>u){const f=2*Math.sqrt(1+i-a-u);this._w=(h-c)/f,this._x=.25*f,this._y=(n+r)/f,this._z=(s+l)/f}else if(a>u){const f=2*Math.sqrt(1+a-i-u);this._w=(s-l)/f,this._x=(n+r)/f,this._y=.25*f,this._z=(c+h)/f}else{const f=2*Math.sqrt(1+u-i-a);this._w=(r-n)/f,this._x=(s+l)/f,this._y=(c+h)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(oe(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const n=Math.min(1,e/i);return this.slerp(t,n),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,n=t._y,s=t._z,r=t._w,a=e._x,c=e._y,l=e._z,h=e._w;return this._x=i*h+r*a+n*l-s*c,this._y=n*h+r*c+s*a-i*l,this._z=s*h+r*l+i*c-n*a,this._w=r*h-i*a-n*c-s*l,this._onChangeCallback(),this}slerp(t,e){let i=t._x,n=t._y,s=t._z,r=t._w,a=this.dot(t);a<0&&(i=-i,n=-n,s=-s,r=-r,a=-a);let c=1-e;if(a<.9995){const l=Math.acos(a),h=Math.sin(l);c=Math.sin(c*l)/h,e=Math.sin(e*l)/h,this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this._onChangeCallback()}else this._x=this._x*c+i*e,this._y=this._y*c+n*e,this._z=this._z*c+s*e,this._w=this._w*c+r*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),n=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(n*Math.sin(t),n*Math.cos(t),s*Math.sin(e),s*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class R{static{R.prototype.isVector3=!0}constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Mv.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Mv.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6]*n,this.y=s[1]*e+s[4]*i+s[7]*n,this.z=s[2]*e+s[5]*i+s[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=t.elements,r=1/(s[3]*e+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*e+s[4]*i+s[8]*n+s[12])*r,this.y=(s[1]*e+s[5]*i+s[9]*n+s[13])*r,this.z=(s[2]*e+s[6]*i+s[10]*n+s[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,n=this.z,s=t.x,r=t.y,a=t.z,c=t.w,l=2*(r*n-a*i),h=2*(a*e-s*n),u=2*(s*i-r*e);return this.x=e+c*l+r*u-a*h,this.y=i+c*h+a*l-s*u,this.z=n+c*u+s*h-r*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*e+s[4]*i+s[8]*n,this.y=s[1]*e+s[5]*i+s[9]*n,this.z=s[2]*e+s[6]*i+s[10]*n,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this.z=oe(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this.z=oe(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,n=t.y,s=t.z,r=e.x,a=e.y,c=e.z;return this.x=n*c-s*a,this.y=s*r-i*c,this.z=i*a-n*r,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return r0.copy(this).projectOnVector(t),this.sub(r0)}reflect(t){return this.sub(r0.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(oe(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return e*e+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const n=Math.sin(e)*t;return this.x=n*Math.sin(i),this.y=Math.cos(e)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=n,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const r0=new R,Mv=new ts;class ie{static{ie.prototype.isMatrix3=!0}constructor(t,e,i,n,s,r,a,c,l){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l)}set(t,e,i,n,s,r,a,c,l){const h=this.elements;return h[0]=t,h[1]=n,h[2]=a,h[3]=e,h[4]=s,h[5]=c,h[6]=i,h[7]=r,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[3],c=i[6],l=i[1],h=i[4],u=i[7],d=i[2],f=i[5],p=i[8],g=n[0],m=n[3],v=n[6],y=n[1],x=n[4],M=n[7],b=n[2],S=n[5],E=n[8];return s[0]=r*g+a*y+c*b,s[3]=r*m+a*x+c*S,s[6]=r*v+a*M+c*E,s[1]=l*g+h*y+u*b,s[4]=l*m+h*x+u*S,s[7]=l*v+h*M+u*E,s[2]=d*g+f*y+p*b,s[5]=d*m+f*x+p*S,s[8]=d*v+f*M+p*E,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8];return e*r*h-e*a*l-i*s*h+i*a*c+n*s*l-n*r*c}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=h*r-a*l,d=a*c-h*s,f=l*s-r*c,p=e*u+i*d+n*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return t[0]=u*g,t[1]=(n*l-h*i)*g,t[2]=(a*i-n*r)*g,t[3]=d*g,t[4]=(h*e-n*c)*g,t[5]=(n*s-a*e)*g,t[6]=f*g,t[7]=(i*c-l*e)*g,t[8]=(r*e-i*s)*g,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,n,s,r,a){const c=Math.cos(s),l=Math.sin(s);return this.set(i*c,i*l,-i*(c*r+l*a)+r+t,-n*l,n*c,-n*(-l*r+c*a)+a+e,0,0,1),this}scale(t,e){return Yc("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(a0.makeScale(t,e)),this}rotate(t){return Yc("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(a0.makeRotation(-t)),this}translate(t,e){return Yc("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(a0.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<9;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}}const a0=new ie,yv=new ie().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),xv=new ie().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function v3(){const o={enabled:!0,workingColorSpace:Zd,spaces:{},convert:function(n,s,r){return this.enabled===!1||s===r||!s||!r||(this.spaces[s].transfer===$e&&(n.r=Kr(n.r),n.g=Kr(n.g),n.b=Kr(n.b)),this.spaces[s].primaries!==this.spaces[r].primaries&&(n.applyMatrix3(this.spaces[s].toXYZ),n.applyMatrix3(this.spaces[r].fromXYZ)),this.spaces[r].transfer===$e&&(n.r=qc(n.r),n.g=qc(n.g),n.b=qc(n.b))),n},workingToColorSpace:function(n,s){return this.convert(n,this.workingColorSpace,s)},colorSpaceToWorking:function(n,s){return this.convert(n,s,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===Ra?Jd:this.spaces[n].transfer},getToneMappingMode:function(n){return this.spaces[n].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(n,s=this.workingColorSpace){return n.fromArray(this.spaces[s].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,s,r){return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[r].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(n,s){return Yc("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),o.workingToColorSpace(n,s)},toWorkingColorSpace:function(n,s){return Yc("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),o.colorSpaceToWorking(n,s)}},t=[.64,.33,.3,.6,.15,.06],e=[.2126,.7152,.0722],i=[.3127,.329];return o.define({[Zd]:{primaries:t,whitePoint:i,transfer:Jd,toXYZ:yv,fromXYZ:xv,luminanceCoefficients:e,workingColorSpaceConfig:{unpackColorSpace:vn},outputColorSpaceConfig:{drawingBufferColorSpace:vn}},[vn]:{primaries:t,whitePoint:i,transfer:$e,toXYZ:yv,fromXYZ:xv,luminanceCoefficients:e,outputColorSpaceConfig:{drawingBufferColorSpace:vn}}}),o}const De=v3();function Kr(o){return o<.04045?o*.0773993808:Math.pow(o*.9478672986+.0521327014,2.4)}function qc(o){return o<.0031308?o*12.92:1.055*Math.pow(o,.41666)-.055}let ic;class M3{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{ic===void 0&&(ic=Ih("canvas")),ic.width=t.width,ic.height=t.height;const n=ic.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),i=ic}return i.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=Ih("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const n=i.getImageData(0,0,t.width,t.height),s=n.data;for(let r=0;r<s.length;r++)s[r]=Kr(s[r]/255)*255;return i.putImageData(n,0,0),e}else if(t.data){const e=t.data.slice(0);for(let i=0;i<e.length;i++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[i]=Math.floor(Kr(e[i]/255)*255):e[i]=Kr(e[i]);return{data:e,width:t.width,height:t.height}}else return Nt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let y3=0;class _g{constructor(t=null){this.isSource=!0,Object.defineProperty(this,"id",{value:y3++}),this.uuid=_s(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];const i={uuid:this.uuid,url:""},n=this.data;if(n!==null){let s;if(Array.isArray(n)){s=[];for(let r=0,a=n.length;r<a;r++)n[r].isDataTexture?s.push(o0(n[r].image)):s.push(o0(n[r]))}else s=o0(n);i.url=s}return e||(t.images[this.uuid]=i),i}}function o0(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&o instanceof ImageBitmap?M3.getDataURL(o):o.data?{data:Array.from(o.data),width:o.width,height:o.height,type:o.data.constructor.name}:(Nt("Texture: Unable to serialize Texture."),{})}let x3=0;const c0=new R;class Mn extends Ha{constructor(t=Mn.DEFAULT_IMAGE,e=Mn.DEFAULT_MAPPING,i=Oi,n=Oi,s=ye,r=Xs,a=Ki,c=Hn,l=Mn.DEFAULT_ANISOTROPY,h=Ra){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:x3++}),this.uuid=_s(),this.name="",this.source=new _g(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=r,this.anisotropy=l,this.format=a,this.internalFormat=null,this.type=c,this.offset=new it(0,0),this.repeat=new it(1,1),this.center=new it(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ie,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(c0).x}get height(){return this.source.getSize(c0).y}get depth(){return this.source.getSize(c0).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(i===void 0){Nt(`Texture.setValues(): parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Nt(`Texture.setValues(): property '${e}' does not exist.`);continue}n&&i&&n.isVector2&&i.isVector2||n&&i&&n.isVector3&&i.isVector3||n&&i&&n.isMatrix3&&i.isMatrix3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==jy)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case Ho:t.x=t.x-Math.floor(t.x);break;case Oi:t.x=t.x<0?0:1;break;case Hp:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case Ho:t.y=t.y-Math.floor(t.y);break;case Oi:t.y=t.y<0?0:1;break;case Hp:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}Mn.DEFAULT_IMAGE=null;Mn.DEFAULT_MAPPING=jy;Mn.DEFAULT_ANISOTROPY=1;class _e{static{_e.prototype.isVector4=!0}constructor(t=0,e=0,i=0,n=1){this.x=t,this.y=e,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,n){return this.x=t,this.y=e,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,n=this.z,s=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*n+r[12]*s,this.y=r[1]*e+r[5]*i+r[9]*n+r[13]*s,this.z=r[2]*e+r[6]*i+r[10]*n+r[14]*s,this.w=r[3]*e+r[7]*i+r[11]*n+r[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,n,s;const c=t.elements,l=c[0],h=c[4],u=c[8],d=c[1],f=c[5],p=c[9],g=c[2],m=c[6],v=c[10];if(Math.abs(h-d)<.01&&Math.abs(u-g)<.01&&Math.abs(p-m)<.01){if(Math.abs(h+d)<.1&&Math.abs(u+g)<.1&&Math.abs(p+m)<.1&&Math.abs(l+f+v-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const x=(l+1)/2,M=(f+1)/2,b=(v+1)/2,S=(h+d)/4,E=(u+g)/4,w=(p+m)/4;return x>M&&x>b?x<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(x),n=S/i,s=E/i):M>b?M<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(M),i=S/n,s=w/n):b<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(b),i=E/s,n=w/s),this.set(i,n,s,e),this}let y=Math.sqrt((m-p)*(m-p)+(u-g)*(u-g)+(d-h)*(d-h));return Math.abs(y)<.001&&(y=1),this.x=(m-p)/y,this.y=(u-g)/y,this.z=(d-h)/y,this.w=Math.acos((l+f+v-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=oe(this.x,t.x,e.x),this.y=oe(this.y,t.y,e.y),this.z=oe(this.z,t.z,e.z),this.w=oe(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=oe(this.x,t,e),this.y=oe(this.y,t,e),this.z=oe(this.z,t,e),this.w=oe(this.w,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(oe(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class b3 extends Ha{constructor(t=1,e=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:ye,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=t,this.height=e,this.depth=i.depth,this.scissor=new _e(0,0,t,e),this.scissorTest=!1,this.viewport=new _e(0,0,t,e),this.textures=[];const n={width:t,height:e,depth:i.depth},s=new Mn(n),r=i.count;for(let a=0;a<r;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(t={}){const e={minFilter:ye,generateMipmaps:!1,flipY:!1,internalFormat:null};t.mapping!==void 0&&(e.mapping=t.mapping),t.wrapS!==void 0&&(e.wrapS=t.wrapS),t.wrapT!==void 0&&(e.wrapT=t.wrapT),t.wrapR!==void 0&&(e.wrapR=t.wrapR),t.magFilter!==void 0&&(e.magFilter=t.magFilter),t.minFilter!==void 0&&(e.minFilter=t.minFilter),t.format!==void 0&&(e.format=t.format),t.type!==void 0&&(e.type=t.type),t.anisotropy!==void 0&&(e.anisotropy=t.anisotropy),t.colorSpace!==void 0&&(e.colorSpace=t.colorSpace),t.flipY!==void 0&&(e.flipY=t.flipY),t.generateMipmaps!==void 0&&(e.generateMipmaps=t.generateMipmaps),t.internalFormat!==void 0&&(e.internalFormat=t.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(e)}get texture(){return this.textures[0]}set texture(t){this.textures[0]=t}set depthTexture(t){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),t!==null&&(t.renderTarget=this),this._depthTexture=t}get depthTexture(){return this._depthTexture}setSize(t,e,i=1){if(this.width!==t||this.height!==e||this.depth!==i){this.width=t,this.height=e,this.depth=i;for(let n=0,s=this.textures.length;n<s;n++)this.textures[n].image.width=t,this.textures[n].image.height=e,this.textures[n].image.depth=i,this.textures[n].isData3DTexture!==!0&&(this.textures[n].isArrayTexture=this.textures[n].image.depth>1);this.dispose()}this.viewport.set(0,0,t,e),this.scissor.set(0,0,t,e)}clone(){return new this.constructor().copy(this)}copy(t){this.width=t.width,this.height=t.height,this.depth=t.depth,this.scissor.copy(t.scissor),this.scissorTest=t.scissorTest,this.viewport.copy(t.viewport),this.textures.length=0;for(let e=0,i=t.textures.length;e<i;e++){this.textures[e]=t.textures[e].clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;const n=Object.assign({},t.textures[e].image);this.textures[e].source=new _g(n)}return this.depthBuffer=t.depthBuffer,this.stencilBuffer=t.stencilBuffer,this.resolveDepthBuffer=t.resolveDepthBuffer,this.resolveStencilBuffer=t.resolveStencilBuffer,t.depthTexture!==null&&(this.depthTexture=t.depthTexture.clone()),this.samples=t.samples,this.multiview=t.multiview,this.useArrayDepthTexture=t.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ai extends b3{constructor(t=1,e=1,i={}){super(t,e,i),this.isWebGLRenderTarget=!0}}class ox extends Mn{constructor(t=null,e=1,i=1,n=1){super(null),this.isDataArrayTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=ei,this.minFilter=ei,this.wrapR=Oi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class cx extends Mn{constructor(t=null,e=1,i=1,n=1){super(null),this.isData3DTexture=!0,this.image={data:t,width:e,height:i,depth:n},this.magFilter=ei,this.minFilter=ei,this.wrapR=Oi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class he{static{he.prototype.isMatrix4=!0}constructor(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m)}set(t,e,i,n,s,r,a,c,l,h,u,d,f,p,g,m){const v=this.elements;return v[0]=t,v[4]=e,v[8]=i,v[12]=n,v[1]=s,v[5]=r,v[9]=a,v[13]=c,v[2]=l,v[6]=h,v[10]=u,v[14]=d,v[3]=f,v[7]=p,v[11]=g,v[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new he().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),i.set(0,0,1),this):(t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){if(t.determinantAffine()===0)return this.identity();const e=this.elements,i=t.elements,n=1/nc.setFromMatrixColumn(t,0).length(),s=1/nc.setFromMatrixColumn(t,1).length(),r=1/nc.setFromMatrixColumn(t,2).length();return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=0,e[4]=i[4]*s,e[5]=i[5]*s,e[6]=i[6]*s,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,n=t.y,s=t.z,r=Math.cos(i),a=Math.sin(i),c=Math.cos(n),l=Math.sin(n),h=Math.cos(s),u=Math.sin(s);if(t.order==="XYZ"){const d=r*h,f=r*u,p=a*h,g=a*u;e[0]=c*h,e[4]=-c*u,e[8]=l,e[1]=f+p*l,e[5]=d-g*l,e[9]=-a*c,e[2]=g-d*l,e[6]=p+f*l,e[10]=r*c}else if(t.order==="YXZ"){const d=c*h,f=c*u,p=l*h,g=l*u;e[0]=d+g*a,e[4]=p*a-f,e[8]=r*l,e[1]=r*u,e[5]=r*h,e[9]=-a,e[2]=f*a-p,e[6]=g+d*a,e[10]=r*c}else if(t.order==="ZXY"){const d=c*h,f=c*u,p=l*h,g=l*u;e[0]=d-g*a,e[4]=-r*u,e[8]=p+f*a,e[1]=f+p*a,e[5]=r*h,e[9]=g-d*a,e[2]=-r*l,e[6]=a,e[10]=r*c}else if(t.order==="ZYX"){const d=r*h,f=r*u,p=a*h,g=a*u;e[0]=c*h,e[4]=p*l-f,e[8]=d*l+g,e[1]=c*u,e[5]=g*l+d,e[9]=f*l-p,e[2]=-l,e[6]=a*c,e[10]=r*c}else if(t.order==="YZX"){const d=r*c,f=r*l,p=a*c,g=a*l;e[0]=c*h,e[4]=g-d*u,e[8]=p*u+f,e[1]=u,e[5]=r*h,e[9]=-a*h,e[2]=-l*h,e[6]=f*u+p,e[10]=d-g*u}else if(t.order==="XZY"){const d=r*c,f=r*l,p=a*c,g=a*l;e[0]=c*h,e[4]=-u,e[8]=l*h,e[1]=d*u+g,e[5]=r*h,e[9]=f*u-p,e[2]=p*u-f,e[6]=a*h,e[10]=g*u+d}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(w3,t,S3)}lookAt(t,e,i){const n=this.elements;return ss.subVectors(t,e),ss.lengthSq()===0&&(ss.z=1),ss.normalize(),ca.crossVectors(i,ss),ca.lengthSq()===0&&(Math.abs(i.z)===1?ss.x+=1e-4:ss.z+=1e-4,ss.normalize(),ca.crossVectors(i,ss)),ca.normalize(),Qh.crossVectors(ss,ca),n[0]=ca.x,n[4]=Qh.x,n[8]=ss.x,n[1]=ca.y,n[5]=Qh.y,n[9]=ss.y,n[2]=ca.z,n[6]=Qh.z,n[10]=ss.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,n=e.elements,s=this.elements,r=i[0],a=i[4],c=i[8],l=i[12],h=i[1],u=i[5],d=i[9],f=i[13],p=i[2],g=i[6],m=i[10],v=i[14],y=i[3],x=i[7],M=i[11],b=i[15],S=n[0],E=n[4],w=n[8],_=n[12],D=n[1],I=n[5],O=n[9],L=n[13],N=n[2],P=n[6],z=n[10],B=n[14],Y=n[3],j=n[7],K=n[11],nt=n[15];return s[0]=r*S+a*D+c*N+l*Y,s[4]=r*E+a*I+c*P+l*j,s[8]=r*w+a*O+c*z+l*K,s[12]=r*_+a*L+c*B+l*nt,s[1]=h*S+u*D+d*N+f*Y,s[5]=h*E+u*I+d*P+f*j,s[9]=h*w+u*O+d*z+f*K,s[13]=h*_+u*L+d*B+f*nt,s[2]=p*S+g*D+m*N+v*Y,s[6]=p*E+g*I+m*P+v*j,s[10]=p*w+g*O+m*z+v*K,s[14]=p*_+g*L+m*B+v*nt,s[3]=y*S+x*D+M*N+b*Y,s[7]=y*E+x*I+M*P+b*j,s[11]=y*w+x*O+M*z+b*K,s[15]=y*_+x*L+M*B+b*nt,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[12],r=t[1],a=t[5],c=t[9],l=t[13],h=t[2],u=t[6],d=t[10],f=t[14],p=t[3],g=t[7],m=t[11],v=t[15],y=c*f-l*d,x=a*f-l*u,M=a*d-c*u,b=r*f-l*h,S=r*d-c*h,E=r*u-a*h;return e*(g*y-m*x+v*M)-i*(p*y-m*b+v*S)+n*(p*x-g*b+v*E)-s*(p*M-g*S+m*E)}determinantAffine(){const t=this.elements,e=t[0],i=t[4],n=t[8],s=t[1],r=t[5],a=t[9],c=t[2],l=t[6],h=t[10];return e*(r*h-a*l)-i*(s*h-a*c)+n*(s*l-r*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=e,n[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],n=t[2],s=t[3],r=t[4],a=t[5],c=t[6],l=t[7],h=t[8],u=t[9],d=t[10],f=t[11],p=t[12],g=t[13],m=t[14],v=t[15],y=e*a-i*r,x=e*c-n*r,M=e*l-s*r,b=i*c-n*a,S=i*l-s*a,E=n*l-s*c,w=h*g-u*p,_=h*m-d*p,D=h*v-f*p,I=u*m-d*g,O=u*v-f*g,L=d*v-f*m,N=y*L-x*O+M*I+b*D-S*_+E*w;if(N===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const P=1/N;return t[0]=(a*L-c*O+l*I)*P,t[1]=(n*O-i*L-s*I)*P,t[2]=(g*E-m*S+v*b)*P,t[3]=(d*S-u*E-f*b)*P,t[4]=(c*D-r*L-l*_)*P,t[5]=(e*L-n*D+s*_)*P,t[6]=(m*M-p*E-v*x)*P,t[7]=(h*E-d*M+f*x)*P,t[8]=(r*O-a*D+l*w)*P,t[9]=(i*D-e*O-s*w)*P,t[10]=(p*S-g*M+v*y)*P,t[11]=(u*M-h*S-f*y)*P,t[12]=(a*_-r*I-c*w)*P,t[13]=(e*I-i*_+n*w)*P,t[14]=(g*x-p*b-m*y)*P,t[15]=(h*b-u*x+d*y)*P,this}scale(t){const e=this.elements,i=t.x,n=t.y,s=t.z;return e[0]*=i,e[4]*=n,e[8]*=s,e[1]*=i,e[5]*=n,e[9]*=s,e[2]*=i,e[6]*=n,e[10]*=s,e[3]*=i,e[7]*=n,e[11]*=s,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,n))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),n=Math.sin(e),s=1-i,r=t.x,a=t.y,c=t.z,l=s*r,h=s*a;return this.set(l*r+i,l*a-n*c,l*c+n*a,0,l*a+n*c,h*a+i,h*c-n*r,0,l*c-n*a,h*c+n*r,s*c*c+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,n,s,r){return this.set(1,i,s,0,t,1,r,0,e,n,1,0,0,0,0,1),this}compose(t,e,i){const n=this.elements,s=e._x,r=e._y,a=e._z,c=e._w,l=s+s,h=r+r,u=a+a,d=s*l,f=s*h,p=s*u,g=r*h,m=r*u,v=a*u,y=c*l,x=c*h,M=c*u,b=i.x,S=i.y,E=i.z;return n[0]=(1-(g+v))*b,n[1]=(f+M)*b,n[2]=(p-x)*b,n[3]=0,n[4]=(f-M)*S,n[5]=(1-(d+v))*S,n[6]=(m+y)*S,n[7]=0,n[8]=(p+x)*E,n[9]=(m-y)*E,n[10]=(1-(d+g))*E,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,e,i){const n=this.elements;t.x=n[12],t.y=n[13],t.z=n[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),e.identity(),this;let r=nc.set(n[0],n[1],n[2]).length();const a=nc.set(n[4],n[5],n[6]).length(),c=nc.set(n[8],n[9],n[10]).length();s<0&&(r=-r),Ds.copy(this);const l=1/r,h=1/a,u=1/c;return Ds.elements[0]*=l,Ds.elements[1]*=l,Ds.elements[2]*=l,Ds.elements[4]*=h,Ds.elements[5]*=h,Ds.elements[6]*=h,Ds.elements[8]*=u,Ds.elements[9]*=u,Ds.elements[10]*=u,e.setFromRotationMatrix(Ds),i.x=r,i.y=a,i.z=c,this}makePerspective(t,e,i,n,s,r,a=Tr,c=!1){const l=this.elements,h=2*s/(e-t),u=2*s/(i-n),d=(e+t)/(e-t),f=(i+n)/(i-n);let p,g;if(c)p=s/(r-s),g=r*s/(r-s);else if(a===Tr)p=-(r+s)/(r-s),g=-2*r*s/(r-s);else if(a===Rh)p=-r/(r-s),g=-r*s/(r-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=g,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,e,i,n,s,r,a=Tr,c=!1){const l=this.elements,h=2/(e-t),u=2/(i-n),d=-(e+t)/(e-t),f=-(i+n)/(i-n);let p,g;if(c)p=1/(r-s),g=r/(r-s);else if(a===Tr)p=-2/(r-s),g=-(r+s)/(r-s);else if(a===Rh)p=-1/(r-s),g=-s/(r-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return l[0]=h,l[4]=0,l[8]=0,l[12]=d,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=p,l[14]=g,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let n=0;n<16;n++)if(e[n]!==i[n])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}}const nc=new R,Ds=new he,w3=new R(0,0,0),S3=new R(1,1,1),ca=new R,Qh=new R,ss=new R,bv=new he,wv=new ts;class jr{constructor(t=0,e=0,i=0,n=jr.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,n=this._order){return this._x=t,this._y=e,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const n=t.elements,s=n[0],r=n[4],a=n[8],c=n[1],l=n[5],h=n[9],u=n[2],d=n[6],f=n[10];switch(e){case"XYZ":this._y=Math.asin(oe(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,f),this._z=Math.atan2(-r,s)):(this._x=Math.atan2(d,l),this._z=0);break;case"YXZ":this._x=Math.asin(-oe(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,s),this._z=0);break;case"ZXY":this._x=Math.asin(oe(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-r,l)):(this._y=0,this._z=Math.atan2(c,s));break;case"ZYX":this._y=Math.asin(-oe(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(c,s)):(this._x=0,this._z=Math.atan2(-r,l));break;case"YZX":this._z=Math.asin(oe(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-oe(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(d,l),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-h,f),this._y=0);break;default:Nt("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return bv.makeRotationFromQuaternion(t),this.setFromRotationMatrix(bv,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return wv.setFromEuler(this),this.setFromQuaternion(wv,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}jr.DEFAULT_ORDER="XYZ";class Tg{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}}let E3=0;const Sv=new R,sc=new ts,Nr=new he,tu=new R,El=new R,A3=new R,_3=new ts,Ev=new R(1,0,0),Av=new R(0,1,0),_v=new R(0,0,1),Tv={type:"added"},T3={type:"removed"},rc={type:"childadded",child:null},l0={type:"childremoved",child:null};class bi extends Ha{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:E3++}),this.uuid=_s(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=bi.DEFAULT_UP.clone();const t=new R,e=new jr,i=new ts,n=new R(1,1,1);function s(){i.setFromEuler(e,!1)}function r(){e.setFromQuaternion(i,void 0,!1)}e._onChange(s),i._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new he},normalMatrix:{value:new ie}}),this.matrix=new he,this.matrixWorld=new he,this.matrixAutoUpdate=bi.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Tg,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return sc.setFromAxisAngle(t,e),this.quaternion.multiply(sc),this}rotateOnWorldAxis(t,e){return sc.setFromAxisAngle(t,e),this.quaternion.premultiply(sc),this}rotateX(t){return this.rotateOnAxis(Ev,t)}rotateY(t){return this.rotateOnAxis(Av,t)}rotateZ(t){return this.rotateOnAxis(_v,t)}translateOnAxis(t,e){return Sv.copy(t).applyQuaternion(this.quaternion),this.position.add(Sv.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(Ev,t)}translateY(t){return this.translateOnAxis(Av,t)}translateZ(t){return this.translateOnAxis(_v,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(Nr.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?tu.copy(t):tu.set(t,e,i);const n=this.parent;this.updateWorldMatrix(!0,!1),El.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Nr.lookAt(El,tu,this.up):Nr.lookAt(tu,El,this.up),this.quaternion.setFromRotationMatrix(Nr),n&&(Nr.extractRotation(n.matrixWorld),sc.setFromRotationMatrix(Nr),this.quaternion.premultiply(sc.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(te("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Tv),rc.child=t,this.dispatchEvent(rc),rc.child=null):te("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(T3),l0.child=t,this.dispatchEvent(l0),l0.child=null),this}removeFromParent(){const t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),Nr.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),Nr.multiply(t.parent.matrixWorld)),t.applyMatrix4(Nr),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Tv),rc.child=t,this.dispatchEvent(rc),rc.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,n=this.children.length;i<n;i++){const r=this.children[i].getObjectByProperty(t,e);if(r!==void 0)return r}}getObjectsByProperty(t,e,i=[]){this[t]===e&&i.push(this);const n=this.children;for(let s=0,r=n.length;s<r;s++)n[s].getObjectsByProperty(t,e,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(El,t,A3),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(El,_3,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}traverse(t){t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const t=this.pivot;if(t!==null){const e=t.x,i=t.y,n=t.z,s=this.matrix.elements;s[12]+=e-s[0]*e-s[4]*i-s[8]*n,s[13]+=i-s[1]*e-s[5]*i-s[9]*n,s[14]+=n-s[2]*e-s[6]*i-s[10]*n}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,n=e.length;i<n;i++)e[i].updateMatrixWorld(t)}updateWorldMatrix(t,e,i=!1){const n=this.parent;if(t===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),e===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0,i)}}toJSON(t){const e=t===void 0||typeof t=="string",i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),this.static!==!1&&(n.static=this.static),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.pivot!==null&&(n.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(n.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(n.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),n.instanceInfo=this._instanceInfo.map(a=>({...a})),n.availableInstanceIds=this._availableInstanceIds.slice(),n.availableGeometryIds=this._availableGeometryIds.slice(),n.nextIndexStart=this._nextIndexStart,n.nextVertexStart=this._nextVertexStart,n.geometryCount=this._geometryCount,n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.matricesTexture=this._matricesTexture.toJSON(t),n.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(n.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(n.boundingBox=this.boundingBox.toJSON()));function s(a,c){return a[c.uuid]===void 0&&(a[c.uuid]=c.toJSON(t)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const c=a.shapes;if(Array.isArray(c))for(let l=0,h=c.length;l<h;l++){const u=c[l];s(t.shapes,u)}else s(t.shapes,c)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(t.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let c=0,l=this.material.length;c<l;c++)a.push(s(t.materials,this.material[c]));n.material=a}else n.material=s(t.materials,this.material);if(this.children.length>0){n.children=[];for(let a=0;a<this.children.length;a++)n.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){n.animations=[];for(let a=0;a<this.animations.length;a++){const c=this.animations[a];n.animations.push(s(t.animations,c))}}if(e){const a=r(t.geometries),c=r(t.materials),l=r(t.textures),h=r(t.images),u=r(t.shapes),d=r(t.skeletons),f=r(t.animations),p=r(t.nodes);a.length>0&&(i.geometries=a),c.length>0&&(i.materials=c),l.length>0&&(i.textures=l),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),p.length>0&&(i.nodes=p)}return i.object=n,i;function r(a){const c=[];for(const l in a){const h=a[l];delete h.metadata,c.push(h)}return c}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let i=0;i<t.children.length;i++){const n=t.children[i];this.add(n.clone())}return this}}bi.DEFAULT_UP=new R(0,1,0);bi.DEFAULT_MATRIX_AUTO_UPDATE=!0;bi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Oe extends bi{constructor(){super(),this.isGroup=!0,this.type="Group"}}const R3={type:"move"};class h0{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Oe,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Oe,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new R,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new R),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Oe,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new R,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new R,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(t){return this._targetRay!==null&&this._targetRay.dispatchEvent(t),this._grip!==null&&this._grip.dispatchEvent(t),this._hand!==null&&this._hand.dispatchEvent(t),this}connect(t){if(t&&t.hand){const e=this._hand;if(e)for(const i of t.hand.values())this._getHandJoint(e,i)}return this.dispatchEvent({type:"connected",data:t}),this}disconnect(t){return this.dispatchEvent({type:"disconnected",data:t}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(t,e,i){let n=null,s=null,r=null;const a=this._targetRay,c=this._grip,l=this._hand;if(t&&e.session.visibilityState!=="visible-blurred"){if(l&&t.hand){r=!0;for(const g of t.hand.values()){const m=e.getJointPose(g,i),v=this._getHandJoint(l,g);m!==null&&(v.matrix.fromArray(m.transform.matrix),v.matrix.decompose(v.position,v.rotation,v.scale),v.matrixWorldNeedsUpdate=!0,v.jointRadius=m.radius),v.visible=m!==null}const h=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=h.position.distanceTo(u.position),f=.02,p=.005;l.inputState.pinching&&d>f+p?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&d<=f-p&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else c!==null&&t.gripSpace&&(s=e.getPose(t.gripSpace,i),s!==null&&(c.matrix.fromArray(s.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,s.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(s.linearVelocity)):c.hasLinearVelocity=!1,s.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(s.angularVelocity)):c.hasAngularVelocity=!1,c.eventsEnabled&&c.dispatchEvent({type:"gripUpdated",data:t,target:this})));a!==null&&(n=e.getPose(t.targetRaySpace,i),n===null&&s!==null&&(n=s),n!==null&&(a.matrix.fromArray(n.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,n.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(n.linearVelocity)):a.hasLinearVelocity=!1,n.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(n.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(R3)))}return a!==null&&(a.visible=n!==null),c!==null&&(c.visible=s!==null),l!==null&&(l.visible=r!==null),this}_getHandJoint(t,e){if(t.joints[e.jointName]===void 0){const i=new Oe;i.matrixAutoUpdate=!1,i.visible=!1,t.joints[e.jointName]=i,t.add(i)}return t.joints[e.jointName]}}const lx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},la={h:0,s:0,l:0},eu={h:0,s:0,l:0};function u0(o,t,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+(t-o)*6*e:e<1/2?t:e<2/3?o+(t-o)*6*(2/3-e):o}class st{constructor(t,e,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,i)}set(t,e,i){if(e===void 0&&i===void 0){const n=t;n&&n.isColor?this.copy(n):typeof n=="number"?this.setHex(n):typeof n=="string"&&this.setStyle(n)}else this.setRGB(t,e,i);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=vn){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(t&255)/255,De.colorSpaceToWorking(this,e),this}setRGB(t,e,i,n=De.workingColorSpace){return this.r=t,this.g=e,this.b=i,De.colorSpaceToWorking(this,n),this}setHSL(t,e,i,n=De.workingColorSpace){if(t=Ag(t,1),e=oe(e,0,1),i=oe(i,0,1),e===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+e):i+e-i*e,r=2*i-s;this.r=u0(r,s,t+1/3),this.g=u0(r,s,t),this.b=u0(r,s,t-1/3)}return De.colorSpaceToWorking(this,n),this}setStyle(t,e=vn){function i(s){s!==void 0&&parseFloat(s)<1&&Nt("Color: Alpha component of "+t+" will be ignored.")}let n;if(n=/^(\w+)\(([^\)]*)\)/.exec(t)){let s;const r=n[1],a=n[2];switch(r){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,e);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,e);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,e);break;default:Nt("Color: Unknown color model "+t)}}else if(n=/^\#([A-Fa-f\d]+)$/.exec(t)){const s=n[1],r=s.length;if(r===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,e);if(r===6)return this.setHex(parseInt(s,16),e);Nt("Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=vn){const i=lx[t.toLowerCase()];return i!==void 0?this.setHex(i,e):Nt("Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=Kr(t.r),this.g=Kr(t.g),this.b=Kr(t.b),this}copyLinearToSRGB(t){return this.r=qc(t.r),this.g=qc(t.g),this.b=qc(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=vn){return De.workingToColorSpace(bn.copy(this),t),Math.round(oe(bn.r*255,0,255))*65536+Math.round(oe(bn.g*255,0,255))*256+Math.round(oe(bn.b*255,0,255))}getHexString(t=vn){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=De.workingColorSpace){De.workingToColorSpace(bn.copy(this),e);const i=bn.r,n=bn.g,s=bn.b,r=Math.max(i,n,s),a=Math.min(i,n,s);let c,l;const h=(a+r)/2;if(a===r)c=0,l=0;else{const u=r-a;switch(l=h<=.5?u/(r+a):u/(2-r-a),r){case i:c=(n-s)/u+(n<s?6:0);break;case n:c=(s-i)/u+2;break;case s:c=(i-n)/u+4;break}c/=6}return t.h=c,t.s=l,t.l=h,t}getRGB(t,e=De.workingColorSpace){return De.workingToColorSpace(bn.copy(this),e),t.r=bn.r,t.g=bn.g,t.b=bn.b,t}getStyle(t=vn){De.workingToColorSpace(bn.copy(this),t);const e=bn.r,i=bn.g,n=bn.b;return t!==vn?`color(${t} ${e.toFixed(3)} ${i.toFixed(3)} ${n.toFixed(3)})`:`rgb(${Math.round(e*255)},${Math.round(i*255)},${Math.round(n*255)})`}offsetHSL(t,e,i){return this.getHSL(la),this.setHSL(la.h+t,la.s+e,la.l+i)}add(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this}addColors(t,e){return this.r=t.r+e.r,this.g=t.g+e.g,this.b=t.b+e.b,this}addScalar(t){return this.r+=t,this.g+=t,this.b+=t,this}sub(t){return this.r=Math.max(0,this.r-t.r),this.g=Math.max(0,this.g-t.g),this.b=Math.max(0,this.b-t.b),this}multiply(t){return this.r*=t.r,this.g*=t.g,this.b*=t.b,this}multiplyScalar(t){return this.r*=t,this.g*=t,this.b*=t,this}lerp(t,e){return this.r+=(t.r-this.r)*e,this.g+=(t.g-this.g)*e,this.b+=(t.b-this.b)*e,this}lerpColors(t,e,i){return this.r=t.r+(e.r-t.r)*i,this.g=t.g+(e.g-t.g)*i,this.b=t.b+(e.b-t.b)*i,this}lerpHSL(t,e){this.getHSL(la),t.getHSL(eu);const i=rh(la.h,eu.h,e),n=rh(la.s,eu.s,e),s=rh(la.l,eu.l,e);return this.setHSL(i,n,s),this}setFromVector3(t){return this.r=t.x,this.g=t.y,this.b=t.z,this}applyMatrix3(t){const e=this.r,i=this.g,n=this.b,s=t.elements;return this.r=s[0]*e+s[3]*i+s[6]*n,this.g=s[1]*e+s[4]*i+s[7]*n,this.b=s[2]*e+s[5]*i+s[8]*n,this}equals(t){return t.r===this.r&&t.g===this.g&&t.b===this.b}fromArray(t,e=0){return this.r=t[e],this.g=t[e+1],this.b=t[e+2],this}toArray(t=[],e=0){return t[e]=this.r,t[e+1]=this.g,t[e+2]=this.b,t}fromBufferAttribute(t,e){return this.r=t.getX(e),this.g=t.getY(e),this.b=t.getZ(e),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const bn=new st;st.NAMES=lx;class Rg{constructor(t,e=1,i=1e3){this.isFog=!0,this.name="",this.color=new st(t),this.near=e,this.far=i}clone(){return new Rg(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Ys extends bi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new jr,this.environmentIntensity=1,this.environmentRotation=new jr,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),t.background!==null&&(this.background=t.background.clone()),t.environment!==null&&(this.environment=t.environment.clone()),t.fog!==null&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),t.overrideMaterial!==null&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return this.fog!==null&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}const Cs=new R,kr=new R,d0=new R,Ur=new R,ac=new R,oc=new R,Rv=new R,f0=new R,p0=new R,m0=new R,g0=new _e,v0=new _e,M0=new _e;class As{constructor(t=new R,e=new R,i=new R){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,n){n.subVectors(i,e),Cs.subVectors(t,e),n.cross(Cs);const s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(t,e,i,n,s){Cs.subVectors(n,e),kr.subVectors(i,e),d0.subVectors(t,e);const r=Cs.dot(Cs),a=Cs.dot(kr),c=Cs.dot(d0),l=kr.dot(kr),h=kr.dot(d0),u=r*l-a*a;if(u===0)return s.set(0,0,0),null;const d=1/u,f=(l*c-a*h)*d,p=(r*h-a*c)*d;return s.set(1-f-p,p,f)}static containsPoint(t,e,i,n){return this.getBarycoord(t,e,i,n,Ur)===null?!1:Ur.x>=0&&Ur.y>=0&&Ur.x+Ur.y<=1}static getInterpolation(t,e,i,n,s,r,a,c){return this.getBarycoord(t,e,i,n,Ur)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(s,Ur.x),c.addScaledVector(r,Ur.y),c.addScaledVector(a,Ur.z),c)}static getInterpolatedAttribute(t,e,i,n,s,r){return g0.setScalar(0),v0.setScalar(0),M0.setScalar(0),g0.fromBufferAttribute(t,e),v0.fromBufferAttribute(t,i),M0.fromBufferAttribute(t,n),r.setScalar(0),r.addScaledVector(g0,s.x),r.addScaledVector(v0,s.y),r.addScaledVector(M0,s.z),r}static isFrontFacing(t,e,i,n){return Cs.subVectors(i,e),kr.subVectors(t,e),Cs.cross(kr).dot(n)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,n){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,e,i,n){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Cs.subVectors(this.c,this.b),kr.subVectors(this.a,this.b),Cs.cross(kr).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return As.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return As.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,n,s){return As.getInterpolation(t,this.a,this.b,this.c,e,i,n,s)}containsPoint(t){return As.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return As.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,n=this.b,s=this.c;let r,a;ac.subVectors(n,i),oc.subVectors(s,i),f0.subVectors(t,i);const c=ac.dot(f0),l=oc.dot(f0);if(c<=0&&l<=0)return e.copy(i);p0.subVectors(t,n);const h=ac.dot(p0),u=oc.dot(p0);if(h>=0&&u<=h)return e.copy(n);const d=c*u-h*l;if(d<=0&&c>=0&&h<=0)return r=c/(c-h),e.copy(i).addScaledVector(ac,r);m0.subVectors(t,s);const f=ac.dot(m0),p=oc.dot(m0);if(p>=0&&f<=p)return e.copy(s);const g=f*l-c*p;if(g<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(i).addScaledVector(oc,a);const m=h*p-f*u;if(m<=0&&u-h>=0&&f-p>=0)return Rv.subVectors(s,n),a=(u-h)/(u-h+(f-p)),e.copy(n).addScaledVector(Rv,a);const v=1/(m+g+d);return r=g*v,a=d*v,e.copy(i).addScaledVector(ac,r).addScaledVector(oc,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class hn{constructor(t=new R(1/0,1/0,1/0),e=new R(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(Os.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(Os.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=Os.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const i=t.geometry;if(i!==void 0){const s=i.getAttribute("position");if(e===!0&&s!==void 0&&t.isInstancedMesh!==!0)for(let r=0,a=s.count;r<a;r++)t.isMesh===!0?t.getVertexPosition(r,Os):Os.fromBufferAttribute(s,r),Os.applyMatrix4(t.matrixWorld),this.expandByPoint(Os);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),iu.copy(t.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),iu.copy(i.boundingBox)),iu.applyMatrix4(t.matrixWorld),this.union(iu)}const n=t.children;for(let s=0,r=n.length;s<r;s++)this.expandByObject(n[s],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Os),Os.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Al),nu.subVectors(this.max,Al),cc.subVectors(t.a,Al),lc.subVectors(t.b,Al),hc.subVectors(t.c,Al),ha.subVectors(lc,cc),ua.subVectors(hc,lc),Wa.subVectors(cc,hc);let e=[0,-ha.z,ha.y,0,-ua.z,ua.y,0,-Wa.z,Wa.y,ha.z,0,-ha.x,ua.z,0,-ua.x,Wa.z,0,-Wa.x,-ha.y,ha.x,0,-ua.y,ua.x,0,-Wa.y,Wa.x,0];return!y0(e,cc,lc,hc,nu)||(e=[1,0,0,0,1,0,0,0,1],!y0(e,cc,lc,hc,nu))?!1:(su.crossVectors(ha,ua),e=[su.x,su.y,su.z],y0(e,cc,lc,hc,nu))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Os).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(Os).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(Fr[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Fr[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Fr[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Fr[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Fr[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Fr[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Fr[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Fr[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Fr),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const Fr=[new R,new R,new R,new R,new R,new R,new R,new R],Os=new R,iu=new hn,cc=new R,lc=new R,hc=new R,ha=new R,ua=new R,Wa=new R,Al=new R,nu=new R,su=new R,Xa=new R;function y0(o,t,e,i,n){for(let s=0,r=o.length-3;s<=r;s+=3){Xa.fromArray(o,s);const a=n.x*Math.abs(Xa.x)+n.y*Math.abs(Xa.y)+n.z*Math.abs(Xa.z),c=t.dot(Xa),l=e.dot(Xa),h=i.dot(Xa);if(Math.max(-Math.max(c,l,h),Math.min(c,l,h))>a)return!1}return!0}const Yr=I3();function I3(){const o=new ArrayBuffer(4),t=new Float32Array(o),e=new Uint32Array(o),i=new Uint32Array(512),n=new Uint32Array(512);for(let c=0;c<256;++c){const l=c-127;l<-27?(i[c]=0,i[c|256]=32768,n[c]=24,n[c|256]=24):l<-14?(i[c]=1024>>-l-14,i[c|256]=1024>>-l-14|32768,n[c]=-l-1,n[c|256]=-l-1):l<=15?(i[c]=l+15<<10,i[c|256]=l+15<<10|32768,n[c]=13,n[c|256]=13):l<128?(i[c]=31744,i[c|256]=64512,n[c]=24,n[c|256]=24):(i[c]=31744,i[c|256]=64512,n[c]=13,n[c|256]=13)}const s=new Uint32Array(2048),r=new Uint32Array(64),a=new Uint32Array(64);for(let c=1;c<1024;++c){let l=c<<13,h=0;for(;(l&8388608)===0;)l<<=1,h-=8388608;l&=-8388609,h+=947912704,s[c]=l|h}for(let c=1024;c<2048;++c)s[c]=939524096+(c-1024<<13);for(let c=1;c<31;++c)r[c]=c<<23;r[31]=1199570944,r[32]=2147483648;for(let c=33;c<63;++c)r[c]=2147483648+(c-32<<23);r[63]=3347054592;for(let c=1;c<64;++c)c!==32&&(a[c]=1024);return{floatView:t,uint32View:e,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:r,offsetTable:a}}function D3(o){Math.abs(o)>65504&&Nt("DataUtils.toHalfFloat(): Value out of range."),o=oe(o,-65504,65504),Yr.floatView[0]=o;const t=Yr.uint32View[0],e=t>>23&511;return Yr.baseTable[e]+((t&8388607)>>Yr.shiftTable[e])}function C3(o){const t=o>>10;return Yr.uint32View[0]=Yr.mantissaTable[Yr.offsetTable[t]+(o&1023)]+Yr.exponentTable[t],Yr.floatView[0]}class ps{static toHalfFloat(t){return D3(t)}static fromHalfFloat(t){return C3(t)}}const Wi=new R,ru=new it;let O3=0;class ce extends Ha{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:O3++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=i,this.usage=ym,this.updateRanges=[],this.gpuType=Dn,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let n=0,s=this.itemSize;n<s;n++)this.array[t+n]=e.array[i+n];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,i=this.count;e<i;e++)ru.fromBufferAttribute(this,e),ru.applyMatrix3(t),this.setXY(e,ru.x,ru.y);else if(this.itemSize===3)for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyMatrix3(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyMatrix4(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.applyNormalMatrix(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)Wi.fromBufferAttribute(this,e),Wi.transformDirection(t),this.setXYZ(e,Wi.x,Wi.y,Wi.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=Vs(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=qe(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=Vs(e,this.array)),e}setX(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=Vs(e,this.array)),e}setY(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=Vs(e,this.array)),e}setZ(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=Vs(e,this.array)),e}setW(t,e){return this.normalized&&(e=qe(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,n){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t*=this.itemSize,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array),s=qe(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=n,this.array[t+3]=s,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(t.name=this.name),this.usage!==ym&&(t.usage=this.usage),t}dispose(){this.dispatchEvent({type:"dispose"})}}class hx extends ce{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class Ig extends ce{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class le extends ce{constructor(t,e,i){super(new Float32Array(t),e,i)}}const P3=new hn,_l=new R,x0=new R;class ea{constructor(t=new R,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;e!==void 0?i.copy(e):P3.setFromPoints(t).getCenter(i);let n=0;for(let s=0,r=t.length;s<r;s++)n=Math.max(n,i.distanceToSquared(t[s]));return this.radius=Math.sqrt(n),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;_l.subVectors(t,this.center);const e=_l.lengthSq();if(e>this.radius*this.radius){const i=Math.sqrt(e),n=(i-this.radius)*.5;this.center.addScaledVector(_l,n/i),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(x0.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(_l.copy(t.center).add(x0)),this.expandByPoint(_l.copy(t.center).sub(x0))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let L3=0;const ys=new he,b0=new bi,uc=new R,rs=new hn,Tl=new hn,an=new R;class ne extends Ha{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:L3++}),this.uuid=_s(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(ZE(t)?Ig:hx)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new ie().getNormalMatrix(t);i.applyNormalMatrix(s),i.needsUpdate=!0}const n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(t),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return ys.makeRotationFromQuaternion(t),this.applyMatrix4(ys),this}rotateX(t){return ys.makeRotationX(t),this.applyMatrix4(ys),this}rotateY(t){return ys.makeRotationY(t),this.applyMatrix4(ys),this}rotateZ(t){return ys.makeRotationZ(t),this.applyMatrix4(ys),this}translate(t,e,i){return ys.makeTranslation(t,e,i),this.applyMatrix4(ys),this}scale(t,e,i){return ys.makeScale(t,e,i),this.applyMatrix4(ys),this}lookAt(t){return b0.lookAt(t),b0.updateMatrix(),this.applyMatrix4(b0.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(uc).negate(),this.translate(uc.x,uc.y,uc.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const i=[];for(let n=0,s=t.length;n<s;n++){const r=t[n];i.push(r.x,r.y,r.z||0)}this.setAttribute("position",new le(i,3))}else{const i=Math.min(t.length,e.count);for(let n=0;n<i;n++){const s=t[n];e.setXYZ(n,s.x,s.y,s.z||0)}t.length>e.count&&Nt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new hn);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){te("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new R(-1/0,-1/0,-1/0),new R(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let i=0,n=e.length;i<n;i++){const s=e[i];rs.setFromBufferAttribute(s),this.morphTargetsRelative?(an.addVectors(this.boundingBox.min,rs.min),this.boundingBox.expandByPoint(an),an.addVectors(this.boundingBox.max,rs.max),this.boundingBox.expandByPoint(an)):(this.boundingBox.expandByPoint(rs.min),this.boundingBox.expandByPoint(rs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&te('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new ea);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){te("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new R,1/0);return}if(t){const i=this.boundingSphere.center;if(rs.setFromBufferAttribute(t),e)for(let s=0,r=e.length;s<r;s++){const a=e[s];Tl.setFromBufferAttribute(a),this.morphTargetsRelative?(an.addVectors(rs.min,Tl.min),rs.expandByPoint(an),an.addVectors(rs.max,Tl.max),rs.expandByPoint(an)):(rs.expandByPoint(Tl.min),rs.expandByPoint(Tl.max))}rs.getCenter(i);let n=0;for(let s=0,r=t.count;s<r;s++)an.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(an));if(e)for(let s=0,r=e.length;s<r;s++){const a=e[s],c=this.morphTargetsRelative;for(let l=0,h=a.count;l<h;l++)an.fromBufferAttribute(a,l),c&&(uc.fromBufferAttribute(t,l),an.add(uc)),n=Math.max(n,i.distanceToSquared(an))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&te('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){te("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.position,n=e.normal,s=e.uv;let r=this.getAttribute("tangent");(r===void 0||r.count!==i.count)&&(r=new ce(new Float32Array(4*i.count),4),this.setAttribute("tangent",r));const a=[],c=[];for(let w=0;w<i.count;w++)a[w]=new R,c[w]=new R;const l=new R,h=new R,u=new R,d=new it,f=new it,p=new it,g=new R,m=new R;function v(w,_,D){l.fromBufferAttribute(i,w),h.fromBufferAttribute(i,_),u.fromBufferAttribute(i,D),d.fromBufferAttribute(s,w),f.fromBufferAttribute(s,_),p.fromBufferAttribute(s,D),h.sub(l),u.sub(l),f.sub(d),p.sub(d);const I=1/(f.x*p.y-p.x*f.y);isFinite(I)&&(g.copy(h).multiplyScalar(p.y).addScaledVector(u,-f.y).multiplyScalar(I),m.copy(u).multiplyScalar(f.x).addScaledVector(h,-p.x).multiplyScalar(I),a[w].add(g),a[_].add(g),a[D].add(g),c[w].add(m),c[_].add(m),c[D].add(m))}let y=this.groups;y.length===0&&(y=[{start:0,count:t.count}]);for(let w=0,_=y.length;w<_;++w){const D=y[w],I=D.start,O=D.count;for(let L=I,N=I+O;L<N;L+=3)v(t.getX(L+0),t.getX(L+1),t.getX(L+2))}const x=new R,M=new R,b=new R,S=new R;function E(w){b.fromBufferAttribute(n,w),S.copy(b);const _=a[w];x.copy(_),x.sub(b.multiplyScalar(b.dot(_))).normalize(),M.crossVectors(S,_);const I=M.dot(c[w])<0?-1:1;r.setXYZW(w,x.x,x.y,x.z,I)}for(let w=0,_=y.length;w<_;++w){const D=y[w],I=D.start,O=D.count;for(let L=I,N=I+O;L<N;L+=3)E(t.getX(L+0)),E(t.getX(L+1)),E(t.getX(L+2))}this._transformed=!0}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(e!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==e.count)i=new ce(new Float32Array(e.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);const n=new R,s=new R,r=new R,a=new R,c=new R,l=new R,h=new R,u=new R;if(t)for(let d=0,f=t.count;d<f;d+=3){const p=t.getX(d+0),g=t.getX(d+1),m=t.getX(d+2);n.fromBufferAttribute(e,p),s.fromBufferAttribute(e,g),r.fromBufferAttribute(e,m),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),a.fromBufferAttribute(i,p),c.fromBufferAttribute(i,g),l.fromBufferAttribute(i,m),a.add(h),c.add(h),l.add(h),i.setXYZ(p,a.x,a.y,a.z),i.setXYZ(g,c.x,c.y,c.z),i.setXYZ(m,l.x,l.y,l.z)}else for(let d=0,f=e.count;d<f;d+=3)n.fromBufferAttribute(e,d+0),s.fromBufferAttribute(e,d+1),r.fromBufferAttribute(e,d+2),h.subVectors(r,s),u.subVectors(n,s),h.cross(u),i.setXYZ(d+0,h.x,h.y,h.z),i.setXYZ(d+1,h.x,h.y,h.z),i.setXYZ(d+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)an.fromBufferAttribute(t,e),an.normalize(),t.setXYZ(e,an.x,an.y,an.z)}toNonIndexed(){function t(a,c){const l=a.array,h=a.itemSize,u=a.normalized,d=new l.constructor(c.length*h);let f=0,p=0;for(let g=0,m=c.length;g<m;g++){a.isInterleavedBufferAttribute?f=c[g]*a.data.stride+a.offset:f=c[g]*h;for(let v=0;v<h;v++)d[p++]=l[f++]}return new ce(d,h,u)}if(this.index===null)return Nt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new ne,i=this.index.array,n=this.attributes;for(const a in n){const c=n[a],l=t(c,i);e.setAttribute(a,l)}const s=this.morphAttributes;for(const a in s){const c=[],l=s[a];for(let h=0,u=l.length;h<u;h++){const d=l[h],f=t(d,i);c.push(f)}e.morphAttributes[a]=c}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,c=r.length;a<c;a++){const l=r[a];e.addGroup(l.start,l.count,l.materialIndex)}return e}toJSON(){const t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,this.name!==""&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(t[l]=c[l]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const c in i){const l=i[c];t.data.attributes[c]=l.toJSON(t.data)}const n={};let s=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],h=[];for(let u=0,d=l.length;u<d;u++){const f=l[u];h.push(f.toJSON(t.data))}h.length>0&&(n[c]=h,s=!0)}s&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;i!==null&&this.setIndex(i.clone());const n=t.attributes;for(const l in n){const h=n[l];this.setAttribute(l,h.clone(e))}const s=t.morphAttributes;for(const l in s){const h=[],u=s[l];for(let d=0,f=u.length;d<f;d++)h.push(u[d].clone(e));this.morphAttributes[l]=h}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let l=0,h=r.length;l<h;l++){const u=r[l];this.addGroup(u.start,u.count,u.materialIndex)}const a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());const c=t.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ux{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=t!==void 0?t.length/e:0,this.usage=ym,this.updateRanges=[],this.version=0,this.uuid=_s()}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,i){t*=this.stride,i*=e.stride;for(let n=0,s=this.stride;n<s;n++)this.array[t+n]=e.array[i+n];return this}set(t,e=0){return this.array.set(t,e),this}clone(t){t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=_s()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const e=new this.array.constructor(t.arrayBuffers[this.array.buffer._uuid]),i=new this.constructor(e,this.stride);return i.setUsage(this.usage),i}onUpload(t){return this.onUploadCallback=t,this}toJSON(t){return t.arrayBuffers===void 0&&(t.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=_s()),t.arrayBuffers[this.array.buffer._uuid]===void 0&&(t.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const On=new R;class tf{constructor(t,e,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=e,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let e=0,i=this.data.count;e<i;e++)On.fromBufferAttribute(this,e),On.applyMatrix4(t),this.setXYZ(e,On.x,On.y,On.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)On.fromBufferAttribute(this,e),On.applyNormalMatrix(t),this.setXYZ(e,On.x,On.y,On.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)On.fromBufferAttribute(this,e),On.transformDirection(t),this.setXYZ(e,On.x,On.y,On.z);return this}getComponent(t,e){let i=this.array[t*this.data.stride+this.offset+e];return this.normalized&&(i=Vs(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=qe(i,this.array)),this.data.array[t*this.data.stride+this.offset+e]=i,this}setX(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset]=e,this}setY(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+1]=e,this}setZ(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+2]=e,this}setW(t,e){return this.normalized&&(e=qe(e,this.array)),this.data.array[t*this.data.stride+this.offset+3]=e,this}getX(t){let e=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(e=Vs(e,this.array)),e}getY(t){let e=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(e=Vs(e,this.array)),e}getZ(t){let e=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(e=Vs(e,this.array)),e}getW(t){let e=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(e=Vs(e,this.array)),e}setXY(t,e,i){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this}setXYZ(t,e,i,n){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this}setXYZW(t,e,i,n,s){return t=t*this.data.stride+this.offset,this.normalized&&(e=qe(e,this.array),i=qe(i,this.array),n=qe(n,this.array),s=qe(s,this.array)),this.data.array[t+0]=e,this.data.array[t+1]=i,this.data.array[t+2]=n,this.data.array[t+3]=s,this}clone(t){if(t===void 0){Qd("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return new ce(new this.array.constructor(e),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new tf(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(t===void 0){Qd("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let i=0;i<this.count;i++){const n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)e.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let N3=0;class Pr extends Ha{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:N3++}),this.uuid=_s(),this.name="",this.type="Material",this.blending=Ua,this.side=za,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Wd,this.blendDst=Ah,this.blendEquation=$r,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new st(0,0,0),this.blendAlpha=0,this.depthFunc=ll,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=mv,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=ec,this.stencilZFail=ec,this.stencilZPass=ec,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(t){this._alphaTest>0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(t!==void 0)for(const e in t){const i=t[e];if(i===void 0){Nt(`Material: parameter '${e}' has value of undefined.`);continue}const n=this[e];if(n===void 0){Nt(`Material: '${e}' is not a property of THREE.${this.type}.`);continue}n&&n.isColor?n.set(i):n&&n.isVector2&&i&&i.isVector2||n&&n.isEuler&&i&&i.isEuler||n&&n.isVector3&&i&&i.isVector3?n.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";e&&(t={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(t).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(t).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(t).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(t).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(t).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(t).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(t).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(t).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(t).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(t).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(t).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.shadowSide!==null&&(i.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),this.blending!==Ua&&(i.blending=this.blending),this.side!==za&&(i.side=this.side),this.vertexColors===!0&&(i.vertexColors=!0),this.opacity<1&&(i.opacity=this.opacity),this.transparent===!0&&(i.transparent=!0),this.blendSrc!==Wd&&(i.blendSrc=this.blendSrc),this.blendDst!==Ah&&(i.blendDst=this.blendDst),this.blendEquation!==$r&&(i.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(i.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(i.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(i.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(i.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(i.blendAlpha=this.blendAlpha),this.depthFunc!==ll&&(i.depthFunc=this.depthFunc),this.depthTest===!1&&(i.depthTest=this.depthTest),this.depthWrite===!1&&(i.depthWrite=this.depthWrite),this.colorWrite===!1&&(i.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(i.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==mv&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ec&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ec&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ec&&(i.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(i.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(i.rotation=this.rotation),this.polygonOffset===!0&&(i.polygonOffset=!0),this.polygonOffsetFactor!==0&&(i.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(i.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(i.linewidth=this.linewidth),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.dithering===!0&&(i.dithering=!0),this.alphaTest>0&&(i.alphaTest=this.alphaTest),this.alphaHash===!0&&(i.alphaHash=!0),this.alphaToCoverage===!0&&(i.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(i.premultipliedAlpha=!0),this.forceSinglePass===!0&&(i.forceSinglePass=!0),this.allowOverride===!1&&(i.allowOverride=!1),this.wireframe===!0&&(i.wireframe=!0),this.wireframeLinewidth>1&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(i.flatShading=!0),this.visible===!1&&(i.visible=!1),this.toneMapped===!1&&(i.toneMapped=!1),this.fog===!1&&(i.fog=!1),Object.keys(this.userData).length>0&&(i.userData=this.userData);function n(s){const r=[];for(const a in s){const c=s[a];delete c.metadata,r.push(c)}return r}if(e){const s=n(t.textures),r=n(t.images);s.length>0&&(i.textures=s),r.length>0&&(i.images=r)}return i}fromJSON(t,e){if(t.uuid!==void 0&&(this.uuid=t.uuid),t.name!==void 0&&(this.name=t.name),t.color!==void 0&&this.color!==void 0&&this.color.setHex(t.color),t.roughness!==void 0&&(this.roughness=t.roughness),t.metalness!==void 0&&(this.metalness=t.metalness),t.sheen!==void 0&&(this.sheen=t.sheen),t.sheenColor!==void 0&&(this.sheenColor=new st().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(this.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(t.emissive),t.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(t.specular),t.specularIntensity!==void 0&&(this.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(this.shininess=t.shininess),t.clearcoat!==void 0&&(this.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(this.dispersion=t.dispersion),t.iridescence!==void 0&&(this.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(this.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(this.transmission=t.transmission),t.thickness!==void 0&&(this.thickness=t.thickness),t.attenuationDistance!==void 0&&(this.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(this.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(this.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(this.fog=t.fog),t.flatShading!==void 0&&(this.flatShading=t.flatShading),t.blending!==void 0&&(this.blending=t.blending),t.combine!==void 0&&(this.combine=t.combine),t.side!==void 0&&(this.side=t.side),t.shadowSide!==void 0&&(this.shadowSide=t.shadowSide),t.opacity!==void 0&&(this.opacity=t.opacity),t.transparent!==void 0&&(this.transparent=t.transparent),t.alphaTest!==void 0&&(this.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(this.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(this.depthFunc=t.depthFunc),t.depthTest!==void 0&&(this.depthTest=t.depthTest),t.depthWrite!==void 0&&(this.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(this.colorWrite=t.colorWrite),t.blendSrc!==void 0&&(this.blendSrc=t.blendSrc),t.blendDst!==void 0&&(this.blendDst=t.blendDst),t.blendEquation!==void 0&&(this.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(this.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(this.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(this.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(this.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(this.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(this.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(this.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(this.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(this.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(this.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(this.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(this.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(this.rotation=t.rotation),t.linewidth!==void 0&&(this.linewidth=t.linewidth),t.dashSize!==void 0&&(this.dashSize=t.dashSize),t.gapSize!==void 0&&(this.gapSize=t.gapSize),t.scale!==void 0&&(this.scale=t.scale),t.polygonOffset!==void 0&&(this.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(this.dithering=t.dithering),t.alphaToCoverage!==void 0&&(this.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(this.forceSinglePass=t.forceSinglePass),t.allowOverride!==void 0&&(this.allowOverride=t.allowOverride),t.visible!==void 0&&(this.visible=t.visible),t.toneMapped!==void 0&&(this.toneMapped=t.toneMapped),t.userData!==void 0&&(this.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?this.vertexColors=t.vertexColors>0:this.vertexColors=t.vertexColors),t.size!==void 0&&(this.size=t.size),t.sizeAttenuation!==void 0&&(this.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(this.map=e[t.map]||null),t.matcap!==void 0&&(this.matcap=e[t.matcap]||null),t.alphaMap!==void 0&&(this.alphaMap=e[t.alphaMap]||null),t.bumpMap!==void 0&&(this.bumpMap=e[t.bumpMap]||null),t.bumpScale!==void 0&&(this.bumpScale=t.bumpScale),t.normalMap!==void 0&&(this.normalMap=e[t.normalMap]||null),t.normalMapType!==void 0&&(this.normalMapType=t.normalMapType),t.normalScale!==void 0){let i=t.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new it().fromArray(i)}return t.displacementMap!==void 0&&(this.displacementMap=e[t.displacementMap]||null),t.displacementScale!==void 0&&(this.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(this.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(this.roughnessMap=e[t.roughnessMap]||null),t.metalnessMap!==void 0&&(this.metalnessMap=e[t.metalnessMap]||null),t.emissiveMap!==void 0&&(this.emissiveMap=e[t.emissiveMap]||null),t.emissiveIntensity!==void 0&&(this.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(this.specularMap=e[t.specularMap]||null),t.specularIntensityMap!==void 0&&(this.specularIntensityMap=e[t.specularIntensityMap]||null),t.specularColorMap!==void 0&&(this.specularColorMap=e[t.specularColorMap]||null),t.envMap!==void 0&&(this.envMap=e[t.envMap]||null),t.envMapRotation!==void 0&&this.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(this.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(this.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(this.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(this.lightMap=e[t.lightMap]||null),t.lightMapIntensity!==void 0&&(this.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(this.aoMap=e[t.aoMap]||null),t.aoMapIntensity!==void 0&&(this.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(this.gradientMap=e[t.gradientMap]||null),t.clearcoatMap!==void 0&&(this.clearcoatMap=e[t.clearcoatMap]||null),t.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=e[t.clearcoatRoughnessMap]||null),t.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=e[t.clearcoatNormalMap]||null),t.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new it().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(this.iridescenceMap=e[t.iridescenceMap]||null),t.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=e[t.iridescenceThicknessMap]||null),t.transmissionMap!==void 0&&(this.transmissionMap=e[t.transmissionMap]||null),t.thicknessMap!==void 0&&(this.thicknessMap=e[t.thicknessMap]||null),t.anisotropyMap!==void 0&&(this.anisotropyMap=e[t.anisotropyMap]||null),t.sheenColorMap!==void 0&&(this.sheenColorMap=e[t.sheenColorMap]||null),t.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=e[t.sheenRoughnessMap]||null),this}clone(){return new this.constructor().copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let i=null;if(e!==null){const n=e.length;i=new Array(n);for(let s=0;s!==n;++s)i[s]=e[s].clone()}return this.clippingPlanes=i,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.allowOverride=t.allowOverride,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){t===!0&&this.version++}}class dd extends Pr{constructor(t){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new st(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.rotation=t.rotation,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}let dc;const Rl=new R,fc=new R,pc=new R,mc=new it,Il=new it,dx=new he,au=new R,Dl=new R,ou=new R,Iv=new it,w0=new it,Dv=new it;class Cl extends bi{constructor(t=new dd){if(super(),this.isSprite=!0,this.type="Sprite",dc===void 0){dc=new ne;const e=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new ux(e,5);dc.setIndex([0,1,2,0,2,3]),dc.setAttribute("position",new tf(i,3,0,!1)),dc.setAttribute("uv",new tf(i,2,3,!1))}this.geometry=dc,this.material=t,this.center=new it(.5,.5),this.count=1}raycast(t,e){t.camera===null&&te('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),fc.setFromMatrixScale(this.matrixWorld),dx.copy(t.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(t.camera.matrixWorldInverse,this.matrixWorld),pc.setFromMatrixPosition(this.modelViewMatrix),t.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&fc.multiplyScalar(-pc.z);const i=this.material.rotation;let n,s;i!==0&&(s=Math.cos(i),n=Math.sin(i));const r=this.center;cu(au.set(-.5,-.5,0),pc,r,fc,n,s),cu(Dl.set(.5,-.5,0),pc,r,fc,n,s),cu(ou.set(.5,.5,0),pc,r,fc,n,s),Iv.set(0,0),w0.set(1,0),Dv.set(1,1);let a=t.ray.intersectTriangle(au,Dl,ou,!1,Rl);if(a===null&&(cu(Dl.set(-.5,.5,0),pc,r,fc,n,s),w0.set(0,1),a=t.ray.intersectTriangle(au,ou,Dl,!1,Rl),a===null))return;const c=t.ray.origin.distanceTo(Rl);c<t.near||c>t.far||e.push({distance:c,point:Rl.clone(),uv:As.getInterpolation(Rl,au,Dl,ou,Iv,w0,Dv,new it),face:null,object:this})}copy(t,e){return super.copy(t,e),t.center!==void 0&&this.center.copy(t.center),this.material=t.material,this}}function cu(o,t,e,i,n,s){mc.subVectors(o,e).addScalar(.5).multiply(i),n!==void 0?(Il.x=s*mc.x-n*mc.y,Il.y=n*mc.x+s*mc.y):Il.copy(mc),o.copy(t),o.x+=Il.x,o.y+=Il.y,o.applyMatrix4(dx)}const zr=new R,S0=new R,lu=new R,da=new R,E0=new R,hu=new R,A0=new R;class zh{constructor(t=new R,e=new R(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,zr)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=zr.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(zr.copy(this.origin).addScaledVector(this.direction,e),zr.distanceToSquared(t))}distanceSqToSegment(t,e,i,n){S0.copy(t).add(e).multiplyScalar(.5),lu.copy(e).sub(t).normalize(),da.copy(this.origin).sub(S0);const s=t.distanceTo(e)*.5,r=-this.direction.dot(lu),a=da.dot(this.direction),c=-da.dot(lu),l=da.lengthSq(),h=Math.abs(1-r*r);let u,d,f,p;if(h>0)if(u=r*c-a,d=r*a-c,p=s*h,u>=0)if(d>=-p)if(d<=p){const g=1/h;u*=g,d*=g,f=u*(u+r*d+2*a)+d*(r*u+d+2*c)+l}else d=s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d=-s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;else d<=-p?(u=Math.max(0,-(-r*s+a)),d=u>0?-s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l):d<=p?(u=0,d=Math.min(Math.max(-s,-c),s),f=d*(d+2*c)+l):(u=Math.max(0,-(r*s+a)),d=u>0?s:Math.min(Math.max(-s,-c),s),f=-u*u+d*(d+2*c)+l);else d=r>0?-s:s,u=Math.max(0,-(r*d+a)),f=-u*u+d*(d+2*c)+l;return i&&i.copy(this.origin).addScaledVector(this.direction,u),n&&n.copy(S0).addScaledVector(lu,d),f}intersectSphere(t,e){zr.subVectors(t.center,this.origin);const i=zr.dot(this.direction),n=zr.dot(zr)-i*i,s=t.radius*t.radius;if(n>s)return null;const r=Math.sqrt(s-n),a=i-r,c=i+r;return c<0?null:a<0?this.at(c,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return i===null?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,n,s,r,a,c;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(i=(t.min.x-d.x)*l,n=(t.max.x-d.x)*l):(i=(t.max.x-d.x)*l,n=(t.min.x-d.x)*l),h>=0?(s=(t.min.y-d.y)*h,r=(t.max.y-d.y)*h):(s=(t.max.y-d.y)*h,r=(t.min.y-d.y)*h),i>r||s>n||((s>i||isNaN(i))&&(i=s),(r<n||isNaN(n))&&(n=r),u>=0?(a=(t.min.z-d.z)*u,c=(t.max.z-d.z)*u):(a=(t.max.z-d.z)*u,c=(t.min.z-d.z)*u),i>c||a>n)||((a>i||i!==i)&&(i=a),(c<n||n!==n)&&(n=c),n<0)?null:this.at(i>=0?i:n,e)}intersectsBox(t){return this.intersectBox(t,zr)!==null}intersectTriangle(t,e,i,n,s){E0.subVectors(e,t),hu.subVectors(i,t),A0.crossVectors(E0,hu);let r=this.direction.dot(A0),a;if(r>0){if(n)return null;a=1}else if(r<0)a=-1,r=-r;else return null;da.subVectors(this.origin,t);const c=a*this.direction.dot(hu.crossVectors(da,hu));if(c<0)return null;const l=a*this.direction.dot(E0.cross(da));if(l<0||c+l>r)return null;const h=-a*da.dot(A0);return h<0?null:this.at(h/r,s)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class es extends Pr{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new st(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.combine=mg,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const Cv=new he,$a=new zh,uu=new ea,Ov=new R,du=new R,fu=new R,pu=new R,_0=new R,mu=new R,Pv=new R,gu=new R;class bt extends bi{constructor(t=new ne,e=new es){super(),this.isMesh=!0,this.type="Mesh",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),t.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=t.morphTargetInfluences.slice()),t.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},t.morphTargetDictionary)),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(t,e){const i=this.geometry,n=i.attributes.position,s=i.morphAttributes.position,r=i.morphTargetsRelative;e.fromBufferAttribute(n,t);const a=this.morphTargetInfluences;if(s&&a){mu.set(0,0,0);for(let c=0,l=s.length;c<l;c++){const h=a[c],u=s[c];h!==0&&(_0.fromBufferAttribute(u,t),r?mu.addScaledVector(_0,h):mu.addScaledVector(_0.sub(e),h))}e.add(mu)}return e}raycast(t,e){const i=this.geometry,n=this.material,s=this.matrixWorld;n!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),uu.copy(i.boundingSphere),uu.applyMatrix4(s),$a.copy(t.ray).recast(t.near),!(uu.containsPoint($a.origin)===!1&&($a.intersectSphere(uu,Ov)===null||$a.origin.distanceToSquared(Ov)>(t.far-t.near)**2))&&(Cv.copy(s).invert(),$a.copy(t.ray).applyMatrix4(Cv),!(i.boundingBox!==null&&$a.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(t,e,$a)))}_computeIntersections(t,e,i){let n;const s=this.geometry,r=this.material,a=s.index,c=s.attributes.position,l=s.attributes.uv,h=s.attributes.uv1,u=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(r))for(let p=0,g=d.length;p<g;p++){const m=d[p],v=r[m.materialIndex],y=Math.max(m.start,f.start),x=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let M=y,b=x;M<b;M+=3){const S=a.getX(M),E=a.getX(M+1),w=a.getX(M+2);n=vu(this,v,t,i,l,h,u,S,E,w),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=m.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),g=Math.min(a.count,f.start+f.count);for(let m=p,v=g;m<v;m+=3){const y=a.getX(m),x=a.getX(m+1),M=a.getX(m+2);n=vu(this,r,t,i,l,h,u,y,x,M),n&&(n.faceIndex=Math.floor(m/3),e.push(n))}}else if(c!==void 0)if(Array.isArray(r))for(let p=0,g=d.length;p<g;p++){const m=d[p],v=r[m.materialIndex],y=Math.max(m.start,f.start),x=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let M=y,b=x;M<b;M+=3){const S=M,E=M+1,w=M+2;n=vu(this,v,t,i,l,h,u,S,E,w),n&&(n.faceIndex=Math.floor(M/3),n.face.materialIndex=m.materialIndex,e.push(n))}}else{const p=Math.max(0,f.start),g=Math.min(c.count,f.start+f.count);for(let m=p,v=g;m<v;m+=3){const y=m,x=m+1,M=m+2;n=vu(this,r,t,i,l,h,u,y,x,M),n&&(n.faceIndex=Math.floor(m/3),e.push(n))}}}}function k3(o,t,e,i,n,s,r,a){let c;if(t.side===xi?c=i.intersectTriangle(r,s,n,!0,a):c=i.intersectTriangle(n,s,r,t.side===za,a),c===null)return null;gu.copy(a),gu.applyMatrix4(o.matrixWorld);const l=e.ray.origin.distanceTo(gu);return l<e.near||l>e.far?null:{distance:l,point:gu.clone(),object:o}}function vu(o,t,e,i,n,s,r,a,c,l){o.getVertexPosition(a,du),o.getVertexPosition(c,fu),o.getVertexPosition(l,pu);const h=k3(o,t,e,i,du,fu,pu,Pv);if(h){const u=new R;As.getBarycoord(Pv,du,fu,pu,u),n&&(h.uv=As.getInterpolatedAttribute(n,a,c,l,u,new it)),s&&(h.uv1=As.getInterpolatedAttribute(s,a,c,l,u,new it)),r&&(h.normal=As.getInterpolatedAttribute(r,a,c,l,u,new R),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const d={a,b:c,c:l,normal:new R,materialIndex:0};As.getNormal(du,fu,pu,d.normal),h.face=d,h.barycoord=u}return h}const Ol=new _e,Lv=new _e,Nv=new _e,U3=new _e,kv=new he,Mu=new R,T0=new ea,Uv=new he,R0=new zh;class $O extends bt{constructor(t,e){super(t,e),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=fv,this.bindMatrix=new he,this.bindMatrixInverse=new he,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){const t=this.geometry;this.boundingBox===null&&(this.boundingBox=new hn),this.boundingBox.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,Mu),this.boundingBox.expandByPoint(Mu)}computeBoundingSphere(){const t=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new ea),this.boundingSphere.makeEmpty();const e=t.getAttribute("position");for(let i=0;i<e.count;i++)this.getVertexPosition(i,Mu),this.boundingSphere.expandByPoint(Mu)}copy(t,e){return super.copy(t,e),this.bindMode=t.bindMode,this.bindMatrix.copy(t.bindMatrix),this.bindMatrixInverse.copy(t.bindMatrixInverse),this.skeleton=t.skeleton,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}raycast(t,e){const i=this.material,n=this.matrixWorld;i!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),T0.copy(this.boundingSphere),T0.applyMatrix4(n),t.ray.intersectsSphere(T0)!==!1&&(Uv.copy(n).invert(),R0.copy(t.ray).applyMatrix4(Uv),!(this.boundingBox!==null&&R0.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(t,e,R0)))}getVertexPosition(t,e){return super.getVertexPosition(t,e),this.applyBoneTransform(t,e),e}bind(t,e){this.skeleton=t,e===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),e=this.matrixWorld),this.bindMatrix.copy(e),this.bindMatrixInverse.copy(e).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){const t=new _e,e=this.geometry.attributes.skinWeight;for(let i=0,n=e.count;i<n;i++){t.fromBufferAttribute(e,i);const s=1/t.manhattanLength();s!==1/0?t.multiplyScalar(s):t.set(1,0,0,0),e.setXYZW(i,t.x,t.y,t.z,t.w)}}updateMatrixWorld(t){super.updateMatrixWorld(t),this.bindMode===fv?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===UE?this.bindMatrixInverse.copy(this.bindMatrix).invert():Nt("SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(t,e){const i=this.skeleton,n=this.geometry;Lv.fromBufferAttribute(n.attributes.skinIndex,t),Nv.fromBufferAttribute(n.attributes.skinWeight,t),e.isVector4?(Ol.copy(e),e.set(0,0,0,0)):(Ol.set(...e,1),e.set(0,0,0)),Ol.applyMatrix4(this.bindMatrix);for(let s=0;s<4;s++){const r=Nv.getComponent(s);if(r!==0){const a=Lv.getComponent(s);kv.multiplyMatrices(i.bones[a].matrixWorld,i.boneInverses[a]),e.addScaledVector(U3.copy(Ol).applyMatrix4(kv),r)}}return e.isVector4&&(e.w=Ol.w),e.applyMatrix4(this.bindMatrixInverse)}}class F3 extends bi{constructor(){super(),this.isBone=!0,this.type="Bone"}}class gs extends Mn{constructor(t=null,e=1,i=1,n,s,r,a,c,l=ei,h=ei,u,d){super(null,r,a,c,l,h,n,s,u,d),this.isDataTexture=!0,this.image={data:t,width:e,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Fv=new he,z3=new he;class fx{constructor(t=[],e=[]){this.uuid=_s(),this.bones=t.slice(0),this.boneInverses=e,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){const t=this.bones,e=this.boneInverses;if(this.boneMatrices=new Float32Array(t.length*16),e.length===0)this.calculateInverses();else if(t.length!==e.length){Nt("Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new he)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,e=this.bones.length;t<e;t++){const i=new he;this.bones[t]&&i.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&i.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,e=this.bones.length;t<e;t++){const i=this.bones[t];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){const t=this.bones,e=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,r=t.length;s<r;s++){const a=t[s]?t[s].matrixWorld:z3;Fv.multiplyMatrices(a,e[s]),Fv.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new fx(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(this.bones.length*4);t=Math.ceil(t/4)*4,t=Math.max(t,4);const e=new Float32Array(t*t*4);e.set(this.boneMatrices);const i=new gs(e,t,t,Ki,Dn);return i.needsUpdate=!0,this.boneMatrices=e,this.boneTexture=i,this}getBoneByName(t){for(let e=0,i=this.bones.length;e<i;e++){const n=this.bones[e];if(n.name===t)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,e){this.uuid=t.uuid;for(let i=0,n=t.bones.length;i<n;i++){const s=t.bones[i];let r=e[s];r===void 0&&(Nt("Skeleton: No bone found with UUID:",s),r=new F3),this.bones.push(r),this.boneInverses.push(new he().fromArray(t.boneInverses[i]))}return this.init(),this}toJSON(){const t={metadata:{version:4.7,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;const e=this.bones,i=this.boneInverses;for(let n=0,s=e.length;n<s;n++){const r=e[n];t.bones.push(r.uuid);const a=i[n];t.boneInverses.push(a.toArray())}return t}}class zv extends ce{constructor(t,e,i,n=1){super(t,e,i),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=n}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}toJSON(){const t=super.toJSON();return t.meshPerAttribute=this.meshPerAttribute,t.isInstancedBufferAttribute=!0,t}}const gc=new he,Bv=new he,yu=[],Hv=new hn,B3=new he,Pl=new bt,Ll=new ea;class YO extends bt{constructor(t,e,i){super(t,e),this.isInstancedMesh=!0,this.instanceMatrix=new zv(new Float32Array(i*16),16),this.instanceColor=null,this.morphTexture=null,this.count=i,this.boundingBox=null,this.boundingSphere=null;for(let n=0;n<i;n++)this.setMatrixAt(n,B3)}computeBoundingBox(){const t=this.geometry,e=this.count;this.boundingBox===null&&(this.boundingBox=new hn),t.boundingBox===null&&t.computeBoundingBox(),this.boundingBox.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,gc),Hv.copy(t.boundingBox).applyMatrix4(gc),this.boundingBox.union(Hv)}computeBoundingSphere(){const t=this.geometry,e=this.count;this.boundingSphere===null&&(this.boundingSphere=new ea),t.boundingSphere===null&&t.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let i=0;i<e;i++)this.getMatrixAt(i,gc),Ll.copy(t.boundingSphere).applyMatrix4(gc),this.boundingSphere.union(Ll)}copy(t,e){return super.copy(t,e),this.instanceMatrix.copy(t.instanceMatrix),t.morphTexture!==null&&(this.morphTexture=t.morphTexture.clone()),t.instanceColor!==null&&(this.instanceColor=t.instanceColor.clone()),this.count=t.count,t.boundingBox!==null&&(this.boundingBox=t.boundingBox.clone()),t.boundingSphere!==null&&(this.boundingSphere=t.boundingSphere.clone()),this}getColorAt(t,e){return this.instanceColor===null?e.setRGB(1,1,1):e.fromArray(this.instanceColor.array,t*3)}getMatrixAt(t,e){return e.fromArray(this.instanceMatrix.array,t*16)}getMorphAt(t,e){const i=e.morphTargetInfluences,n=this.morphTexture.source.data.data,s=i.length+1,r=t*s+1;for(let a=0;a<i.length;a++)i[a]=n[r+a]}raycast(t,e){const i=this.matrixWorld,n=this.count;if(Pl.geometry=this.geometry,Pl.material=this.material,Pl.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Ll.copy(this.boundingSphere),Ll.applyMatrix4(i),t.ray.intersectsSphere(Ll)!==!1))for(let s=0;s<n;s++){this.getMatrixAt(s,gc),Bv.multiplyMatrices(i,gc),Pl.matrixWorld=Bv,Pl.raycast(t,yu);for(let r=0,a=yu.length;r<a;r++){const c=yu[r];c.instanceId=s,c.object=this,e.push(c)}yu.length=0}}setColorAt(t,e){return this.instanceColor===null&&(this.instanceColor=new zv(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),e.toArray(this.instanceColor.array,t*3),this}setMatrixAt(t,e){return e.toArray(this.instanceMatrix.array,t*16),this}setMorphAt(t,e){const i=e.morphTargetInfluences,n=i.length+1;this.morphTexture===null&&(this.morphTexture=new gs(new Float32Array(n*this.count),n,this.count,ul,Dn));const s=this.morphTexture.source.data.data;let r=0;for(let l=0;l<i.length;l++)r+=i[l];const a=this.geometry.morphTargetsRelative?1:1-r,c=n*t;return s[c]=a,s.set(i,c+1),this}updateMorphTargets(){}dispose(){this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null)}}const I0=new R,H3=new R,G3=new ie;class Sa{constructor(t=new R(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,n){return this.normal.set(t,e,i),this.constant=n,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const n=I0.subVectors(i,e).cross(H3.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(n,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e,i=!0){const n=t.delta(I0),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/s;return i===!0&&(r<0||r>1)?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||G3.getNormalMatrix(t),n=this.coplanarPoint(I0).applyMatrix4(t),s=this.normal.applyMatrix3(i).normalize();return this.constant=-n.dot(s),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}}const Ya=new ea,V3=new it(.5,.5),xu=new R;class Dg{constructor(t=new Sa,e=new Sa,i=new Sa,n=new Sa,s=new Sa,r=new Sa){this.planes=[t,e,i,n,s,r]}set(t,e,i,n,s,r){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(i),a[3].copy(n),a[4].copy(s),a[5].copy(r),this}copy(t){const e=this.planes;for(let i=0;i<6;i++)e[i].copy(t.planes[i]);return this}setFromProjectionMatrix(t,e=Tr,i=!1){const n=this.planes,s=t.elements,r=s[0],a=s[1],c=s[2],l=s[3],h=s[4],u=s[5],d=s[6],f=s[7],p=s[8],g=s[9],m=s[10],v=s[11],y=s[12],x=s[13],M=s[14],b=s[15];if(n[0].setComponents(l-r,f-h,v-p,b-y).normalize(),n[1].setComponents(l+r,f+h,v+p,b+y).normalize(),n[2].setComponents(l+a,f+u,v+g,b+x).normalize(),n[3].setComponents(l-a,f-u,v-g,b-x).normalize(),i)n[4].setComponents(c,d,m,M).normalize(),n[5].setComponents(l-c,f-d,v-m,b-M).normalize();else if(n[4].setComponents(l-c,f-d,v-m,b-M).normalize(),e===Tr)n[5].setComponents(l+c,f+d,v+m,b+M).normalize();else if(e===Rh)n[5].setComponents(c,d,m,M).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);return this}intersectsObject(t){if(t.boundingSphere!==void 0)t.boundingSphere===null&&t.computeBoundingSphere(),Ya.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;e.boundingSphere===null&&e.computeBoundingSphere(),Ya.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(Ya)}intersectsSprite(t){Ya.center.set(0,0,0);const e=V3.distanceTo(t.center);return Ya.radius=.7071067811865476+e,Ya.applyMatrix4(t.matrixWorld),this.intersectsSphere(Ya)}intersectsSphere(t){const e=this.planes,i=t.center,n=-t.radius;for(let s=0;s<6;s++)if(e[s].distanceToPoint(i)<n)return!1;return!0}intersectsBox(t){const e=this.planes;for(let i=0;i<6;i++){const n=e[i];if(xu.x=n.normal.x>0?t.max.x:t.min.x,xu.y=n.normal.y>0?t.max.y:t.min.y,xu.z=n.normal.z>0?t.max.z:t.min.z,n.distanceToPoint(xu)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let i=0;i<6;i++)if(e[i].distanceToPoint(t)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class W3 extends Pr{constructor(t){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new st(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.linewidth=t.linewidth,this.linecap=t.linecap,this.linejoin=t.linejoin,this.fog=t.fog,this}}const ef=new R,nf=new R,Gv=new he,Nl=new zh,bu=new ea,D0=new R,Vv=new R;class px extends bi{constructor(t=new ne,e=new W3){super(),this.isLine=!0,this.type="Line",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[0];for(let n=1,s=e.count;n<s;n++)ef.fromBufferAttribute(e,n-1),nf.fromBufferAttribute(e,n),i[n]=i[n-1],i[n]+=ef.distanceTo(nf);t.setAttribute("lineDistance",new le(i,1))}else Nt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Line.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),bu.copy(i.boundingSphere),bu.applyMatrix4(n),bu.radius+=s,t.ray.intersectsSphere(bu)===!1)return;Gv.copy(n).invert(),Nl.copy(t.ray).applyMatrix4(Gv);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=this.isLineSegments?2:1,h=i.index,d=i.attributes.position;if(h!==null){const f=Math.max(0,r.start),p=Math.min(h.count,r.start+r.count);for(let g=f,m=p-1;g<m;g+=l){const v=h.getX(g),y=h.getX(g+1),x=wu(this,t,Nl,c,v,y,g);x&&e.push(x)}if(this.isLineLoop){const g=h.getX(p-1),m=h.getX(f),v=wu(this,t,Nl,c,g,m,p-1);v&&e.push(v)}}else{const f=Math.max(0,r.start),p=Math.min(d.count,r.start+r.count);for(let g=f,m=p-1;g<m;g+=l){const v=wu(this,t,Nl,c,g,g+1,g);v&&e.push(v)}if(this.isLineLoop){const g=wu(this,t,Nl,c,p-1,f,p-1);g&&e.push(g)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function wu(o,t,e,i,n,s,r){const a=o.geometry.attributes.position;if(ef.fromBufferAttribute(a,n),nf.fromBufferAttribute(a,s),e.distanceSqToSegment(ef,nf,D0,Vv)>i)return;D0.applyMatrix4(o.matrixWorld);const l=t.ray.origin.distanceTo(D0);if(!(l<t.near||l>t.far))return{distance:l,point:Vv.clone().applyMatrix4(o.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:o}}const Wv=new R,Xv=new R;class qO extends px{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(t.index===null){const e=t.attributes.position,i=[];for(let n=0,s=e.count;n<s;n+=2)Wv.fromBufferAttribute(e,n),Xv.fromBufferAttribute(e,n+1),i[n]=n===0?0:i[n-1],i[n+1]=i[n]+Wv.distanceTo(Xv);t.setAttribute("lineDistance",new le(i,1))}else Nt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class KO extends px{constructor(t,e){super(t,e),this.isLineLoop=!0,this.type="LineLoop"}}class xm extends Pr{constructor(t){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new st(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.alphaMap=t.alphaMap,this.size=t.size,this.sizeAttenuation=t.sizeAttenuation,this.fog=t.fog,this}}const $v=new he,bm=new zh,Su=new ea,Eu=new R;class Jn extends bi{constructor(t=new ne,e=new xm){super(),this.isPoints=!0,this.type="Points",this.geometry=t,this.material=e,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(t,e){return super.copy(t,e),this.material=Array.isArray(t.material)?t.material.slice():t.material,this.geometry=t.geometry,this}raycast(t,e){const i=this.geometry,n=this.matrixWorld,s=t.params.Points.threshold,r=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Su.copy(i.boundingSphere),Su.applyMatrix4(n),Su.radius+=s,t.ray.intersectsSphere(Su)===!1)return;$v.copy(n).invert(),bm.copy(t.ray).applyMatrix4($v);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),c=a*a,l=i.index,u=i.attributes.position;if(l!==null){const d=Math.max(0,r.start),f=Math.min(l.count,r.start+r.count);for(let p=d,g=f;p<g;p++){const m=l.getX(p);Eu.fromBufferAttribute(u,m),Yv(Eu,m,c,n,t,e,this)}}else{const d=Math.max(0,r.start),f=Math.min(u.count,r.start+r.count);for(let p=d,g=f;p<g;p++)Eu.fromBufferAttribute(u,p),Yv(Eu,p,c,n,t,e,this)}}updateMorphTargets(){const e=this.geometry.morphAttributes,i=Object.keys(e);if(i.length>0){const n=e[i[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,r=n.length;s<r;s++){const a=n[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function Yv(o,t,e,i,n,s,r){const a=bm.distanceSqToPoint(o);if(a<e){const c=new R;bm.closestPointToPoint(o,c),c.applyMatrix4(i);const l=n.ray.origin.distanceTo(c);if(l<n.near||l>n.far)return;s.push({distance:l,distanceToRay:Math.sqrt(a),point:c,index:t,face:null,faceIndex:null,barycoord:null,object:r})}}class mx extends Mn{constructor(t=[],e=Bo,i,n,s,r,a,c,l,h){super(t,e,i,n,s,r,a,c,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class ia extends Mn{constructor(t,e,i,n,s,r,a,c,l){super(t,e,i,n,s,r,a,c,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class Ba extends Mn{constructor(t,e,i=Ts,n,s,r,a=ei,c=ei,l,h=Jr,u=1){if(h!==Jr&&h!==wo)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:t,height:e,depth:u};super(d,n,s,r,a,c,h,i,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(t){return super.copy(t),this.source=new _g(Object.assign({},t.image)),this.compareFunction=t.compareFunction,this}toJSON(t){const e=super.toJSON(t);return this.compareFunction!==null&&(e.compareFunction=this.compareFunction),e}}class X3 extends Ba{constructor(t,e=Ts,i=Bo,n,s,r=ei,a=ei,c,l=Jr){const h={width:t,height:t,depth:1},u=[h,h,h,h,h,h];super(t,t,e,i,n,s,r,a,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(t){this.image=t}}class gx extends Mn{constructor(t=null){super(),this.sourceTexture=t,this.isExternalTexture=!0}copy(t){return super.copy(t),this.sourceTexture=t.sourceTexture,this}}class Pi extends ne{constructor(t=1,e=1,i=1,n=1,s=1,r=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:i,widthSegments:n,heightSegments:s,depthSegments:r};const a=this;n=Math.floor(n),s=Math.floor(s),r=Math.floor(r);const c=[],l=[],h=[],u=[];let d=0,f=0;p("z","y","x",-1,-1,i,e,t,r,s,0),p("z","y","x",1,-1,i,e,-t,r,s,1),p("x","z","y",1,1,t,i,e,n,r,2),p("x","z","y",1,-1,t,i,-e,n,r,3),p("x","y","z",1,-1,t,e,i,n,s,4),p("x","y","z",-1,-1,t,e,-i,n,s,5),this.setIndex(c),this.setAttribute("position",new le(l,3)),this.setAttribute("normal",new le(h,3)),this.setAttribute("uv",new le(u,2));function p(g,m,v,y,x,M,b,S,E,w,_){const D=M/E,I=b/w,O=M/2,L=b/2,N=S/2,P=E+1,z=w+1;let B=0,Y=0;const j=new R;for(let K=0;K<z;K++){const nt=K*I-L;for(let at=0;at<P;at++){const $t=at*D-O;j[g]=$t*y,j[m]=nt*x,j[v]=N,l.push(j.x,j.y,j.z),j[g]=0,j[m]=0,j[v]=S>0?1:-1,h.push(j.x,j.y,j.z),u.push(at/E),u.push(1-K/w),B+=1}}for(let K=0;K<w;K++)for(let nt=0;nt<E;nt++){const at=d+nt+P*K,$t=d+nt+P*(K+1),de=d+(nt+1)+P*(K+1),Gt=d+(nt+1)+P*K;c.push(at,$t,Gt),c.push($t,de,Gt),Y+=6}a.addGroup(f,Y,_),f+=Y,d+=B}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Pi(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}}class Cg extends ne{constructor(t=1,e=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:e,thetaStart:i,thetaLength:n},e=Math.max(3,e);const s=[],r=[],a=[],c=[],l=new R,h=new it;r.push(0,0,0),a.push(0,0,1),c.push(.5,.5);for(let u=0,d=3;u<=e;u++,d+=3){const f=i+u/e*n;l.x=t*Math.cos(f),l.y=t*Math.sin(f),r.push(l.x,l.y,l.z),a.push(0,0,1),h.x=(r[d]/t+1)/2,h.y=(r[d+1]/t+1)/2,c.push(h.x,h.y)}for(let u=1;u<=e;u++)s.push(u,u+1,0);this.setIndex(s),this.setAttribute("position",new le(r,3)),this.setAttribute("normal",new le(a,3)),this.setAttribute("uv",new le(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Cg(t.radius,t.segments,t.thetaStart,t.thetaLength)}}class Cn extends ne{constructor(t=1,e=1,i=1,n=32,s=1,r=!1,a=0,c=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:e,height:i,radialSegments:n,heightSegments:s,openEnded:r,thetaStart:a,thetaLength:c};const l=this;n=Math.floor(n),s=Math.floor(s);const h=[],u=[],d=[],f=[];let p=0;const g=[],m=i/2;let v=0;y(),r===!1&&(t>0&&x(!0),e>0&&x(!1)),this.setIndex(h),this.setAttribute("position",new le(u,3)),this.setAttribute("normal",new le(d,3)),this.setAttribute("uv",new le(f,2));function y(){const M=new R,b=new R;let S=0;const E=(e-t)/i;for(let w=0;w<=s;w++){const _=[],D=w/s,I=D*(e-t)+t;for(let O=0;O<=n;O++){const L=O/n,N=L*c+a,P=Math.sin(N),z=Math.cos(N);b.x=I*P,b.y=-D*i+m,b.z=I*z,u.push(b.x,b.y,b.z),M.set(P,E,z).normalize(),d.push(M.x,M.y,M.z),f.push(L,1-D),_.push(p++)}g.push(_)}for(let w=0;w<n;w++)for(let _=0;_<s;_++){const D=g[_][w],I=g[_+1][w],O=g[_+1][w+1],L=g[_][w+1];(t>0||_!==0)&&(h.push(D,I,L),S+=3),(e>0||_!==s-1)&&(h.push(I,O,L),S+=3)}l.addGroup(v,S,0),v+=S}function x(M){const b=p,S=new it,E=new R;let w=0;const _=M===!0?t:e,D=M===!0?1:-1;for(let O=1;O<=n;O++)u.push(0,m*D,0),d.push(0,D,0),f.push(.5,.5),p++;const I=p;for(let O=0;O<=n;O++){const N=O/n*c+a,P=Math.cos(N),z=Math.sin(N);E.x=_*z,E.y=m*D,E.z=_*P,u.push(E.x,E.y,E.z),d.push(0,D,0),S.x=P*.5+.5,S.y=z*.5*D+.5,f.push(S.x,S.y),p++}for(let O=0;O<n;O++){const L=b+O,N=I+O;M===!0?h.push(N,N+1,L):h.push(N+1,N,L),w+=3}l.addGroup(v,w,M===!0?1:2),v+=w}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Cn(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class vl extends Cn{constructor(t=1,e=1,i=32,n=1,s=!1,r=0,a=Math.PI*2){super(0,t,e,i,n,s,r,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:r,thetaLength:a}}static fromJSON(t){return new vl(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class Lr{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Nt("Curve: .getPoint() not implemented.")}getPointAt(t,e){const i=this.getUtoTmapping(t);return this.getPoint(i,e)}getPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return e}getSpacedPoints(t=5){const e=[];for(let i=0;i<=t;i++)e.push(this.getPointAt(i/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let i,n=this.getPoint(0),s=0;e.push(0);for(let r=1;r<=t;r++)i=this.getPoint(r/t),s+=i.distanceTo(n),e.push(s),n=i;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e=null){const i=this.getLengths();let n=0;const s=i.length;let r;e?r=e:r=t*i[s-1];let a=0,c=s-1,l;for(;a<=c;)if(n=Math.floor(a+(c-a)/2),l=i[n]-r,l<0)a=n+1;else if(l>0)c=n-1;else{c=n;break}if(n=c,i[n]===r)return n/(s-1);const h=i[n],d=i[n+1]-h,f=(r-h)/d;return(n+f)/(s-1)}getTangent(t,e){let n=t-1e-4,s=t+1e-4;n<0&&(n=0),s>1&&(s=1);const r=this.getPoint(n),a=this.getPoint(s),c=e||(r.isVector2?new it:new R);return c.copy(a).sub(r).normalize(),c}getTangentAt(t,e){const i=this.getUtoTmapping(t);return this.getTangent(i,e)}computeFrenetFrames(t,e=!1){const i=new R,n=[],s=[],r=[],a=new R,c=new he;for(let f=0;f<=t;f++){const p=f/t;n[f]=this.getTangentAt(p,new R)}s[0]=new R,r[0]=new R;let l=Number.MAX_VALUE;const h=Math.abs(n[0].x),u=Math.abs(n[0].y),d=Math.abs(n[0].z);h<=l&&(l=h,i.set(1,0,0)),u<=l&&(l=u,i.set(0,1,0)),d<=l&&i.set(0,0,1),a.crossVectors(n[0],i).normalize(),s[0].crossVectors(n[0],a),r[0].crossVectors(n[0],s[0]);for(let f=1;f<=t;f++){if(s[f]=s[f-1].clone(),r[f]=r[f-1].clone(),a.crossVectors(n[f-1],n[f]),a.length()>Number.EPSILON){a.normalize();const p=Math.acos(oe(n[f-1].dot(n[f]),-1,1));s[f].applyMatrix4(c.makeRotationAxis(a,p))}r[f].crossVectors(n[f],s[f])}if(e===!0){let f=Math.acos(oe(s[0].dot(s[t]),-1,1));f/=t,n[0].dot(a.crossVectors(s[0],s[t]))>0&&(f=-f);for(let p=1;p<=t;p++)s[p].applyMatrix4(c.makeRotationAxis(n[p],f*p)),r[p].crossVectors(n[p],s[p])}return{tangents:n,normals:s,binormals:r}}clone(){return new this.constructor().copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class Og extends Lr{constructor(t=0,e=0,i=1,n=1,s=0,r=Math.PI*2,a=!1,c=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=i,this.yRadius=n,this.aStartAngle=s,this.aEndAngle=r,this.aClockwise=a,this.aRotation=c}getPoint(t,e=new it){const i=e,n=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const r=Math.abs(s)<Number.EPSILON;for(;s<0;)s+=n;for(;s>n;)s-=n;s<Number.EPSILON&&(r?s=0:s=n),this.aClockwise===!0&&!r&&(s===n?s=-n:s=s-n);const a=this.aStartAngle+t*s;let c=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){const h=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=c-this.aX,f=l-this.aY;c=d*h-f*u+this.aX,l=d*u+f*h+this.aY}return i.set(c,l)}copy(t){return super.copy(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}toJSON(){const t=super.toJSON();return t.aX=this.aX,t.aY=this.aY,t.xRadius=this.xRadius,t.yRadius=this.yRadius,t.aStartAngle=this.aStartAngle,t.aEndAngle=this.aEndAngle,t.aClockwise=this.aClockwise,t.aRotation=this.aRotation,t}fromJSON(t){return super.fromJSON(t),this.aX=t.aX,this.aY=t.aY,this.xRadius=t.xRadius,this.yRadius=t.yRadius,this.aStartAngle=t.aStartAngle,this.aEndAngle=t.aEndAngle,this.aClockwise=t.aClockwise,this.aRotation=t.aRotation,this}}class $3 extends Og{constructor(t,e,i,n,s,r){super(t,e,i,i,n,s,r),this.isArcCurve=!0,this.type="ArcCurve"}}function Pg(){let o=0,t=0,e=0,i=0;function n(s,r,a,c){o=s,t=a,e=-3*s+3*r-2*a-c,i=2*s-2*r+a+c}return{initCatmullRom:function(s,r,a,c,l){n(r,a,l*(a-s),l*(c-r))},initNonuniformCatmullRom:function(s,r,a,c,l,h,u){let d=(r-s)/l-(a-s)/(l+h)+(a-r)/h,f=(a-r)/h-(c-r)/(h+u)+(c-a)/u;d*=h,f*=h,n(r,a,d,f)},calc:function(s){const r=s*s,a=r*s;return o+t*s+e*r+i*a}}}const qv=new R,Kv=new R,C0=new Pg,O0=new Pg,P0=new Pg;class Y3 extends Lr{constructor(t=[],e=!1,i="centripetal",n=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=t,this.closed=e,this.curveType=i,this.tension=n}getPoint(t,e=new R){const i=e,n=this.points,s=n.length,r=(s-(this.closed?0:1))*t;let a=Math.floor(r),c=r-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/s)+1)*s:c===0&&a===s-1&&(a=s-2,c=1);let l,h;this.closed||a>0?l=n[(a-1)%s]:(Kv.subVectors(n[0],n[1]).add(n[0]),l=Kv);const u=n[a%s],d=n[(a+1)%s];if(this.closed||a+2<s?h=n[(a+2)%s]:(qv.subVectors(n[s-1],n[s-2]).add(n[s-1]),h=qv),this.curveType==="centripetal"||this.curveType==="chordal"){const f=this.curveType==="chordal"?.5:.25;let p=Math.pow(l.distanceToSquared(u),f),g=Math.pow(u.distanceToSquared(d),f),m=Math.pow(d.distanceToSquared(h),f);g<1e-4&&(g=1),p<1e-4&&(p=g),m<1e-4&&(m=g),C0.initNonuniformCatmullRom(l.x,u.x,d.x,h.x,p,g,m),O0.initNonuniformCatmullRom(l.y,u.y,d.y,h.y,p,g,m),P0.initNonuniformCatmullRom(l.z,u.z,d.z,h.z,p,g,m)}else this.curveType==="catmullrom"&&(C0.initCatmullRom(l.x,u.x,d.x,h.x,this.tension),O0.initCatmullRom(l.y,u.y,d.y,h.y,this.tension),P0.initCatmullRom(l.z,u.z,d.z,h.z,this.tension));return i.set(C0.calc(c),O0.calc(c),P0.calc(c)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t.closed=this.closed,t.curveType=this.curveType,t.tension=this.tension,t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new R().fromArray(n))}return this.closed=t.closed,this.curveType=t.curveType,this.tension=t.tension,this}}function Zv(o,t,e,i,n){const s=(i-t)*.5,r=(n-e)*.5,a=o*o,c=o*a;return(2*e-2*i+s+r)*c+(-3*e+3*i-2*s-r)*a+s*o+e}function q3(o,t){const e=1-o;return e*e*t}function K3(o,t){return 2*(1-o)*o*t}function Z3(o,t){return o*o*t}function ah(o,t,e,i){return q3(o,t)+K3(o,e)+Z3(o,i)}function J3(o,t){const e=1-o;return e*e*e*t}function j3(o,t){const e=1-o;return 3*e*e*o*t}function Q3(o,t){return 3*(1-o)*o*o*t}function tA(o,t){return o*o*o*t}function oh(o,t,e,i,n){return J3(o,t)+j3(o,e)+Q3(o,i)+tA(o,n)}class vx extends Lr{constructor(t=new it,e=new it,i=new it,n=new it){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new it){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(oh(t,n.x,s.x,r.x,a.x),oh(t,n.y,s.y,r.y,a.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class eA extends Lr{constructor(t=new R,e=new R,i=new R,n=new R){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=t,this.v1=e,this.v2=i,this.v3=n}getPoint(t,e=new R){const i=e,n=this.v0,s=this.v1,r=this.v2,a=this.v3;return i.set(oh(t,n.x,s.x,r.x,a.x),oh(t,n.y,s.y,r.y,a.y),oh(t,n.z,s.z,r.z,a.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this.v3.copy(t.v3),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t.v3=this.v3.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this.v3.fromArray(t.v3),this}}class Mx extends Lr{constructor(t=new it,e=new it){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=t,this.v2=e}getPoint(t,e=new it){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new it){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class iA extends Lr{constructor(t=new R,e=new R){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=t,this.v2=e}getPoint(t,e=new R){const i=e;return t===1?i.copy(this.v2):(i.copy(this.v2).sub(this.v1),i.multiplyScalar(t).add(this.v1)),i}getPointAt(t,e){return this.getPoint(t,e)}getTangent(t,e=new R){return e.subVectors(this.v2,this.v1).normalize()}getTangentAt(t,e){return this.getTangent(t,e)}copy(t){return super.copy(t),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class yx extends Lr{constructor(t=new it,e=new it,i=new it){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new it){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(ah(t,n.x,s.x,r.x),ah(t,n.y,s.y,r.y)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class nA extends Lr{constructor(t=new R,e=new R,i=new R){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=t,this.v1=e,this.v2=i}getPoint(t,e=new R){const i=e,n=this.v0,s=this.v1,r=this.v2;return i.set(ah(t,n.x,s.x,r.x),ah(t,n.y,s.y,r.y),ah(t,n.z,s.z,r.z)),i}copy(t){return super.copy(t),this.v0.copy(t.v0),this.v1.copy(t.v1),this.v2.copy(t.v2),this}toJSON(){const t=super.toJSON();return t.v0=this.v0.toArray(),t.v1=this.v1.toArray(),t.v2=this.v2.toArray(),t}fromJSON(t){return super.fromJSON(t),this.v0.fromArray(t.v0),this.v1.fromArray(t.v1),this.v2.fromArray(t.v2),this}}class xx extends Lr{constructor(t=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=t}getPoint(t,e=new it){const i=e,n=this.points,s=(n.length-1)*t,r=Math.floor(s),a=s-r,c=n[r===0?r:r-1],l=n[r],h=n[r>n.length-2?n.length-1:r+1],u=n[r>n.length-3?n.length-1:r+2];return i.set(Zv(a,c.x,l.x,h.x,u.x),Zv(a,c.y,l.y,h.y,u.y)),i}copy(t){super.copy(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.points=[];for(let e=0,i=this.points.length;e<i;e++){const n=this.points[e];t.points.push(n.toArray())}return t}fromJSON(t){super.fromJSON(t),this.points=[];for(let e=0,i=t.points.length;e<i;e++){const n=t.points[e];this.points.push(new it().fromArray(n))}return this}}var Jv=Object.freeze({__proto__:null,ArcCurve:$3,CatmullRomCurve3:Y3,CubicBezierCurve:vx,CubicBezierCurve3:eA,EllipseCurve:Og,LineCurve:Mx,LineCurve3:iA,QuadraticBezierCurve:yx,QuadraticBezierCurve3:nA,SplineCurve:xx});class sA extends Lr{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(t){this.curves.push(t)}closePath(){const t=this.curves[0].getPoint(0),e=this.curves[this.curves.length-1].getPoint(1);if(!t.equals(e)){const i=t.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Jv[i](e,t))}return this}getPoint(t,e){const i=t*this.getLength(),n=this.getCurveLengths();let s=0;for(;s<n.length;){if(n[s]>=i){const r=n[s]-i,a=this.curves[s],c=a.getLength(),l=c===0?0:1-r/c;return a.getPointAt(l,e)}s++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let i=0,n=this.curves.length;i<n;i++)e+=this.curves[i].getLength(),t.push(e);return this.cacheLengths=t,t}getSpacedPoints(t=40){const e=[];for(let i=0;i<=t;i++)e.push(this.getPoint(i/t));return this.autoClose&&e.push(e[0]),e}getPoints(t=12){const e=[];let i;for(let n=0,s=this.curves;n<s.length;n++){const r=s[n],a=r.isEllipseCurve?t*2:r.isLineCurve||r.isLineCurve3?1:r.isSplineCurve?t*r.points.length:t,c=r.getPoints(a);for(let l=0;l<c.length;l++){const h=c[l];i&&i.equals(h)||(e.push(h),i=h)}}return this.autoClose&&e.length>1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(n.clone())}return this.autoClose=t.autoClose,this}toJSON(){const t=super.toJSON();t.autoClose=this.autoClose,t.curves=[];for(let e=0,i=this.curves.length;e<i;e++){const n=this.curves[e];t.curves.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.autoClose=t.autoClose,this.curves=[];for(let e=0,i=t.curves.length;e<i;e++){const n=t.curves[e];this.curves.push(new Jv[n.type]().fromJSON(n))}return this}}class jv extends sA{constructor(t){super(),this.type="Path",this.currentPoint=new it,t&&this.setFromPoints(t)}setFromPoints(t){this.moveTo(t[0].x,t[0].y);for(let e=1,i=t.length;e<i;e++)this.lineTo(t[e].x,t[e].y);return this}moveTo(t,e){return this.currentPoint.set(t,e),this}lineTo(t,e){const i=new Mx(this.currentPoint.clone(),new it(t,e));return this.curves.push(i),this.currentPoint.set(t,e),this}quadraticCurveTo(t,e,i,n){const s=new yx(this.currentPoint.clone(),new it(t,e),new it(i,n));return this.curves.push(s),this.currentPoint.set(i,n),this}bezierCurveTo(t,e,i,n,s,r){const a=new vx(this.currentPoint.clone(),new it(t,e),new it(i,n),new it(s,r));return this.curves.push(a),this.currentPoint.set(s,r),this}splineThru(t){const e=[this.currentPoint.clone()].concat(t),i=new xx(e);return this.curves.push(i),this.currentPoint.copy(t[t.length-1]),this}arc(t,e,i,n,s,r){const a=this.currentPoint.x,c=this.currentPoint.y;return this.absarc(t+a,e+c,i,n,s,r),this}absarc(t,e,i,n,s,r){return this.absellipse(t,e,i,i,n,s,r),this}ellipse(t,e,i,n,s,r,a,c){const l=this.currentPoint.x,h=this.currentPoint.y;return this.absellipse(t+l,e+h,i,n,s,r,a,c),this}absellipse(t,e,i,n,s,r,a,c){const l=new Og(t,e,i,n,s,r,a,c);if(this.curves.length>0){const u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);const h=l.getPoint(1);return this.currentPoint.copy(h),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class wm extends jv{constructor(t){super(t),this.uuid=_s(),this.type="Shape",this.holes=[]}getPointsHoles(t){const e=[];for(let i=0,n=this.holes.length;i<n;i++)e[i]=this.holes[i].getPoints(t);return e}extractPoints(t){return{shape:this.getPoints(t),holes:this.getPointsHoles(t)}}copy(t){super.copy(t),this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(n.clone())}return this}toJSON(){const t=super.toJSON();t.uuid=this.uuid,t.holes=[];for(let e=0,i=this.holes.length;e<i;e++){const n=this.holes[e];t.holes.push(n.toJSON())}return t}fromJSON(t){super.fromJSON(t),this.uuid=t.uuid,this.holes=[];for(let e=0,i=t.holes.length;e<i;e++){const n=t.holes[e];this.holes.push(new jv().fromJSON(n))}return this}}function rA(o,t,e=2){const i=t&&t.length,n=i?t[0]*e:o.length;let s=bx(o,0,n,e,!0);const r=[];if(!s||s.next===s.prev)return r;let a,c,l;if(i&&(s=hA(o,t,s,e)),o.length>80*e){a=o[0],c=o[1];let h=a,u=c;for(let d=e;d<n;d+=e){const f=o[d],p=o[d+1];f<a&&(a=f),p<c&&(c=p),f>h&&(h=f),p>u&&(u=p)}l=Math.max(h-a,u-c),l=l!==0?32767/l:0}return Dh(s,r,e,a,c,l,0),r}function bx(o,t,e,i,n){let s;if(n===bA(o,t,e,i)>0)for(let r=t;r<e;r+=i)s=Qv(r/i|0,o[r],o[r+1],s);else for(let r=e-i;r>=t;r-=i)s=Qv(r/i|0,o[r],o[r+1],s);return s&&fl(s,s.next)&&(Oh(s),s=s.next),s}function Vo(o,t){if(!o)return o;t||(t=o);let e=o,i;do if(i=!1,!e.steiner&&(fl(e,e.next)||Ai(e.prev,e,e.next)===0)){if(Oh(e),e=t=e.prev,e===e.next)break;i=!0}else e=e.next;while(i||e!==t);return t}function Dh(o,t,e,i,n,s,r){if(!o)return;!r&&s&&mA(o,i,n,s);let a=o;for(;o.prev!==o.next;){const c=o.prev,l=o.next;if(s?oA(o,i,n,s):aA(o)){t.push(c.i,o.i,l.i),Oh(o),o=l.next,a=l.next;continue}if(o=l,o===a){r?r===1?(o=cA(Vo(o),t),Dh(o,t,e,i,n,s,2)):r===2&&lA(o,t,e,i,n,s):Dh(Vo(o),t,e,i,n,s,1);break}}}function aA(o){const t=o.prev,e=o,i=o.next;if(Ai(t,e,i)>=0)return!1;const n=t.x,s=e.x,r=i.x,a=t.y,c=e.y,l=i.y,h=Math.min(n,s,r),u=Math.min(a,c,l),d=Math.max(n,s,r),f=Math.max(a,c,l);let p=i.next;for(;p!==t;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&Zl(n,a,s,c,r,l,p.x,p.y)&&Ai(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function oA(o,t,e,i){const n=o.prev,s=o,r=o.next;if(Ai(n,s,r)>=0)return!1;const a=n.x,c=s.x,l=r.x,h=n.y,u=s.y,d=r.y,f=Math.min(a,c,l),p=Math.min(h,u,d),g=Math.max(a,c,l),m=Math.max(h,u,d),v=Sm(f,p,t,e,i),y=Sm(g,m,t,e,i);let x=o.prevZ,M=o.nextZ;for(;x&&x.z>=v&&M&&M.z<=y;){if(x.x>=f&&x.x<=g&&x.y>=p&&x.y<=m&&x!==n&&x!==r&&Zl(a,h,c,u,l,d,x.x,x.y)&&Ai(x.prev,x,x.next)>=0||(x=x.prevZ,M.x>=f&&M.x<=g&&M.y>=p&&M.y<=m&&M!==n&&M!==r&&Zl(a,h,c,u,l,d,M.x,M.y)&&Ai(M.prev,M,M.next)>=0))return!1;M=M.nextZ}for(;x&&x.z>=v;){if(x.x>=f&&x.x<=g&&x.y>=p&&x.y<=m&&x!==n&&x!==r&&Zl(a,h,c,u,l,d,x.x,x.y)&&Ai(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;M&&M.z<=y;){if(M.x>=f&&M.x<=g&&M.y>=p&&M.y<=m&&M!==n&&M!==r&&Zl(a,h,c,u,l,d,M.x,M.y)&&Ai(M.prev,M,M.next)>=0)return!1;M=M.nextZ}return!0}function cA(o,t){let e=o;do{const i=e.prev,n=e.next.next;!fl(i,n)&&Sx(i,e,e.next,n)&&Ch(i,n)&&Ch(n,i)&&(t.push(i.i,e.i,n.i),Oh(e),Oh(e.next),e=o=n),e=e.next}while(e!==o);return Vo(e)}function lA(o,t,e,i,n,s){let r=o;do{let a=r.next.next;for(;a!==r.prev;){if(r.i!==a.i&&MA(r,a)){let c=Ex(r,a);r=Vo(r,r.next),c=Vo(c,c.next),Dh(r,t,e,i,n,s,0),Dh(c,t,e,i,n,s,0);return}a=a.next}r=r.next}while(r!==o)}function hA(o,t,e,i){const n=[];for(let s=0,r=t.length;s<r;s++){const a=t[s]*i,c=s<r-1?t[s+1]*i:o.length,l=bx(o,a,c,i,!1);l===l.next&&(l.steiner=!0),n.push(vA(l))}n.sort(uA);for(let s=0;s<n.length;s++)e=dA(n[s],e);return e}function uA(o,t){let e=o.x-t.x;if(e===0&&(e=o.y-t.y,e===0)){const i=(o.next.y-o.y)/(o.next.x-o.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=i-n}return e}function dA(o,t){const e=fA(o,t);if(!e)return t;const i=Ex(e,o);return Vo(i,i.next),Vo(e,e.next)}function fA(o,t){let e=t;const i=o.x,n=o.y;let s=-1/0,r;if(fl(o,e))return e;do{if(fl(o,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const u=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(u<=i&&u>s&&(s=u,r=e.x<e.next.x?e:e.next,u===i))return r}e=e.next}while(e!==t);if(!r)return null;const a=r,c=r.x,l=r.y;let h=1/0;e=r;do{if(i>=e.x&&e.x>=c&&i!==e.x&&wx(n<l?i:s,n,c,l,n<l?s:i,n,e.x,e.y)){const u=Math.abs(n-e.y)/(i-e.x);Ch(e,o)&&(u<h||u===h&&(e.x>r.x||e.x===r.x&&pA(r,e)))&&(r=e,h=u)}e=e.next}while(e!==a);return r}function pA(o,t){return Ai(o.prev,o,t.prev)<0&&Ai(t.next,o,o.next)<0}function mA(o,t,e,i){let n=o;do n.z===0&&(n.z=Sm(n.x,n.y,t,e,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==o);n.prevZ.nextZ=null,n.prevZ=null,gA(n)}function gA(o){let t,e=1;do{let i=o,n;o=null;let s=null;for(t=0;i;){t++;let r=i,a=0;for(let l=0;l<e&&(a++,r=r.nextZ,!!r);l++);let c=e;for(;a>0||c>0&&r;)a!==0&&(c===0||!r||i.z<=r.z)?(n=i,i=i.nextZ,a--):(n=r,r=r.nextZ,c--),s?s.nextZ=n:o=n,n.prevZ=s,s=n;i=r}s.nextZ=null,e*=2}while(t>1);return o}function Sm(o,t,e,i,n){return o=(o-e)*n|0,t=(t-i)*n|0,o=(o|o<<8)&16711935,o=(o|o<<4)&252645135,o=(o|o<<2)&858993459,o=(o|o<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,o|t<<1}function vA(o){let t=o,e=o;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==o);return e}function wx(o,t,e,i,n,s,r,a){return(n-r)*(t-a)>=(o-r)*(s-a)&&(o-r)*(i-a)>=(e-r)*(t-a)&&(e-r)*(s-a)>=(n-r)*(i-a)}function Zl(o,t,e,i,n,s,r,a){return!(o===r&&t===a)&&wx(o,t,e,i,n,s,r,a)}function MA(o,t){return o.next.i!==t.i&&o.prev.i!==t.i&&!yA(o,t)&&(Ch(o,t)&&Ch(t,o)&&xA(o,t)&&(Ai(o.prev,o,t.prev)||Ai(o,t.prev,t))||fl(o,t)&&Ai(o.prev,o,o.next)>0&&Ai(t.prev,t,t.next)>0)}function Ai(o,t,e){return(t.y-o.y)*(e.x-t.x)-(t.x-o.x)*(e.y-t.y)}function fl(o,t){return o.x===t.x&&o.y===t.y}function Sx(o,t,e,i){const n=_u(Ai(o,t,e)),s=_u(Ai(o,t,i)),r=_u(Ai(e,i,o)),a=_u(Ai(e,i,t));return!!(n!==s&&r!==a||n===0&&Au(o,e,t)||s===0&&Au(o,i,t)||r===0&&Au(e,o,i)||a===0&&Au(e,t,i))}function Au(o,t,e){return t.x<=Math.max(o.x,e.x)&&t.x>=Math.min(o.x,e.x)&&t.y<=Math.max(o.y,e.y)&&t.y>=Math.min(o.y,e.y)}function _u(o){return o>0?1:o<0?-1:0}function yA(o,t){let e=o;do{if(e.i!==o.i&&e.next.i!==o.i&&e.i!==t.i&&e.next.i!==t.i&&Sx(e,e.next,o,t))return!0;e=e.next}while(e!==o);return!1}function Ch(o,t){return Ai(o.prev,o,o.next)<0?Ai(o,t,o.next)>=0&&Ai(o,o.prev,t)>=0:Ai(o,t,o.prev)<0||Ai(o,o.next,t)<0}function xA(o,t){let e=o,i=!1;const n=(o.x+t.x)/2,s=(o.y+t.y)/2;do e.y>s!=e.next.y>s&&e.next.y!==e.y&&n<(e.next.x-e.x)*(s-e.y)/(e.next.y-e.y)+e.x&&(i=!i),e=e.next;while(e!==o);return i}function Ex(o,t){const e=Em(o.i,o.x,o.y),i=Em(t.i,t.x,t.y),n=o.next,s=t.prev;return o.next=t,t.prev=o,e.next=n,n.prev=e,i.next=e,e.prev=i,s.next=i,i.prev=s,i}function Qv(o,t,e,i){const n=Em(o,t,e);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function Oh(o){o.next.prev=o.prev,o.prev.next=o.next,o.prevZ&&(o.prevZ.nextZ=o.nextZ),o.nextZ&&(o.nextZ.prevZ=o.prevZ)}function Em(o,t,e){return{i:o,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function bA(o,t,e,i){let n=0;for(let s=t,r=e-i;s<e;s+=i)n+=(o[r]-o[s])*(o[s+1]+o[r+1]),r=s;return n}class wA{static triangulate(t,e,i=2){return rA(t,e,i)}}class ch{static area(t){const e=t.length;let i=0;for(let n=e-1,s=0;s<e;n=s++)i+=t[n].x*t[s].y-t[s].x*t[n].y;return i*.5}static isClockWise(t){return ch.area(t)<0}static triangulateShape(t,e){const i=[],n=[],s=[];tM(t),eM(i,t);let r=t.length;e.forEach(tM);for(let c=0;c<e.length;c++)n.push(r),r+=e[c].length,eM(i,e[c]);const a=wA.triangulate(i,n);for(let c=0;c<a.length;c+=3)s.push(a.slice(c,c+3));return s}}function tM(o){const t=o.length;t>2&&o[t-1].equals(o[0])&&o.pop()}function eM(o,t){for(let e=0;e<t.length;e++)o.push(t[e].x),o.push(t[e].y)}class Of extends ne{constructor(t=[new it(0,-.5),new it(.5,0),new it(0,.5)],e=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:i,phiLength:n},e=Math.floor(e),n=oe(n,0,Math.PI*2);const s=[],r=[],a=[],c=[],l=[],h=1/e,u=new R,d=new it,f=new R,p=new R,g=new R;let m=0,v=0;for(let y=0;y<=t.length-1;y++)switch(y){case 0:m=t[y+1].x-t[y].x,v=t[y+1].y-t[y].y,f.x=v*1,f.y=-m,f.z=v*0,g.copy(f),f.normalize(),c.push(f.x,f.y,f.z);break;case t.length-1:c.push(g.x,g.y,g.z);break;default:m=t[y+1].x-t[y].x,v=t[y+1].y-t[y].y,f.x=v*1,f.y=-m,f.z=v*0,p.copy(f),f.x+=g.x,f.y+=g.y,f.z+=g.z,f.normalize(),c.push(f.x,f.y,f.z),g.copy(p)}for(let y=0;y<=e;y++){const x=i+y*h*n,M=Math.sin(x),b=Math.cos(x);for(let S=0;S<=t.length-1;S++){u.x=t[S].x*M,u.y=t[S].y,u.z=t[S].x*b,r.push(u.x,u.y,u.z),d.x=y/e,d.y=S/(t.length-1),a.push(d.x,d.y);const E=c[3*S+0]*M,w=c[3*S+1],_=c[3*S+0]*b;l.push(E,w,_)}}for(let y=0;y<e;y++)for(let x=0;x<t.length-1;x++){const M=x+y*t.length,b=M,S=M+t.length,E=M+t.length+1,w=M+1;s.push(b,S,w),s.push(E,w,S)}this.setIndex(s),this.setAttribute("position",new le(r,3)),this.setAttribute("uv",new le(a,2)),this.setAttribute("normal",new le(l,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Of(t.points,t.segments,t.phiStart,t.phiLength)}}class Gn extends ne{constructor(t=1,e=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:e,widthSegments:i,heightSegments:n};const s=t/2,r=e/2,a=Math.floor(i),c=Math.floor(n),l=a+1,h=c+1,u=t/a,d=e/c,f=[],p=[],g=[],m=[];for(let v=0;v<h;v++){const y=v*d-r;for(let x=0;x<l;x++){const M=x*u-s;p.push(M,-y,0),g.push(0,0,1),m.push(x/a),m.push(1-v/c)}}for(let v=0;v<c;v++)for(let y=0;y<a;y++){const x=y+l*v,M=y+l*(v+1),b=y+1+l*(v+1),S=y+1+l*v;f.push(x,M,S),f.push(M,b,S)}this.setIndex(f),this.setAttribute("position",new le(p,3)),this.setAttribute("normal",new le(g,3)),this.setAttribute("uv",new le(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Gn(t.width,t.height,t.widthSegments,t.heightSegments)}}class Lg extends ne{constructor(t=new wm([new it(0,.5),new it(-.5,-.5),new it(.5,-.5)]),e=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:e};const i=[],n=[],s=[],r=[];let a=0,c=0;if(Array.isArray(t)===!1)l(t);else for(let h=0;h<t.length;h++)l(t[h]),this.addGroup(a,c,h),a+=c,c=0;this.setIndex(i),this.setAttribute("position",new le(n,3)),this.setAttribute("normal",new le(s,3)),this.setAttribute("uv",new le(r,2));function l(h){const u=n.length/3,d=h.extractPoints(e);let f=d.shape;const p=d.holes;ch.isClockWise(f)===!1&&(f=f.reverse());for(let m=0,v=p.length;m<v;m++){const y=p[m];ch.isClockWise(y)===!0&&(p[m]=y.reverse())}const g=ch.triangulateShape(f,p);for(let m=0,v=p.length;m<v;m++){const y=p[m];f=f.concat(y)}for(let m=0,v=f.length;m<v;m++){const y=f[m];n.push(y.x,y.y,0),s.push(0,0,1),r.push(y.x,y.y)}for(let m=0,v=g.length;m<v;m++){const y=g[m],x=y[0]+u,M=y[1]+u,b=y[2]+u;i.push(x,M,b),c+=3}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){const t=super.toJSON(),e=this.parameters.shapes;return SA(e,t)}static fromJSON(t,e){const i=[];for(let n=0,s=t.shapes.length;n<s;n++){const r=e[t.shapes[n]];i.push(r)}return new Lg(i,t.curveSegments)}}function SA(o,t){if(t.shapes=[],Array.isArray(o))for(let e=0,i=o.length;e<i;e++){const n=o[e];t.shapes.push(n.uuid)}else t.shapes.push(o.uuid);return t}class Gi extends ne{constructor(t=1,e=32,i=16,n=0,s=Math.PI*2,r=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:e,heightSegments:i,phiStart:n,phiLength:s,thetaStart:r,thetaLength:a},e=Math.max(3,Math.floor(e)),i=Math.max(2,Math.floor(i));const c=Math.min(r+a,Math.PI);let l=0;const h=[],u=new R,d=new R,f=[],p=[],g=[],m=[];for(let v=0;v<=i;v++){const y=[],x=v/i,M=r+x*a,b=t*Math.cos(M),S=Math.sqrt(t*t-b*b);let E=0;v===0&&r===0?E=.5/e:v===i&&c===Math.PI&&(E=-.5/e);for(let w=0;w<=e;w++){const _=w/e,D=n+_*s;u.x=-S*Math.cos(D),u.y=b,u.z=S*Math.sin(D),p.push(u.x,u.y,u.z),d.copy(u).normalize(),g.push(d.x,d.y,d.z),m.push(_+E,1-x),y.push(l++)}h.push(y)}for(let v=0;v<i;v++)for(let y=0;y<e;y++){const x=h[v][y+1],M=h[v][y],b=h[v+1][y],S=h[v+1][y+1];(v!==0||r>0)&&f.push(x,M,S),(v!==i-1||c<Math.PI)&&f.push(M,b,S)}this.setIndex(f),this.setAttribute("position",new le(p,3)),this.setAttribute("normal",new le(g,3)),this.setAttribute("uv",new le(m,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Gi(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}}class Ng extends ne{constructor(t=1,e=.4,i=12,n=48,s=Math.PI*2,r=0,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:e,radialSegments:i,tubularSegments:n,arc:s,thetaStart:r,thetaLength:a},i=Math.floor(i),n=Math.floor(n);const c=[],l=[],h=[],u=[],d=new R,f=new R,p=new R;for(let g=0;g<=i;g++){const m=r+g/i*a;for(let v=0;v<=n;v++){const y=v/n*s;f.x=(t+e*Math.cos(m))*Math.cos(y),f.y=(t+e*Math.cos(m))*Math.sin(y),f.z=e*Math.sin(m),l.push(f.x,f.y,f.z),d.x=t*Math.cos(y),d.y=t*Math.sin(y),p.subVectors(f,d).normalize(),h.push(p.x,p.y,p.z),u.push(v/n),u.push(g/i)}}for(let g=1;g<=i;g++)for(let m=1;m<=n;m++){const v=(n+1)*g+m-1,y=(n+1)*(g-1)+m-1,x=(n+1)*(g-1)+m,M=(n+1)*g+m;c.push(v,y,M),c.push(y,x,M)}this.setIndex(c),this.setAttribute("position",new le(l,3)),this.setAttribute("normal",new le(h,3)),this.setAttribute("uv",new le(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Ng(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}}class ZO extends ne{constructor(t=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:t},t!==null){const e=[],i=new Set,n=new R,s=new R;if(t.index!==null){const r=t.attributes.position,a=t.index;let c=t.groups;c.length===0&&(c=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,h=c.length;l<h;++l){const u=c[l],d=u.start,f=u.count;for(let p=d,g=d+f;p<g;p+=3)for(let m=0;m<3;m++){const v=a.getX(p+m),y=a.getX(p+(m+1)%3);n.fromBufferAttribute(r,v),s.fromBufferAttribute(r,y),iM(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}}else{const r=t.attributes.position;for(let a=0,c=r.count/3;a<c;a++)for(let l=0;l<3;l++){const h=3*a+l,u=3*a+(l+1)%3;n.fromBufferAttribute(r,h),s.fromBufferAttribute(r,u),iM(n,s,i)===!0&&(e.push(n.x,n.y,n.z),e.push(s.x,s.y,s.z))}}this.setAttribute("position",new le(e,3))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}}function iM(o,t,e){const i=`${o.x},${o.y},${o.z}-${t.x},${t.y},${t.z}`,n=`${t.x},${t.y},${t.z}-${o.x},${o.y},${o.z}`;return e.has(i)===!0||e.has(n)===!0?!1:(e.add(i),e.add(n),!0)}function pl(o){const t={};for(const e in o){t[e]={};for(const i in o[e]){const n=o[e][i];if(nM(n))n.isRenderTargetTexture?(Nt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[e][i]=null):t[e][i]=n.clone();else if(Array.isArray(n))if(nM(n[0])){const s=[];for(let r=0,a=n.length;r<a;r++)s[r]=n[r].clone();t[e][i]=s}else t[e][i]=n.slice();else t[e][i]=n}}return t}function Pn(o){const t={};for(let e=0;e<o.length;e++){const i=pl(o[e]);for(const n in i)t[n]=i[n]}return t}function nM(o){return o&&(o.isColor||o.isMatrix3||o.isMatrix4||o.isVector2||o.isVector3||o.isVector4||o.isTexture||o.isQuaternion)}function EA(o){const t=[];for(let e=0;e<o.length;e++)t.push(o[e].clone());return t}function Ax(o){const t=o.getRenderTarget();return t===null?o.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:De.workingColorSpace}const AA={clone:pl,merge:Pn};var _A=`void main() {
|
|
2409
2409
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
2410
2410
|
}`,TA=`void main() {
|
|
2411
2411
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
2412
|
-
}`;class Se extends Pr{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=_A,this.fragmentShader=TA,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,t!==void 0&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=pl(t.uniforms),this.uniformsGroups=EA(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this.defaultAttributeValues=Object.assign({},t.defaultAttributeValues),this.index0AttributeName=t.index0AttributeName,this.uniformsNeedUpdate=t.uniformsNeedUpdate,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const n in this.uniforms){const r=this.uniforms[n].value;r&&r.isTexture?e.uniforms[n]={type:"t",value:r.toJSON(t).uuid}:r&&r.isColor?e.uniforms[n]={type:"c",value:r.getHex()}:r&&r.isVector2?e.uniforms[n]={type:"v2",value:r.toArray()}:r&&r.isVector3?e.uniforms[n]={type:"v3",value:r.toArray()}:r&&r.isVector4?e.uniforms[n]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?e.uniforms[n]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?e.uniforms[n]={type:"m4",value:r.toArray()}:e.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}fromJSON(t,e){if(super.fromJSON(t,e),t.uniforms!==void 0)for(const i in t.uniforms){const n=t.uniforms[i];switch(this.uniforms[i]={},n.type){case"t":this.uniforms[i].value=e[n.value]||null;break;case"c":this.uniforms[i].value=new st().setHex(n.value);break;case"v2":this.uniforms[i].value=new it().fromArray(n.value);break;case"v3":this.uniforms[i].value=new R().fromArray(n.value);break;case"v4":this.uniforms[i].value=new _e().fromArray(n.value);break;case"m3":this.uniforms[i].value=new ie().fromArray(n.value);break;case"m4":this.uniforms[i].value=new he().fromArray(n.value);break;default:this.uniforms[i].value=n.value}}if(t.defines!==void 0&&(this.defines=t.defines),t.vertexShader!==void 0&&(this.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(this.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(this.glslVersion=t.glslVersion),t.extensions!==void 0)for(const i in t.extensions)this.extensions[i]=t.extensions[i];return t.lights!==void 0&&(this.lights=t.lights),t.clipping!==void 0&&(this.clipping=t.clipping),this}}class _x extends Se{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ia extends Pr{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new st(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new st(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Kd,this.normalScale=new it(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class RA extends Ia{constructor(t){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new it(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return oe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new st(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new st(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new st(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class Rs extends Pr{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new st(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new st(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Kd,this.normalScale=new it(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.combine=mg,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class IA extends Pr{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=GE,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class DA extends Pr{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Tu(o,t){return!o||o.constructor===t?o:typeof t.BYTES_PER_ELEMENT=="number"?new t(o):Array.prototype.slice.call(o)}function CA(o){function t(n,s){return o[n]-o[s]}const e=o.length,i=new Array(e);for(let n=0;n!==e;++n)i[n]=n;return i.sort(t),i}function sM(o,t,e){const i=o.length,n=new o.constructor(i);for(let s=0,r=0;r!==i;++s){const a=e[s]*t;for(let c=0;c!==t;++c)n[r++]=o[a+c]}return n}function OA(o,t,e,i){let n=1,s=o[0];for(;s!==void 0&&s[i]===void 0;)s=o[n++];if(s===void 0)return;let r=s[i];if(r!==void 0)if(Array.isArray(r))do r=s[i],r!==void 0&&(t.push(s.time),e.push(...r)),s=o[n++];while(s!==void 0);else if(r.toArray!==void 0)do r=s[i],r!==void 0&&(t.push(s.time),r.toArray(e,e.length)),s=o[n++];while(s!==void 0);else do r=s[i],r!==void 0&&(t.push(s.time),e.push(r)),s=o[n++];while(s!==void 0)}class Bh{constructor(t,e,i,n){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=n!==void 0?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let i=this._cachedIndex,n=e[i],s=e[i-1];t:{e:{let r;i:{n:if(!(t<n)){for(let a=i+2;;){if(n===void 0){if(t<s)break n;return i=e.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===a)break;if(s=n,n=e[++i],t<n)break e}r=e.length;break i}if(!(t>=s)){const a=e[1];t<a&&(i=2,s=a);for(let c=i-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===c)break;if(n=s,s=e[--i-1],t>=s)break e}r=i,i=0;break i}break t}for(;i<r;){const a=i+r>>>1;t<e[a]?r=a:i=a+1}if(n=e[i],s=e[i-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===void 0)return i=e.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,s,n)}return this.interpolate_(i,s,t,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){const e=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=t*n;for(let r=0;r!==n;++r)e[r]=i[s+r];return e}interpolate_(){throw new Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class PA extends Bh{constructor(t,e,i,n){super(t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Nc,endingEnd:Nc}}intervalChanged_(t,e,i){const n=this.parameterPositions;let s=t-2,r=t+1,a=n[s],c=n[r];if(a===void 0)switch(this.getSettings_().endingStart){case kc:s=t,a=2*e-i;break;case qd:s=n.length-2,a=e+n[s]-n[s+1];break;default:s=t,a=i}if(c===void 0)switch(this.getSettings_().endingEnd){case kc:r=t,c=2*i-e;break;case qd:r=1,c=i+n[1]-n[0];break;default:r=t-1,c=e}const l=(i-e)*.5,h=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(c-i),this._offsetPrev=s*h,this._offsetNext=r*h}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(i-e)/(n-e),g=p*p,m=g*p,v=-d*m+2*d*g-d*p,y=(1+d)*m+(-1.5-2*d)*g+(-.5+d)*p+1,x=(-1-f)*m+(1.5+f)*g+.5*p,M=f*m-f*g;for(let b=0;b!==a;++b)s[b]=v*r[h+b]+y*r[l+b]+x*r[c+b]+M*r[u+b];return s}}class Tx extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=(i-e)/(n-e),u=1-h;for(let d=0;d!==a;++d)s[d]=r[l+d]*u+r[c+d]*h;return s}}class LA extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t){return this.copySampleValue_(t-1)}}class NA extends Bh{interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=this.inTangents,u=this.outTangents;if(!h||!u){const p=(i-e)/(n-e),g=1-p;for(let m=0;m!==a;++m)s[m]=r[l+m]*g+r[c+m]*p;return s}const d=a*2,f=t-1;for(let p=0;p!==a;++p){const g=r[l+p],m=r[c+p],v=f*d+p*2,y=u[v],x=u[v+1],M=t*d+p*2,b=h[M],S=h[M+1];let E=(i-e)/(n-e),w,_,D,I,O;for(let L=0;L<8;L++){w=E*E,_=w*E,D=1-E,I=D*D,O=I*D;const P=O*e+3*I*E*y+3*D*w*b+_*n-i;if(Math.abs(P)<1e-10)break;const z=3*I*(y-e)+6*D*E*(b-y)+3*w*(n-b);if(Math.abs(z)<1e-10)break;E=E-P/z,E=Math.max(0,Math.min(1,E))}s[p]=O*g+3*I*E*x+3*D*w*S+_*m}return s}}class qs{constructor(t,e,i,n){if(t===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(e===void 0||e.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Tu(e,this.TimeBufferType),this.values=Tu(i,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}static toJSON(t){const e=t.constructor;let i;if(e.toJSON!==this.toJSON)i=e.toJSON(t);else{i={name:t.name,times:Tu(t.times,Array),values:Tu(t.values,Array)};const n=t.getInterpolation();n!==t.DefaultInterpolation&&(i.interpolation=n)}return i.type=t.ValueTypeName,i}InterpolantFactoryMethodDiscrete(t){return new LA(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new Tx(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new PA(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodBezier(t){const e=new NA(this.times,this.values,this.getValueSize(),t);return this.settings&&(e.inTangents=this.settings.inTangents,e.outTangents=this.settings.outTangents),e}setInterpolation(t){let e;switch(t){case Yd:e=this.InterpolantFactoryMethodDiscrete;break;case Mm:e=this.InterpolantFactoryMethodLinear;break;case s0:e=this.InterpolantFactoryMethodSmooth;break;case pv:e=this.InterpolantFactoryMethodBezier;break}if(e===void 0){const i="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(t!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(i);return Nt("KeyframeTrack:",i),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Yd;case this.InterpolantFactoryMethodLinear:return Mm;case this.InterpolantFactoryMethodSmooth:return s0;case this.InterpolantFactoryMethodBezier:return pv}}getValueSize(){return this.values.length/this.times.length}shift(t){if(t!==0){const e=this.times;for(let i=0,n=e.length;i!==n;++i)e[i]+=t}return this}scale(t){if(t!==1){const e=this.times;for(let i=0,n=e.length;i!==n;++i)e[i]*=t}return this}trim(t,e){const i=this.times,n=i.length;let s=0,r=n-1;for(;s!==n&&i[s]<t;)++s;for(;r!==-1&&i[r]>e;)--r;if(++r,s!==0||r!==n){s>=r&&(r=Math.max(r,1),s=r-1);const a=this.getValueSize();this.times=i.slice(s,r),this.values=this.values.slice(s*a,r*a)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(te("KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,n=this.values,s=i.length;s===0&&(te("KeyframeTrack: Track is empty.",this),t=!1);let r=null;for(let a=0;a!==s;a++){const c=i[a];if(typeof c=="number"&&isNaN(c)){te("KeyframeTrack: Time is not a valid number.",this,a,c),t=!1;break}if(r!==null&&r>c){te("KeyframeTrack: Out of order keys.",this,a,c,r),t=!1;break}r=c}if(n!==void 0&&JE(n))for(let a=0,c=n.length;a!==c;++a){const l=n[a];if(isNaN(l)){te("KeyframeTrack: Value is not a valid number.",this,a,l),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===s0,s=t.length-1;let r=1;for(let a=1;a<s;++a){let c=!1;const l=t[a],h=t[a+1];if(l!==h&&(a!==1||l!==t[0]))if(n)c=!0;else{const u=a*i,d=u-i,f=u+i;for(let p=0;p!==i;++p){const g=e[u+p];if(g!==e[d+p]||g!==e[f+p]){c=!0;break}}}if(c){if(a!==r){t[r]=t[a];const u=a*i,d=r*i;for(let f=0;f!==i;++f)e[d+f]=e[u+f]}++r}}if(s>0){t[r]=t[s];for(let a=s*i,c=r*i,l=0;l!==i;++l)e[c+l]=e[a+l];++r}return r!==t.length?(this.times=t.slice(0,r),this.values=e.slice(0,r*i)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),i=this.constructor,n=new i(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}qs.prototype.ValueTypeName="";qs.prototype.TimeBufferType=Float32Array;qs.prototype.ValueBufferType=Float32Array;qs.prototype.DefaultInterpolation=Mm;class Ml extends qs{constructor(t,e,i){super(t,e,i)}}Ml.prototype.ValueTypeName="bool";Ml.prototype.ValueBufferType=Array;Ml.prototype.DefaultInterpolation=Yd;Ml.prototype.InterpolantFactoryMethodLinear=void 0;Ml.prototype.InterpolantFactoryMethodSmooth=void 0;class Rx extends qs{constructor(t,e,i,n){super(t,e,i,n)}}Rx.prototype.ValueTypeName="color";class kg extends qs{constructor(t,e,i,n){super(t,e,i,n)}}kg.prototype.ValueTypeName="number";class kA extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=(i-e)/(n-e);let l=t*a;for(let h=l+a;l!==h;l+=4)ts.slerpFlat(s,0,r,l-a,r,l,c);return s}}class Ug extends qs{constructor(t,e,i,n){super(t,e,i,n)}InterpolantFactoryMethodLinear(t){return new kA(this.times,this.values,this.getValueSize(),t)}}Ug.prototype.ValueTypeName="quaternion";Ug.prototype.InterpolantFactoryMethodSmooth=void 0;class yl extends qs{constructor(t,e,i){super(t,e,i)}}yl.prototype.ValueTypeName="string";yl.prototype.ValueBufferType=Array;yl.prototype.DefaultInterpolation=Yd;yl.prototype.InterpolantFactoryMethodLinear=void 0;yl.prototype.InterpolantFactoryMethodSmooth=void 0;class Ix extends qs{constructor(t,e,i,n){super(t,e,i,n)}}Ix.prototype.ValueTypeName="vector";class rM{constructor(t="",e=-1,i=[],n=wg){this.name=t,this.tracks=i,this.duration=e,this.blendMode=n,this.uuid=_s(),this.userData={},this.duration<0&&this.resetDuration()}static parse(t){const e=[],i=t.tracks,n=1/(t.fps||1);for(let r=0,a=i.length;r!==a;++r)e.push(FA(i[r]).scale(n));const s=new this(t.name,t.duration,e,t.blendMode);return s.uuid=t.uuid,s.userData=JSON.parse(t.userData||"{}"),s}static toJSON(t){const e=[],i=t.tracks,n={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode,userData:JSON.stringify(t.userData)};for(let s=0,r=i.length;s!==r;++s)e.push(qs.toJSON(i[s]));return n}static CreateFromMorphTargetSequence(t,e,i,n){const s=e.length,r=[];for(let a=0;a<s;a++){let c=[],l=[];c.push((a+s-1)%s,a,(a+1)%s),l.push(0,1,0);const h=CA(c);c=sM(c,1,h),l=sM(l,1,h),!n&&c[0]===0&&(c.push(s),l.push(l[0])),r.push(new kg(".morphTargetInfluences["+e[a].name+"]",c,l).scale(1/i))}return new this(t,-1,r)}static findByName(t,e){let i=t;if(!Array.isArray(t)){const n=t;i=n.geometry&&n.geometry.animations||n.animations}for(let n=0;n<i.length;n++)if(i[n].name===e)return i[n];return null}static CreateClipsFromMorphTargetSequences(t,e,i){const n={},s=/^([\w-]*?)([\d]+)$/;for(let a=0,c=t.length;a<c;a++){const l=t[a],h=l.name.match(s);if(h&&h.length>1){const u=h[1];let d=n[u];d||(n[u]=d=[]),d.push(l)}}const r=[];for(const a in n)r.push(this.CreateFromMorphTargetSequence(a,n[a],e,i));return r}resetDuration(){const t=this.tracks;let e=0;for(let i=0,n=t.length;i!==n;++i){const s=this.tracks[i];e=Math.max(e,s.times[s.times.length-1])}return this.duration=e,this}trim(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].trim(0,this.duration);return this}validate(){let t=!0;for(let e=0;e<this.tracks.length;e++)t=t&&this.tracks[e].validate();return t}optimize(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].optimize();return this}clone(){const t=[];for(let i=0;i<this.tracks.length;i++)t.push(this.tracks[i].clone());const e=new this.constructor(this.name,this.duration,t,this.blendMode);return e.userData=JSON.parse(JSON.stringify(this.userData)),e}toJSON(){return this.constructor.toJSON(this)}}function UA(o){switch(o.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return kg;case"vector":case"vector2":case"vector3":case"vector4":return Ix;case"color":return Rx;case"quaternion":return Ug;case"bool":case"boolean":return Ml;case"string":return yl}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+o)}function FA(o){if(o.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const t=UA(o.type);if(o.times===void 0){const e=[],i=[];OA(o.keys,e,i,"value"),o.times=e,o.values=i}return t.parse!==void 0?t.parse(o):new t(o.name,o.times,o.values,o.interpolation)}const qr={enabled:!1,files:{},add:function(o,t){this.enabled!==!1&&(aM(o)||(this.files[o]=t))},get:function(o){if(this.enabled!==!1&&!aM(o))return this.files[o]},remove:function(o){delete this.files[o]},clear:function(){this.files={}}};function aM(o){try{const t=o.slice(o.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch{return!1}}class zA{constructor(t,e,i){const n=this;let s=!1,r=0,a=0,c;const l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this._abortController=null,this.itemStart=function(h){a++,s===!1&&n.onStart!==void 0&&n.onStart(h,r,a),s=!0},this.itemEnd=function(h){r++,n.onProgress!==void 0&&n.onProgress(h,r,a),r===a&&(s=!1,n.onLoad!==void 0&&n.onLoad())},this.itemError=function(h){n.onError!==void 0&&n.onError(h)},this.resolveURL=function(h){return h=h.normalize("NFC"),c?c(h):h},this.setURLModifier=function(h){return c=h,this},this.addHandler=function(h,u){return l.push(h,u),this},this.removeHandler=function(h){const u=l.indexOf(h);return u!==-1&&l.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=l.length;u<d;u+=2){const f=l[u],p=l[u+1];if(f.global&&(f.lastIndex=0),f.test(h))return p}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const BA=new zA;class Hh{constructor(t){this.manager=t!==void 0?t:BA,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(t,e){const i=this;return new Promise(function(n,s){i.load(t,n,e,s)})}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}abort(){return this}}Hh.DEFAULT_MATERIAL_NAME="__DEFAULT";const Br={};class HA extends Error{constructor(t,e){super(t),this.response=e}}class ZO extends Hh{constructor(t){super(t),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(t,e,i,n){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=qr.get(`file:${t}`);if(s!==void 0){this.manager.itemStart(t),setTimeout(()=>{e&&e(s),this.manager.itemEnd(t)},0);return}if(Br[t]!==void 0){Br[t].push({onLoad:e,onProgress:i,onError:n});return}Br[t]=[],Br[t].push({onLoad:e,onProgress:i,onError:n});const r=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,c=this.responseType;fetch(r).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&Nt("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;const h=Br[t],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,p=f!==0;let g=0;const m=new ReadableStream({start(v){y();function y(){u.read().then(({done:x,value:M})=>{if(x)v.close();else{g+=M.byteLength;const b=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let S=0,E=h.length;S<E;S++){const w=h[S];w.onProgress&&w.onProgress(b)}v.enqueue(M),y()}},x=>{v.error(x)})}}});return new Response(m)}else throw new HA(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,a));case"json":return l.json();default:if(a==="")return l.text();{const u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return l.arrayBuffer().then(p=>f.decode(p))}}}).then(l=>{qr.add(`file:${t}`,l);const h=Br[t];delete Br[t];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{const h=Br[t];if(h===void 0)throw this.manager.itemError(t),l;delete Br[t];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onError&&f.onError(l)}this.manager.itemError(t)}).finally(()=>{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}const vc=new WeakMap;class GA extends Hh{constructor(t){super(t)}load(t,e,i,n){this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,r=qr.get(`image:${t}`);if(r!==void 0){if(r.complete===!0)s.manager.itemStart(t),setTimeout(function(){e&&e(r),s.manager.itemEnd(t)},0);else{let u=vc.get(r);u===void 0&&(u=[],vc.set(r,u)),u.push({onLoad:e,onError:n})}return r}const a=Ih("img");function c(){h(),e&&e(this);const u=vc.get(this)||[];for(let d=0;d<u.length;d++){const f=u[d];f.onLoad&&f.onLoad(this)}vc.delete(this),s.manager.itemEnd(t)}function l(u){h(),n&&n(u),qr.remove(`image:${t}`);const d=vc.get(this)||[];for(let f=0;f<d.length;f++){const p=d[f];p.onError&&p.onError(u)}vc.delete(this),s.manager.itemError(t),s.manager.itemEnd(t)}function h(){a.removeEventListener("load",c,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",c,!1),a.addEventListener("error",l,!1),t.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),qr.add(`image:${t}`,a),s.manager.itemStart(t),a.src=t,a}}class JO extends Hh{constructor(t){super(t)}load(t,e,i,n){const s=new Mn,r=new GA(this.manager);return r.setCrossOrigin(this.crossOrigin),r.setPath(this.path),r.load(t,function(a){s.image=a,s.needsUpdate=!0,e!==void 0&&e(s)},i,n),s}}class Pf extends bi{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new st(t),this.intensity=e}dispose(){this.dispatchEvent({type:"dispose"})}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,e}}class VA extends Pf{constructor(t,e,i){super(t,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.groundColor=new st(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}toJSON(t){const e=super.toJSON(t);return e.object.groundColor=this.groundColor.getHex(),e}}const L0=new he,oM=new R,cM=new R;class Fg{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new it(512,512),this.mapType=Hn,this.map=null,this.mapPass=null,this.matrix=new he,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Dg,this._frameExtents=new it(1,1),this._viewportCount=1,this._viewports=[new _e(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,i=this.matrix;oM.setFromMatrixPosition(t.matrixWorld),e.position.copy(oM),cM.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(cM),e.updateMatrixWorld(),L0.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(L0,e.coordinateSystem,e.reversedDepth),e.coordinateSystem===Rh||e.reversedDepth?i.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(L0)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.autoUpdate=t.autoUpdate,this.needsUpdate=t.needsUpdate,this.normalBias=t.normalBias,this.blurSamples=t.blurSamples,this.mapSize.copy(t.mapSize),this.biasNode=t.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){const t={};return this.intensity!==1&&(t.intensity=this.intensity),this.bias!==0&&(t.bias=this.bias),this.normalBias!==0&&(t.normalBias=this.normalBias),this.radius!==1&&(t.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}const Ru=new R,Iu=new ts,Qs=new R;class Dx extends bi{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new he,this.projectionMatrix=new he,this.projectionMatrixInverse=new he,this.coordinateSystem=Tr,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorld.decompose(Ru,Iu,Qs),Qs.x===1&&Qs.y===1&&Qs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ru,Iu,Qs.set(1,1,1)).invert()}updateWorldMatrix(t,e,i=!1){super.updateWorldMatrix(t,e,i),this.matrixWorld.decompose(Ru,Iu,Qs),Qs.x===1&&Qs.y===1&&Qs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ru,Iu,Qs.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const fa=new R,lM=new it,hM=new it;class jn extends Dx{constructor(t=50,e=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=dl*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(sh*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return dl*2*Math.atan(Math.tan(sh*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,i){fa.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(fa.x,fa.y).multiplyScalar(-t/fa.z),fa.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(fa.x,fa.y).multiplyScalar(-t/fa.z)}getViewSize(t,e){return this.getViewBounds(t,lM,hM),e.subVectors(hM,lM)}setViewOffset(t,e,i,n,s,r){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(sh*.5*this.fov)/this.zoom,i=2*e,n=this.aspect*i,s=-.5*n;const r=this.view;if(this.view!==null&&this.view.enabled){const c=r.fullWidth,l=r.fullHeight;s+=r.offsetX*n/c,e-=r.offsetY*i/l,n*=r.width/c,i*=r.height/l}const a=this.filmOffset;a!==0&&(s+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+n,e,e-i,t,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}class WA extends Fg{constructor(){super(new jn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(t){const e=this.camera,i=dl*2*t.angle*this.focus,n=this.mapSize.width/this.mapSize.height*this.aspect,s=t.distance||e.far;(i!==e.fov||n!==e.aspect||s!==e.far)&&(e.fov=i,e.aspect=n,e.far=s,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class jO extends Pf{constructor(t,e,i=0,n=Math.PI/3,s=0,r=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.target=new bi,this.distance=i,this.angle=n,this.penumbra=s,this.decay=r,this.map=null,this.shadow=new WA}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.map=t.map,this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.distance=this.distance,e.object.angle=this.angle,e.object.decay=this.decay,e.object.penumbra=this.penumbra,e.object.target=this.target.uuid,this.map&&this.map.isTexture&&(e.object.map=this.map.toJSON(t).uuid),e.object.shadow=this.shadow.toJSON(),e}}class XA extends Fg{constructor(){super(new jn(90,1,.5,500)),this.isPointLightShadow=!0}}class Cx extends Pf{constructor(t,e,i=0,n=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new XA}get power(){return this.intensity*4*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.distance=this.distance,e.object.decay=this.decay,e.object.shadow=this.shadow.toJSON(),e}}class Is extends Dx{constructor(t=-1,e=1,i=1,n=-1,s=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=i,this.bottom=n,this.near=s,this.far=r,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=t.view===null?null:Object.assign({},t.view),this}setViewOffset(t,e,i,n,s,r){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let s=i-t,r=i+t,a=n+e,c=n-e;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,r=s+l*this.view.width,a-=h*this.view.offsetY,c=a-h*this.view.height}this.projectionMatrix.makeOrthographic(s,r,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}}class $A extends Fg{constructor(){super(new Is(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class uM extends Pf{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.target=new bi,this.shadow=new $A}dispose(){super.dispose(),this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.shadow=this.shadow.toJSON(),e.object.target=this.target.uuid,e}}class QO{static extractUrlBase(t){const e=t.lastIndexOf("/");return e===-1?"./":t.slice(0,e+1)}static resolveURL(t,e){return typeof t!="string"||t===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class t8 extends ne{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}const N0=new WeakMap;class e8 extends Hh{constructor(t){super(t),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&Nt("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Nt("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(t){return this.options=t,this}load(t,e,i,n){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,r=qr.get(`image-bitmap:${t}`);if(r!==void 0){if(s.manager.itemStart(t),r.then){r.then(l=>{N0.has(r)===!0?(n&&n(N0.get(r)),s.manager.itemError(t),s.manager.itemEnd(t)):(e&&e(l),s.manager.itemEnd(t))});return}setTimeout(function(){e&&e(r),s.manager.itemEnd(t)},0);return}const a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const c=fetch(t,a).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(l){qr.add(`image-bitmap:${t}`,l),e&&e(l),s.manager.itemEnd(t)}).catch(function(l){n&&n(l),N0.set(c,l),qr.remove(`image-bitmap:${t}`),s.manager.itemError(t),s.manager.itemEnd(t)});qr.add(`image-bitmap:${t}`,c),s.manager.itemStart(t)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}const Mc=-90,yc=1;class zg extends bi{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new jn(Mc,yc,t,e);n.layers=this.layers,this.add(n);const s=new jn(Mc,yc,t,e);s.layers=this.layers,this.add(s);const r=new jn(Mc,yc,t,e);r.layers=this.layers,this.add(r);const a=new jn(Mc,yc,t,e);a.layers=this.layers,this.add(a);const c=new jn(Mc,yc,t,e);c.layers=this.layers,this.add(c);const l=new jn(Mc,yc,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,n,s,r,a,c]=e;for(const l of e)this.remove(l);if(t===Tr)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(t===Rh)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(const l of e)this.add(l),l.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[s,r,a,c,l,h]=this.children,u=t.getRenderTarget(),d=t.getActiveCubeFace(),f=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let m=!1;t.isWebGLRenderer===!0?m=t.state.buffers.depth.getReversed():m=t.reversedDepthBuffer,t.setRenderTarget(i,0,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,s),t.setRenderTarget(i,1,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,r),t.setRenderTarget(i,2,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,a),t.setRenderTarget(i,3,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,c),t.setRenderTarget(i,4,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,l),i.texture.generateMipmaps=g,t.setRenderTarget(i,5,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,h),t.setRenderTarget(u,d,f),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class YA extends jn{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class qA{constructor(t,e,i){this.binding=t,this.valueSize=i;let n,s,r;switch(e){case"quaternion":n=this._slerp,s=this._slerpAdditive,r=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":n=this._select,s=this._select,r=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:n=this._lerp,s=this._lerpAdditive,r=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=s,this._setIdentity=r,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(t,e){const i=this.buffer,n=this.valueSize,s=t*n+n;let r=this.cumulativeWeight;if(r===0){for(let a=0;a!==n;++a)i[s+a]=i[a];r=e}else{r+=e;const a=e/r;this._mixBufferRegion(i,s,0,a,n)}this.cumulativeWeight=r}accumulateAdditive(t){const e=this.buffer,i=this.valueSize,n=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(e,n,0,t,i),this.cumulativeWeightAdditive+=t}apply(t){const e=this.valueSize,i=this.buffer,n=t*e+e,s=this.cumulativeWeight,r=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){const c=e*this._origIndex;this._mixBufferRegion(i,n,c,1-s,e)}r>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*e,1,e);for(let c=e,l=e+e;c!==l;++c)if(i[c]!==i[c+e]){a.setValue(i,n);break}}saveOriginalState(){const t=this.binding,e=this.buffer,i=this.valueSize,n=i*this._origIndex;t.getValue(e,n);for(let s=i,r=n;s!==r;++s)e[s]=e[n+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=this.valueSize*3;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let i=t;i<e;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const t=this._origIndex*this.valueSize,e=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[e+i]=this.buffer[t+i]}_select(t,e,i,n,s){if(n>=.5)for(let r=0;r!==s;++r)t[e+r]=t[i+r]}_slerp(t,e,i,n){ts.slerpFlat(t,e,t,e,t,i,n)}_slerpAdditive(t,e,i,n,s){const r=this._workIndex*s;ts.multiplyQuaternionsFlat(t,r,t,e,t,i),ts.slerpFlat(t,e,t,e,t,r,n)}_lerp(t,e,i,n,s){const r=1-n;for(let a=0;a!==s;++a){const c=e+a;t[c]=t[c]*r+t[i+a]*n}}_lerpAdditive(t,e,i,n,s){for(let r=0;r!==s;++r){const a=e+r;t[a]=t[a]+t[i+r]*n}}}const Bg="\\[\\]\\.:\\/",KA=new RegExp("["+Bg+"]","g"),Hg="[^"+Bg+"]",ZA="[^"+Bg.replace("\\.","")+"]",JA=/((?:WC+[\/:])*)/.source.replace("WC",Hg),jA=/(WCOD+)?/.source.replace("WCOD",ZA),QA=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Hg),t_=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Hg),e_=new RegExp("^"+JA+jA+QA+t_+"$"),i_=["material","materials","bones","map"];class n_{constructor(t,e,i){const n=i||Ke.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,n)}getValue(t,e){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(t,e)}setValue(t,e){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,s=i.length;n!==s;++n)i[n].setValue(t,e)}bind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,i=t.length;e!==i;++e)t[e].bind()}unbind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,i=t.length;e!==i;++e)t[e].unbind()}}class Ke{constructor(t,e,i){this.path=e,this.parsedPath=i||Ke.parseTrackName(e),this.node=Ke.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,i){return t&&t.isAnimationObjectGroup?new Ke.Composite(t,e,i):new Ke(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(KA,"")}static parseTrackName(t){const e=e_.exec(t);if(e===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+t);const i={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const s=i.nodeName.substring(n+1);i_.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,e){if(e===void 0||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){const i=t.skeleton.getBoneByName(e);if(i!==void 0)return i}if(t.children){const i=function(s){for(let r=0;r<s.length;r++){const a=s[r];if(a.name===e||a.uuid===e)return a;const c=i(a.children);if(c)return c}return null},n=i(t.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)t[e++]=i[n]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++]}_setValue_array_setNeedsUpdate(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node;const e=this.parsedPath,i=e.objectName,n=e.propertyName;let s=e.propertyIndex;if(t||(t=Ke.findNode(this.rootNode,e.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){Nt("PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let l=e.objectIndex;switch(i){case"materials":if(!t.material){te("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.materials){te("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}t=t.material.materials;break;case"bones":if(!t.skeleton){te("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}t=t.skeleton.bones;for(let h=0;h<t.length;h++)if(t[h].name===l){l=h;break}break;case"map":if("map"in t){t=t.map;break}if(!t.material){te("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.map){te("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}t=t.material.map;break;default:if(t[i]===void 0){te("PropertyBinding: Can not bind to objectName of node undefined.",this);return}t=t[i]}if(l!==void 0){if(t[l]===void 0){te("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);return}t=t[l]}}const r=t[n];if(r===void 0){const l=e.nodeName;te("PropertyBinding: Trying to update property for track: "+l+"."+n+" but it wasn't found.",t);return}let a=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?a=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(a=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(s!==void 0){if(n==="morphTargetInfluences"){if(!t.geometry){te("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!t.geometry.morphAttributes){te("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}t.morphTargetDictionary[s]!==void 0&&(s=t.morphTargetDictionary[s])}c=this.BindingType.ArrayElement,this.resolvedProperty=r,this.propertyIndex=s}else r.fromArray!==void 0&&r.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=r):Array.isArray(r)?(c=this.BindingType.EntireArray,this.resolvedProperty=r):this.propertyName=n;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Ke.Composite=n_;Ke.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};Ke.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};Ke.prototype.GetterByBindingType=[Ke.prototype._getValue_direct,Ke.prototype._getValue_array,Ke.prototype._getValue_arrayElement,Ke.prototype._getValue_toArray];Ke.prototype.SetterByBindingTypeAndVersioning=[[Ke.prototype._setValue_direct,Ke.prototype._setValue_direct_setNeedsUpdate,Ke.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_array,Ke.prototype._setValue_array_setNeedsUpdate,Ke.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_arrayElement,Ke.prototype._setValue_arrayElement_setNeedsUpdate,Ke.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_fromArray,Ke.prototype._setValue_fromArray_setNeedsUpdate,Ke.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class s_{constructor(t,e,i=null,n=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=i,this.blendMode=n;const s=e.tracks,r=s.length,a=new Array(r),c={endingStart:Nc,endingEnd:Nc};for(let l=0;l!==r;++l){const h=s[l].createInterpolant(null);a[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=a,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=zE,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,i=!1){if(t.fadeOut(e),this.fadeIn(e),i===!0){const n=this._clip.duration,s=t._clip.duration,r=s/n,a=n/s;t._restoreTimeScale=t.timeScale,this._restoreTimeScale=this.timeScale,t.warp(1,r,e),this.warp(a,1,e)}return this}crossFadeTo(t,e,i=!1){return t.crossFadeFrom(this,e,i)}stopFading(){const t=this._weightInterpolant;return t!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,i){const n=this._mixer,s=n.time,r=this.timeScale;let a=this._timeScaleInterpolant;a===null&&(a=n._lendControlInterpolant(),this._timeScaleInterpolant=a);const c=a.parameterPositions,l=a.sampleValues;return c[0]=s,c[1]=s+i,l[0]=t/r,l[1]=e/r,this}stopWarping(){const t=this._timeScaleInterpolant;return t!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,i,n){if(!this.enabled){this._updateWeight(t);return}const s=this._startTime;if(s!==null){const c=(t-s)*i;c<0||i===0?e=0:(this._startTime=null,e=i*c)}e*=this._updateTimeScale(t);const r=this._updateTime(e),a=this._updateWeight(t);if(a>0){const c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case HE:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(r),l[h].accumulateAdditive(a);break;case wg:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(r),l[h].accumulate(n,a)}}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(e===0?this.paused=!0:(this._restoreTimeScale!==null&&(e=this._restoreTimeScale),this.timeScale=e),this.stopWarping())}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,i=this.loop;let n=this.time+t,s=this._loopCount;const r=i===BE;if(t===0)return s===-1?n:r&&(s&1)===1?e-n:n;if(i===rx){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(n>=e)n=e;else if(n<0)n=0;else{this.time=n;break t}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(s===-1&&(t>=0?(s=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),n>=e||n<0){const a=Math.floor(n/e);n-=e*a,s+=Math.abs(a);const c=this.repetitions-s;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=t>0?e:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(c===1){const l=t<0;this._setEndings(l,!l,r)}else this._setEndings(!1,!1,r);this._loopCount=s,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this._loopCount=s,this.time=n;if(r&&(s&1)===1)return e-n}return n}_setEndings(t,e,i){const n=this._interpolantSettings;i?(n.endingStart=kc,n.endingEnd=kc):(t?n.endingStart=this.zeroSlopeAtStart?kc:Nc:n.endingStart=qd,e?n.endingEnd=this.zeroSlopeAtEnd?kc:Nc:n.endingEnd=qd)}_scheduleFading(t,e,i){const n=this._mixer,s=n.time;let r=this._weightInterpolant;r===null&&(r=n._lendControlInterpolant(),this._weightInterpolant=r);const a=r.parameterPositions,c=r.sampleValues;return a[0]=s,c[0]=e,a[1]=s+t,c[1]=i,this}}const r_=new Float32Array(1);class a_ extends Ha{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(t,e){const i=t._localRoot||this._root,n=t._clip.tracks,s=n.length,r=t._propertyBindings,a=t._interpolants,c=i.uuid,l=this._bindingsByRootAndName;let h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==s;++u){const d=n[u],f=d.name;let p=h[f];if(p!==void 0)++p.referenceCount,r[u]=p;else{if(p=r[u],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,c,f));continue}const g=e&&e._propertyBindings[u].binding.parsedPath;p=new qA(Ke.create(i,f,g),d.ValueTypeName,d.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,c,f),r[u]=p}a[u].resultBuffer=p.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(t._cacheIndex===null){const i=(t._localRoot||this._root).uuid,n=t._clip.uuid,s=this._actionsByClip[n];this._bindAction(t,s&&s.knownActions[0]),this._addInactiveAction(t,n,i)}const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return e!==null&&e<this._nActiveActions}_addInactiveAction(t,e,i){const n=this._actions,s=this._actionsByClip;let r=s[e];if(r===void 0)r={knownActions:[t],actionByRoot:{}},t._byClipCacheIndex=0,s[e]=r;else{const a=r.knownActions;t._byClipCacheIndex=a.length,a.push(t)}t._cacheIndex=n.length,n.push(t),r.actionByRoot[i]=t}_removeInactiveAction(t){const e=this._actions,i=e[e.length-1],n=t._cacheIndex;i._cacheIndex=n,e[n]=i,e.pop(),t._cacheIndex=null;const s=t._clip.uuid,r=this._actionsByClip,a=r[s],c=a.knownActions,l=c[c.length-1],h=t._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),t._byClipCacheIndex=null;const u=a.actionByRoot,d=(t._localRoot||this._root).uuid;delete u[d],c.length===0&&delete r[s],this._removeInactiveBindingsForAction(t)}_removeInactiveBindingsForAction(t){const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(t){const e=this._actions,i=t._cacheIndex,n=this._nActiveActions++,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_takeBackAction(t){const e=this._actions,i=t._cacheIndex,n=--this._nActiveActions,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_addInactiveBinding(t,e,i){const n=this._bindingsByRootAndName,s=this._bindings;let r=n[e];r===void 0&&(r={},n[e]=r),r[i]=t,t._cacheIndex=s.length,s.push(t)}_removeInactiveBinding(t){const e=this._bindings,i=t.binding,n=i.rootNode.uuid,s=i.path,r=this._bindingsByRootAndName,a=r[n],c=e[e.length-1],l=t._cacheIndex;c._cacheIndex=l,e[l]=c,e.pop(),delete a[s],Object.keys(a).length===0&&delete r[n]}_lendBinding(t){const e=this._bindings,i=t._cacheIndex,n=this._nActiveBindings++,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_takeBackBinding(t){const e=this._bindings,i=t._cacheIndex,n=--this._nActiveBindings,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_lendControlInterpolant(){const t=this._controlInterpolants,e=this._nActiveControlInterpolants++;let i=t[e];return i===void 0&&(i=new Tx(new Float32Array(2),new Float32Array(2),1,r_),i.__cacheIndex=e,t[e]=i),i}_takeBackControlInterpolant(t){const e=this._controlInterpolants,i=t.__cacheIndex,n=--this._nActiveControlInterpolants,s=e[n];t.__cacheIndex=n,e[n]=t,s.__cacheIndex=i,e[i]=s}clipAction(t,e,i){const n=e||this._root,s=n.uuid;let r=typeof t=="string"?rM.findByName(n,t):t;const a=r!==null?r.uuid:t,c=this._actionsByClip[a];let l=null;if(i===void 0&&(r!==null?i=r.blendMode:i=wg),c!==void 0){const u=c.actionByRoot[s];if(u!==void 0&&u.blendMode===i)return u;l=c.knownActions[0],r===null&&(r=l._clip)}if(r===null)return null;const h=new s_(this,r,e,i);return this._bindAction(h,l),this._addInactiveAction(h,a,s),h}existingAction(t,e){const i=e||this._root,n=i.uuid,s=typeof t=="string"?rM.findByName(i,t):t,r=s?s.uuid:t,a=this._actionsByClip[r];return a!==void 0&&a.actionByRoot[n]||null}stopAllAction(){const t=this._actions,e=this._nActiveActions;for(let i=e-1;i>=0;--i)t[i].stop();return this}update(t){t*=this.timeScale;const e=this._actions,i=this._nActiveActions,n=this.time+=t,s=Math.sign(t),r=this._accuIndex^=1;for(let l=0;l!==i;++l)e[l]._update(n,t,s,r);const a=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)a[l].apply(r);return this}setTime(t){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(t)}getRoot(){return this._root}uncacheClip(t){const e=this._actions,i=t.uuid,n=this._actionsByClip,s=n[i];if(s!==void 0){const r=s.knownActions;for(let a=0,c=r.length;a!==c;++a){const l=r[a];this._deactivateAction(l);const h=l._cacheIndex,u=e[e.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=h,e[h]=u,e.pop(),this._removeInactiveBindingsForAction(l)}delete n[i]}}uncacheRoot(t){const e=t.uuid,i=this._actionsByClip;for(const r in i){const a=i[r].actionByRoot,c=a[e];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}const n=this._bindingsByRootAndName,s=n[e];if(s!==void 0)for(const r in s){const a=s[r];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(t,e){const i=this.existingAction(t,e);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class i8 extends ux{constructor(t,e,i=1){super(t,e),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=i}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}}const dM=new he;class fd{constructor(t,e,i=0,n=1/0){this.ray=new zh(t,e),this.near=i,this.far=n,this.camera=null,this.layers=new Tg,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,e.projectionMatrix.elements[14]).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):te("Raycaster: Unsupported camera type: "+e.type)}setFromXRController(t){return dM.identity().extractRotation(t.matrixWorld),this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(dM),this}intersectObject(t,e=!0,i=[]){return Am(t,this,i,e),i.sort(fM),i}intersectObjects(t,e=!0,i=[]){for(let n=0,s=t.length;n<s;n++)Am(t[n],this,i,e);return i.sort(fM),i}}function fM(o,t){return o.distance-t.distance}function Am(o,t,e,i){let n=!0;if(o.layers.test(t.layers)&&o.raycast(t,e)===!1&&(n=!1),n===!0&&i===!0){const s=o.children;for(let r=0,a=s.length;r<a;r++)Am(s[r],t,e,!0)}}class Ox{static{Ox.prototype.isMatrix2=!0}constructor(t,e,i,n){this.elements=[1,0,0,1],t!==void 0&&this.set(t,e,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(t,e=0){for(let i=0;i<4;i++)this.elements[i]=t[i+e];return this}set(t,e,i,n){const s=this.elements;return s[0]=t,s[2]=e,s[1]=i,s[3]=n,this}}const pM=new R,Du=new R,xc=new R,bc=new R,k0=new R,o_=new R,c_=new R;class n8{constructor(t=new R,e=new R){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){pM.subVectors(t,this.start),Du.subVectors(this.end,this.start);const i=Du.dot(Du);if(i===0)return 0;let s=Du.dot(pM)/i;return e&&(s=oe(s,0,1)),s}closestPointToPoint(t,e,i){const n=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(n).add(this.start)}distanceSqToLine3(t,e=o_,i=c_){const n=10000000000000001e-32;let s,r;const a=this.start,c=t.start,l=this.end,h=t.end;xc.subVectors(l,a),bc.subVectors(h,c),k0.subVectors(a,c);const u=xc.dot(xc),d=bc.dot(bc),f=bc.dot(k0);if(u<=n&&d<=n)return e.copy(a),i.copy(c),e.sub(i),e.dot(e);if(u<=n)s=0,r=f/d,r=oe(r,0,1);else{const p=xc.dot(k0);if(d<=n)r=0,s=oe(-p/u,0,1);else{const g=xc.dot(bc),m=u*d-g*g;m!==0?s=oe((g*f-p*d)/m,0,1):s=0,r=(g*s+f)/d,r<0?(r=0,s=oe(-p/u,0,1)):r>1&&(r=1,s=oe((g-p)/u,0,1))}}return e.copy(a).addScaledVector(xc,s),i.copy(c).addScaledVector(bc,r),e.distanceToSquared(i)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}function mM(o,t,e,i){const n=l_(i);switch(e){case nx:return o*t;case ul:return o*t/n.components*n.byteLength;case yg:return o*t/n.components*n.byteLength;case Go:return o*t*2/n.components*n.byteLength;case xg:return o*t*2/n.components*n.byteLength;case sx:return o*t*3/n.components*n.byteLength;case Ki:return o*t*4/n.components*n.byteLength;case bg:return o*t*4/n.components*n.byteLength;case cd:case ld:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*8;case hd:case ud:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case Vp:case Xp:return Math.max(o,16)*Math.max(t,8)/4;case Gp:case Wp:return Math.max(o,8)*Math.max(t,8)/2;case $p:case Yp:case Kp:case Zp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*8;case qp:case Xd:case Jp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case jp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case Qp:return Math.floor((o+4)/5)*Math.floor((t+3)/4)*16;case tm:return Math.floor((o+4)/5)*Math.floor((t+4)/5)*16;case em:return Math.floor((o+5)/6)*Math.floor((t+4)/5)*16;case im:return Math.floor((o+5)/6)*Math.floor((t+5)/6)*16;case nm:return Math.floor((o+7)/8)*Math.floor((t+4)/5)*16;case sm:return Math.floor((o+7)/8)*Math.floor((t+5)/6)*16;case rm:return Math.floor((o+7)/8)*Math.floor((t+7)/8)*16;case am:return Math.floor((o+9)/10)*Math.floor((t+4)/5)*16;case om:return Math.floor((o+9)/10)*Math.floor((t+5)/6)*16;case cm:return Math.floor((o+9)/10)*Math.floor((t+7)/8)*16;case lm:return Math.floor((o+9)/10)*Math.floor((t+9)/10)*16;case hm:return Math.floor((o+11)/12)*Math.floor((t+9)/10)*16;case um:return Math.floor((o+11)/12)*Math.floor((t+11)/12)*16;case dm:case fm:case pm:return Math.ceil(o/4)*Math.ceil(t/4)*16;case mm:case gm:return Math.ceil(o/4)*Math.ceil(t/4)*8;case $d:case vm:return Math.ceil(o/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function l_(o){switch(o){case Hn:case Qy:return{byteLength:1,components:1};case _h:case tx:case Be:return{byteLength:2,components:1};case vg:case Mg:return{byteLength:2,components:4};case Ts:case gg:case Dn:return{byteLength:4,components:1};case ex:case ix:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${o}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:pg}}));typeof window<"u"&&(window.__THREE__?Nt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=pg);/**
|
|
2412
|
+
}`;class Se extends Pr{constructor(t){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=_A,this.fragmentShader=TA,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,t!==void 0&&this.setValues(t)}copy(t){return super.copy(t),this.fragmentShader=t.fragmentShader,this.vertexShader=t.vertexShader,this.uniforms=pl(t.uniforms),this.uniformsGroups=EA(t.uniformsGroups),this.defines=Object.assign({},t.defines),this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.fog=t.fog,this.lights=t.lights,this.clipping=t.clipping,this.extensions=Object.assign({},t.extensions),this.glslVersion=t.glslVersion,this.defaultAttributeValues=Object.assign({},t.defaultAttributeValues),this.index0AttributeName=t.index0AttributeName,this.uniformsNeedUpdate=t.uniformsNeedUpdate,this}toJSON(t){const e=super.toJSON(t);e.glslVersion=this.glslVersion,e.uniforms={};for(const n in this.uniforms){const r=this.uniforms[n].value;r&&r.isTexture?e.uniforms[n]={type:"t",value:r.toJSON(t).uuid}:r&&r.isColor?e.uniforms[n]={type:"c",value:r.getHex()}:r&&r.isVector2?e.uniforms[n]={type:"v2",value:r.toArray()}:r&&r.isVector3?e.uniforms[n]={type:"v3",value:r.toArray()}:r&&r.isVector4?e.uniforms[n]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?e.uniforms[n]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?e.uniforms[n]={type:"m4",value:r.toArray()}:e.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const i={};for(const n in this.extensions)this.extensions[n]===!0&&(i[n]=!0);return Object.keys(i).length>0&&(e.extensions=i),e}fromJSON(t,e){if(super.fromJSON(t,e),t.uniforms!==void 0)for(const i in t.uniforms){const n=t.uniforms[i];switch(this.uniforms[i]={},n.type){case"t":this.uniforms[i].value=e[n.value]||null;break;case"c":this.uniforms[i].value=new st().setHex(n.value);break;case"v2":this.uniforms[i].value=new it().fromArray(n.value);break;case"v3":this.uniforms[i].value=new R().fromArray(n.value);break;case"v4":this.uniforms[i].value=new _e().fromArray(n.value);break;case"m3":this.uniforms[i].value=new ie().fromArray(n.value);break;case"m4":this.uniforms[i].value=new he().fromArray(n.value);break;default:this.uniforms[i].value=n.value}}if(t.defines!==void 0&&(this.defines=t.defines),t.vertexShader!==void 0&&(this.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(this.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(this.glslVersion=t.glslVersion),t.extensions!==void 0)for(const i in t.extensions)this.extensions[i]=t.extensions[i];return t.lights!==void 0&&(this.lights=t.lights),t.clipping!==void 0&&(this.clipping=t.clipping),this}}class _x extends Se{constructor(t){super(t),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ia extends Pr{constructor(t){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new st(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new st(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Kd,this.normalScale=new it(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={STANDARD:""},this.color.copy(t.color),this.roughness=t.roughness,this.metalness=t.metalness,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.roughnessMap=t.roughnessMap,this.metalnessMap=t.metalnessMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.envMapIntensity=t.envMapIntensity,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class RA extends Ia{constructor(t){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new it(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return oe(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new st(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new st(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new st(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(t)}get anisotropy(){return this._anisotropy}set anisotropy(t){this._anisotropy>0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class Rs extends Pr{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new st(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new st(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Kd,this.normalScale=new it(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new jr,this.combine=mg,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.envMapIntensity=t.envMapIntensity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class IA extends Pr{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=GE,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class DA extends Pr{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Tu(o,t){return!o||o.constructor===t?o:typeof t.BYTES_PER_ELEMENT=="number"?new t(o):Array.prototype.slice.call(o)}function CA(o){function t(n,s){return o[n]-o[s]}const e=o.length,i=new Array(e);for(let n=0;n!==e;++n)i[n]=n;return i.sort(t),i}function sM(o,t,e){const i=o.length,n=new o.constructor(i);for(let s=0,r=0;r!==i;++s){const a=e[s]*t;for(let c=0;c!==t;++c)n[r++]=o[a+c]}return n}function OA(o,t,e,i){let n=1,s=o[0];for(;s!==void 0&&s[i]===void 0;)s=o[n++];if(s===void 0)return;let r=s[i];if(r!==void 0)if(Array.isArray(r))do r=s[i],r!==void 0&&(t.push(s.time),e.push(...r)),s=o[n++];while(s!==void 0);else if(r.toArray!==void 0)do r=s[i],r!==void 0&&(t.push(s.time),r.toArray(e,e.length)),s=o[n++];while(s!==void 0);else do r=s[i],r!==void 0&&(t.push(s.time),e.push(r)),s=o[n++];while(s!==void 0)}class Bh{constructor(t,e,i,n){this.parameterPositions=t,this._cachedIndex=0,this.resultBuffer=n!==void 0?n:new e.constructor(i),this.sampleValues=e,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(t){const e=this.parameterPositions;let i=this._cachedIndex,n=e[i],s=e[i-1];t:{e:{let r;i:{n:if(!(t<n)){for(let a=i+2;;){if(n===void 0){if(t<s)break n;return i=e.length,this._cachedIndex=i,this.copySampleValue_(i-1)}if(i===a)break;if(s=n,n=e[++i],t<n)break e}r=e.length;break i}if(!(t>=s)){const a=e[1];t<a&&(i=2,s=a);for(let c=i-2;;){if(s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===c)break;if(n=s,s=e[--i-1],t>=s)break e}r=i,i=0;break i}break t}for(;i<r;){const a=i+r>>>1;t<e[a]?r=a:i=a+1}if(n=e[i],s=e[i-1],s===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(n===void 0)return i=e.length,this._cachedIndex=i,this.copySampleValue_(i-1)}this._cachedIndex=i,this.intervalChanged_(i,s,n)}return this.interpolate_(i,s,t,n)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(t){const e=this.resultBuffer,i=this.sampleValues,n=this.valueSize,s=t*n;for(let r=0;r!==n;++r)e[r]=i[s+r];return e}interpolate_(){throw new Error("THREE.Interpolant: Call to abstract method.")}intervalChanged_(){}}class PA extends Bh{constructor(t,e,i,n){super(t,e,i,n),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Nc,endingEnd:Nc}}intervalChanged_(t,e,i){const n=this.parameterPositions;let s=t-2,r=t+1,a=n[s],c=n[r];if(a===void 0)switch(this.getSettings_().endingStart){case kc:s=t,a=2*e-i;break;case qd:s=n.length-2,a=e+n[s]-n[s+1];break;default:s=t,a=i}if(c===void 0)switch(this.getSettings_().endingEnd){case kc:r=t,c=2*i-e;break;case qd:r=1,c=i+n[1]-n[0];break;default:r=t-1,c=e}const l=(i-e)*.5,h=this.valueSize;this._weightPrev=l/(e-a),this._weightNext=l/(c-i),this._offsetPrev=s*h,this._offsetNext=r*h}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,p=(i-e)/(n-e),g=p*p,m=g*p,v=-d*m+2*d*g-d*p,y=(1+d)*m+(-1.5-2*d)*g+(-.5+d)*p+1,x=(-1-f)*m+(1.5+f)*g+.5*p,M=f*m-f*g;for(let b=0;b!==a;++b)s[b]=v*r[h+b]+y*r[l+b]+x*r[c+b]+M*r[u+b];return s}}class Tx extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=(i-e)/(n-e),u=1-h;for(let d=0;d!==a;++d)s[d]=r[l+d]*u+r[c+d]*h;return s}}class LA extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t){return this.copySampleValue_(t-1)}}class NA extends Bh{interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=t*a,l=c-a,h=this.inTangents,u=this.outTangents;if(!h||!u){const p=(i-e)/(n-e),g=1-p;for(let m=0;m!==a;++m)s[m]=r[l+m]*g+r[c+m]*p;return s}const d=a*2,f=t-1;for(let p=0;p!==a;++p){const g=r[l+p],m=r[c+p],v=f*d+p*2,y=u[v],x=u[v+1],M=t*d+p*2,b=h[M],S=h[M+1];let E=(i-e)/(n-e),w,_,D,I,O;for(let L=0;L<8;L++){w=E*E,_=w*E,D=1-E,I=D*D,O=I*D;const P=O*e+3*I*E*y+3*D*w*b+_*n-i;if(Math.abs(P)<1e-10)break;const z=3*I*(y-e)+6*D*E*(b-y)+3*w*(n-b);if(Math.abs(z)<1e-10)break;E=E-P/z,E=Math.max(0,Math.min(1,E))}s[p]=O*g+3*I*E*x+3*D*w*S+_*m}return s}}class qs{constructor(t,e,i,n){if(t===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(e===void 0||e.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+t);this.name=t,this.times=Tu(e,this.TimeBufferType),this.values=Tu(i,this.ValueBufferType),this.setInterpolation(n||this.DefaultInterpolation)}static toJSON(t){const e=t.constructor;let i;if(e.toJSON!==this.toJSON)i=e.toJSON(t);else{i={name:t.name,times:Tu(t.times,Array),values:Tu(t.values,Array)};const n=t.getInterpolation();n!==t.DefaultInterpolation&&(i.interpolation=n)}return i.type=t.ValueTypeName,i}InterpolantFactoryMethodDiscrete(t){return new LA(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodLinear(t){return new Tx(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodSmooth(t){return new PA(this.times,this.values,this.getValueSize(),t)}InterpolantFactoryMethodBezier(t){const e=new NA(this.times,this.values,this.getValueSize(),t);return this.settings&&(e.inTangents=this.settings.inTangents,e.outTangents=this.settings.outTangents),e}setInterpolation(t){let e;switch(t){case Yd:e=this.InterpolantFactoryMethodDiscrete;break;case Mm:e=this.InterpolantFactoryMethodLinear;break;case s0:e=this.InterpolantFactoryMethodSmooth;break;case pv:e=this.InterpolantFactoryMethodBezier;break}if(e===void 0){const i="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(t!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(i);return Nt("KeyframeTrack:",i),this}return this.createInterpolant=e,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Yd;case this.InterpolantFactoryMethodLinear:return Mm;case this.InterpolantFactoryMethodSmooth:return s0;case this.InterpolantFactoryMethodBezier:return pv}}getValueSize(){return this.values.length/this.times.length}shift(t){if(t!==0){const e=this.times;for(let i=0,n=e.length;i!==n;++i)e[i]+=t}return this}scale(t){if(t!==1){const e=this.times;for(let i=0,n=e.length;i!==n;++i)e[i]*=t}return this}trim(t,e){const i=this.times,n=i.length;let s=0,r=n-1;for(;s!==n&&i[s]<t;)++s;for(;r!==-1&&i[r]>e;)--r;if(++r,s!==0||r!==n){s>=r&&(r=Math.max(r,1),s=r-1);const a=this.getValueSize();this.times=i.slice(s,r),this.values=this.values.slice(s*a,r*a)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!==0&&(te("KeyframeTrack: Invalid value size in track.",this),t=!1);const i=this.times,n=this.values,s=i.length;s===0&&(te("KeyframeTrack: Track is empty.",this),t=!1);let r=null;for(let a=0;a!==s;a++){const c=i[a];if(typeof c=="number"&&isNaN(c)){te("KeyframeTrack: Time is not a valid number.",this,a,c),t=!1;break}if(r!==null&&r>c){te("KeyframeTrack: Out of order keys.",this,a,c,r),t=!1;break}r=c}if(n!==void 0&&JE(n))for(let a=0,c=n.length;a!==c;++a){const l=n[a];if(isNaN(l)){te("KeyframeTrack: Value is not a valid number.",this,a,l),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),i=this.getValueSize(),n=this.getInterpolation()===s0,s=t.length-1;let r=1;for(let a=1;a<s;++a){let c=!1;const l=t[a],h=t[a+1];if(l!==h&&(a!==1||l!==t[0]))if(n)c=!0;else{const u=a*i,d=u-i,f=u+i;for(let p=0;p!==i;++p){const g=e[u+p];if(g!==e[d+p]||g!==e[f+p]){c=!0;break}}}if(c){if(a!==r){t[r]=t[a];const u=a*i,d=r*i;for(let f=0;f!==i;++f)e[d+f]=e[u+f]}++r}}if(s>0){t[r]=t[s];for(let a=s*i,c=r*i,l=0;l!==i;++l)e[c+l]=e[a+l];++r}return r!==t.length?(this.times=t.slice(0,r),this.values=e.slice(0,r*i)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),i=this.constructor,n=new i(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}qs.prototype.ValueTypeName="";qs.prototype.TimeBufferType=Float32Array;qs.prototype.ValueBufferType=Float32Array;qs.prototype.DefaultInterpolation=Mm;class Ml extends qs{constructor(t,e,i){super(t,e,i)}}Ml.prototype.ValueTypeName="bool";Ml.prototype.ValueBufferType=Array;Ml.prototype.DefaultInterpolation=Yd;Ml.prototype.InterpolantFactoryMethodLinear=void 0;Ml.prototype.InterpolantFactoryMethodSmooth=void 0;class Rx extends qs{constructor(t,e,i,n){super(t,e,i,n)}}Rx.prototype.ValueTypeName="color";class kg extends qs{constructor(t,e,i,n){super(t,e,i,n)}}kg.prototype.ValueTypeName="number";class kA extends Bh{constructor(t,e,i,n){super(t,e,i,n)}interpolate_(t,e,i,n){const s=this.resultBuffer,r=this.sampleValues,a=this.valueSize,c=(i-e)/(n-e);let l=t*a;for(let h=l+a;l!==h;l+=4)ts.slerpFlat(s,0,r,l-a,r,l,c);return s}}class Ug extends qs{constructor(t,e,i,n){super(t,e,i,n)}InterpolantFactoryMethodLinear(t){return new kA(this.times,this.values,this.getValueSize(),t)}}Ug.prototype.ValueTypeName="quaternion";Ug.prototype.InterpolantFactoryMethodSmooth=void 0;class yl extends qs{constructor(t,e,i){super(t,e,i)}}yl.prototype.ValueTypeName="string";yl.prototype.ValueBufferType=Array;yl.prototype.DefaultInterpolation=Yd;yl.prototype.InterpolantFactoryMethodLinear=void 0;yl.prototype.InterpolantFactoryMethodSmooth=void 0;class Ix extends qs{constructor(t,e,i,n){super(t,e,i,n)}}Ix.prototype.ValueTypeName="vector";class rM{constructor(t="",e=-1,i=[],n=wg){this.name=t,this.tracks=i,this.duration=e,this.blendMode=n,this.uuid=_s(),this.userData={},this.duration<0&&this.resetDuration()}static parse(t){const e=[],i=t.tracks,n=1/(t.fps||1);for(let r=0,a=i.length;r!==a;++r)e.push(FA(i[r]).scale(n));const s=new this(t.name,t.duration,e,t.blendMode);return s.uuid=t.uuid,s.userData=JSON.parse(t.userData||"{}"),s}static toJSON(t){const e=[],i=t.tracks,n={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode,userData:JSON.stringify(t.userData)};for(let s=0,r=i.length;s!==r;++s)e.push(qs.toJSON(i[s]));return n}static CreateFromMorphTargetSequence(t,e,i,n){const s=e.length,r=[];for(let a=0;a<s;a++){let c=[],l=[];c.push((a+s-1)%s,a,(a+1)%s),l.push(0,1,0);const h=CA(c);c=sM(c,1,h),l=sM(l,1,h),!n&&c[0]===0&&(c.push(s),l.push(l[0])),r.push(new kg(".morphTargetInfluences["+e[a].name+"]",c,l).scale(1/i))}return new this(t,-1,r)}static findByName(t,e){let i=t;if(!Array.isArray(t)){const n=t;i=n.geometry&&n.geometry.animations||n.animations}for(let n=0;n<i.length;n++)if(i[n].name===e)return i[n];return null}static CreateClipsFromMorphTargetSequences(t,e,i){const n={},s=/^([\w-]*?)([\d]+)$/;for(let a=0,c=t.length;a<c;a++){const l=t[a],h=l.name.match(s);if(h&&h.length>1){const u=h[1];let d=n[u];d||(n[u]=d=[]),d.push(l)}}const r=[];for(const a in n)r.push(this.CreateFromMorphTargetSequence(a,n[a],e,i));return r}resetDuration(){const t=this.tracks;let e=0;for(let i=0,n=t.length;i!==n;++i){const s=this.tracks[i];e=Math.max(e,s.times[s.times.length-1])}return this.duration=e,this}trim(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].trim(0,this.duration);return this}validate(){let t=!0;for(let e=0;e<this.tracks.length;e++)t=t&&this.tracks[e].validate();return t}optimize(){for(let t=0;t<this.tracks.length;t++)this.tracks[t].optimize();return this}clone(){const t=[];for(let i=0;i<this.tracks.length;i++)t.push(this.tracks[i].clone());const e=new this.constructor(this.name,this.duration,t,this.blendMode);return e.userData=JSON.parse(JSON.stringify(this.userData)),e}toJSON(){return this.constructor.toJSON(this)}}function UA(o){switch(o.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return kg;case"vector":case"vector2":case"vector3":case"vector4":return Ix;case"color":return Rx;case"quaternion":return Ug;case"bool":case"boolean":return Ml;case"string":return yl}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+o)}function FA(o){if(o.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");const t=UA(o.type);if(o.times===void 0){const e=[],i=[];OA(o.keys,e,i,"value"),o.times=e,o.values=i}return t.parse!==void 0?t.parse(o):new t(o.name,o.times,o.values,o.interpolation)}const qr={enabled:!1,files:{},add:function(o,t){this.enabled!==!1&&(aM(o)||(this.files[o]=t))},get:function(o){if(this.enabled!==!1&&!aM(o))return this.files[o]},remove:function(o){delete this.files[o]},clear:function(){this.files={}}};function aM(o){try{const t=o.slice(o.indexOf(":")+1);return new URL(t).protocol==="blob:"}catch{return!1}}class zA{constructor(t,e,i){const n=this;let s=!1,r=0,a=0,c;const l=[];this.onStart=void 0,this.onLoad=t,this.onProgress=e,this.onError=i,this._abortController=null,this.itemStart=function(h){a++,s===!1&&n.onStart!==void 0&&n.onStart(h,r,a),s=!0},this.itemEnd=function(h){r++,n.onProgress!==void 0&&n.onProgress(h,r,a),r===a&&(s=!1,n.onLoad!==void 0&&n.onLoad())},this.itemError=function(h){n.onError!==void 0&&n.onError(h)},this.resolveURL=function(h){return h=h.normalize("NFC"),c?c(h):h},this.setURLModifier=function(h){return c=h,this},this.addHandler=function(h,u){return l.push(h,u),this},this.removeHandler=function(h){const u=l.indexOf(h);return u!==-1&&l.splice(u,2),this},this.getHandler=function(h){for(let u=0,d=l.length;u<d;u+=2){const f=l[u],p=l[u+1];if(f.global&&(f.lastIndex=0),f.test(h))return p}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const BA=new zA;class Hh{constructor(t){this.manager=t!==void 0?t:BA,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(t,e){const i=this;return new Promise(function(n,s){i.load(t,n,e,s)})}parse(){}setCrossOrigin(t){return this.crossOrigin=t,this}setWithCredentials(t){return this.withCredentials=t,this}setPath(t){return this.path=t,this}setResourcePath(t){return this.resourcePath=t,this}setRequestHeader(t){return this.requestHeader=t,this}abort(){return this}}Hh.DEFAULT_MATERIAL_NAME="__DEFAULT";const Br={};class HA extends Error{constructor(t,e){super(t),this.response=e}}class JO extends Hh{constructor(t){super(t),this.mimeType="",this.responseType="",this._abortController=new AbortController}load(t,e,i,n){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=qr.get(`file:${t}`);if(s!==void 0){this.manager.itemStart(t),setTimeout(()=>{e&&e(s),this.manager.itemEnd(t)},0);return}if(Br[t]!==void 0){Br[t].push({onLoad:e,onProgress:i,onError:n});return}Br[t]=[],Br[t].push({onLoad:e,onProgress:i,onError:n});const r=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin",signal:typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),a=this.mimeType,c=this.responseType;fetch(r).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&Nt("FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;const h=Br[t],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,p=f!==0;let g=0;const m=new ReadableStream({start(v){y();function y(){u.read().then(({done:x,value:M})=>{if(x)v.close();else{g+=M.byteLength;const b=new ProgressEvent("progress",{lengthComputable:p,loaded:g,total:f});for(let S=0,E=h.length;S<E;S++){const w=h[S];w.onProgress&&w.onProgress(b)}v.enqueue(M),y()}},x=>{v.error(x)})}}});return new Response(m)}else throw new HA(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(c){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(h=>new DOMParser().parseFromString(h,a));case"json":return l.json();default:if(a==="")return l.text();{const u=/charset="?([^;"\s]*)"?/i.exec(a),d=u&&u[1]?u[1].toLowerCase():void 0,f=new TextDecoder(d);return l.arrayBuffer().then(p=>f.decode(p))}}}).then(l=>{qr.add(`file:${t}`,l);const h=Br[t];delete Br[t];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{const h=Br[t];if(h===void 0)throw this.manager.itemError(t),l;delete Br[t];for(let u=0,d=h.length;u<d;u++){const f=h[u];f.onError&&f.onError(l)}this.manager.itemError(t)}).finally(()=>{this.manager.itemEnd(t)}),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}const vc=new WeakMap;class GA extends Hh{constructor(t){super(t)}load(t,e,i,n){this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,r=qr.get(`image:${t}`);if(r!==void 0){if(r.complete===!0)s.manager.itemStart(t),setTimeout(function(){e&&e(r),s.manager.itemEnd(t)},0);else{let u=vc.get(r);u===void 0&&(u=[],vc.set(r,u)),u.push({onLoad:e,onError:n})}return r}const a=Ih("img");function c(){h(),e&&e(this);const u=vc.get(this)||[];for(let d=0;d<u.length;d++){const f=u[d];f.onLoad&&f.onLoad(this)}vc.delete(this),s.manager.itemEnd(t)}function l(u){h(),n&&n(u),qr.remove(`image:${t}`);const d=vc.get(this)||[];for(let f=0;f<d.length;f++){const p=d[f];p.onError&&p.onError(u)}vc.delete(this),s.manager.itemError(t),s.manager.itemEnd(t)}function h(){a.removeEventListener("load",c,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",c,!1),a.addEventListener("error",l,!1),t.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),qr.add(`image:${t}`,a),s.manager.itemStart(t),a.src=t,a}}class jO extends Hh{constructor(t){super(t)}load(t,e,i,n){const s=new Mn,r=new GA(this.manager);return r.setCrossOrigin(this.crossOrigin),r.setPath(this.path),r.load(t,function(a){s.image=a,s.needsUpdate=!0,e!==void 0&&e(s)},i,n),s}}class Pf extends bi{constructor(t,e=1){super(),this.isLight=!0,this.type="Light",this.color=new st(t),this.intensity=e}dispose(){this.dispatchEvent({type:"dispose"})}copy(t,e){return super.copy(t,e),this.color.copy(t.color),this.intensity=t.intensity,this}toJSON(t){const e=super.toJSON(t);return e.object.color=this.color.getHex(),e.object.intensity=this.intensity,e}}class VA extends Pf{constructor(t,e,i){super(t,i),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.groundColor=new st(e)}copy(t,e){return super.copy(t,e),this.groundColor.copy(t.groundColor),this}toJSON(t){const e=super.toJSON(t);return e.object.groundColor=this.groundColor.getHex(),e}}const L0=new he,oM=new R,cM=new R;class Fg{constructor(t){this.camera=t,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new it(512,512),this.mapType=Hn,this.map=null,this.mapPass=null,this.matrix=new he,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Dg,this._frameExtents=new it(1,1),this._viewportCount=1,this._viewports=[new _e(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(t){const e=this.camera,i=this.matrix;oM.setFromMatrixPosition(t.matrixWorld),e.position.copy(oM),cM.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(cM),e.updateMatrixWorld(),L0.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),this._frustum.setFromProjectionMatrix(L0,e.coordinateSystem,e.reversedDepth),e.coordinateSystem===Rh||e.reversedDepth?i.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):i.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),i.multiply(L0)}getViewport(t){return this._viewports[t]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(t){return this.camera=t.camera.clone(),this.intensity=t.intensity,this.bias=t.bias,this.radius=t.radius,this.autoUpdate=t.autoUpdate,this.needsUpdate=t.needsUpdate,this.normalBias=t.normalBias,this.blurSamples=t.blurSamples,this.mapSize.copy(t.mapSize),this.biasNode=t.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){const t={};return this.intensity!==1&&(t.intensity=this.intensity),this.bias!==0&&(t.bias=this.bias),this.normalBias!==0&&(t.normalBias=this.normalBias),this.radius!==1&&(t.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(t.mapSize=this.mapSize.toArray()),t.camera=this.camera.toJSON(!1).object,delete t.camera.matrix,t}}const Ru=new R,Iu=new ts,Qs=new R;class Dx extends bi{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new he,this.projectionMatrix=new he,this.projectionMatrixInverse=new he,this.coordinateSystem=Tr,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorld.decompose(Ru,Iu,Qs),Qs.x===1&&Qs.y===1&&Qs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ru,Iu,Qs.set(1,1,1)).invert()}updateWorldMatrix(t,e,i=!1){super.updateWorldMatrix(t,e,i),this.matrixWorld.decompose(Ru,Iu,Qs),Qs.x===1&&Qs.y===1&&Qs.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Ru,Iu,Qs.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const fa=new R,lM=new it,hM=new it;class jn extends Dx{constructor(t=50,e=1,i=.1,n=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=i,this.far=n,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=t.view===null?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=dl*2*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(sh*.5*this.fov);return .5*this.getFilmHeight()/t}getEffectiveFOV(){return dl*2*Math.atan(Math.tan(sh*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,i){fa.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(fa.x,fa.y).multiplyScalar(-t/fa.z),fa.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(fa.x,fa.y).multiplyScalar(-t/fa.z)}getViewSize(t,e){return this.getViewBounds(t,lM,hM),e.subVectors(hM,lM)}setViewOffset(t,e,i,n,s,r){this.aspect=t/e,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(sh*.5*this.fov)/this.zoom,i=2*e,n=this.aspect*i,s=-.5*n;const r=this.view;if(this.view!==null&&this.view.enabled){const c=r.fullWidth,l=r.fullHeight;s+=r.offsetX*n/c,e-=r.offsetY*i/l,n*=r.width/c,i*=r.height/l}const a=this.filmOffset;a!==0&&(s+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+n,e,e-i,t,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,this.view!==null&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}class WA extends Fg{constructor(){super(new jn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(t){const e=this.camera,i=dl*2*t.angle*this.focus,n=this.mapSize.width/this.mapSize.height*this.aspect,s=t.distance||e.far;(i!==e.fov||n!==e.aspect||s!==e.far)&&(e.fov=i,e.aspect=n,e.far=s,e.updateProjectionMatrix()),super.updateMatrices(t)}copy(t){return super.copy(t),this.focus=t.focus,this}}class QO extends Pf{constructor(t,e,i=0,n=Math.PI/3,s=0,r=2){super(t,e),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.target=new bi,this.distance=i,this.angle=n,this.penumbra=s,this.decay=r,this.map=null,this.shadow=new WA}get power(){return this.intensity*Math.PI}set power(t){this.intensity=t/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.angle=t.angle,this.penumbra=t.penumbra,this.decay=t.decay,this.target=t.target.clone(),this.map=t.map,this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.distance=this.distance,e.object.angle=this.angle,e.object.decay=this.decay,e.object.penumbra=this.penumbra,e.object.target=this.target.uuid,this.map&&this.map.isTexture&&(e.object.map=this.map.toJSON(t).uuid),e.object.shadow=this.shadow.toJSON(),e}}class XA extends Fg{constructor(){super(new jn(90,1,.5,500)),this.isPointLightShadow=!0}}class Cx extends Pf{constructor(t,e,i=0,n=2){super(t,e),this.isPointLight=!0,this.type="PointLight",this.distance=i,this.decay=n,this.shadow=new XA}get power(){return this.intensity*4*Math.PI}set power(t){this.intensity=t/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(t,e){return super.copy(t,e),this.distance=t.distance,this.decay=t.decay,this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.distance=this.distance,e.object.decay=this.decay,e.object.shadow=this.shadow.toJSON(),e}}class Is extends Dx{constructor(t=-1,e=1,i=1,n=-1,s=.1,r=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=i,this.bottom=n,this.near=s,this.far=r,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=t.view===null?null:Object.assign({},t.view),this}setViewOffset(t,e,i,n,s,r){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=i,this.view.offsetY=n,this.view.width=s,this.view.height=r,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,n=(this.top+this.bottom)/2;let s=i-t,r=i+t,a=n+e,c=n-e;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,h=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=l*this.view.offsetX,r=s+l*this.view.width,a-=h*this.view.offsetY,c=a-h*this.view.height}this.projectionMatrix.makeOrthographic(s,r,a,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,this.view!==null&&(e.object.view=Object.assign({},this.view)),e}}class $A extends Fg{constructor(){super(new Is(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class uM extends Pf{constructor(t,e){super(t,e),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(bi.DEFAULT_UP),this.updateMatrix(),this.target=new bi,this.shadow=new $A}dispose(){super.dispose(),this.shadow.dispose()}copy(t){return super.copy(t),this.target=t.target.clone(),this.shadow=t.shadow.clone(),this}toJSON(t){const e=super.toJSON(t);return e.object.shadow=this.shadow.toJSON(),e.object.target=this.target.uuid,e}}class t8{static extractUrlBase(t){const e=t.lastIndexOf("/");return e===-1?"./":t.slice(0,e+1)}static resolveURL(t,e){return typeof t!="string"||t===""?"":(/^https?:\/\//i.test(e)&&/^\//.test(t)&&(e=e.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(t)||/^data:.*,.*$/i.test(t)||/^blob:.*$/i.test(t)?t:e+t)}}class e8 extends ne{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(t){return super.copy(t),this.instanceCount=t.instanceCount,this}toJSON(){const t=super.toJSON();return t.instanceCount=this.instanceCount,t.isInstancedBufferGeometry=!0,t}}const N0=new WeakMap;class i8 extends Hh{constructor(t){super(t),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&Nt("ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&Nt("ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"},this._abortController=new AbortController}setOptions(t){return this.options=t,this}load(t,e,i,n){t===void 0&&(t=""),this.path!==void 0&&(t=this.path+t),t=this.manager.resolveURL(t);const s=this,r=qr.get(`image-bitmap:${t}`);if(r!==void 0){if(s.manager.itemStart(t),r.then){r.then(l=>{N0.has(r)===!0?(n&&n(N0.get(r)),s.manager.itemError(t),s.manager.itemEnd(t)):(e&&e(l),s.manager.itemEnd(t))});return}setTimeout(function(){e&&e(r),s.manager.itemEnd(t)},0);return}const a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader,a.signal=typeof AbortSignal.any=="function"?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;const c=fetch(t,a).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(l){qr.add(`image-bitmap:${t}`,l),e&&e(l),s.manager.itemEnd(t)}).catch(function(l){n&&n(l),N0.set(c,l),qr.remove(`image-bitmap:${t}`),s.manager.itemError(t),s.manager.itemEnd(t)});qr.add(`image-bitmap:${t}`,c),s.manager.itemStart(t)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}}const Mc=-90,yc=1;class zg extends bi{constructor(t,e,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const n=new jn(Mc,yc,t,e);n.layers=this.layers,this.add(n);const s=new jn(Mc,yc,t,e);s.layers=this.layers,this.add(s);const r=new jn(Mc,yc,t,e);r.layers=this.layers,this.add(r);const a=new jn(Mc,yc,t,e);a.layers=this.layers,this.add(a);const c=new jn(Mc,yc,t,e);c.layers=this.layers,this.add(c);const l=new jn(Mc,yc,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[i,n,s,r,a,c]=e;for(const l of e)this.remove(l);if(t===Tr)i.up.set(0,1,0),i.lookAt(1,0,0),n.up.set(0,1,0),n.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),r.up.set(0,0,1),r.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(t===Rh)i.up.set(0,-1,0),i.lookAt(-1,0,0),n.up.set(0,-1,0),n.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),r.up.set(0,0,-1),r.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);for(const l of e)this.add(l),l.updateMatrixWorld()}update(t,e){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:n}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[s,r,a,c,l,h]=this.children,u=t.getRenderTarget(),d=t.getActiveCubeFace(),f=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const g=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let m=!1;t.isWebGLRenderer===!0?m=t.state.buffers.depth.getReversed():m=t.reversedDepthBuffer,t.setRenderTarget(i,0,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,s),t.setRenderTarget(i,1,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,r),t.setRenderTarget(i,2,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,a),t.setRenderTarget(i,3,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,c),t.setRenderTarget(i,4,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,l),i.texture.generateMipmaps=g,t.setRenderTarget(i,5,n),m&&t.autoClear===!1&&t.clearDepth(),t.render(e,h),t.setRenderTarget(u,d,f),t.xr.enabled=p,i.texture.needsPMREMUpdate=!0}}class YA extends jn{constructor(t=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=t}}class qA{constructor(t,e,i){this.binding=t,this.valueSize=i;let n,s,r;switch(e){case"quaternion":n=this._slerp,s=this._slerpAdditive,r=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":n=this._select,s=this._select,r=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:n=this._lerp,s=this._lerpAdditive,r=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=n,this._mixBufferRegionAdditive=s,this._setIdentity=r,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(t,e){const i=this.buffer,n=this.valueSize,s=t*n+n;let r=this.cumulativeWeight;if(r===0){for(let a=0;a!==n;++a)i[s+a]=i[a];r=e}else{r+=e;const a=e/r;this._mixBufferRegion(i,s,0,a,n)}this.cumulativeWeight=r}accumulateAdditive(t){const e=this.buffer,i=this.valueSize,n=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(e,n,0,t,i),this.cumulativeWeightAdditive+=t}apply(t){const e=this.valueSize,i=this.buffer,n=t*e+e,s=this.cumulativeWeight,r=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){const c=e*this._origIndex;this._mixBufferRegion(i,n,c,1-s,e)}r>0&&this._mixBufferRegionAdditive(i,n,this._addIndex*e,1,e);for(let c=e,l=e+e;c!==l;++c)if(i[c]!==i[c+e]){a.setValue(i,n);break}}saveOriginalState(){const t=this.binding,e=this.buffer,i=this.valueSize,n=i*this._origIndex;t.getValue(e,n);for(let s=i,r=n;s!==r;++s)e[s]=e[n+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=this.valueSize*3;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let i=t;i<e;i++)this.buffer[i]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){const t=this._origIndex*this.valueSize,e=this._addIndex*this.valueSize;for(let i=0;i<this.valueSize;i++)this.buffer[e+i]=this.buffer[t+i]}_select(t,e,i,n,s){if(n>=.5)for(let r=0;r!==s;++r)t[e+r]=t[i+r]}_slerp(t,e,i,n){ts.slerpFlat(t,e,t,e,t,i,n)}_slerpAdditive(t,e,i,n,s){const r=this._workIndex*s;ts.multiplyQuaternionsFlat(t,r,t,e,t,i),ts.slerpFlat(t,e,t,e,t,r,n)}_lerp(t,e,i,n,s){const r=1-n;for(let a=0;a!==s;++a){const c=e+a;t[c]=t[c]*r+t[i+a]*n}}_lerpAdditive(t,e,i,n,s){for(let r=0;r!==s;++r){const a=e+r;t[a]=t[a]+t[i+r]*n}}}const Bg="\\[\\]\\.:\\/",KA=new RegExp("["+Bg+"]","g"),Hg="[^"+Bg+"]",ZA="[^"+Bg.replace("\\.","")+"]",JA=/((?:WC+[\/:])*)/.source.replace("WC",Hg),jA=/(WCOD+)?/.source.replace("WCOD",ZA),QA=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",Hg),t_=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",Hg),e_=new RegExp("^"+JA+jA+QA+t_+"$"),i_=["material","materials","bones","map"];class n_{constructor(t,e,i){const n=i||Ke.parseTrackName(e);this._targetGroup=t,this._bindings=t.subscribe_(e,n)}getValue(t,e){this.bind();const i=this._targetGroup.nCachedObjects_,n=this._bindings[i];n!==void 0&&n.getValue(t,e)}setValue(t,e){const i=this._bindings;for(let n=this._targetGroup.nCachedObjects_,s=i.length;n!==s;++n)i[n].setValue(t,e)}bind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,i=t.length;e!==i;++e)t[e].bind()}unbind(){const t=this._bindings;for(let e=this._targetGroup.nCachedObjects_,i=t.length;e!==i;++e)t[e].unbind()}}class Ke{constructor(t,e,i){this.path=e,this.parsedPath=i||Ke.parseTrackName(e),this.node=Ke.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,i){return t&&t.isAnimationObjectGroup?new Ke.Composite(t,e,i):new Ke(t,e,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(KA,"")}static parseTrackName(t){const e=e_.exec(t);if(e===null)throw new Error("THREE.PropertyBinding: Cannot parse trackName: "+t);const i={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){const s=i.nodeName.substring(n+1);i_.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("THREE.PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,e){if(e===void 0||e===""||e==="."||e===-1||e===t.name||e===t.uuid)return t;if(t.skeleton){const i=t.skeleton.getBoneByName(e);if(i!==void 0)return i}if(t.children){const i=function(s){for(let r=0;r<s.length;r++){const a=s[r];if(a.name===e||a.uuid===e)return a;const c=i(a.children);if(c)return c}return null},n=i(t.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,e){t[e]=this.targetObject[this.propertyName]}_getValue_array(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)t[e++]=i[n]}_getValue_arrayElement(t,e){t[e]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,e){this.resolvedProperty.toArray(t,e)}_setValue_direct(t,e){this.targetObject[this.propertyName]=t[e]}_setValue_direct_setNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,e){this.targetObject[this.propertyName]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++]}_setValue_array_setNeedsUpdate(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,e){const i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[e++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,e){this.resolvedProperty[this.propertyIndex]=t[e]}_setValue_arrayElement_setNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty[this.propertyIndex]=t[e],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,e){this.resolvedProperty.fromArray(t,e)}_setValue_fromArray_setNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,e){this.resolvedProperty.fromArray(t,e),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,e){this.bind(),this.getValue(t,e)}_setValue_unbound(t,e){this.bind(),this.setValue(t,e)}bind(){let t=this.node;const e=this.parsedPath,i=e.objectName,n=e.propertyName;let s=e.propertyIndex;if(t||(t=Ke.findNode(this.rootNode,e.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){Nt("PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let l=e.objectIndex;switch(i){case"materials":if(!t.material){te("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.materials){te("PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}t=t.material.materials;break;case"bones":if(!t.skeleton){te("PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}t=t.skeleton.bones;for(let h=0;h<t.length;h++)if(t[h].name===l){l=h;break}break;case"map":if("map"in t){t=t.map;break}if(!t.material){te("PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.map){te("PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}t=t.material.map;break;default:if(t[i]===void 0){te("PropertyBinding: Can not bind to objectName of node undefined.",this);return}t=t[i]}if(l!==void 0){if(t[l]===void 0){te("PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);return}t=t[l]}}const r=t[n];if(r===void 0){const l=e.nodeName;te("PropertyBinding: Trying to update property for track: "+l+"."+n+" but it wasn't found.",t);return}let a=this.Versioning.None;this.targetObject=t,t.isMaterial===!0?a=this.Versioning.NeedsUpdate:t.isObject3D===!0&&(a=this.Versioning.MatrixWorldNeedsUpdate);let c=this.BindingType.Direct;if(s!==void 0){if(n==="morphTargetInfluences"){if(!t.geometry){te("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!t.geometry.morphAttributes){te("PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}t.morphTargetDictionary[s]!==void 0&&(s=t.morphTargetDictionary[s])}c=this.BindingType.ArrayElement,this.resolvedProperty=r,this.propertyIndex=s}else r.fromArray!==void 0&&r.toArray!==void 0?(c=this.BindingType.HasFromToArray,this.resolvedProperty=r):Array.isArray(r)?(c=this.BindingType.EntireArray,this.resolvedProperty=r):this.propertyName=n;this.getValue=this.GetterByBindingType[c],this.setValue=this.SetterByBindingTypeAndVersioning[c][a]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}}Ke.Composite=n_;Ke.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3};Ke.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2};Ke.prototype.GetterByBindingType=[Ke.prototype._getValue_direct,Ke.prototype._getValue_array,Ke.prototype._getValue_arrayElement,Ke.prototype._getValue_toArray];Ke.prototype.SetterByBindingTypeAndVersioning=[[Ke.prototype._setValue_direct,Ke.prototype._setValue_direct_setNeedsUpdate,Ke.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_array,Ke.prototype._setValue_array_setNeedsUpdate,Ke.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_arrayElement,Ke.prototype._setValue_arrayElement_setNeedsUpdate,Ke.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Ke.prototype._setValue_fromArray,Ke.prototype._setValue_fromArray_setNeedsUpdate,Ke.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];class s_{constructor(t,e,i=null,n=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=i,this.blendMode=n;const s=e.tracks,r=s.length,a=new Array(r),c={endingStart:Nc,endingEnd:Nc};for(let l=0;l!==r;++l){const h=s[l].createInterpolant(null);a[l]=h,h.settings=c}this._interpolantSettings=c,this._interpolants=a,this._propertyBindings=new Array(r),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._restoreTimeScale=null,this._weightInterpolant=null,this.loop=zE,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,i=!1){if(t.fadeOut(e),this.fadeIn(e),i===!0){const n=this._clip.duration,s=t._clip.duration,r=s/n,a=n/s;t._restoreTimeScale=t.timeScale,this._restoreTimeScale=this.timeScale,t.warp(1,r,e),this.warp(a,1,e)}return this}crossFadeTo(t,e,i=!1){return t.crossFadeFrom(this,e,i)}stopFading(){const t=this._weightInterpolant;return t!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,i){const n=this._mixer,s=n.time,r=this.timeScale;let a=this._timeScaleInterpolant;a===null&&(a=n._lendControlInterpolant(),this._timeScaleInterpolant=a);const c=a.parameterPositions,l=a.sampleValues;return c[0]=s,c[1]=s+i,l[0]=t/r,l[1]=e/r,this}stopWarping(){const t=this._timeScaleInterpolant;return t!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this._restoreTimeScale=null,this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,i,n){if(!this.enabled){this._updateWeight(t);return}const s=this._startTime;if(s!==null){const c=(t-s)*i;c<0||i===0?e=0:(this._startTime=null,e=i*c)}e*=this._updateTimeScale(t);const r=this._updateTime(e),a=this._updateWeight(t);if(a>0){const c=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case HE:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(r),l[h].accumulateAdditive(a);break;case wg:default:for(let h=0,u=c.length;h!==u;++h)c[h].evaluate(r),l[h].accumulate(n,a)}}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const i=this._weightInterpolant;if(i!==null){const n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(this.stopFading(),n===0&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const i=this._timeScaleInterpolant;if(i!==null){const n=i.evaluate(t)[0];e*=n,t>i.parameterPositions[1]&&(e===0?this.paused=!0:(this._restoreTimeScale!==null&&(e=this._restoreTimeScale),this.timeScale=e),this.stopWarping())}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,i=this.loop;let n=this.time+t,s=this._loopCount;const r=i===BE;if(t===0)return s===-1?n:r&&(s&1)===1?e-n:n;if(i===rx){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(n>=e)n=e;else if(n<0)n=0;else{this.time=n;break t}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(s===-1&&(t>=0?(s=0,this._setEndings(!0,this.repetitions===0,r)):this._setEndings(this.repetitions===0,!0,r)),n>=e||n<0){const a=Math.floor(n/e);n-=e*a,s+=Math.abs(a);const c=this.repetitions-s;if(c<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,n=t>0?e:0,this.time=n,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(c===1){const l=t<0;this._setEndings(l,!l,r)}else this._setEndings(!1,!1,r);this._loopCount=s,this.time=n,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this._loopCount=s,this.time=n;if(r&&(s&1)===1)return e-n}return n}_setEndings(t,e,i){const n=this._interpolantSettings;i?(n.endingStart=kc,n.endingEnd=kc):(t?n.endingStart=this.zeroSlopeAtStart?kc:Nc:n.endingStart=qd,e?n.endingEnd=this.zeroSlopeAtEnd?kc:Nc:n.endingEnd=qd)}_scheduleFading(t,e,i){const n=this._mixer,s=n.time;let r=this._weightInterpolant;r===null&&(r=n._lendControlInterpolant(),this._weightInterpolant=r);const a=r.parameterPositions,c=r.sampleValues;return a[0]=s,c[0]=e,a[1]=s+t,c[1]=i,this}}const r_=new Float32Array(1);class a_ extends Ha{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(t,e){const i=t._localRoot||this._root,n=t._clip.tracks,s=n.length,r=t._propertyBindings,a=t._interpolants,c=i.uuid,l=this._bindingsByRootAndName;let h=l[c];h===void 0&&(h={},l[c]=h);for(let u=0;u!==s;++u){const d=n[u],f=d.name;let p=h[f];if(p!==void 0)++p.referenceCount,r[u]=p;else{if(p=r[u],p!==void 0){p._cacheIndex===null&&(++p.referenceCount,this._addInactiveBinding(p,c,f));continue}const g=e&&e._propertyBindings[u].binding.parsedPath;p=new qA(Ke.create(i,f,g),d.ValueTypeName,d.getValueSize()),++p.referenceCount,this._addInactiveBinding(p,c,f),r[u]=p}a[u].resultBuffer=p.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(t._cacheIndex===null){const i=(t._localRoot||this._root).uuid,n=t._clip.uuid,s=this._actionsByClip[n];this._bindAction(t,s&&s.knownActions[0]),this._addInactiveAction(t,n,i)}const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return e!==null&&e<this._nActiveActions}_addInactiveAction(t,e,i){const n=this._actions,s=this._actionsByClip;let r=s[e];if(r===void 0)r={knownActions:[t],actionByRoot:{}},t._byClipCacheIndex=0,s[e]=r;else{const a=r.knownActions;t._byClipCacheIndex=a.length,a.push(t)}t._cacheIndex=n.length,n.push(t),r.actionByRoot[i]=t}_removeInactiveAction(t){const e=this._actions,i=e[e.length-1],n=t._cacheIndex;i._cacheIndex=n,e[n]=i,e.pop(),t._cacheIndex=null;const s=t._clip.uuid,r=this._actionsByClip,a=r[s],c=a.knownActions,l=c[c.length-1],h=t._byClipCacheIndex;l._byClipCacheIndex=h,c[h]=l,c.pop(),t._byClipCacheIndex=null;const u=a.actionByRoot,d=(t._localRoot||this._root).uuid;delete u[d],c.length===0&&delete r[s],this._removeInactiveBindingsForAction(t)}_removeInactiveBindingsForAction(t){const e=t._propertyBindings;for(let i=0,n=e.length;i!==n;++i){const s=e[i];--s.referenceCount===0&&this._removeInactiveBinding(s)}}_lendAction(t){const e=this._actions,i=t._cacheIndex,n=this._nActiveActions++,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_takeBackAction(t){const e=this._actions,i=t._cacheIndex,n=--this._nActiveActions,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_addInactiveBinding(t,e,i){const n=this._bindingsByRootAndName,s=this._bindings;let r=n[e];r===void 0&&(r={},n[e]=r),r[i]=t,t._cacheIndex=s.length,s.push(t)}_removeInactiveBinding(t){const e=this._bindings,i=t.binding,n=i.rootNode.uuid,s=i.path,r=this._bindingsByRootAndName,a=r[n],c=e[e.length-1],l=t._cacheIndex;c._cacheIndex=l,e[l]=c,e.pop(),delete a[s],Object.keys(a).length===0&&delete r[n]}_lendBinding(t){const e=this._bindings,i=t._cacheIndex,n=this._nActiveBindings++,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_takeBackBinding(t){const e=this._bindings,i=t._cacheIndex,n=--this._nActiveBindings,s=e[n];t._cacheIndex=n,e[n]=t,s._cacheIndex=i,e[i]=s}_lendControlInterpolant(){const t=this._controlInterpolants,e=this._nActiveControlInterpolants++;let i=t[e];return i===void 0&&(i=new Tx(new Float32Array(2),new Float32Array(2),1,r_),i.__cacheIndex=e,t[e]=i),i}_takeBackControlInterpolant(t){const e=this._controlInterpolants,i=t.__cacheIndex,n=--this._nActiveControlInterpolants,s=e[n];t.__cacheIndex=n,e[n]=t,s.__cacheIndex=i,e[i]=s}clipAction(t,e,i){const n=e||this._root,s=n.uuid;let r=typeof t=="string"?rM.findByName(n,t):t;const a=r!==null?r.uuid:t,c=this._actionsByClip[a];let l=null;if(i===void 0&&(r!==null?i=r.blendMode:i=wg),c!==void 0){const u=c.actionByRoot[s];if(u!==void 0&&u.blendMode===i)return u;l=c.knownActions[0],r===null&&(r=l._clip)}if(r===null)return null;const h=new s_(this,r,e,i);return this._bindAction(h,l),this._addInactiveAction(h,a,s),h}existingAction(t,e){const i=e||this._root,n=i.uuid,s=typeof t=="string"?rM.findByName(i,t):t,r=s?s.uuid:t,a=this._actionsByClip[r];return a!==void 0&&a.actionByRoot[n]||null}stopAllAction(){const t=this._actions,e=this._nActiveActions;for(let i=e-1;i>=0;--i)t[i].stop();return this}update(t){t*=this.timeScale;const e=this._actions,i=this._nActiveActions,n=this.time+=t,s=Math.sign(t),r=this._accuIndex^=1;for(let l=0;l!==i;++l)e[l]._update(n,t,s,r);const a=this._bindings,c=this._nActiveBindings;for(let l=0;l!==c;++l)a[l].apply(r);return this}setTime(t){this.time=0;for(let e=0;e<this._actions.length;e++)this._actions[e].time=0;return this.update(t)}getRoot(){return this._root}uncacheClip(t){const e=this._actions,i=t.uuid,n=this._actionsByClip,s=n[i];if(s!==void 0){const r=s.knownActions;for(let a=0,c=r.length;a!==c;++a){const l=r[a];this._deactivateAction(l);const h=l._cacheIndex,u=e[e.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=h,e[h]=u,e.pop(),this._removeInactiveBindingsForAction(l)}delete n[i]}}uncacheRoot(t){const e=t.uuid,i=this._actionsByClip;for(const r in i){const a=i[r].actionByRoot,c=a[e];c!==void 0&&(this._deactivateAction(c),this._removeInactiveAction(c))}const n=this._bindingsByRootAndName,s=n[e];if(s!==void 0)for(const r in s){const a=s[r];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(t,e){const i=this.existingAction(t,e);i!==null&&(this._deactivateAction(i),this._removeInactiveAction(i))}}class n8 extends ux{constructor(t,e,i=1){super(t,e),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=i}copy(t){return super.copy(t),this.meshPerAttribute=t.meshPerAttribute,this}clone(t){const e=super.clone(t);return e.meshPerAttribute=this.meshPerAttribute,e}toJSON(t){const e=super.toJSON(t);return e.isInstancedInterleavedBuffer=!0,e.meshPerAttribute=this.meshPerAttribute,e}}const dM=new he;class fd{constructor(t,e,i=0,n=1/0){this.ray=new zh(t,e),this.near=i,this.far=n,this.camera=null,this.layers=new Tg,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(t,e){this.ray.set(t,e)}setFromCamera(t,e){e.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(t.x,t.y,.5).unproject(e).sub(this.ray.origin).normalize(),this.camera=e):e.isOrthographicCamera?(this.ray.origin.set(t.x,t.y,e.projectionMatrix.elements[14]).unproject(e),this.ray.direction.set(0,0,-1).transformDirection(e.matrixWorld),this.camera=e):te("Raycaster: Unsupported camera type: "+e.type)}setFromXRController(t){return dM.identity().extractRotation(t.matrixWorld),this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(dM),this}intersectObject(t,e=!0,i=[]){return Am(t,this,i,e),i.sort(fM),i}intersectObjects(t,e=!0,i=[]){for(let n=0,s=t.length;n<s;n++)Am(t[n],this,i,e);return i.sort(fM),i}}function fM(o,t){return o.distance-t.distance}function Am(o,t,e,i){let n=!0;if(o.layers.test(t.layers)&&o.raycast(t,e)===!1&&(n=!1),n===!0&&i===!0){const s=o.children;for(let r=0,a=s.length;r<a;r++)Am(s[r],t,e,!0)}}class Ox{static{Ox.prototype.isMatrix2=!0}constructor(t,e,i,n){this.elements=[1,0,0,1],t!==void 0&&this.set(t,e,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(t,e=0){for(let i=0;i<4;i++)this.elements[i]=t[i+e];return this}set(t,e,i,n){const s=this.elements;return s[0]=t,s[2]=e,s[1]=i,s[3]=n,this}}const pM=new R,Du=new R,xc=new R,bc=new R,k0=new R,o_=new R,c_=new R;class s8{constructor(t=new R,e=new R){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){pM.subVectors(t,this.start),Du.subVectors(this.end,this.start);const i=Du.dot(Du);if(i===0)return 0;let s=Du.dot(pM)/i;return e&&(s=oe(s,0,1)),s}closestPointToPoint(t,e,i){const n=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(n).add(this.start)}distanceSqToLine3(t,e=o_,i=c_){const n=10000000000000001e-32;let s,r;const a=this.start,c=t.start,l=this.end,h=t.end;xc.subVectors(l,a),bc.subVectors(h,c),k0.subVectors(a,c);const u=xc.dot(xc),d=bc.dot(bc),f=bc.dot(k0);if(u<=n&&d<=n)return e.copy(a),i.copy(c),e.sub(i),e.dot(e);if(u<=n)s=0,r=f/d,r=oe(r,0,1);else{const p=xc.dot(k0);if(d<=n)r=0,s=oe(-p/u,0,1);else{const g=xc.dot(bc),m=u*d-g*g;m!==0?s=oe((g*f-p*d)/m,0,1):s=0,r=(g*s+f)/d,r<0?(r=0,s=oe(-p/u,0,1)):r>1&&(r=1,s=oe((g-p)/u,0,1))}}return e.copy(a).addScaledVector(xc,s),i.copy(c).addScaledVector(bc,r),e.distanceToSquared(i)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}function mM(o,t,e,i){const n=l_(i);switch(e){case nx:return o*t;case ul:return o*t/n.components*n.byteLength;case yg:return o*t/n.components*n.byteLength;case Go:return o*t*2/n.components*n.byteLength;case xg:return o*t*2/n.components*n.byteLength;case sx:return o*t*3/n.components*n.byteLength;case Ki:return o*t*4/n.components*n.byteLength;case bg:return o*t*4/n.components*n.byteLength;case cd:case ld:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*8;case hd:case ud:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case Vp:case Xp:return Math.max(o,16)*Math.max(t,8)/4;case Gp:case Wp:return Math.max(o,8)*Math.max(t,8)/2;case $p:case Yp:case Kp:case Zp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*8;case qp:case Xd:case Jp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case jp:return Math.floor((o+3)/4)*Math.floor((t+3)/4)*16;case Qp:return Math.floor((o+4)/5)*Math.floor((t+3)/4)*16;case tm:return Math.floor((o+4)/5)*Math.floor((t+4)/5)*16;case em:return Math.floor((o+5)/6)*Math.floor((t+4)/5)*16;case im:return Math.floor((o+5)/6)*Math.floor((t+5)/6)*16;case nm:return Math.floor((o+7)/8)*Math.floor((t+4)/5)*16;case sm:return Math.floor((o+7)/8)*Math.floor((t+5)/6)*16;case rm:return Math.floor((o+7)/8)*Math.floor((t+7)/8)*16;case am:return Math.floor((o+9)/10)*Math.floor((t+4)/5)*16;case om:return Math.floor((o+9)/10)*Math.floor((t+5)/6)*16;case cm:return Math.floor((o+9)/10)*Math.floor((t+7)/8)*16;case lm:return Math.floor((o+9)/10)*Math.floor((t+9)/10)*16;case hm:return Math.floor((o+11)/12)*Math.floor((t+9)/10)*16;case um:return Math.floor((o+11)/12)*Math.floor((t+11)/12)*16;case dm:case fm:case pm:return Math.ceil(o/4)*Math.ceil(t/4)*16;case mm:case gm:return Math.ceil(o/4)*Math.ceil(t/4)*8;case $d:case vm:return Math.ceil(o/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${e} format.`)}function l_(o){switch(o){case Hn:case Qy:return{byteLength:1,components:1};case _h:case tx:case Be:return{byteLength:2,components:1};case vg:case Mg:return{byteLength:2,components:4};case Ts:case gg:case Dn:return{byteLength:4,components:1};case ex:case ix:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${o}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:pg}}));typeof window<"u"&&(window.__THREE__?Nt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=pg);/**
|
|
2413
2413
|
* @license
|
|
2414
2414
|
* Copyright 2010-2026 Three.js Authors
|
|
2415
2415
|
* SPDX-License-Identifier: MIT
|
|
@@ -8632,7 +8632,7 @@ uniform float uWindowLuminance;
|
|
|
8632
8632
|
varying float vLitRank;
|
|
8633
8633
|
${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
|
|
8634
8634
|
totalEmissiveRadiance *= step(vLitRank, uLitShare) * uWindowLuminance * ${yt.WINDOW_VARIETY_GLSL};`)}`},r.customProgramCacheKey=()=>"facade-lit-windows";const a=new bt(s,r);return a.castShadow=!0,a.receiveShadow=!0,e.add(a),e}static CLOSED_AT_NIGHT_SHARE=.2;static litWindowShare={value:0};static WINDOW_LUMINANCE_CD_M2=15;static ROOM_LIGHT_K=2900;static COLD_ROOM_LIGHT_K=4e3;static windowLuminance={value:0};static get WINDOW_VARIETY_GLSL(){const t=n=>`vec3(${n.map(s=>s.toFixed(4)).join(", ")})`,e=el.ofTemperature(yt.ROOM_LIGHT_K),i=el.ofTemperature(yt.COLD_ROOM_LIGHT_K);return`(mix(0.35, 2.0, fract(vLitRank * 97.13) * fract(vLitRank * 97.13)) * mix(${t(e)}, ${t(i)}, step(0.86, fract(vLitRank * 53.71))))`}static setWindowLuminance(t){yt.windowLuminance.value=yt.WINDOW_LUMINANCE_CD_M2*t}static setLitWindowShare(t){yt.litWindowShare.value=Math.max(0,Math.min(1,t))}static build(t,e){const i=yt.hasFacade(t)?yt.buildFacade(t):t.kind==="building"?l2(t.floors??zd,t.windows,t.observerSide,t.occupiedFloor,t.observerFacing):t.kind==="tree"?u2():t.kind==="shrub"?h2():t.kind==="bridge"?NC(t):t.kind==="wire"?kC(t):t.kind==="wall"?$i.build(t):t.kind==="crop"?f2():t.kind==="terrace"?WC():t.kind==="mound"?p2():t.kind==="streetlight"?m2(e,t.lamp?.mount,t.lamp):t.kind==="trafficlight"?ge.trafficLight(se.isPedestrian(t.lights)):t.kind==="crossing"?ge.crossing(yt.sizeOf(t).widthM,yt.sizeOf(t).lengthM):t.kind==="roadsign"?ge.roadSign(t.sign):t.kind==="vehicle"?g2(e,t.windows,t.observerSide,t.observerFacing):t.kind==="aircraft"?w2():t.kind==="entity"?x2():ng();t.color&&this.paint(i,t.color);const n=this.scaleFor(t),s=new Oe;return t.kind==="building"&&t.roof&&this.addRoof(s,t),i.name=yt.BODY_NAME,i.scale.copy(n),s.add(i),t.headingDeg!==void 0&&(s.rotation.y=-t.headingDeg*q0),this.addLights(s,t.lights),yt.fitLights(s,t,t.sizeM??{}),s}static scaleFor(t){const e=t.sizeM;if(!e||yt.hasFacade(t)||t.kind==="bridge"||t.kind==="wire"||t.kind==="terrace"||t.kind==="wall"||t.kind==="crossing")return new R(1,1,1);const i=this.naturalSize(t.kind,t.floors);return new R(e.widthM===void 0?1:j0(e.widthM,i.widthM),e.heightM===void 0?1:j0(t.kind==="building"?this.wallHeightOf(t,e.heightM):e.heightM,i.heightM),e.lengthM===void 0?1:j0(e.lengthM,i.lengthM))}static naturalSize(t,e){const i=t==="building"?Math.max(1,(e??zd)+1):0;if(t==="bridge")return ui.NATURAL_SIZE;if(t==="wire")return To.NATURAL_SIZE;if(t==="terrace"||t==="wall")return{widthM:1,lengthM:1,heightM:1};if(t==="crossing")return{widthM:6,lengthM:2.5,heightM:ge.CROSSING_LIFT_M};const n=`${t}:${i}`,s=v2.get(n);if(s)return s;const r=t==="building"?l2(i-1,void 0,void 0,void 0):t==="tree"?u2():t==="shrub"?h2():t==="crop"?f2():t==="mound"?p2():t==="streetlight"?m2(!1):t==="trafficlight"?ge.trafficLight(!1):t==="roadsign"?ge.roadSign(void 0):t==="vehicle"?g2(!1,void 0,void 0):t==="aircraft"?w2():t==="entity"?x2():ng(),a=new hn().setFromObject(r),c={widthM:a.max.x-a.min.x,heightM:a.max.y-a.min.y,lengthM:a.max.z-a.min.z};return this.dispose(r),v2.set(n,c),c}static usesModel(t){return Bd(t)!==void 0&&!(t.observerSide!==void 0&&al(t.kind))}static applyModel(t,e,i,n={}){const s=this.bodyOf(t),r=new Oe;r.name=yt.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*q0,i.updateMatrixWorld(!0);const a=new hn().setFromObject(i),c={lengthM:a.max.z-a.min.z,heightM:a.max.y-a.min.y,widthM:a.max.x-a.min.x},l=e.kind==="tree"&&e.sizeM?.heightM!==void 0?{heightM:e.sizeM.heightM}:e.sizeM,h=M2(l,c)??M2(n.depictedSizeM,c)??1;i.scale.multiplyScalar(h);const u=a.getCenter(new R).multiplyScalar(h);i.position.x-=u.x,i.position.z-=u.z,i.position.y-=e.kind==="aircraft"?u.y:a.min.y*h,i.traverse(d=>{d instanceof bt&&(d.castShadow=!0,d.receiveShadow=!0)}),r.add(i),e.kind==="tree"&&r.add(yt.trunkShadow(c.heightM*h)),s.parent?(s.parent.add(r),s.removeFromParent()):t.add(r),this.dispose(s),yt.fitLights(t,e,{widthM:c.widthM*h,heightM:c.heightM*h,lengthM:c.lengthM*h})}static fitLights(t,e,i){const n=Hd.byId(Bc.rigOf(e)||void 0)?.referenceSizeM;if(!n||!e.lights)return;const s=(h,u)=>h===void 0||u===0?1:h/u,r=s(i.widthM,n.widthM),a=s(i.heightM,n.heightM),c=s(i.lengthM,n.lengthM),l=new Map(e.lights.map(h=>[h.id,h.offsetM]));t.traverse(h=>{const u=h.userData.lightId,d=u===void 0?void 0:l.get(u);d&&h.position.set(d.x*r,d.y*a,d.z*c)})}static trunkShadow(t){yt.trunkProxy??={geometry:new Cn(1,1.15,1,8),material:new es({colorWrite:!1,depthWrite:!1})};const e=new bt(yt.trunkProxy.geometry,yt.trunkProxy.material),i=Math.min(.3,Math.max(.12,t*.035)),n=t*.45;return e.scale.set(i,n,i),e.position.y=n/2,e.castShadow=!0,e.receiveShadow=!1,e.userData.sharedModel=!0,e.name="trunk-shadow",e}static trunkProxy;static sizeOf(t){const e=this.naturalSize(t.kind,t.floors);return{widthM:t.sizeM?.widthM??e.widthM,lengthM:t.sizeM?.lengthM??e.lengthM,heightM:t.sizeM?.heightM??e.heightM}}static addLights(t,e){for(const i of e??[]){const n=_C(i.color),s=se.figureOf(i),r=s?ge.pedestrianFigure(s,1.8*(i.radiusM??K0)):new Gi(i.radiusM??K0,8,6),a=Ue(t,r,n,i.offsetM.y,!0);a.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),a.userData={emissive:!0,lightId:i.id,lightColor:n},a.visible=!1;const c=a.material;Xx.apply(c),c.transparent=!0,c.depthWrite=!1,c.fog=!1}}static setLights(t,e,i,n,s=0,r=1,a=xC,c=[1,1,1],l){if(!e||e.length===0)return;const h=new Map(e.map(d=>[d.id,d]));let u;l&&e.some(d=>d.beamDeg!==void 0)&&(t.updateWorldMatrix(!0,!1),u=t.worldToLocal(yt.eyeScratch.copy(l)));for(const d of t.children){if(!(d instanceof bt))continue;const f=d.userData.lightId;if(!f)continue;const p=h.get(f);if(!p)continue;const g=s>0?_y(p,i,i+s):oS(p,i)?1:0,m=u&&p.beamDeg!==void 0?yt.beamShare(p.beamDeg,d.position,u):1;d.visible=g>0&&m>0;const v=p.radiusM??K0,y=Math.max(1,n*a/v),x=v*y,M=r/(Math.PI*x*x),b=d.material,S=d.userData.lightColor;if(S){const E=g*m*bC*(p.intensity??1)*M,w=[S[0]*E*c[0],S[1]*E*c[1],S[2]*E*c[2]],_=Math.min(1,o2/Math.max(w[0],w[1],w[2],1e-30));b.color.setRGB(w[0]*_,w[1]*_,w[2]*_)}d.scale.setScalar(y)}}static eyeScratch=new R;static beamShare(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=i.z-e.z,a=Math.hypot(n,s,r);if(a===0)return 1;const c=-r/a;if(c<=0)return 0;const l=Math.log(.5)/Math.log(Math.cos(t*Math.PI/180));return Math.pow(c,l)}static setLit(t,e,i,n=1,s){const[r,a,c]=e==="streetlight"?[wC*yt.lampShare(s),SC,yt.lampHue(s)]:[EC,AC,vb],l=i?r*n/(Math.PI*a*a):0,h=Math.min(1,o2/Math.max(c[0]*l,c[1]*l,c[2]*l,1e-30)),u=[c[0]*l*h,c[1]*l*h,c[2]*l*h];t.traverse(d=>{const f=d.userData;!(d instanceof bt)||!f.emissive||f.lightId||(d.material instanceof Rs?d.material.emissive.setRGB(...u):d.material.color.setRGB(...u))})}static REFERENCE_LUMENS=1e4;static lampShare(t){return t?.lumens?t.lumens/yt.REFERENCE_LUMENS:1}static lampHue(t){return t?.colorTemperatureK?el.ofTemperature(t.colorTemperatureK):RC}static dispose(t){t.traverse(e=>{if(!(e instanceof bt))return;if(e.userData.sharedModel){for(const n of e.userData.tintedMaterials??[])n.dispose();return}e.geometry.dispose();const i=e.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const tp="https://ufoathome.org/models/index.json";class mh{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??qC()}async entries(t){const e=await this.load();return t?e.filter(i=>[i.kind].flat().includes(t)):e}async entry(t){return(await this.load()).find(e=>e.id===t)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
8635
|
-
`);let e=mh.shared.get(t);return e||(e=this.fetchFirstAvailable(),mh.shared.set(t,e),e.then(i=>{i.length===0&&mh.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function qC(){const o=`?v=${encodeURIComponent("0.
|
|
8635
|
+
`);let e=mh.shared.get(t);return e||(e=this.fetchFirstAvailable(),mh.shared.set(t,e),e.then(i=>{i.length===0&&mh.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function qC(){const o=`?v=${encodeURIComponent("0.142.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==tp?[t,tp]:[tp]).map(e=>e+o)}const KC=[{id:"ufoathome",name:"UFO@home",credit:"3D models re-hosted by UFO@home, each under its own author's licence",creditUrl:"https://ufoathome.org/models/",create:()=>new mh}];async function ep(o){const{GLTFLoader:t}=await we(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BGUT3v5v.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const Eb=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class us{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new bt(new Gn(2,2),new Se({uniforms:{uColor:{value:new st(0,0,0)},uRadius:{value:1}},vertexShader:us.VERTEX,fragmentShader:us.FRAGMENT,transparent:!0,depthWrite:!1,blending:nn,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,n){const s=Math.max(t,n*us.MIN_ANGLE_RAD),r=us.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(us.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(us.MAX_SHARE*us.FILL*Math.PI))}static VERTEX=`
|
|
8636
8636
|
uniform float uRadius;
|
|
8637
8637
|
varying vec2 vOffset;
|
|
8638
8638
|
void main() {
|
|
@@ -9263,7 +9263,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
9263
9263
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
9264
9264
|
gl_FragColor = vec4(light, 1.0);
|
|
9265
9265
|
}
|
|
9266
|
-
`,transparent:!0,blending:nn,depthWrite:!1,side:xi,fog:!1});this.object=new bt(new Gi(i1.RADIUS,128,32,0,Math.PI*2,0,Ie.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ie.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ps.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=ps.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class mf{constructor(t){this.generator=t}static SIZE=128;target=new Ph(mf.SIZE,{type:Be,generateMipmaps:!1,minFilter:ye,magFilter:ye});camera=new zg(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const l=c;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,l)=>{c.visible=a[l]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class _n{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){_n.install(),this.generator=new _m(t),this.eye=new mf(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=_n.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new mf(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==a),p=f().filter(({probe:m})=>d-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((v,y)=>y.probe.capturedAtMs<v.probe.capturedAtMs?y:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...s]),_n.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...s,...c]),l?.(m.probe.sharp),_n.decor=m.probe.filtered;for(const v of r)_n.reflectOn(v,m.probe);for(const v of n)v.shiny||_n.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(d-m.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:_n.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Nh?e.sharp&&s.setSurroundings(e.sharp):s instanceof Ia&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(_n.installed)return;_n.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!re.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}re.lights_fragment_maps=re.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function QC(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const Vu=900,ip=1,E2=4,np=5,Wu=.5,Xu=Si.GROUND_RADIUS_M;function A2(o){return Si.groundRadiusFor(o)}const sp=.5,rp=850,ap=.03,t6=.015,Wn=850,Gl=300,ga=120,e6=700,i6=3.5,$u=20,_2=.04,n6=.26,T2=4,op=1.5,R2=-1,s6=.01,vd=-4,r6=2,a6=20,Yu=2600,o6=.97,c6=.38,Vl=vd,l6=8,h6=2,I2=1500,u6=.7,d6=.3,f6=.32,p6=.65,D2=2.4,m6=.9,g6=400,v6=[0,45,90,135,180,225,270,315],M6=2,y6=16,C2=4e3,O2=880,qu=40,P2=60,x6=10,b6=1,w6=Si.REBUILD_DISTANCE_M,S6=55,E6=.5,A6=17,L2=.265,N2=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*L2,Math.sin(e)*L2]})],cp=700,lp=250/rg,_6=12,k2=5,hp=6,Ka=[.92,.92,.95],up=[.15,.15,.19],dp={snow:{fallSpeedMPerS:2,size:.3,color:new st(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new st(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Rc=0,fp=0,T6=150,pp=3e3,Wl=20,R6=15,U2=Rc,I6=40,F2=1,D6=9;function mp(o){return F2+(D6-F2)*o}const z2=new st(.75,.82,.92),C6=10,O6=.5;function B2(o){return rr(o/C6,O6,1)}const Za=200,H2=.18,G2=.32,P6=.35,V2=new st(.85,.9,.98),W2=5,X2=.85,$2=.01;function L6(o,t,e=1){return Math.round(o*($2+(1-$2)*t)*e)}function N6(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const Y2=230,q2=.7,K2=.05,k6=.6,U6=.7,F6=.15,Z2=.35,z6=3,B6=1/12,H6=.5,er=new st(.82,.86,1),G6=2500,V6=1.6,gp=15,W6={Venus:new st(1,.96,.85),Mars:new st(1,.55,.4),Jupiter:new st(.95,.87,.72),Saturn:new st(.92,.86,.68)};class Et{renderer;scene=new Ys;phenomena=new ks(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;camera;celestialGroup=new Oe;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+C2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),C2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new it;decorModelProvider=KC[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new Ee(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??Et.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Et.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new uM(16777215,0);celestialLightTarget=new bi;skyLight=new VA(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new fd;weather=Ef;observerElevationM=0;siteElevationM=0;air=new Ss;groundRadius=Xu;terrainRadius=Xu;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new it;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new uM(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new fd;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new fd;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=di.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new kh;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Hy()){this.renderer=new sI({canvas:t,antialias:!0}),this.resolution=new Fe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=nh,this.camera=new jn(60,t.width/Math.max(t.height,1),.1,Vu*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-ga,this.celestialLight.shadow.camera.right=ga,this.celestialLight.shadow.camera.top=ga,this.celestialLight.shadow.camera.bottom=-ga,this.celestialLight.shadow.camera.near=Wn-Gl,this.celestialLight.shadow.camera.far=Wn+Gl,this.celestialLight.shadow.bias=-.03/(2*Gl),this.celestialLight.shadow.normalBias=_2,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(er),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ve(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*lp,0,t.z*lp);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*pi,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*pi;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*pi,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(A2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Xu),this.camera.far=Math.max(Vu*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=Et.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Si.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===d&&this.setTerrainOrigin(t,e,i)}),Et.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<w6*(r/Xu))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(r2(t,e,this.terrainProviders,r,{route:this.observerRoute}),Et.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,y=v?ae(t,e,v.lat,v.lng):void 0;m&&y&&Math.hypot(y.x,y.z)<=a&&(u.position.y=m.position.y+this.groundYOfPatch(m,y.x,y.z)),m&&v&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=b6,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,g),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=Si.beamReachFor(this.beams,{lat:t,lng:e});if(!Si.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:g}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<i*Et.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??Si.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(r2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*Et.FAR_RING_OPEN_SHARE,referenceElevationM:s}),Et.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=Et.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-Et.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/Et.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Si.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>Et.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(uh(t,e,i)),Et.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>Et.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),Et.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(uh(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),Et.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),_n.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=we(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BLt9Dsxc.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>Et.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(uh(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),Et.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),_n.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=we(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-SElJhlLh.js");return{RailwaySystem:t}},[],import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=we(async()=>{const{TraceSystem:t}=await import("./TraceSystem-DpokUmzt.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(np);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=yt.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new hi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyLensFlareTint(t){if(!this.lensFlare)return;const e=S6*(this.sunArriving[1]/A6);this.lensFlare.uniforms.uColorGain.value.setRGB(e*t[0],e*t[1],e*t[2]),this.applyDazzleStrength()}applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=ln.K*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(QC(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!N6(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=Ss.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:La.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=H6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(Et.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=Et.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=Et.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),yt.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,l6);for(const i of t){const n=yt.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<h6,i.lamp),i.model&&i.id.startsWith(gn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=we(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D_EBfThB.js");return{ContrailSystem:t}},__vite__mapDeps([0,1]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=Et.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=zn.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ie.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(t){t!==this.beams&&(this.beams=t,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(t.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=we(async()=>{const{BeamSystem:t}=await import("./BeamSystem-Ddt2lTBT.js");return{BeamSystem:t}},[],import.meta.url).then(({BeamSystem:t})=>{const e=new t;this.scene.add(e.group),this.beamSystem=e})}updateBeams(){const t=this.decorReferencePose;!this.beamSystem||t?.lat===void 0||t.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(e,i,n)=>this.transmittanceTo(e,i,n),groundYAt:(e,i)=>this.groundYUnder(e,i)})}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Ye(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*pi)/Math.cos(t.lat*pi)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?(u,d)=>c.relativeOfLuminance(u,d):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,l)=>(a*e+(c+l)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await ep(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(Bd(t))||!yt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=jC(i.scene);n.traverse(s=>{s instanceof bt&&(s.userData.sharedModel=!0)}),yt.applyModelParameters(n,t.modelParameters,i.bindings),yt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(t.id,i.credit)}standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?Ey[t.kind]:Bd(t);if(!(!n||!yt.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await ep(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&_n.reflectOn(c);const h={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=ep(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||_n.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&al(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=Er(s,i),g=yt.occupantView(s,p.headingDeg),m=-(p.headingDeg??0)*pi,v=g.x*Math.cos(m)+g.z*Math.sin(m),y=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+n.x,M=-p.northM+n.z;r.x=-(x+v),r.z=-(M+y),this.camera.position.y=this.groundYUnder(x,M)+g.eyeY,c=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*pi,-(g.headingDeg+this.indoorLookYawDeg)*pi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(g=>g.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const g=this.decorGroups.get(p.id);if(!g)continue;const m=Er(p,i),v=this.lampNudges.get(p.id),y=m.eastM+(v?.eastM??0)+n.x+r.x,x=-(m.northM+(v?.northM??0))+n.z+r.z,M=this.terrainMesh,b=`${M?.geometry.uuid}:${(y-(M?.position.x??0)).toFixed(3)}:${(x-(M?.position.z??0)).toFixed(3)}:${(M?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${h}`;if(g.userData.footprintKey!==b){if(p.kind==="wire"){const O=yt.wireGround(p,y,x,m.headingDeg,(L,N)=>this.groundYUnder(L,N));g.userData.footprintGroundY=O.startY,yt.shearWire(g,yt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(y,x),L=-(m.headingDeg??0)*pi,N=Math.cos(L),P=Math.sin(L);g.userData.footprintGroundY=O,ge.drape(yt.bodyOf(g),(z,B)=>this.groundYUnder(y+z*N+B*P,x-z*P+B*N)-O)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,y,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=b}const E=m.altitudeM>Et.AIRBORNE_M&&Math.hypot(y,x)<Et.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:g.userData.footprintGroundY;if(g.position.set(y,E+m.altitudeM,x),p.kind==="crop"){const O=Math.hypot(y,x);g.visible=O<=T6}const w=this.decorPresence.get(p.id),_=w!==void 0&&(i<w.fromMs||i>w.untilMs);w&&(g.visible=!_);const D=this.decorSunlight.get(p.id);D&&!_&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*pi);const I=cS(p,i);if(I!==void 0&&Et.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,y-(O?.position.x??0),x-(O?.position.z??0),g.position.y-(O?.position.y??0),m.headingDeg,m.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");g.userData.cropGroundKey!==L&&(yt.fitCropToGround(g,(N,P)=>this.groundYUnder(N,P)+m.altitudeM),g.userData.cropGroundKey=L)}if(!_){const O=g.position.distanceTo(this.camera.position);a=Math.max(a,O),O<Et.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateBeams();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.beams?.length&&this.terrainMeshOrigin?Si.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(Vu*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Er(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=yt.sizeOf(s),u=-(a.headingDeg??0)*pi,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=yt.fitTerrace(r,s,(g,m)=>this.terrainYUnder(c+g*d+m*f,l-g*f+m*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):fp}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+Et.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),g=u*u/(2*Et.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-g-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return fp;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=rr((e-r)/(a-r)*(s-1),0,s-1),u=rr((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return fp;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,g=u-f,m=(b,S)=>n.getY(b*s+S),v=m(f,d),y=m(f,d+1),x=m(f+1,d),M=m(f+1,d+1);return p+g<=1?v+(y-v)*p+(x-v)*g:M+(x-M)*(1-p)+(y-M)*(1-g)}groundUnderFootprint(t,e,i,n,s=0){return yt.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=is.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n){const s=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0,maxIso:t.maxIso,exposureSeconds:e,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?is.NONE:this.perception??is.NONE;if(Yi.uColorVision.value.set(...i.colorMatrix),Yi.uContrast.value=i.contrastGain,!t){Yi.uMedium.value=0;return}Yi.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:3;const n=t.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=r=>.065*t.exposureSeconds*r*this.filterTransmittance/(t.fNumber*t.fNumber*e);Yi.uMediumExposure.value=n!==void 0&&n>0?Math.min(1/(e*n),t.maxIso!==void 0?s(t.maxIso):1/0):s(t.iso)}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new it;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&yt.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?Ay(n,t):void 0,c=a!==void 0?Uo.lamps(a):If(n,t,this.lastAstronomy?.sun.altitudeDeg);yt.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=we(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-Cz4cc2lG.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=yt.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-d6);r.y+=u6;const a=yt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*f6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?Uo.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*D2,this.camera.position.y-m6,n.z*D2);this.headlightSystem.aim("observer",e,s,n,p6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=yt.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=I2*yt.lampShare(n),c=new Cx(16764006,a*this.relativeScale,g6);n?.colorTemperatureK&&c.color.setRGB(...yt.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;yt.setLitWindowShare(t?un.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=r=>{const a=Ws.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Pt.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Ui.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,T2,new st(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<vd){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=T2/Wn*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ye(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ye(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(rr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?rr(e.separationDeg*n*pi/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*pi,moonRadiusRad:f*pi};const p=.01,g=(y,x)=>Ye(t.sun.altitudeDeg+y,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Gc(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateBeams());const e=this.scatteredSky?.ambient??Et.relativeSkyOf(Nm(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Ot.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??I2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?Xt.DEFAULT_AEROSOL_OPTICAL_DEPTH:La.opticalDepth(i))*Xt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ie.aureoleScale(n,Ie.airMass(t.altitudeDeg))*s,c=Ie.coronaScale(r),l=Ie.illuminanceOf(t.magnitude),h=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new i1,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ie.profile(Ie.HAZE_COARSE_MODE),d=Ie.profile(Ie.CLOUD_DROPLETS),f=VM(t.altitudeDeg),p=new Float32Array(Ie.STEPS*3);let g=0;for(let x=0;x<Ie.STEPS;x++){const M=x*3,b=[0,1,2].map(E=>l*f[E]*(a*u[M+E]+c*d[M+E])),S=Ws.shown(b,Ws.luminanceOf(b),(E,w)=>e.relativeOfLuminance(E,w));p.set(S,M),g=Math.max(g,Ws.response(S))}const{x:m,y:v,z:y}=Ye(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof Lo||(this.scene.fog=new Lo),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,Et.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:Ui.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Ui.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?y6:M6),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new vC(rp),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):md(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(t){if(t.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Yn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):md(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new ri,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(t,this.relativeScale,e=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),e=>this.cloudTransmission(e)),this.render())}pickPlumeAt(t,e){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,Et.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(t,e)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(ap*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(gn.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(ap*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=Vl,s=!n&&t.moon.altitudeDeg>=Vl,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*pi)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?S2.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=Vl&&(h=t.moon,u=S2.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*pi)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(n||s){const S=Ie.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)m[I]=S*E[I]*g*c,this.cloudBeam[I]=S*E[I];const{x:w,y:_,z:D}=Ye(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,_,D),u>0){const I=Ie.illuminanceOf(h.magnitude)*i,O=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),L=h===r?f:this.cloudTransmission(h);for(let N=0;N<3;N++)a[N]=I*O[N]*L*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),E=e.skyIrradiance,w=[0,1,2].map(D=>E[D]*S+m[D]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const _=jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(_*(w[0]+a[0]*d),_*(w[1]+a[1]*d),_*(w[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:y,y:x,z:M}=Ye(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(y,x,M),this.celestialLight.shadow.normalBias=_2*rr(x/n6,.1,1),this.placeShadowFrustum();const b=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/b,a[1]/b,a[2]/b),this.celestialLight.intensity=b,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=zn.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ie.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=Et.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof Rs||r instanceof Ia)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Et.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new R(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,n=i6;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=$u+5,i.near=this.shadowLightDistanceM-$u,i.far=this.shadowLightDistanceM+$u,i.updateProjectionMatrix(),e.bias=-.004/(2*$u),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Et.CABIN_SKY_SHARE&&(r.envMapIntensity=Et.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(e6,Math.max(ga,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(Gl,e*(Gl/ga));this.shadowLightDistanceM=Math.max(Wn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=e>2*ga?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=ga;shadowLightDistanceM=Wn;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*pi,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Pt.semiSaturation(Pt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new on,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem?.update(t)}setInstrument(t){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const e=Bi.starPointsOf(t),i=Bi.flareArtifactsOf(t);e===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=e,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=e,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return md(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.develop(this.renderer,t.frame,this.ghostOptics),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+Et.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&al(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Er(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=yt.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new _n(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Jn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,a=>this.measureSurroundings(a,n,s),t?0:_n.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,Et.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new hh;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>Ye(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,s,r=>{const a=f=>f.map(p=>p/e),c=this.surroundings,l={up:a(r.up),down:a(r.down)},h=(f,p)=>f.some((g,m)=>Math.abs(g-p[m])>.03*Math.max(Math.abs(g),Math.abs(p[m]),1e-12)),u=!c||h(c.up,l.up)||h(c.down,l.down);u&&(this.surroundings=l),this.eyeSettledVersion=-1;const d=this.scatteredSky?.adaptToSurroundings(Et.adaptingLuminance(Math.exp(r.logAverage)/e,l.down))??!1;if(!u&&!d){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Vl?t.sun:t.moon.altitudeDeg>=Vl?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;surroundings;animate(t,e){const i=Math.min(e/1e3,B6);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),yt.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),Yi.uRodShare.value=this.scatteredSky?.rodShare??0,Yi.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Yi.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Jn&&e.userData.pointSource||e instanceof bt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(np),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Ab),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new es({blending:Fo,blendSrc:xr,blendDst:xr,blendSrcAlpha:xr,blendDstAlpha:xr,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=we(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-CEn7MuVP.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>this.render());this.references=s;for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}referenceFailedToLoad(t){return this.references?.failedToLoad(this.documentRelative(t))??!1}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&Et.markDecorDepth(s,n.kind!=="crop")}t.layers.set(ip),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(_b),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new es({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(Et.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*pi}static isSolidSurface(t){if(!(t instanceof bt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==nn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof bt))return;e&&Et.isSolidSurface(i)?i.layers.enable(ip):i.layers.disable(ip)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new it),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new pI(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+Et.EXPOSURE_BUDGET_MS,s=Et.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Yi.uRodShare.value=this.scatteredSky?.rodShare??0,Yi.uHasOverlay.value=1,Yi.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Ys,n=new Is(-1,1,1,-1,0,2),s=qu/(O2*Math.tan(P2*pi/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new Cl(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new hn,i=new R,n=this.camera.getWorldDirection(new R),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<Et.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;c=Math.min(c,m),l=Math.max(l,m),h=Math.min(h,v),u=Math.max(u,v)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new it),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new fh(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Yi.uMediumExposure.value)}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new it);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new $n(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new it);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new e1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new it);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new vi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new it(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);if(this.projectionKind==="equidistant"&&this.equidistantPass)return vi.ndcFor(e,this.camera.fov,n);if(e.z>=0)return;const s=Math.tan(this.camera.fov/2*pi);return{ndcX:e.x/-e.z/(n*s),ndcY:e.y/-e.z/s}}screenPointScratch=new R;screenPointQuaternion=new ts;screenPointSize=new it;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(E2),this.camera.layers.set(E2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of N2)this.isSunOccluded(e[0],e[1])||t++;return t/N2.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),t!==0||e!==0){const a=Math.PI/180,c=this.sunOcclusionRightScratch.set(n.z,0,-n.x);c.lengthSq()<1e-9&&c.set(1,0,0),c.normalize();const l=this.sunOcclusionUpScratch.crossVectors(c,n).normalize();n.addScaledVector(c,t*a).addScaledVector(l,e*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const m=(s.position.y-t.y)/e.y;if(m>n&&m<i){const v=t.x+e.x*m-s.position.x,y=t.z+e.z*m-s.position.z;if(Math.hypot(v,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[m,v,y]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(v)<1e-12){if(m<x||m>M)return!1;continue}const b=(x-m)/v,S=(M-m)/v;d=Math.max(d,Math.min(b,S)),f=Math.min(f,Math.max(b,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,y=t.x+e.x*v,x=t.y+e.y*v,M=t.z+e.z*v;if(x<=this.groundYUnder(y,M))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Wu;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>Et.isSolidSurface(l.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=s6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=Et.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const l=Math.acos(rr(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=t6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?Et.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new hn,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,g=d.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||c!==void 0&&c<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),y=Math.atan(p/m);if(y>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;y<h&&(h=y,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(ap*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Wu)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new hn;bodyCornerScratch=new R;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let c=0;c<8;c++){const l=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*pi/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new Sa;decorHitScratch=new R;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Et.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=Et.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=Et.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!n)return;const s=this.raycaster.ray;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,n.distance-Et.RAILWAY_GROUND_MARGIN_M,Wu))return;const r=i.group.worldToLocal(n.point.clone()),a=i.lineAt(r.x,r.z);if(!a)return;const c=i.contactHeightM(a);return{line:a,distanceM:n.distance,...c!==void 0?{contactM:c}:{}}}pickBeamAt(t,e){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,Et.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,Wu))return;const r=Et.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())yt.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<Et.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Gi(Vu,32,16),i=e.attributes.position,n=e.getAttribute("color")??new le(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=vI(i.getX(r),i.getY(r),i.getZ(r)),l=AI(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new es({vertexColors:!0,side:xi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new bt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=A2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Cg(this.groundRadius,48),i=new Rs({color:new st(sp,sp,sp),fog:!0});Lo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new bt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=Ye(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-ke.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*o6);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-ke.iceAlphaAt(i,Yu,r,this.cloudFieldOffset)*c6),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<vd){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=Ye(e.altitudeDeg,e.azimuthDeg,Wn),l=VM(e.altitudeDeg),h=this.cloudTransmission(e),u=this.arrivingIlluminance(e,s,h),d=Et.unitLuminance(n);let f=this.bodyMeshes.get(t);if(t==="sun"){const p=Math.PI*(i/Wn)**2,g=[0,1,2].map(v=>d[v]*u[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(Et.BRIGHTEST_RELATIVE,v));f instanceof bt||(this.disposeMesh(f),f=new bt(new Gi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(f),this.bodyMeshes.set(t,f)),f.material.color.setRGB(m[0],m[1],m[2]),f.scale.setScalar(i)}else{if(!(f instanceof Jn)){this.disposeMesh(f);const m=new ne;m.setAttribute("position",new ce(new Float32Array(3),3)),m.setAttribute("color",new ce(new Float32Array(3),3)),f=new Jn(m,Ot.material(Co[Co.length-1].size,!1)),Ot.track(f),this.celestialGroup.add(f),this.bodyMeshes.set(t,f)}const p=f.geometry.getAttribute("color"),g=t.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*u[0]*g,d[1]*u[1]*g,d[2]*u[2]*g),p.needsUpdate=!0}if(f.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=u),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,u,i/Wn*(180/Math.PI),Et.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,c*p),this.lensFlare||(this.lensFlare=gC(),this.lensFlare.uniforms.uOpacity.value=E6,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(l)}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<vd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ye(t.altitudeDeg,t.azimuthDeg,Wn),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??mr.MEAN_RADIUS_DEG,h=Wn*Math.tan(l*pi),u=Math.max(rr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Wn)**2,d=new st(...c.map(g=>Math.min(Et.BRIGHTEST_RELATIVE,g/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(rr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Cl?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=j2(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Cl(new dd({map:j2(t.phase),color:d,fog:!1,blending:nn,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=r6){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return Et.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new st;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Ot.CONE_SOLID_ANGLE/e)}pointScratch=new it;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ie.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Ws.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new dd({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Cl(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(ln.radiusDeg(ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new ln(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=Eo(t.magnitude,e),s=X0(n);this.cometKey=i,this.setBodyMesh(i,t.position,op*(.5+.5*n),new st(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new cs(Wn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Di,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Yu},0);return}const s=this.lowerCloudCover(),r=ue.deckLitUntilDeg(ue.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ve.SUN_MAGNITUDE:e.magnitude),l=ue.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=Ye(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Yu},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Jb,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new So,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?ve.SUN_MAGNITUDE:e.magnitude,a6),c=os.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=Ye(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Ea,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Ns.galactic(i,n),r=Et.directionOf(s.centre),a=Et.directionOf(s.rotation),c=Et.directionOf(s.pole),l=new ie().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=Et.directionOf(Ns.eclipticPole(i,n)),u=Et.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:Et.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ye(t.altitudeDeg,t.azimuthDeg,1);return new R(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=Eo(n.magnitude,e),a=X0(r);this.setBodyMesh(s,n.position,op*(.5+.5*r),new st(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=Eo(n.magnitude,e),r=X0(s),a=W6[n.body]??new st(1,1,1),c=new st(a.r*r,a.g*r,a.b*r),l=op*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new Bs(n,s),a=vp(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<R2)continue;const{x:p,y:g,z:m}=Ye(d,f,rp);c.push({x:p,y:g,z:m,brightness:Eo(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ie.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of qD){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<R2)continue;const{x:f,y:p,z:g}=Ye(u,d,rp);this.namedStars.push({star:h,direction:new R(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Co.map((h,u)=>{const d=c.filter(b=>Ff(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((b,S)=>{f[S*3]=b.x,f[S*3+1]=b.y,f[S*3+2]=b.z,p[S]=b.brightness,g.set(b.illuminance,S*3),m[S]=b.phase,v[S]=b.speedFactor});const y=new ne;y.setAttribute("position",new ce(f,3)),y.setAttribute("seed",new ce(m.map(b=>b/(2*Math.PI)),1));const x=new ce(new Float32Array(d.length*3),3);y.setAttribute("color",x);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new Jn(y,Ot.material(h.size)),Ot.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ot.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Zc(this.celestialGroup,cp,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new st(Ka[0]+(up[0]-Ka[0])*e,Ka[1]+(up[1]-Ka[1])*e,Ka[2]+(up[2]-Ka[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Dm(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Cm(cp);this.cloudMesh=new bt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Dm(new st(...Ka),t,Yu,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new bt(Cm(cp*1.04),e),this.cirrusMesh.renderOrder=k2-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Zc.deckOrder(!0,0,1):k2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??rg)-this.observerElevationM)*lp;return Math.sign(e||1)*Math.max(Math.abs(e),_6)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*gp*this.relativeScale/Math.PI,l=new st(e[0]+er.r*c,e[1]+er.g*c,e[2]+er.b*c);this.layeredClouds?.setLighting(n.clone(),new st(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return L6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,pp],[this.rainSplashSystem?.points,Za],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:dp[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=B2(mp(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=dp[t],i=e.poolSize,n=vp(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const M=n()*Math.PI*2,b=n()*e.radiusM;s[x*3]=Math.cos(M)*b,s[x*3+1]=Rc+n()*(e.topYM-Rc),s[x*3+2]=Math.sin(M)*b,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const g=new ne;g.setAttribute("position",new ce(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new st(...this.baseFogColor)},uTexture:{value:X6(t)},uNearFocusDistance:{value:W2},uHazeDistance:{value:e.radiusM*X2}},v=new Se({uniforms:m,vertexShader:J6,fragmentShader:j6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new Jn(g,v);y.renderOrder=hp,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=dp[i];if(this.precipitationUniforms?.uColor.value.copy(Et.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*pi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let M=0,b=0;M<c.length;M+=3,b++){if(x&&f[b]>0){if(f[b]-=e,f[b]<=0){const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_,f[b]=0}else{const w=1-f[b]/g[b];c[M+1]=Rc+Math.sin(Math.PI*w)*p[b],c[M]=Ku(c[M]+(r+m[b])*e,n.radiusM),c[M+2]=Ku(c[M+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,E=0;if(y){const w=k6*u[b],_=U6*d[b];S=Math.sin(t*w*Math.PI*2+l[b])*_,E=Math.sin(t*w*Math.PI*2+l[b]+Math.PI/2)*_}if(c[M]+=(r+S)*e,c[M+1]-=n.fallSpeedMPerS*h[b]*e,c[M+2]+=(a+E)*e,c[M]=Ku(c[M],n.radiusM),c[M+2]=Ku(c[M+2],n.radiusM),c[M+1]<Rc){if(x){p[b]=Z2*(.2+Math.random()*1.6),g[b]=F6*(.5+Math.random()),f[b]=g[b];const D=Math.random()*Math.PI*2,I=z6*(p[b]/Z2);m[b]=Math.cos(D)*I,v[b]=Math.sin(D)*I,c[M+1]=Rc;continue}const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=mp(this.weather.precipitationIntensity);this.rainSystem=dC({count:pp,radiusM:Wl,heightM:R6,bottomYM:U2,overallSpeed:I6,color:z2.clone(),opacity:.85,visibleCount:this.precipitationCount(pp),speedStreak:B2(t),pixelSize:Y2,seed:9001,nearFocusDistanceM:W2,hazeDistanceM:Wl*X2,hazeColor:new st(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=hp,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=vp(4242),e=new Float32Array(Za*3),i=new Float32Array(Za),n=new Float32Array(Za),s=new Float32Array(Za);for(let h=0;h<Za;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Wl;e[h*3]=Math.cos(u)*d,e[h*3+1]=U2,e[h*3+2]=Math.sin(u)*d,n[h]=J2(H2,G2),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ne;r.setAttribute("position",new ce(e,3));const a=new ce(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Za));const c=new Se({uniforms:{uMaxSize:{value:P6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:V2.clone()},uTexture:{value:q6()}},vertexShader:K6,fragmentShader:Z6,transparent:!0,depthWrite:!1}),l=new Jn(r,c);l.renderOrder=hp,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*pi;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-mp(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(Et.litBySky(z2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Et.litBySky(V2,this.baseFogColor));const n=this.weather.windDirectionDeg*pi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Wl,c=h=>(h%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=q2+(1-q2)*(1-l),u=K2+(1-K2)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=Y2*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Wl;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=J2(H2,G2),n[l]=0}a[l]=n[l]/s[l]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const l=Qi.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(G6/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*gp*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+er.r*l,this.airlight[1]+er.g*l,this.airlight[2]+er.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*V6;r.setRGB(1+c*er.r,1+c*er.g,1+c*er.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*gp*this.relativeScale,e){const{x:c,y:l,z:h}=Ye(25,e.azimuthDeg,Wn);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Aa(Wn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=v6.map(t=>{const e=Po.point(t,this.compassPoints),i=new dd({map:Q6(e),depthTest:!1,fog:!1}),n=new Cl(i),{x:s,y:r,z:a}=Ye(0,t,O2);return n.position.set(s,r,a),n.scale.set(qu,qu,1),n.renderOrder=x6,n.layers.set(np),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=P2*Math.PI/360,i=qu*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const pi=Math.PI/180;function rr(o,t,e){return Math.max(t,Math.min(e,o))}function J2(o,t){return o+Math.random()*(t-o)}function Ku(o,t){return(o%(t*2)+t*3)%(t*2)-t}let Zu,Ju;function X6(o){switch(o){case"snow":return $6();case"hail":return Y6()}}function $6(){if(Zu)return Zu;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),Zu=new ia(t),Zu}function Y6(){if(Ju)return Ju;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),Ju=new ia(t),Ju}let ju;function q6(){if(ju)return ju;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),ju=new ia(t),ju}const K6=`
|
|
9266
|
+
`,transparent:!0,blending:nn,depthWrite:!1,side:xi,fog:!1});this.object=new bt(new Gi(i1.RADIUS,128,32,0,Math.PI*2,0,Ie.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ie.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ps.toHalfFloat(Math.min(e[i*3+n],6e4));this.texels[i*4+3]=ps.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class mf{constructor(t){this.generator=t}static SIZE=128;target=new Ph(mf.SIZE,{type:Be,generateMipmaps:!1,minFilter:ye,magFilter:ye});camera=new zg(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,n=[]){const s=t.shadowMap.autoUpdate;let r=!1;e.traverse(c=>{const l=c;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(r=!0)}),t.shadowMap.autoUpdate=r?s:!1;const a=n.map(c=>c.visible);for(const c of n)c.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),n.forEach((c,l)=>{c.visible=a[l]}),t.shadowMap.autoUpdate=s,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class _n{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){_n.install(),this.generator=new _m(t),this.eye=new mf(this.generator)}static decor;refresh(t,e,i,n,s,r,a,c=[],l,h=_n.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new mf(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==a),p=f().filter(({probe:m})=>d-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((v,y)=>y.probe.capturedAtMs<v.probe.capturedAtMs?y:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...s]),_n.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...s,...c]),l?.(m.probe.sharp),_n.decor=m.probe.filtered;for(const v of r)_n.reflectOn(v,m.probe);for(const v of n)v.shiny||_n.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(d-m.capturedAtMs))))}scratch=new R;static reflectOn(t,e={filtered:_n.decor}){t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Nh?e.sharp&&s.setSurroundings(e.sharp):s instanceof Ia&&e.filtered&&s.envMap!==e.filtered&&(s.envMap=e.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(_n.installed)return;_n.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!re.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}re.lights_fragment_maps=re.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function QC(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.rareIceCrystals===t.rareIceCrystals&&o.lowerCloudCover===t.lowerCloudCover&&o.relativeHumidity===t.relativeHumidity&&o.precipitationType===t.precipitationType&&o.precipitationIntensity===t.precipitationIntensity&&o.precipitationAmount===t.precipitationAmount&&o.windDirectionDeg===t.windDirectionDeg&&o.windSpeed===t.windSpeed&&o.storm===t.storm}const Vu=900,ip=1,E2=4,np=5,Wu=.5,Xu=Si.GROUND_RADIUS_M;function A2(o){return Si.groundRadiusFor(o)}const sp=.5,rp=850,ap=.03,t6=.015,Wn=850,Gl=300,ga=120,e6=700,i6=3.5,$u=20,_2=.04,n6=.26,T2=4,op=1.5,R2=-1,s6=.01,vd=-4,r6=2,a6=20,Yu=2600,o6=.97,c6=.38,Vl=vd,l6=8,h6=2,I2=1500,u6=.7,d6=.3,f6=.32,p6=.65,D2=2.4,m6=.9,g6=400,v6=[0,45,90,135,180,225,270,315],M6=2,y6=16,C2=4e3,O2=880,qu=40,P2=60,x6=10,b6=1,w6=Si.REBUILD_DISTANCE_M,S6=55,E6=.5,A6=17,L2=.265,N2=[[0,0],...Array.from({length:8},(o,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*L2,Math.sin(e)*L2]})],cp=700,lp=250/rg,_6=12,k2=5,hp=6,Ka=[.92,.92,.95],up=[.15,.15,.19],dp={snow:{fallSpeedMPerS:2,size:.3,color:new st(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new st(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Rc=0,fp=0,T6=150,pp=3e3,Wl=20,R6=15,U2=Rc,I6=40,F2=1,D6=9;function mp(o){return F2+(D6-F2)*o}const z2=new st(.75,.82,.92),C6=10,O6=.5;function B2(o){return rr(o/C6,O6,1)}const Za=200,H2=.18,G2=.32,P6=.35,V2=new st(.85,.9,.98),W2=5,X2=.85,$2=.01;function L6(o,t,e=1){return Math.round(o*($2+(1-$2)*t)*e)}function N6(o,t){return JSON.stringify(o.cloudLayers)===JSON.stringify(t.cloudLayers)&&o.cloudCover===t.cloudCover&&o.cloudDarkness===t.cloudDarkness&&o.cloudBaseM===t.cloudBaseM&&o.highCloudCover===t.highCloudCover&&o.iceCrystalAlignment===t.iceCrystalAlignment&&o.lowerCloudCover===t.lowerCloudCover}const Y2=230,q2=.7,K2=.05,k6=.6,U6=.7,F6=.15,Z2=.35,z6=3,B6=1/12,H6=.5,er=new st(.82,.86,1),G6=2500,V6=1.6,gp=15,W6={Venus:new st(1,.96,.85),Mars:new st(1,.55,.4),Jupiter:new st(.95,.87,.72),Saturn:new st(.92,.86,.68)};class Et{renderer;scene=new Ys;phenomena=new ks(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;onReferencesSettled;camera;celestialGroup=new Oe;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=e===void 0?void 0:setTimeout(n,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+C2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),C2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new it;decorModelProvider=KC[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new Ee(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??Et.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Et.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;beams=[];beamSystem;beamSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new uM(16777215,0);celestialLightTarget=new bi;skyLight=new VA(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new fd;weather=Ef;observerElevationM=0;siteElevationM=0;air=new Ss;groundRadius=Xu;terrainRadius=Xu;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new R;cloudFieldOffset=new R;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new R;rainLastVerticalFacing=-1;rainViewportSize=new it;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new uM(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new fd;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new fd;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=di.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new kh;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=Hy()){this.renderer=new sI({canvas:t,antialias:!0}),this.resolution=new Fe(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=nh,this.camera=new jn(60,t.width/Math.max(t.height,1),.1,Vu*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-ga,this.celestialLight.shadow.camera.right=ga,this.celestialLight.shadow.camera.top=ga,this.celestialLight.shadow.camera.bottom=-ga,this.celestialLight.shadow.camera.near=Wn-Gl,this.celestialLight.shadow.camera.far=Wn+Gl,this.celestialLight.shadow.bias=-.03/(2*Gl),this.celestialLight.shadow.normalBias=_2,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(er),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ve(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*lp,0,t.z*lp);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*pi,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*pi;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*pi,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(A2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Xu),this.camera.far=Math.max(Vu*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseElevationM=t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+t.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;observerRoute;setObserverRoute(t){this.observerRoute=t,this.decorTerrainRadiusM=Et.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return Si.decorReachFor(t,e)}placeTerrain(t,e,i,n){const s=(r,a)=>{const c=ae(a.lat,a.lng,t,e);r.position.x=c.x-i,r.position.z=c.z+n};if(this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;s(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const n=this.terrainProviders.patches;let s;if(n){if(!n.loaded){if(this.patchesAwaited!==n){this.patchesAwaited=n;const d=this.terrainProviders;this.awaitArrival(n.ready.then(()=>{this.terrainProviders===d&&this.setTerrainOrigin(t,e,i)}),Et.TERRAIN_PATIENCE_MS)}return}const u=n.nearest(t,e);u&&(t=u.lat,e=u.lng,s=u.radiusM)}const r=s??Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:u,z:d}=ae(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<w6*(r/Xu))return}const a=this.terrainRadius,c=this.terrainMeshOrigin;c!==void 0&&Math.hypot(ae(t,e,c.lat,c.lng).x,ae(t,e,c.lat,c.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(r2(t,e,this.terrainProviders,r,{route:this.observerRoute}),Et.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,y=v?ae(t,e,v.lat,v.lng):void 0;m&&y&&Math.hypot(y.x,y.z)<=a&&(u.position.y=m.position.y+this.groundYOfPatch(m,y.x,y.z)),m&&v&&y&&Math.hypot(y.x,y.z)<=a?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=b6,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,r),this.buildWater(t,e,r,p,g),this.buildRailways(t,e,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,r,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,n,s){n.geometry.computeBoundingBox();const r=n.position.y+(n.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,c=Si.beamReachFor(this.beams,{lat:t,lng:e});if(!Si.needsFarRing(i,a,c)){this.dropFarRing();return}if(this.farRing){const{x:p,z:g}=ae(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(p,g)<i*Et.FAR_RING_KEPT_SHARE)return}const l=this.terrainProviders.patches,h=l?.farRingOf?.(t,e);if(l&&!h){this.dropFarRing();return}const u=h?.radiusM??Si.FAR_RING_RADIUS_M,d=++this.farRingToken,f=this.terrainProviders;this.awaitArrival(r2(t,e,{elevation:f.elevation,imagery:f.imagery},u,void 0,{innerM:i*Et.FAR_RING_OPEN_SHARE,referenceElevationM:s}),Et.TERRAIN_PATIENCE_MS).then(({mesh:p})=>{if(d!==this.farRingToken||this.terrainProviders!==f){this.disposeMesh(p);return}this.dropFarRing(),this.farRingToken=d,p.renderOrder=Et.FAR_RING_RENDER_ORDER,p.position.y=n.position.y-Et.FAR_RING_DROP_M;const g=p.material;g.polygonOffset=!0,g.polygonOffsetFactor=2,g.polygonOffsetUnits=8,g.alphaTest=.5,this.farRing={mesh:p,origin:{lat:t,lng:e}},this.farRingRadiusM=u,this.scene.add(p),p.position.x=n.position.x,p.position.z=n.position.z,this.compileNextFrameOffThread(),this.render()},p=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",p))}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(t,e,i){if(this.grassReference){const r=ae(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const n=ae(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const n=t.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/Et.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(r)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=Si.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const n=this.terrainProviders.roads;if(!n||i>Et.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRoads(s.ways,t,e,n.contemporary);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,t,e,n.contemporary),this.awaitArrival(n.getRoads(uh(t,e,i)),Et.ROADS_PATIENCE_MS).then(r=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:r},this.drapeRoads(r,t,e,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(t,e,i,n,s){const r=this.terrainProviders.water;if(!r||i>Et.ROADS_MAX_RADIUS_M){this.clearWater();return}if(n){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:n},this.awaitArrival(this.drapeWater(n,t,e,i),Et.ROADS_PATIENCE_MS).catch(c=>console.warn("Water not drawn:",c));return}const a=this.waterSurfaces;if(a&&a.lat===t&&a.lng===e&&a.radiusM===i){this.drapeWater(a.surfaces,t,e,i);return}a&&Math.hypot(ae(t,e,a.lat,a.lng).x,ae(t,e,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,t,e,i),this.awaitArrival((s??r.getWater(uh(t,e,i))).then(c=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:c},this.drapeWater(c,t,e,i)}),Et.ROADS_PATIENCE_MS).catch(c=>{console.warn("Water unavailable, drawing none:",c)})}async drapeWater(t,e,i,n){if(t.length===0&&!this.waterSystem)return;const s=await this.loadWaterSystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n,this.patchSpacingM(r)),_n.reflectOn(s.group),this.waterAttribution=s.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=we(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BLt9Dsxc.js");return{WaterSystem:t}},[],import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const n=this.terrainProviders.railways;if(!n||i>Et.ROADS_MAX_RADIUS_M){this.clearRailways();return}const s=this.railwayLines;if(s&&s.lat===t&&s.lng===e&&s.radiusM===i){this.drapeRailways(s.lines,t,e,i);return}s&&Math.hypot(ae(t,e,s.lat,s.lng).x,ae(t,e,s.lat,s.lng).z)<=s.radiusM&&this.drapeRailways(s.lines,t,e,i),this.awaitArrival(n.getRailways(uh(t,e,i)).then(r=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:r},this.drapeRailways(r,t,e,i)}),Et.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(t,e,i,n){if(!this.railwaySystem&&!t.some(a=>a.level>=0))return;const s=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(s.group.position.copy(r.position),s.setGroundSpacing(this.patchSpacingM(r)),s.set(t,e,i,(a,c)=>this.groundYOfPatch(r,a,c),n),_n.reflectOn(s.group),this.railwayAttribution=s.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=we(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-SElJhlLh.js");return{RailwaySystem:t}},[],import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=we(async()=>{const{TraceSystem:t}=await import("./TraceSystem-DpokUmzt.js");return{TraceSystem:t}},[],import.meta.url).then(({TraceSystem:t})=>{const e=new t(np);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(e,n,s)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="building"&&!n.observerSide&&!n.track).map(n=>{const s=yt.naturalSize(n.kind,n.floors),r=(n.headingDeg??0)*Math.PI/180;return{x:i.x+n.eastM,z:i.z-n.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(n.sizeM?.lengthM??s.lengthM)/2,halfAcrossM:(n.sizeM?.widthM??s.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ae(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(n=>n.kind==="streetlight"&&!n.lamp?.supposed&&!n.track).map(n=>({x:i.x+n.eastM,z:i.z-n.northM}))}lampNudges=new Map;lampsToKerb(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const n of this.decorObjects){if(n.kind!=="streetlight"||!n.lamp?.supposed||n.track)continue;const s=i.x+n.eastM,r=i.z-n.northM,a=this.roadSystem.atKerb(s,r);(a.x!==s||a.z!==r)&&this.lampNudges.set(n.id,{eastM:a.x-s,northM:-(a.z-r)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,n)=>{const s=e[n];if(i.id!==s.id||(i.track?.length??-1)!==(s.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(s)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==s[a])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const n=this.wallsOf(t,e.lat,e.lng),s=this.roadWalls;s?.lat===e.lat&&s.lng===e.lng&&s.walls.length===n.length&&s.walls.every((a,c)=>a.what===n[c].what&&Math.hypot(a.x-n[c].x,a.z-n[c].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const n=this.decorOriginInRoads(e,i);return t.filter(s=>s.kind==="building"||s.kind==="streetlight").map(s=>({what:`${s.kind}:${s.lamp?.supposed?"s":""}${s.headingDeg??0}:${s.sizeM?.widthM??""}:${s.sizeM?.lengthM??""}`,x:n.x+s.eastM,z:n.z-s.northM}))}roadWalls;drapeRoads(t,e,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(t,e,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius,new hi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyLensFlareTint(t){if(!this.lensFlare)return;const e=S6*(this.sunArriving[1]/A6);this.lensFlare.uniforms.uColorGain.value.setRGB(e*t[0],e*t[1],e*t[2]),this.applyDazzleStrength()}applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,n=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=ln.K*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(t){this.compassHovered!==t&&(this.compassHovered=t,this.updateCompassVisibility())}setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassHovered||this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(QC(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!N6(e,t),n=e.precipitationType!==t.precipitationType,s=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;(e.relativeHumidity!==t.relativeHumidity||n||s)&&(this.air=Ss.of(t),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:t.relativeHumidity===void 0?void 0:La.steppedOpticalDepth(t.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),n?this.buildPrecipitation():s&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||n||s)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=t.storm&&t.cloudDarkness>=H6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(Et.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=Et.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=Et.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),yt.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,l6);for(const i of t){const n=yt.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,n,e.indexOf(i)<h6,i.lamp),i.model&&i.id.startsWith(gn.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=we(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-D_EBfThB.js");return{ContrailSystem:t}},__vite__mapDeps([0,1]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,n=Et.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(e&&i){const a=zn.litFraction(e.sunElevationDeg,e.heightM);if(a>0){const c=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ie.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*l*c[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setBeams(t){t!==this.beams&&(this.beams=t,this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),!(t.length===0&&!this.beamSystem)&&this.loadBeamSystem().then(()=>{this.updateBeams(),this.render()}))}get beamSegmentCount(){return this.beamSystem?.segmentCount??0}loadBeamSystem(){return this.beamSystemLoading??=we(async()=>{const{BeamSystem:t}=await import("./BeamSystem-Ddt2lTBT.js");return{BeamSystem:t}},[],import.meta.url).then(({BeamSystem:t})=>{const e=new t;this.scene.add(e.group),this.beamSystem=e})}updateBeams(){const t=this.decorReferencePose;!this.beamSystem||t?.lat===void 0||t.lng===void 0||this.beamSystem.update(this.beams,this.decorTime,{reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(e,i,n)=>this.transmittanceTo(e,i,n),groundYAt:(e,i)=>this.groundYUnder(e,i)})}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?Ye(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(t+s*n,e-r)-i}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*pi)/Math.cos(t.lat*pi)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,c=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},e,c?(u,d)=>c.relativeOfLuminance(u,d):void 0,i),this.bodySystem.setSmoke(n,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,c,l)=>(a*e+(c+l)/2*s)/Math.PI;return[r(t.r,i.r,n.r),r(t.g,i.g,n.g),r(t.b,i.b,n.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,n=t.credit??e?.credit;if(!(!i||!n))return{scene:await ep(i),credit:n,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(Bd(t))||!yt.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const n=jC(i.scene);n.traverse(s=>{s instanceof bt&&(s.userData.sharedModel=!0)}),yt.applyModelParameters(n,t.modelParameters,i.bindings),yt.applyModel(e,t,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(t.id,i.credit)}standInScenes=new Map;async loadDecorModel(t,e,i=!1){const n=i?Ey[t.kind]:Bd(t);if(!(!n||!yt.usesModel(t)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const c=i||t.kind==="tree"?await this.standInScene(r):await ep(r);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&_n.reflectOn(c);const h={ref:JSON.stringify(n),scene:c,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${t.id}":`,s)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=ep(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||_n.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const n=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?ae(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},s=this.decorObjects.find(p=>p.observerSide!==void 0&&al(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.lng,s?0:this.gaitOffset.eastM,s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let a=0,c;if(s){const p=Er(s,i),g=yt.occupantView(s,p.headingDeg),m=-(p.headingDeg??0)*pi,v=g.x*Math.cos(m)+g.z*Math.sin(m),y=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+n.x,M=-p.northM+n.z;r.x=-(x+v),r.z=-(M+y),this.camera.position.y=this.groundYUnder(x,M)+g.eyeY,c=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*pi,-(g.headingDeg+this.indoorLookYawDeg)*pi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const l=this.findCabin(i,n,r);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(g=>g.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const g=this.decorGroups.get(p.id);if(!g)continue;const m=Er(p,i),v=this.lampNudges.get(p.id),y=m.eastM+(v?.eastM??0)+n.x+r.x,x=-(m.northM+(v?.northM??0))+n.z+r.z,M=this.terrainMesh,b=`${M?.geometry.uuid}:${(y-(M?.position.x??0)).toFixed(3)}:${(x-(M?.position.z??0)).toFixed(3)}:${(M?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${h}`;if(g.userData.footprintKey!==b){if(p.kind==="wire"){const O=yt.wireGround(p,y,x,m.headingDeg,(L,N)=>this.groundYUnder(L,N));g.userData.footprintGroundY=O.startY,yt.shearWire(g,yt.sizeOf(p).lengthM,O.dropM)}else if(p.kind==="crossing"){const O=this.groundYUnder(y,x),L=-(m.headingDeg??0)*pi,N=Math.cos(L),P=Math.sin(L);g.userData.footprintGroundY=O,ge.drape(yt.bodyOf(g),(z,B)=>this.groundYUnder(y+z*N+B*P,x-z*P+B*N)-O)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,y,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=b}const E=m.altitudeM>Et.AIRBORNE_M&&Math.hypot(y,x)<Et.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:g.userData.footprintGroundY;if(g.position.set(y,E+m.altitudeM,x),p.kind==="crop"){const O=Math.hypot(y,x);g.visible=O<=T6}const w=this.decorPresence.get(p.id),_=w!==void 0&&(i<w.fromMs||i>w.untilMs);w&&(g.visible=!_);const D=this.decorSunlight.get(p.id);D&&!_&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*pi);const I=cS(p,i);if(I!==void 0&&Et.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const O=this.terrainMesh,L=[O?.geometry.uuid,y-(O?.position.x??0),x-(O?.position.z??0),g.position.y-(O?.position.y??0),m.headingDeg,m.altitudeM].map(N=>typeof N=="number"?N.toFixed(4):N).join(":");g.userData.cropGroundKey!==L&&(yt.fitCropToGround(g,(N,P)=>this.groundYUnder(N,P)+m.altitudeM),g.userData.cropGroundKey=L)}if(!_){const O=g.position.distanceTo(this.camera.position);a=Math.max(a,O),O<Et.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(s&&c!==void 0){const p=this.decorGroups.get(s.id);p&&(this.camera.position.y=p.position.y+c)}this.updateContrails(),this.updateBeams();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.beams?.length&&this.terrainMeshOrigin?Si.beamReachFor(this.beams,this.terrainMeshOrigin):0,f=Math.max(Vu*1.2,this.groundRadius*2.5,a*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let n=i;for(const s of this.terraces){const r=t-s.x,a=e-s.z,c=r*s.cos-a*s.sin,l=r*s.sin+a*s.cos;if(Math.abs(c)<=s.halfWidthM&&Math.abs(l)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(c))/s.bankM)),u=h*h*(3-2*h);n=Math.max(n,u*s.levelY+(1-u)*Math.min(s.levelY,i))}}return n}placeTerraces(t,e,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Er(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=yt.sizeOf(s),u=-(a.headingDeg??0)*pi,d=Math.cos(u),f=Math.sin(u),p=`${n?.geometry.uuid}:${(c-(n?.position.x??0)).toFixed(3)}:${(l-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(c,0,l),a.headingDeg!==void 0&&(r.rotation.y=u),r.userData.terraceKey!==p&&(r.userData.terraceLevelY=yt.fitTerrace(r,s,(g,m)=>this.terrainYUnder(c+g*d+m*f,l-g*f+m*d)),r.userData.terraceKey=p),this.terraces.push({x:c,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):fp}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const n=this.horizonByBearing.length,s=Math.round((t%360+360)%360/(360/n))%n;let r=this.horizonByBearing[s];return Number.isNaN(r)&&(r=this.horizonByBearing[s]=this.marchHorizon(s*360/n)),r}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+Et.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,n=t*Math.PI/180,s=Math.sin(n),r=-Math.cos(n),a=this.farRing?.mesh,c=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=c;u=Math.max(u+l,u*1.02)){const d=i.x+s*u,f=i.z+r*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):a.position.y+this.groundYOfPatch(a,d-a.position.x,f-a.position.z),g=u*u/(2*Et.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(p-g-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const n=t.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return fp;const r=n.getX(0),a=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=rr((e-r)/(a-r)*(s-1),0,s-1),u=rr((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return fp;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,g=u-f,m=(b,S)=>n.getY(b*s+S),v=m(f,d),y=m(f,d+1),x=m(f+1,d),M=m(f+1,d+1);return p+g<=1?v+(y-v)*p+(x-v)*g:M+(x-M)*(1-p)+(y-M)*(1-g)}groundUnderFootprint(t,e,i,n,s=0){return yt.groundUnderFootprint(t,e,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=is.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,n){const s=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:n??t.iso,autoExposure:t.autoExposure===!0,maxIso:t.maxIso,exposureSeconds:e,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?is.NONE:this.perception??is.NONE;if(Yi.uColorVision.value.set(...i.colorMatrix),Yi.uContrast.value=i.contrastGain,!t){Yi.uMedium.value=0;return}Yi.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:3;const n=t.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0,s=r=>.065*t.exposureSeconds*r*this.filterTransmittance/(t.fNumber*t.fNumber*e);Yi.uMediumExposure.value=n!==void 0&&n>0?Math.min(1/(e*n),t.maxIso!==void 0?s(t.maxIso):1/0):s(t.iso)}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new it;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&yt.setLights(s,n.lights,t,s.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(s),this.camera.position),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=n.kind==="vehicle"?Ay(n,t):void 0,c=a!==void 0?Uo.lamps(a):If(n,t,this.lastAstronomy?.sun.altitudeDeg);yt.setLit(r,n.kind,c,this.relativeScale,n.lamp);const l=this.streetlightLights.get(n.id);l&&(l.visible=c),a!==void 0&&(this.headlightSettings.set(n.id,a),this.aimDecorBeam(n,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=we(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-Cz4cc2lG.js");return{HeadlightSystem:t}},[],import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const n=new R(0,0,-1).transformDirection(e.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=yt.sizeOf(t).lengthM,r=e.getWorldPosition(new R).addScaledVector(n,s/2-d6);r.y+=u6;const a=yt.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,r,n,a*f6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?Uo.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,n=new R(Math.sin(i),0,-Math.cos(i)),s=new R(n.x*D2,this.camera.position.y-m6,n.z*D2);this.headlightSystem.aim("observer",e,s,n,p6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,n){const s=yt.bodyOf(e),r=s.children.find(l=>l.userData.emissive);if(!r)return;const a=I2*yt.lampShare(n),c=new Cx(16764006,a*this.relativeScale,g6);n?.colorTemperatureK&&c.color.setRGB(...yt.lampHue(n)),c.userData.candela=a,c.position.copy(r.position).multiply(s.scale),c.castShadow=i,c.shadow.mapSize.set(512,512),c.shadow.bias=-.002,e.add(c),this.streetlightLights.set(t,c)}applyWindowGlow(){const t=this.lastAstronomy;yt.setLitWindowShare(t?un.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=r=>{const a=Ws.luminanceOf(r);if(!(a>0))return[0,0,0];const c=Pt.relativeOfResponse(a)/a;return[r[0]*c,r[1]*c,r[2]*c]},n=i(t.zenith),s=i(t.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Ui.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,T2,new st(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<vd){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=T2/Wn*(180/Math.PI),n=i/e.sunRadiusDeg,s=Ye(t.sun.altitudeDeg,t.sun.azimuthDeg,1),r=Ye(t.moon.altitudeDeg,t.moon.azimuthDeg,1),a=Math.acos(rr(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),c=a>1e-9?rr(e.separationDeg*n*pi/a,0,2):0,l=Math.sin(a),[h,u]=a>1e-9?[Math.sin((1-c)*a)/l,Math.sin(c*a)/l]:[1,0],d={x:s.x*h+r.x*u,y:s.y*h+r.y*u,z:s.z*h+r.z*u},f=e.moonRadiusDeg*n;this.eclipseDiscs={sun:new R(s.x,s.y,s.z).normalize(),moon:new R(d.x,d.y,d.z).normalize(),sunRadiusRad:i*pi,moonRadiusRad:f*pi};const p=.01,g=(y,x)=>Ye(t.sun.altitudeDeg+y,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:n,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Gc(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateBeams());const e=this.scatteredSky?.ambient??Et.relativeSkyOf(Nm(t.sun.altitudeDeg),this.relativeScale),i=e,n=this.lightUnderClouds(t),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Ot.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=(r.userData.candela??I2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?Xt.DEFAULT_AEROSOL_OPTICAL_DEPTH:La.opticalDepth(i))*Xt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),r=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ie.aureoleScale(n,Ie.airMass(t.altitudeDeg))*s,c=Ie.coronaScale(r),l=Ie.illuminanceOf(t.magnitude),h=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),c.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new i1,this.celestialGroup.add(this.lunarDiffraction.object));const u=Ie.profile(Ie.HAZE_COARSE_MODE),d=Ie.profile(Ie.CLOUD_DROPLETS),f=VM(t.altitudeDeg),p=new Float32Array(Ie.STEPS*3);let g=0;for(let x=0;x<Ie.STEPS;x++){const M=x*3,b=[0,1,2].map(E=>l*f[E]*(a*u[M+E]+c*d[M+E])),S=Ws.shown(b,Ws.luminanceOf(b),(E,w)=>e.relativeOfLuminance(E,w));p.set(S,M),g=Math.max(g,Ws.response(S))}const{x:m,y:v,z:y}=Ye(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof Lo||(this.scene.fog=new Lo),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+e,Math.hypot(t-n.x,e-n.y,i-n.z))}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,n]=this.air.transmittance(t,t,Et.UMBRA_PATH_M),s=.2126*e+.7152*i+.0722*n;return s>0?[(.4124*e+.3576*i+.1805*n)/s,1,(.0193*e+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:Ui.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Ui.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?y6:M6),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new vC(rp),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):md(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(t){if(t.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new Yn,this.celestialGroup.add(this.reentrySystem.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):md(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(t,e,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(t){t.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new ri,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(t,this.relativeScale,e=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),e=>this.cloudTransmission(e)),this.render())}pickPlumeAt(t,e){if(!this.plumeSystem?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=this.plumeSystem.pickAt(i,Et.BEAM_PICK_PIXELS*this.contrailPixelRad(),this.skyLightTowards(i));return n&&this.groundHides(t,e)?void 0:n}get plumePuffCount(){return this.plumeSystem?.count??0}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(ap*this.camera.fov*Math.PI/180);let s,r=n;const a=new R;for(const[c,l]of this.decorGroups){if(!l.visible||!c.startsWith(gn.ID_PREFIX))continue;a.copy(l.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,s=c)}return s&&!this.groundHides(t,e)?s:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(ap*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(t,e)?void 0:n}updateCelestialLight(t,e){const i=this.relativeScale,n=t.sun.altitudeDeg>=Vl,s=!n&&t.moon.altitudeDeg>=Vl,r=n?t.sun:t.moon,a=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*pi)),l=this.siteElevationM+this.observerElevationM;let h=r,u=n||s?S2.directFraction(r.altitudeDeg,l):0;n&&u<=0&&t.moon.altitudeDeg>=Vl&&(h=t.moon,u=S2.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*pi)),f=n||s?this.cloudTransmission(r):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(n||s){const S=Ie.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(l,r.altitudeDeg);for(let I=0;I<3;I++)m[I]=S*E[I]*g*c,this.cloudBeam[I]=S*E[I];const{x:w,y:_,z:D}=Ye(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,_,D),u>0){const I=Ie.illuminanceOf(h.magnitude)*i,O=h===r?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),L=h===r?f:this.cloudTransmission(h);for(let N=0;N<3;N++)a[N]=I*O[N]*L*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),E=e.skyIrradiance,w=[0,1,2].map(D=>E[D]*S+m[D]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const _=jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(_*(w[0]+a[0]*d),_*(w[1]+a[1]*d),_*(w[2]+a[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||u<=0){this.celestialLight.intensity=0;return}const{x:y,y:x,z:M}=Ye(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(y,x,M),this.celestialLight.shadow.normalBias=_2*rr(x/n6,.1,1),this.placeShadowFrustum();const b=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/b,a[1]/b,a[2]/b),this.celestialLight.intensity=b,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=zn.litFraction(e.sunElevationDeg,e.heightM);if(s>0){const r=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),a=Ie.illuminanceOf(i.magnitude)*this.relativeScale,c=e.heightM>=Et.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)n[l]=Math.max(0,a*r[l]*s*c-this.sceneSunBeam[l])}}t.traverse(s=>{const r=s.material;if(!(r instanceof Rs||r instanceof Ia)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Et.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new R(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,t);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(t,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,n=i6;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=$u+5,i.near=this.shadowLightDistanceM-$u,i.far=this.shadowLightDistanceM+$u,i.updateProjectionMatrix(),e.bias=-.004/(2*$u),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Et.CABIN_SKY_SHARE&&(r.envMapIntensity=Et.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(e6,Math.max(ga,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,n=i.camera;n.left=-e,n.right=e,n.top=e,n.bottom=-e;const s=Math.max(Gl,e*(Gl/ga));this.shadowLightDistanceM=Math.max(Wn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=e>2*ga?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=ga;shadowLightDistanceM=Wn;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const n=i*pi,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)t+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),e+=s}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Pt.semiSaturation(Pt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new on,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem?.update(t)}setInstrument(t){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const e=Bi.starPointsOf(t),i=Bi.flareArtifactsOf(t);e===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=e,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=e,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}magnitudeLimitOf(t){const e=At.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return md(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const n=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.develop(this.renderer,t.frame,this.ghostOptics),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+Et.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of t){const a=e.get(r)?.currentProgram;(!a||a.isReady())&&t.delete(r)}t.size===0||performance.now()>i?n():setTimeout(s,10)};s()})}compileNextFrameOffThread(){this.compileBeforeNextDraw=!0}contextReleased=!1;releaseContext(){this.contextReleased||(this.contextReleased=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.compiling=void 0,this.cancelScatteredSkyPump(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e);const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(t,e,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&al(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Er(s,t),c=a.eastM+e.x+i.x,l=-a.northM+e.z+i.z,h=yt.sizeOf(s),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(c,l)<u&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<u&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new _n(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof Jn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],s,i,a=>this.measureSurroundings(a,n,s),t?0:_n.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,Et.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new hh;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>Ye(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,s,r=>{const a=f=>f.map(p=>p/e),c=this.surroundings,l={up:a(r.up),down:a(r.down)},h=(f,p)=>f.some((g,m)=>Math.abs(g-p[m])>.03*Math.max(Math.abs(g),Math.abs(p[m]),1e-12)),u=!c||h(c.up,l.up)||h(c.down,l.down);u&&(this.surroundings=l),this.eyeSettledVersion=-1;const d=this.scatteredSky?.adaptToSurroundings(Et.adaptingLuminance(Math.exp(r.logAverage)/e,l.down))??!1;if(!u&&!d){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Vl?t.sun:t.moon.altitudeDeg>=Vl?t.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*n,e.up[1]*n,e.up[2]*n]}}probeIrradiance;surroundings;animate(t,e){const i=Math.min(e/1e3,B6);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),yt.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const r=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,a,c)=>this.directionAtScreenPoint(r,a,c),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),Yi.uRodShare.value=this.scatteredSky?.rodShare??0,Yi.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Yi.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),s,r=>{this.lensFlare&&(this.lensFlare.mesh.visible=r?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Jn&&e.userData.pointSource||e instanceof bt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(s=>s.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(np),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Ab),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new es({blending:Fo,blendSrc:xr,blendDst:xr,blendSrcAlpha:xr,blendDstAlpha:xr,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(n=>{const s=this.documentRelative(n.src);return s===n.src?n:{...n,src:s}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=we(async()=>{const{ReferenceSystem:n}=await import("./ReferenceSystem-DKmWxtY-.js");return{ReferenceSystem:n}},[],import.meta.url).then(({ReferenceSystem:n})=>{const s=new n(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=s;for(const[a,c]of this.referenceViews)s.setView(a,c);s.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&s.set(r.references,void 0,r.observerAt),this.render(),s})}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);s&&Et.markDecorDepth(s,n.kind!=="crop")}t.layers.set(ip),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(_b),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new es({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const n=t.getObjectByName("head");if(!n)return;const s=((i-e)%360+540)%360-180,r=Math.max(-85,Math.min(Et.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*pi}static isSolidSurface(t){if(!(t instanceof bt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==nn}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof bt))return;e&&Et.isSolidSurface(i)?i.layers.enable(ip):i.layers.disable(ip)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new it),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new pI(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+Et.EXPOSURE_BUDGET_MS,s=Et.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let r=0;do{this.restateAt(t,this.exposureInstantsDone);const a=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=a[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Yi.uRodShare.value=this.scatteredSky?.rodShare??0,Yi.uHasOverlay.value=1,Yi.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Ys,n=new Is(-1,1,1,-1,0,2),s=qu/(O2*Math.tan(P2*pi/2));for(const a of this.compassSprites){if(!a.visible)continue;const c=a.getWorldPosition(new R).sub(this.camera.position).normalize(),l=this.screenPointOf(c);if(!l)continue;const h=new Cl(a.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(s/this.camera.aspect,s,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,n)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new hn,i=new R,n=this.camera.getWorldDirection(new R),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(e.setFromObject(a),e.isEmpty())||e.distanceToPoint(this.camera.position)<Et.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;c=Math.min(c,m),l=Math.max(l,m),h=Math.min(h,v),u=Math.max(u,v)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&t.push({x:c,y:h,width:l-c,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}usableDepthOfFieldPass(){const t=this.lensOptics;if(!t)return;const e=this.renderer.getDrawingBufferSize(new it),i=Math.max(1,Math.round(e.x)),n=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new fh(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Yi.uMediumExposure.value)}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new it);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new $n(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new it);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new e1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const t=this.renderer.getDrawingBufferSize(new it);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new vi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){t.setFromCamera(new it(e,i),this.camera);return}const s=n.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new R)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),n=i.x/Math.max(i.y,1);if(this.projectionKind==="equidistant"&&this.equidistantPass)return vi.ndcFor(e,this.camera.fov,n);if(e.z>=0)return;const s=Math.tan(this.camera.fov/2*pi);return{ndcX:e.x/-e.z/(n*s),ndcY:e.y/-e.z/s}}screenPointScratch=new R;screenPointQuaternion=new ts;screenPointSize=new it;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;t.uniforms.uResolution.value.set(n,s),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const n=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(n.x,n.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(E2),this.camera.layers.set(E2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of N2)this.isSunOccluded(e[0],e[1])||t++;return t/N2.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){const i=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&i.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(this.sunWorldPosition).sub(this.camera.position),s=n.length();if(n.normalize(),t!==0||e!==0){const a=Math.PI/180,c=this.sunOcclusionRightScratch.set(n.z,0,-n.x);c.lengthSq()<1e-9&&c.set(1,0,0),c.normalize();const l=this.sunOcclusionUpScratch.crossVectors(c,n).normalize();n.addScaledVector(c,t*a).addScaledVector(l,e*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(t,e,i,n=0){const s=this.groundMesh;if(s&&e.y<0){const m=(s.position.y-t.y)/e.y;if(m>n&&m<i){const v=t.x+e.x*m-s.position.x,y=t.z+e.z*m-s.position.z;if(Math.hypot(v,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(a.count));if(c<2||c*c!==a.count)return!1;const l=[r.position.x+a.getX(0),r.position.x+a.getX(c-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((c-1)*c)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(c-1);if(!(u>0))return!1;let d=n,f=i;for(const[m,v,y]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(v)<1e-12){if(m<x||m>M)return!1;continue}const b=(x-m)/v,S=(M-m)/v;d=Math.max(d,Math.min(b,S)),f=Math.min(f,Math.max(b,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,y=t.x+e.x*v,x=t.y+e.y*v,M=t.z+e.z*v;if(x<=this.groundYUnder(y,M))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Wu;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const c=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(l=>Et.isSolidSurface(l.object));c&&(r.occludesSourceIds?.includes(i)?n=n===void 0?c.distance:Math.max(n,c.distance):s=s===void 0?c.distance:Math.min(s,c.distance))}return{behindM:n,inFrontM:s}}pickBodyAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,n=this.raycaster.ray.direction,s=s6*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new R).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),a=this.eclipseDiscs,c=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],l=Et.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...c],s);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let n,s=1/0,r=1/0,a=!1;for(const c of e){const l=Math.acos(rr(c.direction.dot(t),-1,1))-c.radiusRad;if(l>i)continue;const h=l<=0,u=s<=0,d=c.inFront===!0;(h!==u?h:h?d!==a?d:c.radiusRad<r:l<s)&&(n=c.key,s=l,r=c.radiusRad,a=d)}return n}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=t6*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],c=a.length>0?Et.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let l,h=1/0;const u=new hn,d=new R;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new R).length()/2,g=d.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||c!==void 0&&c<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),y=Math.atan(p/m);if(y>r){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||c!==void 0&&c<x.distance)continue}else if(v>r)continue;y<h&&(h=y,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,n=Math.cos(ap*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const c=a.direction.dot(i);c>r&&(r=c,s={star:a.star,altitudeDeg:a.altitudeDeg})}return s&&this.groundHides(t,e)?void 0:s}groundHides(t,e){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Wu)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let a=0;a<8;a++){const c=this.bodyCornerScratch.set(a&1?e.max.x:e.min.x,a&2?e.max.y:e.min.y,a&4?e.max.z:e.min.z),l=this.screenPointOf(c.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),s=Math.max(s,l.ndcX),n=Math.min(n,l.ndcY),r=Math.max(r,l.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new hn;bodyCornerScratch=new R;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;const i=this.bodyBoxScratch.setFromObject(e);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let c=0;c<8;c++){const l=this.bodyCornerScratch.set(c&1?i.max.x:i.min.x,c&2?i.max.y:i.min.y,c&4?i.max.z:i.min.z),h=this.screenPointOf(l.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,n=0){const s=this.decorGroups.get(t);if(!s)return;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*pi/2):0}decorGrabHeightAt(t,e,i){const n=this.decorGroups.get(t);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),c=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return c?Math.min(Math.max(c.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new Sa;decorHitScratch=new R;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Et.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],n=Et.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=Et.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!n)return;const s=this.raycaster.ray;if(this.terrainMesh&&this.groundBlocks(s.origin,s.direction,n.distance-Et.RAILWAY_GROUND_MARGIN_M,Wu))return;const r=i.group.worldToLocal(n.point.clone()),a=i.lineAt(r.x,r.z);if(!a)return;const c=i.contactHeightM(a);return{line:a,distanceM:n.distance,...c!==void 0?{contactM:c}:{}}}pickBeamAt(t,e){const i=this.beamSystem;if(!i||i.segmentCount===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,s=i.pickAt(n.origin,n.direction,Et.BEAM_PICK_PIXELS*this.contrailPixelRad());if(!s||this.terrainMesh&&this.groundBlocks(n.origin,n.direction,s.distanceM-1,Wu))return;const r=Et.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(r&&r.distance<s.distanceM))return s}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],n=Math.hypot(t.x,t.y,t.z)||1,s=Math.max(0,Math.min(1,t.y/n));return i(e.horizon)+(i(e.zenith)-i(e.horizon))*Math.sqrt(s)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),this.phenomena.clear(),this.references?.disposeAll(),this.terrainBuildToken++,this.cancelScatteredSkyPump(),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.skyGradientMaterial),this.scatteredSky?.dispose(),this.scatteredSky=void 0,this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.beamSystem?.dispose(),this.beamSystem=void 0,this.beamSystemLoading=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.plumeSystem?.dispose(),this.plumeSystem=void 0,this.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())yt.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear(),this.lensFlare&&(this.lensFlare.mesh.removeFromParent(),this.lensFlare.mesh.geometry.dispose(),this.lensFlare.mesh.material.dispose(),this.lensFlare=void 0),this.renderer.dispose()}animationsRunning=!1;startTwinkle(){if(this.animationFrameId!==null||!this.needsAnimationLoop())return;this.cancelFlush();const t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const s=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!t||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&!this.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new R;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<Et.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Gi(Vu,32,16),i=e.attributes.position,n=e.getAttribute("color")??new le(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:c}=vI(i.getX(r),i.getY(r),i.getZ(r)),l=AI(a,c,t.azimuthDeg,t.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",n);const s=new es({vertexColors:!0,side:xi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new bt(e,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=A2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new Cg(this.groundRadius,48),i=new Rs({color:new st(sp,sp,sp),fog:!0});Lo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new bt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([r,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.z/10)}`).join(";")+(e?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=Ye(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-ke.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*o6);const r=e?0:this.weather.highCloudCover??0;return r>0&&(n*=1-ke.iceAlphaAt(i,Yu,r,this.cloudFieldOffset)*c6),Math.max(0,Math.min(1,n))}setBodyMesh(t,e,i,n,s){if(e.altitudeDeg<vd){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1);return}const{x:r,y:a,z:c}=Ye(e.altitudeDeg,e.azimuthDeg,Wn),l=VM(e.altitudeDeg),h=this.cloudTransmission(e),u=this.arrivingIlluminance(e,s,h),d=Et.unitLuminance(n);let f=this.bodyMeshes.get(t);if(t==="sun"){const p=Math.PI*(i/Wn)**2,g=[0,1,2].map(v=>d[v]*u[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(Et.BRIGHTEST_RELATIVE,v));f instanceof bt||(this.disposeMesh(f),f=new bt(new Gi(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(f),this.bodyMeshes.set(t,f)),f.material.color.setRGB(m[0],m[1],m[2]),f.scale.setScalar(i)}else{if(!(f instanceof Jn)){this.disposeMesh(f);const m=new ne;m.setAttribute("position",new ce(new Float32Array(3),3)),m.setAttribute("color",new ce(new Float32Array(3),3)),f=new Jn(m,Ot.material(Co[Co.length-1].size,!1)),Ot.track(f),this.celestialGroup.add(f),this.bodyMeshes.set(t,f)}const p=f.geometry.getAttribute("color"),g=t.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*u[0]*g,d[1]*u[1]*g,d[2]*u[2]*g),p.needsUpdate=!0}if(f.position.set(r,a,c),this.setHitArea(t,r,a,c,i),t==="sun"&&(this.sunArriving=u),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,r,a,c,u,i/Wn*(180/Math.PI),Et.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,c*p),this.lensFlare||(this.lensFlare=gC(),this.lensFlare.uniforms.uOpacity.value=E6,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(l)}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<vd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=Ye(t.altitudeDeg,t.azimuthDeg,Wn),a=this.cloudTransmission(t),c=this.arrivingIlluminance(t,t.magnitude,a),l=t.radiusDeg??mr.MEAN_RADIUS_DEG,h=Wn*Math.tan(l*pi),u=Math.max(rr(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Wn)**2,d=new st(...c.map(g=>Math.min(Et.BRIGHTEST_RELATIVE,g/u))),f=`${t.phase.phaseFraction<.5}:${Math.round(rr(t.phase.illuminatedFraction,0,1)*500)}`;let p=this.bodyMeshes.get(i);p instanceof Cl?(p.userData.phaseKey!==f&&(p.material.map?.dispose(),p.material.map=j2(t.phase),p.userData.phaseKey=f),p.material.color.copy(d)):(this.disposeMesh(p),p=new Cl(new dd({map:j2(t.phase),color:d,fog:!1,blending:nn,depthWrite:!1})),p.userData.phaseKey=f,this.celestialGroup.add(p),this.bodyMeshes.set(i,p)),p.scale.set(h*2,h*2,1),p.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,c,l)}bentLight(t,e,i=r6){const[n,s,r]=this.arrivingIlluminance(t,e,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(t,e){return Et.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new st;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Ot.CONE_SOLID_ANGLE/e)}pointScratch=new it;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),s=Ie.illuminanceOf(e)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(t){const e=Ws.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,n,s){let r=this.hitAreas.get(t);if(!r){const c=new dd({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Cl(c),this.celestialGroup.add(r),this.hitAreas.set(t,r)}r.position.set(e,i,n);const a=s*2;r.scale.set(a,a,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,n,s,r,a=0){if(ln.radiusDeg(ln.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(t);return}let c=this.glareSprites.get(t);c||(c=new ln(`veil:${t}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(t,c)),c.shine({x:e,y:i,z:n},s,r,a)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=Eo(t.magnitude,e),s=X0(n);this.cometKey=i,this.setBodyMesh(i,t.position,op*(.5+.5*n),new st(s,s,s),t.magnitude),this.cometTail||(this.cometTail=new cs(Wn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,n)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Di,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Yu},0);return}const s=this.lowerCloudCover(),r=ue.deckLitUntilDeg(ue.DECK_HEIGHT_M),a=t.altitudeDeg>-r?t:e,c=this.bentLight(a,a===t?ve.SUN_MAGNITUDE:e.magnitude),l=ue.strength(i,s,a.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=Ye(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},a.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Yu},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Jb,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new So,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=t.altitudeDeg>0,s=n?t:e,r=this.lowerCloudCover(),a=this.bentLight(s,n?ve.SUN_MAGNITUDE:e.magnitude,a6),c=os.strength(i,r,s.altitudeDeg)*a.scale;if(c<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=Ye(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,a.tint,n)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Ea,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=t.frame,s=Ns.galactic(i,n),r=Et.directionOf(s.centre),a=Et.directionOf(s.rotation),c=Et.directionOf(s.pole),l=new ie().set(r.x,r.y,r.z,a.x,a.y,a.z,c.x,c.y,c.z),h=Et.directionOf(Ns.eclipticPole(i,n)),u=Et.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:Et.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:At.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new R(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:n}=Ye(t.altitudeDeg,t.azimuthDeg,1);return new R(e,i,n).normalize()}buildNovae(t,e){const i=new Set;for(const n of t){if(n.magnitude>e)continue;const s=`nova:${n.id}`;i.add(s);const r=Eo(n.magnitude,e),a=X0(r);this.setBodyMesh(s,n.position,op*(.5+.5*r),new st(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of t){if(n.magnitude>e)continue;i.add(n.body);const s=Eo(n.magnitude,e),r=X0(s),a=W6[n.body]??new st(1,1,1),c=new st(a.r*r,a.g*r,a.b*r),l=op*(.5+.5*s);this.setBodyMesh(n.body,n.position,l,c,n.magnitude)}for(const n of[...this.bodyMeshes.keys()])i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n))}buildStars(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=t,r=new Bs(n,s),a=vp(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<R2)continue;const{x:p,y:g,z:m}=Ye(d,f,rp);c.push({x:p,y:g,z:m,brightness:Eo(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ie.illuminanceOf(u)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of qD){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<R2)continue;const{x:f,y:p,z:g}=Ye(u,d,rp);this.namedStars.push({star:h,direction:new R(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Co.map((h,u)=>{const d=c.filter(b=>Ff(b.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((b,S)=>{f[S*3]=b.x,f[S*3+1]=b.y,f[S*3+2]=b.z,p[S]=b.brightness,g.set(b.illuminance,S*3),m[S]=b.phase,v[S]=b.speedFactor});const y=new ne;y.setAttribute("position",new ce(f,3)),y.setAttribute("seed",new ce(m.map(b=>b/(2*Math.PI)),1));const x=new ce(new Float32Array(d.length*3),3);y.setAttribute("color",x);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new Jn(y,Ot.material(h.size)),Ot.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Ot.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;for(const i of this.starTiers){const n=i.colorAttribute.array;for(let s=0;s<i.brightness.length;s++)n[s*3]=i.illuminance[s*3]*e,n[s*3+1]=i.illuminance[s*3+1]*e,n[s*3+2]=i.illuminance[s*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Zc(this.celestialGroup,cp,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new st(Ka[0]+(up[0]-Ka[0])*e,Ka[1]+(up[1]-Ka[1])*e,Ka[2]+(up[2]-Ka[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Dm(i,t,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=n,this.cloudUniforms=s,s.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Cm(cp);this.cloudMesh=new bt(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Dm(new st(...Ka),t,Yu,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new bt(Cm(cp*1.04),e),this.cirrusMesh.renderOrder=k2-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Zc.deckOrder(!0,0,1):k2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??rg)-this.observerElevationM)*lp;return Math.sign(e||1)*Math.max(Math.abs(e),_6)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,a]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*gp*this.relativeScale/Math.PI,l=new st(e[0]+er.r*c,e[1]+er.g*c,e[2]+er.b*c);this.layeredClouds?.setLighting(n.clone(),new st(s,r,a),l,l);const h=Math.max(0,n.y);for(const u of i)u.sunDir.value.copy(n),u.sunColor.value.setRGB(s*h,r*h,a*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return L6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,pp],[this.rainSplashSystem?.points,Za],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:dp[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=B2(mp(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=dp[t],i=e.poolSize,n=vp(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),c=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const M=n()*Math.PI*2,b=n()*e.radiusM;s[x*3]=Math.cos(M)*b,s[x*3+1]=Rc+n()*(e.topYM-Rc),s[x*3+2]=Math.sin(M)*b,r[x]=n()*Math.PI*2,a[x]=.7+n()*.6,c[x]=.6+n()*.8,l[x]=.4+n()*1.2}const g=new ne;g.setAttribute("position",new ce(s,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new st(...this.baseFogColor)},uTexture:{value:X6(t)},uNearFocusDistance:{value:W2},uHazeDistance:{value:e.radiusM*X2}},v=new Se({uniforms:m,vertexShader:J6,fragmentShader:j6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new Jn(g,v);y.renderOrder=hp,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const n=dp[i];if(this.precipitationUniforms?.uColor.value.copy(Et.litBySky(n.color,this.baseFogColor)),e<=0)return;const s=this.weather.windDirectionDeg*pi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,c=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let M=0,b=0;M<c.length;M+=3,b++){if(x&&f[b]>0){if(f[b]-=e,f[b]<=0){const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_,f[b]=0}else{const w=1-f[b]/g[b];c[M+1]=Rc+Math.sin(Math.PI*w)*p[b],c[M]=Ku(c[M]+(r+m[b])*e,n.radiusM),c[M+2]=Ku(c[M+2]+(a+v[b])*e,n.radiusM)}continue}let S=0,E=0;if(y){const w=k6*u[b],_=U6*d[b];S=Math.sin(t*w*Math.PI*2+l[b])*_,E=Math.sin(t*w*Math.PI*2+l[b]+Math.PI/2)*_}if(c[M]+=(r+S)*e,c[M+1]-=n.fallSpeedMPerS*h[b]*e,c[M+2]+=(a+E)*e,c[M]=Ku(c[M],n.radiusM),c[M+2]=Ku(c[M+2],n.radiusM),c[M+1]<Rc){if(x){p[b]=Z2*(.2+Math.random()*1.6),g[b]=F6*(.5+Math.random()),f[b]=g[b];const D=Math.random()*Math.PI*2,I=z6*(p[b]/Z2);m[b]=Math.cos(D)*I,v[b]=Math.sin(D)*I,c[M+1]=Rc;continue}const w=Math.random()*Math.PI*2,_=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(w)*_,c[M+1]=n.topYM,c[M+2]=Math.sin(w)*_}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=mp(this.weather.precipitationIntensity);this.rainSystem=dC({count:pp,radiusM:Wl,heightM:R6,bottomYM:U2,overallSpeed:I6,color:z2.clone(),opacity:.85,visibleCount:this.precipitationCount(pp),speedStreak:B2(t),pixelSize:Y2,seed:9001,nearFocusDistanceM:W2,hazeDistanceM:Wl*X2,hazeColor:new st(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=hp,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=vp(4242),e=new Float32Array(Za*3),i=new Float32Array(Za),n=new Float32Array(Za),s=new Float32Array(Za);for(let h=0;h<Za;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Wl;e[h*3]=Math.cos(u)*d,e[h*3+1]=U2,e[h*3+2]=Math.sin(u)*d,n[h]=J2(H2,G2),i[h]=t()*n[h],s[h]=i[h]/n[h]}const r=new ne;r.setAttribute("position",new ce(e,3));const a=new ce(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Za));const c=new Se({uniforms:{uMaxSize:{value:P6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:V2.clone()},uTexture:{value:q6()}},vertexShader:K6,fragmentShader:Z6,transparent:!0,depthWrite:!1}),l=new Jn(r,c);l.renderOrder=hp,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*pi;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-mp(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(Et.litBySky(z2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Et.litBySky(V2,this.baseFogColor));const n=this.weather.windDirectionDeg*pi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Wl,c=h=>(h%(a*2)+a*3)%(a*2)-a;e.uniforms.uWindOffset.value.set(c(e.uniforms.uWindOffset.value.x+s*t),c(e.uniforms.uWindOffset.value.y+r*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=q2+(1-q2)*(1-l),u=K2+(1-K2)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=Y2*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=e,a=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=t,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Wl;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=J2(H2,G2),n[l]=0}a[l]=n[l]/s[l]}e.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>t)break;const l=Qi.brightnessAt(c,t);l>i&&(e=c,i=l)}const n=e?Math.min(1,Math.max(.1,(G6/e.distanceM)**2)):0,s=i*n*(e?.cloudToGround?1:.6);if(s===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*gp*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+er.r*l,this.airlight[1]+er.g*l,this.airlight[2]+er.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*V6;r.setRGB(1+c*er.r,1+c*er.g,1+c*er.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*gp*this.relativeScale,e){const{x:c,y:l,z:h}=Ye(25,e.azimuthDeg,Wn);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new Aa(Wn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,a),this.render()}buildCompassLabels(){this.compassSprites=v6.map(t=>{const e=Po.point(t,this.compassPoints),i=new dd({map:Q6(e),depthTest:!1,fog:!1}),n=new Cl(i),{x:s,y:r,z:a}=Ye(0,t,O2);return n.position.set(s,r,a),n.scale.set(qu,qu,1),n.renderOrder=x6,n.layers.set(np),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=P2*Math.PI/360,i=qu*Math.tan(t)/Math.tan(e);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const n=i.map;n&&n.dispose(),i.dispose()}}}const pi=Math.PI/180;function rr(o,t,e){return Math.max(t,Math.min(e,o))}function J2(o,t){return o+Math.random()*(t-o)}function Ku(o,t){return(o%(t*2)+t*3)%(t*2)-t}let Zu,Ju;function X6(o){switch(o){case"snow":return $6();case"hail":return Y6()}}function $6(){if(Zu)return Zu;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),Zu=new ia(t),Zu}function Y6(){if(Ju)return Ju;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),Ju=new ia(t),Ju}let ju;function q6(){if(ju)return ju;const o=64,t=document.createElement("canvas");t.width=o,t.height=o;const e=t.getContext("2d"),i=e.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,o,o),ju=new ia(t),ju}const K6=`
|
|
9267
9267
|
uniform float uMaxSize;
|
|
9268
9268
|
uniform float uScale;
|
|
9269
9269
|
attribute float aLife;
|
|
@@ -9329,10 +9329,10 @@ void main() {
|
|
|
9329
9329
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
9330
9330
|
}
|
|
9331
9331
|
`;function j2(o){const e=document.createElement("canvas");e.width=128,e.height=128;const i=e.getContext("2d"),n=128/2-2,s=128/2,r=128/2,a="#010101",c="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const l=rr(o.illuminatedFraction,0,1),h=o.phaseFraction<.5,u=n*Math.abs(1-2*l),d=l<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=c,i.beginPath(),h?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,u,n,0,Math.PI/2,-Math.PI/2,d)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,u,n,0,-Math.PI/2,Math.PI/2,d)),i.fill(),i.restore(),new ia(e)}function Q6(o){const t=document.createElement("canvas");t.width=128,t.height=128;const e=t.getContext("2d");return e.fillStyle="rgba(0, 0, 0, 0.55)",e.beginPath(),e.arc(64,64,60,0,Math.PI*2),e.fill(),e.fillStyle="#ffffff",e.font="bold 52px sans-serif",e.textAlign="center",e.textBaseline="middle",e.fillText(o,64,68),new ia(t)}function vp(o){let t=o;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class gf{constructor(t,e){this.source=t,this.create=e}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(t,e){this.disposed||(this.wanted={t,canvas:e},this.pumping||this.pump())}recordingChanged(t){this.scene&&(this.scene.sightingData=t)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const t=this.create();return t.setAttribute("max-pixel-ratio","1"),t.setAttribute("always-live",""),Object.assign(t.style,{position:"fixed",left:"-10000px",top:"0",width:`${gf.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(t),t.documentUrl=this.source.documentUrl,t.accountInTheRound=this.source.accountInTheRound,t.sightingData=this.source.sightingData,this.scene=t,t}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t,canvas:e}=this.wanted;this.wanted=void 0;const i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(t);for(let n=0;n<gf.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class ti{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const i=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,i).href}static hold(t,e){ti.held.set(t,e),ti.loaded.delete(t),ti.generation++}static release(){if(ti.held.size!==0){for(const t of ti.held.keys())ti.loaded.delete(t);ti.held.clear(),ti.generation++}}static bytes(t,e=fetch.bind(globalThis)){const i=ti.held.get(t);if(i)return Promise.resolve(i);let n=ti.loaded.get(t);return n||(n=e(t).then(async s=>{if(!s.ok)throw new Error(`Frozen data not found (${s.status}): ${t}`);return new Uint8Array(await s.arrayBuffer())}),ti.loaded.set(t,n),n.catch(()=>ti.loaded.delete(t))),n}static async json(t){return JSON.parse(new TextDecoder().decode(await ti.bytes(t)))}static async zip(t){const e=await ti.bytes(t),{unzipSync:i}=await we(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);return i(e)}}class Dr{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(t){this.ready=t.then(e=>{this.list=e},()=>{}).finally(()=>{this.loaded=!0})}nearest(t,e){let i,n=1/0;for(const s of this.list){if(s.far)continue;const{x:r,z:a}=ae(s.lat,s.lng,t,e),c=Math.hypot(r,a);c<n&&(n=c,i=s)}return i}farRingOf(t,e){return this.list.find(i=>i.far&&Math.abs(i.lat-t)<=Dr.SAME_BOUNDS_DEG&&Math.abs(i.lng-e)<=Dr.SAME_BOUNDS_DEG)}static boundsOf(t){return uh(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const i=(n,s)=>Math.abs(n-s)<=Dr.SAME_BOUNDS_DEG;return i(t.north,e.north)&&i(t.south,e.south)&&i(t.east,e.east)&&i(t.west,e.west)}static contains(t,e){return t.north>=e.north&&t.south<=e.south&&t.east>=e.east&&t.west<=e.west}static samePatches(t,e){return t.length===e.length&&t.every((i,n)=>i.lat===e[n].lat&&i.lng===e[n].lng&&i.radiusM===e[n].radiusM&&i.far===e[n].far)}}class vf{static async encode(t){const{zipSync:e,strToU8:i}=await we(async()=>{const{zipSync:r,strToU8:a}=await import("./browser-_Ncw3Jhn.js");return{zipSync:r,strToU8:a}},[],import.meta.url),n={},s={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((r,a)=>{const c=`${a}.f32`;return n[c]=vf.byPlane(r.grid.heights),{lat:r.lat,lng:r.lng,radiusM:r.radiusM,...r.far?{far:r.far}:{},bounds:r.grid.bounds,width:r.grid.width,height:r.grid.height,file:c}})};return n["index.json"]=i(JSON.stringify(s,null,1)),e(n,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(e));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(n=>{const s=t[n.file];if(!s||s.length!==n.width*n.height*4)return[];const r={heights:vf.fromPlanes(s),width:n.width,height:n.height,bounds:n.bounds};return[{lat:n.lat,lng:n.lng,radiusM:n.radiusM,...n.far?{far:n.far}:{},grid:r}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=t.length,n=new Uint8Array(e.length);for(let s=0;s<i;s++)for(let r=0;r<4;r++)n[r*i+s]=e[s*4+r];return n}static fromPlanes(t){const e=t.length/4,i=new Uint8Array(t.length);for(let n=0;n<e;n++)for(let s=0;s<4;s++)i[n*4+s]=t[s*e+n];return new Float32Array(i.buffer)}}class n1{constructor(t){this.annex=t}async getElevationGrid(t,e,i){const{patches:n}=await this.annex,s=n.find(a=>Dr.sameBounds(Dr.boundsOf(a),t));if(s)return{...s.grid,heights:new Float32Array(s.grid.heights)};const r=n.find(a=>Dr.contains(a.grid.bounds,t));if(r)return n1.resample(r.grid,t,e);throw new Error("The frozen relief does not hold this ground")}static resample(t,e,i){const{width:n,height:s}=i,r=new Float32Array(n*s),a=t.bounds.east-t.bounds.west,c=t.bounds.north-t.bounds.south;for(let l=0;l<s;l++){const h=e.north-(e.north-e.south)*(s>1?l/(s-1):0),u=Math.min(t.height-1,Math.max(0,(t.bounds.north-h)/c*(t.height-1))),d=Math.floor(u),f=Math.min(t.height-1,d+1),p=u-d;for(let g=0;g<n;g++){const m=e.west+(e.east-e.west)*(n>1?g/(n-1):0),v=Math.min(t.width-1,Math.max(0,(m-t.bounds.west)/a*(t.width-1))),y=Math.floor(v),x=Math.min(t.width-1,y+1),M=v-y,b=(w,_)=>t.heights[w*t.width+_],S=b(d,y)*(1-M)+b(d,x)*M,E=b(f,y)*(1-M)+b(f,x)*M;r[l*n+g]=S*(1-p)+E*p}}return{heights:r,width:n,height:s,bounds:e}}}function Rb(o,t){return o.find(e=>e.id===t)??o[0]}class tO{attribution;fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis);const e=t.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${e}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${e})`}async getImageryTexture(t,e){return zy(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const Ib=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:o=>new By({fetchImpl:o})},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:o=>new tO({fetchImpl:o})}];class Q2{static async encode(t){const{zipSync:e,strToU8:i}=await we(async()=>{const{zipSync:c,strToU8:l}=await import("./browser-_Ncw3Jhn.js");return{zipSync:c,strToU8:l}},[],import.meta.url),n={},s={};let r=0;for(const[c,l]of t.tiles){const h=`tiles/${r++}`;n[h]=l.bytes,s[c]={file:h,type:l.type}}const a={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:s};return n["index.json"]=i(JSON.stringify(a,null,1)),e(n,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(e)),n=new Map;for(const[s,{file:r,type:a}]of Object.entries(i.tiles)){const c=t[r];c&&n.set(s,{bytes:c,type:a})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:n}}}class $f{constructor(t,e=""){this.annex=t,this.attributionStated=e}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(t,e){return(await(this.provider??=this.annex.then(n=>(this.attributionRead=n.attribution,Rb(Ib,n.source).create($f.fetchFrom(n.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const i=typeof e=="string"?e:e instanceof URL?e.href:e.url,n=t.get(i);return n?new Response(n.bytes,{status:200,headers:{"content-type":n.type}}):new Response(null,{status:404})}}}class eO{constructor(t,e=""){this.annex=t,this.attributionStated=e}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(t=>{if(!t.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=t.attribution,Rb(Ib,t.source).create($f.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class s1{constructor(t){this.annex=t}attributionRead;contemporaryRead;async itemsFor(t){const e=await this.annex;return this.attributionRead=e.attribution,this.contemporaryRead=e.contemporary,e.patches.find(i=>Dr.sameBounds(Dr.boundsOf(i),t))?.items??[]}}class iO{constructor(t,e=""){this.attributionStated=e,this.reader=new s1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(t){return this.reader.itemsFor(t)}}class nO{constructor(t,e=""){this.attributionStated=e,this.reader=new s1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class sO{constructor(t,e=""){this.attributionStated=e,this.reader=new s1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(t){return this.reader.itemsFor(t)}}class Mf{static providers(t,e,i){const n=f=>Wc.held(t,f),s=n("relief"),r=n("imagery"),a=n("roads"),c=n("water"),l=n("railways");if(!s&&!r&&!a&&!c&&!l)return i;const h=f=>ti.address(f.src,e),u=[],d={...i};if(s){const f=ti.zip(h(s)).then(p=>vf.decode(p));d.elevation=new n1(f),u.push(f.then(p=>p.patches))}if(r){const f=ti.zip(h(r)).then(p=>Q2.decode(p));d.imagery=new $f(f,r.attribution),u.push(f.then(p=>p.patches))}if(a){const f=ti.json(h(a));d.roads=new iO(f,a.attribution),u.push(f.then(p=>p.patches))}if(c){const f=ti.json(h(c));d.water=new nO(f,c.attribution),u.push(f.then(p=>p.patches))}if(l){const f=ti.json(h(l));d.railways=new sO(f,l.attribution),u.push(f.then(p=>p.patches))}return d.patches=new Dr(Mf.firstRead(u)),d}static map(t,e){const i=ti.zip(ti.address(t.src,e)).then(n=>Q2.decode(n));return new eO(i,t.attribution)}static async firstRead(t){for(const e of t)try{const i=await e;if(i.length>0)return i.map(({lat:n,lng:s,radiusM:r,far:a})=>({lat:n,lng:s,radiusM:r,...a?{far:a}:{}}))}catch{}return[]}}class Vc{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,i){let n;try{n=await this.annex}catch{return{status:"failed"}}const s=c=>Math.abs(c.lat-t.lat)<=Vc.SAME_PLACE_DEG&&Math.abs(c.lng-t.lng)<=Vc.SAME_PLACE_DEG,a=n.answers.find(c=>s(c)&&Math.abs(c.startMs-e)<=Vc.SAME_TIME_MS&&Math.abs(c.endMs-i)<=Vc.SAME_TIME_MS)??n.answers.find(c=>c.startMs<=e&&c.endMs>=i);return a?a.answer:{status:"failed"}}}const Mp=7.5,yp=9;class ar{static cache=new Map;static load(t){let e=ar.cache.get(t);return e||(e=fetch(t).then(i=>i.arrayBuffer()).then(i=>ar.parse(i)),ar.cache.set(t,e)),e}static upTo(t,e){const i=t.filter((r,a)=>a===0||t[a-1].magnitudeLimit<e);if(i.length<=1)return ar.load(t[0].url);const n=i.map(r=>r.url).join(`
|
|
9332
|
-
`);let s=ar.cache.get(n);return s||(s=Promise.all(i.map(r=>ar.load(r.url))).then(r=>r.reduce((a,c)=>ar.concat(a,c))),ar.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class We{constructor(t){if(this.heights=t,t.length!==We.WIDTH*We.HEIGHT)throw new Error(`a lunar relief has ${We.WIDTH*We.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*We.SAMPLES_PER_DEGREE;static HEIGHT=180*We.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=We.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,l=s-a,h=(f,p)=>{const g=(f%We.WIDTH+We.WIDTH)%We.WIDTH,m=Math.min(We.HEIGHT-1,Math.max(0,p));return this.heights[m*We.WIDTH+g]},u=h(r,a)*(1-c)+h(r+1,a)*c,d=h(r,a+1)*(1-c)+h(r+1,a+1)*c;return(u*(1-l)+d*l)*We.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=We.BAND_FROM_DEG&&n<=We.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(We.WIDTH*We.HEIGHT),r=We.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),l=Math.floor((90-t)*r);for(let h=-a;h<=a;h++)for(let u=-a;u<=a;u++)Math.hypot(u,h)<=a&&(s[(l+h)*We.WIDTH+(c+u+We.WIDTH)%We.WIDTH]=Math.round(i/We.UNIT_KM));return new We(s)}static smooth(){return new We(new Int8Array(We.WIDTH*We.HEIGHT))}}class ws{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=ws.SAMPLES){const{s,u:r,w:a,distanceKm:c}=ws.frame(t,e),l=Math.PI/180,h=new Float32Array(n),u=We.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),g=Math.sin(f),m=p*r[0]+g*a[0],v=p*r[1]+g*a[1],y=p*r[2]+g*a[2];let x=0;for(let M=ws.SEARCH_FROM_DEG;M<=ws.SEARCH_TO_DEG;M+=ws.SEARCH_STEP_DEG){const b=Math.cos(M*l),S=Math.sin(M*l),E=b*s[0]+S*m,w=b*s[1]+S*v,_=b*s[2]+S*y,D=Math.asin(Math.max(-1,Math.min(1,_)))/l,I=Math.atan2(w,E)/l,O=u+i.heightKm(D,I),L=Math.atan2(O*S,c-O*b);L>x&&(x=L)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/c)/l}}static frame(t,e){const i=new Qr(e.lat,e.lng,e.elevationM),n=ta(t),s=Vm(t,i,!1),r=new Ce(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*ws.AU_KM,c=ws.bodyFixed(t),l=c(r),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=_D(t,i),f=Jg(d),p=Zr(d,new Ce(-r.x,-r.y,-r.z,n.t)),g=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),m=Math.atan2(-p.y,p.x),v=new Ce(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),y=new Ce(-Math.sin(m),-Math.cos(m),0,n.t);return{s:u,u:c(Zr(f,v)),w:c(Zr(f,y)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=ws.frame(t,e),c=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),h=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*l[u]);return{latDeg:Math.asin(h[2])/c,lonDeg:Math.atan2(h[1],h[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,l=Math.cos(c),h=Math.sin(c),u=l*i.upDeg+h*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const g=Math.max(0,u-f),m=Math.max(g,t.radiusDeg[a]);p>m&&(r+=.5*(p*p-m*m))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=GD(ut.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],c=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new Qr(e.lat,e.lng,e.elevationM),n=ta(t),s=Vm(t,i,!1),r=ws.bodyFixed(t)(new Ce(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class gh{static cache=new Map;static load(t){let e=gh.cache.get(t);return e||(e=gh.fetchRelief(t).catch(()=>{}),gh.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new We(new Int8Array(i.buffer,i.byteOffset,i.length))}}class yf{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=yf.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=yf.MATRICES[String(t.type)];if(!e)return is.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>is.IDENTITY[a]+(r-is.IDENTITY[a])*n),contrastGain:1}}}class r1{static ID="fatigue";id=r1.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return is.NONE}}class so{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=so.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:so.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(so.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return is.NONE;const n=i/so.MEASURED_LEVEL*so.MEASURED_LOSS_DB;return{colorMatrix:is.IDENTITY,contrastGain:10**(-n/20)}}}class vh{static ALL=[new yf,new so,new r1];static byId(t){return vh.ALL.find(e=>e.id===t)}static perceptionOf(t){return vh.ALL.reduce((e,i)=>is.combine(e,i.perceive(t?.[i.id]??{})),is.NONE)}static compact(t){const e={};for(const i of vh.ALL){const n=t[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(e[i.id]=s)}return Object.keys(e).length>0?e:void 0}}class xf{constructor(t){this.names=t}body(t,e){return this.names?.bodies[t]??e}star(t){return this.names?.stars[t.name]??t.name}comet(t){return this.names?.comets[t.id]??t.name}nova(t){return this.names?.novae[t.id]??t.name}satelliteClass(t){return this.names?.satelliteClasses[t.id]??t.name}shower(t){return this.names?.showers[t.id]??t.name}lightRig(t){return this.names?.lightRigs[t.id]??t.name}instrument(t){return this.names?.instruments[t.id]??t.name}decorKind(t,e){return this.names?.decorKinds[t]??e}point(t){return Po.point(t,this.names?.compassPoints)}towards(t){return Po.towards(t,this.names)}}class zs{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??zs.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(zs.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?zs.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===zs.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==zs.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${zs.name(s,e)}; ${r.join(", ")}`:`${zs.name(s,e)} — ${r.join(", ")}`}}class a1{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const n=a1.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const rO={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},aO=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,oO=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,cO=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,lO=20,hO=1;class uO{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Io.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(aO,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/lO,1);const s=i>hO;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(oO,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(cO,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n;const r=i.createGain();r.gain.value=e,s.connect(r).connect(this.output(i)),s.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class Wr{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Wr.stumpffC(n),a=e-i*i*i/Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2)*Wr.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*Wr.stumpffS(c)+l*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Wr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),l=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*l},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Db=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class dO{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Db.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=Je(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),l=this.length(a),h=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:c,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,l)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,l=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,s,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Zr(wD(),new Ce(t.x,t.y,t.z,e)),r=Zr(db(e),s),a=Vm(e,new Qr(n.lat,n.lng,n.elevationM),!0),c=new Ce(r.x-a.x,r.y-a.y,r.z-a.z,e),l=Wf(c);return t1(l.ra,l.dec,i,n)}static earthPositionAt(t){return Zr(bD(),Fa(ut.Earth,t))}static julianDayOf(t){return 2451545+Je(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new Wr(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const xp=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class ty{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return xp.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of xp){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Bs.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return xp.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,l]=i[s]??i[0];if(c===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+h*(l-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const fO=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],bf=6.5;class bp{static activeAt(t){return fO.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),l=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>l?0:1-a/l:1}static observedRatePerHour(t,e,i,n=bf){if(e<=0)return 0;const s=bf-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return Bs.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class Ci{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=Je(t),n=new Bf(0,QI(t).elon-90,1),s=Zr(TD(i),Qg(n,i)),r=Wf(s);return t1(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=bf){const i=Ci.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=bf-e;return(Ci.QUIET_RATE_PER_HOUR+i)/Math.pow(Ci.POPULATION_INDEX,n)}static schedule(t){const e=new Xf(t.seed^1542469173);return Hs.schedule(t).map(i=>{const n=Ci.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Ci.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Ci.toHorizontal(a),bearingDeg:Ci.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Ci.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Ci.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Ci.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Ci.normalise(Ci.cross(t,e));return[i,Ci.normalise(Ci.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Ci.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Ci.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Ci.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const ey="https://ufoathome.org/tle/index.json";class Sn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Sn.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(ey)||t.push(ey),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Sn.FIRST_SNAPSHOT}T00:00:00Z`)-Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS&&t.getTime()<=Date.parse(n.to)+Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*Sn.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,l=new Set(i.kinds[t].bins),h=[a,c].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>l.has(g));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...h.map(g=>this.binary(new URL(`${t}/${g}.bin`,n).href))]),f=new Map;for(const g of d)for(const m of Sn.decode(g,i.recordBytes)){const v=f.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&f.set(m.norad,m)}const p=[];for(const g of f.values()){const m=Math.abs(g.epochMs-s)/Sn.DAY_MS;if(m>Sn.MAX_ELEMENT_AGE_DAYS)continue;const v=u[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||p.push({norad:g.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS,l=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:l,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class pO{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=Ze.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=Ze.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:Ze.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:Ze.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class No{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*No.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=No.degOver(t)/e;return i<1?1:Math.min(No.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class fn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return No.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return fn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return fn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??fn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=fn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,fn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=fn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??fn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*fn.ARCSEC_PER_RADIAN,r=1.22*fn.WAVELENGTH_M/(i/1e3)*fn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/fn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=fn.graspOf(t,e),n=fn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Bi.focalLengthMmFor(t,e.fieldOfViewDeg);return fn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const iy=111320,Xl=Math.PI/180,mO=1.02,gO=1;class Mh{static of(t,e){const i=Mh.sightings(t,e);if(i.length<2)return;const n=Mh.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*Xl)===0?0:Math.tan(s.widthDeg/2*Xl)/Math.tan(r.widthDeg/2*Xl);if(c<mO)return;const l=a/(c-1),h=Ze.sizeMAt(l,s.widthDeg),u=i.map(d=>({t:d.t,m:Ze.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=ze(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=Mh.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<gO||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*iy,n=(e.lng-t.lng)*iy*Math.cos(t.lat*Xl),s=(t.sightAzimuthDeg??0)*Xl;return i*Math.cos(s)+n*Math.sin(s)}}class Ln{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:Ln.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:Ln.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:Ln.atLeastNearest(t.derivedM),basis:"derived"};const e=Ln.largest(t.range?.minM,t.crossing?.behindM),i=Ln.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*Ln.MARGIN,s=i===void 0?void 0:i/Ln.MARGIN;return n!==void 0&&s!==void 0?{distanceM:Ln.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(Ln.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}const wp=Math.PI/180;class Wt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Wt.collect(this.motionKeys,s.t,s.motions),Wt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Wt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Wt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Wt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=ze(t,0),s=ze(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Wt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Wt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Wt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*wp,n=e*wp;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const g=i+n+1>>1;e[g].t>t?n=g-1:i=g}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Wt.lerp(r.carried.eastM,a.carried.eastM,c):Wt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Wt.lerp(r.carried.northM,a.carried.northM,c):Wt.lerp(r.northM,a.northM,c),d={widthM:Wt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Wt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Wt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Wt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Wt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Wt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Wt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const g=Wt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+g+d.heightM/2}else p=Wt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Wt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Wt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Wt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Wt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Wt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Wt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),lights:this.lightsAt(t),throwsFlame:this.body.track.some(g=>g.flame!==void 0&&g.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Wt.lerp(n.lengthM,s.lengthM,i),widthM:Wt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Wt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){return"upM"in t.vertical?t.vertical.upM:this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2}groundUnderFootprint(t,e,i,n){const s=n*wp,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Wt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Wt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Wt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Wt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Wt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Wt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Wt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Wt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Wt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Wt.rgbOf(t),s=Wt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Wt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class Nn{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>Nn.bodiesOf(i))]}}static bodiesOf(t){const e={...Nn.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const u=Nn.aircraftAt(n,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[l(r),l(a)],sound:n.sound})}return n.glow&&i.push(Nn.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(Nn.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=Nn.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...Nn.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},l=(t.wind?.towardDeg??0)*Math.PI/180,h=t.wind?.speedMS??0,u=Math.sin(l)*h,d=Math.cos(l)*h,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],g=Nn.STEP_S,m=Math.round(n/1e3/g),v=Math.ceil(e.burnS/g);for(let y=1;y<=v;y++){const x=y*g,M=e.massKg-e.burnedKg*Math.min(1,x/e.burnS),b=1.225*Math.exp(-(c.z+f)/8500),S=c.vx-u,E=c.vy-d,w=c.vz,_=Math.hypot(S,E,w),D=.5*b*e.dragAreaM2*_/M;c.vx=(c.vx+D*g*u)/(1+D*g),c.vy=(c.vy+D*g*d)/(1+D*g),c.vz=(c.vz-Nn.G*g)/(1+D*g),c.x+=c.vx*g,c.y+=c.vy*g,c.z+=c.vz*g,(y%m===0||y===v)&&p.push({t:i+Math.round(x*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let l=e.fromT,h=!0;l<e.untilT;h=!h)l+=(h?e.onS:e.offS)*1e3,l<e.untilT&&s.push({t:l,lit:!h});const r=(l,h)=>{const u=Nn.aircraftAt(t.aircraft,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:l,lit:h},u)=>{u>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=Nn.trajectory(t,e,i.t),l=c.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*Nn.burnShare(e,(h.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return l.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:l}}}class mi{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ffa250"};static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>mi.bodiesOf(i))]}}static bodiesOf(t){return mi.releasesOf(t).map((e,i)=>mi.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=mi.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const l=i.fromT+r*c+(n()-.5)*r,h=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(u)*10)/10,northM:Math.round(h*Math.cos(u)*10)/10,burnedS:i.burnedS,lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...mi.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=mi.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=mi.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=mi.SAMPLE_MS){const n=mi.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,l=(t.airTemperatureC??10)+273.15,h={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*mi.heatShare(n,a)},u=mi.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:h.x,y:h.y,z:h.z,light:mi.heatShare(n,a)}];for(let g=1;g<=f;g++){const m=g*u,v=a+m,y=mi.heatShare(n,v);h.excessK+=(n.insideExcessK*y-h.excessK)*Math.min(1,u/mi.COOLING_S);const x=h.z-r,M=l-mi.LAPSE*Math.max(0,x),b=101325*Math.exp(-(h.z+c)/8400),S=b/(mi.R_AIR*M),E=b/(mi.R_AIR*(M+h.excessK)),w=n.massKg-n.fuelKg*Math.min(1,v/n.burnS),_=(S-E)*n.envelopeVolumeM3*mi.G,D=w+E*n.envelopeVolumeM3+.5*S*n.envelopeVolumeM3,I=mi.windAt(t,x),O=h.vx-I.x,L=h.vy-I.y,N=h.vz,P=.5*S*n.dragAreaM2*Math.hypot(O,L,N)/D;h.vx=(h.vx+P*u*I.x)/(1+P*u),h.vy=(h.vy+P*u*I.y)/(1+P*u),h.vz=(h.vz+(_-w*mi.G)/D*u)/(1+P*u),h.x+=h.vx*u,h.y+=h.vy*u,h.z=Math.max(r,h.z+h.vz*u);const z=h.z<=r&&m>10;if((g%d===0||g===f||z)&&p.push({t:e.t+Math.round(m*1e3),x:h.x,y:h.y,z:h.z,light:y}),z)break}return p}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=mi.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=mi.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=r.map((l,h)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...h===0?{sizeM:a,present:!0}:{},appearance:{color:n.color,luminanceCdM2:s*l.light,...h===0?{albedo:.6,haloScale:1}:{}}}));return c.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:t.title,explains:e.explains,model:{id:"sphere"},track:c}}}class o1{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=o1.FIRST_DAY}}class vO{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const MO="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",yO=[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new vO(MO,o=>o1.mayCover(o),async()=>new(await we(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-SLZYD2p1.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class kn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=kn.positionAt(t,i);if(!n)return;const s=Ae.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:kn.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>kn.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*kn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>kn.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,l=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:kn.wrapLongitude(s.lng+h*c),heightM:l*kn.FT_TO_M},altitudeFt:l,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=kn.positionAt(t,i-500),s=kn.positionAt(t,i+500);if(!n||!s)return;const r=kn.unit(Ae.seenFrom(e,n.geo)),a=kn.unit(Ae.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const ny="https://ufoathome.org/fireballs/index.json";class gr{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??gr.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(ny)||t.push(ny),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=gr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!gr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=gr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=Ae.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/Ae.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:gr.COLOR,trainS:gr.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const Ac=Math.PI/180,$l=180/Math.PI;class gi{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),l=Math.max(gi.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+l||n.altitudeDeg>(c.high??i.altitudeDeg)+l||n.altitudeDeg<(c.low??i.altitudeDeg)-l},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/gi.SIZE_TOLERANCE||n>(s.high??i)*gi.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=gi.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const l=this.timeline.getInterpolatedShapeAt(t,c);!l||l.transparency>=1||s.push({...gi.compare(c,r.id,{aim:l.aim,angular:l.angular},a,this.tolerance),title:l.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?gi.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(gi.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,h=(u,d)=>s?s.size(d,d*u):!gi.withinSize(u);return c!==void 0&&h(c,i.angular.widthDeg)&&r.push("width"),l!==void 0&&h(l,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:l,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:gi.outlineOf(t),s=i&&i.length>0?gi.centreOf(i):t,r=gi.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=gi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=gi.cross(a,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},g=gi.dot(p,r);if(g<=0)return;const m=Math.atan2(gi.dot(p,a),g),v=Math.atan2(gi.dot(p,c),g);l=Math.min(l,m),h=Math.max(h,m),u=Math.min(u,v),d=Math.max(d,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*$l+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*$l},angular:{widthDeg:(h-l)*$l,heightDeg:(d-u)*$l}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*Ac,n=e.altitudeDeg*Ac,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*Ac);return Math.acos(Math.max(-1,Math.min(1,s)))*$l}static withinSize(t){return t<=gi.SIZE_TOLERANCE&&t>=1/gi.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&Eb.includes(r))for(let u=0;u<=gi.RINGS;u++){const d=u/gi.RINGS*Math.PI;for(let f=0;f<gi.SEGMENTS;f++){const p=f/gi.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*Ac,l=t.attitude.pitchDeg*Ac,h=t.attitude.rollDeg*Ac;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),g=-u*Math.sin(h)+f*Math.cos(h),m=d*Math.cos(l)-g*Math.sin(l),v=d*Math.sin(l)+g*Math.cos(l);return{eastM:t.eastM+p*Math.cos(c)+m*Math.sin(c),northM:t.northM-p*Math.sin(c)+m*Math.cos(c),upM:t.upM+v}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}Vy();const xO={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},bO="{name} — mag {mag}, {alt}° above the horizon",wO="{name} — {size}, {distance} away",SO="{name} — satellite, mag {mag}, {height} km up",sy={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},EO={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},AO="satellites-change",_O="fireballs-change",TO="aircraft-change",Cb="rr0-confrontation",RO="{name} — mag {mag}, {alt}° below the horizontal",Sp="Credits",ry="comet:",ay="nova:",Ep={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},IO=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,DO=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,CO=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,OO=-18,PO={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Qu={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class be extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Ar,_r,bo]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new R;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Sn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new gr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=yO[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return be.trafficRuntimeLoading??=we(()=>import("./trafficRuntime-CfPqH9j0.js"),__vite__mapDeps([2,1]),import.meta.url).then(t=>be.trafficRuntime=t),be.trafficRuntimeLoading.catch(()=>{be.trafficRuntimeLoading=void 0}),be.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new uO;vehicleAudio=new bS;aircraftAudio;vehicleHearing=new Vd;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=t=>{if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1),c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)};showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,l,h,u]=Array.from(this.ghostPath.children);for(const d of[c,l])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const E=r?.ghostTooltip??sy,w=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:w,detail:()=>E.dropDetail.replace("{name}",w)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=c?this.interpretationShown?.bodies.find(E=>E.id===c):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?s.decorKind("entity",Ep.entity):void 0):void 0;if(c!==void 0&&h)return{kind:"body",id:c,name:h};const u=this.ufoElement.sighting.skyEvents?.beams,d=u?.length?this.sceneRenderer.pickBeamAt(t,e):void 0,f=d?u?.find(E=>E.id===d.id):void 0;if(d&&f){const E=this.said.read(f.title)||"Laser";return{kind:"beam",id:f.id,name:E,detail:()=>`${E} (${f.wavelengthNm} nm, ${f.powerW.toLocaleString()} W), ${this.distanceText(d.distanceM)}`}}const p=i?this.ghostPick(t,e):void 0;if(p)return p;const g=this.pickDecorAt(t,e),m=g?this.ufoElement.sighting.decor.find(E=>E.id===g):void 0;if(m){const E=this.said.read(m.title)||s.decorKind(m.kind,Ep[m.kind]);return{kind:"decor",id:m.id,name:E,detail:()=>this.decorTooltip(m,E)}}const v=this.sceneRenderer.pickRailwayAt(t,e);if(v){const E=r?.railwayTooltip??zs.ENGLISH;return{kind:"railway",id:v.line.id,name:zs.name(v.line,E),detail:()=>zs.detail(v,E,w=>this.distanceText(w))}}const y=this.trafficTooltipAt(t,e);if(y)return{kind:"traffic",name:y};const x=this.plumePickAt(t,e);if(x)return x;const M=this.sceneRenderer.pickSatelliteAt(t,e);if(M)return{kind:"satellite",name:(r?.satelliteTooltip??SO).replace("{name}",M.name).replace("{mag}",M.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(M.heightKm).toLocaleString())};const b=this.sceneRenderer.pickOpticsAt(t,e);if(b){const E=(r?.opticsTooltips??rO)[b.id].replace("{angle}",String(Math.round(b.angleDeg??0)));return{kind:"optics",id:b.id,name:E.split(" — ")[0],detail:()=>E}}const S=this.sceneRenderer.pickStarAt(t,e);if(S){const E=S.star.mag,w=S.altitudeDeg;return{kind:"star",name:(w<0?r?.starTooltipBelow??RO:r?.starTooltip??bO).replace("{name}",s.star(S.star)).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(w))))}}}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names?.ghostTooltip??sy,s=this.ufoElement.canvasElement,r={x:8/Math.max(1,s.clientWidth),y:8/Math.max(1,s.clientHeight)},a=[];for(let g=-4;g<=4;g++)for(let m=-4;m<=4;m++)a.push([m,g]);a.sort((g,m)=>Math.hypot(...g)-Math.hypot(...m));let c,l;for(const[g,m]of a){const v=this.pickAt(i.source.x+g*r.x,i.source.y+m*r.y,!1);if(v?.kind==="star")l??=v;else if(v){c=v;break}}c??=this.shiningDecorNear(i.source.x,i.source.y,6*Math.max(r.x,r.y)),c??=l;const h=(c?.kind==="star"?c.name.split(" — ")[0]:c?.name)??n.unnamed,u=i.ghost,f=(di.scatters(u)?n.halo:u.cause==="glass"?n.double:n.ghost).replace("{name}",h),p=u.scale<0?n.opposite:u.scale===1?n.around:n.sameSide;return{kind:"ghost",id:c?.id,name:f,detail:()=>n.detail.replace("{name}",f).replace("{cause}",n.causes[u.cause??"lens"]).replace("{where}",p),path:{from:{x:t,y:e},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const l=this.said.read(s.title)||this.naming.decorKind(s.kind,Ep[s.kind]);n={distance:c,pick:{kind:"decor",id:s.id,name:l}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new _o(n=>{if(!di.records(t.instrument)||!di.falling(t.lens))return 0;const s=wl(t,n*1e3),r=ze(t,n*1e3);return(s.precipitationAmount??1)*di.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(t,e){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(t,e):void 0,s=n?i?.find(l=>l.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??EO,a=this.said.read(s.title)||s.vehicle?.mission||r.name,c=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((h,u)=>`jet:${h.id??u}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",c()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),n=yt.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??wO).replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(ry)?t.slice(ry.length):void 0,i=e?Db.find(r=>r.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(ay)?ty.byId(t.slice(ay.length)):void 0;if(n)return this.naming.nova(n);const s=xO[t];return s===void 0?t:this.naming.body(t,s)}get naming(){return this.sceneNaming}sceneNaming=new xf;namesLanguage="en";async loadSceneNames(){const t=dg(ka.preferencesFor(this),fg);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await Iy(t);t===this.namesLanguage&&this.applySceneNaming(new xf(e))}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}s.append(l),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t;const e=t.names?.credits??Sp;this.creditsButton.title=e,this.creditsButton.setAttribute("aria-label",e),t.names&&this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names?.compassPoints)}showHoverTooltip(t,e){this.hoverTooltip.textContent=e,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=t.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${t.clientY-i.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Qi.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(wl(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now()),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${AS}</style>${ES}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new Et(this.sceneCanvas);const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new a1(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(Pp),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&dn.fill(n,this)}),this.creditsButton.title=Sp,this.creditsButton.setAttribute("aria-label",Sp),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Wy,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of be.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Es(ka.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:Uo.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=ze(t,e);if(!i)return 0;for(const n of[400,-400]){const s=ze(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=ae(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=ka.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of be.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of be.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===Ar||t===_r||t===bo)&&i!==e&&this.forwardPlayerAttributes(),t===bo&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Ar,_r,bo]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=ze(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=ae(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=Na.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){this.ufoElement.sightingData=t,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(t),this.interpretationShown=this.inTheRound?mi.expand(Nn.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new gf(this,()=>document.createElement(wf))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailedToLoad(t){return this.sceneRenderer.referenceFailedToLoad(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(t){const e=Wc.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
9332
|
+
`);let s=ar.cache.get(n);return s||(s=Promise.all(i.map(r=>ar.load(r.url))).then(r=>r.reduce((a,c)=>ar.concat(a,c))),ar.cache.set(n,s)),s}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(n,s)=>{const r=new Float32Array(n.length+s.length);return r.set(n,0),r.set(s,n.length),r};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class We{constructor(t){if(this.heights=t,t.length!==We.WIDTH*We.HEIGHT)throw new Error(`a lunar relief has ${We.WIDTH*We.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*We.SAMPLES_PER_DEGREE;static HEIGHT=180*We.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=We.SAMPLES_PER_DEGREE,n=(e%360+360)%360*i-.5,s=(90-t)*i-.5,r=Math.floor(n),a=Math.floor(s),c=n-r,l=s-a,h=(f,p)=>{const g=(f%We.WIDTH+We.WIDTH)%We.WIDTH,m=Math.min(We.HEIGHT-1,Math.max(0,p));return this.heights[m*We.WIDTH+g]},u=h(r,a)*(1-c)+h(r+1,a)*c,d=h(r,a+1)*(1-c)+h(r+1,a+1)*c;return(u*(1-l)+d*l)*We.UNIT_KM}static inBand(t,e){const i=Math.PI/180,n=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return n>=We.BAND_FROM_DEG&&n<=We.BAND_TO_DEG}static withBump(t,e,i,n=.4){const s=new Int8Array(We.WIDTH*We.HEIGHT),r=We.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),c=Math.floor(e*r),l=Math.floor((90-t)*r);for(let h=-a;h<=a;h++)for(let u=-a;u<=a;u++)Math.hypot(u,h)<=a&&(s[(l+h)*We.WIDTH+(c+u+We.WIDTH)%We.WIDTH]=Math.round(i/We.UNIT_KM));return new We(s)}static smooth(){return new We(new Int8Array(We.WIDTH*We.HEIGHT))}}class ws{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,n=ws.SAMPLES){const{s,u:r,w:a,distanceKm:c}=ws.frame(t,e),l=Math.PI/180,h=new Float32Array(n),u=We.REFERENCE_RADIUS_KM;for(let d=0;d<n;d++){const f=d/n*2*Math.PI,p=Math.cos(f),g=Math.sin(f),m=p*r[0]+g*a[0],v=p*r[1]+g*a[1],y=p*r[2]+g*a[2];let x=0;for(let M=ws.SEARCH_FROM_DEG;M<=ws.SEARCH_TO_DEG;M+=ws.SEARCH_STEP_DEG){const b=Math.cos(M*l),S=Math.sin(M*l),E=b*s[0]+S*m,w=b*s[1]+S*v,_=b*s[2]+S*y,D=Math.asin(Math.max(-1,Math.min(1,_)))/l,I=Math.atan2(w,E)/l,O=u+i.heightKm(D,I),L=Math.atan2(O*S,c-O*b);L>x&&(x=L)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/c)/l}}static frame(t,e){const i=new Qr(e.lat,e.lng,e.elevationM),n=ta(t),s=Vm(t,i,!1),r=new Ce(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*ws.AU_KM,c=ws.bodyFixed(t),l=c(r),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=_D(t,i),f=Jg(d),p=Zr(d,new Ce(-r.x,-r.y,-r.z,n.t)),g=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),m=Math.atan2(-p.y,p.x),v=new Ce(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),y=new Ce(-Math.sin(m),-Math.cos(m),0,n.t);return{s:u,u:c(Zr(f,v)),w:c(Zr(f,y)),distanceKm:a}}static surfacePoint(t,e,i,n){const{s,u:r,w:a}=ws.frame(t,e),c=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*c)*r[u]+Math.sin(i*c)*a[u]),h=[0,1,2].map(u=>Math.cos(n*c)*s[u]+Math.sin(n*c)*l[u]);return{latDeg:Math.asin(h[2])/c,lonDeg:Math.atan2(h[1],h[0])/c}}static radiusAt(t,e){const i=t.radiusDeg.length,n=(e/360*i%i+i)%i,s=Math.floor(n),r=n-s;return t.radiusDeg[s]*(1-r)+t.radiusDeg[(s+1)%i]*r}static uncoveredFraction(t,e,i){const n=t.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const c=a/n*2*Math.PI,l=Math.cos(c),h=Math.sin(c),u=l*i.upDeg+h*i.rightDeg,d=u*u-s+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const g=Math.max(0,u-f),m=Math.max(g,t.radiusDeg[a]);p>m&&(r+=.5*(p*p-m*m))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=GD(ut.Moon,t),i=Math.PI/180,n=e.ra*15*i,s=e.dec*i,r=e.spin*i,a=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],c=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>a(r,c(Math.PI/2-s,a(Math.PI/2+n,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new Qr(e.lat,e.lng,e.elevationM),n=ta(t),s=Vm(t,i,!1),r=ws.bodyFixed(t)(new Ce(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class gh{static cache=new Map;static load(t){let e=gh.cache.get(t);return e||(e=gh.fetchRelief(t).catch(()=>{}),gh.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new We(new Int8Array(i.buffer,i.byteOffset,i.length))}}class yf{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=yf.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=yf.MATRICES[String(t.type)];if(!e)return is.NONE;const i=Number(t.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((r,a)=>is.IDENTITY[a]+(r-is.IDENTITY[a])*n),contrastGain:1}}}class r1{static ID="fatigue";id=r1.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return is.NONE}}class so{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=so.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary), drawn up to 0.1 % at most: a higher level is recorded but shown as 0.1 %, since nothing was measured past it. Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:so.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(so.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return is.NONE;const n=i/so.MEASURED_LEVEL*so.MEASURED_LOSS_DB;return{colorMatrix:is.IDENTITY,contrastGain:10**(-n/20)}}}class vh{static ALL=[new yf,new so,new r1];static byId(t){return vh.ALL.find(e=>e.id===t)}static perceptionOf(t){return vh.ALL.reduce((e,i)=>is.combine(e,i.perceive(t?.[i.id]??{})),is.NONE)}static compact(t){const e={};for(const i of vh.ALL){const n=t[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(e[i.id]=s)}return Object.keys(e).length>0?e:void 0}}class xf{constructor(t){this.names=t}body(t,e){return this.names?.bodies[t]??e}star(t){return this.names?.stars[t.name]??t.name}comet(t){return this.names?.comets[t.id]??t.name}nova(t){return this.names?.novae[t.id]??t.name}satelliteClass(t){return this.names?.satelliteClasses[t.id]??t.name}shower(t){return this.names?.showers[t.id]??t.name}lightRig(t){return this.names?.lightRigs[t.id]??t.name}instrument(t){return this.names?.instruments[t.id]??t.name}decorKind(t,e){return this.names?.decorKinds[t]??e}point(t){return Po.point(t,this.names?.compassPoints)}towards(t){return Po.towards(t,this.names)}}class zs{static ENGLISH={kinds:{rail:"Railway",light_rail:"Light rail",tram:"Tramway",subway:"Metro",funicular:"Funicular"},highSpeed:"High-speed line",service:"Siding",singleTrack:"single track",tracks:"{count} tracks",overhead:"overhead wire {height} m above the rail",overheadVoltage:"overhead wire at {voltage}, {height} m above the rail",thirdRail:"third rail",thirdRailVoltage:"third rail at {voltage}",notElectrified:"not electrified",gauge:"{mm} mm gauge",metreGauge:"metre gauge",distance:"{distance} away"};static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??zs.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,n){const{line:s}=t,r=[];s.name&&r.push(zs.kind(s,e).toLocaleLowerCase(n)),r.push(s.tracks>1?e.tracks.replace("{count}",String(s.tracks)):e.singleTrack);const a=s.voltageV?zs.voltage(s.voltageV,n):void 0;if(t.contactM!==void 0){const c=t.contactM.toLocaleString(n,{minimumFractionDigits:2,maximumFractionDigits:2});r.push((a?e.overheadVoltage.replace("{voltage}",a):e.overhead).replace("{height}",c))}else s.electrification==="third_rail"?r.push(a?e.thirdRailVoltage.replace("{voltage}",a):e.thirdRail):s.electrification==="none"&&r.push(e.notElectrified);return s.gaugeMm===zs.METRE_GAUGE_MM?r.push(e.metreGauge):s.gaugeMm!==zs.STANDARD_GAUGE_MM&&r.push(e.gauge.replace("{mm}",s.gaugeMm.toLocaleString(n))),r.push(e.distance.replace("{distance}",i(t.distanceM))),s.services?.length?`${zs.name(s,e)}; ${r.join(", ")}`:`${zs.name(s,e)} — ${r.join(", ")}`}}class a1{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const n=a1.resolve(t,e);if(this.url=n,!n||!i){this.release();return}this.element.src=n,this.element.hidden=!1;const s=this.shown;this.shown=!0,s||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const rO={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},aO=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,oO=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,cO=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,lO=20,hO=1;class uO{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Io.unlock(this.context)}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const n=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=n==="hail"?Math.min(1,e*1.3+.2):n==="rain"?e:0,n!==this.ambientKey){this.ambientKey=n;const r=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,n!=="none"&&this.startLoop(aO,this.ambientVolume).then(a=>this.applyIfCurrent(a,r,()=>this.ambientToken,c=>{this.ambientSource=c?.source,this.ambientGain=c?.gain,c&&(c.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/lO,1);const s=i>hO;if(s!==this.windActive){this.windActive=s;const r=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,s&&this.startLoop(oO,this.windVolume).then(a=>this.applyIfCurrent(a,r,()=>this.windToken,c=>{this.windSource=c?.source,this.windGain=c?.gain,c&&(c.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:n}=this.requested;this.setAmbient(e,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(cO,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,n){if(e!==i()){t?.source.stop();return}n(t)}async startLoop(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=e,s.connect(r).connect(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(t,e){const i=this.context;if(i)try{const n=await this.getBuffer(t),s=i.createBufferSource();s.buffer=n;const r=i.createGain();r.gain.value=e,s.connect(r).connect(this.output(i)),s.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}class Wr{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[n,s]=this.perifocalAxes(),r=Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*Wr.stumpffC(n),a=e-i*i*i/Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2)*Wr.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(Wr.SUN_GM_AU3_PER_DAY2)*Math.abs(t),n=a=>{const c=this.inverseSemiMajorAxis*a*a,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*a*a*a*Wr.stumpffS(c)+l*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<Wr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){const c=(r+s)/2;n(c)<i?r=c:s=c}return e*(r+s)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(t),s=Math.sin(t),r=Math.cos(e),a=Math.sin(e),c=Math.cos(i),l=Math.sin(i);return[{x:n*r-s*a*c,y:s*r+n*a*c,z:a*l},{x:-n*a-s*r*c,y:-s*a+n*r*c,z:r*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Db=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class dO{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Db.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(t,e,i){const n=Je(e),s=this.earthPositionAt(n),r=this.apparentPositionOf(t,2451545+n.tt,s),a=this.subtract(r,s),c=this.length(r),l=this.length(a),h=this.tailEndAt(t,r,s,c,n,e,i),u=this.horizontalOf(a,n,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:c,earthDistanceAu:l,elongationDeg:this.angleBetween(a,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(t,c,l)}}static magnitudeAt(t,e,i){const n=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(n,t.peakMagnitude)}static tailEndAt(t,e,i,n,s,r,a){if(t.tailLengthAu===void 0)return{};const c=1+t.tailLengthAu/n,l=this.subtract({x:e.x*c,y:e.y*c,z:e.z*c},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,s,r,a),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const n=this.orbitOf(t);let s=n.positionAt(e);for(let r=0;r<2;r++){const a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(e-a)}return s}static horizontalOf(t,e,i,n){const s=Zr(wD(),new Ce(t.x,t.y,t.z,e)),r=Zr(db(e),s),a=Vm(e,new Qr(n.lat,n.lng,n.elevationM),!0),c=new Ce(r.x-a.x,r.y-a.y,r.z-a.z,e),l=Wf(c);return t1(l.ra,l.dec,i,n)}static earthPositionAt(t){return Zr(bD(),Fa(ut.Earth,t))}static julianDayOf(t){return 2451545+Je(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new Wr(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const xp=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class ty{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return xp.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),n=[];for(const s of xp){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Bs.ofJ2000(s.raHours,s.decDeg,t,e),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return xp.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,n=e-t.startJd;if(i.length===0||n<i[0][0]||n>i[i.length-1][0])return;let s=1;for(;s<i.length-1&&i[s][0]<n;)s++;const[r,a]=i[s-1]??i[0],[c,l]=i[s]??i[0];if(c===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(c-r)));return a+h*(l-a)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const fO=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],bf=6.5;class bp{static activeAt(t){return fO.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),n=this.dayOfYear(this.asDate(t.start)),s=this.dayOfYear(this.asDate(t.peak)),r=this.dayOfYear(this.asDate(t.end)),a=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),l=this.wrappedDelta(r,s);return a<0?a<-c?0:1+a/c:a>0?a>l?0:1-a/l:1}static observedRatePerHour(t,e,i,n=bf){if(e<=0)return 0;const s=bf-n;return t*Math.sin(e*Math.PI/180)/Math.pow(i,s)}static radiantPosition(t,e,i){return Bs.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class Ci{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=Je(t),n=new Bf(0,QI(t).elon-90,1),s=Zr(TD(i),Qg(n,i)),r=Wf(s);return t1(r.ra,r.dec,t,e)}static observedRatePerHour(t,e=bf){const i=Ci.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),n=bf-e;return(Ci.QUIET_RATE_PER_HOUR+i)/Math.pow(Ci.POPULATION_INDEX,n)}static schedule(t){const e=new Xf(t.seed^1542469173);return Hs.schedule(t).map(i=>{const n=Ci.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Ci.turnAround(n,e.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:Ci.toHorizontal(a),bearingDeg:Ci.bearingFrom(a,n)}})}static turnAround(t,e){const[i,n]=Ci.basisAround(t),s=e*Math.PI/180;return{x:i.x*Math.cos(s)+n.x*Math.sin(s),y:i.y*Math.cos(s)+n.y*Math.sin(s),z:i.z*Math.cos(s)+n.z*Math.sin(s)}}static bearingFrom(t,e){const[i,n]=Ci.basisAround(t),s=t.x*e.x+t.y*e.y+t.z*e.z,r=Ci.normalise({x:e.x-t.x*s,y:e.y-t.y*s,z:e.z-t.z*s});return(Math.atan2(r.x*n.x+r.y*n.y+r.z*n.z,r.x*i.x+r.y*i.y+r.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Ci.normalise(Ci.cross(t,e));return[i,Ci.normalise(Ci.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=Ci.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Ci.turnAround(e,t.bearingDeg),n=t.fromRadiantDeg*Math.PI/180;return Ci.toHorizontal({x:e.x*Math.cos(n)+i.x*Math.sin(n),y:e.y*Math.cos(n)+i.y*Math.sin(n),z:e.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,n=Math.cos(e);return{x:n*Math.sin(i),y:Math.sin(e),z:-n*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const ey="https://ufoathome.org/tle/index.json";class Sn{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Sn.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(ey)||t.push(ey),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Sn.FIRST_SNAPSHOT}T00:00:00Z`)-Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>t.getTime()>=Date.parse(n.from)-Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS&&t.getTime()<=Date.parse(n.to)+Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:n}=e,s=[],r=[];for(const a of Object.keys(i.kinds)){const c=await this.kindAt(a,t,i,n);s.push(...c),r.push(this.coverageOf(a,t,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,n){const s=e.getTime(),r=i.binDays*Sn.DAY_MS,a=Math.floor(s/r),c=s-a*r<r/2?a-1:a+1,l=new Set(i.kinds[t].bins),h=[a,c].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>l.has(g));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,n).href),...h.map(g=>this.binary(new URL(`${t}/${g}.bin`,n).href))]),f=new Map;for(const g of d)for(const m of Sn.decode(g,i.recordBytes)){const v=f.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&f.set(m.norad,m)}const p=[];for(const g of f.values()){const m=Math.abs(g.epochMs-s)/Sn.DAY_MS;if(m>Sn.MAX_ELEMENT_AGE_DAYS)continue;const v=u[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||p.push({norad:g.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return p}coverageOf(t,e,i,n){const{from:s,to:r}=i.kinds[t],a=e.getTime(),c=Sn.MAX_ELEMENT_AGE_DAYS*Sn.DAY_MS,l=n?"covered":a<Date.parse(s)-c?"before":a>Date.parse(r)+c?"after":"gap";return{kind:t,status:l,from:s,to:r}}static decode(t,e){const i=new DataView(t),n=[];for(let s=0;s+e<=t.byteLength;s+=e)n.push({norad:i.getUint32(s,!0),epochMs:i.getFloat64(s+4,!0),bstar:i.getFloat32(s+12,!0),inclinationDeg:i.getFloat32(s+16,!0),raanDeg:i.getFloat32(s+20,!0),eccentricity:i.getFloat32(s+24,!0),argOfPerigeeDeg:i.getFloat32(s+28,!0),meanAnomalyDeg:i.getFloat32(s+32,!0),meanMotion:i.getFloat64(s+36,!0)});return n}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(n=>{if(!n.ok)throw new Error(`${t}: ${n.status}`);return e(n)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class pO{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=Ze.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=Ze.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:Ze.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:Ze.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class No{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*No.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=No.degOver(t)/e;return i<1?1:Math.min(No.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class fn{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return No.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return fn.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,n=e.fNumber??t.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return fn.EYE;const s=e.focalLengthMm??t.frame?.focalLengthMm??fn.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=fn.resolutionArcsec(t,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,fn.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(t,e){const i=t.visualAid,n=fn.EYE,s=e??t.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(t,e,i){const s=(t.detailUm??fn.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*fn.ARCSEC_PER_RADIAN,r=1.22*fn.WAVELENGTH_M/(i/1e3)*fn.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(t){return t/fn.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=fn.graspOf(t,e),n=fn.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Bi.focalLengthMmFor(t,e.fieldOfViewDeg);return fn.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const iy=111320,Xl=Math.PI/180,mO=1.02,gO=1;class Mh{static of(t,e){const i=Mh.sightings(t,e);if(i.length<2)return;const n=Mh.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,c=Math.tan(r.widthDeg/2*Xl)===0?0:Math.tan(s.widthDeg/2*Xl)/Math.tan(r.widthDeg/2*Xl);if(c<mO)return;const l=a/(c-1),h=Ze.sizeMAt(l,s.widthDeg),u=i.map(d=>({t:d.t,m:Ze.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===e)?.shape,s=n?.angular?.widthDeg,r=ze(t,i.t);return s===void 0||s<=0||r?.lat===void 0||r.lng===void 0?[]:[{t:i.t,widthDeg:s,lat:r.lat,lng:r.lng,sightAzimuthDeg:n?.aim?.azimuthDeg??r.headingDeg}]}).sort((i,n)=>i.t-n.t)}static baseline(t){let e;for(const i of t)for(const n of t){if(i.t>=n.t)continue;const s=Mh.closedAlongSight(i,n),[r,a,c]=s>=0?[n,i,s]:[i,n,-s];c<gO||r.widthDeg<=a.widthDeg||(!e||c>e.closedM)&&(e={near:r,far:a,closedM:c})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*iy,n=(e.lng-t.lng)*iy*Math.cos(t.lat*Xl),s=(t.sightAzimuthDeg??0)*Xl;return i*Math.cos(s)+n*Math.sin(s)}}class Ln{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:Ln.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:Ln.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:Ln.atLeastNearest(t.derivedM),basis:"derived"};const e=Ln.largest(t.range?.minM,t.crossing?.behindM),i=Ln.smallest(t.range?.maxM,t.crossing?.inFrontM),n=e===void 0?void 0:e*Ln.MARGIN,s=i===void 0?void 0:i/Ln.MARGIN;return n!==void 0&&s!==void 0?{distanceM:Ln.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(Ln.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}const wp=Math.PI/180;class Wt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Wt.collect(this.motionKeys,s.t,s.motions),Wt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Wt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Wt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Wt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=ze(t,0),s=ze(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ae(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Wt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Wt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Wt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*wp,n=e*wp;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const g=i+n+1>>1;e[g].t>t?n=g-1:i=g}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Wt.lerp(r.carried.eastM,a.carried.eastM,c):Wt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Wt.lerp(r.carried.northM,a.carried.northM,c):Wt.lerp(r.northM,a.northM,c),d={widthM:Wt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Wt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Wt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Wt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Wt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Wt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Wt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const g=Wt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+g+d.heightM/2}else p=Wt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Wt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Wt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Wt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Wt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Wt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Wt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),lights:this.lightsAt(t),throwsFlame:this.body.track.some(g=>g.flame!==void 0&&g.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Wt.lerp(n.lengthM,s.lengthM,i),widthM:Wt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Wt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){return"upM"in t.vertical?t.vertical.upM:this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2}groundUnderFootprint(t,e,i,n){const s=n*wp,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Wt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Wt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Wt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Wt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Wt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Wt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Wt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Wt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Wt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Wt.rgbOf(t),s=Wt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Wt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class Nn{static MJU_7={massKg:.37,burnedKg:.26,dragAreaM2:1.2*.0508*.2032,ejectionMS:30,burnS:4.5,luminousIntensityCd:2e4,flameSizeM:1.5,color:"#ffd9a0"};static SAMPLE_MS=100;static STEP_S=.002;static G=9.81;static expand(t){const e=t?.flares;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>Nn.bodiesOf(i))]}}static bodiesOf(t){const e={...Nn.MJU_7,...t.flare},i=[],n=t.aircraft;if(n.model||n.sound){const s=t.releases.map(h=>h.t),r=Math.min(n.t,...s)-12e4,a=Math.max(n.t,...s)+12e4,c=n.model?{color:"#30333a",albedo:.15}:{transparency:1},l=h=>{const u=Nn.aircraftAt(n,h);return{t:h,eastM:u.x,northM:u.y,altitudeM:u.z,attitude:{headingDeg:n.headingDeg},sizeM:n.sizeM??{widthM:1,lengthM:1,heightM:1},appearance:c}};i.push({id:`${t.id}-aircraft`,title:t.title,model:n.model??{id:"sphere"},track:[l(r),l(a)],sound:n.sound})}return n.glow&&i.push(Nn.glowBody(t,n.glow)),t.releases.forEach((s,r)=>i.push(Nn.flareBody(t,e,s,r))),i}static aircraftAt(t,e){const i=t.headingDeg*Math.PI/180,n=(e-t.t)/1e3*t.speedMS;return{x:t.eastM+Math.sin(i)*n,y:t.northM+Math.cos(i)*n,z:t.altitudeM}}static burnShare(t,e){if(e<0||e>=t.burnS)return 0;if(e<.2)return e/.2;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static trajectory(t,e,i,n=Nn.SAMPLE_MS){const s=t.aircraft,r=s.headingDeg*Math.PI/180,c={...Nn.aircraftAt(s,i),vx:Math.sin(r)*s.speedMS,vy:Math.cos(r)*s.speedMS,vz:-e.ejectionMS},l=(t.wind?.towardDeg??0)*Math.PI/180,h=t.wind?.speedMS??0,u=Math.sin(l)*h,d=Math.cos(l)*h,f=s.originElevationM??1e3,p=[{t:i,x:c.x,y:c.y,z:c.z}],g=Nn.STEP_S,m=Math.round(n/1e3/g),v=Math.ceil(e.burnS/g);for(let y=1;y<=v;y++){const x=y*g,M=e.massKg-e.burnedKg*Math.min(1,x/e.burnS),b=1.225*Math.exp(-(c.z+f)/8500),S=c.vx-u,E=c.vy-d,w=c.vz,_=Math.hypot(S,E,w),D=.5*b*e.dragAreaM2*_/M;c.vx=(c.vx+D*g*u)/(1+D*g),c.vy=(c.vy+D*g*d)/(1+D*g),c.vz=(c.vz-Nn.G*g)/(1+D*g),c.x+=c.vx*g,c.y+=c.vy*g,c.z+=c.vz*g,(y%m===0||y===v)&&p.push({t:i+Math.round(x*1e3),x:c.x,y:c.y,z:c.z})}return p}static glowBody(t,e){const i=e.sizeM/2,n=e.luminousIntensityCd/(Math.PI*i*i),s=[{t:e.fromT,lit:!0}];if(e.onS&&e.offS)for(let l=e.fromT,h=!0;l<e.untilT;h=!h)l+=(h?e.onS:e.offS)*1e3,l<e.untilT&&s.push({t:l,lit:!h});const r=(l,h)=>{const u=Nn.aircraftAt(t.aircraft,l);return{t:l,eastM:u.x,northM:u.y,altitudeM:u.z,appearance:{color:e.color,luminanceCdM2:h?n:0}}},a=[];s.forEach(({t:l,lit:h},u)=>{u>0&&a.push(r(l-1,!h)),a.push(r(l,h))}),a[0]={...a[0],sizeM:{widthM:e.sizeM,lengthM:e.sizeM,heightM:e.sizeM},present:!0};const c=s[s.length-1];return a.push(r(e.untilT,c.lit),{t:e.untilT+1,present:!1}),{id:`${t.id}-glow`,title:t.title,explains:e.explains,model:{id:"sphere"},track:a}}static flareBody(t,e,i,n){const s=e.flameSizeM,r=s/2,a=e.luminousIntensityCd/(Math.PI*r*r),c=Nn.trajectory(t,e,i.t),l=c.map((h,u)=>({t:h.t,eastM:h.x,northM:h.y,altitudeM:h.z,...u===0?{sizeM:{widthM:s,lengthM:s,heightM:s},present:!0}:{},appearance:{color:e.color,luminanceCdM2:a*Nn.burnShare(e,(h.t-i.t)/1e3),...u===0?{haloScale:1}:{}}}));return l.push({t:c[c.length-1].t+1,present:!1}),{id:`${t.id}-flare-${n+1}`,title:t.title,explains:i.explains,model:{id:"sphere"},track:l}}}class mi{static COMMON={envelopeVolumeM3:.19,massKg:.065,fuelKg:.03,burnS:600,insideExcessK:150,dragAreaM2:.25,luminousIntensityCd:10,widthM:.6,heightM:1,color:"#ffa250"};static SAMPLE_MS=1e3;static STEP_S=.05;static COOLING_S=20;static G=9.81;static R_AIR=287.05;static LAPSE=.0065;static expand(t){const e=t?.lanterns;return!t||!e||e.length===0?t:{...t,bodies:[...t.bodies,...e.flatMap(i=>mi.bodiesOf(i))]}}static bodiesOf(t){return mi.releasesOf(t).map((e,i)=>mi.lanternBody(t,e,i))}static releasesOf(t){const e=[...t.releases??[]],i=t.group;if(!i||!(i.count>0))return e;const n=mi.randomFrom(i.seed??1),s=c=>c.min+(c.max-c.min)*n(),r=i.count>1?(i.untilT-i.fromT)/(i.count-1):0,a=i.radiusM??20;for(let c=0;c<i.count;c++){const l=i.fromT+r*c+(n()-.5)*r,h=a*Math.sqrt(n()),u=2*Math.PI*n();e.push({t:Math.round(Math.min(i.untilT,Math.max(i.fromT,l))),explains:i.explains,eastM:Math.round(h*Math.sin(u)*10)/10,northM:Math.round(h*Math.cos(u)*10)/10,burnedS:i.burnedS,lantern:{burnS:Math.round(s(i.burnS??{min:480,max:900})),insideExcessK:Math.round(s(i.insideExcessK??{min:125,max:175}))}})}return e}static randomFrom(t){let e=t>>>0;return()=>{e=e+1831565813>>>0;let i=e;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}static typeOf(t,e){return{...mi.COMMON,...t.lantern,...e.lantern}}static heatShare(t,e){if(e<0||e>=t.burnS)return 0;const i=t.burnS*.75;return e<=i?1:(t.burnS-e)/(t.burnS-i)}static windAt(t,e){const i=mi.componentsOf(t.wind),n=t.windAloft;if(!n)return i;const s=mi.componentsOf(n),r=Math.max(0,Math.min(1,e/n.atM));return{x:i.x+(s.x-i.x)*r,y:i.y+(s.y-i.y)*r}}static trajectory(t,e,i=mi.SAMPLE_MS){const n=mi.typeOf(t,e),s=t.site,r=s.altitudeM??0,a=Math.max(0,e.burnedS??0),c=s.originElevationM??0,l=(t.airTemperatureC??10)+273.15,h={x:s.eastM+(e.eastM??0),y:s.northM+(e.northM??0),z:e.altitudeM??r,vx:0,vy:0,vz:0,excessK:n.insideExcessK*mi.heatShare(n,a)},u=mi.STEP_S,d=Math.max(1,Math.round(i/1e3/u)),f=Math.ceil(Math.max(0,n.burnS-a)/u),p=[{t:e.t,x:h.x,y:h.y,z:h.z,light:mi.heatShare(n,a)}];for(let g=1;g<=f;g++){const m=g*u,v=a+m,y=mi.heatShare(n,v);h.excessK+=(n.insideExcessK*y-h.excessK)*Math.min(1,u/mi.COOLING_S);const x=h.z-r,M=l-mi.LAPSE*Math.max(0,x),b=101325*Math.exp(-(h.z+c)/8400),S=b/(mi.R_AIR*M),E=b/(mi.R_AIR*(M+h.excessK)),w=n.massKg-n.fuelKg*Math.min(1,v/n.burnS),_=(S-E)*n.envelopeVolumeM3*mi.G,D=w+E*n.envelopeVolumeM3+.5*S*n.envelopeVolumeM3,I=mi.windAt(t,x),O=h.vx-I.x,L=h.vy-I.y,N=h.vz,P=.5*S*n.dragAreaM2*Math.hypot(O,L,N)/D;h.vx=(h.vx+P*u*I.x)/(1+P*u),h.vy=(h.vy+P*u*I.y)/(1+P*u),h.vz=(h.vz+(_-w*mi.G)/D*u)/(1+P*u),h.x+=h.vx*u,h.y+=h.vy*u,h.z=Math.max(r,h.z+h.vz*u);const z=h.z<=r&&m>10;if((g%d===0||g===f||z)&&p.push({t:e.t+Math.round(m*1e3),x:h.x,y:h.y,z:h.z,light:y}),z)break}return p}static componentsOf(t){if(!t)return{x:0,y:0};const e=t.towardDeg*Math.PI/180;return{x:Math.sin(e)*t.speedMS,y:Math.cos(e)*t.speedMS}}static lanternBody(t,e,i){const n=mi.typeOf(t,e),s=n.luminousIntensityCd/(Math.PI*n.widthM/2*n.heightM/2),r=mi.trajectory(t,e),a={widthM:n.widthM,lengthM:n.widthM,heightM:n.heightM},c=r.map((l,h)=>({t:l.t,eastM:l.x,northM:l.y,altitudeM:l.z,...h===0?{sizeM:a,present:!0}:{},appearance:{color:n.color,luminanceCdM2:s*l.light,...h===0?{albedo:.6,haloScale:1}:{}}}));return c.push({t:r[r.length-1].t+1,present:!1}),{id:`${t.id}-lantern-${i+1}`,title:t.title,explains:e.explains,model:{id:"sphere"},track:c}}}class o1{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=o1.FIRST_DAY}}class vO{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,n){try{return await(await this.provider()).between(t,e,i,n)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const MO="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",yO=[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new vO(MO,o=>o1.mayCover(o),async()=>new(await we(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-SLZYD2p1.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class kn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const n=kn.positionAt(t,i);if(!n)return;const s=Ae.seenFrom(e,n.geo);if(!(s.altitudeDeg<0))return{track:t,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:kn.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(n=>kn.seenFrom(n,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,n=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*kn.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=e;)n++;const s=i[n],r=i[n+1]??s,a=r.t-s.t;if(a>kn.MAX_GAP_S*1e3)return;const c=a>0?(e-s.t)/a:0,l=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*c,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*c,lng:kn.wrapLongitude(s.lng+h*c),heightM:l*kn.FT_TO_M},altitudeFt:l,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(t,e,i){const n=kn.positionAt(t,i-500),s=kn.positionAt(t,i+500);if(!n||!s)return;const r=kn.unit(Ae.seenFrom(e,n.geo)),a=kn.unit(Ae.seenFrom(e,s.geo)),c=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[2]));return Math.acos(c)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const ny="https://ufoathome.org/fireballs/index.json";class gr{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??gr.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(ny)||t.push(ny),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=gr.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!gr.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=t&&r.t<=e):void 0}static seenFrom(t,e){const i=gr.peakFraction(t),n={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},s=Ae.seenFrom(e,n);if(!(s.altitudeDeg<0))return{record:t,peak:s,magnitude:t.peakMagnitude+5*Math.log10(s.distanceKm/Ae.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,n=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:n,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:gr.COLOR,trainS:gr.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(t,i)),i}}const Ac=Math.PI/180,$l=180/Math.PI;class gi{constructor(t,e){this.timeline=t,this.tolerance=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;static lawsOf(t,e){return{direction(i,n,s){const r=t.law({kind:"heading",value:i.azimuthDeg},e),a=Math.abs(((n.azimuthDeg-i.azimuthDeg)%360+540)%360-180),c=t.law({kind:"elevation",value:i.altitudeDeg},e),l=Math.max(gi.DIRECTION_TOLERANCE_DEG,s);return a>(r.high??i.azimuthDeg)-i.azimuthDeg+l||n.altitudeDeg>(c.high??i.altitudeDeg)+l||n.altitudeDeg<(c.low??i.altitudeDeg)-l},size(i,n){const s=t.law({kind:"angularSize",value:i},e);return n<(s.low??i)/gi.SIZE_TOLERANCE||n>(s.high??i)*gi.SIZE_TOLERANCE}}}at(t,e,i,n){const s=[];for(const r of e){const a=gi.projectionOf(r,i,n?.(r));if(a)for(const c of r.explains){const l=this.timeline.getInterpolatedShapeAt(t,c);!l||l.transparency>=1||s.push({...gi.compare(c,r.id,{aim:l.aim,angular:l.angular},a,this.tolerance),title:l.title})}}return s}static compare(t,e,i,n,s){const r=[],a=i.aim?gi.separationDeg(i.aim,n.aim):void 0;if(a!==void 0){const u=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;(s?s.direction(i.aim,n.aim,u):a>Math.max(gi.DIRECTION_TOLERANCE_DEG,u))&&r.push("direction")}const c=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0,h=(u,d)=>s?s.size(d,d*u):!gi.withinSize(u);return c!==void 0&&h(c,i.angular.widthDeg)&&r.push("width"),l!==void 0&&h(l,i.angular.heightDeg)&&r.push("height"),{sourceId:t,bodyId:e,stated:i,predicted:n,separationDeg:a,widthRatio:c,heightRatio:l,disagreements:r}}static projectionOf(t,e,i){const n=i&&i.length>0?i:gi.outlineOf(t),s=i&&i.length>0?gi.centreOf(i):t,r=gi.normalized({eastM:s.eastM-e.eastM,northM:s.northM-e.northM,upM:s.upM-e.upM});if(!r)return;const a=gi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=gi.cross(a,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-e.eastM,northM:f.northM-e.northM,upM:f.upM-e.upM},g=gi.dot(p,r);if(g<=0)return;const m=Math.atan2(gi.dot(p,a),g),v=Math.atan2(gi.dot(p,c),g);l=Math.min(l,m),h=Math.max(h,m),u=Math.min(u,v),d=Math.max(d,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*$l+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*$l},angular:{widthDeg:(h-l)*$l,heightDeg:(d-u)*$l}}}static centreOf(t){const e=i=>(Math.min(...t.map(n=>n[i]))+Math.max(...t.map(n=>n[i])))/2;return{eastM:e("eastM"),northM:e("northM"),upM:e("upM")}}static separationDeg(t,e){const i=t.altitudeDeg*Ac,n=e.altitudeDeg*Ac,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((t.azimuthDeg-e.azimuthDeg)*Ac);return Math.acos(Math.max(-1,Math.min(1,s)))*$l}static withinSize(t){return t<=gi.SIZE_TOLERANCE&&t>=1/gi.SIZE_TOLERANCE}static outlineOf(t){const e=t.sizeM.widthM/2,i=t.sizeM.lengthM/2,n=t.sizeM.heightM/2,s=[],r=t.model.url===void 0?t.model.id:void 0;if(r!==void 0&&r!=="box"&&Eb.includes(r))for(let u=0;u<=gi.RINGS;u++){const d=u/gi.RINGS*Math.PI;for(let f=0;f<gi.SEGMENTS;f++){const p=f/gi.SEGMENTS*2*Math.PI;s.push([e*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-e,e])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=t.attitude.headingDeg*Ac,l=t.attitude.pitchDeg*Ac,h=t.attitude.rollDeg*Ac;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),g=-u*Math.sin(h)+f*Math.cos(h),m=d*Math.cos(l)-g*Math.sin(l),v=d*Math.sin(l)+g*Math.cos(l);return{eastM:t.eastM+p*Math.cos(c)+m*Math.sin(c),northM:t.northM-p*Math.sin(c)+m*Math.cos(c),upM:t.upM+v}})}static dot(t,e){return t.eastM*e.eastM+t.northM*e.northM+t.upM*e.upM}static cross(t,e){return{eastM:t.northM*e.upM-t.upM*e.northM,northM:t.upM*e.eastM-t.eastM*e.upM,upM:t.eastM*e.northM-t.northM*e.eastM}}static normalized(t){const e=Math.hypot(t.eastM,t.northM,t.upM);return e>1e-9?{eastM:t.eastM/e,northM:t.northM/e,upM:t.upM/e}:void 0}}Vy();const xO={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},bO="{name} — mag {mag}, {alt}° above the horizon",wO="{name} — {size}, {distance} away",SO="{name} — satellite, mag {mag}, {height} km up",sy={ghost:"Ghost: {name}",halo:"Halo: {name}",double:"Double: {name}",unnamed:"a light",detail:"{name}. {cause}, {where}.",causes:{lens:"A reflection between two surfaces of the lens",sensor:"The sensor's reflection, sent back by its cover glass",filter:"The sensor's reflection, sent back by the filter",glass:"A reflection between the two faces of the glass in front of the lens",drops:"Light scattered by drops on the glass",condensation:"Light scattered by condensation on the glass",dirt:"Light scattered by dirt on the glass"},opposite:"across the centre of the picture from the light",sameSide:"on the same side of the centre as the light",around:"round the light",drop:{lens:"Drop on the lens",filter:"Drop on the filter",window:"Drop on the window",windscreen:"Drop on the windscreen"},dropDetail:"{name}. Like a small lens, it shows upside down and blurred what is on the other side of it, rather than what is behind it."},EO={name:"Rocket plume",detail:"{name} — {part}, {distance} away, {height} km up",ascent:"exhaust of the ascent",burn:"exhaust of an engine burn",vent:"vented propellant"},AO="satellites-change",_O="fireballs-change",TO="references-change",RO="aircraft-change",Cb="rr0-confrontation",IO="{name} — mag {mag}, {alt}° below the horizontal",Sp="Credits",ry="comet:",ay="nova:",Ep={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",trafficlight:"Traffic light",crossing:"Pedestrian crossing",roadsign:"Road sign",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},DO=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,CO=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,OO=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,PO=-18,LO={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Qu={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class be extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Ar,_r,bo]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new R;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Sn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new gr;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static NO_BEAMS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=yO[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return be.trafficRuntimeLoading??=we(()=>import("./trafficRuntime-CfPqH9j0.js"),__vite__mapDeps([2,1]),import.meta.url).then(t=>be.trafficRuntime=t),be.trafficRuntimeLoading.catch(()=>{be.trafficRuntimeLoading=void 0}),be.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new uO;vehicleAudio=new bS;aircraftAudio;vehicleHearing=new Vd;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=t=>{if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(t.clientX-i.left)/i.width*e.width,s=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(t.clientX-i.left)/i.width*2-1,a=-((t.clientY-i.top)/i.height*2-1),c=this.pickAt(r,a,!0,t.altKey);c?this.showHoverTooltip(t,t.altKey&&c.detail?c.detail():c.name):this.hoverTooltip.hidden=!0,this.showGhostPath(c?.path,i)};showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),n=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),s=n(t.from),r=n(t.to),a=n({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[c,l,h,u]=Array.from(this.ghostPath.children);for(const d of[c,l])d.setAttribute("x1",String(s.x)),d.setAttribute("y1",String(s.y)),d.setAttribute("x2",String(r.x)),d.setAttribute("y2",String(r.y));h.setAttribute("cx",String(a.x)),h.setAttribute("cy",String(a.y)),u.setAttribute("cx",String(r.x)),u.setAttribute("cy",String(r.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,n=!1){const s=this.naming,r=s.names;if(n&&this.sceneRenderer.pickDropAt(t,e)){const E=r?.ghostTooltip??sy,w=E.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:w,detail:()=>E.dropDetail.replace("{name}",w)}}const a=this.sceneRenderer.pickBodyAt(t,e);if(a)return{kind:"sky",id:a,name:this.bodyName(a)};const c=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=c?this.interpretationShown?.bodies.find(E=>E.id===c):void 0,h=l?this.said.read(l.title)||(l.model.id==="figure"?s.decorKind("entity",Ep.entity):void 0):void 0;if(c!==void 0&&h)return{kind:"body",id:c,name:h};const u=this.ufoElement.sighting.skyEvents?.beams,d=u?.length?this.sceneRenderer.pickBeamAt(t,e):void 0,f=d?u?.find(E=>E.id===d.id):void 0;if(d&&f){const E=this.said.read(f.title)||"Laser";return{kind:"beam",id:f.id,name:E,detail:()=>`${E} (${f.wavelengthNm} nm, ${f.powerW.toLocaleString()} W), ${this.distanceText(d.distanceM)}`}}const p=i?this.ghostPick(t,e):void 0;if(p)return p;const g=this.pickDecorAt(t,e),m=g?this.ufoElement.sighting.decor.find(E=>E.id===g):void 0;if(m){const E=this.said.read(m.title)||s.decorKind(m.kind,Ep[m.kind]);return{kind:"decor",id:m.id,name:E,detail:()=>this.decorTooltip(m,E)}}const v=this.sceneRenderer.pickRailwayAt(t,e);if(v){const E=r?.railwayTooltip??zs.ENGLISH;return{kind:"railway",id:v.line.id,name:zs.name(v.line,E),detail:()=>zs.detail(v,E,w=>this.distanceText(w))}}const y=this.trafficTooltipAt(t,e);if(y)return{kind:"traffic",name:y};const x=this.plumePickAt(t,e);if(x)return x;const M=this.sceneRenderer.pickSatelliteAt(t,e);if(M)return{kind:"satellite",name:(r?.satelliteTooltip??SO).replace("{name}",M.name).replace("{mag}",M.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(M.heightKm).toLocaleString())};const b=this.sceneRenderer.pickOpticsAt(t,e);if(b){const E=(r?.opticsTooltips??rO)[b.id].replace("{angle}",String(Math.round(b.angleDeg??0)));return{kind:"optics",id:b.id,name:E.split(" — ")[0],detail:()=>E}}const S=this.sceneRenderer.pickStarAt(t,e);if(S){const E=S.star.mag,w=S.altitudeDeg;return{kind:"star",name:(w<0?r?.starTooltipBelow??IO:r?.starTooltip??bO).replace("{name}",s.star(S.star)).replace("{mag}",E.toLocaleString(void 0,{maximumFractionDigits:Math.abs(E)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(w))))}}}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const n=this.naming.names?.ghostTooltip??sy,s=this.ufoElement.canvasElement,r={x:8/Math.max(1,s.clientWidth),y:8/Math.max(1,s.clientHeight)},a=[];for(let g=-4;g<=4;g++)for(let m=-4;m<=4;m++)a.push([m,g]);a.sort((g,m)=>Math.hypot(...g)-Math.hypot(...m));let c,l;for(const[g,m]of a){const v=this.pickAt(i.source.x+g*r.x,i.source.y+m*r.y,!1);if(v?.kind==="star")l??=v;else if(v){c=v;break}}c??=this.shiningDecorNear(i.source.x,i.source.y,6*Math.max(r.x,r.y)),c??=l;const h=(c?.kind==="star"?c.name.split(" — ")[0]:c?.name)??n.unnamed,u=i.ghost,f=(di.scatters(u)?n.halo:u.cause==="glass"?n.double:n.ghost).replace("{name}",h),p=u.scale<0?n.opposite:u.scale===1?n.around:n.sameSide;return{kind:"ghost",id:c?.id,name:f,detail:()=>n.detail.replace("{name}",f).replace("{cause}",n.causes[u.cause??"lens"]).replace("{where}",p),path:{from:{x:t,y:e},to:i.source}}}shiningDecorNear(t,e,i){let n;for(const s of this.ufoElement.sighting.decor){if(!(s.kind==="streetlight"||s.kind==="trafficlight"||(s.lights?.length??0)>0||s.kind==="vehicle"&&s.lit))continue;const a=this.sceneRenderer.decorScreenBox(s.id);if(!a)continue;const c=Math.hypot(Math.max(a.minX-t,0,t-a.maxX),Math.max(a.minY-e,0,e-a.maxY));if(c>i||n&&c>=n.distance)continue;const l=this.said.read(s.title)||this.naming.decorKind(s.kind,Ep[s.kind]);n={distance:c,pick:{kind:"decor",id:s.id,name:l}}}return n?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new _o(n=>{if(!di.records(t.instrument)||!di.falling(t.lens))return 0;const s=wl(t,n*1e3),r=ze(t,n*1e3);return(s.precipitationAmount??1)*di.impactRate(s,t.lens?.glass,r&&{headingDeg:r.headingDeg??0,pitchDeg:r.pitchDeg,windFromDeg:s.windDirectionDeg,windSpeedMS:s.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;plumePickAt(t,e){const i=this.ufoElement.sighting.skyEvents?.launches,n=i?.length?this.sceneRenderer.pickPlumeAt(t,e):void 0,s=n?i?.find(l=>l.id===n.launchId):void 0;if(!n||!s)return;const r=this.naming.names?.plumeTooltip??EO,a=this.said.read(s.title)||s.vehicle?.mission||r.name,c=()=>n.release===void 0||n.release==="burn"?r.ascent:s.jets?.find((h,u)=>`jet:${h.id??u}`===n.release)?.kind==="vent"?r.vent:r.burn;return{kind:"plume",id:s.id,name:a,detail:()=>r.detail.replace("{name}",a).replace("{part}",c()).replace("{distance}",this.distanceText(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=l=>l.toLocaleString(void 0,{maximumFractionDigits:l<10?1:0}),n=yt.sizeOf(t),s=this.sceneRenderer.decorDistanceM(t.id),r=s===void 0?"":this.distanceText(s);return(this.naming.names?.decorTooltip??wO).replace("{name}",e).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(t){const e=t.startsWith(ry)?t.slice(ry.length):void 0,i=e?Db.find(r=>r.id===e):void 0;if(i)return this.naming.comet(i);const n=t.startsWith(ay)?ty.byId(t.slice(ay.length)):void 0;if(n)return this.naming.nova(n);const s=xO[t];return s===void 0?t:this.naming.body(t,s)}get naming(){return this.sceneNaming}sceneNaming=new xf;namesLanguage="en";async loadSceneNames(){const t=dg(ka.preferencesFor(this),fg);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await Iy(t);t===this.namesLanguage&&this.applySceneNaming(new xf(e))}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,c)=>{c>0&&s.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of a){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}s.append(l),i++})};n(this.loaderNotVideo,t),i+=6,n(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t;const e=t.names?.credits??Sp;this.creditsButton.title=e,this.creditsButton.setAttribute("aria-label",e),t.names&&this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names?.compassPoints)}showHoverTooltip(t,e){this.hoverTooltip.textContent=e,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect(),n=t.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${t.clientY-i.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(t){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),Qi.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(wl(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now()),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(t,t),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),this.aircraftAudio?.setPaused(!t),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${AS}</style>${ES}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new Et(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(TO));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new a1(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.ufoElement=document.createElement(Pp),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapFrozenSource=s=>this.frozenMapOf(s),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&dn.fill(n,this)}),this.creditsButton.title=Sp,this.creditsButton.setAttribute("aria-label",Sp),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.addEventListener(Wy,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of be.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Es(ka.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return i?{setting:Uo.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}:void 0}travelHeadingAt(t,e){const i=ze(t,e);if(!i)return 0;for(const n of[400,-400]){const s=ze(t,e+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=ae(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:n},n}traceLabels(t){const e=ka.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const n of t){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of be.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of be.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(t===Ar||t===_r||t===bo)&&i!==e&&this.forwardPlayerAttributes(),t===bo&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Ar,_r,bo]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.sceneRenderer.setCompassForced(t)}lookToward(t){const e=ze(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=ae(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,n)<1)return this.setLookOffset(0,0);const s=(Math.atan2(i,-n)*180/Math.PI+360)%360;this.setLookOffset(((s-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed)}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,n=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,n)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=Na.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){this.ufoElement.sightingData=t,this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(t),this.interpretationShown=this.inTheRound?mi.expand(Nn.expand(this.ufoElement.sighting.interpretation)):void 0,this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new gf(this,()=>document.createElement(wf))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.frozenKey=void 0,this.applyFrozen(this.ufoElement.sighting.frozen)}liveTerrainProviders;frozenKey="none";applyFrozen(t){const e=Wc.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
9333
9333
|
${this.documentUrl??""}
|
|
9334
9334
|
${ti.generation}`;if(e===this.frozenKey)return;const i=this.frozenKey!==void 0&&this.traffic?.set!==void 0;this.frozenKey=e,this.sceneRenderer.setTerrainProviders(Mf.providers(t,this.documentUrl,this.liveTerrainProviders??Hy())),this.ufoElement.observerMapFrozen=this.frozenMapOf(t),i&&(this.traffic=void 0,this.decorMemo=void 0)}frozenMapOf(t){const e=Wc.held(t,"map");if(!e)return;const i=`${ti.address(e.src,this.documentUrl)}
|
|
9335
|
-
${ti.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:Mf.map(e,this.documentUrl)}),this.frozenMap.imagery}frozenMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=Ze.CANVAS_HEIGHT_PX,i=Bi.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Mp,url:this.getAttribute("star-catalog-src")??DO},{magnitudeLimit:yp,url:this.getAttribute("deep-star-catalog-src")??CO}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Mp?yp:Mp;const n=await ar.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=yp||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=fn.gainFor(t.instrument,{fNumber:ze(t,0)?.fNumber,fieldOfViewDeg:In.fovOf(t,0),exposureSeconds:t.exposure});return md(OO,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=Fs.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=No.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,Fs.instants(this.decorWithTraffic(this.ufoElement.sighting),ze(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:In.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:Dc.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;this.setWeather(wl(i,t)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??be.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??be.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=ze(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=ze(i,0),r=_c(i,0),a=ja(i.event.time??{},n?.lng??Qu.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?wS(a):void 0,l=Object.fromEntries(yd(_c(i,t)).map(I=>[I.id,q1(t,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(q1(t,i.weatherTrack,r,s,n,void 0,c),l),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:Qu),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(fn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:In.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Gs.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setLensGhosts(di.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(vh.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(Xe.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(ze(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const h=n?.lat??Qu.lat,u=n?.lng??Qu.lng,d=ja(i.event.time??{},u,i.event.utcOffsetHours),f={lat:h,lng:u,elevationM:n?.elevationM??0};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=i.skyEvents,g=[...p?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(g.length===0?[]:Ae.viewsAt(g,t,{lat:h,lng:u,heightM:f.elevationM})),this.sceneRenderer.setBeams(p?.beams??be.NO_BEAMS);const m=p?.launches??[];if(this.sceneRenderer.setLaunchPlumes(m.length===0||!d?[]:It.viewsAt(m,t,{lat:h,lng:u,heightM:f.elevationM},It.sunDirectionAt(new Date(d.getTime()+t)))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(PO);return}const v=new Date(d.getTime()+t),y=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/No.DEG_PER_SECOND*1e3)),x=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),M=`${Math.floor(v.getTime()/y)}|${Math.round(h/x)}|${Math.round(u/x)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(M===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=M;const b=Fu("Sun",v,f),S=Fu("Moon",v,f);let E=Ui.separationOf(b,S)<1?Ui.viewAt(v,f):void 0;if(E){const I=Ui.offsetOf(b,S,E.separationDeg);if(E.obscuration>be.LIMB_FROM_OBSCURATION){const O=this.limbFor(v,f);O&&(E={...E,obscuration:1-ws.uncoveredFraction(O,E.sunRadiusDeg,I),limb:O})}E={...E,horizonShare:Ui.horizonShare(E,I,b.altitudeDeg,b.azimuthDeg,mr.distanceKm(v,f))}}const w={...b,magnitude:Y0("Sun",v)-2.5*Math.log10(Ui.beamFraction(E))};this.lastSun={altitudeDeg:w.altitudeDeg,azimuthDeg:w.azimuthDeg};const _={...S,phase:WD(v),magnitude:Y0("Moon",v),radiusDeg:mr.apparentRadiusDeg(v,f)},D=VD.map(I=>({body:I,position:Fu(I,v,f),magnitude:Y0(I,v)}));this.sceneRenderer.setAstronomy({sun:w,moon:_,planets:D,comet:this.cometAt(v,f),novae:ty.appearancesAt(v,f).map(({outburst:I,position:O,magnitude:L})=>({id:I.id,position:O,magnitude:L})),stars:this.starCatalog?{catalog:this.starCatalog,date:v,observer:f}:void 0,frame:{date:v,observer:f},localHour:((v.getUTCHours()+v.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(w.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,gh.load(IO).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=ws.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!gr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,be.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>gr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(_O)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=F1(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=F1(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=ze(t,0),i=e?.lng===void 0?void 0:ja(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=be.aircraftProviders.get(this.aircraftSource.id);if(a||be.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const l={lat:e.lat,lng:e.lng,heightM:e.elevationM??0},h=kn.MAX_GAP_S*1e3,u=be.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:e.elevationM??0},f=(p,g)=>p.TrafficDecor.from(c.tracks??[],l,s,p.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,d)});a.between(l,s-u,s+n+h).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await be.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.set=f(g),this.startAircraftSound(c,g),this.announceTraffic(),this.describeTraffic(a,c,g,f),c.set.shown>0&&(this.readUpperAir(c,g,s-u,s+n+h),this.readTrailTraffic(a,c,g,l,s-be.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),l=c?kn.positionAt(c,i.startMs+t):void 0;l&&e.set(r,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(s,i.observer,l.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=be.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=be.trafficRuntime;if(!n)return;const s=e.descriptions?.get(gn.keyOf(i)),r=ze(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:r?.elevationM??0},c=n.AmbientNoise.dbA(wl(this.ufoElement.sighting,this.lastTimeMs)),l=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),h=l&&this.contrailAt(t,this.lastTimeMs);return l&&h?{...l,contrail:h}:l}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,gn.keyOf,{...t.observer,heightM:0},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=be.trafficRuntime;if(!n){i.setVoices([]);return}const s=ze(t,e),r=wl(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),l=t.event.place?.[0],h={lat:s?.lat??l?.lat,lng:s?.lng??l?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(be.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(be.trafficRuntime):be.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>Wt.eyeOf(t,f,a),l=c(e);if(!l)return[];const h=new Map,u=(f,p)=>{let g=h.get(f.id);return g||h.set(f.id,g=new Wt(f,a,c)),g.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,l,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:e?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,gn.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||be.trafficRuntime){!this.aircraftAudio&&be.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(be.trafficRuntime));return}be.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(TO)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(l=>gn.keyOf(l))),r=e.tracks.filter(l=>s.has(gn.keyOf(l))&&l.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),u=await t.describe(l,h).catch(()=>{});u&&(c.set(gn.keyOf(l),u),a.set(gn.keyOf(l),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!l.has(gn.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&l.set(gn.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=i.TrafficDecor.from(c,n,e.startMs,be.TRAIL_MAX_AIRCRAFT,{models:l});e.trailSet=be.alignTrailIds(h,e.set),e.models=new Map([...l,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const l=e.presence.get(a);if(l)for(const[h,u]of t.flights){const d=t.presence.get(h);!d||gn.keyOf(u)!==gn.keyOf(c)||d.fromMs<=l.untilMs&&l.fromMs<=d.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=Wc.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const l=ti.address(s.src,this.documentUrl);r=be.upperAirProviders.get(l),r||be.upperAirProviders.set(l,r=new Vc(ti.json(l)))}else{const l=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=be.upperAirProviders.get(l.id),r||be.upperAirProviders.set(l.id,r=l.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const l=kn.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));l&&e.set(r.id,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(s,i.observer,l.geo)})}return e}sunElevationAt(t,e){const i=Fu("Sun",new Date(t.t),e);return zn.sunElevationDeg(i,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t){t.id!==this.aircraftSource.id&&(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??be.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(AO)))},s=be.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),we(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(gn.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=ja(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const l=Math.min(Math.max(t,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=dO.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,l=new Set;for(const p of i.sourceIds){const g=i.getInterpolatedShapeAt(t,p);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};a.set(p,m);const v=g.aim?this.sceneRenderer.screenPointOf(ks.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},y=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,x=y?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,p):{};l.add(p),(y||g.aim)&&l.delete(p);const M=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),b=this.sizeEstimateOf(p);b.add(M,x);const S=Mh.of(e,p);c.set(p,Ln.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:S&&M>0?Ze.distanceMAt(S.widthM,M):void 0,range:b.distanceRangeAt(M),crossing:x}))}for(const[p,g]of a)for(const[m,v]of a){if(m===p||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const x=c.get(m);x&&c.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=c;const h=i.sourceIds,u=[];for(const[p,g]of a)u.push({sourceId:p,shape:g,distanceM:c.get(p).distanceM,renderOrder:h.indexOf(p),aim:g.aim,hidden:l.has(p)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=(ze(e,t)?.rollDeg??0)+Xe.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Bi.starPointsOf(e.instrument),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=mi.expand(Nn.expand(t)),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,i){const n=this.sceneRenderer.bodyGround,s=Wt.eyeOf(this.ufoElement.sighting,i,n);return s?Wt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>Wt.eyeOf(n,d,i),r=new Wt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,l=r.northM-a.northM,h=r.upM-a.upM,u=Math.hypot(c,l);return{azimuthDeg:(Math.atan2(c,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,u)*180/Math.PI,distanceM:Math.hypot(u,h),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>Wt.eyeOf(n,c,i),r=new Wt(t,i,s).at(e),a=s(e);return r&&a?gi.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>Wt.eyeOf(n,p,i),r=new Wt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),l=a===void 0?void 0:s(a);if(!c||!l)return;const h=c.eastM-l.eastM,u=c.northM-l.northM,d=c.upM-l.upM,f=Math.hypot(h,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>Wt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new Wt(p,a,c).at(t)).filter(p=>p!==void 0));const l=_c(n,t),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new gi(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(Cb,{detail:r})))}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&_c(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=_c(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?ja(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=Qi.schedule({durationMs:a,seed:c,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?ja(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Ci.schedule({ratePerHour:Ci.observedRatePerHour(Ci.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Ci.TYPICAL_VELOCITY_KM_S,seed:a}),l=bp.activeAt(n).map(u=>{const d=bp.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:bp.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const h=Hs.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...c],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>Hs.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=ze(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Bi.focalLengthMmFor(i,In.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return yr.of(e.instrument,Ze.CANVAS_HEIGHT_PX,In.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new pO,this.sizeEstimates.set(t,e)),e}}const wf="rr0-scene";function Ob(){Vy(),customElements.get(wf)||customElements.define(wf,be)}const LO={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",referenceGhostsFailed:"The picture could not be read: its site has to allow it to be read from another.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",rareIceCrystals:"Rare crystals",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},th={...LO,accountBy:"Account by",unnamedObserver:"Observer {n}",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",source:"Source",basis:{measured:"measured",stated:"stated",derived:"derived",assumed:"assumed"},credits:"Credits",editThisObservation:"Edit this observation",share:"Share",embedObservation:"Embed the observation",back:"Back",shareScope:"Share",shareScopeCase:"Whole case",shareOpensOn:"Opens on",shareStartAt:"Start at",shareOptionLabels:"Show summary chips",shareOptionMap:"Open map",shareOptionMilestones:"Show moments",shareOptionCompare:"Compare account",showLabels:"Show what it states",interpretation:"Interpretation",account:"Account",interpretationBy:"{title}, by {by}",confrontation:"Against the account",confrontationDirection:"{deg}° off",confrontationWidth:"width ×{ratio}",confrontationHeight:"height ×{ratio}",showComparison:"Compare with the account",hideComparison:"Stop comparing with the account",hideLabels:"Hide what it states",variant:"Variant: {name}",verdicts:{consolidated:"compatible with consolidated biases",contested:"only by invoking contested biases",incompatible:"incompatible even at the bounds"},variantFields:{time:"Time",heading:"Heading",elevation:"Elevation",size:"Size",duration:"Duration",sweep:"Sweep across the sky"},variantReadings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving","moving-seen-still":"a moving light seen hovering","brightening-as-approach":"growing brighter read as coming nearer"}},NO=Object.freeze(Object.defineProperty({__proto__:null,sightingMessages_en:th},Symbol.toStringTag,{value:"Module"}));class vr{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(t,e,i){const n=new URL(`${t}.mjs`,e);return n.href.startsWith(`${vr.CDN}/`)?`${i}/lib/${t}.mjs`:(n.pathname=n.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),n.href)}static VERSION_PARAMETER="v";static freezable(t){return t in vr.DIRECTORIES}static frozenLink(t,e){const i=new URL(t);return i.searchParams.set(vr.VERSION_PARAMETER,e),i.href}static frozen(t,e){return`${vr.CDN}/${vr.PACKAGE}@${e}/${vr.DIRECTORIES[t]}/${t}.mjs`}}class Uh{static PRODUCTION="https://ufoathome.org";static home(){try{const t=new URL(import.meta.url),e=new URL(location.href);return(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname.endsWith(".localhost"))&&t.origin===e.origin?e.origin:Uh.PRODUCTION}catch{return Uh.PRODUCTION}}}const sg={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},kO=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:sg},Symbol.toStringTag,{value:"Module"})),UO=`
|
|
9335
|
+
${ti.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery:Mf.map(e,this.documentUrl)}),this.frozenMap.imagery}frozenMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=Ze.CANVAS_HEIGHT_PX,i=Bi.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:Mp,url:this.getAttribute("star-catalog-src")??CO},{magnitudeLimit:yp,url:this.getAttribute("deep-star-catalog-src")??OO}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>Mp?yp:Mp;const n=await ar.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=yp||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=fn.gainFor(t.instrument,{fNumber:ze(t,0)?.fNumber,fieldOfViewDeg:In.fovOf(t,0),exposureSeconds:t.exposure});return md(PO,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=Fs.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,n=this.degreesPerPixelAt(t),s=No.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(t).length,Fs.instants(this.decorWithTraffic(this.ufoElement.sighting),ze(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(e.fromMs+e.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-1)*s/r),stepMs:e.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:In.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:Dc.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;this.setWeather(wl(i,t)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??be.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??be.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const n=ze(i,t);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=ze(i,0),r=_c(i,0),a=ja(i.event.time??{},n?.lng??Qu.lng,i.event.utcOffsetHours),c=i.weatherSource!==void 0&&a?wS(a):void 0,l=Object.fromEntries(yd(_c(i,t)).map(I=>[I.id,q1(t,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:c)]));this.sceneRenderer.setCloudOffset(q1(t,i.weatherTrack,r,s,n,void 0,c),l),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,t)}:Qu),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(fn.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:In.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,Gs.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setLensGhosts(di.optics(i.instrument,n?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3))),this.sceneRenderer.setPerception(vh.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(Xe.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(ze(i,0),n,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applyFrozen(i.frozen),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const h=n?.lat??Qu.lat,u=n?.lng??Qu.lng,d=ja(i.event.time??{},u,i.event.utcOffsetHours),f={lat:h,lng:u,elevationM:n?.elevationM??0};this.pushSatellitesAt(d,t,f),this.ensureFireballs(d);const p=i.skyEvents,g=[...p?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(g.length===0?[]:Ae.viewsAt(g,t,{lat:h,lng:u,heightM:f.elevationM})),this.sceneRenderer.setBeams(p?.beams??be.NO_BEAMS);const m=p?.launches??[];if(this.sceneRenderer.setLaunchPlumes(m.length===0||!d?[]:It.viewsAt(m,t,{lat:h,lng:u,heightM:f.elevationM},It.sunDirectionAt(new Date(d.getTime()+t)))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!d),!d){this.sceneRenderer.setAstronomy(LO);return}const v=new Date(d.getTime()+t),y=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/No.DEG_PER_SECOND*1e3)),x=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),M=`${Math.floor(v.getTime()/y)}|${Math.round(h/x)}|${Math.round(u/x)}|${Math.round(f.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(M===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=M;const b=Fu("Sun",v,f),S=Fu("Moon",v,f);let E=Ui.separationOf(b,S)<1?Ui.viewAt(v,f):void 0;if(E){const I=Ui.offsetOf(b,S,E.separationDeg);if(E.obscuration>be.LIMB_FROM_OBSCURATION){const O=this.limbFor(v,f);O&&(E={...E,obscuration:1-ws.uncoveredFraction(O,E.sunRadiusDeg,I),limb:O})}E={...E,horizonShare:Ui.horizonShare(E,I,b.altitudeDeg,b.azimuthDeg,mr.distanceKm(v,f))}}const w={...b,magnitude:Y0("Sun",v)-2.5*Math.log10(Ui.beamFraction(E))};this.lastSun={altitudeDeg:w.altitudeDeg,azimuthDeg:w.azimuthDeg};const _={...S,phase:WD(v),magnitude:Y0("Moon",v),radiusDeg:mr.apparentRadiusDeg(v,f)},D=VD.map(I=>({body:I,position:Fu(I,v,f),magnitude:Y0(I,v)}));this.sceneRenderer.setAstronomy({sun:w,moon:_,planets:D,comet:this.cometAt(v,f),novae:ty.appearancesAt(v,f).map(({outburst:I,position:O,magnitude:L})=>({id:I.id,position:O,magnitude:L})),stars:this.starCatalog?{catalog:this.starCatalog,date:v,observer:f}:void 0,frame:{date:v,observer:f},localHour:((v.getUTCHours()+v.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(u/15)))%24+24)%24,eclipse:E}),this.ufoElement.setSunAltitude(w.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,gh.load(DO).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const n=ws.profile(t,e,this.limbRelief);return this.limbCache={profile:n,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},n}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(t.getTime()+e),s=[];for(const r of this.satellites.passes.positionsAt(n,i,-1))r.magnitude!==void 0&&s.push({norad:r.object.norad,name:r.object.name,position:{altitudeDeg:r.altitudeDeg,azimuthDeg:r.azimuthDeg},magnitude:r.magnitude,heightKm:r.heightKm});this.sceneRenderer.setSatellites(s)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=t?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!gr.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,be.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(c=>gr.asReentry(c,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(_O)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const n=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:n},n}seatedDecor(t,e){if(!t.some(r=>r.observerKeyframes?.length))return t;const i=t.map(r=>{if(!r.observerKeyframes?.length)return"";const a=F1(r,e);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===t&&n.seats===i)return n.seated;const s=t.map(r=>{if(!r.observerKeyframes?.length)return r;const a=F1(r,e);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:t,seats:i,seated:s},s}ensureTraffic(t){const e=ze(t,0),i=e?.lng===void 0?void 0:ja(t.event.time??{},e.lng,t.event.utcOffsetHours),n=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(this.upperAirHeardLive=void 0,r===""||s===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:r,status:"outside"};return}let a=be.aircraftProviders.get(this.aircraftSource.id);if(a||be.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const c={key:r,status:"loading",startMs:s,observer:{lat:e.lat,lng:e.lng}};this.traffic=c;const l={lat:e.lat,lng:e.lng,heightM:e.elevationM??0},h=kn.MAX_GAP_S*1e3,u=be.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:e.elevationM??0},f=(p,g)=>p.TrafficDecor.from(c.tracks??[],l,s,p.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,d)});a.between(l,s-u,s+n+h).then(async p=>{if(this.traffic!==c)return;if(p.status!=="found"){c.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await be.loadTrafficRuntime()}catch{this.traffic===c&&(c.status="unavailable",this.announceTraffic());return}this.traffic===c&&(c.status="ready",c.tracks=p.tracks,c.set=f(g),this.startAircraftSound(c,g),this.announceTraffic(),this.describeTraffic(a,c,g,f),c.set.shown>0&&(this.readUpperAir(c,g,s-u,s+n+h),this.readTrailTraffic(a,c,g,l,s-be.TRAIL_LOOKBACK_MS,s+n+h)))})}trafficSunlight(t){const e=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return e;for(const[r,a]of n.presence){if(t<a.fromMs||t>a.untilMs)continue;const c=n.flights.get(r),l=c?kn.positionAt(c,i.startMs+t):void 0;l&&e.set(r,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(s,i.observer,l.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=be.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const n=be.trafficRuntime;if(!n)return;const s=e.descriptions?.get(gn.keyOf(i)),r=ze(this.ufoElement.sighting,this.lastTimeMs),a={lat:e.observer.lat,lng:e.observer.lng,heightM:r?.elevationM??0},c=n.AmbientNoise.dbA(wl(this.ufoElement.sighting,this.lastTimeMs)),l=n.TrafficInfos.at(i,s,a,e.startMs+this.lastTimeMs,{ambientDbA:c}),h=l&&this.contrailAt(t,this.lastTimeMs);return l&&h?{...l,contrail:h}:l}contrailAt(t,e){const i=this.traffic?.contrails?.find(s=>s.id===t);if(!i)return;let n;for(const s of i.points){if(s.tMs>e)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){!t.set||!t.observer||(t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,gn.keyOf,{...t.observer,heightM:0},{ambientDbA:e.AmbientNoise.BASE_DB_A}))}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound();const i=this.aircraftAudio;if(!i)return;const n=be.trafficRuntime;if(!n){i.setVoices([]);return}const s=ze(t,e),r=wl(t,e),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},c=this.trafficVoices(e,s,a,n),l=t.event.place?.[0],h={lat:s?.lat??l?.lat,lng:s?.lng??l?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,c.push(...this.decorAircraftHearing.voices(t,e,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,u=>this.decorModelSounds.get(u.model?.id??""))),c.push(...this.bodyVoices(t,e,a,n)),c.sort((u,d)=>d.levelDbA-u.levelDbA),c.length=Math.min(c.length,4)),i.setVoices(c,s?.headingDeg??0)}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(be.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(be.trafficRuntime):be.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,n){const s=this.interpretationShown,r=t.event.place?.[0];if(!s||!r||!s.bodies.some(f=>f.sound))return[];const a=this.sceneRenderer.bodyGround,c=f=>Wt.eyeOf(t,f,a),l=c(e);if(!l)return[];const h=new Map,u=(f,p)=>{let g=h.get(f.id);return g||h.set(f.id,g=new Wt(f,a,c)),g.at(p)};this.bodyHearing??=new n.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(s.bodies,u,l,r,e,d,i)}trafficVoices(t,e,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:e?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,gn.keyOf,a,s.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(e.length!==0){for(const i of e){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||be.trafficRuntime){!this.aircraftAudio&&be.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(be.trafficRuntime));return}be.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio;return e.setLevel(this.ufoElement.level),this.interacted&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"),e}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(RO)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,n){if(!t.describe||!e.set||!e.tracks)return;const s=new Set([...e.set.flights.values()].map(l=>gn.keyOf(l))),r=e.tracks.filter(l=>s.has(gn.keyOf(l))&&l.points.length>0),a=new Map,c=new Map;await Promise.all(r.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),u=await t.describe(l,h).catch(()=>{});u&&(c.set(gn.keyOf(l),u),a.set(gn.keyOf(l),i.AircraftModels.of(u)))})),!(this.traffic!==e||a.size===0)&&(e.descriptions=c,e.models=a,e.set=n(i,a),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,n,s,r){if(e.startMs===void 0)return;const a=await t.between(n,s,r).catch(()=>{});if(this.traffic!==e||a?.status!=="found")return;const c=a.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(e.models??[]);if(t.describe&&await Promise.all(c.filter(u=>u.points.length>0&&!l.has(gn.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&l.set(gn.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=i.TrafficDecor.from(c,n,e.startMs,be.TRAIL_MAX_AIRCRAFT,{models:l});e.trailSet=be.alignTrailIds(h,e.set),e.models=new Map([...l,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[a,c]of e.flights){const l=e.presence.get(a);if(l)for(const[h,u]of t.flights){const d=t.presence.get(h);!d||gn.keyOf(u)!==gn.keyOf(c)||d.fromMs<=l.untilMs&&l.fromMs<=d.untilMs&&i.set(h,a)}}const n=a=>i.get(a)??`${a}-trail`,s=new Set(i.values()),r=e.objects.filter(a=>!s.has(a.id));return{...t,objects:[...t.objects.map(a=>({...a,id:n(a.id)})),...r],presence:new Map([...[...t.presence].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.presence.get(a.id)])]),flights:new Map([...[...t.flights].map(([a,c])=>[n(a),c]),...r.map(a=>[a.id,e.flights.get(a.id)])])}}async readUpperAir(t,e,i,n){if(!t.observer)return;const s=Wc.held(this.ufoElement.sighting.frozen,"upperAir");let r;if(s){const l=ti.address(s.src,this.documentUrl);r=be.upperAirProviders.get(l),r||be.upperAirProviders.set(l,r=new Vc(ti.json(l)))}else{const l=this.upperAirSource??e.UPPER_AIR_SOURCES[0];r=be.upperAirProviders.get(l.id),r||be.upperAirProviders.set(l.id,r=l.create())}const a={lat:t.observer.lat,lng:t.observer.lng},c=await r.between(a,i,n);this.traffic!==t||c.status!=="found"||(s||(this.upperAirHeardLive={...a,startMs:i,endMs:n,answer:c}),t.air=c.samples,t.airSource=c.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,n=i?.trailSet??i?.set,s=this.lastSun;if(!i||!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const r of i.contrails){const a=n.presence.get(r.id),c=n.flights.get(r.id);if(!a||!c)continue;const l=kn.positionAt(c,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,t)));l&&e.set(r.id,{heightM:l.geo.heightM,sunElevationDeg:zn.sunElevationDeg(s,i.observer,l.geo)})}return e}sunElevationAt(t,e){const i=Fu("Sun",new Date(t.t),e);return zn.sunElevationDeg(i,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t){t.id!==this.aircraftSource.id&&(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??be.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(AO)))},s=be.tleArchive;(async()=>{if(!await s.covers(t))return n("outside");const[r,a]=await Promise.all([s.at(t),we(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(gn.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!(!e||r===void 0||a===void 0))return e.passes.positionsAt(t,{lat:r,lng:a,elevationM:n?.elevationM??0})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,n=ze(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!e||r===void 0||a===void 0)return[];const c=ja(i.event.time??{},a,i.event.utcOffsetHours);if(!c)return[];const l=Math.min(Math.max(t,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},u=JSON.stringify([this.satellitesFor,c.getTime(),r,a,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=e.passes.passesDuring(c,new Date(c.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=dO.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=e.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(t),a=new Map,c=new Map,l=new Set;for(const p of i.sourceIds){const g=i.getInterpolatedShapeAt(t,p);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};a.set(p,m);const v=g.aim?this.sceneRenderer.screenPointOf(ks.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},y=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,x=y?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,p):{};l.add(p),(y||g.aim)&&l.delete(p);const M=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),b=this.sizeEstimateOf(p);b.add(M,x);const S=Mh.of(e,p);c.set(p,Ln.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:S&&M>0?Ze.distanceMAt(S.widthM,M):void 0,range:b.distanceRangeAt(M),crossing:x}))}for(const[p,g]of a)for(const[m,v]of a){if(m===p||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const x=c.get(m);x&&c.set(p,{distanceM:x.distanceM*.999,basis:x.basis});break}this.depths=c;const h=i.sourceIds,u=[];for(const[p,g]of a)u.push({sourceId:p,shape:g,distanceM:c.get(p).distanceM,renderOrder:h.indexOf(p),aim:g.aim,hidden:l.has(p)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=(ze(e,t)?.rollDeg??0)+Xe.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(u,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Bi.starPointsOf(e.instrument),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.interpretationShown=mi.expand(Nn.expand(t)),this.ufoElement.playerTitle=t?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,i){const n=this.sceneRenderer.bodyGround,s=Wt.eyeOf(this.ufoElement.sighting,i,n);return s?Wt.lineOfSightMeetsGround(s,t,e,n):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>Wt.eyeOf(n,d,i),r=new Wt(t,i,s).at(e),a=s(e);if(!r||!a)return;const c=r.eastM-a.eastM,l=r.northM-a.northM,h=r.upM-a.upM,u=Math.hypot(c,l);return{azimuthDeg:(Math.atan2(c,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,u)*180/Math.PI,distanceM:Math.hypot(u,h),eastM:r.eastM,northM:r.northM,aboveGroundM:r.upM-r.sizeM.heightM/2-i.heightAt(r.eastM,r.northM),sizeM:r.sizeM,attitude:r.attitude,appearance:r.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=c=>Wt.eyeOf(n,c,i),r=new Wt(t,i,s).at(e),a=s(e);return r&&a?gi.projectionOf(r,a):void 0}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>Wt.eyeOf(n,p,i),r=new Wt(t,i,s),a=r.at(e)?e:t.track[0]?.t,c=a===void 0?void 0:r.at(a),l=a===void 0?void 0:s(a);if(!c||!l)return;const h=c.eastM-l.eastM,u=c.northM-l.northM,d=c.upM-l.upM,f=Math.hypot(h,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,c=p=>Wt.eyeOf(n,p,a);i&&(s=i.bodies.map(p=>new Wt(p,a,c).at(t)).filter(p=>p!==void 0));const l=_c(n,t),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(t):void 0;if(d&&(r=new gi(n.timeline,this.confrontationTolerance).at(t,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!e)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(Cb,{detail:r})))}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(n)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const n=this.lastLightningT;if(this.lastLightningT=e,n===void 0||e<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=e).pop();s&&_c(t,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(t){const e=_c(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=t.event.time,s=t.event.place?.[0],r=n?.year!==void 0?ja(n,s?.lng??0,t.event.utcOffsetHours):void 0,a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=Qi.schedule({durationMs:a,seed:c,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,n=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?ja(i,e.lng,t.event.utcOffsetHours):void 0;if(!n||e?.lat===void 0||e.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:e.lat,lng:e.lng,elevationM:0},r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,a=Math.round(n.getTime()/1e3)+Math.round(e.lat*1e3),c=Ci.schedule({ratePerHour:Ci.observedRatePerHour(Ci.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Ci.TYPICAL_VELOCITY_KM_S,seed:a}),l=bp.activeAt(n).map(u=>{const d=bp.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:bp.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(c,0,0);return}const h=Hs.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:a+1});this.sceneRenderer.setMeteorShower([...h,...c],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(r=>r.t+r.durationMs<=this.ufoElement.seekableDuration).filter(r=>Hs.magnitudeOf(r)<=e).filter(r=>{const a=this.sceneRenderer.meteorMidpoint(r);return a!==void 0&&!this.sceneRenderer.groundHidesDirection(a.altitudeDeg,a.azimuthDeg)}).sort((r,a)=>a.brightness-r.brightness);if(i.length===0)return;const n=i[t%i.length],s=this.sceneRenderer.meteorMidpoint(n);if(s)return{t:Math.round(n.t+n.durationMs*.45),...s}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,n=i.frame,s=ze(e,t),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Bi.focalLengthMmFor(i,In.fovOf(e,t));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return yr.of(e.instrument,Ze.CANVAS_HEIGHT_PX,In.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new pO,this.sizeEstimates.set(t,e)),e}}const wf="rr0-scene";function Ob(){Vy(),customElements.get(wf)||customElements.define(wf,be)}const NO={color:"Color",transparency:"Transparency",halo:"Halo",blur:"Blur",brightness:"Brilliance",shapeTitle:"Name",utcOffset:"Time zone",cloudBase:"Cloud base",elevation:"Altitude",heightAboveGround:"Height above ground",duration:"Duration",placeName:"Place",latitude:"Latitude",longitude:"Longitude",heading:"Heading",pitch:"Tilt",roll:"Roll",sway:"Sway at rest",swayTitle:"How much the body holding the instrument moves the view when not walking: 1 for a person standing, 0 for a tripod. Blank: 1 (0 if the account says the observer was paralysed)",referenceGhosts:"Ghosts in the picture",referenceFindGhosts:"Look for ghosts",referenceGhostsSearching:"Looking…",referenceGhostsFound:"{count} ghosts found, each across the lens's axis from its light.",referenceGhostsFoundScaled:"{count} ghosts found, each at {scale} times its light's offset from the lens's axis.",referenceGhostsLow:"Perhaps {count} ghost(s): too few to be sure.",referenceGhostsNone:"No ghost found: no faint spot lies across one point from a light.",referenceGhostsCropped:"The lens's axis is off the picture's centre: the picture was cropped.",lensGlass:"Taken through",lensGlassNone:"the lens alone",lensGlassFilter:"a filter on the lens",lensGlassWindow:"a window",lensGlassWindscreen:"a windscreen",lensDrops:"Drops on the glass",lensDropsTitle:"0 to 1: how much of the outermost glass drops of water cover. Blank: from the rain or snow falling, unless the glass is sheltered",lensCondensation:"Condensation",lensCondensationTitle:"0 to 1: condensation on the glass, as on a lens taken from the warm into the cold. Blank: none",lensDirt:"Dirt",lensDirtTitle:"0 to 1: dirt, grease or fingerprints on the glass. Blank: none",lensSheltered:"Sheltered from the rain",lensShelteredTitle:"The outermost glass was out of the rain or snow: under a roof, or behind a windscreen whose wipers run",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",rareIceCrystals:"Rare crystals",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorTrafficLight:"Traffic light",decorCrossing:"Pedestrian crossing",decorRoadSign:"Road sign",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},th={...NO,accountBy:"Account by",unnamedObserver:"Observer {n}",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",source:"Source",basis:{measured:"measured",stated:"stated",derived:"derived",assumed:"assumed"},credits:"Credits",editThisObservation:"Edit this observation",share:"Share",embedObservation:"Embed the observation",back:"Back",shareScope:"Share",shareScopeCase:"Whole case",shareOpensOn:"Opens on",shareStartAt:"Start at",shareOptionLabels:"Show summary chips",shareOptionMap:"Open map",shareOptionMilestones:"Show moments",shareOptionCompare:"Compare account",showLabels:"Show what it states",interpretation:"Interpretation",account:"Account",interpretationBy:"{title}, by {by}",confrontation:"Against the account",confrontationDirection:"{deg}° off",confrontationWidth:"width ×{ratio}",confrontationHeight:"height ×{ratio}",showComparison:"Compare with the account",hideComparison:"Stop comparing with the account",hideLabels:"Hide what it states",variant:"Variant: {name}",verdicts:{consolidated:"compatible with consolidated biases",contested:"only by invoking contested biases",incompatible:"incompatible even at the bounds"},variantFields:{time:"Time",heading:"Heading",elevation:"Elevation",size:"Size",duration:"Duration",sweep:"Sweep across the sky"},variantReadings:{grouped:"lights read as one body","still-seen-moving":"a still light seen moving","moving-seen-still":"a moving light seen hovering","brightening-as-approach":"growing brighter read as coming nearer"}},kO=Object.freeze(Object.defineProperty({__proto__:null,sightingMessages_en:th},Symbol.toStringTag,{value:"Module"}));class vr{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(t,e,i){const n=new URL(`${t}.mjs`,e);return n.href.startsWith(`${vr.CDN}/`)?`${i}/lib/${t}.mjs`:(n.pathname=n.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),n.href)}static VERSION_PARAMETER="v";static freezable(t){return t in vr.DIRECTORIES}static frozenLink(t,e){const i=new URL(t);return i.searchParams.set(vr.VERSION_PARAMETER,e),i.href}static frozen(t,e){return`${vr.CDN}/${vr.PACKAGE}@${e}/${vr.DIRECTORIES[t]}/${t}.mjs`}}class Uh{static PRODUCTION="https://ufoathome.org";static home(){try{const t=new URL(import.meta.url),e=new URL(location.href);return(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname.endsWith(".localhost"))&&t.origin===e.origin?e.origin:Uh.PRODUCTION}catch{return Uh.PRODUCTION}}}const sg={share:"Share",close:"Close",link:"Link",embed:"Embed",copy:"Copy",copied:"Copied",freeze:"Freeze version {version}",freezeHint:"The embed keeps the rendering of this version of UFO@home, loaded from jsDelivr, and gets none of the later fixes. Unticked, it follows each release.",unsaved:"The link opens the file at its address: your unsaved changes are not in it. Save the file there first.",unavailable:"Only a file loaded from an address can be shared: put it online, then open it from its address."},UO=Object.freeze(Object.defineProperty({__proto__:null,shareMessages_en:sg},Symbol.toStringTag,{value:"Module"})),FO=`
|
|
9336
9336
|
<style>
|
|
9337
9337
|
/* What the dialog is drawn with: light by default, and the dark set when the system asks for it, as the player and the editors
|
|
9338
9338
|
are. The form controls follow through color-scheme. Defined here and not by the host, so that any element can hold this dialog;
|
|
@@ -9558,6 +9558,6 @@ ${ti.generation}`;return this.frozenMap?.key!==i&&(this.frozenMap={key:i,imagery
|
|
|
9558
9558
|
<button id="copy" class="share-copy" type="button">Copy</button>
|
|
9559
9559
|
</div>
|
|
9560
9560
|
</dialog>
|
|
9561
|
-
`;class il extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(il.TAG)||customElements.define(il.TAG,il)}subject;messages=sg;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=
|
|
9562
|
-
${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages,e=(i,n)=>{this.shadow.getElementById(i).textContent=n};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("freeze-label",t.freeze.replace("{version}","0.141.0")),this.freeze.parentElement.title=t.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=we(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-C53SBK2N.js");return{ShareCodeEditor:t}},[],import.meta.url).then(({ShareCodeEditor:t})=>{this.codeEditor=new t(this.shadow.getElementById("embed-code"),this.embedMarkup.value,e=>{this.embedMarkup.value=e},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(t,e){try{await navigator.clipboard.writeText(t),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{e.select()}}}class mn{static PLAIN=/^\d+(?:[.,]\d+)?$/;static COLONS=/^(?:(\d+):)?(\d{1,2}):(\d{1,2}(?:[.,]\d+)?)$/;static UNITS=/^(?:(\d+(?:[.,]\d+)?)h)?(?:(\d+(?:[.,]\d+)?)m)?(?:(\d+(?:[.,]\d+)?)s)?$/i;static CLOCK=/^(?:(\d{4})-(\d{2})-(\d{2})[T ])?T?(\d{1,2}):(\d{2})(?::(\d{2}(?:[.,]\d+)?))?$/;static num(t){return t===void 0?0:Number(t.replace(",","."))}static delta(t){const e=(t??"").trim();if(e==="")return;if(mn.PLAIN.test(e))return mn.num(e);const i=mn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||mn.num(a)>=60?void 0:mn.num(s)*3600+Number(r)*60+mn.num(a)}const n=mn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?mn.num(n[1])*3600+mn.num(n[2])*60+mn.num(n[3]):/^P/i.test(e)?Xc.seconds(e.toUpperCase()):void 0}static isClock(t){return mn.clock(t)!==void 0}static clock(t){const e=mn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:mn.num(c)};if(!(l.hour>=24||l.minute>=60||l.second>=60)){if(i!==void 0){const h={year:Number(i),month:Number(n),day:Number(s)};if(h.month<1||h.month>12||h.day<1||h.day>31)return;l.date=h}return l}}static elapsedSince(t,e){if(!t||t.hour===void 0||t.minute===void 0)return;const i=t.hour*3600+t.minute*60+(t.second??0),n=e.hour*3600+e.minute*60+e.second;if(e.date){if(t.year===void 0||t.month===void 0||t.day===void 0)return;const r=Date.UTC(e.date.year,e.date.month-1,e.date.day)/1e3+n,a=Date.UTC(t.year,t.month-1,t.day)/1e3+i;return Math.max(0,r-a)}let s=n-i;return s<=-43200&&(s+=86400),Math.max(0,s)}}Ob();il.register();const Md=Uh.home(),td="compare-account",Ap="start-time",oy="start-clock",Yl="observer",ed="case",id="account",nd="variant-",_p=`${Md}/edit/`;class nl extends HTMLElement{static get observedAttributes(){return["src","show-labels",Ap,oy,Yl,Ar,_r,td]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;shareButton;shareDialog;shareStartOn;shareStart;shareScopeRow;shareScopeLabel;shareScope;shareOpensRow;shareOpensLabel;shareOpens;shareStartLabel;shareOptions;labelsToggle;paramSummary;summaryBuilder=new wh(th,new xf,new Es(["en"]),new rd({}),{messages:th,locale:"en"});summarySignature="";assessmentEntries=[];assessmentToken=0;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];caseSource;interpretationChoice;interpretationLabel;interpretationSelect;confrontationElement;confrontationHeading;confrontationList;compareButton;variantChips;variantMoved;interpretationLoaders=new Map;interpretationToken=0;offeredFor;currentSrc;infoOpen=!1;creditsOpen=!1;labelsShown=!1;language="en";messages=th;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${Hb}</style>${Bb}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(wf),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=qt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(Cb,i=>this.showConfrontation(i.detail)),this.sceneElement.ufoElement.addEventListener("timeupdate",()=>this.refreshParamSummary()),this.supportsPopover?(this.infoPanel.setAttribute("popover","auto"),this.infoPanel.removeAttribute("hidden"),this.infoButton.setAttribute("popovertarget","info-panel"),this.infoPanel.addEventListener("beforetoggle",i=>{i.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",i=>this.syncInfoOpen(i.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.shareButton.addEventListener("click",()=>this.openShare());for(const i of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(n=>n.input)])i.addEventListener("input",()=>this.refreshShareLinks());for(const i of[this.shareScope,this.shareOpens])i.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&this.loadLocaleMessages()}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=ka.preferencesFor(this);this.preferences=e;const i=dg(e,fg),[n,s,r]=i==="en"?[th,{},void 0]:await Promise.all([VS(i),$S(i),Iy(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new rd(s),this.said=new Es(e),this.summaryBuilder=new wh(this.messages,new xf(r),this.said,this.tags,{messages:this.messages,locale:i}),this.accountPrefix.textContent=this.messages.accountBy,this.interpretationLabel.textContent=this.messages.interpretation,this.confrontationHeading.textContent=this.messages.confrontation;const c=this.entries.find(l=>l.src===this.currentSrc);c&&this.offerInterpretations(c),this.updateCompareButton(),this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.syncLabelsToggle(),this.refreshParamSummary(),a&&this.currentSrc&&this.runAssessments(),this.shareButton.title=this.messages.share,this.shareButton.setAttribute("aria-label",this.messages.share),this.shareStartLabel.textContent=this.messages.shareStartAt,this.shareScopeLabel.textContent=this.messages.shareScope,this.shareOpensLabel.textContent=this.messages.shareOpensOn,this.shareOptions.labels.label.textContent=this.messages.shareOptionLabels,this.shareOptions.map.label.textContent=this.messages.shareOptionMap,this.shareOptions.milestones.label.textContent=this.messages.shareOptionMilestones,this.shareOptions.compare.label.textContent=this.messages.shareOptionCompare,this.shareStart.setAttribute("aria-label",this.messages.shareStartAt),this.shareDialog.useLanguage(i),this.infoOpen&&this.populateInfoPanel(),this.updateAccountLine()}preferences=[];localeToken=0;said=new Es(["en"]);tags=new rd({});connectedCallback(){ka.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Ar||t===_r)&&this.forwardPlayerAttributes(),t===Yl&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===td&&this.setComparing(this.hasAttribute(td))}forwardPlayerAttributes(){for(const t of[Ar,_r]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Na.recording(t);this.sceneElement.holdForNewScene(e);const i=await e;if(Array.isArray(i))throw new Error(`${t} is a bare list of recordings, which is no longer read: list them as the sighting events of a case.json`);if(tn.isCase(i)){tn.check(i);const n=tn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:t}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?tn.accountIds(i.json,i.url,s.src,r):[r]).includes(e)});n&&n.src!==this.currentSrc&&this.selectObserver(n.src),this.sceneElement.ufoElement.currentTime=Math.max(0,t)*1e3}get observerUrls(){return this.entries.map(t=>t.src)}set observerUrls(t){this.loadObserverUrls(t)}async loadObserverUrls(t,e){const i=await Promise.all(t.map(async n=>({src:n,sighting:await Na.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=tn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t,this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.messages.unnamedObserver.replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const l=n.filter(h=>h===n[r]).length>1;c.textContent=(l?this.caseTitleOf(a):void 0)??n[r],this.observerSelect.appendChild(c)}const s=t.find(r=>r.src===this.currentSrc)??this.entryAsked(t)??t[0];s?this.selectObserver(s.src):this.updateAccountLine()}entryAsked(t){const e=this.getAttribute(Yl)?.trim();if(!e)return;const i=t.find(s=>this.plain(s).observer?.id===e);if(i)return i;const n=t.find(s=>s.src.split("/").pop()===e.split("/").pop());return n||(/^\d+$/.test(e)?t[Number(e)-1]:void 0)}observerKeyOf(t){return this.plain(t).observer?.id??String(this.entries.indexOf(t)+1)}sharedEntry(){const t=this.shareScope.value;if(!(!this.caseSource||t===ed))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===ed}editorUrl(){if(!this.currentSrc)return _p;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${_p}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${_p}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){const t=this.caseSource,e=this.entries.find(s=>s.src===this.currentSrc),i=/^case-(\d+)$/.exec(this.interpretationSelect.value);if(!t||!e||!i)return;const n=tn.interpretationEvents(t.json,tn.accountIds(t.json,t.url,e.src,this.plain(e).id))[Number(i[1])];return n?.url?new URL(n.url,t.url).href:void 0}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Yl,t.observer]]:[],...this.replayAttributes()].map(([n,s])=>s===""?` ${n}`:` ${n}="${s}"`).join("");return`<rr0-sighting src="${t.src}"${i}></rr0-sighting>`}playUrl(){const t=this.sharedAddress(),e=[...t.observer?[`${Yl}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${Md}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${Md}/play/${e&&"?"+e}`}sharedAddress(){const t=e=>e?new URL(e,location.href).href:"";if(this.sharesCase){const e=this.entries.find(i=>i.src===this.shareOpens.value)??this.entries.find(i=>i.src===this.currentSrc);return{src:this.caseSource.url,observer:e?this.observerKeyOf(e):void 0}}return{src:t(this.sharedEntry()?.src??this.currentSrc??"")}}replayAttributes(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push([Ap,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Ar,""]),t.milestones.input.checked||e.push([_r,""]),t.compare.input.checked&&e.push([td,""]),e}replayQuery(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push(`d=${this.shareStartSeconds}`),t.labels.input.checked||e.push("labels=0"),t.map.input.checked&&e.push("map=1"),t.milestones.input.checked||e.push("moments=0"),t.compare.input.checked&&e.push("compare=1"),e}get shareStartSeconds(){const t=Math.floor(Number(this.shareStart.value));return this.shareStartOn.checked&&Number.isFinite(t)&&t>=0?t:void 0}refreshShareLinks(){this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.refresh()}openShare(){const t=this.sceneElement.ufoElement;this.shareStart.max=String(Math.floor(t.seekableDuration/1e3)),this.shareStart.value=String(Math.floor(t.currentTime/1e3)),this.shareStartOn.checked=!1,this.shareOptions.labels.input.checked=this.labelsShown,this.shareOptions.map.input.checked=t.observerMapOpen,this.shareOptions.milestones.input.checked=t.milestonesVisible,this.shareOptions.compare.input.checked=this.sceneElement.compareAccount,this.offerShareScope(),this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.open()}offerShareScope(){const t=this.caseSource!==void 0&&this.entries.length>1;if(this.shareScopeRow.hidden=!t,this.shareScope.innerHTML="",this.shareOpens.innerHTML="",!t)return;const e=(i,n,s)=>{const r=document.createElement("option");r.value=n,r.textContent=s,i.appendChild(r)};e(this.shareScope,ed,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.messages.unnamedObserver.replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=ed,this.shareOpens.value=this.currentSrc??this.entries[0].src}offerInterpretations(t){const e=this.offeredFor===t.sighting,i=this.interpretationSelect.value;this.offeredFor=t.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(u,d,f)=>{const p=document.createElement("option");p.value=u,p.textContent=d,this.interpretationSelect.appendChild(p),this.interpretationLoaders.set(u,f)},s=t===this.entries.find(u=>u.src===this.currentSrc),r=s?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(id,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&tn.interpretationEvents(a.json,tn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(g=>this.agentName(g)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>tn.interpretationOf(u,a.url,g=>Na.recording(g)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${nd}${u}`,`${this.variantLabel(d)} (${this.messages.verdicts[d.variant.verdict]})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const h=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:id;this.interpretationSelect.value=h,h===id?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton(),this.showVariants(c)}keptVariants(t){const e={consolidated:0,contested:1,incompatible:2};return(t.sighting.variants??[]).map((i,n)=>({index:n,kept:i})).filter(({kept:i})=>i.variant).sort((i,n)=>e[i.kept.variant.verdict]-e[n.kept.variant.verdict]||i.kept.variant.cost-n.kept.variant.cost)}variantLabel(t){return this.messages.variant.replace("{name}",t.variant.label??t.variant.candidate)}showVariants(t){if(this.variantChips.innerHTML="",this.variantChips.hidden=t.length===0,t.length===0){this.showVariantMoved();return}const e=(i,n,s)=>{const r=document.createElement("button");r.type="button",r.dataset.value=i,s&&(r.dataset.verdict=s,r.title=this.messages.verdicts[s],r.append(Object.assign(document.createElement("span"),{className:"dot"}))),r.append(n),r.addEventListener("click",()=>{this.interpretationSelect.value!==i&&(this.interpretationSelect.value=i,this.chooseInterpretation(i))}),this.variantChips.append(r)};e(id,this.messages.account);for(const{index:i,kept:n}of t)e(`${nd}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){const t=this.interpretationSelect.value;for(const s of this.variantChips.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.value===t));this.variantMoved.innerHTML="";const e=t.startsWith(nd)?Number(t.slice(nd.length)):-1,i=this.sceneElement.ufoElement.sighting.variants?.[e]?.variant;if(this.variantMoved.hidden=!i||i.moved.length+(i.readings?.length??0)===0,!i)return;const n=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});for(const s of i.moved){const[r,a]=s.field==="time"?["0 min",`${s.variant>0?"+":""}${n.format(s.variant)} min`]:s.field==="duration"?[`${n.format(s.stated)} s`,`${n.format(s.variant)} s`]:[`${n.format(s.stated)}°`,`${n.format(s.variant)}°`],c=document.createElement("span");c.append(`${this.messages.variantFields[s.field]}${this.colon}`,Object.assign(document.createElement("s"),{textContent:r})," → ",Object.assign(document.createElement("b"),{textContent:a})),this.variantMoved.append(c)}for(const s of i.readings??[]){const r=this.messages.variantReadings[s.reading];r&&this.variantMoved.append(Object.assign(document.createElement("span"),{className:"reading",textContent:r}))}}setComparing(t){this.sceneElement.compareAccount=t,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const t=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(t));const e=t?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=e,this.compareButton.setAttribute("aria-label",e)}static DATE_LOCALES={en:"en-US",fr:"fr-FR",es:"es-ES",it:"it-IT"};get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,s)}):void 0;e===this.interpretationToken&&(this.sceneElement.interpretation=n,this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved())}agentName(t){if("people"in t){const[e,...i]=t.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,e].join(" ")}return"org"in t?t.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(t)??""}showConfrontation(t){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const e=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of t){const s=document.createElement("li");s.append(`${this.said.read(n.title)??n.sourceId}${this.colon}`);const r=[];n.separationDeg!==void 0&&r.push([this.messages.confrontationDirection.replace("{deg}",e.format(n.separationDeg)),n.disagreements.includes("direction")]),n.widthRatio!==void 0&&r.push([this.messages.confrontationWidth.replace("{ratio}",i.format(n.widthRatio)),n.disagreements.includes("width")]),n.heightRatio!==void 0&&r.push([this.messages.confrontationHeight.replace("{ratio}",i.format(n.heightRatio)),n.disagreements.includes("height")]),r.forEach(([a,c],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=a,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=mn.clock(this.getAttribute(oy));return(e?mn.elapsedSince(this.plain(t).time,e):void 0)??mn.delta(this.getAttribute(Ap))}selectObserver(t){const e=this.entries.find(n=>n.src===t);if(!e)return;this.currentSrc=t,this.observerSelect.value=t,this.sceneElement.documentUrl=e.src?new URL(e.src,location.href).href:void 0;const i=!this.sceneElement.ufoElement.playRequested;if(e.sighting.image?this.sceneElement.showPoster(e.sighting.image,e.src?new URL(e.src,location.href).href:void 0,i):this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,i),this.sceneElement.holdForNewScene(),this.sceneElement.sightingData=e.sighting,this.startPending){this.startPending=!1;const n=this.startSeconds(e);n!==void 0&&(this.sceneElement.ufoElement.currentTime=Math.max(0,n)*1e3)}this.offerInterpretations(e),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(FO,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new MS(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(n=>n.src===this.currentSrc),e=t?this.observerDisplayName(this.plain(t).observer):void 0,i=e!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=e??"",this.editLink.hidden=!this.currentSrc,this.editLink.href=this.editorUrl(),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation)}caseTitleOf(t){const e=this.caseSource;if(!e)return;const i=e.json.events?.find(n=>n.url!==void 0&&!n.interpretationOf&&new URL(n.url,e.url).href===new URL(t.src,location.href).href);return i?this.said.read(i.title):void 0}observerDisplayName(t){if(!t)return;const e=[...t.firstNames??[],t.lastName].filter(Boolean).join(" ");return this.said.read(t.title)||e||t.id}plainRecordings=new WeakMap;plain(t){return this.stripped(t).recording}stripped(t){let e=this.plainRecordings.get(t.sighting);return e||(e=Fn.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={measured:-1,stated:0,derived:1,assumed:2},s=i.paths().filter(c=>e.some(l=>c===l||c.startsWith(`${l}.`))).map(c=>i.at(c)),r=s.reduce((c,l)=>n[l.basis]>n[c]?l.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.[0],i=ja(t.time??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(nl.DATE_LOCALES[this.language],{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages.hideLabels:this.messages.showLabels,this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg}),...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages.summaryGroup:r.group==="observer"?this.messages.observerGroup:r.group in this.messages.summaryGroups?this.messages.summaryGroups[r.group]:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(a!==void 0&&!s){const l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=a,l.append(h),s={group:r.group,element:l},n.push(l)}const c=this.paramItem(r);s?s.element.append(c):n.push(c)}this.paramSummary.replaceChildren(...n),this.syncDescription(e)}openDescription;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),hy.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages.case,e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages.date,s,this.basisOf(t,nl.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,nl.PLACE_PATHS))}const i=this.said.read(this.plain(t).description);i&&!this.labelsShown&&this.appendInfoRow(this.infoObservationList,this.messages.description,i);for(const s of this.plain(t).sources??[])this.appendInfoSource(this.infoObservationList,this.messages.source,s);const n=this.plain(t).tags;!this.labelsShown&&n&&n.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,n.map(s=>this.tags.name(s)).join(", "))}this.infoAppLink.href=Md,this.infoAppLink.textContent="UFO@home v0.141.0",dn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=i.title??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place.0"];appendInfoRow(t,e,i,n){const s=document.createElement("dt");s.textContent=e;const r=document.createElement("dd");if(r.textContent=i,n){const a=document.createElement("span");a.className=`basis basis-${n.basis}`,a.textContent=this.messages.basis[n.basis],n.rationales.length>0&&(a.title=n.rationales.join(`
|
|
9563
|
-
`)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const cy="rr0-sighting",
|
|
9561
|
+
`;class il extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(il.TAG)||customElements.define(il.TAG,il)}subject;messages=sg;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;freeze;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=FO;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.freeze=t("freeze"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.freeze.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(t){const e=++this.languageToken,i=t==="en"?sg:await XS(t);if(e===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(t){this.noteElement.textContent=t??"",this.noteElement.hidden=t===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.freeze.checked;this.linkField.value=e?vr.frozenLink(t.link(),"0.142.0"):t.link(),this.fitLink();const n=`<script type="module" src="${e?vr.frozen(t.module,"0.142.0"):vr.current(t.module,import.meta.url,Uh.home())}"><\/script>
|
|
9562
|
+
${t.element()}`;this.embedMarkup.value=n,this.codeEditor&&(this.codeEditor.text=n)}applyMessages(){const t=this.messages,e=(i,n)=>{this.shadow.getElementById(i).textContent=n};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("freeze-label",t.freeze.replace("{version}","0.142.0")),this.freeze.parentElement.title=t.freezeHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=we(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-C53SBK2N.js");return{ShareCodeEditor:t}},[],import.meta.url).then(({ShareCodeEditor:t})=>{this.codeEditor=new t(this.shadow.getElementById("embed-code"),this.embedMarkup.value,e=>{this.embedMarkup.value=e},this.messages.embed),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(t,e){try{await navigator.clipboard.writeText(t),this.copyButton.textContent=this.messages.copied,window.setTimeout(()=>this.copyButton.textContent=this.messages.copy,1500)}catch{e.select()}}}class mn{static PLAIN=/^\d+(?:[.,]\d+)?$/;static COLONS=/^(?:(\d+):)?(\d{1,2}):(\d{1,2}(?:[.,]\d+)?)$/;static UNITS=/^(?:(\d+(?:[.,]\d+)?)h)?(?:(\d+(?:[.,]\d+)?)m)?(?:(\d+(?:[.,]\d+)?)s)?$/i;static CLOCK=/^(?:(\d{4})-(\d{2})-(\d{2})[T ])?T?(\d{1,2}):(\d{2})(?::(\d{2}(?:[.,]\d+)?))?$/;static num(t){return t===void 0?0:Number(t.replace(",","."))}static delta(t){const e=(t??"").trim();if(e==="")return;if(mn.PLAIN.test(e))return mn.num(e);const i=mn.COLONS.exec(e);if(i){const[,s,r,a]=i;return Number(r)>=60||mn.num(a)>=60?void 0:mn.num(s)*3600+Number(r)*60+mn.num(a)}const n=mn.UNITS.exec(e);return n&&(n[1]!==void 0||n[2]!==void 0||n[3]!==void 0)?mn.num(n[1])*3600+mn.num(n[2])*60+mn.num(n[3]):/^P/i.test(e)?Xc.seconds(e.toUpperCase()):void 0}static isClock(t){return mn.clock(t)!==void 0}static clock(t){const e=mn.CLOCK.exec((t??"").trim());if(!e)return;const[,i,n,s,r,a,c]=e,l={hour:Number(r),minute:Number(a),second:mn.num(c)};if(!(l.hour>=24||l.minute>=60||l.second>=60)){if(i!==void 0){const h={year:Number(i),month:Number(n),day:Number(s)};if(h.month<1||h.month>12||h.day<1||h.day>31)return;l.date=h}return l}}static elapsedSince(t,e){if(!t||t.hour===void 0||t.minute===void 0)return;const i=t.hour*3600+t.minute*60+(t.second??0),n=e.hour*3600+e.minute*60+e.second;if(e.date){if(t.year===void 0||t.month===void 0||t.day===void 0)return;const r=Date.UTC(e.date.year,e.date.month-1,e.date.day)/1e3+n,a=Date.UTC(t.year,t.month-1,t.day)/1e3+i;return Math.max(0,r-a)}let s=n-i;return s<=-43200&&(s+=86400),Math.max(0,s)}}Ob();il.register();const Md=Uh.home(),td="compare-account",Ap="start-time",oy="start-clock",Yl="observer",ed="case",id="account",nd="variant-",_p=`${Md}/edit/`;class nl extends HTMLElement{static get observedAttributes(){return["src","show-labels",Ap,oy,Yl,Ar,_r,td]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;observerText;observerSelect;infoButton;infoPanel;infoAppLink;editLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;shareButton;shareDialog;shareStartOn;shareStart;shareScopeRow;shareScopeLabel;shareScope;shareOpensRow;shareOpensLabel;shareOpens;shareStartLabel;shareOptions;labelsToggle;paramSummary;summaryBuilder=new wh(th,new xf,new Es(["en"]),new rd({}),{messages:th,locale:"en"});summarySignature="";assessmentEntries=[];assessmentToken=0;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];caseSource;interpretationChoice;interpretationLabel;interpretationSelect;confrontationElement;confrontationHeading;confrontationList;compareButton;variantChips;variantMoved;interpretationLoaders=new Map;interpretationToken=0;offeredFor;currentSrc;infoOpen=!1;creditsOpen=!1;labelsShown=!1;language="en";messages=th;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${Hb}</style>${Bb}`,this.shadow.appendChild(t.content.cloneNode(!0)),customElements.upgrade(this.shadow),this.sceneElement=document.createElement(wf),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.toolbarElement=this.shadow.getElementById("toolbar"),this.accountElement=this.shadow.getElementById("account"),this.accountPrefix=this.shadow.getElementById("account-prefix"),this.observerText=this.shadow.getElementById("observer-text"),this.observerSelect=this.shadow.getElementById("observer"),this.infoButton=this.shadow.getElementById("info-button"),this.infoPanel=this.shadow.getElementById("info-panel"),this.infoAppLink=this.shadow.getElementById("info-app-link"),this.editLink=this.shadow.getElementById("edit-link"),this.infoObservationHeading=this.shadow.getElementById("info-observation-heading"),this.infoObservationList=this.shadow.getElementById("info-observation-list"),this.infoCreditsToggle=this.shadow.getElementById("info-credits-toggle"),this.infoCreditsList=this.shadow.getElementById("info-credits-list"),this.infoCloseButton=this.shadow.getElementById("info-close"),this.labelsToggle=this.shadow.getElementById("info-labels-toggle"),this.paramSummary=this.shadow.getElementById("param-summary"),this.labelsToggle.addEventListener("click",()=>{this.showLabels=!this.showLabels}),this.shareButton=document.createElement("button"),this.shareButton.type="button",this.shareButton.id="share-button",this.shareButton.setAttribute("aria-haspopup","dialog"),this.shareButton.innerHTML=qt.SHARE,this.sceneElement.ufoElement.addControl(this.shareButton),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.shareStartOn=this.shadow.getElementById("share-start-on"),this.shareStart=this.shadow.getElementById("share-start"),this.shareStartLabel=this.shadow.getElementById("share-start-label"),this.shareScopeRow=this.shadow.getElementById("share-scope-row"),this.shareScopeLabel=this.shadow.getElementById("share-scope-label"),this.shareScope=this.shadow.getElementById("share-scope"),this.shareOpensRow=this.shadow.getElementById("share-opens-row"),this.shareOpensLabel=this.shadow.getElementById("share-opens-label"),this.shareOpens=this.shadow.getElementById("share-opens");const e=i=>({input:this.shadow.getElementById(`share-opt-${i}`),label:this.shadow.getElementById(`share-opt-${i}-label`)});this.shareOptions={labels:e("labels"),map:e("map"),milestones:e("milestones"),compare:e("compare")},this.interpretationChoice=this.shadow.getElementById("interpretation-choice"),this.interpretationLabel=this.shadow.getElementById("interpretation-label"),this.interpretationSelect=this.shadow.getElementById("interpretation"),this.confrontationElement=this.shadow.getElementById("confrontation"),this.confrontationHeading=this.shadow.getElementById("confrontation-heading"),this.confrontationList=this.shadow.getElementById("confrontation-list"),this.compareButton=this.shadow.getElementById("compare-account"),this.variantChips=this.shadow.getElementById("variant-chips"),this.variantMoved=this.shadow.getElementById("variant-moved"),this.compareButton.addEventListener("click",()=>this.setComparing(!this.sceneElement.compareAccount)),this.observerSelect.addEventListener("change",()=>this.selectObserver(this.observerSelect.value)),this.interpretationSelect.addEventListener("change",()=>void this.chooseInterpretation(this.interpretationSelect.value)),this.sceneElement.addEventListener(Cb,i=>this.showConfrontation(i.detail)),this.sceneElement.ufoElement.addEventListener("timeupdate",()=>this.refreshParamSummary()),this.supportsPopover?(this.infoPanel.setAttribute("popover","auto"),this.infoPanel.removeAttribute("hidden"),this.infoButton.setAttribute("popovertarget","info-panel"),this.infoPanel.addEventListener("beforetoggle",i=>{i.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",i=>this.syncInfoOpen(i.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.shareButton.addEventListener("click",()=>this.openShare());for(const i of[this.shareStartOn,this.shareStart,...Object.values(this.shareOptions).map(n=>n.input)])i.addEventListener("input",()=>this.refreshShareLinks());for(const i of[this.shareScope,this.shareOpens])i.addEventListener("change",()=>this.refreshShareLinks());this.isConnected&&this.loadLocaleMessages()}get scene(){return this.sceneElement}async loadLocaleMessages(){const t=++this.localeToken,e=ka.preferencesFor(this);this.preferences=e;const i=dg(e,fg),[n,s,r]=i==="en"?[th,{},void 0]:await Promise.all([VS(i),$S(i),Iy(i)]);if(t!==this.localeToken)return;const a=i!==this.language;this.language=i,this.messages=n,this.tags=new rd(s),this.said=new Es(e),this.summaryBuilder=new wh(this.messages,new xf(r),this.said,this.tags,{messages:this.messages,locale:i}),this.accountPrefix.textContent=this.messages.accountBy,this.interpretationLabel.textContent=this.messages.interpretation,this.confrontationHeading.textContent=this.messages.confrontation;const c=this.entries.find(l=>l.src===this.currentSrc);c&&this.offerInterpretations(c),this.updateCompareButton(),this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.syncLabelsToggle(),this.refreshParamSummary(),a&&this.currentSrc&&this.runAssessments(),this.shareButton.title=this.messages.share,this.shareButton.setAttribute("aria-label",this.messages.share),this.shareStartLabel.textContent=this.messages.shareStartAt,this.shareScopeLabel.textContent=this.messages.shareScope,this.shareOpensLabel.textContent=this.messages.shareOpensOn,this.shareOptions.labels.label.textContent=this.messages.shareOptionLabels,this.shareOptions.map.label.textContent=this.messages.shareOptionMap,this.shareOptions.milestones.label.textContent=this.messages.shareOptionMilestones,this.shareOptions.compare.label.textContent=this.messages.shareOptionCompare,this.shareStart.setAttribute("aria-label",this.messages.shareStartAt),this.shareDialog.useLanguage(i),this.infoOpen&&this.populateInfoPanel(),this.updateAccountLine()}preferences=[];localeToken=0;said=new Es(["en"]);tags=new rd({});connectedCallback(){ka.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(t===Ar||t===_r)&&this.forwardPlayerAttributes(),t===Yl&&this.entries.length>1){const n=this.entryAsked(this.entries);n&&n.src!==this.currentSrc&&this.selectObserver(n.src)}t===td&&this.setComparing(this.hasAttribute(td))}forwardPlayerAttributes(){for(const t of[Ar,_r]){const e=this.getAttribute(t);e===null?this.sceneElement.removeAttribute(t):this.sceneElement.setAttribute(t,e)}}async loadFromSrc(t){this.startPending=!0;const e=Na.recording(t);this.sceneElement.holdForNewScene(e);const i=await e;if(Array.isArray(i))throw new Error(`${t} is a bare list of recordings, which is no longer read: list them as the sighting events of a case.json`);if(tn.isCase(i)){tn.check(i);const n=tn.sightingUrls(i,new URL(t,location.href).href);if(n.length===0)throw new Error(`${t} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(n,{json:i,url:new URL(t,location.href).href})}else this.setEntries([{src:t,sighting:i}],void 0)}get sightingData(){return this.entries.find(t=>t.src===this.currentSrc)?.sighting}set sightingData(t){this.startPending=!0,this.currentSrc="",this.setEntries([{src:"",sighting:t}],void 0)}seekTo(t,e){const i=this.caseSource,n=e===void 0?void 0:this.entries.find(s=>{const r=this.plain(s).id;return(i?tn.accountIds(i.json,i.url,s.src,r):[r]).includes(e)});n&&n.src!==this.currentSrc&&this.selectObserver(n.src),this.sceneElement.ufoElement.currentTime=Math.max(0,t)*1e3}get observerUrls(){return this.entries.map(t=>t.src)}set observerUrls(t){this.loadObserverUrls(t)}async loadObserverUrls(t,e){const i=await Promise.all(t.map(async n=>({src:n,sighting:await Na.recording(n)})));this.setEntries(i,e)}reportCaseProblems(t,e){const{duplicateIds:i,unresolved:n}=tn.problems(t,e.map(s=>this.plain(s).id).filter(s=>s!==void 0));for(const s of i)console.warn(`The case ${t.id??""} gives the id "${s}" to more than one event: a reference to it is ambiguous.`);for(const{reading:s,reference:r}of n)console.warn(`The reading ${s} of the case ${t.id??""} is "interpretationOf" "${r}", which no event of the case has as its id, nor any recording it lists.`)}setEntries(t,e){this.entries=t,this.caseSource=e,e&&this.reportCaseProblems(e.json,t),this.toolbarElement.hidden=t.length===0;const i=t.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";const n=t.map((r,a)=>this.observerDisplayName(this.plain(r).observer)??this.messages.unnamedObserver.replace("{n}",String(a+1)));for(const[r,a]of t.entries()){const c=document.createElement("option");c.value=a.src;const l=n.filter(h=>h===n[r]).length>1;c.textContent=(l?this.caseTitleOf(a):void 0)??n[r],this.observerSelect.appendChild(c)}const s=t.find(r=>r.src===this.currentSrc)??this.entryAsked(t)??t[0];s?this.selectObserver(s.src):this.updateAccountLine()}entryAsked(t){const e=this.getAttribute(Yl)?.trim();if(!e)return;const i=t.find(s=>this.plain(s).observer?.id===e);if(i)return i;const n=t.find(s=>s.src.split("/").pop()===e.split("/").pop());return n||(/^\d+$/.test(e)?t[Number(e)-1]:void 0)}observerKeyOf(t){return this.plain(t).observer?.id??String(this.entries.indexOf(t)+1)}sharedEntry(){const t=this.shareScope.value;if(!(!this.caseSource||t===ed))return this.entries.find(e=>e.src===t)}get sharesCase(){return this.caseSource!==void 0&&!this.shareScopeRow.hidden&&this.shareScope.value===ed}editorUrl(){if(!this.currentSrc)return _p;const t=new URL(this.currentSrc,location.href),e=this.caseSource;return e?`${_p}?file=${encodeURIComponent(e.url)}&track=${encodeURIComponent(this.shownTrackUrl()??t.href)}`:`${_p}?file=${encodeURIComponent(t.href)}`}get editorHref(){return this.editorUrl()}shownTrackUrl(){const t=this.caseSource,e=this.entries.find(s=>s.src===this.currentSrc),i=/^case-(\d+)$/.exec(this.interpretationSelect.value);if(!t||!e||!i)return;const n=tn.interpretationEvents(t.json,tn.accountIds(t.json,t.url,e.src,this.plain(e).id))[Number(i[1])];return n?.url?new URL(n.url,t.url).href:void 0}shareSubject={module:"rr0-sighting",link:()=>this.playUrl(),element:()=>this.replayElement()};replayElement(){const t=this.sharedAddress(),i=[...t.observer?[[Yl,t.observer]]:[],...this.replayAttributes()].map(([n,s])=>s===""?` ${n}`:` ${n}="${s}"`).join("");return`<rr0-sighting src="${t.src}"${i}></rr0-sighting>`}playUrl(){const t=this.sharedAddress(),e=[...t.observer?[`${Yl}=${encodeURIComponent(t.observer)}`]:[],...this.replayQuery()].join("&");return t.src?`${Md}/play/?file=${encodeURIComponent(t.src)}${e&&"&"+e}`:`${Md}/play/${e&&"?"+e}`}sharedAddress(){const t=e=>e?new URL(e,location.href).href:"";if(this.sharesCase){const e=this.entries.find(i=>i.src===this.shareOpens.value)??this.entries.find(i=>i.src===this.currentSrc);return{src:this.caseSource.url,observer:e?this.observerKeyOf(e):void 0}}return{src:t(this.sharedEntry()?.src??this.currentSrc??"")}}replayAttributes(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push([Ap,String(this.shareStartSeconds)]),t.labels.input.checked&&e.push(["show-labels",""]),t.map.input.checked&&e.push([Ar,""]),t.milestones.input.checked||e.push([_r,""]),t.compare.input.checked&&e.push([td,""]),e}replayQuery(){const t=this.shareOptions,e=[];return this.shareStartSeconds!==void 0&&e.push(`d=${this.shareStartSeconds}`),t.labels.input.checked||e.push("labels=0"),t.map.input.checked&&e.push("map=1"),t.milestones.input.checked||e.push("moments=0"),t.compare.input.checked&&e.push("compare=1"),e}get shareStartSeconds(){const t=Math.floor(Number(this.shareStart.value));return this.shareStartOn.checked&&Number.isFinite(t)&&t>=0?t:void 0}refreshShareLinks(){this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.refresh()}openShare(){const t=this.sceneElement.ufoElement;this.shareStart.max=String(Math.floor(t.seekableDuration/1e3)),this.shareStart.value=String(Math.floor(t.currentTime/1e3)),this.shareStartOn.checked=!1,this.shareOptions.labels.input.checked=this.labelsShown,this.shareOptions.map.input.checked=t.observerMapOpen,this.shareOptions.milestones.input.checked=t.milestonesVisible,this.shareOptions.compare.input.checked=this.sceneElement.compareAccount,this.offerShareScope(),this.shareOpensRow.hidden=!this.sharesCase,this.shareDialog.open()}offerShareScope(){const t=this.caseSource!==void 0&&this.entries.length>1;if(this.shareScopeRow.hidden=!t,this.shareScope.innerHTML="",this.shareOpens.innerHTML="",!t)return;const e=(i,n,s)=>{const r=document.createElement("option");r.value=n,r.textContent=s,i.appendChild(r)};e(this.shareScope,ed,this.messages.shareScopeCase);for(const i of this.entries){const n=this.observerDisplayName(this.plain(i).observer)??this.messages.unnamedObserver.replace("{n}",String(this.entries.indexOf(i)+1));e(this.shareScope,i.src,n),e(this.shareOpens,i.src,n)}this.shareScope.value=ed,this.shareOpens.value=this.currentSrc??this.entries[0].src}offerInterpretations(t){const e=this.offeredFor===t.sighting,i=this.interpretationSelect.value;this.offeredFor=t.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(u,d,f)=>{const p=document.createElement("option");p.value=u,p.textContent=d,this.interpretationSelect.appendChild(p),this.interpretationLoaders.set(u,f)},s=t===this.entries.find(u=>u.src===this.currentSrc),r=s?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(id,this.messages.account,()=>Promise.resolve(r));const a=this.caseSource;a&&tn.interpretationEvents(a.json,tn.accountIds(a.json,a.url,t.src,this.plain(t).id)).forEach((u,d)=>{const f=this.said.read(u.title)??`#${d+1}`,p=(u.by??[]).map(g=>this.agentName(g)).filter(Boolean).join(", ");n(`case-${d}`,p?this.messages.interpretationBy.replace("{title}",f).replace("{by}",p):f,()=>tn.interpretationOf(u,a.url,g=>Na.recording(g)))});const c=s?this.keptVariants(t):[];for(const{index:u,kept:d}of c)n(`${nd}${u}`,`${this.variantLabel(d)} (${this.messages.verdicts[d.variant.verdict]})`,()=>Promise.resolve(d.bodies.length>0?d:void 0));const h=e&&[...this.interpretationSelect.options].some(u=>u.value===i)?i:id;this.interpretationSelect.value=h,h===id?this.sceneElement.interpretation!==r&&(this.sceneElement.interpretation=r):this.sceneElement.interpretation||this.chooseInterpretation(h),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton(),this.showVariants(c)}keptVariants(t){const e={consolidated:0,contested:1,incompatible:2};return(t.sighting.variants??[]).map((i,n)=>({index:n,kept:i})).filter(({kept:i})=>i.variant).sort((i,n)=>e[i.kept.variant.verdict]-e[n.kept.variant.verdict]||i.kept.variant.cost-n.kept.variant.cost)}variantLabel(t){return this.messages.variant.replace("{name}",t.variant.label??t.variant.candidate)}showVariants(t){if(this.variantChips.innerHTML="",this.variantChips.hidden=t.length===0,t.length===0){this.showVariantMoved();return}const e=(i,n,s)=>{const r=document.createElement("button");r.type="button",r.dataset.value=i,s&&(r.dataset.verdict=s,r.title=this.messages.verdicts[s],r.append(Object.assign(document.createElement("span"),{className:"dot"}))),r.append(n),r.addEventListener("click",()=>{this.interpretationSelect.value!==i&&(this.interpretationSelect.value=i,this.chooseInterpretation(i))}),this.variantChips.append(r)};e(id,this.messages.account);for(const{index:i,kept:n}of t)e(`${nd}${i}`,n.variant.label??n.variant.candidate,n.variant.verdict);this.showVariantMoved()}showVariantMoved(){const t=this.interpretationSelect.value;for(const s of this.variantChips.querySelectorAll("button"))s.setAttribute("aria-pressed",String(s.dataset.value===t));this.variantMoved.innerHTML="";const e=t.startsWith(nd)?Number(t.slice(nd.length)):-1,i=this.sceneElement.ufoElement.sighting.variants?.[e]?.variant;if(this.variantMoved.hidden=!i||i.moved.length+(i.readings?.length??0)===0,!i)return;const n=new Intl.NumberFormat(this.language,{maximumFractionDigits:1});for(const s of i.moved){const[r,a]=s.field==="time"?["0 min",`${s.variant>0?"+":""}${n.format(s.variant)} min`]:s.field==="duration"?[`${n.format(s.stated)} s`,`${n.format(s.variant)} s`]:[`${n.format(s.stated)}°`,`${n.format(s.variant)}°`],c=document.createElement("span");c.append(`${this.messages.variantFields[s.field]}${this.colon}`,Object.assign(document.createElement("s"),{textContent:r})," → ",Object.assign(document.createElement("b"),{textContent:a})),this.variantMoved.append(c)}for(const s of i.readings??[]){const r=this.messages.variantReadings[s.reading];r&&this.variantMoved.append(Object.assign(document.createElement("span"),{className:"reading",textContent:r}))}}setComparing(t){this.sceneElement.compareAccount=t,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const t=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(t));const e=t?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=e,this.compareButton.setAttribute("aria-label",e)}static DATE_LOCALES={en:"en-US",fr:"fr-FR",es:"es-ES",it:"it-IT"};get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(t){const e=++this.interpretationToken,i=this.interpretationLoaders.get(t),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${t}":`,s)}):void 0;e===this.interpretationToken&&(this.sceneElement.interpretation=n,this.editLink.href=this.editorUrl(),this.dispatchEvent(new CustomEvent("interpretationchange",{detail:{track:this.shownTrackUrl()}})),this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation),this.showVariantMoved())}agentName(t){if("people"in t){const[e,...i]=t.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,e].join(" ")}return"org"in t?t.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(t)??""}showConfrontation(t){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const e=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of t){const s=document.createElement("li");s.append(`${this.said.read(n.title)??n.sourceId}${this.colon}`);const r=[];n.separationDeg!==void 0&&r.push([this.messages.confrontationDirection.replace("{deg}",e.format(n.separationDeg)),n.disagreements.includes("direction")]),n.widthRatio!==void 0&&r.push([this.messages.confrontationWidth.replace("{ratio}",i.format(n.widthRatio)),n.disagreements.includes("width")]),n.heightRatio!==void 0&&r.push([this.messages.confrontationHeight.replace("{ratio}",i.format(n.heightRatio)),n.disagreements.includes("height")]),r.forEach(([a,c],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=a,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}startPending=!1;startSeconds(t){const e=mn.clock(this.getAttribute(oy));return(e?mn.elapsedSince(this.plain(t).time,e):void 0)??mn.delta(this.getAttribute(Ap))}selectObserver(t){const e=this.entries.find(n=>n.src===t);if(!e)return;this.currentSrc=t,this.observerSelect.value=t,this.sceneElement.documentUrl=e.src?new URL(e.src,location.href).href:void 0;const i=!this.sceneElement.ufoElement.playRequested;if(e.sighting.image?this.sceneElement.showPoster(e.sighting.image,e.src?new URL(e.src,location.href).href:void 0,i):this.sceneElement.showPoster(this.caseSource?.json.image,this.caseSource?.url,i),this.sceneElement.holdForNewScene(),this.sceneElement.sightingData=e.sighting,this.startPending){this.startPending=!1;const n=this.startSeconds(e);n!==void 0&&(this.sceneElement.ufoElement.currentTime=Math.max(0,n)*1e3)}this.offerInterpretations(e),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(zO,{detail:{src:t}}))}async runAssessments(){const t=++this.assessmentToken,e=await new MS(this.messages).read(this.sceneElement.ufoElement.sighting);t===this.assessmentToken&&(this.assessmentEntries=e.entries,this.refreshParamSummary())}updateAccountLine(){const t=this.entries.find(n=>n.src===this.currentSrc),e=t?this.observerDisplayName(this.plain(t).observer):void 0,i=e!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=e??"",this.editLink.hidden=!this.currentSrc,this.editLink.href=this.editorUrl(),this.editLink.title=this.messages.editThisObservation,this.editLink.setAttribute("aria-label",this.messages.editThisObservation)}caseTitleOf(t){const e=this.caseSource;if(!e)return;const i=e.json.events?.find(n=>n.url!==void 0&&!n.interpretationOf&&new URL(n.url,e.url).href===new URL(t.src,location.href).href);return i?this.said.read(i.title):void 0}observerDisplayName(t){if(!t)return;const e=[...t.firstNames??[],t.lastName].filter(Boolean).join(" ");return this.said.read(t.title)||e||t.id}plainRecordings=new WeakMap;plain(t){return this.stripped(t).recording}stripped(t){let e=this.plainRecordings.get(t.sighting);return e||(e=Fn.strip(t.sighting),this.plainRecordings.set(t.sighting,e)),e}basisOf(t,e){const i=this.stripped(t).provenance,n={measured:-1,stated:0,derived:1,assumed:2},s=i.paths().filter(c=>e.some(l=>c===l||c.startsWith(`${l}.`))).map(c=>i.at(c)),r=s.reduce((c,l)=>n[l.basis]>n[c]?l.basis:c,"stated"),a=s.filter(c=>c.basis===r&&c.rationale).map(c=>c.rationale);return{basis:r,rationales:a}}formatDate(t){const e=t.place?.[0],i=ja(t.time??{},e?.lng??0,t.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(t,e?.lng??0)*36e5;if(Number.isFinite(n))return new Intl.DateTimeFormat(nl.DATE_LOCALES[this.language],{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(t,e){return t.utcOffsetHours??Math.round(e/15)}formatLocation(t){const e=t.place?.[0];if(e)return`${e.lat.toFixed(4)}, ${e.lng.toFixed(4)}`}toggleInfoPanel(){const t=!this.infoOpen;if(this.supportsPopover){const e=this.infoPanel.matches(":popover-open");t&&!e?this.infoPanel.showPopover():!t&&e&&this.infoPanel.hidePopover();return}t&&this.bringInfoButtonIntoView(),this.syncInfoOpen(t),this.infoPanel.hidden=!t,t?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const t=this.infoButton.getBoundingClientRect(),e=window.innerHeight||document.documentElement.clientHeight;t.top>=0&&t.bottom<=e||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(t){t!==this.infoOpen&&(this.infoOpen=t,this.infoButton.setAttribute("aria-expanded",String(t)),t?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=t=>{const e=t.composedPath();!e.includes(this.infoPanel)&&!e.includes(this.infoButton)&&this.toggleInfoPanel()};toggleCredits(){this.creditsOpen=!this.creditsOpen,this.infoCreditsList.hidden=!this.creditsOpen,this.infoCreditsToggle.setAttribute("aria-expanded",String(this.creditsOpen)),this.creditsOpen&&this.revealInPanel(this.infoCreditsList)}revealInPanel(t){t.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(t){this.toggleAttribute("show-labels",t)}applyLabels(t){this.labelsShown=t,this.syncLabelsToggle(),this.refreshParamSummary(),this.populateInfoPanel()}syncLabelsToggle(){this.labelsToggle.textContent=this.labelsShown?this.messages.hideLabels:this.messages.showLabels,this.labelsToggle.setAttribute("aria-pressed",String(this.labelsShown))}refreshParamSummary(){if(this.paramSummary.hidden=!this.labelsShown,!this.labelsShown){this.paramSummary.replaceChildren(),this.summarySignature="";return}const t=this.sceneElement.ufoElement.sighting,e=[...this.summaryBuilder.entriesFor(t,this.sceneElement.ufoElement.currentTime,{roadGradeDeg:this.sceneElement.roadGradeDeg}),...this.assessmentEntries],i=e.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.full??""}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of e){s&&s.group!==r.group&&(s=void 0);const a=r.group==="summary"?this.messages.summaryGroup:r.group==="observer"?this.messages.observerGroup:r.group in this.messages.summaryGroups?this.messages.summaryGroups[r.group]:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(a!==void 0&&!s){const l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=a,l.append(h),s={group:r.group,element:l},n.push(l)}const c=this.paramItem(r);s?s.element.append(c):n.push(c)}this.paramSummary.replaceChildren(...n),this.syncDescription(e)}openDescription;syncDescription(t){this.openDescription!==void 0&&!t.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),hy.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription(t)})}paramItem(t){const e=document.createElement("span");if(e.className=t.fromSource?"param-label from-source":"param-label",t.full!==void 0){e.classList.add("describable"),e.tabIndex=0,e.setAttribute("role","button");const s=()=>{this.openDescription=t.full,this.syncDescription([t])};e.addEventListener("click",s),e.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),s())})}const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${t.label} `,e.append(i),t.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=t.color,e.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=t.unit===""?t.value:`${t.value} ${t.unit}`,e.append(n),e}populateInfoPanel(){const t=this.entries.find(e=>e.src===this.currentSrc);if(this.infoObservationList.innerHTML="",t){const e=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(e&&this.appendInfoRow(this.infoObservationList,this.messages.case,e),!this.labelsShown){const s=this.formatDate(this.plain(t));s&&this.appendInfoRow(this.infoObservationList,this.messages.date,s,this.basisOf(t,nl.DATE_PATHS));const r=this.formatLocation(this.plain(t));r&&this.appendInfoRow(this.infoObservationList,this.messages.location,r,this.basisOf(t,nl.PLACE_PATHS))}const i=this.said.read(this.plain(t).description);i&&!this.labelsShown&&this.appendInfoRow(this.infoObservationList,this.messages.description,i);for(const s of this.plain(t).sources??[])this.appendInfoSource(this.infoObservationList,this.messages.source,s);const n=this.plain(t).tags;!this.labelsShown&&n&&n.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,n.map(s=>this.tags.name(s)).join(", "))}this.infoAppLink.href=Md,this.infoAppLink.textContent="UFO@home v0.142.0",dn.fill(this.infoCreditsList,this.sceneElement)}appendInfoSource(t,e,i){const n=document.createElement("dt");n.textContent=e;const s=document.createElement("dd"),r=i.title??i.url??"";if(i.url&&/^https?:\/\//i.test(i.url)){const c=document.createElement("a");c.href=i.url,c.target="_blank",c.rel="noopener noreferrer",c.textContent=r,s.appendChild(c)}else s.append(r);const a=[i.authors?.join(", "),i.publication?.publisher,i.publication?.time,i.index].filter(Boolean);a.length>0&&s.append(`, ${a.join(", ")}`),t.append(n,s)}static DATE_PATHS=["time","utcOffsetHours","timeZone"];static PLACE_PATHS=["place.0"];appendInfoRow(t,e,i,n){const s=document.createElement("dt");s.textContent=e;const r=document.createElement("dd");if(r.textContent=i,n){const a=document.createElement("span");a.className=`basis basis-${n.basis}`,a.textContent=this.messages.basis[n.basis],n.rationales.length>0&&(a.title=n.rationales.join(`
|
|
9563
|
+
`)),r.append(" ",a)}t.appendChild(s),t.appendChild(r)}}const cy="rr0-sighting",zO="observerchange",ly="rr0-eyeobserver";class BO extends nl{}function HO(){Ob(),il.register(),customElements.get(cy)||customElements.define(cy,nl),customElements.get(ly)||customElements.define(ly,BO)}HO();export{Mn as $,Io as A,ne as B,st as C,Ic as D,Jn as E,le as F,Oe as G,dd as H,e8 as I,ia as J,Cl as K,Cp as L,RA as M,es as N,Bn as O,xm as P,Xt as Q,Ae as R,Mh as S,gn as T,AA as U,Ps as V,ZO as W,en as X,nn as Y,QO as Z,Uo as _,kn as a,vn as a0,ye as a1,xi as a2,Gi as a3,Gn as a4,bi as a5,MO as a6,o1 as a7,GO as a8,WO as a9,px as aA,KO as aB,jn as aC,Is as aD,fx as aE,rM as aF,F3 as aG,jC as aH,Yd as aI,Mm as aJ,Ix as aK,kg as aL,Ug as aM,De as aN,za as aO,Bh as aP,VO as aa,Hh as ab,t8 as ac,JO as ad,Zd as ae,Cx as af,uM as ag,YO as ah,ts as ai,zv as aj,jO as ak,i8 as al,ux as am,Xs as an,jh as ao,n0 as ap,FE as aq,ei as ar,Ho as as,Hp as at,Oi as au,Pr as av,W3 as aw,Ke as ax,$O as ay,qO as az,bt as b,Fu as c,it as d,ch as e,Ia as f,ae as g,ce as h,Rs as i,n8 as j,tf as k,fs as l,hn as m,ea as n,R as o,US as p,Se as q,Er as r,ja as s,lr as t,Mt as u,_e as v,s8 as w,he as x,XO as y,eE as z};
|