@rr0/ufoathome 0.70.0 → 0.70.1
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.
|
@@ -1190,7 +1190,7 @@ input[type=range] {
|
|
|
1190
1190
|
pointer-events: none;
|
|
1191
1191
|
white-space: nowrap;
|
|
1192
1192
|
}
|
|
1193
|
-
`;class ba{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||t.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new ba(t)}static TRAVEL_M=50;get travels(){return this.spanM>ba.TRAVEL_M}get moved(){return this.spanM>ba.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(ii(t,e.east,t,e.west).x),Math.abs(ii(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+t),e)/2;return{north:ys(0,-s,i,n).lat,south:ys(0,s,i,n).lat,east:ys(s,0,i,n).lng,west:ys(-s,0,i,n).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class mn{constructor(e,t){this.rotationPassed=e,this.scale=t}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(e){const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>mn.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new mn(Math.max(1-(e.instrument.stabilization??0),mn.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*t+d),[s,r,o,c,l,h]=mn.HZ;return{eastM:i*mn.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*mn.SWAY_M*(.6*n(o,2.2)+.4*n(l,.8)),upM:i*mn.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*mn.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*mn.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(o,.4)),rollDeg:i*this.rotationPassed*mn.DRIFT_ROLL_DEG*n(s,2.9)}}}class xt{constructor(e,t){this.stretches=e,this.rotationPassed=t}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(e){const t=ba.of(e);if(!t||t.points.length<2)return;const i=[];let n=0;for(let s=1;s<t.points.length;s++){const r=t.points[s-1],o=t.points[s],c=(o.t-r.t)/1e3;if(c<=0)continue;const l=ii(o.lat,o.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=xt.stepHzFor(f);i.push({startMs:r.t,endMs:o.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],o=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=o===void 0||o.stepHz===0}if(i.some(s=>s.stepHz>0))return new xt(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=xt.of(e)?.offsetAt(t)??xt.STILL;return i?n:xt.add(n,mn.of(e)?.offsetAt(t))}static stepHzFor(e){return e<xt.SLOWEST_WALK_M_PER_S||e>xt.FASTEST_WALK_M_PER_S?0:xt.REFERENCE_STEP_HZ*Math.pow(e/xt.REFERENCE_SPEED_M_PER_S,xt.CADENCE_EXPONENT)}offsetAt(e){return xt.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/xt.REFERENCE_SPEED_M_PER_S,n=(o,c,l,h)=>{if(o<0||o>xt.JOLT_LASTS_MS)return;const u=o/1e3,d=Math.exp(-u/xt.JOLT_DECAY_S)*Math.sin(2*Math.PI*xt.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*t.eastUnit,northM:f*t.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,xt.STOP_LURCH_M,xt.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,xt.START_LURCH_M,xt.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(c=>e>=c.startMs&&e<=c.endMs);if(!t||t.stepHz===0)return xt.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=xt.SWAY_M*s*Math.cos(n/2),o=s*this.rotationPassed*t.speedMPerS/xt.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:xt.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:xt.HEAD_ROLL_DEG*o*Math.cos(n/2),pitchDeg:-1.25*o*Math.cos(n),yawDeg:xt.HEAD_YAW_DEG*o*Math.cos(n/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,n=Math.min(i,(e.endMs-e.startMs)/2);if(n<=0)return 1;const s=t-e.startMs,r=e.endMs-t,o=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(o,0)))/2}}class Jv{constructor(e,t){this.timeline=e,this.onFrame=t}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 e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}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(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}this.onFrame(e,t)}}const vg=["nw","n","ne","e","se","s","sw","w"],jv=24,tc=8,Qv=3,e2=8;function ic(a,e,t){const i=a.x-e.x,n=a.y-e.y,s=Math.cos(t),r=Math.sin(t);return{x:e.x+i*s-n*r,y:e.y+i*r+n*s}}function Va(a){return{x:a.x+a.width/2,y:a.y+a.height/2}}const t2={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 cn{static handlePointsFor(e){const{x:t,y:i,width:n,height:s}=e.bounds,r={nw:{x:t,y:i},n:{x:t+n/2,y:i},ne:{x:t+n,y:i},e:{x:t+n,y:i+s/2},se:{x:t+n,y:i+s},s:{x:t+n/2,y:i+s},sw:{x:t,y:i+s},w:{x:t,y:i+s/2},rotate:{x:t+n/2,y:i-jv}},o=Va(e.bounds),c={};for(const l of Object.keys(r))c[l]=ic(r[l],o,e.angle);return c}static hitTestHandle(e,t,i=8,n=[...vg,"rotate"]){const s=cn.handlePointsFor(e);for(const r of n)if(Math.hypot(t.x-s[r].x,t.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(e,t){const n=((cn.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(e,t,i,n){const s=Va(e),r=ic(n,s,-t),{x:o,y:c,width:l,height:h}=e,u=t2[i];let d=o,f=c,p=o+l,v=c+h;return u.left&&(d=Math.min(r.x,p-tc)),u.right&&(p=Math.max(r.x,d+tc)),u.top&&(f=Math.min(r.y,v-tc)),u.bottom&&(v=Math.max(r.y,f+tc)),{x:d,y:f,width:p-d,height:v-f}}static resizeShape(e,t,i){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=e.bounds,r=cn.resizeBounds(e.bounds,e.angle,t,i);if(e.kind==="oval")return{...e,bounds:r};const o=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...e,bounds:r,points:e.points.map(l=>({x:l.x*o,y:l.y*c}))}}static rotateShape(e,t){const i=Va(e.bounds),n=Math.atan2(t.y-i.y,t.x-i.x)+Math.PI/2;return{...e,angle:n}}static groupBoundsFor(e){const t=Math.min(...e.map(r=>r.x)),i=Math.min(...e.map(r=>r.y)),n=Math.max(...e.map(r=>r.x+r.width)),s=Math.max(...e.map(r=>r.y+r.height));return{x:t,y:i,width:n-t,height:s-i}}static vertexPointsFor(e){const t=Va(e.bounds);return e.points.map(i=>ic({x:e.bounds.x+i.x,y:e.bounds.y+i.y},t,e.angle))}static hitTestVertex(e,t,i=e2){const n=cn.vertexPointsFor(e);let s,r=i;return n.forEach((o,c)=>{const l=Math.hypot(t.x-o.x,t.y-o.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(e,t){const i=Va(e.bounds),n=ic(t,i,-e.angle);return{x:n.x-e.bounds.x,y:n.y-e.bounds.y}}static moveVertex(e,t,i){const n=e.points.map((u,d)=>d===t?cn.toLocalPoint(e,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),o=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:e.bounds.x+s,y:e.bounds.y+r,width:o-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...e,bounds:l,points:h}}static insertVertexNear(e,t){const i=cn.toLocalPoint(e,t),{points:n}=e;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=cn.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const o=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...e,points:o}}static distanceToSegment(e,t,i){const n=i.x-t.x,s=i.y-t.y,r=n*n+s*s,o=r===0?0:Math.max(0,Math.min(1,((e.x-t.x)*n+(e.y-t.y)*s)/r)),c=t.x+o*n,l=t.y+o*s;return Math.hypot(e.x-c,e.y-l)}static deleteVertex(e,t){return e.points.length<=Qv?e:{...e,points:e.points.filter((i,n)=>n!==t)}}}const Ru=6,nc=Ru/2,pf=20,mf=24,gf=9,vf=6,Mf=7,xf=6,Gn=4;class No{constructor(e){this.ctx=e}starPoints=0;roll=0;clear(e,t){this.ctx.clearRect(0,0,e,t)}static paintExtent(e){const{x:t,y:i,width:n,height:s}=e.bounds,r=t+n/2,o=i+s/2,c=e.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=e.brightness??0,p=f>0?Math.max(d*(1+gf*f),xf*f)-d:0,v=f>0?d*(1+Mf*f)-d:0,m=3*mf*(e.blur??0)+1.5*pf*e.haloScale,g=Math.max(p,v,0)+m+2;return{x:r-h-g,y:o-u-g,width:2*(h+g),height:2*(u+g)}}paintInto(e,t,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-t.x,-t.y);const s=e.selected?{...e,selected:!1}:e;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency;const t=e.blur??0;t>0&&(this.ctx.filter=`blur(${(mf*t).toFixed(2)}px)`);const i=e.brightness??0;i>0&&this.paintDazzle(e,i),e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}setStarPoints(e){this.starPoints=Math.max(0,Math.floor(e))}setRoll(e){this.roll=e}paintDazzle(e,t){const{x:i,y:n,width:s,height:r}=e.bounds,o=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+gf*t),xf*t);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(o,c,0,o,c,h);for(let d=0;d<=vf;d++){const f=d/vf,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(e.color,p*t*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(o,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+Mf*t);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,v=o+Math.cos(p)*d,m=c+Math.sin(p)*d,g=this.ctx.createLinearGradient(o,c,v,m);g.addColorStop(0,this.withAlpha(e.color,t*.55)),g.addColorStop(.35,this.withAlpha(e.color,t*.22)),g.addColorStop(1,this.withAlpha(e.color,0)),this.ctx.strokeStyle=g,this.ctx.beginPath(),this.ctx.moveTo(o,c),this.ctx.lineTo(v,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(e,t){if(t<=0)return e.color;const i=/^#([0-9a-f]{6})$/i.exec(e.color.trim());if(!i)return e.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*t);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(e,t){const i=Math.max(0,Math.min(1,t)),n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!n)return e;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(e){this.ctx.fillStyle=this.dazzledFill(e,e.brightness??0),this.tracePath(e),this.ctx.fill()}paintGhost(e,t){this.ctx.save(),this.tracePath(e),this.ctx.setLineDash([t*3,t*2]),this.ctx.lineWidth=t,this.ctx.strokeStyle=e.color,this.ctx.stroke(),this.ctx.restore()}tracePath(e){if(this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:i,width:n,height:s}=e.bounds,r=n/2,o=s/2;this.ctx.ellipse(t+r,i+o,r,o,e.angle,0,2*Math.PI)}else{const{x:t,y:i,width:n,height:s}=e.bounds;this.ctx.save(),this.ctx.translate(t+n/2,i+s/2),this.ctx.rotate(e.angle),this.ctx.translate(-n/2,-s/2),e.points.forEach((r,o)=>{o===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=pf*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame(cn.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of cn.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,Gn,Gn,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline(cn.handlePointsFor(e))}paintSelectionOnly(e){this.paintSelectionHandles(e)}paintPictureFrame(e,t,i){const n=this.ctx;if(n.save(),e&&e.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of t){const r=No.landmarkColour(s.residualDeg),o=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=o+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Gn+2,Gn+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,Gn,Gn,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=o,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Gn+2,Gn+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Gn+5,s.picture.y-Gn-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}static landmarkColour(e){return e===void 0?"#ffb000":e<=1?"#3c3":e<=3?"#ffb000":"#f33"}paintLabel(e,t,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const o=r.measureText(e).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(t-3,i-2,o+6,s+4),r.fillStyle=n,r.fillText(e,t,i),r.restore()}paintGroupHandles(e){this.paintHandleFrame(cn.handlePointsFor({bounds:e,angle:0}),{includeRotate:!0})}paintOutline(e){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(e.nw.x,e.nw.y),this.ctx.lineTo(e.ne.x,e.ne.y),this.ctx.lineTo(e.se.x,e.se.y),this.ctx.lineTo(e.sw.x,e.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(e,{includeRotate:t}){this.paintOutline(e),this.ctx.fillStyle="lightgray";for(const i of vg){const n=e[i];this.ctx.fillRect(n.x-nc,n.y-nc,Ru,Ru)}t&&(this.ctx.beginPath(),this.ctx.moveTo(e.n.x,e.n.y),this.ctx.lineTo(e.rotate.x,e.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(e.rotate.x,e.rotate.y,nc+1,nc+1,0,0,2*Math.PI),this.ctx.fill())}}const yf=.05,_f=.08,bf=2,Sf=3,i2=14,n2=.02;class s2{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}this.context.state==="suspended"&&this.context.resume()}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const n=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,n,yf);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,yf)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const n=e.createOscillator();n.type="sawtooth";const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(e.destination),i.start(),n.start(),{key:t,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(e,t){const i=e.createOscillator();i.type="sine";const n=e.createOscillator();n.type="sine",n.frequency.value=5;const s=e.createGain(),r=e.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(e.destination),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=e.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(e.destination),i.start(),{key:t,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=e.createGain();s.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const o=e.createGain();return o.gain.value=0,r.connect(o).connect(s.gain),i.connect(n).connect(s).connect(e.destination),i.start(),r.start(),{key:t,nodes:[n,s,o],sources:[i,r],volumeParam:o.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(e)}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 o=n.createGain();o.gain.value=0,r.connect(o).connect(n.destination),r.start(),this.voice={key:t,nodes:[o],sources:[r],volumeParam:o.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*bf),e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*bf),e.sampleRate),i=t.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 t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*Sf),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(n2*e.sampleRate)),s=Math.round(Sf*i2);for(let r=0;r<s;r++){const o=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&o+l<i.length;l++)i[o+l]=Math.max(i[o+l],c*(1-l/n))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,_f/3);const n=i+_f;for(const s of e.sources){s.onended=()=>{s.disconnect();for(const r of e.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of e.nodes)r.disconnect()}}}}function Ml(a){return[...a].sort((e,t)=>e.t-t.t)}function wf(a,e){let t;for(const i of Ml(a)){if(i.t>e)break;t=i}return t}const rh=Math.PI/180,sc=180/Math.PI;class _s{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*rh/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new _s(e.projection,t,i)}degToPx(e){const t=e*rh;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*sc:2*Math.atan(e/(2*this.focalPx))*sc}angleDegToRadiusPx(e){const t=e*rh;return this.kind==="equidistant"?this.focalPx*t:this.focalPx*Math.tan(t)}halfWidthAngleDeg(e){return this.radiusPxToAngleDeg(this.canvasHeightPx*e/2)}radiusPxToAngleDeg(e){return this.kind==="equidistant"?e/this.focalPx*sc:Math.atan(e/this.focalPx)*sc}ofBounds(e){return{widthDeg:this.pxToDeg(e.width),heightDeg:this.pxToDeg(e.height)}}toBoundsSize(e){return{width:this.degToPx(e.widthDeg),height:this.degToPx(e.heightDeg)}}widthPx(e){return this.degToPx(Pt.angularWidthDeg(e))}}class Ji{static fovOf(e,t){return Jt(e,t)?.fovDeg??ni.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>({...t,angular:i.ofBounds(t.bounds)}))}static toBounds(e){this.eachKeyframe(e,(t,i)=>{if(!t.angular)return t;const{width:n,height:s}=i.toBoundsSize(t.angular),r={x:t.bounds.x+(t.bounds.width-n)/2,y:t.bounds.y+(t.bounds.height-s)/2,width:n,height:s};if(t.kind!=="polygon")return{...t,bounds:r};const o=t.bounds.width===0?1:n/t.bounds.width,c=t.bounds.height===0?1:s/t.bounds.height;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*o,y:l.y*c}))}})}static toAim(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);if(s&&Math.abs(s.x-t.bounds.x)<Ji.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Ji.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,Jt(e,t),i)}static aimFrom(e,t,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(e),r=t.radiusPxToAngleDeg(n.x+n.width/2-s.x),o=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+o}}static toPosition(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);return s?{...t,bounds:{...t.bounds,...s}}:t})}static positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),o=this.shortestArc(t.azimuthDeg-s.headingDeg),c=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,o)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(e){return{x:ni.frameWidthPx(e.instrument,Pt.CANVAS_HEIGHT_PX)/2,y:Pt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Ji.OFF_CANVAS_DEG?Math.sign(t)*Ji.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=ni.frameWidthPx(t,Pt.CANVAS_HEIGHT_PX)/2,s=ni.frameWidthPx(e.instrument,Pt.CANVAS_HEIGHT_PX)/2,r=Pt.CANVAS_HEIGHT_PX/2;for(const o of[...e.timeline.allKeyframes]){const c=this.fovOf(e,o.t),l=i?.get(o.t)??c,h=_s.of(t,Pt.CANVAS_HEIGHT_PX,l),u=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,c);e.timeline.addKeyframe(o.t,o.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,v=f.y+f.height/2-r,m=Math.hypot(p,v),g=m===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,y={...f,x:s+p*g-f.width/2,y:r+v*g-f.height/2};return{...d,shape:{...d.shape,bounds:y}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=Jt(e,n.t),r=this.fovOf(e,n.t),o=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(c=>({...c,shape:t(c.shape,o,s)})))}}}function r2(a){return Ki.restore(a2(a),a.provenance)}function a2(a){return Ji.toAngular(a),Ji.toAim(a),{version:1,id:a.id,time:a.event.time,endTime:a.event.endTime,durationSeconds:a.event.durationSeconds,utcOffsetHours:a.event.utcOffsetHours,timeZone:a.event.timeZone,place:a.event.place,observer:a.observer,account:a.account,sway:a.sway,vehicle:a.vehicle,description:a.event.description,tags:a.event.tags,timeline:a.timeline.toJSON(),observerTrack:a.observerTrack.toJSON(),weatherTrack:a.weatherTrack.toJSON(),soundTrack:a.soundTrack.toJSON(),weather:a.weather,decor:a.decor,milestones:a.milestones.length>0?a.milestones:void 0,references:a.references.length>0?a.references:void 0,roads:a.roads.length>0?a.roads:void 0,weatherSource:a.weatherSource,instrument:a.instrumentId,exposureSeconds:a.exposureSeconds,iso:a.iso,interpretation:a.interpretation}}function o2(a){const{recording:e,provenance:t}=Ki.strip(a),i=c2(e);return i.provenance=t,i}function c2(a){const e=new Gl({eventType:"sighting",time:a.time,endTime:a.endTime,durationSeconds:a.durationSeconds,utcOffsetHours:a.utcOffsetHours,timeZone:a.timeZone,place:a.place,description:a.description,tags:a.tags},Hl.fromJSON(a.timeline),a.observerTrack?Io.fromJSON(a.observerTrack):new Io,a.weatherTrack?Po.fromJSON(a.weatherTrack):new Po,a.soundTrack?Lo.fromJSON(a.soundTrack):new Lo,a.observer&&{id:a.observer.id,title:a.observer.title,lastName:a.observer.lastName,firstNames:a.observer.firstNames},a.id,a.weather,a.decor??[],a.weatherSource,a.instrument,a.exposureSeconds??a.observerTrack?.keyframes.map(t=>t.pose.exposureSeconds).find(t=>t!==void 0),Ml(a.milestones??[]),a.references??[],a.roads??[]);return e.account=a.account,e.sway=a.sway,e.iso=a.iso,e.vehicle=a.vehicle,e.interpretation=a.interpretation,Ji.toBounds(e),Ji.toPosition(e),e}class Cn{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,n=Math.max(0,e-i*1e3),s=Math.max(0,e-n);return{fromMs:n,toMs:e,ms:s,seconds:s/1e3}}static instants(e,t,i,n,s){if(!(n>0))return 1;const r=s>0?Cn.travelDegOver(e,t,i,i+n*1e3)/s/Cn.PIXELS_PER_INSTANT:0,o=Cn.flashesOver(e,n)*Cn.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,o));return c<2?1:Math.min(Cn.MAX_INSTANTS,c)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=Cn.directionAt(r,t,i),c=Cn.directionAt(r,t,n),l=Math.min(1,Math.max(-1,o.x*c.x+o.y*c.y+o.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(e,t){let i=0;for(const n of e)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const n=Pa(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,c=Math.hypot(s,r,o);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:o/c}}}function Fo(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Ir{static preferencesFor(e){const t=navigator.languages??[],i=this.declaredFor(e);return i?[i,...t]:t}static declaredFor(e){for(let t=e;t;){const i=t.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=t.getRootNode();t=n instanceof ShadowRoot?n.host:void 0}}}class Pn{constructor(e){this.preferences=e}read(e){if(e===void 0||typeof e=="string")return e===""?void 0:e;for(const i of this.preferences){const n=e[i]??e[Pn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>Pn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(Pn.base(i)))return n;return Object.values(e).find(i=>i)??void 0}write(e,t,i){const n=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return n;const s={...e},r=Object.keys(s).find(o=>o===i)??Object.keys(s).find(o=>Pn.base(o)===Pn.base(i))??i;return n===void 0?delete s[r]:s[r]=n,Object.keys(s).length===0?void 0:s}static base(e){return e.toLowerCase().split("-")[0]}}const Mg=["en","fr"],l2={en:()=>As(()=>Promise.resolve().then(()=>p2),void 0,import.meta.url).then(a=>a.ufoMessages_en),fr:()=>As(()=>import("./UfoMessages_fr-w9ZrScvP.js"),[],import.meta.url).then(a=>a.ufoMessages_fr)};function h2(a){return l2[a]()}const u2={en:()=>As(()=>Promise.resolve().then(()=>bA),void 0,import.meta.url).then(a=>a.sightingMessages_en),fr:()=>As(()=>import("./SightingMessages_fr-B1p11Wm5.js"),[],import.meta.url).then(a=>a.sightingMessages_fr)};function d2(a){return u2[a]()}function f2(a){return a==="fr"?As(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr):Promise.resolve({})}const xg={play:"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",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",referenceOpacity:"Picture opacity",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery"},p2=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:xg},Symbol.toStringTag,{value:"Module"})),yg=Math.PI/180,m2=180/Math.PI,g2=256,_g=19,v2=1.25;function bg(a,e){return 156543.03392*Math.cos(a*yg)/2**e}function Sg(a,e){return bg(a,e)*g2}function M2(a,e){let t=0;for(;t<_g&&Sg(a,t+1)>=e;)t++;return t}function wg(a,e){return Sg(a,e)}function x2(a,e){const t=e*v2;let i=0;for(;i<_g&&bg(a,i)>t;)i++;return i}function il(a){const e=a*yg;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function Eg(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:il(e)*i}}function Ag(a,e,t){const i=il(a.north),n=il(a.south);return{x:(e-a.west)/(a.east-a.west),y:(il(t)-i)/(n-i)}}function y2(a,e,t){const{x:i,y:n}=Eg(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function _2(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=Ef(a.y,e);return{south:Ef(a.y+1,e),north:n,west:t,east:i}}function Ef(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*m2}function Tg(a,e,t,i){const n=y2(a,e,t),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:t});const o=r.map(_2),c={south:Math.min(...o.map(l=>l.south)),north:Math.max(...o.map(l=>l.north)),west:Math.min(...o.map(l=>l.west)),east:Math.max(...o.map(l=>l.east))};return{tiles:r,bounds:c}}class Mr{constructor(e){this.ctx=e}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(e,t){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-e,s.y-t);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(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const n=Ag(e,i,t);return{x:n.x*this.width,y:n.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const n=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const n=this.toCanvas(e.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}),t.beginPath(),t.rect(n.x-3.5,n.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(n=>this.toCanvas(e.bounds,n.lat,n.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))t.lineTo(n.x,n.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:n}=e;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),o=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,o,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,o);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(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(e.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:Mr.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Mr.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,n.x,n.y)}}paintObserver(e,t){const{ctx:i}=this,n=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:n.x,y:n.y,radius:8});const s=e.markers.some(r=>{if(!r.current)return!1;const o=ii(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Mr.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Mr.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:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=t?this.wrap(t,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=(e.south+e.north)/2,c=Math.abs(ii(r,e.east,r,e.west).x)/this.width,l=Mr.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(e,t,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(e,t,i),n.fillStyle="#fff",n.fillText(e,t,i)}wrap(e,t){const i=[];let n="";for(const s of e.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>t?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class vi{static MIN_ZOOM=.25;static MAX_ZOOM=64;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(e,t,i){const n=Math.min(vi.MAX_ZOOM,Math.max(vi.MIN_ZOOM,this.zoom*i)),s=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=s-(e-.5)/n,this.centerY=r-(t-.5)/n,this.zoom=n}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),n=vi.mercatorY01(t.north),s=vi.mercatorY01(t.south),r=vi.mercatorY01(i.north),o=vi.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+o)/2-n)/(s-n)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=vi.mercatorY01(e.north),n=vi.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:vi.latitudeAt(i+(this.centerY-t)*(n-i)),south:vi.latitudeAt(i+(this.centerY+t)*(n-i))}}static pointAt(e,t,i){const n=vi.mercatorY01(e.north),s=vi.mercatorY01(e.south);return{lat:vi.latitudeAt(n+i*(s-n)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const fn=256,Af=3,b2=32768;class S2{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,n=(e.west+e.east)/2,s=Math.abs(ii(i,e.east,i,e.west).x),r=Math.abs(ii(e.north,n,e.south,n).z),o=M2(i,Math.max(s,r)),{tiles:c}=Tg(n,i,o,Af),l=Af*fn,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(t.width*t.height);for(let f=0;f<t.height;f++){const p=e.north+(e.south-e.north)*(f/(t.height-1));for(let v=0;v<t.width;v++){const m=e.west+(e.east-e.west)*(v/(t.width-1));d[f*t.width+v]=this.sampleAt(p,m,o,u,h,l)}}return{heights:d,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,n){const s=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const o=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=fn,c.height=fn;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(o,0,0);const{data:h}=l.getImageData(0,0,fn,fn),u=(e.x-t.x)*fn,d=(e.y-t.y)*fn;for(let f=0;f<fn;f++)for(let p=0;p<fn;p++){const v=(f*fn+p)*4,m=h[v]*256+h[v+1]+h[v+2]/256-b2,g=u+p,y=d+f;i[y*n+g]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:c}=Eg(t,e,i),l=(o-n.x)*fn,h=(c-n.y)*fn,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),v=l-u,m=h-d,g=s[d*r+u],y=s[d*r+f],b=s[p*r+u],M=s[p*r+f],S=g+(y-g)*v,w=b+(M-b)*v;return S+(w-S)*m}}const nl=256,w2=5;async function E2(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ii(n,a.east,n,a.west).x),o=Math.abs(ii(a.north,s,a.south,s).z),c=Math.max(r,o),{zoom:l,gridSize:h}=A2(n,c,Math.max(e.width,e.height)),{tiles:u,bounds:d}=Tg(s,n,l,h),f=h*nl,p=document.createElement("canvas");p.width=f,p.height=f;const v=p.getContext("2d");if(!v)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async M=>{const S=t(M),w=await i(S);if(!w.ok)throw new Error(`Imagery tile fetch failed (${w.status}): ${S}`);const T=await createImageBitmap(await w.blob());v.drawImage(T,(M.x-m.x)*nl,(M.y-m.y)*nl)}));const g=Math.min(Math.max(e.width,e.height),f);if(g===f)return{source:p,width:f,height:f,bounds:d};const y=document.createElement("canvas");y.width=g,y.height=g;const b=y.getContext("2d");if(!b)throw new Error("2D canvas context unavailable");return b.drawImage(p,0,0,f,f,0,0,g,g),{source:y,width:g,height:g,bounds:d}}function A2(a,e,t){let i=x2(a,e/Math.max(1,t)),n=Tf(a,i,e);for(;n>w2&&i>0;)i--,n=Tf(a,i,e);return{zoom:i,gridSize:n,mPerPixel:wg(a,i)/nl}}function Tf(a,e,t){const i=Math.ceil(t/2/wg(a,e));return Math.max(3,2*i+1)}class T2{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return E2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class En{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;static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints??En.ENDPOINTS}static queue=Promise.resolve();static RETRY_MS=4e3;async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${En.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.queued(()=>this.ask(i)))}waysFrom(e){const t=[];for(const i of e.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||t.push({id:`osm-${i.id??t.length}`,name:s.name,surface:En.surfaceOf(s),widthM:En.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=En.queue.then(e,e);return En.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints)for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`);if(s.ok)return await s.json();if(t=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){t=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,En.RETRY_MS))}throw t??new Error("No Overpass instance answered")}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:En.WIDTH_M[e.highway]??En.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const ah="https://ufoathome.org/roads/index.json";class i0{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??i0.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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(){return this.index??=this.fetchFirstAvailable(),this.index}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.69.2")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==ah?[t,ah]:[ah]).map(i=>i+e)}}function R2(){return{elevation:new S2,imagery:Rg(),roads:D2()}}function Rg(){return new T2}function D2(){return new i0({fallback:new En})}const C2=new Set,Ss="show-observer-map",ws="hide-milestones";class Ri extends HTMLElement{static get observedAttributes(){return["src",Ss,ws]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;observerMapButton;referencesButton;referenceOpacityInput;referencesShownState=!0;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new vi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Gl.create();sightingAudio=new s2;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=xg;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.resizeObserverMap()};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=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.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=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Ri.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=vi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=vi.MIN_ZOOM,this.paintObserverMap(this.currentTime),clearTimeout(this.observerMapImageryTimer),this.observerMapImageryTimer=setTimeout(()=>void this.loadObserverMapImagery(),Ri.OBSERVER_MAP_IMAGERY_DELAY_MS)}static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=vi.pointAt(t,(e.clientX-i.left)/i.width,(e.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 e=document.createElement("template");e.innerHTML=`<style>${Zv}</style>${Kv}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new No(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),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 Mr(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");for(const t of[this.timeStartLabel,this.timeEndLabel])t.addEventListener("click",()=>this.toggleTimeDisplay()),t.addEventListener("keydown",i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),this.toggleTimeDisplay())});this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),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",t=>{this.seekSnapArmed=!0,this.nameMarkUnder(t)}),this.seekInput.addEventListener("pointerup",()=>{this.seekSnapArmed=!1}),this.seekInput.addEventListener("pointermove",t=>this.nameMarkUnder(t)),this.seekInput.addEventListener("pointerleave",()=>this.seekInput.removeAttribute("title")),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.canvas.addEventListener("click",t=>{this.enableClickToPlay&&(t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause())}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateMilestonesButton(),this.refresh(),this.loadLocaleMessages()}connectedCallback(){this.saidTexts=void 0;const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.observerMapResizeObserver?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Ss&&this.applyObserverMapDefault(),e===ws&&this.setMilestonesShown(!this.hasAttribute(ws))}async loadFromSrc(e){this.sightingData=await bo.json(e)}get sightingData(){return r2(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=o2(e),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}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(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){this.player.seekableDuration<=0||this.playbackState==="playing"||this.togglePlayPause()}pause(){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(e){this.toolbar.classList.toggle("hidden",!e)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referenceOpacityInput,this.referencesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else for(const i of t)this.toolbar.appendChild(i)}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}toggleReferences(){this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity)),this.updateReferencesButton()}updateReferencesButton(){const e=this.currentSighting.references.length>0;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState,this.referencesButton.setAttribute("aria-pressed",String(this.referencesShownState));const t=this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=t,this.referencesButton.setAttribute("aria-label",t),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}dispatchReferenceView(){this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?Ml(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n}))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=Ri.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?wf(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=Cn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Ri.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Ri.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Ri.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Ri.EXPOSURE_STEP_PX),s=Math.min(Ri.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(e,t,i){for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=ni.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:C2;this.canvasRenderer.setStarPoints(ni.starPointsOf(this.sighting.instrument));const n=(Jt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,c]of o.shapes){const l=o.share,h=l===1?c:{...c,transparency:1-(1-c.transparency)*l};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,c]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));if(this.selectionShown&&i.size>1){const o=cn.groupBoundsFor([...t].filter(([c])=>i.has(c)).map(([,c])=>c.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(dg(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new Jv(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Ri.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){this.player.seekableDuration<=0||(this.player.playbackState==="playing"?(this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh()):(this.sightingAudio.resume(),this.player.play()),this.updatePlayPauseButton(),this.flashPlayback())}flashPlayback(){const e=this.playbackFlash;e.textContent=this.player.playbackState==="playing"?"▶":"⏸",e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.playPauseButton.textContent=e?"⏸":"▶";const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?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 e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.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(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton()}toggleObserverMap(){this.setObserverMapOpen(this.observerMapPanel.hidden)}applyObserverMapDefault(){const e=this.getAttribute(Ss),t=e===null?this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);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 e=this.observerPath!==void 0;if(this.observerPath=ba.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.observerPath.boundsAround(Ri.OBSERVER_MAP_MIN_SPAN_M,Ri.OBSERVER_MAP_MARGIN);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,t))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,t),this.observerMapBounds=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||!this.observerMapImageryNeededFor(e))return;this.observerMapImageryBounds=e;const t=Rg();try{const i=await t.getImageryTexture(e,{width:Ri.OBSERVER_MAP_IMAGERY_PX,height:Ri.OBSERVER_MAP_IMAGERY_PX});if(this.observerMapImageryBounds!==e)return;this.observerMapImagery=i,this.observerMapImageryCredit=t.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==e)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}this.paintObserverMap(this.currentTime)}observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=e.west>=i.west&&e.east<=i.east&&e.south>=i.south&&e.north<=i.north,s=e.east-e.west>(t.east-t.west)/2;return!n||!s}get observerMapCredit(){return this.observerMapImageryCredit}get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of t)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>e.bottom+u||d.y+d.height<e.top-u))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=Ri.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&c),this.observerMapPanel.classList.contains("on-the-left")){!o&&(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 e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=Jt(this.currentSighting,e),i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?wf(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Ml(this.currentSighting.milestones):[]){const o=Jt(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?_s.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(ni.aspectOf(i)):void 0,markers:n,decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0;const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=Jt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Pa(i,e),{lat:s,lng:r}=ys(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=Jt(this.currentSighting,this.currentTime),s=_s.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return xt.bodyAt(this.currentSighting,e,this.steadyObserver)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Pn(Ir.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fo(Ir.preferencesFor(this),Mg);e!=="en"&&this.applyMessages(await h2(e))}updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t;for(const i of[this.timeStartLabel,this.timeEndLabel])i.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateMilestonesButton()}updateTimeLabels(){const e=this.currentSighting.event,t=ug(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Tu(e.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.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return rc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Df(Rf(this.realStartMs+i)):rc(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?rc(this.currentSighting.timeline.duration):this.canShowClockTime?Df(Rf(this.realStartMs+this.realDurationMs)):rc(this.realDurationMs)}}function Rf(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Df(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function rc(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Du="rr0-ufo";function Dg(){customElements.get(Du)||customElements.define(Du,Ri)}/**
|
|
1193
|
+
`;class ba{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||t.push({t:i.t,lat:n,lng:s,headingDeg:r})}if(t.length===0){const i=e.event.place?.[0];if(!i)return;t.push({t:0,lat:i.lat,lng:i.lng})}return new ba(t)}static TRAVEL_M=50;get travels(){return this.spanM>ba.TRAVEL_M}get moved(){return this.spanM>ba.STATIONARY_M}get spanM(){const e=this.box,t=(e.south+e.north)/2,i=(e.west+e.east)/2;return Math.max(Math.abs(ii(t,e.east,t,e.west).x),Math.abs(ii(e.north,i,e.south,i).z))}get center(){const e=this.box;return{lat:(e.south+e.north)/2,lng:(e.west+e.east)/2}}boundsAround(e,t){const{lat:i,lng:n}=this.center,s=Math.max(this.spanM*(1+t),e)/2;return{north:ys(0,-s,i,n).lat,south:ys(0,s,i,n).lat,east:ys(s,0,i,n).lng,west:ys(-s,0,i,n).lng}}get box(){const e=this.points.map(i=>i.lat),t=this.points.map(i=>i.lng);return{south:Math.min(...e),north:Math.max(...e),west:Math.min(...t),east:Math.max(...t)}}}class mn{constructor(e,t){this.rotationPassed=e,this.scale=t}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(e){const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>mn.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new mn(Math.max(1-(e.instrument.stabilization??0),mn.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*t+d),[s,r,o,c,l,h]=mn.HZ;return{eastM:i*mn.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*mn.SWAY_M*(.6*n(o,2.2)+.4*n(l,.8)),upM:i*mn.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*mn.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*mn.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(o,.4)),rollDeg:i*this.rotationPassed*mn.DRIFT_ROLL_DEG*n(s,2.9)}}}class xt{constructor(e,t){this.stretches=e,this.rotationPassed=t}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(e){const t=ba.of(e);if(!t||t.points.length<2)return;const i=[];let n=0;for(let s=1;s<t.points.length;s++){const r=t.points[s-1],o=t.points[s],c=(o.t-r.t)/1e3;if(c<=0)continue;const l=ii(o.lat,o.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=xt.stepHzFor(f);i.push({startMs:r.t,endMs:o.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],o=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=o===void 0||o.stepHz===0}if(i.some(s=>s.stepHz>0))return new xt(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=xt.of(e)?.offsetAt(t)??xt.STILL;return i?n:xt.add(n,mn.of(e)?.offsetAt(t))}static stepHzFor(e){return e<xt.SLOWEST_WALK_M_PER_S||e>xt.FASTEST_WALK_M_PER_S?0:xt.REFERENCE_STEP_HZ*Math.pow(e/xt.REFERENCE_SPEED_M_PER_S,xt.CADENCE_EXPONENT)}offsetAt(e){return xt.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/xt.REFERENCE_SPEED_M_PER_S,n=(o,c,l,h)=>{if(o<0||o>xt.JOLT_LASTS_MS)return;const u=o/1e3,d=Math.exp(-u/xt.JOLT_DECAY_S)*Math.sin(2*Math.PI*xt.JOLT_HZ*u),f=h*c*i*d;return{eastM:f*t.eastUnit,northM:f*t.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,xt.STOP_LURCH_M,xt.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,xt.START_LURCH_M,xt.START_PITCH_DEG,-1):void 0;if(r)return r}}static add(e,t){return t?{eastM:e.eastM+t.eastM,northM:e.northM+t.northM,upM:e.upM+t.upM,rollDeg:e.rollDeg+t.rollDeg,pitchDeg:e.pitchDeg+t.pitchDeg,yawDeg:e.yawDeg+t.yawDeg}:e}cycleAt(e){const t=this.stretches.find(c=>e>=c.startMs&&e<=c.endMs);if(!t||t.stepHz===0)return xt.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=xt.SWAY_M*s*Math.cos(n/2),o=s*this.rotationPassed*t.speedMPerS/xt.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:xt.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:xt.HEAD_ROLL_DEG*o*Math.cos(n/2),pitchDeg:-1.25*o*Math.cos(n),yawDeg:xt.HEAD_YAW_DEG*o*Math.cos(n/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,n=Math.min(i,(e.endMs-e.startMs)/2);if(n<=0)return 1;const s=t-e.startMs,r=e.endMs-t,o=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(o,0)))/2}}class Jv{constructor(e,t){this.timeline=e,this.onFrame=t}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 e=()=>{if(this.state!=="playing")return;const t=performance.now();if(this.currentT+=(t-this.lastWallTime)*this.playbackRate,this.lastWallTime=t,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}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(e){this.currentT=Math.max(0,Math.min(e,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(e){const t=new Map;for(const i of this.timeline.sourceIds){const n=this.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}this.onFrame(e,t)}}const vg=["nw","n","ne","e","se","s","sw","w"],jv=24,tc=8,Qv=3,e2=8;function ic(a,e,t){const i=a.x-e.x,n=a.y-e.y,s=Math.cos(t),r=Math.sin(t);return{x:e.x+i*s-n*r,y:e.y+i*r+n*s}}function Va(a){return{x:a.x+a.width/2,y:a.y+a.height/2}}const t2={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 cn{static handlePointsFor(e){const{x:t,y:i,width:n,height:s}=e.bounds,r={nw:{x:t,y:i},n:{x:t+n/2,y:i},ne:{x:t+n,y:i},e:{x:t+n,y:i+s/2},se:{x:t+n,y:i+s},s:{x:t+n/2,y:i+s},sw:{x:t,y:i+s},w:{x:t,y:i+s/2},rotate:{x:t+n/2,y:i-jv}},o=Va(e.bounds),c={};for(const l of Object.keys(r))c[l]=ic(r[l],o,e.angle);return c}static hitTestHandle(e,t,i=8,n=[...vg,"rotate"]){const s=cn.handlePointsFor(e);for(const r of n)if(Math.hypot(t.x-s[r].x,t.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(e,t){const n=((cn.HANDLE_DIRECTION_DEG[e]+t*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(e,t,i,n){const s=Va(e),r=ic(n,s,-t),{x:o,y:c,width:l,height:h}=e,u=t2[i];let d=o,f=c,p=o+l,v=c+h;return u.left&&(d=Math.min(r.x,p-tc)),u.right&&(p=Math.max(r.x,d+tc)),u.top&&(f=Math.min(r.y,v-tc)),u.bottom&&(v=Math.max(r.y,f+tc)),{x:d,y:f,width:p-d,height:v-f}}static resizeShape(e,t,i){if(t==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=e.bounds,r=cn.resizeBounds(e.bounds,e.angle,t,i);if(e.kind==="oval")return{...e,bounds:r};const o=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...e,bounds:r,points:e.points.map(l=>({x:l.x*o,y:l.y*c}))}}static rotateShape(e,t){const i=Va(e.bounds),n=Math.atan2(t.y-i.y,t.x-i.x)+Math.PI/2;return{...e,angle:n}}static groupBoundsFor(e){const t=Math.min(...e.map(r=>r.x)),i=Math.min(...e.map(r=>r.y)),n=Math.max(...e.map(r=>r.x+r.width)),s=Math.max(...e.map(r=>r.y+r.height));return{x:t,y:i,width:n-t,height:s-i}}static vertexPointsFor(e){const t=Va(e.bounds);return e.points.map(i=>ic({x:e.bounds.x+i.x,y:e.bounds.y+i.y},t,e.angle))}static hitTestVertex(e,t,i=e2){const n=cn.vertexPointsFor(e);let s,r=i;return n.forEach((o,c)=>{const l=Math.hypot(t.x-o.x,t.y-o.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(e,t){const i=Va(e.bounds),n=ic(t,i,-e.angle);return{x:n.x-e.bounds.x,y:n.y-e.bounds.y}}static moveVertex(e,t,i){const n=e.points.map((u,d)=>d===t?cn.toLocalPoint(e,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),o=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:e.bounds.x+s,y:e.bounds.y+r,width:o-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...e,bounds:l,points:h}}static insertVertexNear(e,t){const i=cn.toLocalPoint(e,t),{points:n}=e;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=cn.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const o=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...e,points:o}}static distanceToSegment(e,t,i){const n=i.x-t.x,s=i.y-t.y,r=n*n+s*s,o=r===0?0:Math.max(0,Math.min(1,((e.x-t.x)*n+(e.y-t.y)*s)/r)),c=t.x+o*n,l=t.y+o*s;return Math.hypot(e.x-c,e.y-l)}static deleteVertex(e,t){return e.points.length<=Qv?e:{...e,points:e.points.filter((i,n)=>n!==t)}}}const Ru=6,nc=Ru/2,pf=20,mf=24,gf=9,vf=6,Mf=7,xf=6,Gn=4;class No{constructor(e){this.ctx=e}starPoints=0;roll=0;clear(e,t){this.ctx.clearRect(0,0,e,t)}static paintExtent(e){const{x:t,y:i,width:n,height:s}=e.bounds,r=t+n/2,o=i+s/2,c=e.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=e.brightness??0,p=f>0?Math.max(d*(1+gf*f),xf*f)-d:0,v=f>0?d*(1+Mf*f)-d:0,m=3*mf*(e.blur??0)+1.5*pf*e.haloScale,g=Math.max(p,v,0)+m+2;return{x:r-h-g,y:o-u-g,width:2*(h+g),height:2*(u+g)}}paintInto(e,t,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-t.x,-t.y);const s=e.selected?{...e,selected:!1}:e;n?this.paintGhost(s,1.5):this.paintShape(s),this.ctx.restore()}paintShape(e){this.ctx.save(),this.ctx.globalAlpha=1-e.transparency;const t=e.blur??0;t>0&&(this.ctx.filter=`blur(${(mf*t).toFixed(2)}px)`);const i=e.brightness??0;i>0&&this.paintDazzle(e,i),e.haloScale>0&&this.paintHalo(e),this.paintBase(e),this.ctx.restore(),e.selected&&this.paintSelectionHandles(e)}setStarPoints(e){this.starPoints=Math.max(0,Math.floor(e))}setRoll(e){this.roll=e}paintDazzle(e,t){const{x:i,y:n,width:s,height:r}=e.bounds,o=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+gf*t),xf*t);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(o,c,0,o,c,h);for(let d=0;d<=vf;d++){const f=d/vf,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(e.color,p*t*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(o,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+Mf*t);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,v=o+Math.cos(p)*d,m=c+Math.sin(p)*d,g=this.ctx.createLinearGradient(o,c,v,m);g.addColorStop(0,this.withAlpha(e.color,t*.55)),g.addColorStop(.35,this.withAlpha(e.color,t*.22)),g.addColorStop(1,this.withAlpha(e.color,0)),this.ctx.strokeStyle=g,this.ctx.beginPath(),this.ctx.moveTo(o,c),this.ctx.lineTo(v,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(e,t){if(t<=0)return e.color;const i=/^#([0-9a-f]{6})$/i.exec(e.color.trim());if(!i)return e.color;const n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*t);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(e,t){const i=Math.max(0,Math.min(1,t)),n=/^#([0-9a-f]{6})$/i.exec(e.trim());if(!n)return e;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&255}, ${i.toFixed(3)})`}paintBase(e){this.ctx.fillStyle=this.dazzledFill(e,e.brightness??0),this.tracePath(e),this.ctx.fill()}paintGhost(e,t){this.ctx.save(),this.tracePath(e),this.ctx.setLineDash([t*3,t*2]),this.ctx.lineWidth=t,this.ctx.strokeStyle=e.color,this.ctx.stroke(),this.ctx.restore()}tracePath(e){if(this.ctx.beginPath(),e.kind==="oval"){const{x:t,y:i,width:n,height:s}=e.bounds,r=n/2,o=s/2;this.ctx.ellipse(t+r,i+o,r,o,e.angle,0,2*Math.PI)}else{const{x:t,y:i,width:n,height:s}=e.bounds;this.ctx.save(),this.ctx.translate(t+n/2,i+s/2),this.ctx.rotate(e.angle),this.ctx.translate(-n/2,-s/2),e.points.forEach((r,o)=>{o===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(e){this.ctx.save(),this.ctx.shadowColor=e.color,this.ctx.shadowBlur=pf*e.haloScale,this.paintBase(e),this.ctx.restore()}paintSelectionHandles(e){this.paintHandleFrame(cn.handlePointsFor(e),{includeRotate:!0}),e.kind==="polygon"&&this.paintVertexHandles(e)}paintVertexHandles(e){this.ctx.fillStyle="#39f";for(const t of cn.vertexPointsFor(e))this.ctx.beginPath(),this.ctx.ellipse(t.x,t.y,Gn,Gn,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(e){this.paintOutline(cn.handlePointsFor(e))}paintSelectionOnly(e){this.paintSelectionHandles(e)}paintPictureFrame(e,t,i){const n=this.ctx;if(n.save(),e&&e.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(e[0].x,e[0].y);for(const s of e.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of t){const r=No.landmarkColour(s.residualDeg),o=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=o+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Gn+2,Gn+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,Gn,Gn,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=o,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Gn+2,Gn+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Gn+5,s.picture.y-Gn-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}static landmarkColour(e){return e===void 0?"#ffb000":e<=1?"#3c3":e<=3?"#ffb000":"#f33"}paintLabel(e,t,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const o=r.measureText(e).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(t-3,i-2,o+6,s+4),r.fillStyle=n,r.fillText(e,t,i),r.restore()}paintGroupHandles(e){this.paintHandleFrame(cn.handlePointsFor({bounds:e,angle:0}),{includeRotate:!0})}paintOutline(e){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(e.nw.x,e.nw.y),this.ctx.lineTo(e.ne.x,e.ne.y),this.ctx.lineTo(e.se.x,e.se.y),this.ctx.lineTo(e.sw.x,e.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(e,{includeRotate:t}){this.paintOutline(e),this.ctx.fillStyle="lightgray";for(const i of vg){const n=e[i];this.ctx.fillRect(n.x-nc,n.y-nc,Ru,Ru)}t&&(this.ctx.beginPath(),this.ctx.moveTo(e.n.x,e.n.y),this.ctx.lineTo(e.rotate.x,e.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(e.rotate.x,e.rotate.y,nc+1,nc+1,0,0,2*Math.PI),this.ctx.fill())}}const yf=.05,_f=.08,bf=2,Sf=3,i2=14,n2=.02;class s2{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",e);return}}this.context.state==="suspended"&&this.context.resume()}setSound(e){if(this.requested=e,!this.context)return;const t=this.keyFor(e);if(!t){this.silence();return}if(this.voice?.key!==t){this.stopVoice();const i=++this.voiceToken;t.startsWith("src:")?this.buildRecordedVoice(e.src,t,i):this.voice=this.buildSynthesizedVoice(e,t)}this.applyTo(this.voice,e)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),this.context?.close(),this.context=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(e){if(!(e.volume<=0))return e.src?`src:${e.src}`:e.kind==="none"?void 0:e.kind}applyTo(e,t){const i=this.context;if(!e||!i)return;const n=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,n,yf);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,yf)}buildSynthesizedVoice(e,t){const i=this.context;if(i)switch(e.kind){case"hum":return this.buildHum(i,t);case"whistle":return this.buildWhistle(i,t);case"rumble":return this.buildRumble(i,t);case"crackle":return this.buildCrackle(i,t);default:return}}buildHum(e,t){const i=e.createOscillator();i.type="sawtooth";const n=e.createOscillator();n.type="sawtooth";const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(e.destination),i.start(),n.start(),{key:t,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(e,t){const i=e.createOscillator();i.type="sine";const n=e.createOscillator();n.type="sine",n.frequency.value=5;const s=e.createGain(),r=e.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(e.destination),i.start(),n.start(),{key:t,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=e.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(e.destination),i.start(),{key:t,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const n=e.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=e.createGain();s.gain.value=0;const r=e.createBufferSource();r.buffer=this.crackleEnvelope(e),r.loop=!0;const o=e.createGain();return o.gain.value=0,r.connect(o).connect(s.gain),i.connect(n).connect(s).connect(e.destination),i.start(),r.start(),{key:t,nodes:[n,s,o],sources:[i,r],volumeParam:o.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(e)}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 o=n.createGain();o.gain.value=0,r.connect(o).connect(n.destination),r.start(),this.voice={key:t,nodes:[o],sources:[r],volumeParam:o.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(e){const t=this.context;if(!t)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*bf),e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*bf),e.sampleRate),i=t.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 t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*Sf),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(n2*e.sampleRate)),s=Math.round(Sf*i2);for(let r=0;r<s;r++){const o=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&o+l<i.length;l++)i[o+l]=Math.max(i[o+l],c*(1-l/n))}this.crackleBuffer=t}return this.crackleBuffer}stopVoice(){const e=this.voice,t=this.context;if(this.voice=void 0,!e||!t)return;const i=t.currentTime;e.volumeParam.cancelScheduledValues(i),e.volumeParam.setTargetAtTime(0,i,_f/3);const n=i+_f;for(const s of e.sources){s.onended=()=>{s.disconnect();for(const r of e.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of e.nodes)r.disconnect()}}}}function Ml(a){return[...a].sort((e,t)=>e.t-t.t)}function wf(a,e){let t;for(const i of Ml(a)){if(i.t>e)break;t=i}return t}const rh=Math.PI/180,sc=180/Math.PI;class _s{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*rh/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new _s(e.projection,t,i)}degToPx(e){const t=e*rh;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*sc:2*Math.atan(e/(2*this.focalPx))*sc}angleDegToRadiusPx(e){const t=e*rh;return this.kind==="equidistant"?this.focalPx*t:this.focalPx*Math.tan(t)}halfWidthAngleDeg(e){return this.radiusPxToAngleDeg(this.canvasHeightPx*e/2)}radiusPxToAngleDeg(e){return this.kind==="equidistant"?e/this.focalPx*sc:Math.atan(e/this.focalPx)*sc}ofBounds(e){return{widthDeg:this.pxToDeg(e.width),heightDeg:this.pxToDeg(e.height)}}toBoundsSize(e){return{width:this.degToPx(e.widthDeg),height:this.degToPx(e.heightDeg)}}widthPx(e){return this.degToPx(Pt.angularWidthDeg(e))}}class Ji{static fovOf(e,t){return Jt(e,t)?.fovDeg??ni.fieldOfViewDeg(e.instrument)}static toAngular(e){this.eachKeyframe(e,(t,i)=>({...t,angular:i.ofBounds(t.bounds)}))}static toBounds(e){this.eachKeyframe(e,(t,i)=>{if(!t.angular)return t;const{width:n,height:s}=i.toBoundsSize(t.angular),r={x:t.bounds.x+(t.bounds.width-n)/2,y:t.bounds.y+(t.bounds.height-s)/2,width:n,height:s};if(t.kind!=="polygon")return{...t,bounds:r};const o=t.bounds.width===0?1:n/t.bounds.width,c=t.bounds.height===0?1:s/t.bounds.height;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*o,y:l.y*c}))}})}static toAim(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);if(s&&Math.abs(s.x-t.bounds.x)<Ji.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Ji.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,Jt(e,t),i)}static aimFrom(e,t,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(e),r=t.radiusPxToAngleDeg(n.x+n.width/2-s.x),o=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+o}}static toPosition(e){this.eachKeyframe(e,(t,i,n)=>{const s=t.aim&&this.positionOf(e,t.aim,t.bounds,i,n);return s?{...t,bounds:{...t.bounds,...s}}:t})}static positionOf(e,t,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(e),o=this.shortestArc(t.azimuthDeg-s.headingDeg),c=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,o)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(e){return{x:ni.frameWidthPx(e.instrument,Pt.CANVAS_HEIGHT_PX)/2,y:Pt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Ji.OFF_CANVAS_DEG?Math.sign(t)*Ji.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=ni.frameWidthPx(t,Pt.CANVAS_HEIGHT_PX)/2,s=ni.frameWidthPx(e.instrument,Pt.CANVAS_HEIGHT_PX)/2,r=Pt.CANVAS_HEIGHT_PX/2;for(const o of[...e.timeline.allKeyframes]){const c=this.fovOf(e,o.t),l=i?.get(o.t)??c,h=_s.of(t,Pt.CANVAS_HEIGHT_PX,l),u=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,c);e.timeline.addKeyframe(o.t,o.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,v=f.y+f.height/2-r,m=Math.hypot(p,v),g=m===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,y={...f,x:s+p*g-f.width/2,y:r+v*g-f.height/2};return{...d,shape:{...d.shape,bounds:y}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=Jt(e,n.t),r=this.fovOf(e,n.t),o=_s.of(e.instrument,Pt.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(c=>({...c,shape:t(c.shape,o,s)})))}}}function r2(a){return Ki.restore(a2(a),a.provenance)}function a2(a){return Ji.toAngular(a),Ji.toAim(a),{version:1,id:a.id,time:a.event.time,endTime:a.event.endTime,durationSeconds:a.event.durationSeconds,utcOffsetHours:a.event.utcOffsetHours,timeZone:a.event.timeZone,place:a.event.place,observer:a.observer,account:a.account,sway:a.sway,vehicle:a.vehicle,description:a.event.description,tags:a.event.tags,timeline:a.timeline.toJSON(),observerTrack:a.observerTrack.toJSON(),weatherTrack:a.weatherTrack.toJSON(),soundTrack:a.soundTrack.toJSON(),weather:a.weather,decor:a.decor,milestones:a.milestones.length>0?a.milestones:void 0,references:a.references.length>0?a.references:void 0,roads:a.roads.length>0?a.roads:void 0,weatherSource:a.weatherSource,instrument:a.instrumentId,exposureSeconds:a.exposureSeconds,iso:a.iso,interpretation:a.interpretation}}function o2(a){const{recording:e,provenance:t}=Ki.strip(a),i=c2(e);return i.provenance=t,i}function c2(a){const e=new Gl({eventType:"sighting",time:a.time,endTime:a.endTime,durationSeconds:a.durationSeconds,utcOffsetHours:a.utcOffsetHours,timeZone:a.timeZone,place:a.place,description:a.description,tags:a.tags},Hl.fromJSON(a.timeline),a.observerTrack?Io.fromJSON(a.observerTrack):new Io,a.weatherTrack?Po.fromJSON(a.weatherTrack):new Po,a.soundTrack?Lo.fromJSON(a.soundTrack):new Lo,a.observer&&{id:a.observer.id,title:a.observer.title,lastName:a.observer.lastName,firstNames:a.observer.firstNames},a.id,a.weather,a.decor??[],a.weatherSource,a.instrument,a.exposureSeconds??a.observerTrack?.keyframes.map(t=>t.pose.exposureSeconds).find(t=>t!==void 0),Ml(a.milestones??[]),a.references??[],a.roads??[]);return e.account=a.account,e.sway=a.sway,e.iso=a.iso,e.vehicle=a.vehicle,e.interpretation=a.interpretation,Ji.toBounds(e),Ji.toPosition(e),e}class Cn{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(e,t){const i=Number.isFinite(t)?Math.max(0,t):0,n=Math.max(0,e-i*1e3),s=Math.max(0,e-n);return{fromMs:n,toMs:e,ms:s,seconds:s/1e3}}static instants(e,t,i,n,s){if(!(n>0))return 1;const r=s>0?Cn.travelDegOver(e,t,i,i+n*1e3)/s/Cn.PIXELS_PER_INSTANT:0,o=Cn.flashesOver(e,n)*Cn.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,o));return c<2?1:Math.min(Cn.MAX_INSTANTS,c)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=Cn.directionAt(r,t,i),c=Cn.directionAt(r,t,n),l=Math.min(1,Math.max(-1,o.x*c.x+o.y*c.y+o.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(e,t){let i=0;for(const n of e)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const n=Pa(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,c=Math.hypot(s,r,o);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:o/c}}}function Fo(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Ir{static preferencesFor(e){const t=navigator.languages??[],i=this.declaredFor(e);return i?[i,...t]:t}static declaredFor(e){for(let t=e;t;){const i=t.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=t.getRootNode();t=n instanceof ShadowRoot?n.host:void 0}}}class Pn{constructor(e){this.preferences=e}read(e){if(e===void 0||typeof e=="string")return e===""?void 0:e;for(const i of this.preferences){const n=e[i]??e[Pn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>Pn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(Pn.base(i)))return n;return Object.values(e).find(i=>i)??void 0}write(e,t,i){const n=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return n;const s={...e},r=Object.keys(s).find(o=>o===i)??Object.keys(s).find(o=>Pn.base(o)===Pn.base(i))??i;return n===void 0?delete s[r]:s[r]=n,Object.keys(s).length===0?void 0:s}static base(e){return e.toLowerCase().split("-")[0]}}const Mg=["en","fr"],l2={en:()=>As(()=>Promise.resolve().then(()=>p2),void 0,import.meta.url).then(a=>a.ufoMessages_en),fr:()=>As(()=>import("./UfoMessages_fr-w9ZrScvP.js"),[],import.meta.url).then(a=>a.ufoMessages_fr)};function h2(a){return l2[a]()}const u2={en:()=>As(()=>Promise.resolve().then(()=>bA),void 0,import.meta.url).then(a=>a.sightingMessages_en),fr:()=>As(()=>import("./SightingMessages_fr-B1p11Wm5.js"),[],import.meta.url).then(a=>a.sightingMessages_fr)};function d2(a){return u2[a]()}function f2(a){return a==="fr"?As(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr):Promise.resolve({})}const xg={play:"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",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",referenceOpacity:"Picture opacity",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery"},p2=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:xg},Symbol.toStringTag,{value:"Module"})),yg=Math.PI/180,m2=180/Math.PI,g2=256,_g=19,v2=1.25;function bg(a,e){return 156543.03392*Math.cos(a*yg)/2**e}function Sg(a,e){return bg(a,e)*g2}function M2(a,e){let t=0;for(;t<_g&&Sg(a,t+1)>=e;)t++;return t}function wg(a,e){return Sg(a,e)}function x2(a,e){const t=e*v2;let i=0;for(;i<_g&&bg(a,i)>t;)i++;return i}function il(a){const e=a*yg;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function Eg(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:il(e)*i}}function Ag(a,e,t){const i=il(a.north),n=il(a.south);return{x:(e-a.west)/(a.east-a.west),y:(il(t)-i)/(n-i)}}function y2(a,e,t){const{x:i,y:n}=Eg(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function _2(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=Ef(a.y,e);return{south:Ef(a.y+1,e),north:n,west:t,east:i}}function Ef(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*m2}function Tg(a,e,t,i){const n=y2(a,e,t),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:t});const o=r.map(_2),c={south:Math.min(...o.map(l=>l.south)),north:Math.max(...o.map(l=>l.north)),west:Math.min(...o.map(l=>l.west)),east:Math.max(...o.map(l=>l.east))};return{tiles:r,bounds:c}}class Mr{constructor(e){this.ctx=e}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(e,t){let i,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-e,s.y-t);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(e){const{ctx:t}=this;t.save(),this.targets=[],t.clearRect(0,0,this.width,this.height),this.paintGround(e),this.paintNight(e.nightFraction),this.paintPath(e),e.position?(this.paintCone(e,e.position),this.paintDecor(e),this.paintMarkers(e),this.paintObserver(e,e.position)):(this.paintDecor(e),this.paintMarkers(e)),this.paintNorth(),this.paintFooter(e.bounds,e.attribution),t.restore()}toCanvas(e,t,i){const n=Ag(e,i,t);return{x:n.x*this.width,y:n.y*this.height}}paintGround(e){const{ctx:t}=this;t.fillStyle="#1d2321",t.fillRect(0,0,this.width,this.height);const i=e.imagery;if(!i)return;const n=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.y)}paintNight(e=0){if(e<=0)return;const{ctx:t}=this;t.save(),t.fillStyle=`rgba(6, 12, 30, ${Math.min(e,1)*.78})`,t.fillRect(0,0,this.width,this.height),t.restore()}paintDecor(e){const{ctx:t}=this;for(const i of e.decor){const n=this.toCanvas(e.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}),t.beginPath(),t.rect(n.x-3.5,n.y-3.5,7,7),t.fillStyle="rgba(120, 220, 255, 0.85)",t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.7)",t.stroke(),i.headingDeg===void 0)continue;const s=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*10),t.lineWidth=3,t.strokeStyle="rgba(0, 0, 0, 0.6)",t.stroke(),t.lineWidth=1.5,t.strokeStyle="rgba(120, 220, 255, 0.9)",t.stroke()}}paintPath(e){if(!e.path.moved)return;const{ctx:t}=this,i=e.path.points.map(n=>this.toCanvas(e.bounds,n.lat,n.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))t.lineTo(n.x,n.y);t.lineJoin="round",t.lineCap="round",t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=5,t.stroke(),t.strokeStyle="rgba(255, 255, 255, 0.9)",t.lineWidth=2,t.stroke()}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:n}=e;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),o=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,o,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,o);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(e){const{ctx:t}=this;t.textAlign="center",t.textBaseline="middle",t.font="bold 10px sans-serif";for(const i of[...e.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=this.toCanvas(e.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:Mr.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Mr.MARKER_RADIUS_PX,0,Math.PI*2),t.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",t.fill(),t.lineWidth=2,t.strokeStyle="rgba(255, 255, 255, 0.9)",t.stroke(),t.fillStyle=i.current?"#1d2321":"#fff",t.fillText(i.label,n.x,n.y)}}paintObserver(e,t){const{ctx:i}=this,n=this.toCanvas(e.bounds,t.lat,t.lng);e.observerLabel&&this.targets.push({kind:"observer",label:e.observerLabel,lat:t.lat,lng:t.lng,x:n.x,y:n.y,radius:8});const s=e.markers.some(r=>{if(!r.current)return!1;const o=ii(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Mr.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Mr.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:e}=this,t=this.width-14,i=16;e.beginPath(),e.moveTo(t,i-9),e.lineTo(t-4.5,i+5),e.lineTo(t,i+2),e.lineTo(t+4.5,i+5),e.closePath(),e.fillStyle="rgba(255, 255, 255, 0.92)",e.strokeStyle="rgba(0, 0, 0, 0.6)",e.lineWidth=1,e.fill(),e.stroke(),e.font="bold 9px sans-serif",e.textAlign="center",e.textBaseline="top",e.strokeText("N",t,i+6),e.fillText("N",t,i+6)}paintFooter(e,t){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const n=t?this.wrap(t,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=(e.south+e.north)/2,c=Math.abs(ii(r,e.east,r,e.west).x)/this.width,l=Mr.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(e,t,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(e,t,i),n.fillStyle="#fff",n.fillText(e,t,i)}wrap(e,t){const i=[];let n="";for(const s of e.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>t?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class vi{static MIN_ZOOM=.25;static MAX_ZOOM=64;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(e,t,i){const n=Math.min(vi.MAX_ZOOM,Math.max(vi.MIN_ZOOM,this.zoom*i)),s=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=s-(e-.5)/n,this.centerY=r-(t-.5)/n,this.zoom=n}panBy(e,t){this.centerX-=e/this.zoom,this.centerY-=t/this.zoom}refit(e,t){if(!this.changed)return;const i=this.boundsWithin(e),n=vi.mercatorY01(t.north),s=vi.mercatorY01(t.south),r=vi.mercatorY01(i.north),o=vi.mercatorY01(i.south);this.zoom=(t.east-t.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-t.west)/(t.east-t.west),this.centerY=((r+o)/2-n)/(s-n)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=vi.mercatorY01(e.north),n=vi.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:vi.latitudeAt(i+(this.centerY-t)*(n-i)),south:vi.latitudeAt(i+(this.centerY+t)*(n-i))}}static pointAt(e,t,i){const n=vi.mercatorY01(e.north),s=vi.mercatorY01(e.south);return{lat:vi.latitudeAt(n+i*(s-n)),lng:e.west+t*(e.east-e.west)}}static mercatorY01(e){const t=e*Math.PI/180;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}static latitudeAt(e){return Math.atan(Math.sinh(Math.PI*(1-2*e)))*180/Math.PI}}const fn=256,Af=3,b2=32768;class S2{fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(e,t){const i=(e.south+e.north)/2,n=(e.west+e.east)/2,s=Math.abs(ii(i,e.east,i,e.west).x),r=Math.abs(ii(e.north,n,e.south,n).z),o=M2(i,Math.max(s,r)),{tiles:c}=Tg(n,i,o,Af),l=Af*fn,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(t.width*t.height);for(let f=0;f<t.height;f++){const p=e.north+(e.south-e.north)*(f/(t.height-1));for(let v=0;v<t.width;v++){const m=e.west+(e.east-e.west)*(v/(t.width-1));d[f*t.width+v]=this.sampleAt(p,m,o,u,h,l)}}return{heights:d,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,n){const s=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const o=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=fn,c.height=fn;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(o,0,0);const{data:h}=l.getImageData(0,0,fn,fn),u=(e.x-t.x)*fn,d=(e.y-t.y)*fn;for(let f=0;f<fn;f++)for(let p=0;p<fn;p++){const v=(f*fn+p)*4,m=h[v]*256+h[v+1]+h[v+2]/256-b2,g=u+p,y=d+f;i[y*n+g]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:c}=Eg(t,e,i),l=(o-n.x)*fn,h=(c-n.y)*fn,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),v=l-u,m=h-d,g=s[d*r+u],y=s[d*r+f],b=s[p*r+u],M=s[p*r+f],S=g+(y-g)*v,w=b+(M-b)*v;return S+(w-S)*m}}const nl=256,w2=5;async function E2(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ii(n,a.east,n,a.west).x),o=Math.abs(ii(a.north,s,a.south,s).z),c=Math.max(r,o),{zoom:l,gridSize:h}=A2(n,c,Math.max(e.width,e.height)),{tiles:u,bounds:d}=Tg(s,n,l,h),f=h*nl,p=document.createElement("canvas");p.width=f,p.height=f;const v=p.getContext("2d");if(!v)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async M=>{const S=t(M),w=await i(S);if(!w.ok)throw new Error(`Imagery tile fetch failed (${w.status}): ${S}`);const T=await createImageBitmap(await w.blob());v.drawImage(T,(M.x-m.x)*nl,(M.y-m.y)*nl)}));const g=Math.min(Math.max(e.width,e.height),f);if(g===f)return{source:p,width:f,height:f,bounds:d};const y=document.createElement("canvas");y.width=g,y.height=g;const b=y.getContext("2d");if(!b)throw new Error("2D canvas context unavailable");return b.drawImage(p,0,0,f,f,0,0,g,g),{source:y,width:g,height:g,bounds:d}}function A2(a,e,t){let i=x2(a,e/Math.max(1,t)),n=Tf(a,i,e);for(;n>w2&&i>0;)i--,n=Tf(a,i,e);return{zoom:i,gridSize:n,mPerPixel:wg(a,i)/nl}}function Tf(a,e,t){const i=Math.ceil(t/2/wg(a,e));return Math.max(3,2*i+1)}class T2{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=e.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(e,t){return E2(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class En{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;static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints??En.ENDPOINTS}static queue=Promise.resolve();static RETRY_MS=4e3;async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${En.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.queued(()=>this.ask(i)))}waysFrom(e){const t=[];for(const i of e.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||t.push({id:`osm-${i.id??t.length}`,name:s.name,surface:En.surfaceOf(s),widthM:En.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=En.queue.then(e,e);return En.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints)for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`);if(s.ok)return await s.json();if(t=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){t=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,En.RETRY_MS))}throw t??new Error("No Overpass instance answered")}static widthOf(e){const t=Number.parseFloat(e.width??e.est_width??"");if(Number.isFinite(t)&&t>0)return t;const i=Number.parseInt(e.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:En.WIDTH_M[e.highway]??En.DEFAULT_WIDTH_M}static surfaceOf(e){const t=e.surface;return t==="dirt"||t==="earth"||t==="mud"?"dirt":t==="gravel"||t==="fine_gravel"||t==="compacted"||t==="ground"||t==="sand"||t==="unpaved"?"gravel":t?"paved":e.highway==="track"?"gravel":"paved"}}const ah="https://ufoathome.org/roads/index.json";class i0{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??i0.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRoads(e);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(e){let t;try{t=await this.load()}catch{return}const i=t.find(({entry:n})=>n.north>=e.north&&n.south<=e.south&&n.east>=e.east&&n.west<=e.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(){return this.index??=this.fetchFirstAvailable(),this.index}async fetchFirstAvailable(){for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json();if(Array.isArray(i?.entries))return i.entries.map(n=>({entry:n,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.70.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==ah?[t,ah]:[ah]).map(i=>i+e)}}function R2(){return{elevation:new S2,imagery:Rg(),roads:D2()}}function Rg(){return new T2}function D2(){return new i0({fallback:new En})}const C2=new Set,Ss="show-observer-map",ws="hide-milestones";class Ri extends HTMLElement{static get observedAttributes(){return["src",Ss,ws]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;observerMapButton;referencesButton;referenceOpacityInput;referencesShownState=!0;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new vi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Gl.create();sightingAudio=new s2;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=xg;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.resizeObserverMap()};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=e=>{e.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=e=>{const t=this.canvasPointFromEvent(e),i=t&&this.shapeAt(t.x,t.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=`${e.clientX-s.left+12}px`,this.tooltip.style.top=`${e.clientY-s.top+12}px`};handleObserverMapPointerMove=e=>{if(this.dragObserverMap(e))return;const t=this.observerMapTargetFrom(e);if(!t){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(e,this.messages.placeObserverHere);return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(e,t.label)};showObserverMapTooltip(e,t){this.tooltip.textContent=t,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-i.left+12}px`,this.tooltip.style.top=`${e.clientY-i.top+12}px`}handleObserverMapClick=e=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const t=this.observerMapTargetFrom(e);if(!t){this.observerPlacing&&this.placeObserverFrom(e);return}if(t.kind==="milestone"&&t.t!==void 0){this.player.seek(t.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:t.lat,lng:t.lng,kind:t.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(e){const t=this.observerMapCanvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return this.observerMapRenderer.hitTest((e.clientX-t.left)/t.width*this.observerMapCanvas.width,(e.clientY-t.top)/t.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=e=>{e.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,moved:!1})};handleObserverMapPointerUp=e=>{const t=this.observerMapDrag;!t||t.pointerId!==e.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),t.moved&&(this.suppressObserverMapClick=!0,this.observerMapCanvas.hasPointerCapture?.(e.pointerId)&&this.observerMapCanvas.releasePointerCapture(e.pointerId)))};dragObserverMap(e){const t=this.observerMapDrag;if(!t||t.pointerId!==e.pointerId)return!1;if(!t.moved){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<Ri.OBSERVER_MAP_DRAG_PX)return!1;t.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(e.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((e.clientX-t.lastX)/i.width,(e.clientY-t.lastY)/i.height),this.observerMapViewChanged()),t.lastX=e.clientX,t.lastY=e.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=e=>{e.preventDefault();const t=this.observerMapCanvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=e.deltaMode===0?e.deltaY:e.deltaY*40;this.zoomObserverMap((e.clientX-t.left)/t.width,(e.clientY-t.top)/t.height,Math.exp(-i*.002))};zoomObserverMap(e,t,i){this.observerMapView.zoomAt(e,t,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=vi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=vi.MIN_ZOOM,this.paintObserverMap(this.currentTime),clearTimeout(this.observerMapImageryTimer),this.observerMapImageryTimer=setTimeout(()=>void this.loadObserverMapImagery(),Ri.OBSERVER_MAP_IMAGERY_DELAY_MS)}static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=vi.pointAt(t,(e.clientX-i.left)/i.width,(e.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 e=document.createElement("template");e.innerHTML=`<style>${Zv}</style>${Kv}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new No(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),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 Mr(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");for(const t of[this.timeStartLabel,this.timeEndLabel])t.addEventListener("click",()=>this.toggleTimeDisplay()),t.addEventListener("keydown",i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),this.toggleTimeDisplay())});this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),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",t=>{this.seekSnapArmed=!0,this.nameMarkUnder(t)}),this.seekInput.addEventListener("pointerup",()=>{this.seekSnapArmed=!1}),this.seekInput.addEventListener("pointermove",t=>this.nameMarkUnder(t)),this.seekInput.addEventListener("pointerleave",()=>this.seekInput.removeAttribute("title")),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.canvas.addEventListener("click",t=>{this.enableClickToPlay&&(t.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause())}),this.canvas.addEventListener("dblclick",t=>{this.enableClickToPlay&&(t.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateMilestonesButton(),this.refresh(),this.loadLocaleMessages()}connectedCallback(){this.saidTexts=void 0;const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.observerMapResizeObserver?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Ss&&this.applyObserverMapDefault(),e===ws&&this.setMilestonesShown(!this.hasAttribute(ws))}async loadFromSrc(e){this.sightingData=await bo.json(e)}get sightingData(){return r2(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=o2(e),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get sighting(){return this.currentSighting}previewSound(e){this.soundPreview=e,this.sightingAudio.resume(),this.sightingAudio.setSound(e)}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(e){this.player.seek(e)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(e){e!==this.loopEnabled&&this.toggleLoop()}play(){this.player.seekableDuration<=0||this.playbackState==="playing"||this.togglePlayPause()}pause(){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(e){this.toolbar.classList.toggle("hidden",!e)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(e){this.currentSighting.event.durationSeconds=e,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(e){const t=new Set(e);t.size===this.highlightedSourceIds.size&&[...t].every(n=>this.highlightedSourceIds.has(n))||(this.highlightedSourceIds=t,this.refresh())}hasVisibleShapeAt(e,t){return this.shapeAt(e,t)!==void 0}refresh(){this.applyFrameFormat(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referenceOpacityInput,this.referencesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else for(const i of t)this.toolbar.appendChild(i)}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}toggleReferences(){this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity)),this.updateReferencesButton()}updateReferencesButton(){const e=this.currentSighting.references.length>0;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState,this.referencesButton.setAttribute("aria-pressed",String(this.referencesShownState));const t=this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=t,this.referencesButton.setAttribute("aria-label",t),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}dispatchReferenceView(){this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?Ml(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),o=r?`${s} — ${r}`:s;return n.title=o,n.setAttribute("aria-label",o),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n}))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(e){const t=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(t<=0||i<=0)return;const n=Ri.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const o=Number(r.dataset.t);Math.abs(o-e)>n||(!s||Math.abs(o-e)<Math.abs(s.t-e))&&(s={t:o,name:r.title})}return s}snapSeekToMark(e){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(e)?.t??e):e}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=(e.clientX-t.left)/t.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?wf(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,!t)return;const i=document.createElement("b");i.textContent=this.said.read(t.label)??"";const n=this.said.read(t.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(e=this.currentTime){const t=Cn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<Ri.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(Ri.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/Ri.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/Ri.EXPOSURE_STEP_PX),s=Math.min(Ri.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let o=0;o<s;o++)r.push(t.fromMs+t.ms*o/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,o]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(e,t,i){for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,e,t,i);if(s)return s}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);n&&t.set(i,n)}return t}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const e=ni.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===e)return;this.canvas.width=e,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${e} / ${this.canvas.height}`)}canvasPointFromEvent(e){const t=this.canvas.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*this.canvas.width,y:(e.clientY-t.top)/t.height*this.canvas.height}}onFrame(e,t){this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:C2;this.canvasRenderer.setStarPoints(ni.starPointsOf(this.sighting.instrument));const n=(Jt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of s)for(const[,c]of o.shapes){const l=o.share,h=l===1?c:{...c,transparency:1-(1-c.transparency)*l};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,c]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));if(this.selectionShown&&i.size>1){const o=cn.groupBoundsFor([...t].filter(([c])=>i.has(c)).map(([,c])=>c.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(dg(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:e}}))}shifted(e,t){return t.x===0&&t.y===0?e:{...e,bounds:{...e.bounds,x:e.bounds.x+t.x,y:e.bounds.y+t.y}}}createPlayer(){const e=new Jv(this.currentSighting.timeline,(t,i)=>this.onFrame(t,i));return e.loop=this.loopEnabled,e.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},e}static SEEK_KEY_STEP_MS=5e3;handleSeekKey=e=>{if(e.altKey||e.ctrlKey||e.metaKey)return;const t=e.key==="ArrowLeft"?-1:e.key==="ArrowRight"?1:0;if(t){e.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+t*Ri.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){this.player.seekableDuration<=0||(this.player.playbackState==="playing"?(this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh()):(this.sightingAudio.resume(),this.player.play()),this.updatePlayPauseButton(),this.flashPlayback())}flashPlayback(){const e=this.playbackFlash;e.textContent=this.player.playbackState==="playing"?"▶":"⏸",e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.playPauseButton.textContent=e?"⏸":"▶";const t=this.player.seekableDuration>0;this.playPauseButton.disabled=!t;const i=t?e?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 e=this.playbackBeforeClick;e&&(this.currentTime=e.time,e.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(e=>{console.error("<rr0-ufo>: requestFullscreen() failed —",e)})}enterSimulatedFullscreen(){const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=e.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const t=e.style;t.setProperty("position","fixed"),t.setProperty("inset","0"),t.setProperty("margin","0"),t.setProperty("max-width","none"),t.setProperty("max-height","none"),t.setProperty("aspect-ratio","auto"),t.setProperty("z-index","2147483647"),t.setProperty("background","#000"),t.setProperty("width","100vw"),t.setProperty("width","100dvw"),t.setProperty("height","100vh"),t.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const e=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?e.setAttribute("style",this.styleBeforeSimulatedFullscreen):e.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear()}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(Ss),t=e===null?this.observerPath?.travels===!0:e!=="false";this.setObserverMapOpen(t&&this.observerPath!==void 0)}setObserverMapOpen(e){this.observerMapPanel.hidden=!e,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(e)),this.updateObserverMapButton(),e&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden?this.messages.hideObserverMap:this.messages.showObserverMap;this.observerMapButton.title=t,this.observerMapButton.setAttribute("aria-label",t);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 e=this.observerPath!==void 0;if(this.observerPath=ba.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!e&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const t=this.observerPath.boundsAround(Ri.OBSERVER_MAP_MIN_SPAN_M,Ri.OBSERVER_MAP_MARGIN);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,t))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,t),this.observerMapBounds=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(e,t){const i=Math.abs(e.east-e.west)/20;return Math.abs(e.north-t.north)<i&&Math.abs(e.south-t.south)<i&&Math.abs(e.west-t.west)<i&&Math.abs(e.east-t.east)<i}async loadObserverMapImagery(){const e=this.observerMapViewBounds;if(!e||this.observerMapPanel.hidden||!this.observerMapImageryNeededFor(e))return;this.observerMapImageryBounds=e;const t=Rg();try{const i=await t.getImageryTexture(e,{width:Ri.OBSERVER_MAP_IMAGERY_PX,height:Ri.OBSERVER_MAP_IMAGERY_PX});if(this.observerMapImageryBounds!==e)return;this.observerMapImagery=i,this.observerMapImageryCredit=t.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==e)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}this.paintObserverMap(this.currentTime)}observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=e.west>=i.west&&e.east<=i.east&&e.south>=i.south&&e.north<=i.north,s=e.east-e.west>(t.east-t.west)/2;return!n||!s}get observerMapCredit(){return this.observerMapImageryCredit}get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages.mapImageryUnavailable:this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(e){this.mapSceneBounds=e.map(t=>({x:t.x*this.canvas.width,y:t.y*this.canvas.height,width:t.width*this.canvas.width,height:t.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const e=this.observerMapBoxPx;if(!e)return;const t=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of t)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>e.bottom+u||d.y+d.height<e.top-u))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=Ri.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(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 e=this.observerMapPanel.clientWidth;if(e===0)return;const t=Math.round(e*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==t&&(this.observerMapCanvas.width=t,this.observerMapCanvas.height=t)}measureObserverMapBox(){const e=this.observerMapPanel.getBoundingClientRect(),t=this.canvas.getBoundingClientRect();if(t.width===0||t.height===0)return;const i=this.canvas.width/t.width,n=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*n,bottom:(e.bottom-t.top)*n}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=Jt(this.currentSighting,e),i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?wf(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Ml(this.currentSighting.milestones):[]){const o=Jt(this.currentSighting,r.t);o?.lat===void 0||o.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:o.lat,lng:o.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?_s.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(ni.aspectOf(i)):void 0,markers:n,decor:this.observerMapDecorAt(e),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages.observerHere,nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(e){this.milestonesShown=e,this.milestoneMarks.hidden=!e,this.milestonesButton.setAttribute("aria-pressed",String(e)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0;const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=Jt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Pa(i,e),{lat:s,lng:r}=ys(n.eastM,-n.northM,t.lat,t.lng);return{lat:s,lng:r,headingDeg:n.headingDeg,label:this.said.read(i.title)??this.messages.decorHere}})}observerMapNightFraction;setSunAltitude(e){const t=e===void 0?void 0:Math.max(0,Math.min(1,-e/12));t!==this.observerMapNightFraction&&(this.observerMapNightFraction=t,this.paintObserverMap(this.currentTime))}setLookOffset(e,t){e===this.lookYawDeg&&t===this.lookPitchDeg||(this.lookYawDeg=e,this.lookPitchDeg=t,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const e=this.gaitAt(this.currentTime),t=this.lookYawDeg+e.yawDeg,i=this.lookPitchDeg+e.pitchDeg;if(t===0&&i===0)return{x:0,y:0};const n=Jt(this.currentSighting,this.currentTime),s=_s.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return xt.bodyAt(this.currentSighting,e,this.steadyObserver)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Pn(Ir.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=Fo(Ir.preferencesFor(this),Mg);e!=="en"&&this.applyMessages(await h2(e))}updateTimeLabelTitles(){const e=this.showClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime,t=this.canSwitchTimeDisplay?` — ${e}`:"";this.timeStartLabel.title=this.messages.currentPosition+t,this.timeEndLabel.title=this.messages.duration+t;for(const i of[this.timeStartLabel,this.timeEndLabel])i.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateMilestonesButton()}updateTimeLabels(){const e=this.currentSighting.event,t=ug(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?Tu(e.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.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return rc(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?Df(Rf(this.realStartMs+i)):rc(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?rc(this.currentSighting.timeline.duration):this.canShowClockTime?Df(Rf(this.realStartMs+this.realDurationMs)):rc(this.realDurationMs)}}function Rf(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function Df(a){if(a.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return a.second?`${e(a.hour)}:${e(a.minute??0)}:${e(a.second)}`:`${e(a.hour)}:${e(a.minute??0)}`}function rc(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Du="rr0-ufo";function Dg(){customElements.get(Du)||customElements.define(Du,Ri)}/**
|
|
1194
1194
|
* @license
|
|
1195
1195
|
* Copyright 2010-2026 Three.js Authors
|
|
1196
1196
|
* SPDX-License-Identifier: MIT
|
|
@@ -7035,7 +7035,7 @@ void main()
|
|
|
7035
7035
|
if (ice <= 0.0) discard;
|
|
7036
7036
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
7037
7037
|
}
|
|
7038
|
-
`,transparent:!0,blending:Oi,depthWrite:!1,side:Bt,fog:!1}),this.object=new Re(new ri(Ci.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,n,s,r){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(n[0],n[1],n[2]),o.uIceCover.value=s.cover,o.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r)}requestMap(e,t){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<Ci.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Ci.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<Ci.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Ci.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.sky.begin(e,t),this.tracing=!0,this.scheduleWork()}pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;next;tracingFor(e,t){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<Ci.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Ci.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?Ci.URGENT_BUDGET_MS:Ci.BUDGET_MS;do this.sky.trace(Ci.RAYS_PER_BATCH);while(this.sky.tracedRays<Ci.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Ci.RAYS){this.publish(),this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment;const s=this.next;s&&this.requestMap(s.sourceAltitudeDeg,s.alignment);return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}stopWork(){this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){const t=this.sky.harvest().data;for(let i=0,n=0;n<t.length;i+=4,n+=3)this.texels[i]=Fn.toHalfFloat(t[n]),this.texels[i+1]=Fn.toHalfFloat(t[n+1]),this.texels[i+2]=Fn.toHalfFloat(t[n+2]),this.texels[i+3]=1;this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class gi{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=gi.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(gi.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=gi.MAX_CONCURRENT*gi.SEGMENTS*gi.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ot;t.setAttribute("position",new tt(this.positions,3)),t.setAttribute("color",new tt(this.colors,3)),t.setDrawRange(0,0),this.object=new Re(t,new yn({vertexColors:!0,transparent:!0,blending:Oi,depthWrite:!1,fog:!1,side:ji})),this.object.frustumCulled=!1}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.meteors.length===0){t.setDrawRange(0,0);return}const i=Pr.aliveAt(this.meteors,e).slice(0,gi.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const c=ci(o.altitudeDeg,o.azimuthDeg,1),[l,h]=this.basisAround(c),u=s.fromRadiantDeg+r*s.lengthDeg,d=Math.max(s.fromRadiantDeg,u-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(l,h,s.bearingDeg),v=(.15+.85*s.brightness)*f,m=b=>v*b**1.6,g=b=>this.onSphere(c,p,d+(u-d)*b),y=b=>gi.RADIUS*((gi.MIN_HALF_WIDTH_DEG+gi.BRIGHT_HALF_WIDTH_DEG*s.brightness*b)*Math.PI/180);for(let b=1;b<gi.POINTS;b++){const M=(b-1)/gi.SEGMENTS,S=b/gi.SEGMENTS;n=this.pushRibbon(n,g(M),g(S),y(M),y(S),m(M),m(S))}}t.setDrawRange(0,n),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=ci(t.altitudeDeg,t.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,e.bearingDeg),o=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),c=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/c)*180/Math.PI,azimuthDeg:(Math.atan2(o.x,-o.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,n,s,r,o){const c=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let l=0;l<gi.ACROSS-1;l++){const h=l-1,u=l,d=this.across(t,c,n,h),f=this.across(i,c,s,h),p=this.across(t,c,n,u),v=this.across(i,c,s,u),m=(g,y)=>g===0?y:0;e=this.push(e,d,m(h,r)),e=this.push(e,f,m(h,o)),e=this.push(e,p,m(u,r)),e=this.push(e,f,m(h,o)),e=this.push(e,v,m(u,o)),e=this.push(e,p,m(u,r))}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i){const n=e*3;this.positions[n]=t.x,this.positions[n+1]=t.y,this.positions[n+2]=t.z;const s=Ee.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,e+1}turn(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:e.x*s+t.x*r,y:e.y*s+t.y*r,z:e.z*s+t.z*r}}onSphere(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(e.x*s+t.x*r)*gi.RADIUS,y:(e.y*s+t.y*r)*gi.RADIUS,z:(e.z*s+t.z*r)*gi.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class It{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??It.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??It.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??It.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??It.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(It.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const c of[-1,1]){const l=t-this.deck;l>0&&this.bank>0&&n.push(It.box(e+1,l,It.ABUTMENT_THICKNESS_M,0,l/2,c*(i-It.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(It.box(e,.04,this.span,0,t+.02,0));const r=[];for(const c of[-1,1])this.bank<=0||(r.push(this.embankment(c)),s.push(this.bankRoad(c)));const o=[];for(const c of[-1,1])o.push(...this.railing(c*(e/2-It.POST_SIDE_M)));return{concrete:It.merge(n),road:It.merge(s),earth:It.merge(r),railing:It.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(l,h,u,d)=>{n.push(l.x,l.y,l.z,h.x,h.y,h.z,u.x,u.y,u.z,l.x,l.y,l.z,u.x,u.y,u.z,d.x,d.y,d.z)},r=l=>{const h=this.roadAt(l),u=t+It.BANK_SLOPE*h;return{leftFoot:new R(-u,0,l),leftTop:new R(-t,h,l),rightTop:new R(t,h,l),rightFoot:new R(u,0,l)}};for(let l=1;l<i.length;l++){const h=r(i[l-1]),u=r(i[l]),d=e>0,f=(p,v,m,g)=>d?s(p,v,m,g):s(g,m,v,p);f(h.leftFoot,h.leftTop,u.leftTop,u.leftFoot),f(h.leftTop,h.rightTop,u.rightTop,u.leftTop),f(h.rightTop,h.rightFoot,u.rightFoot,u.rightTop)}const o=r(i[0]);e>0?s(o.leftFoot,o.rightFoot,o.rightTop,o.leftTop):s(o.leftTop,o.rightTop,o.rightFoot,o.leftFoot);const c=new ot;return c.setAttribute("position",new ut(n,3)),c.computeVertexNormals(),c}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),n=[];for(let r=1;r<i.length;r++){const o=i[r-1],c=i[r],l=this.roadAt(o)+.02,h=this.roadAt(c)+.02,u=e>0?[[-t,l,o],[t,l,o],[t,h,c],[-t,h,c]]:[[-t,h,c],[t,h,c],[t,l,o],[-t,l,o]];for(const d of[0,2,1,0,3,2])n.push(...u[d])}const s=new ot;return s.setAttribute("position",new ut(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=It.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/It.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let o=0;o<=i;o++)n.push(-t+this.size.lengthM*o/i);const s=[],r=It.POST_SIDE_M;for(const o of n)s.push(It.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const c=this.railHeight*o/this.rails-It.RAIL_HEIGHT_M/2;for(let l=1;l<n.length;l++){const h=new R(e,this.roadAt(n[l-1])+c,n[l-1]),u=new R(e,this.roadAt(n[l])+c,n[l]);s.push(It.beam(h,u))}}return s}static box(e,t,i,n,s,r){return new Vi(e,t,i).translate(n,s,r)}static beam(e,t){const i=new R().subVectors(t,e),n=new Vi(It.RAIL_DEPTH_M,It.RAIL_HEIGHT_M,i.length()),s=new Qi().setFromUnitVectors(new R(0,0,1),i.clone().normalize()),r=new R().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new Ze().compose(r,s,new R(1,1,1)))}static merge(e){const t=e.map(c=>c.getIndex()?c.toNonIndexed():c),i=t.reduce((c,l)=>c+l.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const c of t){const l=c.getAttribute("position"),h=c.getAttribute("normal");n.set(l.array,r*3),h&&s.set(h.array,r*3),r+=l.count}const o=new ot;o.setAttribute("position",new ut(n,3)),o.setAttribute("normal",new ut(s,3));for(const c of e)c.dispose();for(const c of t)c.dispose();return o}}const jh=Math.PI/180;function Ot(a,e,t,i,n=!1){const s=n?new yn({color:new se(...t)}):new za({color:new se(...t)}),r=new Re(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const Qh=.25,C5=.002,I5=100,P5=1500,L5=.25,O5=1e3,N5=.15;function F5(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return[1,1,1];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const U5=[.32,.32,.3],V1=[1,.85,.5],k5=[.25,.25,.25],W1=[1,.97,.85],z5=[.55,.68,.72],Zn=.03,Jn=.05,X1={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function zi(a,e){return a?.[e]}function jn(a,e,t,i,n,s,r,o){if(o===void 0)return;const c=new za({color:new se(...z5),transparent:!0,opacity:o/100}),l=new Re(new Vi(e,t,i),c);l.position.set(n,s,r),a.add(l)}const vn=.05,eu=[.6,.58,.53],dm=[.5,.5,.48];function ya(a,e,t,i,n,s,r,o){const c=new za({color:new se(...o),side:Bt}),l=new Re(new Vi(e,t,i),c);l.position.set(n,s,r),a.add(l)}function B5(a,e,t,i,n,s,r,o,c){const l=(i-s)/2,h=(p,v,m,g)=>{p<=0||(e?ya(a,p,v,vn,m,o+g,r,c):ya(a,vn,v,p,r,o+g,m,c))};h(t,l,0,i/2-l/2),h(t,l,0,-(i/2-l/2));const u=[...n].sort((p,v)=>p.center-v.center);let d=-t/2;for(const p of u){const m=p.center-p.main/2-d;h(m,s,d+m/2,0),d=p.center+p.main/2}const f=t/2-d;h(f,s,d+f/2,0)}function Y1(a,e,t,i,n,s,r,o,c,l){const h=(i+n)/2,u=n-i,d=(f,p,v,m)=>{f.length===0?p?ya(a,v,u,vn,0,h,m,eu):ya(a,vn,u,v,m,h,0,eu):B5(a,p,v,u,f,s,m,h,eu)};d(r,!0,e*2,-t+vn),d(o,!0,e*2,t-vn),d(c,!1,t*2,-e+vn),d(l,!1,t*2,e-vn),ya(a,e*2,vn,t*2,0,i+vn,0,dm),ya(a,e*2,vn,t*2,0,n-vn,0,dm)}function qd(a,e,t,i){switch(a){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-Qn};case"front-right":return{x:e-i,z:-Qn};case"behind-left":return{x:-(e-i),z:Qn};case"behind-right":return{x:e-i,z:Qn}}}function q1(a,e,t,i,n,s,r){const o=Zd();o.scale.setScalar(i),o.rotation.y=X1[e];const{x:c,z:l}=qd(e,n,s,r);o.position.set(c,t,l),a.add(o)}const $d=6,Kd=6,Ks=3,ao=1.4,oo=Ks*.5,$1=1.2,K1=.35,H5=.75,G5=1.6;function fm(a,e,t,i){const n=new Rt,s=Math.max(1,a+1),r=s*Ks;Ot(n,new Vi($d,r,Kd),[.55,.54,.5],r/2);const o=$d/2,c=Kd/2;for(let l=0;l<s;l++){const h=l*Ks+Ks/2;jn(n,ao,oo,Jn,0,h,-c-Zn,zi(e,"front")),jn(n,ao,oo,Jn,0,h,c+Zn,zi(e,"behind")),jn(n,Jn,oo,ao,-o-Zn,h,0,zi(e,"left")),jn(n,Jn,oo,ao,o+Zn,h,0,zi(e,"right"))}if(t){const l=Math.min(Math.max(i??0,0),s-1);q1(n,t,l*Ks,.72,o,c,$1);const h=u=>zi(e,u)!==void 0?[{main:ao,center:0}]:[];Y1(n,o,c,l*Ks,(l+1)*Ks,oo,h("front"),h("behind"),h("left"),h("right"))}return n}function pm(){const a=new Rt,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,n,s]of e){const r=new ri(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Ot(a,r,[.26,.28,.17],s)}return a}function V5(a){const e=new Rt,t=new It(li.sizeOf(a),a.bridge).build();Ot(e,t.concrete,[.6,.6,.58],0);const i=Ot(e,t.road,[.2,.2,.21],0),n=Ot(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=ji;return Ot(e,t.railing,[.5,.52,.55],0),e}function mm(){const a=new Rt;return Ot(a,new as(.15,.22,2,8),[.32,.22,.14],1),Ot(a,new ka(1.4,3,8),[.16,.32,.14],3.5),a}const gm=.275,W5=.35,X5=.9,Y5=34,q5=8,$5=1.4;function vm(){const a=new Rt,e=new ri(gm,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,W5/gm,1);const t=li.repeatOnGrid(e,Y5,X5,q5,$5),i=Ot(a,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),a}function Mm(){const a=new Rt,e=new ri(1,7,3,0,Math.PI*2,0,Math.PI/2);return Ot(a,e,[.38,.36,.32],0),a}function xm(a){const e=new Rt;return Ot(e,new as(.05,.08,5,8),[.28,.28,.3],2.5),Ot(e,new ri(.25,12,8),a?V1:U5,5.1,!0),e}const K5=[.08,.08,.08],Xs=.8,pa=1,Yn=1.7,tu=.6,pr=.4,Wc=1.2,ua=.7,Qn=.5,Z5=Yn;function ym(a,e,t){const i=new Rt;Ot(i,new Vi(1.8,1.4,4.2),[.45,.14,.14],.7),Ot(i,new Vi(Xs*2,tu,pa*2),[.4,.12,.12],Yn);for(const s of[-1.4,1.4])for(const r of[-.95,.95]){const o=Ot(i,new as(.4,.4,.3,12),K5,.4);o.rotation.z=Math.PI/2,o.position.x=r,o.position.z=s}const n=a?W1:k5;for(const s of[-.7,.7])Ot(i,new ri(.15,8,6),n,.7,!0).position.set(s,.7,-2.1);if(jn(i,Wc,pr,Jn,0,Yn,-pa-Zn,zi(e,"front")),jn(i,Wc,pr,Jn,0,Yn,pa+Zn,zi(e,"behind")),jn(i,Jn,pr,ua,-Xs-Zn,Yn,-Qn,zi(e,"front-left")),jn(i,Jn,pr,ua,-Xs-Zn,Yn,Qn,zi(e,"behind-left")),jn(i,Jn,pr,ua,Xs+Zn,Yn,-Qn,zi(e,"front-right")),jn(i,Jn,pr,ua,Xs+Zn,Yn,Qn,zi(e,"behind-right")),t){q1(i,t,H5,.5,Xs,pa,K1);const s=(c,l)=>{const h=[];return zi(e,c)!==void 0&&h.push({main:ua,center:-Qn}),zi(e,l)!==void 0&&h.push({main:ua,center:Qn}),h},r=zi(e,"front")!==void 0?[{main:Wc,center:0}]:[],o=zi(e,"behind")!==void 0?[{main:Wc,center:0}]:[];Y1(i,Xs,pa,Yn-tu/2,Yn+tu/2,pr,r,o,s("front-left","behind-left"),s("front-right","behind-right"))}return i}const _m=new Map;function bm(a,e){if(!a)return;const t=[[a.lengthM,e.lengthM],[a.heightM,e.heightM],[a.widthM,e.widthM]];for(const[i,n]of t)if(i!==void 0&&n>1e-6)return i/n}function iu(a,e){return e>1e-6?a/e:1}const Z1=[.95,.9,.82],Sm=[.72,.74,.78];function wm(){const a=new Rt;Ot(a,new as(.25,.3,1.5,10),Sm,.75),Ot(a,new ri(.26,10,8),Sm,1.74);const e=Ot(a,new ka(.07,.16,8),Z1,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function Zd(){const a=new Rt;Ot(a,new as(.25,.3,1.5,10),[.3,.3,.35],.75),Ot(a,new ri(.22,10,8),[.62,.52,.46],1.72);const e=Ot(a,new ka(.07,.16,8),Z1,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const J5=17,Em=18.5,nu=[.16,.16,.18];function Am(){const a=new Rt,e=Ot(a,new as(1.8,1.8,Em*2,10),nu,0);e.rotation.x=Math.PI/2,Ot(a,new Vi(J5*2,.5,4.5),nu,0);const t=Ot(a,new Vi(.4,5.5,4),nu,3);return t.position.z=-Em+2,a}class li{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=li.sizeOf(e);if(r>o.heightM)return s(t,i);const c=(n??0)*Math.PI/180,l=Math.min(21,Math.max(2,Math.ceil(o.lengthM/.75)+1)),h=Math.min(21,Math.max(2,Math.ceil(o.widthM/.75)+1)),u=li.GROWS_FROM_GROUND.has(e.kind);let d=u?1/0:-1/0;for(let f=0;f<l;f++){const p=(f/(l-1)-.5)*o.lengthM;for(let v=0;v<h;v++){const m=(v/(h-1)-.5)*o.widthM,g=t+Math.sin(c)*p+Math.cos(c)*m,y=i-Math.cos(c)*p+Math.sin(c)*m;d=u?Math.min(d,s(g,y)):Math.max(d,s(g,y))}}return Number.isFinite(d)?d:s(t,i)}static occupantView(e){const t=e.observerSide;if(!t)throw new Error("occupantView requires object.observerSide to be set");const{x:i,z:n}=e.kind==="vehicle"?qd(t,Xs,pa,K1):qd(t,$d/2,Kd/2,$1),s=e.kind==="vehicle"?Z5:(e.occupiedFloor??0)*Ks+G5,r=(e.headingDeg??0)-X1[t]/jh,o=this.scaleFor(e);return{x:i*o.x,z:n*o.z,eyeY:s*o.y,headingDeg:r}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName(li.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),c=e.getIndex();if(!c)throw new Error("repeatOnGrid needs an indexed geometry");const l=r.count,h=t*n,u=new Float32Array(l*h*3),d=new Float32Array(l*h*3),f=new Uint32Array(c.count*h),p=-((t-1)*i)/2,v=-((n-1)*s)/2;let m=0;for(let y=0;y<n;y++)for(let b=0;b<t;b++,m++){const M=v+y*s,S=p+b*i;for(let w=0;w<l;w++){const T=(m*l+w)*3;u[T]=r.getX(w)+M,u[T+1]=r.getY(w),u[T+2]=r.getZ(w)+S,d[T]=o.getX(w),d[T+1]=o.getY(w),d[T+2]=o.getZ(w)}for(let w=0;w<c.count;w++)f[m*c.count+w]=c.getX(w)+m*l}const g=new ot;return g.setAttribute("position",new ut(u,3)),g.setAttribute("normal",new ut(d,3)),g.setIndex(new M0(f,1)),g}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new R;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const c=s.geometry.getAttribute("position"),l=new Ze().copy(s.matrixWorld).invert();for(let h=0;h<c.count;h+=o){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(l);for(let u=h;u<h+o;u++)c.setY(u,r[u*3+1]+i.y)}c.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static paint(e,t){e.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(t)})}static build(e,t){const i=e.kind==="building"?fm(e.floors??rf,e.windows,e.observerSide,e.occupiedFloor):e.kind==="tree"?mm():e.kind==="shrub"?pm():e.kind==="bridge"?V5(e):e.kind==="crop"?vm():e.kind==="mound"?Mm():e.kind==="streetlight"?xm(t):e.kind==="vehicle"?ym(t,e.windows,e.observerSide):e.kind==="aircraft"?Am():e.kind==="entity"?wm():Zd();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Rt;return i.name=li.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*jh),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge")return new R(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new R(t.widthM===void 0?1:iu(t.widthM,i.widthM),t.heightM===void 0?1:iu(t.heightM,i.heightM),t.lengthM===void 0?1:iu(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??rf)+1):0;if(e==="bridge")return It.NATURAL_SIZE;const n=`${e}:${i}`,s=_m.get(n);if(s)return s;const r=e==="building"?fm(i-1,void 0,void 0,void 0):e==="tree"?mm():e==="shrub"?pm():e==="crop"?vm():e==="mound"?Mm():e==="streetlight"?xm(!1):e==="vehicle"?ym(!1,void 0,void 0):e==="aircraft"?Am():e==="entity"?wm():Zd(),o=new Gi().setFromObject(r),c={widthM:o.max.x-o.min.x,heightM:o.max.y-o.min.y,lengthM:o.max.z-o.min.z};return this.dispose(r),_m.set(n,c),c}static usesModel(e){return e.model!==void 0&&!(e.observerSide!==void 0&&fg(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Rt;r.name=li.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*jh,i.updateMatrixWorld(!0);const o=new Gi().setFromObject(i),c={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},l=bm(t.sizeM,c)??bm(n.depictedSizeM,c)??1;i.scale.multiplyScalar(l);const h=o.getCenter(new R).multiplyScalar(l);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*l,i.traverse(u=>{u instanceof Re&&(u.castShadow=!0,u.receiveShadow=!0)}),r.add(i),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s)}static sizeOf(e){const t=this.naturalSize(e.kind,e.floors);return{widthM:e.sizeM?.widthM??t.widthM,lengthM:e.sizeM?.lengthM??t.lengthM,heightM:e.sizeM?.heightM??t.heightM}}static addLights(e,t){for(const i of t??[]){const n=F5(i.color),s=Ot(e,new ri(Qh,8,6),n,i.offsetM.y,!0);s.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),s.userData={emissive:!0,lightId:i.id,lightColor:n},s.visible=!1}}static setLights(e,t,i,n,s=0,r=1,o=C5){if(!t||t.length===0)return;const c=new Map(t.map(d=>[d.id,d])),l=Math.max(1,n*o/Qh),h=Qh*l,u=r/(Math.PI*h*h);for(const d of e.children){if(!(d instanceof Re))continue;const f=d.userData.lightId;if(!f)continue;const p=c.get(f);if(!p)continue;const v=s>0?mg(p,i,i+s):Ov(p,i)?1:0;d.visible=v>0;const m=d.material,g=d.userData.lightColor;if(g){const y=v*I5*(p.intensity??1)*u;m.color.setRGB(g[0]*y,g[1]*y,g[2]*y)}d.scale.setScalar(l)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[P5,L5,V1]:[O5,N5,W1],c=i?s*n/(Math.PI*r*r):0,l=[o[0]*c,o[1]*c,o[2]*c];e.traverse(h=>{const u=h.userData;!(h instanceof Re)||!u.emissive||u.lightId||h.material.color.setRGB(...l)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Re))return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const su="https://ufoathome.org/models/index.json";class j5{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Q5()}async entries(e){const t=await this.load();return e?t.filter(i=>i.kind===e):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){return this.loading??=this.fetchFirstAvailable(),this.loading}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function Q5(){const a=`?v=${encodeURIComponent("0.69.2")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==su?[e,su]:[su]).map(t=>t+a)}const eE=[{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 j5}];async function Tm(a){const{GLTFLoader:e}=await As(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-D3g0zZHB.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(a,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${a}: ${s instanceof Error?s.message:String(s)}`)))})}const J1=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class ln{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Re(new Wi(2,2),new ct({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:ln.VERTEX,fragmentShader:ln.FRAGMENT,transparent:!0,depthWrite:!1,blending:Oi,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,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(e,t,i,n){const s=Math.max(e,n*ln.MIN_ANGLE_RAD),r=ln.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(ln.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(ln.MAX_SHARE*ln.FILL*Math.PI))}static VERTEX=`
|
|
7038
|
+
`,transparent:!0,blending:Oi,depthWrite:!1,side:Bt,fog:!1}),this.object=new Re(new ri(Ci.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,n,s,r){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(n[0],n[1],n[2]),o.uIceCover.value=s.cover,o.uIceHeight.value=s.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r)}requestMap(e,t){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<Ci.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Ci.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<Ci.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Ci.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.sky.begin(e,t),this.tracing=!0,this.scheduleWork()}pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;next;tracingFor(e,t){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<Ci.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Ci.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?Ci.URGENT_BUDGET_MS:Ci.BUDGET_MS;do this.sky.trace(Ci.RAYS_PER_BATCH);while(this.sky.tracedRays<Ci.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Ci.RAYS){this.publish(),this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment;const s=this.next;s&&this.requestMap(s.sourceAltitudeDeg,s.alignment);return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}stopWork(){this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){const t=this.sky.harvest().data;for(let i=0,n=0;n<t.length;i+=4,n+=3)this.texels[i]=Fn.toHalfFloat(t[n]),this.texels[i+1]=Fn.toHalfFloat(t[n+1]),this.texels[i+2]=Fn.toHalfFloat(t[n+2]),this.texels[i+3]=1;this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class gi{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=gi.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(gi.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=gi.MAX_CONCURRENT*gi.SEGMENTS*gi.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new ot;t.setAttribute("position",new tt(this.positions,3)),t.setAttribute("color",new tt(this.colors,3)),t.setDrawRange(0,0),this.object=new Re(t,new yn({vertexColors:!0,transparent:!0,blending:Oi,depthWrite:!1,fog:!1,side:ji})),this.object.frustumCulled=!1}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.meteors.length===0){t.setDrawRange(0,0);return}const i=Pr.aliveAt(this.meteors,e).slice(0,gi.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const c=ci(o.altitudeDeg,o.azimuthDeg,1),[l,h]=this.basisAround(c),u=s.fromRadiantDeg+r*s.lengthDeg,d=Math.max(s.fromRadiantDeg,u-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(l,h,s.bearingDeg),v=(.15+.85*s.brightness)*f,m=b=>v*b**1.6,g=b=>this.onSphere(c,p,d+(u-d)*b),y=b=>gi.RADIUS*((gi.MIN_HALF_WIDTH_DEG+gi.BRIGHT_HALF_WIDTH_DEG*s.brightness*b)*Math.PI/180);for(let b=1;b<gi.POINTS;b++){const M=(b-1)/gi.SEGMENTS,S=b/gi.SEGMENTS;n=this.pushRibbon(n,g(M),g(S),y(M),y(S),m(M),m(S))}}t.setDrawRange(0,n),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=ci(t.altitudeDeg,t.azimuthDeg,1),[n,s]=this.basisAround(i),r=this.turn(n,s,e.bearingDeg),o=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),c=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/c)*180/Math.PI,azimuthDeg:(Math.atan2(o.x,-o.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,n,s,r,o){const c=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let l=0;l<gi.ACROSS-1;l++){const h=l-1,u=l,d=this.across(t,c,n,h),f=this.across(i,c,s,h),p=this.across(t,c,n,u),v=this.across(i,c,s,u),m=(g,y)=>g===0?y:0;e=this.push(e,d,m(h,r)),e=this.push(e,f,m(h,o)),e=this.push(e,p,m(u,r)),e=this.push(e,f,m(h,o)),e=this.push(e,v,m(u,o)),e=this.push(e,p,m(u,r))}return e}across(e,t,i,n){return{x:e.x+t.x*i*n,y:e.y+t.y*i*n,z:e.z+t.z*i*n}}push(e,t,i){const n=e*3;this.positions[n]=t.x,this.positions[n+1]=t.y,this.positions[n+2]=t.z;const s=Ee.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[n]=s*.9,this.colors[n+1]=s*.95,this.colors[n+2]=s,e+1}turn(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:e.x*s+t.x*r,y:e.y*s+t.y*r,z:e.z*s+t.z*r}}onSphere(e,t,i){const n=i*Math.PI/180,s=Math.cos(n),r=Math.sin(n);return{x:(e.x*s+t.x*r)*gi.RADIUS,y:(e.y*s+t.y*r)*gi.RADIUS,z:(e.z*s+t.z*r)*gi.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class It{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??It.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??It.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??It.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??It.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,n=[];if(this.span>0){n.push(It.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const c of[-1,1]){const l=t-this.deck;l>0&&this.bank>0&&n.push(It.box(e+1,l,It.ABUTMENT_THICKNESS_M,0,l/2,c*(i-It.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(It.box(e,.04,this.span,0,t+.02,0));const r=[];for(const c of[-1,1])this.bank<=0||(r.push(this.embankment(c)),s.push(this.bankRoad(c)));const o=[];for(const c of[-1,1])o.push(...this.railing(c*(e/2-It.POST_SIDE_M)));return{concrete:It.merge(n),road:It.merge(s),earth:It.merge(r),railing:It.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(l,h,u,d)=>{n.push(l.x,l.y,l.z,h.x,h.y,h.z,u.x,u.y,u.z,l.x,l.y,l.z,u.x,u.y,u.z,d.x,d.y,d.z)},r=l=>{const h=this.roadAt(l),u=t+It.BANK_SLOPE*h;return{leftFoot:new R(-u,0,l),leftTop:new R(-t,h,l),rightTop:new R(t,h,l),rightFoot:new R(u,0,l)}};for(let l=1;l<i.length;l++){const h=r(i[l-1]),u=r(i[l]),d=e>0,f=(p,v,m,g)=>d?s(p,v,m,g):s(g,m,v,p);f(h.leftFoot,h.leftTop,u.leftTop,u.leftFoot),f(h.leftTop,h.rightTop,u.rightTop,u.leftTop),f(h.rightTop,h.rightFoot,u.rightFoot,u.rightTop)}const o=r(i[0]);e>0?s(o.leftFoot,o.rightFoot,o.rightTop,o.leftTop):s(o.leftTop,o.rightTop,o.rightFoot,o.leftFoot);const c=new ot;return c.setAttribute("position",new ut(n,3)),c.computeVertexNormals(),c}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),n=[];for(let r=1;r<i.length;r++){const o=i[r-1],c=i[r],l=this.roadAt(o)+.02,h=this.roadAt(c)+.02,u=e>0?[[-t,l,o],[t,l,o],[t,h,c],[-t,h,c]]:[[-t,h,c],[t,h,c],[t,l,o],[-t,l,o]];for(const d of[0,2,1,0,3,2])n.push(...u[d])}const s=new ot;return s.setAttribute("position",new ut(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=It.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/It.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),n=[];for(let o=0;o<=i;o++)n.push(-t+this.size.lengthM*o/i);const s=[],r=It.POST_SIDE_M;for(const o of n)s.push(It.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const c=this.railHeight*o/this.rails-It.RAIL_HEIGHT_M/2;for(let l=1;l<n.length;l++){const h=new R(e,this.roadAt(n[l-1])+c,n[l-1]),u=new R(e,this.roadAt(n[l])+c,n[l]);s.push(It.beam(h,u))}}return s}static box(e,t,i,n,s,r){return new Vi(e,t,i).translate(n,s,r)}static beam(e,t){const i=new R().subVectors(t,e),n=new Vi(It.RAIL_DEPTH_M,It.RAIL_HEIGHT_M,i.length()),s=new Qi().setFromUnitVectors(new R(0,0,1),i.clone().normalize()),r=new R().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new Ze().compose(r,s,new R(1,1,1)))}static merge(e){const t=e.map(c=>c.getIndex()?c.toNonIndexed():c),i=t.reduce((c,l)=>c+l.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const c of t){const l=c.getAttribute("position"),h=c.getAttribute("normal");n.set(l.array,r*3),h&&s.set(h.array,r*3),r+=l.count}const o=new ot;o.setAttribute("position",new ut(n,3)),o.setAttribute("normal",new ut(s,3));for(const c of e)c.dispose();for(const c of t)c.dispose();return o}}const jh=Math.PI/180;function Ot(a,e,t,i,n=!1){const s=n?new yn({color:new se(...t)}):new za({color:new se(...t)}),r=new Re(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const Qh=.25,C5=.002,I5=100,P5=1500,L5=.25,O5=1e3,N5=.15;function F5(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return[1,1,1];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const U5=[.32,.32,.3],V1=[1,.85,.5],k5=[.25,.25,.25],W1=[1,.97,.85],z5=[.55,.68,.72],Zn=.03,Jn=.05,X1={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function zi(a,e){return a?.[e]}function jn(a,e,t,i,n,s,r,o){if(o===void 0)return;const c=new za({color:new se(...z5),transparent:!0,opacity:o/100}),l=new Re(new Vi(e,t,i),c);l.position.set(n,s,r),a.add(l)}const vn=.05,eu=[.6,.58,.53],dm=[.5,.5,.48];function ya(a,e,t,i,n,s,r,o){const c=new za({color:new se(...o),side:Bt}),l=new Re(new Vi(e,t,i),c);l.position.set(n,s,r),a.add(l)}function B5(a,e,t,i,n,s,r,o,c){const l=(i-s)/2,h=(p,v,m,g)=>{p<=0||(e?ya(a,p,v,vn,m,o+g,r,c):ya(a,vn,v,p,r,o+g,m,c))};h(t,l,0,i/2-l/2),h(t,l,0,-(i/2-l/2));const u=[...n].sort((p,v)=>p.center-v.center);let d=-t/2;for(const p of u){const m=p.center-p.main/2-d;h(m,s,d+m/2,0),d=p.center+p.main/2}const f=t/2-d;h(f,s,d+f/2,0)}function Y1(a,e,t,i,n,s,r,o,c,l){const h=(i+n)/2,u=n-i,d=(f,p,v,m)=>{f.length===0?p?ya(a,v,u,vn,0,h,m,eu):ya(a,vn,u,v,m,h,0,eu):B5(a,p,v,u,f,s,m,h,eu)};d(r,!0,e*2,-t+vn),d(o,!0,e*2,t-vn),d(c,!1,t*2,-e+vn),d(l,!1,t*2,e-vn),ya(a,e*2,vn,t*2,0,i+vn,0,dm),ya(a,e*2,vn,t*2,0,n-vn,0,dm)}function qd(a,e,t,i){switch(a){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-Qn};case"front-right":return{x:e-i,z:-Qn};case"behind-left":return{x:-(e-i),z:Qn};case"behind-right":return{x:e-i,z:Qn}}}function q1(a,e,t,i,n,s,r){const o=Zd();o.scale.setScalar(i),o.rotation.y=X1[e];const{x:c,z:l}=qd(e,n,s,r);o.position.set(c,t,l),a.add(o)}const $d=6,Kd=6,Ks=3,ao=1.4,oo=Ks*.5,$1=1.2,K1=.35,H5=.75,G5=1.6;function fm(a,e,t,i){const n=new Rt,s=Math.max(1,a+1),r=s*Ks;Ot(n,new Vi($d,r,Kd),[.55,.54,.5],r/2);const o=$d/2,c=Kd/2;for(let l=0;l<s;l++){const h=l*Ks+Ks/2;jn(n,ao,oo,Jn,0,h,-c-Zn,zi(e,"front")),jn(n,ao,oo,Jn,0,h,c+Zn,zi(e,"behind")),jn(n,Jn,oo,ao,-o-Zn,h,0,zi(e,"left")),jn(n,Jn,oo,ao,o+Zn,h,0,zi(e,"right"))}if(t){const l=Math.min(Math.max(i??0,0),s-1);q1(n,t,l*Ks,.72,o,c,$1);const h=u=>zi(e,u)!==void 0?[{main:ao,center:0}]:[];Y1(n,o,c,l*Ks,(l+1)*Ks,oo,h("front"),h("behind"),h("left"),h("right"))}return n}function pm(){const a=new Rt,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,n,s]of e){const r=new ri(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Ot(a,r,[.26,.28,.17],s)}return a}function V5(a){const e=new Rt,t=new It(li.sizeOf(a),a.bridge).build();Ot(e,t.concrete,[.6,.6,.58],0);const i=Ot(e,t.road,[.2,.2,.21],0),n=Ot(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=ji;return Ot(e,t.railing,[.5,.52,.55],0),e}function mm(){const a=new Rt;return Ot(a,new as(.15,.22,2,8),[.32,.22,.14],1),Ot(a,new ka(1.4,3,8),[.16,.32,.14],3.5),a}const gm=.275,W5=.35,X5=.9,Y5=34,q5=8,$5=1.4;function vm(){const a=new Rt,e=new ri(gm,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,W5/gm,1);const t=li.repeatOnGrid(e,Y5,X5,q5,$5),i=Ot(a,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),a}function Mm(){const a=new Rt,e=new ri(1,7,3,0,Math.PI*2,0,Math.PI/2);return Ot(a,e,[.38,.36,.32],0),a}function xm(a){const e=new Rt;return Ot(e,new as(.05,.08,5,8),[.28,.28,.3],2.5),Ot(e,new ri(.25,12,8),a?V1:U5,5.1,!0),e}const K5=[.08,.08,.08],Xs=.8,pa=1,Yn=1.7,tu=.6,pr=.4,Wc=1.2,ua=.7,Qn=.5,Z5=Yn;function ym(a,e,t){const i=new Rt;Ot(i,new Vi(1.8,1.4,4.2),[.45,.14,.14],.7),Ot(i,new Vi(Xs*2,tu,pa*2),[.4,.12,.12],Yn);for(const s of[-1.4,1.4])for(const r of[-.95,.95]){const o=Ot(i,new as(.4,.4,.3,12),K5,.4);o.rotation.z=Math.PI/2,o.position.x=r,o.position.z=s}const n=a?W1:k5;for(const s of[-.7,.7])Ot(i,new ri(.15,8,6),n,.7,!0).position.set(s,.7,-2.1);if(jn(i,Wc,pr,Jn,0,Yn,-pa-Zn,zi(e,"front")),jn(i,Wc,pr,Jn,0,Yn,pa+Zn,zi(e,"behind")),jn(i,Jn,pr,ua,-Xs-Zn,Yn,-Qn,zi(e,"front-left")),jn(i,Jn,pr,ua,-Xs-Zn,Yn,Qn,zi(e,"behind-left")),jn(i,Jn,pr,ua,Xs+Zn,Yn,-Qn,zi(e,"front-right")),jn(i,Jn,pr,ua,Xs+Zn,Yn,Qn,zi(e,"behind-right")),t){q1(i,t,H5,.5,Xs,pa,K1);const s=(c,l)=>{const h=[];return zi(e,c)!==void 0&&h.push({main:ua,center:-Qn}),zi(e,l)!==void 0&&h.push({main:ua,center:Qn}),h},r=zi(e,"front")!==void 0?[{main:Wc,center:0}]:[],o=zi(e,"behind")!==void 0?[{main:Wc,center:0}]:[];Y1(i,Xs,pa,Yn-tu/2,Yn+tu/2,pr,r,o,s("front-left","behind-left"),s("front-right","behind-right"))}return i}const _m=new Map;function bm(a,e){if(!a)return;const t=[[a.lengthM,e.lengthM],[a.heightM,e.heightM],[a.widthM,e.widthM]];for(const[i,n]of t)if(i!==void 0&&n>1e-6)return i/n}function iu(a,e){return e>1e-6?a/e:1}const Z1=[.95,.9,.82],Sm=[.72,.74,.78];function wm(){const a=new Rt;Ot(a,new as(.25,.3,1.5,10),Sm,.75),Ot(a,new ri(.26,10,8),Sm,1.74);const e=Ot(a,new ka(.07,.16,8),Z1,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function Zd(){const a=new Rt;Ot(a,new as(.25,.3,1.5,10),[.3,.3,.35],.75),Ot(a,new ri(.22,10,8),[.62,.52,.46],1.72);const e=Ot(a,new ka(.07,.16,8),Z1,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const J5=17,Em=18.5,nu=[.16,.16,.18];function Am(){const a=new Rt,e=Ot(a,new as(1.8,1.8,Em*2,10),nu,0);e.rotation.x=Math.PI/2,Ot(a,new Vi(J5*2,.5,4.5),nu,0);const t=Ot(a,new Vi(.4,5.5,4),nu,3);return t.position.z=-Em+2,a}class li{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=li.sizeOf(e);if(r>o.heightM)return s(t,i);const c=(n??0)*Math.PI/180,l=Math.min(21,Math.max(2,Math.ceil(o.lengthM/.75)+1)),h=Math.min(21,Math.max(2,Math.ceil(o.widthM/.75)+1)),u=li.GROWS_FROM_GROUND.has(e.kind);let d=u?1/0:-1/0;for(let f=0;f<l;f++){const p=(f/(l-1)-.5)*o.lengthM;for(let v=0;v<h;v++){const m=(v/(h-1)-.5)*o.widthM,g=t+Math.sin(c)*p+Math.cos(c)*m,y=i-Math.cos(c)*p+Math.sin(c)*m;d=u?Math.min(d,s(g,y)):Math.max(d,s(g,y))}}return Number.isFinite(d)?d:s(t,i)}static occupantView(e){const t=e.observerSide;if(!t)throw new Error("occupantView requires object.observerSide to be set");const{x:i,z:n}=e.kind==="vehicle"?qd(t,Xs,pa,K1):qd(t,$d/2,Kd/2,$1),s=e.kind==="vehicle"?Z5:(e.occupiedFloor??0)*Ks+G5,r=(e.headingDeg??0)-X1[t]/jh,o=this.scaleFor(e);return{x:i*o.x,z:n*o.z,eyeY:s*o.y,headingDeg:r}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName(li.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),c=e.getIndex();if(!c)throw new Error("repeatOnGrid needs an indexed geometry");const l=r.count,h=t*n,u=new Float32Array(l*h*3),d=new Float32Array(l*h*3),f=new Uint32Array(c.count*h),p=-((t-1)*i)/2,v=-((n-1)*s)/2;let m=0;for(let y=0;y<n;y++)for(let b=0;b<t;b++,m++){const M=v+y*s,S=p+b*i;for(let w=0;w<l;w++){const T=(m*l+w)*3;u[T]=r.getX(w)+M,u[T+1]=r.getY(w),u[T+2]=r.getZ(w)+S,d[T]=o.getX(w),d[T+1]=o.getY(w),d[T+2]=o.getZ(w)}for(let w=0;w<c.count;w++)f[m*c.count+w]=c.getX(w)+m*l}const g=new ot;return g.setAttribute("position",new ut(u,3)),g.setAttribute("normal",new ut(d,3)),g.setIndex(new M0(f,1)),g}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new R;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const c=s.geometry.getAttribute("position"),l=new Ze().copy(s.matrixWorld).invert();for(let h=0;h<c.count;h+=o){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(s.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(l);for(let u=h;u<h+o;u++)c.setY(u,r[u*3+1]+i.y)}c.needsUpdate=!0,s.geometry.computeBoundingBox(),s.geometry.computeBoundingSphere()})}static paint(e,t){e.traverse(i=>{const n=i,s=n.userData;if(!n.isMesh||s?.emissive)return;const r=n.material;r?.color&&r.color.set(t)})}static build(e,t){const i=e.kind==="building"?fm(e.floors??rf,e.windows,e.observerSide,e.occupiedFloor):e.kind==="tree"?mm():e.kind==="shrub"?pm():e.kind==="bridge"?V5(e):e.kind==="crop"?vm():e.kind==="mound"?Mm():e.kind==="streetlight"?xm(t):e.kind==="vehicle"?ym(t,e.windows,e.observerSide):e.kind==="aircraft"?Am():e.kind==="entity"?wm():Zd();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Rt;return i.name=li.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*jh),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge")return new R(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new R(t.widthM===void 0?1:iu(t.widthM,i.widthM),t.heightM===void 0?1:iu(t.heightM,i.heightM),t.lengthM===void 0?1:iu(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??rf)+1):0;if(e==="bridge")return It.NATURAL_SIZE;const n=`${e}:${i}`,s=_m.get(n);if(s)return s;const r=e==="building"?fm(i-1,void 0,void 0,void 0):e==="tree"?mm():e==="shrub"?pm():e==="crop"?vm():e==="mound"?Mm():e==="streetlight"?xm(!1):e==="vehicle"?ym(!1,void 0,void 0):e==="aircraft"?Am():e==="entity"?wm():Zd(),o=new Gi().setFromObject(r),c={widthM:o.max.x-o.min.x,heightM:o.max.y-o.min.y,lengthM:o.max.z-o.min.z};return this.dispose(r),_m.set(n,c),c}static usesModel(e){return e.model!==void 0&&!(e.observerSide!==void 0&&fg(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Rt;r.name=li.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*jh,i.updateMatrixWorld(!0);const o=new Gi().setFromObject(i),c={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},l=bm(t.sizeM,c)??bm(n.depictedSizeM,c)??1;i.scale.multiplyScalar(l);const h=o.getCenter(new R).multiplyScalar(l);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*l,i.traverse(u=>{u instanceof Re&&(u.castShadow=!0,u.receiveShadow=!0)}),r.add(i),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s)}static sizeOf(e){const t=this.naturalSize(e.kind,e.floors);return{widthM:e.sizeM?.widthM??t.widthM,lengthM:e.sizeM?.lengthM??t.lengthM,heightM:e.sizeM?.heightM??t.heightM}}static addLights(e,t){for(const i of t??[]){const n=F5(i.color),s=Ot(e,new ri(Qh,8,6),n,i.offsetM.y,!0);s.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),s.userData={emissive:!0,lightId:i.id,lightColor:n},s.visible=!1}}static setLights(e,t,i,n,s=0,r=1,o=C5){if(!t||t.length===0)return;const c=new Map(t.map(d=>[d.id,d])),l=Math.max(1,n*o/Qh),h=Qh*l,u=r/(Math.PI*h*h);for(const d of e.children){if(!(d instanceof Re))continue;const f=d.userData.lightId;if(!f)continue;const p=c.get(f);if(!p)continue;const v=s>0?mg(p,i,i+s):Ov(p,i)?1:0;d.visible=v>0;const m=d.material,g=d.userData.lightColor;if(g){const y=v*I5*(p.intensity??1)*u;m.color.setRGB(g[0]*y,g[1]*y,g[2]*y)}d.scale.setScalar(l)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[P5,L5,V1]:[O5,N5,W1],c=i?s*n/(Math.PI*r*r):0,l=[o[0]*c,o[1]*c,o[2]*c];e.traverse(h=>{const u=h.userData;!(h instanceof Re)||!u.emissive||u.lightId||h.material.color.setRGB(...l)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Re))return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const su="https://ufoathome.org/models/index.json";class j5{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Q5()}async entries(e){const t=await this.load();return e?t.filter(i=>i.kind===e):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){return this.loading??=this.fetchFirstAvailable(),this.loading}async fetchFirstAvailable(){for(const e of this.indexUrls){const t=await this.fetchIndex(e);if(t)return t}return[]}async fetchIndex(e){try{const t=await this.fetchImpl(e);if(!t.ok)return;const i=await t.json();return Array.isArray(i?.models)?i.models.map(({file:n,...s})=>({...s,url:new URL(n,e).href})):void 0}catch{return}}}function Q5(){const a=`?v=${encodeURIComponent("0.70.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==su?[e,su]:[su]).map(t=>t+a)}const eE=[{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 j5}];async function Tm(a){const{GLTFLoader:e}=await As(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-D3g0zZHB.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(a,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${a}: ${s instanceof Error?s.message:String(s)}`)))})}const J1=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class ln{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Re(new Wi(2,2),new ct({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:ln.VERTEX,fragmentShader:ln.FRAGMENT,transparent:!0,depthWrite:!1,blending:Oi,toneMapped:!1})),this.mesh.name=e,this.mesh.frustumCulled=!1,this.mesh.renderOrder=t,this.mesh.visible=!1}shine(e,t,i){this.mesh.visible=!0,this.mesh.position.set(e.x,e.y,e.z),this.mesh.material.uniforms.uRadius.value=t,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(e,t,i,n){const s=Math.max(e,n*ln.MIN_ANGLE_RAD),r=ln.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(ln.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(ln.MAX_SHARE*ln.FILL*Math.PI))}static VERTEX=`
|
|
7039
7039
|
uniform float uRadius;
|
|
7040
7040
|
varying vec2 vOffset;
|
|
7041
7041
|
void main() {
|
|
@@ -7594,7 +7594,7 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
|
|
|
7594
7594
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
7595
7595
|
gl_FragColor = vec4(light, 1.0);
|
|
7596
7596
|
}
|
|
7597
|
-
`,transparent:!0,blending:Oi,depthWrite:!1,side:Bt,fog:!1});this.object=new Re(new ri(G0.RADIUS,128,32,0,Math.PI*2,0,dt.MAX_ANGLE_RAD),t),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(e,t){if(!e||!t){this.object.visible=!1;return}this.towards.set(e.x,e.y,e.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<dt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Fn.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=Fn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class zl{constructor(e){this.generator=e}static SIZE=128;target=new Wo(zl.SIZE,{type:Vt,generateMipmaps:!1,minFilter:at,magFilter:at});camera=new E0(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(e,t,i,n=[]){const s=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;const r=n.map(o=>o.visible);for(const o of n)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((o,c)=>{o.visible=r[c]}),e.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 on{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){on.install(),this.generator=new xd(e),this.eye=new zl(this.generator)}static decor;refresh(e,t,i,n,s,r,o,c=[],l){for(const v of[...this.probes.keys()])n.some(m=>m.id===v&&m.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const h=[{probe:this.eye}];for(const v of n){if(!v.shiny)continue;let m=this.probes.get(v.id);m||(m=new zl(this.generator),this.probes.set(v.id,m)),h.push({probe:m,reflector:v})}const u=performance.now(),d=()=>h.filter(({probe:v})=>v.capturedVersion!==o),f=d().filter(({probe:v})=>u-v.capturedAtMs>=on.REFRESH_MS);if(f.length>0){const v=f.reduce((m,g)=>g.probe.capturedAtMs<m.probe.capturedAtMs?g:m);if(v.reflector){const m=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,m,[v.reflector.holder,...s]),on.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...s,...c]),l?.(v.probe.sharp),on.decor=v.probe.filtered;for(const m of r)on.reflectOn(m,v.probe);for(const m of n)m.shiny||on.reflectOn(m.holder,v.probe)}v.probe.capturedVersion=o}const p=d();if(p.length!==0)return Math.max(16,Math.min(...p.map(({probe:v})=>on.REFRESH_MS-(u-v.capturedAtMs))))}scratch=new R;static reflectOn(e,t={filtered:on.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Yo?t.sharp&&s.setSurroundings(t.sharp):s instanceof yr&&t.filtered&&s.envMap!==t.filtered&&(s.envMap=t.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(on.installed)return;on.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!We.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}We.lights_fragment_maps=We.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function nE(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover&&a.relativeHumidity===e.relativeHumidity&&a.precipitationType===e.precipitationType&&a.precipitationIntensity===e.precipitationIntensity&&a.precipitationAmount===e.precipitationAmount&&a.windDirectionDeg===e.windDirectionDeg&&a.windSpeed===e.windSpeed&&a.storm===e.storm}const qc=900,ru=1,Rm=4,Dm=5,Cm=.5,_o=900,sE=6371e3,rE=3e4;function Im(a){const e=Math.sqrt(2*sE*Math.max(a,0));return Math.max(_o,Math.min(e,rE))}const au=.5,ou=850,Pm=.03,sn=850,lo=300,Ws=120,aE=700,oE=.04,ho=4,cu=1.5,Lm=-1,cE=6,Jd=-4,lE=2,hE=20,$c=2600,uE=.97,dE=.38,Kc=Jd,Om=1500,fE=400,pE=[0,45,90,135,180,225,270,315],mE={en:["N","NE","E","SE","S","SW","W","NW"],fr:["N","NE","E","SE","S","SO","O","NO"]},gE=["en","fr"],vE=2,ME=16,Nm=2500,Fm=880,Zc=40,Um=60,xE=10,yE=1,_E=150,bE=55,SE=.5,wE=17,km=.265,zm=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*km,Math.sin(t)*km]})],lu=700,hu=250/Qd,EE=12,Bm=5,uu=6,mr=[.92,.92,.95],du=[.15,.15,.19],fu={snow:{fallSpeedMPerS:2,size:.3,color:new se(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new se(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ma=0,pu=0,AE=150,mu=3e3,uo=20,TE=15,Hm=ma,RE=40,Gm=1,DE=9;function gu(a){return Gm+(DE-Gm)*a}const Vm=new se(.75,.82,.92),CE=10,IE=.5;function Wm(a){return _a(a/CE,IE,1)}const gr=200,Xm=.18,Ym=.32,PE=.35,qm=new se(.85,.9,.98),$m=5,Km=.85,Zm=.01;function LE(a,e,t=1){return Math.round(a*(Zm+(1-Zm)*e)*t)}function OE(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover}const Jm=230,jm=.7,Qm=.05,NE=.6,FE=.7,UE=.15,eg=.35,kE=3,zE=1/12,BE=.5,Xn=new se(.82,.86,1),HE=2500,GE=1.6,vu=15,VE={Venus:new se(1,.96,.85),Mars:new se(1,.55,.4),Jupiter:new se(.95,.87,.72),Saturn:new se(.92,.86,.68)};class kt{renderer;scene=new Ds;phenomena=new Dn(this.scene);references=new An(this.scene,()=>this.render());camera;celestialGroup=new Rt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new gn;roadAttribution;roadWays;statedRoads=[];decorModelProvider=eE[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new ht(e=>this.loadBodyModel(e),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];decorGroups=new Map;decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new bp(16777215,0);celestialLightTarget=new Ft;skyLight=new Tx(16777215,0,0);streetlightLights=new Map;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new ll;weather=e0;observerElevationM=0;siteElevationM=0;air=new Mn;groundRadius=_o;terrainRadius=_o;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 Me;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new bp(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new ll;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new ll;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=R2()){this.renderer=new BS({canvas:e,antialias:!0}),this.resolution=new mt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=So,this.camera=new Zi(60,e.width/Math.max(e.height,1),.1,qc*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=t,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-Ws,this.celestialLight.shadow.camera.right=Ws,this.celestialLight.shadow.camera.top=Ws,this.celestialLight.shadow.camera.bottom=-Ws,this.celestialLight.shadow.camera.near=sn-lo,this.celestialLight.shadow.camera.far=sn+lo,this.celestialLight.shadow.bias=-.03/(2*lo),this.celestialLight.shadow.normalBias=oE,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Xn),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);const i=new Ht(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}resize(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*hu,0,e.z*hu);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(e){const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*Yi,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Yi;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Yi,t,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,t,"YXZ"),e.elevationM!==this.observerElevationM&&(this.observerElevationM=e.elevationM,this.syncCloudLayer(),Math.abs(Im(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/_o),this.camera.far=Math.max(qc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ii(this.terrainOrigin.lat,this.terrainOrigin.lng,e.lat,e.lng);this.terrainMesh.position.x=n.x,this.terrainMesh.position.z=n.z}this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.terrainOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.groundRadius;if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:c,z:l}=ii(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(c*c+l*l)<_E*(n/_o))return}const s=this.terrainOrigin,r=this.terrainRadius;(!s||s.lat!==e||s.lng!==t)&&(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const o=++this.terrainBuildToken;d5(e,t,this.terrainProviders,n).then(({mesh:c,attribution:l,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const u=this.terrainMesh,d=s?ii(e,t,s.lat,s.lng):void 0;u&&d&&Math.hypot(d.x,d.z)<=r&&(c.position.y=u.position.y+this.groundYOfPatch(u,d.x,d.z)),u&&d&&Math.hypot(d.x,d.z)<=r?this.crossfadeTerrain(c,u):this.disposeMesh(this.terrainMesh),c.renderOrder=yE,this.terrainMesh=c,this.compileNextFrameOffThread(),this.terrainAttribution=l,this.scene.add(c),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.render(),i?.()}).catch(c=>{console.warn("Terrain build failed, keeping the flat ground fallback:",c),i?.()})}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t){this.stopTerrainFade();const i=e.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),s=()=>{const r=Math.min(1,(performance.now()-n)/kt.TERRAIN_CROSSFADE_MS);if(i.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(s);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,frameId:requestAnimationFrame(s)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=5e3;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>kt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRoads(s.ways,e,t,n.contemporary);return}n.getRoads(G1(e,t,i)).then(r=>{this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t||(this.roadWays={lat:e,lng:t,radiusM:i,ways:r},this.drapeRoads(r,e,t,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}drapeRoads(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.set(e,t,i,(r,o)=>this.groundYOfPatch(s,r,o),n),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}applyLensFlareTint(e){if(!this.lensFlare)return;const t=bE*(this.sunArriving[1]/wE);this.lensFlare.uniforms.uColorGain.value.setRGB(t*e[0],t*e[1],t*e[2]),this.applyDazzleStrength()}applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,n=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=Ii.K*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(nE(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!OE(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Mn.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:er.steppedOpticalDepth(e.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=e.storm&&e.cloudDarkness>=BE,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects!==e){this.decorObjects=e,this.decorModelToken++,this.decorModelCredits.clear();for(const t of this.decorGroups.values())t.removeFromParent(),li.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=li.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),this.loadDecorModel(t,this.decorModelToken)}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t);return{heightAt:(n,s)=>this.groundYUnder(e+n,t-s)-i}}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:o}=this.bodyOrigin,c=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,u)=>this.groundYUnder(h,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,u,d)=>this.transmittanceTo(h,u,d)},t,c?(h,u)=>c.relativeOfLuminance(h,u):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const l=this.bodySystem.furthestFrom(this.camera.position)*1.2;l>this.camera.far&&(this.camera.far=l,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(o,c,l)=>(o*t+(c+l)/2*s)/Math.PI;return[r(e.r,i.r,n.r),r(e.g,i.g,n.g),r(e.b,i.b,n.b)]}bodyOutline(e,t){return this.bodySystem.outlineOf(e,t)}documentUrl;modelUrl(e){return e.url?this.documentRelative(e.url):void 0}documentRelative(e){if(e.startsWith("data:"))return e;const t=this.documentUrl??(typeof location>"u"?void 0:location.href);return t?new URL(e,t).href:e}async loadBodyModel(e){const t=e.url?void 0:e.id?await this.decorModelProvider.entry(e.id):void 0,i=this.modelUrl(e)??t?.url,n=e.credit??t?.credit;if(!(!i||!n))return{scene:await Tm(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}async loadDecorModel(e,t){const i=e.model;if(!(!i||!li.usesModel(e)))try{const n=i.url?void 0:i.id?await this.decorModelProvider.entry(i.id):void 0,s=this.modelUrl(i)??n?.url,r=i.credit??n?.credit;if(!s||!r)return;const o=await Tm(s);if(t!==this.decorModelToken)return;const c=this.decorGroups.get(e.id);if(!c)return;on.reflectOn(o),li.applyModel(c,e,o,{headingOffsetDeg:i.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM}),this.decorModelCredits.set(e.id,r),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const n=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ii(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(l=>l.observerSide!==void 0&&fg(l.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const l=ii(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=l.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=l.z+(s?0:this.gaitOffset.northM),this.roadSystem.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 o=0;if(s){const l=li.occupantView(s),h=-(s.headingDeg??0)*Yi,u=l.x*Math.cos(h)+l.z*Math.sin(h),d=-l.x*Math.sin(h)+l.z*Math.cos(h),f=s.eastM+n.x,p=-s.northM+n.z;r.x=-(f+u),r.z=-(p+d),this.camera.position.y=this.groundYUnder(f,p)+l.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Yi,-(l.headingDeg+this.indoorLookYawDeg)*Yi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum();for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=Pa(l,i),d=u.eastM+n.x+r.x,f=-u.northM+n.z+r.z,p=this.terrainMesh,v=`${p?.geometry.uuid}:${(d-(p?.position.x??0)).toFixed(3)}:${(f-(p?.position.z??0)).toFixed(3)}:${(p?.position.y??0).toFixed(3)}:${u.headingDeg}:${u.altitudeM}`;if(h.userData.footprintKey!==v&&(h.userData.footprintGroundY=this.groundUnderFootprint(l,d,f,u.headingDeg,u.altitudeM),h.userData.footprintKey=v),h.position.set(d,h.userData.footprintGroundY+u.altitudeM,f),l.kind==="crop"){const m=Math.hypot(d,f);h.visible=m<=AE}if(u.headingDeg!==void 0&&(h.rotation.y=-u.headingDeg*Yi),l.kind==="crop"&&h.visible){const m=this.terrainMesh,g=[m?.geometry.uuid,d-(m?.position.x??0),f-(m?.position.z??0),h.position.y-(m?.position.y??0),u.headingDeg,u.altitudeM].map(y=>typeof y=="number"?y.toFixed(4):y).join(":");h.userData.cropGroundKey!==g&&(li.fitCropToGround(h,(y,b)=>this.groundYUnder(y,b)+u.altitudeM),h.userData.cropGroundKey=g)}o=Math.max(o,h.position.distanceTo(this.camera.position))}const c=Math.max(qc*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-c)>1&&(this.camera.far=c,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):pu}groundYOfPatch(e,t,i){const n=e.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return pu;const r=n.getX(0),o=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=_a((t-r)/(o-r)*(s-1),0,s-1),u=_a((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return pu;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,v=u-f,m=(S,w)=>n.getY(S*s+w),g=m(f,d),y=m(f,d+1),b=m(f+1,d),M=m(f+1,d+1);return p+v<=1?g+(y-g)*p+(b-g)*v:M+(b-M)*(1-p)+(y-M)*(1-v)}groundUnderFootprint(e,t,i,n,s=0){return li.groundUnderFootprint(e,t,i,n,(r,o)=>this.groundYUnder(r,o),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}medium;setMedium(e,t,i,n){const s=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0,exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30);if(!e){Bi.uMedium.value=0;return}Bi.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;Bi.uMediumExposure.value=i!==void 0&&i>0?1/(t*i):.065*e.exposureSeconds*e.iso/(e.fNumber*e.fNumber*t)}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new Me;updateDecorLitState(e,t=0){const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&li.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=pg(n,e);li.setLit(r,n.kind,o,this.relativeScale);const c=this.streetlightLights.get(n.id);c&&(c.visible=o)}}addStreetlightLight(e,t){const i=li.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new c1(16764006,Om*this.relativeScale,fE);s.position.copy(n.position).multiply(i.scale),s.castShadow=!0,s.shadow.mapSize.set(512,512),s.shadow.bias=-.002,t.add(s),this.streetlightLights.set(e,s)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&(this.skyHoldUntilMs=performance.now()+Nm,this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Nm+20)),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=ul(e.sun.altitudeDeg,this.instrumentMagnitudeGain);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const o=On.luminanceOf(r);if(!(o>0))return[0,0,0];const c=Ee.relativeOfResponse(o)/o;return[r[0]*c,r[1]*c,r[2]*c]},n=i(e.zenith),s=i(e.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.setBodyMesh("sun",e.sun,ho,new se(1,.96,.88),e.sun.magnitude),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,ul(e.sun.altitudeDeg,this.instrumentMagnitudeGain)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon));const t=this.scatteredSky?.ambient??kt.relativeSkyOf(Rd(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(o=>r[o]*n.through+n.radiance[o]*(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(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),nt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=Om*this.relativeScale;this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?Ne.DEFAULT_AEROSOL_OPTICAL_DEPTH:er.opticalDepth(i))*Ne.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=dt.aureoleScale(n,dt.airMass(e.altitudeDeg))*s,c=dt.coronaScale(r),l=dt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),c.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new G0,this.celestialGroup.add(this.lunarDiffraction.object));const u=dt.profile(dt.HAZE_COARSE_MODE),d=dt.profile(dt.CLOUD_DROPLETS),f=jp(e.altitudeDeg),p=new Float32Array(dt.STEPS*3);let v=0;for(let b=0;b<dt.STEPS;b++){const M=b*3,S=[0,1,2].map(T=>l*f[T]*(o*u[M+T]+c*d[M+T])),w=On.shown(S,On.luminanceOf(S),(T,x)=>t.relativeOfLuminance(T,x));p.set(w,M),v=Math.max(v,On.response(w))}const{x:m,y:g,z:y}=ci(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(v>1/200?{x:m,y:g,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof Lr||(this.scene.fog=new Lr),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+t,Math.hypot(e-n.x,t-n.y,i-n.z))}setSiteElevation(e){Math.abs(e-this.siteElevationM)<1||(this.siteElevationM=e,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}scatteredSkyState(e){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,sun:{altitudeDeg:e.sun.altitudeDeg,azimuthDeg:e.sun.azimuthDeg,magnitude:e.sun.magnitude},moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:qe.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?ME:vE),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(e){if(e.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new D5(ou),this.celestialGroup.add(this.satelliteField.object));const t=ul(this.lastSunPosition?.altitudeDeg??-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(Pm*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(e,t)?void 0:n}updateCelestialLight(e,t){const i=this.relativeScale,n=e.sun.altitudeDeg>=Kc,s=!n&&e.moon.altitudeDeg>=Kc,r=n?e.sun:e.moon,o=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Yi)),l=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(l,1e-6)),u=Math.max(0,1/(1+.1125*h)-l),d=[0,0,0];if(n||s){const y=dt.illuminanceOf(r.magnitude)*i,b=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let T=0;T<3;T++)o[T]=y*b[T]*l,d[T]=y*b[T]*u*c,this.cloudBeam[T]=y*b[T];const{x:M,y:S,z:w}=ci(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(M,S,w)}else this.cloudBeam.fill(0);const f=this.surroundings;if(f)this.skyLight.color.setRGB(f.up[0]*i,f.up[1]*i,f.up[2]*i),this.skyLight.groundColor.setRGB(f.down[0]*i,f.down[1]*i,f.down[2]*i);else{const y=this.skyCloudTransmission(),b=t.skyIrradiance,M=[0,1,2].map(w=>b[w]*y+d[w]);this.skyLight.color.setRGB(M[0],M[1],M[2]);const S=Ve.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(S*(M[0]+o[0]*c),S*(M[1]+o[1]*c),S*(M[2]+o[2]*c))}if(this.skyLight.intensity=1,!n&&!s){this.celestialLight.intensity=0;return}const{x:p,y:v,z:m}=ci(r.altitudeDeg,r.azimuthDeg,1);this.lightDirection.set(p,v,m),this.placeShadowFrustum();const g=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/g,o[1]/g,o[2]/g),this.celestialLight.intensity=g,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}lightDirection=new R(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,e);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(e,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,0,this.bodyOrigin.z),o=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(aE,Math.max(Ws,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,n=i.camera;n.left=-t,n.right=t,n.top=t,n.bottom=-t;const s=Math.max(lo,t*(lo/Ws));this.shadowLightDistanceM=Math.max(sn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*Ws?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Ws;shadowLightDistanceM=sn;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Yi,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)e+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=s}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ee.semiSaturation(Ee.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new gi,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(e,t,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(e){return this.meteorSystem?.midpointOf(e)}updateMeteors(e){this.meteorSystem?.update(e)}setInstrument(e){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const t=ni.starPointsOf(e),i=ni.flareArtifactsOf(e);t===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=t,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}setInstrumentGain(e,t=!1){this.instrumentMagnitudeGain=Number.isFinite(e)?e:0,this.scatteredSky?.setInstrument(t,this.instrumentMagnitudeGain)}render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()})))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased)){if(this.skyHoldUntilMs){if(!this.firstFrameReady()&&performance.now()<this.skyHoldUntilMs)return;this.skyHoldUntilMs=null,this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1)}if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;return}if(!this.compiling){this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{this.renderOnce()}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+kt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const o=t.get(r)?.currentProgram;(!o||o.isReady())&&e.delete(r)}e.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())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}refreshReflections(){this.reflections??=new on(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(s=>s.mesh)],t=[...this.starTiers.map(s=>s.points),...[...this.bodyMeshes.values()].filter(s=>s instanceof vs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(s=>s!==void 0)],i=this.relativeScale,n=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values()],this.sceneVersion,t,s=>this.measureSurroundings(s,i));n===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()}))},n))}measureSurroundings(e,t){const i=this.lastAstronomy;if(!i)return;this.probeIrradiance??=new Ro;const n=[i.sun,i.moon].filter(s=>s.altitudeDeg>-2).map(s=>ci(s.altitudeDeg,s.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,n,s=>{const r=d=>d.map(f=>f/t),o=this.surroundings,c={up:r(s.up),down:r(s.down)},l=(d,f)=>d.some((p,v)=>Math.abs(p-f[v])>.03*Math.max(Math.abs(p),Math.abs(f[v]),1e-12)),h=!o||l(o.up,c.up)||l(o.down,c.down);h&&(this.surroundings=c);const u=this.scatteredSky?.adaptToSurroundings(Math.exp(s.logAverage)/t)??!1;!h&&!u||(this.skyColoursStale=!0,this.render())})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=Kc?e.sun:e.moon.altitudeDeg>=Kc?e.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*n,t.up[1]*n,t.up[2]*n]}}probeIrradiance;surroundings;animate(e,t){const i=Math.min(t/1e3,zE);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,o,c)=>this.directionAtScreenPoint(r,o,c),r=>this.screenPointOf(r)),this.references.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references.furthestM)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),Bi.uRodShare.value=this.scatteredSky?.rodShare??0,Bi.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Bi.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!t){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,e);return}t.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(),e)}renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){if(!this.compassSprites.some(n=>n.visible))return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Dm),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}renderReferencesPass(e){if(!this.references.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Q1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){this.references.set(e.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}}),void 0,t)}referenceAspect(e){return this.references.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new R)}referenceFailedToLoad(e){return this.references.failedToLoad(this.documentRelative(e))}setReferencesShown(e){this.references.setShown(e),this.render()}setReferenceView(e,t){this.references.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;const t=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&&kt.markDecorDepth(s,n.kind!=="crop")}e.layers.set(ru),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(j1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new yn({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Re))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Oi?i.layers.enable(ru):i.layers.disable(ru)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new Me),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new $S(t,i)),this.exposureAccumulation.resize(t,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const e=this.exposureInstantAt,t=this.exposureAccumulation;if(!e||!t)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+kt.EXPOSURE_BUDGET_MS,s=kt.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=o[l]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){if(Bi.uRodShare.value=this.scatteredSky?.rodShare??0,Bi.uHasOverlay.value=1,Bi.uRelativeScale.value=this.relativeScale,this.applyMedium(),this.exposureAccumulation?.develop(this.renderer,this.exposureInstants/this.exposureInstantsDone),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(s=>s.visible))return;const e=new Ds,t=new Un(-1,1,1,-1,0,2),i=Zc/(Fm*Math.tan(Um*Yi/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new R).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const c=new Ja(s.material);c.position.set(o.ndcX,o.ndcY,-1),c.scale.set(i/this.camera.aspect,i,1),e.add(c)}const n=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(e,t)}finally{this.renderer.autoClear=n}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new Gi,i=new R,n=this.decorObjects.filter(r=>r.track?.length||r.kind==="aircraft"||r.kind==="vehicle").map(r=>this.decorGroups.get(r.id)),s=this.bodySystem.reflectors.map(r=>r.holder);for(const r of[...n,...s]){if(!r?.visible||(t.setFromObject(r),t.isEmpty())||t.distanceToPoint(this.camera.position)<kt.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,c=-1/0,l=1/0,h=-1/0;for(const u of[t.min.x,t.max.x])for(const d of[t.min.y,t.max.y])for(const f of[t.min.z,t.max.z]){i.set(u,d,f).sub(this.camera.position).normalize();const p=this.screenPointOf(i);if(!p)continue;const v=(p.ndcX+1)/2,m=(1-p.ndcY)/2;o=Math.min(o,v),c=Math.max(c,v),l=Math.min(l,m),h=Math.max(h,m)}Number.isFinite(o)&&e.push({x:o,y:l,width:c-o,height:h-l})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new Me),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Do(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new Me);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new H0(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new Me);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new Mi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new Me(t,i),this.camera);return}const s=n.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),e.camera=this.camera}pickCloudAt(e,t){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(e,t))}cloudDirectionAt(e,t){return this.directionAtScreenPoint(e,t,new R)}directionAtScreenPoint(e,t,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(e){this.camera.updateMatrixWorld();const t=this.screenPointScratch.copy(e).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 Mi.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Yi);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new R;screenPointQuaternion=new Qi;screenPointSize=new Me;updateLensFlarePosition(){const e=this.lensFlare;if(!e)return;if(!this.sunVisible){e.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){e.mesh.visible=!1;return}const t=this.sunVisibleFraction();if(t<=0){e.mesh.visible=!1;return}e.mesh.visible=!0,this.sunUnhiddenFraction=t,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);e.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;e.uniforms.uResolution.value.set(n,s),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}renderDazzleOnResample(){const e=this.lensFlare;if(!e||!this.sunVisible)return;const t=this.sunVisibleFraction();if(t<=0)return;this.sunUnhiddenFraction=t,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);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(n.x,n.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(Rm),this.camera.layers.set(Rm),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of zm)this.isSunOccluded(t[0],t[1])||e++;return e/zm.length}raycastableDecor(){const e=[];for(const t of this.decorObjects){if(t.kind==="crop")continue;const i=this.decorGroups.get(t.id);i&&e.push(i)}return e}isSunOccluded(e=0,t=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(),e!==0||t!==0){const o=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,e*o).addScaledVector(l,t*o).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(e,t,i,n=0){const s=this.groundMesh;if(s&&t.y<0){const m=(s.position.y-e.y)/t.y;if(m>n&&m<i){const g=e.x+t.x*m-s.position.x,y=e.z+t.z*m-s.position.z;if(Math.hypot(g,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(o.count));if(c<2||c*c!==o.count)return!1;const l=[r.position.x+o.getX(0),r.position.x+o.getX(c-1)],h=[r.position.z+o.getZ(0),r.position.z+o.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,g,y]of[[e.x,t.x,l],[e.z,t.z,h]]){const b=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(g)<1e-12){if(m<b||m>M)return!1;continue}const S=(b-m)/g,w=(M-m)/g;d=Math.max(d,Math.min(S,w)),f=Math.min(f,Math.max(S,w))}if(!(f>d))return!1;const p=Math.hypot(t.x,t.z),v=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=v;m++){const g=d+(f-d)*m/v,y=e.x+t.x*g,b=e.y+t.y*g,M=e.z+t.z*g;if(b<=this.groundYUnder(y,M))return!0}return!1}setPhenomena(e,t){this.phenomena.set(e,t)}decorDistancesAt(e,t,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),this.ufoOcclusionRaycaster.near=Cm;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const c=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];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(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.hitAreas.entries()],n=this.raycaster.intersectObjects(i.map(([,s])=>s))[0];if(n&&!this.groundHides(e,t))return i.find(([,s])=>s===n.object)?.[0]}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(Pm*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const c=o.direction.dot(i);c>r&&(r=c,s={star:o.star,altitudeDeg:o.altitudeDeg})}return s&&this.groundHides(e,t)?void 0:s}groundHides(e,t){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Cm)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?t.max.x:t.min.x,o&2?t.max.y:t.min.y,o&4?t.max.z:t.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 Gi;bodyCornerScratch=new R;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=this.raycaster.intersectObjects(i.map(([,r])=>r),!0)[0];if(!n)return;let s=n.object;for(;s&&!i.some(([,r])=>r===s);)s=s.parent;return i.find(([,r])=>r===s)?.[0]}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.roadSystem.dispose(),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.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.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())li.dispose(e);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 e=t=>{this.frame(t),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setAnimationsRunning(e,t=!1){const i=e&&t;if(e===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset()),!e&&this.renderer.getPixelRatio()!==this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&this.hasAnimations()}hasAnimations(){return this.starTiers.length>0||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.lensFlare!==void 0&&this.sunVisible}syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(e){const t=this.skyMesh?.geometry??new ri(qc,32,16),i=t.attributes.position,n=t.getAttribute("color")??new ut(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:c}=JS(i.getX(r),i.getY(r),i.getZ(r)),l=rw(o,c,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new yn({vertexColors:!0,side:Bt,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Re(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=Im(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new y0(this.groundRadius,48),i=new za({color:new se(au,au,au),fog:!0});Lr.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Re(t,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 e=this.groundMesh?.material;if(!e)return;const t=this.terrainMesh===void 0;e.depthWrite!==t&&(e.depthWrite=t,e.needsUpdate=!0)}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.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,o])=>`${r}=${Math.round(o.x/10)},${Math.round(o.z/10)}`).join(";")+(t?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=ci(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-pt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*uE);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-pt.iceAlphaAt(i,$c,r,this.cloudFieldOffset)*dE),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Jd){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:o,z:c}=ci(t.altitudeDeg,t.azimuthDeg,sn),l=jp(t.altitudeDeg),h=this.cloudTransmission(t),u=this.arrivingIlluminance(t,s,h),d=kt.unitLuminance(n);let f=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/sn)**2,v=[0,1,2].map(m=>Math.min(kt.BRIGHTEST_RELATIVE,d[m]*u[m]/p));f instanceof Re||(this.disposeMesh(f),f=new Re(new ri(1,16,16),new yn({fog:!1})),this.celestialGroup.add(f),this.bodyMeshes.set(e,f)),f.material.color.setRGB(v[0],v[1],v[2]),f.scale.setScalar(i)}else{if(!(f instanceof vs)){this.disposeMesh(f);const m=new ot;m.setAttribute("position",new tt(new Float32Array(3),3)),m.setAttribute("color",new tt(new Float32Array(3),3)),f=new vs(m,nt.material(To[To.length-1].size,!1)),nt.track(f),this.celestialGroup.add(f),this.bodyMeshes.set(e,f)}const p=f.geometry.getAttribute("color"),v=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*u[0]*v,d[1]*u[1]*v,d[2]*u[2]*v),p.needsUpdate=!0}if(f.position.set(r,o,c),this.setHitArea(e,r,o,c,i),e==="sun"&&(this.sunArriving=u),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,c,u,i/sn*(180/Math.PI),kt.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,o*p+this.celestialGroup.position.y,c*p),this.lensFlare||(this.lensFlare=R5(),this.lensFlare.uniforms.uOpacity.value=SE,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(l)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Jd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=ci(e.altitudeDeg,e.azimuthDeg,sn),o=this.cloudTransmission(e),c=this.arrivingIlluminance(e,e.magnitude,o),l=Math.max(_a(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(ho/sn)**2,h=new se(...c.map(f=>Math.min(kt.BRIGHTEST_RELATIVE,f/l))),u=`${e.phase.phaseFraction<.5}:${Math.round(_a(e.phase.illuminatedFraction,0,1)*500)}`;let d=this.bodyMeshes.get(i);if(d instanceof Ja)d.userData.phaseKey!==u&&(d.material.map?.dispose(),d.material.map=ig(e.phase),d.userData.phaseKey=u),d.material.color.copy(h);else{this.disposeMesh(d),d=new Ja(new cl({map:ig(e.phase),color:h,fog:!1})),d.userData.phaseKey=u;const f=ho*2;d.scale.set(f,f,1),this.celestialGroup.add(d),this.bodyMeshes.set(i,d)}d.position.set(n,s,r),this.setHitArea(i,n,s,r,ho),this.setGlare(i,n,s,r,c,ho/sn*(180/Math.PI))}bentLight(e,t,i=lE){const[n,s,r]=this.arrivingIlluminance(e,t,1),o=Math.max(s,1e-30);return{scale:s/i,tint:[n/o,1,r/o]}}static litBySky(e,t){return kt.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new se;pointToPixel(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),t=(this.camera.fov*Math.PI/180/e)**2;return Math.min(1,nt.CONE_SOLID_ANGLE/t)}pointScratch=new Me;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),s=dt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=On.luminanceOf([e.r,e.g,e.b]);return t>0?[e.r/t,e.g/t,e.b/t]:[1,1,1]}setHitArea(e,t,i,n,s){let r=this.hitAreas.get(e);if(!r){const c=new cl({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Ja(c),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*cE;r.scale.set(o,o,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,n,s,r,o=0){if(Ii.radiusDeg(Ii.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let c=this.glareSprites.get(e);c||(c=new Ii(`veil:${e}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(e,c)),c.shine({x:t,y:i,z:n},s,r,o)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=vo(e.magnitude,t),s=qh(n);this.cometKey=i,this.setBodyMesh(i,e.position,cu*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new an(sn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Ci,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:$c},0);return}const s=this.lowerCloudCover(),r=ft.deckLitUntilDeg(ft.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,c=this.bentLight(o,o===e?Ht.SUN_MAGNITUDE:t.magnitude),l=ft.strength(i,s,o.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=ci(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},o.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??$c},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Sv)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Tr,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=e.altitudeDeg>0,s=n?e:t,r=this.lowerCloudCover(),o=this.bentLight(s,n?Ht.SUN_MAGNITUDE:t.magnitude,hE),c=rn.strength(i,r,s.altitudeDeg)*o.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}=ci(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new qs,this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Rn.galactic(i,n),r=kt.directionOf(s.centre),o=kt.directionOf(s.rotation),c=kt.directionOf(s.pole),l=new Xe().set(r.x,r.y,r.z,o.x,o.y,o.z,c.x,c.y,c.z),h=kt.directionOf(Rn.eclipticPole(i,n)),u=kt.directionOf(e.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:kt.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:qe.phaseAngleOf(e.moon.phase.illuminatedFraction)},skyColor:new R(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=ci(e.altitudeDeg,e.azimuthDeg,1);return new R(t,i,n).normalize()}buildNovae(e,t){const i=new Set;for(const n of e){if(n.magnitude>t)continue;const s=`nova:${n.id}`;i.add(s);const r=vo(n.magnitude,t),o=qh(r);this.setBodyMesh(s,n.position,cu*(.5+.5*r),new se(o,o,o),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(e,t){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of e){if(n.magnitude>t)continue;i.add(n.body);const s=vo(n.magnitude,t),r=qh(s),o=VE[n.body]??new se(1,1,1),c=new se(o.r*r,o.g*r,o.b*r),l=cu*(.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(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=e,r=new In(n,s),o=Mu(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>t)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<Lm)continue;const{x:p,y:v,z:m}=ci(d,f,ou);c.push({x:p,y:v,z:m,brightness:vo(u,t),illuminance:this.air.transmittanceFromSpace(l,d).map(g=>g*dt.illuminanceOf(u)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of o5){if(h.mag>t)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<Lm)continue;const{x:f,y:p,z:v}=ci(u,d,ou);this.namedStars.push({star:h,direction:new R(f,p,v).normalize(),altitudeDeg:u})}this.starTiers=To.map((h,u)=>{const d=c.filter(S=>b1(S.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),v=new Float32Array(d.length*3),m=new Float32Array(d.length),g=new Float32Array(d.length);d.forEach((S,w)=>{f[w*3]=S.x,f[w*3+1]=S.y,f[w*3+2]=S.z,p[w]=S.brightness,v.set(S.illuminance,w*3),m[w]=S.phase,g[w]=S.speedFactor});const y=new ot;y.setAttribute("position",new tt(f,3)),y.setAttribute("seed",new tt(m.map(S=>S/(2*Math.PI)),1));const b=new tt(new Float32Array(d.length*3),3);y.setAttribute("color",b);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new vs(y,nt.material(h.size)),nt.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:b,brightness:p,illuminance:v,phase:m,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){nt.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;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]*t,n[s*3+1]=i.illuminance[s*3+1]*t,n[s*3+2]=i.illuminance[s*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Aa(this.celestialGroup,lu,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 e=this.lowerCloudCover();if(e<=0){this.disposeCloudSystem();return}const t=this.weather.cloudDarkness,i=new se(mr[0]+(du[0]-mr[0])*t,mr[1]+(du[1]-mr[1])*t,mr[2]+(du[2]-mr[2])*t);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=e,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Sd(i,e,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=wd(lu);this.cloudMesh=new Re(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type!=="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type==="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.highCloudCover}buildCirrus(){const e=this.weather.highCloudCover??0;if(this.layeredClouds||e<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=e,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:t,uniforms:i}=Sd(new se(...mr),e,$c,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Re(wd(lu*1.04),t),this.cirrusMesh.renderOrder=Bm-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 e=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(e)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,e)}faceCloudDeck(e,t){const i=t<0;e.scale.y=i?-1:1,e.renderOrder=i?Aa.deckOrder(!0,0,1):Bm}cloudLayerOffset(){const t=((this.weather.cloudBaseM??Qd)-this.observerElevationM)*hu;return Math.sign(t||1)*Math.max(Math.abs(t),EE)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,o]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*vu*this.relativeScale/Math.PI,l=new se(t[0]+Xn.r*c,t[1]+Xn.g*c,t[2]+Xn.b*c);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),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,o*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(e){return LE(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,mu],[this.rainSplashSystem?.points,gr],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:fu[this.weather.precipitationType].poolSize]];for(const[t,i]of e)t&&i!==void 0&&t.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=Wm(gu(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const e=this.weather.precipitationType;if(e==="none")return;if(e==="rain"){this.buildRain();return}const t=fu[e],i=t.poolSize,n=Mu(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=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 b=0;b<i;b++){const M=n()*Math.PI*2,S=n()*t.radiusM;s[b*3]=Math.cos(M)*S,s[b*3+1]=ma+n()*(t.topYM-ma),s[b*3+2]=Math.sin(M)*S,r[b]=n()*Math.PI*2,o[b]=.7+n()*.6,c[b]=.6+n()*.8,l[b]=.4+n()*1.2}const v=new ot;v.setAttribute("position",new tt(s,3)),v.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new se(...this.baseFogColor)},uTexture:{value:WE(e)},uNearFocusDistance:{value:$m},uHazeDistance:{value:t.radiusM*Km}},g=new ct({uniforms:m,vertexShader:ZE,fragmentShader:JE,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new vs(v,g);y.renderOrder=uu,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(e,t){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=fu[i];if(this.precipitationUniforms?.uColor.value.copy(kt.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Yi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-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,v=this.precipitationBounceDuration,m=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,b=i==="hail"&&f&&p&&v&&m&&g;for(let M=0,S=0;M<c.length;M+=3,S++){if(b&&f[S]>0){if(f[S]-=t,f[S]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(x)*A,c[M+1]=n.topYM,c[M+2]=Math.sin(x)*A,f[S]=0}else{const x=1-f[S]/v[S];c[M+1]=ma+Math.sin(Math.PI*x)*p[S],c[M]=Jc(c[M]+(r+m[S])*t,n.radiusM),c[M+2]=Jc(c[M+2]+(o+g[S])*t,n.radiusM)}continue}let w=0,T=0;if(y){const x=NE*u[S],A=FE*d[S];w=Math.sin(e*x*Math.PI*2+l[S])*A,T=Math.sin(e*x*Math.PI*2+l[S]+Math.PI/2)*A}if(c[M]+=(r+w)*t,c[M+1]-=n.fallSpeedMPerS*h[S]*t,c[M+2]+=(o+T)*t,c[M]=Jc(c[M],n.radiusM),c[M+2]=Jc(c[M+2],n.radiusM),c[M+1]<ma){if(b){p[S]=eg*(.2+Math.random()*1.6),v[S]=UE*(.5+Math.random()),f[S]=v[S];const I=Math.random()*Math.PI*2,C=kE*(p[S]/eg);m[S]=Math.cos(I)*C,g[S]=Math.sin(I)*C,c[M+1]=ma;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(x)*A,c[M+1]=n.topYM,c[M+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=gu(this.weather.precipitationIntensity);this.rainSystem=w5({count:mu,radiusM:uo,heightM:TE,bottomYM:Hm,overallSpeed:RE,color:Vm.clone(),opacity:.85,visibleCount:this.precipitationCount(mu),speedStreak:Wm(e),pixelSize:Jm,seed:9001,nearFocusDistanceM:$m,hazeDistanceM:uo*Km,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=uu,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Mu(4242),t=new Float32Array(gr*3),i=new Float32Array(gr),n=new Float32Array(gr),s=new Float32Array(gr);for(let h=0;h<gr;h++){const u=e()*Math.PI*2,d=Math.sqrt(e())*uo;t[h*3]=Math.cos(u)*d,t[h*3+1]=Hm,t[h*3+2]=Math.sin(u)*d,n[h]=tg(Xm,Ym),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ot;r.setAttribute("position",new tt(t,3));const o=new tt(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(gr));const c=new ct({uniforms:{uMaxSize:{value:PE},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:qm.clone()},uTexture:{value:qE()}},vertexShader:$E,fragmentShader:KE,transparent:!0,depthWrite:!1}),l=new vs(r,c);l.renderOrder=uu,this.scene.add(l),this.rainSplashSystem={points:l,positions:t,life:i,duration:n,lifeAttribute:o}}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 e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Yi;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-gu(this.weather.precipitationIntensity),-Math.cos(t)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);e.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(e){const t=this.rainSystem;if(!t)return;t.uniforms.uTime.value+=e,t.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),t.uniforms.uColor.value.copy(kt.litBySky(Vm,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(kt.litBySky(qm,this.baseFogColor));const n=this.weather.windDirectionDeg*Yi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=uo,c=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(c(t.uniforms.uWindOffset.value.x+s*e),c(t.uniforms.uWindOffset.value.y+r*e)),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=jm+(1-jm)*(1-l),u=Qm+(1-Qm)*(1-l);t.uniforms.uUvSquash.value=u,t.uniforms.uPixelSize.value=Jm*h*(.5+.5*u)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=t,o=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=e,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*uo;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=tg(Xm,Ym),n[l]=0}o[l]=n[l]/s[l]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>e)break;const l=hi.brightnessAt(c,e);l>i&&(t=c,i=l)}const n=t?Math.min(1,Math.max(.1,(HE/t.distanceM)**2)):0,s=i*n*(t?.cloudToGround?1:.6);if(s===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*vu*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Xn.r*l,this.airlight[1]+Xn.g*l,this.airlight[2]+Xn.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*GE;r.setRGB(1+c*Xn.r,1+c*Xn.g,1+c*Xn.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*vu*this.relativeScale,t){const{x:c,y:l,z:h}=ci(25,t.azimuthDeg,sn);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new $s(sn*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){const e=Fo(navigator.languages,gE),t=mE[e];this.compassSprites=pE.map((i,n)=>{const s=t[n],r=new cl({map:jE(s),depthTest:!1,fog:!1}),o=new Ja(r),{x:c,y:l,z:h}=ci(0,i,Fm);return o.position.set(c,l,h),o.scale.set(Zc,Zc,1),o.renderOrder=xE,o.layers.set(Dm),o.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(o),o}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=Um*Math.PI/360,i=Zc*Math.tan(e)/Math.tan(t);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const e of this.compassSprites)e.removeFromParent(),e.material.map?.dispose(),e.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const e of this.starTiers)this.disposeMesh(e.points);this.starTiers=[]}disposeMesh(e){if(!e)return;e.removeFromParent(),"geometry"in e&&e.geometry.dispose();const t=e.material;for(const i of Array.isArray(t)?t:[t]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Yi=Math.PI/180;function _a(a,e,t){return Math.max(e,Math.min(t,a))}function tg(a,e){return a+Math.random()*(e-a)}function Jc(a,e){return(a%(e*2)+e*3)%(e*2)-e}let jc,Qc;function WE(a){switch(a){case"snow":return XE();case"hail":return YE()}}function XE(){if(jc)return jc;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),jc=new Ps(e),jc}function YE(){if(Qc)return Qc;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),Qc=new Ps(e),Qc}let el;function qE(){if(el)return el;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),el=new Ps(e),el}const $E=`
|
|
7597
|
+
`,transparent:!0,blending:Oi,depthWrite:!1,side:Bt,fog:!1});this.object=new Re(new ri(G0.RADIUS,128,32,0,Math.PI*2,0,dt.MAX_ANGLE_RAD),t),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(e,t){if(!e||!t){this.object.visible=!1;return}this.towards.set(e.x,e.y,e.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<dt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=Fn.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=Fn.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class zl{constructor(e){this.generator=e}static SIZE=128;target=new Wo(zl.SIZE,{type:Vt,generateMipmaps:!1,minFilter:at,magFilter:at});camera=new E0(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(e,t,i,n=[]){const s=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;const r=n.map(o=>o.visible);for(const o of n)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((o,c)=>{o.visible=r[c]}),e.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 on{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){on.install(),this.generator=new xd(e),this.eye=new zl(this.generator)}static decor;refresh(e,t,i,n,s,r,o,c=[],l){for(const v of[...this.probes.keys()])n.some(m=>m.id===v&&m.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const h=[{probe:this.eye}];for(const v of n){if(!v.shiny)continue;let m=this.probes.get(v.id);m||(m=new zl(this.generator),this.probes.set(v.id,m)),h.push({probe:m,reflector:v})}const u=performance.now(),d=()=>h.filter(({probe:v})=>v.capturedVersion!==o),f=d().filter(({probe:v})=>u-v.capturedAtMs>=on.REFRESH_MS);if(f.length>0){const v=f.reduce((m,g)=>g.probe.capturedAtMs<m.probe.capturedAtMs?g:m);if(v.reflector){const m=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,m,[v.reflector.holder,...s]),on.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...s,...c]),l?.(v.probe.sharp),on.decor=v.probe.filtered;for(const m of r)on.reflectOn(m,v.probe);for(const m of n)m.shiny||on.reflectOn(m.holder,v.probe)}v.probe.capturedVersion=o}const p=d();if(p.length!==0)return Math.max(16,Math.min(...p.map(({probe:v})=>on.REFRESH_MS-(u-v.capturedAtMs))))}scratch=new R;static reflectOn(e,t={filtered:on.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Yo?t.sharp&&s.setSurroundings(t.sharp):s instanceof yr&&t.filtered&&s.envMap!==t.filtered&&(s.envMap=t.filtered,s.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(on.installed)return;on.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!We.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}We.lights_fragment_maps=We.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function nE(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover&&a.relativeHumidity===e.relativeHumidity&&a.precipitationType===e.precipitationType&&a.precipitationIntensity===e.precipitationIntensity&&a.precipitationAmount===e.precipitationAmount&&a.windDirectionDeg===e.windDirectionDeg&&a.windSpeed===e.windSpeed&&a.storm===e.storm}const qc=900,ru=1,Rm=4,Dm=5,Cm=.5,_o=900,sE=6371e3,rE=3e4;function Im(a){const e=Math.sqrt(2*sE*Math.max(a,0));return Math.max(_o,Math.min(e,rE))}const au=.5,ou=850,Pm=.03,sn=850,lo=300,Ws=120,aE=700,oE=.04,ho=4,cu=1.5,Lm=-1,cE=6,Jd=-4,lE=2,hE=20,$c=2600,uE=.97,dE=.38,Kc=Jd,Om=1500,fE=400,pE=[0,45,90,135,180,225,270,315],mE={en:["N","NE","E","SE","S","SW","W","NW"],fr:["N","NE","E","SE","S","SO","O","NO"]},gE=["en","fr"],vE=2,ME=16,Nm=2500,Fm=880,Zc=40,Um=60,xE=10,yE=1,_E=150,bE=55,SE=.5,wE=17,km=.265,zm=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*km,Math.sin(t)*km]})],lu=700,hu=250/Qd,EE=12,Bm=5,uu=6,mr=[.92,.92,.95],du=[.15,.15,.19],fu={snow:{fallSpeedMPerS:2,size:.3,color:new se(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new se(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},ma=0,pu=0,AE=150,mu=3e3,uo=20,TE=15,Hm=ma,RE=40,Gm=1,DE=9;function gu(a){return Gm+(DE-Gm)*a}const Vm=new se(.75,.82,.92),CE=10,IE=.5;function Wm(a){return _a(a/CE,IE,1)}const gr=200,Xm=.18,Ym=.32,PE=.35,qm=new se(.85,.9,.98),$m=5,Km=.85,Zm=.01;function LE(a,e,t=1){return Math.round(a*(Zm+(1-Zm)*e)*t)}function OE(a,e){return JSON.stringify(a.cloudLayers)===JSON.stringify(e.cloudLayers)&&a.cloudCover===e.cloudCover&&a.cloudDarkness===e.cloudDarkness&&a.cloudBaseM===e.cloudBaseM&&a.highCloudCover===e.highCloudCover&&a.iceCrystalAlignment===e.iceCrystalAlignment&&a.lowerCloudCover===e.lowerCloudCover}const Jm=230,jm=.7,Qm=.05,NE=.6,FE=.7,UE=.15,eg=.35,kE=3,zE=1/12,BE=.5,Xn=new se(.82,.86,1),HE=2500,GE=1.6,vu=15,VE={Venus:new se(1,.96,.85),Mars:new se(1,.55,.4),Jupiter:new se(.95,.87,.72),Saturn:new se(.92,.86,.68)};class kt{renderer;scene=new Ds;phenomena=new Dn(this.scene);references=new An(this.scene,()=>this.render());camera;celestialGroup=new Rt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new gn;roadAttribution;roadWays;statedRoads=[];decorModelProvider=eE[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new ht(e=>this.loadBodyModel(e),()=>this.render(),()=>this.relativeScale);bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];decorGroups=new Map;decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new bp(16777215,0);celestialLightTarget=new Ft;skyLight=new Tx(16777215,0,0);streetlightLights=new Map;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new ll;weather=e0;observerElevationM=0;siteElevationM=0;air=new Mn;groundRadius=_o;terrainRadius=_o;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 Me;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new bp(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new R;sunVisible=!1;lensFlareScratch=new R;sunOcclusionRaycaster=new ll;sunOcclusionDirectionScratch=new R;sunOcclusionRightScratch=new R;sunOcclusionUpScratch=new R;ufoOcclusionRaycaster=new ll;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(e){return Math.max(3,Math.round(6e6/Math.max(1,e)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=R2()){this.renderer=new BS({canvas:e,antialias:!0}),this.resolution=new mt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=So,this.camera=new Zi(60,e.width/Math.max(e.height,1),.1,qc*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=t,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-Ws,this.celestialLight.shadow.camera.right=Ws,this.celestialLight.shadow.camera.top=Ws,this.celestialLight.shadow.camera.bottom=-Ws,this.celestialLight.shadow.camera.near=sn-lo,this.celestialLight.shadow.camera.far=sn+lo,this.celestialLight.shadow.bias=-.03/(2*lo),this.celestialLight.shadow.normalBias=oE,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Xn),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);const i=new Ht(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}resize(e,t){this.cssSize.width=e,this.cssSize.height=t,this.renderer.setSize(e,t,!1),this.camera.aspect=e/Math.max(t,1),this.camera.updateProjectionMatrix(),this.render()}setCloudRendering(e){e!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=e,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(e,t={}){this.cloudOffsetM.set(e.x,0,e.z),this.cloudLayerOffsetsM=t,this.layeredClouds?.setOffsets(e,t),this.cloudFieldOffset.set(e.x*hu,0,e.z*hu);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(e){const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*Yi,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Yi;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Yi,t,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,t,"YXZ"),e.elevationM!==this.observerElevationM&&(this.observerElevationM=e.elevationM,this.syncCloudLayer(),Math.abs(Im(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/_o),this.camera.far=Math.max(qc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ii(this.terrainOrigin.lat,this.terrainOrigin.lng,e.lat,e.lng);this.terrainMesh.position.x=n.x,this.terrainMesh.position.z=n.z}this.poseCameraY=this.groundYUnder(0,0)+1.6+e.elevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==e.fovDeg&&(this.camera.fov=e.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(e){this.stopTerrainFade(),this.terrainProviders=e,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.terrainOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=this.groundRadius;if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:c,z:l}=ii(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(c*c+l*l)<_E*(n/_o))return}const s=this.terrainOrigin,r=this.terrainRadius;(!s||s.lat!==e||s.lng!==t)&&(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const o=++this.terrainBuildToken;d5(e,t,this.terrainProviders,n).then(({mesh:c,attribution:l,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const u=this.terrainMesh,d=s?ii(e,t,s.lat,s.lng):void 0;u&&d&&Math.hypot(d.x,d.z)<=r&&(c.position.y=u.position.y+this.groundYOfPatch(u,d.x,d.z)),u&&d&&Math.hypot(d.x,d.z)<=r?this.crossfadeTerrain(c,u):this.disposeMesh(this.terrainMesh),c.renderOrder=yE,this.terrainMesh=c,this.compileNextFrameOffThread(),this.terrainAttribution=l,this.scene.add(c),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.render(),i?.()}).catch(c=>{console.warn("Terrain build failed, keeping the flat ground fallback:",c),i?.()})}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t){this.stopTerrainFade();const i=e.material;i.opacity=0,i.polygonOffset=!0,i.polygonOffsetFactor=-1,i.polygonOffsetUnits=-4;const n=performance.now(),s=()=>{const r=Math.min(1,(performance.now()-n)/kt.TERRAIN_CROSSFADE_MS);if(i.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(s);return}i.polygonOffset=!1,i.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,frameId:requestAnimationFrame(s)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const e=this.terrainMesh?.material;e&&(e.opacity=1,e.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=5e3;buildRoads(e,t,i){const n=this.terrainProviders.roads;if(!n||i>kt.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.roadAttribution=void 0;return}const s=this.roadWays;if(s&&s.lat===e&&s.lng===t&&s.radiusM===i){this.drapeRoads(s.ways,e,t,n.contemporary);return}n.getRoads(G1(e,t,i)).then(r=>{this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t||(this.roadWays={lat:e,lng:t,radiusM:i,ways:r},this.drapeRoads(r,e,t,n.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}setStatedRoads(e){e!==this.statedRoads&&(this.statedRoads=e,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const e=this.terrainMesh;e&&(this.roadSystem.group.position.copy(e.position),this.roadSystem.setStated(this.statedRoads,(t,i)=>this.groundYOfPatch(e,t,i)))}drapeRoads(e,t,i,n){const s=this.terrainMesh;s&&(this.roadSystem.group.position.copy(s.position),this.roadSystem.set(e,t,i,(r,o)=>this.groundYOfPatch(s,r,o),n),this.roadAttribution=e.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(e){this.showCompass!==e&&(this.showCompass=e,this.disposeCompassLabels(),e&&this.buildCompassLabels(),this.render())}applyLensFlareTint(e){if(!this.lensFlare)return;const t=bE*(this.sunArriving[1]/wE);this.lensFlare.uniforms.uColorGain.value.setRGB(t*e[0],t*e[1],t*e[2]),this.applyDazzleStrength()}applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,n=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/n,1,i/n),this.lensFlare.uniforms.uVeilStrength.value=Ii.K*t*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassHovered(e){this.compassHovered!==e&&(this.compassHovered=e,this.updateCompassVisibility())}setCompassForced(e){this.compassForced!==e&&(this.compassForced=e,this.updateCompassVisibility())}updateCompassVisibility(){const e=this.compassHovered||this.compassForced;if(this.compassSprites.some(t=>t.visible!==e)){for(const t of this.compassSprites)t.visible=e;this.developingExposure?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(nE(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!OE(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Mn.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:er.steppedOpticalDepth(e.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=e.storm&&e.cloudDarkness>=BE,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects!==e){this.decorObjects=e,this.decorModelToken++,this.decorModelCredits.clear();for(const t of this.decorGroups.values())t.removeFromParent(),li.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=li.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),this.loadDecorModel(t,this.decorModelToken)}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}setDecorModelProvider(e){this.decorModelProvider=e;const t=this.decorObjects;this.decorObjects=[],this.setDecor(t)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}get bodyGround(){const{x:e,z:t}=this.bodyOrigin,i=this.groundYUnder(e,t);return{heightAt:(n,s)=>this.groundYUnder(e+n,t-s)-i}}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:o}=this.bodyOrigin,c=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,u)=>this.groundYUnder(h,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,u,d)=>this.transmittanceTo(h,u,d)},t,c?(h,u)=>c.relativeOfLuminance(h,u):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const l=this.bodySystem.furthestFrom(this.camera.position)*1.2;l>this.camera.far&&(this.camera.far=l,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(o,c,l)=>(o*t+(c+l)/2*s)/Math.PI;return[r(e.r,i.r,n.r),r(e.g,i.g,n.g),r(e.b,i.b,n.b)]}bodyOutline(e,t){return this.bodySystem.outlineOf(e,t)}documentUrl;modelUrl(e){return e.url?this.documentRelative(e.url):void 0}documentRelative(e){if(e.startsWith("data:"))return e;const t=this.documentUrl??(typeof location>"u"?void 0:location.href);return t?new URL(e,t).href:e}async loadBodyModel(e){const t=e.url?void 0:e.id?await this.decorModelProvider.entry(e.id):void 0,i=this.modelUrl(e)??t?.url,n=e.credit??t?.credit;if(!(!i||!n))return{scene:await Tm(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}async loadDecorModel(e,t){const i=e.model;if(!(!i||!li.usesModel(e)))try{const n=i.url?void 0:i.id?await this.decorModelProvider.entry(i.id):void 0,s=this.modelUrl(i)??n?.url,r=i.credit??n?.credit;if(!s||!r)return;const o=await Tm(s);if(t!==this.decorModelToken)return;const c=this.decorGroups.get(e.id);if(!c)return;on.reflectOn(o),li.applyModel(c,e,o,{headingOffsetDeg:i.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM}),this.decorModelCredits.set(e.id,r),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const n=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ii(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(l=>l.observerSide!==void 0&&fg(l.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const l=ii(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=l.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=l.z+(s?0:this.gaitOffset.northM),this.roadSystem.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 o=0;if(s){const l=li.occupantView(s),h=-(s.headingDeg??0)*Yi,u=l.x*Math.cos(h)+l.z*Math.sin(h),d=-l.x*Math.sin(h)+l.z*Math.cos(h),f=s.eastM+n.x,p=-s.northM+n.z;r.x=-(f+u),r.z=-(p+d),this.camera.position.y=this.groundYUnder(f,p)+l.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Yi,-(l.headingDeg+this.indoorLookYawDeg)*Yi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum();for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=Pa(l,i),d=u.eastM+n.x+r.x,f=-u.northM+n.z+r.z,p=this.terrainMesh,v=`${p?.geometry.uuid}:${(d-(p?.position.x??0)).toFixed(3)}:${(f-(p?.position.z??0)).toFixed(3)}:${(p?.position.y??0).toFixed(3)}:${u.headingDeg}:${u.altitudeM}`;if(h.userData.footprintKey!==v&&(h.userData.footprintGroundY=this.groundUnderFootprint(l,d,f,u.headingDeg,u.altitudeM),h.userData.footprintKey=v),h.position.set(d,h.userData.footprintGroundY+u.altitudeM,f),l.kind==="crop"){const m=Math.hypot(d,f);h.visible=m<=AE}if(u.headingDeg!==void 0&&(h.rotation.y=-u.headingDeg*Yi),l.kind==="crop"&&h.visible){const m=this.terrainMesh,g=[m?.geometry.uuid,d-(m?.position.x??0),f-(m?.position.z??0),h.position.y-(m?.position.y??0),u.headingDeg,u.altitudeM].map(y=>typeof y=="number"?y.toFixed(4):y).join(":");h.userData.cropGroundKey!==g&&(li.fitCropToGround(h,(y,b)=>this.groundYUnder(y,b)+u.altitudeM),h.userData.cropGroundKey=g)}o=Math.max(o,h.position.distanceTo(this.camera.position))}const c=Math.max(qc*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-c)>1&&(this.camera.far=c,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):pu}groundYOfPatch(e,t,i){const n=e.geometry.getAttribute("position"),s=Math.round(Math.sqrt(n.count));if(s<2||s*s!==n.count)return pu;const r=n.getX(0),o=n.getX(s-1),c=n.getZ(0),l=n.getZ((s-1)*s),h=_a((t-r)/(o-r)*(s-1),0,s-1),u=_a((i-c)/(l-c)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(u))return pu;const d=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(u),s-2),p=h-d,v=u-f,m=(S,w)=>n.getY(S*s+w),g=m(f,d),y=m(f,d+1),b=m(f+1,d),M=m(f+1,d+1);return p+v<=1?g+(y-g)*p+(b-g)*v:M+(b-M)*(1-p)+(y-M)*(1-v)}groundUnderFootprint(e,t,i,n,s=0){return li.groundUnderFootprint(e,t,i,n,(r,o)=>this.groundYUnder(r,o),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;setGait(e){this.gaitOffset=e}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(e,t){this.lookYawDeg=e,this.lookPitchDeg=t}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(e,t){this.indoorLookYawDeg=e,this.indoorLookPitchDeg=t}medium;setMedium(e,t,i,n){const s=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:n??e.iso,autoExposure:e.autoExposure===!0,exposureSeconds:t,fNumber:i}:void 0;JSON.stringify(s)!==JSON.stringify(this.medium)&&(this.medium=s,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30);if(!e){Bi.uMedium.value=0;return}Bi.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;Bi.uMediumExposure.value=i!==void 0&&i>0?1/(t*i):.065*e.exposureSeconds*e.iso/(e.fNumber*e.fNumber*t)}grain;lampBloomRadiusRad(){if(!this.grain)return;const e=this.camera.fov*Math.PI/180,t=this.grain.frameHeightMm/(2*Math.tan(e/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/t,e/i)}bloomSize=new Me;updateDecorLitState(e,t=0){const i=this.lampBloomRadiusRad();for(const n of this.decorObjects){const s=this.decorGroups.get(n.id);if(s&&n.lights?.length&&li.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=pg(n,e);li.setLit(r,n.kind,o,this.relativeScale);const c=this.streetlightLights.get(n.id);c&&(c.visible=o)}}addStreetlightLight(e,t){const i=li.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new c1(16764006,Om*this.relativeScale,fE);s.position.copy(n.position).multiply(i.scale),s.castShadow=!0,s.shadow.mapSize.set(512,512),s.shadow.bias=-.002,t.add(s),this.streetlightLights.set(e,s)}setAstronomy(e){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-e.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=e,this.scatteredSky?.update(this.scatteredSkyState(e)),this.skyHoldUntilMs===void 0&&(this.skyHoldUntilMs=performance.now()+Nm,this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Nm+20)),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=ul(e.sun.altitudeDeg,this.instrumentMagnitudeGain);this.buildStars(e.stars,t),this.placeBodies(e,t),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon),this.applySkyColours(e),this.syncAnimationLoop(),this.render()}static relativeSkyOf(e,t){const i=r=>{const o=On.luminanceOf(r);if(!(o>0))return[0,0,0];const c=Ee.relativeOfResponse(o)/o;return[r[0]*c,r[1]*c,r[2]*c]},n=i(e.zenith),s=i(e.horizon);return{zenith:n,horizon:s,airlight:s,skyIrradiance:[n[0]*Math.PI,n[1]*Math.PI,n[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.setBodyMesh("sun",e.sun,ho,new se(1,.96,.88),e.sun.magnitude),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}bodiesScale=0;applySkyColours(e){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(e,ul(e.sun.altitudeDeg,this.instrumentMagnitudeGain)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon));const t=this.scatteredSky?.ambient??kt.relativeSkyOf(Rd(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(o=>r[o]*n.through+n.radiance[o]*(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(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),nt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=Om*this.relativeScale;this.buildSkyGlow(e,i.zenith),this.applyAir(),this.buildLunarDiffraction(e.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(e){const t=this.scatteredSky?.ready?this.scatteredSky:void 0;if(e.altitudeDeg<-.5||!t){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=this.weather.relativeHumidity,n=(i===void 0?Ne.DEFAULT_AEROSOL_OPTICAL_DEPTH:er.opticalDepth(i))*Ne.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=dt.aureoleScale(n,dt.airMass(e.altitudeDeg))*s,c=dt.coronaScale(r),l=dt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),c.toExponential(2),Math.log10(Math.max(t.adaptation,1e-12)).toFixed(2)].join(":");if(h===this.lunarDiffractionKey)return;this.lunarDiffractionKey=h,this.lunarDiffraction||(this.lunarDiffraction=new G0,this.celestialGroup.add(this.lunarDiffraction.object));const u=dt.profile(dt.HAZE_COARSE_MODE),d=dt.profile(dt.CLOUD_DROPLETS),f=jp(e.altitudeDeg),p=new Float32Array(dt.STEPS*3);let v=0;for(let b=0;b<dt.STEPS;b++){const M=b*3,S=[0,1,2].map(T=>l*f[T]*(o*u[M+T]+c*d[M+T])),w=On.shown(S,On.luminanceOf(S),(T,x)=>t.relativeOfLuminance(T,x));p.set(w,M),v=Math.max(v,On.response(w))}const{x:m,y:g,z:y}=ci(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(v>1/200?{x:m,y:g,z:y}:void 0,p)}applyAir(){this.scene.fog instanceof Lr||(this.scene.fog=new Lr),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const n=this.camera.position;return this.air.transmittance(this.siteElevationM+n.y,this.siteElevationM+t,Math.hypot(e-n.x,t-n.y,i-n.z))}setSiteElevation(e){Math.abs(e-this.siteElevationM)<1||(this.siteElevationM=e,this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}scatteredSkyState(e){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,sun:{altitudeDeg:e.sun.altitudeDeg,azimuthDeg:e.sun.azimuthDeg,magnitude:e.sun.magnitude},moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:qe.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?ME:vE),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(e){if(e.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new D5(ou),this.celestialGroup.add(this.satelliteField.object));const t=ul(this.lastSunPosition?.altitudeDeg??-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(Pm*this.camera.fov*Math.PI/180),n=this.satelliteField.nearest(this.raycaster.ray.direction,i);return n&&this.groundHides(e,t)?void 0:n}updateCelestialLight(e,t){const i=this.relativeScale,n=e.sun.altitudeDeg>=Kc,s=!n&&e.moon.altitudeDeg>=Kc,r=n?e.sun:e.moon,o=[0,0,0],c=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*Yi)),l=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(l,1e-6)),u=Math.max(0,1/(1+.1125*h)-l),d=[0,0,0];if(n||s){const y=dt.illuminanceOf(r.magnitude)*i,b=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let T=0;T<3;T++)o[T]=y*b[T]*l,d[T]=y*b[T]*u*c,this.cloudBeam[T]=y*b[T];const{x:M,y:S,z:w}=ci(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(M,S,w)}else this.cloudBeam.fill(0);const f=this.surroundings;if(f)this.skyLight.color.setRGB(f.up[0]*i,f.up[1]*i,f.up[2]*i),this.skyLight.groundColor.setRGB(f.down[0]*i,f.down[1]*i,f.down[2]*i);else{const y=this.skyCloudTransmission(),b=t.skyIrradiance,M=[0,1,2].map(w=>b[w]*y+d[w]);this.skyLight.color.setRGB(M[0],M[1],M[2]);const S=Ve.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(S*(M[0]+o[0]*c),S*(M[1]+o[1]*c),S*(M[2]+o[2]*c))}if(this.skyLight.intensity=1,!n&&!s){this.celestialLight.intensity=0;return}const{x:p,y:v,z:m}=ci(r.altitudeDeg,r.azimuthDeg,1);this.lightDirection.set(p,v,m),this.placeShadowFrustum();const g=Math.max(o[0],o[1],o[2],1e-30);this.celestialLight.color.setRGB(o[0]/g,o[1]/g,o[2]/g),this.celestialLight.intensity=g,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}lightDirection=new R(0,1,0);placeShadowFrustum(){const e=this.lightDirection,t=this.celestialLight.shadow.camera,i=(t.right-t.left)/this.celestialLight.shadow.mapSize.x,n=this.shadowAxisX.crossVectors(this.shadowUp,e);n.lengthSq()<1e-8&&n.set(1,0,0),n.normalize();const s=this.shadowAxisY.crossVectors(e,n).normalize(),r=this.shadowWorld.set(this.bodyOrigin.x,0,this.bodyOrigin.z),o=l=>{const h=r.dot(l)/i;return(h-Math.round(h))*i},c=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(c).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(aE,Math.max(Ws,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,n=i.camera;n.left=-t,n.right=t,n.top=t,n.bottom=-t;const s=Math.max(lo,t*(lo/Ws));this.shadowLightDistanceM=Math.max(sn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*Ws?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=Ws;shadowLightDistanceM=sn;shadowUp=new R(0,1,0);shadowAxisX=new R;shadowAxisY=new R;shadowWorld=new R;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*Yi,s=Math.sin(n)*Math.cos(n)*2;for(let r=0;r<360;r+=60)e+=s*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=s}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new R(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ee.semiSaturation(Ee.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new gi,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(e,t,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(e){return this.meteorSystem?.midpointOf(e)}updateMeteors(e){this.meteorSystem?.update(e)}setInstrument(e){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const t=ni.starPointsOf(e),i=ni.flareArtifactsOf(e);t===this.starPoints&&i===this.lensFlareArtifactIntensity||(this.starPoints=t,this.lensFlareArtifactIntensity=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=t,this.lensFlare.uniforms.uFlareIntensity.value=i),this.render())}setInstrumentGain(e,t=!1){this.instrumentMagnitudeGain=Number.isFinite(e)?e:0,this.scatteredSky?.setInstrument(t,this.instrumentMagnitudeGain)}render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()})))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased)){if(this.skyHoldUntilMs){if(!this.firstFrameReady()&&performance.now()<this.skyHoldUntilMs)return;this.skyHoldUntilMs=null,this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1)}if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const e=this.compileOffThread().then(()=>{this.compiling===e&&(this.compiling=void 0,this.render())});this.compiling=e;return}if(!this.compiling){this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{this.renderOnce()}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const e=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const t=this.renderer.properties,i=performance.now()+kt.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const o=t.get(r)?.currentProgram;(!o||o.isReady())&&e.delete(r)}e.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())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(e){if(this.animationsRunning){const t=this.lastFrameTimeMs===void 0?0:e-this.lastFrameTimeMs;this.lastFrameTimeMs=e,this.hasAnimations()&&this.animate(e,t);const i=this.resolution.ratioFor(e,t);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}this.drawIfDirty()}refreshReflections(){this.reflections??=new on(this.renderer);const e=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(s=>s.mesh)],t=[...this.starTiers.map(s=>s.points),...[...this.bodyMeshes.values()].filter(s=>s instanceof vs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(s=>s!==void 0)],i=this.relativeScale,n=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,e,[...this.decorGroups.values()],this.sceneVersion,t,s=>this.measureSurroundings(s,i));n===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()}))},n))}measureSurroundings(e,t){const i=this.lastAstronomy;if(!i)return;this.probeIrradiance??=new Ro;const n=[i.sun,i.moon].filter(s=>s.altitudeDeg>-2).map(s=>ci(s.altitudeDeg,s.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,n,s=>{const r=d=>d.map(f=>f/t),o=this.surroundings,c={up:r(s.up),down:r(s.down)},l=(d,f)=>d.some((p,v)=>Math.abs(p-f[v])>.03*Math.max(Math.abs(p),Math.abs(f[v]),1e-12)),h=!o||l(o.up,c.up)||l(o.down,c.down);h&&(this.surroundings=c);const u=this.scatteredSky?.adaptToSurroundings(Math.exp(s.logAverage)/t)??!1;!h&&!u||(this.skyColoursStale=!0,this.render())})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=Kc?e.sun:e.moon.altitudeDeg>=Kc?e.moon:void 0;if(!i)return;const n=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*n,t.up[1]*n,t.up[2]*n]}}probeIrradiance;surroundings;animate(e,t){const i=Math.min(t/1e3,zE);this.twinkleSeconds=e/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(e/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=e/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(e){this.resolution.maximum=e,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(e){this.renderer.setPixelRatio(e),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(e,t){const i=t?Math.max(1,Math.round(e)):1;if(i===this.exposureInstants&&(i===1||t===this.exposureInstantAt)){this.exposureInstantAt=t;return}this.exposureInstants=i,this.exposureInstantAt=t,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(e){if(this.onMapSubjectBounds){const r=this.mapSubjectBounds();e?this.exposureSubjectBounds.push(...r):this.onMapSubjectBounds(r)}const t=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.phenomena.place(this.camera,(r,o,c)=>this.directionAtScreenPoint(r,o,c),r=>this.screenPointOf(r)),this.references.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references.furthestM)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),Bi.uRodShare.value=this.scatteredSky?.rodShare??0,Bi.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);Bi.uHasOverlay.value=n?1:0;const s=n?r=>this.renderOverlayPasses(r):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!t){this.updateLensFlarePosition();const r=this.usableDepthOfFieldPass();r?r.render(this.renderer,this.scene,this.camera,s,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,s,void 0,e);return}t.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(),e)}renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderPhenomenaPass(e),this.renderHudPass(e)}renderHudPass(e){if(!this.compassSprites.some(n=>n.visible))return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Dm),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}renderReferencesPass(e){if(!this.references.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(Q1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){this.references.set(e.map(i=>{const n=this.documentRelative(i.src);return n===i.src?i:{...i,src:n}}),void 0,t)}referenceAspect(e){return this.references.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new R)}referenceFailedToLoad(e){return this.references.failedToLoad(this.documentRelative(e))}setReferencesShown(e){this.references.setShown(e),this.render()}setReferenceView(e,t){this.references.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;const t=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&&kt.markDecorDepth(s,n.kind!=="crop")}e.layers.set(ru),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(j1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new yn({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Re))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Oi?i.layers.enable(ru):i.layers.disable(ru)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new Me),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new $S(t,i)),this.exposureAccumulation.resize(t,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const e=this.exposureInstantAt,t=this.exposureAccumulation;if(!e||!t)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const n=performance.now()+kt.EXPOSURE_BUDGET_MS,s=kt.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(c=>c.visible);for(const c of this.compassSprites)c.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((c,l)=>{c.visible=o[l]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<n&&r<s);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){if(Bi.uRodShare.value=this.scatteredSky?.rodShare??0,Bi.uHasOverlay.value=1,Bi.uRelativeScale.value=this.relativeScale,this.applyMedium(),this.exposureAccumulation?.develop(this.renderer,this.exposureInstants/this.exposureInstantsDone),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(s=>s.visible))return;const e=new Ds,t=new Un(-1,1,1,-1,0,2),i=Zc/(Fm*Math.tan(Um*Yi/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new R).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const c=new Ja(s.material);c.position.set(o.ndcX,o.ndcY,-1),c.scale.set(i/this.camera.aspect,i,1),e.add(c)}const n=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(e,t)}finally{this.renderer.autoClear=n}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new Gi,i=new R,n=this.camera.getWorldDirection(new R),s=this.decorObjects.filter(o=>o.track?.length||o.kind==="aircraft"||o.kind==="vehicle").map(o=>this.decorGroups.get(o.id)),r=this.bodySystem.reflectors.map(o=>o.holder);for(const o of[...s,...r]){if(!o?.visible||(t.setFromObject(o),t.isEmpty())||t.distanceToPoint(this.camera.position)<kt.MAP_SUBJECT_NEAREST_M)continue;let c=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[t.min.x,t.max.x])for(const f of[t.min.y,t.max.y])for(const p of[t.min.z,t.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const v=this.screenPointOf(i);if(!v)continue;const m=(v.ndcX+1)/2,g=(1-v.ndcY)/2;c=Math.min(c,m),l=Math.max(l,m),h=Math.min(h,g),u=Math.max(u,g)}c=Math.max(c,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=c&&u>=h&&e.push({x:c,y:h,width:l-c,height:u-h})}return e}restateAt(e,t){this.restatingExposure=!0;try{e(t)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(e){const t=this.lensOptics;this.lensOptics=e,(t===void 0!=(e===void 0)||t&&e&&(t.focalLengthMm!==e.focalLengthMm||t.fNumber!==e.fNumber||t.focusDistance!==e.focusDistance||t.frameHeightMm!==e.frameHeightMm))&&(e&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.render())}usableDepthOfFieldPass(){const e=this.lensOptics;if(!e)return;const t=this.renderer.getDrawingBufferSize(new Me),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new Do(i,n)),this.depthOfFieldPass.resize(i,n),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new Me);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new H0(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new Me);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new Mi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new Me(t,i),this.camera);return}const s=n.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(s.x,s.y,s.z).applyQuaternion(this.camera.quaternion).normalize(),e.camera=this.camera}pickCloudAt(e,t){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(e,t))}cloudDirectionAt(e,t){return this.directionAtScreenPoint(e,t,new R)}directionAtScreenPoint(e,t,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(e){this.camera.updateMatrixWorld();const t=this.screenPointScratch.copy(e).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 Mi.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*Yi);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new R;screenPointQuaternion=new Qi;screenPointSize=new Me;updateLensFlarePosition(){const e=this.lensFlare;if(!e)return;if(!this.sunVisible){e.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){e.mesh.visible=!1;return}const t=this.sunVisibleFraction();if(t<=0){e.mesh.visible=!1;return}e.mesh.visible=!0,this.sunUnhiddenFraction=t,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);e.uniforms.uLensPosition.value.set(i.x,i.y);const n=this.renderer.domElement.width,s=this.renderer.domElement.height;e.uniforms.uResolution.value.set(n,s),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}renderDazzleOnResample(){const e=this.lensFlare;if(!e||!this.sunVisible)return;const t=this.sunVisibleFraction();if(t<=0)return;this.sunUnhiddenFraction=t,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);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(n.x,n.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const s=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(Rm),this.camera.layers.set(Rm),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=s}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of zm)this.isSunOccluded(t[0],t[1])||e++;return e/zm.length}raycastableDecor(){const e=[];for(const t of this.decorObjects){if(t.kind==="crop")continue;const i=this.decorGroups.get(t.id);i&&e.push(i)}return e}isSunOccluded(e=0,t=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(),e!==0||t!==0){const o=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,e*o).addScaledVector(l,t*o).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(e,t,i,n=0){const s=this.groundMesh;if(s&&t.y<0){const m=(s.position.y-e.y)/t.y;if(m>n&&m<i){const g=e.x+t.x*m-s.position.x,y=e.z+t.z*m-s.position.z;if(Math.hypot(g,y)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),c=Math.round(Math.sqrt(o.count));if(c<2||c*c!==o.count)return!1;const l=[r.position.x+o.getX(0),r.position.x+o.getX(c-1)],h=[r.position.z+o.getZ(0),r.position.z+o.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,g,y]of[[e.x,t.x,l],[e.z,t.z,h]]){const b=Math.min(y[0],y[1]),M=Math.max(y[0],y[1]);if(Math.abs(g)<1e-12){if(m<b||m>M)return!1;continue}const S=(b-m)/g,w=(M-m)/g;d=Math.max(d,Math.min(S,w)),f=Math.min(f,Math.max(S,w))}if(!(f>d))return!1;const p=Math.hypot(t.x,t.z),v=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=v;m++){const g=d+(f-d)*m/v,y=e.x+t.x*g,b=e.y+t.y*g,M=e.z+t.z*g;if(b<=this.groundYUnder(y,M))return!0}return!1}setPhenomena(e,t){this.phenomena.set(e,t)}decorDistancesAt(e,t,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t),this.ufoOcclusionRaycaster.near=Cm;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const c=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];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(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.hitAreas.entries()],n=this.raycaster.intersectObjects(i.map(([,s])=>s))[0];if(n&&!this.groundHides(e,t))return i.find(([,s])=>s===n.object)?.[0]}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(Pm*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const c=o.direction.dot(i);c>r&&(r=c,s={star:o.star,altitudeDeg:o.altitudeDeg})}return s&&this.groundHides(e,t)?void 0:s}groundHides(e,t){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,e,t);const i=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(i.origin,i.direction,1/0,Cm)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,n=1/0,s=-1/0,r=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?t.max.x:t.min.x,o&2?t.max.y:t.min.y,o&4?t.max.z:t.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 Gi;bodyCornerScratch=new R;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=this.raycaster.intersectObjects(i.map(([,r])=>r),!0)[0];if(!n)return;let s=n.object;for(;s&&!i.some(([,r])=>r===s);)s=s.parent;return i.find(([,r])=>r===s)?.[0]}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.roadSystem.dispose(),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.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.lightningBolt?.dispose(),this.lightningBolt=void 0;for(const e of this.bodyMeshes.values())this.disposeMesh(e);this.bodyMeshes.clear(),this.novaKeys.clear();for(const e of[...this.hitAreas.keys()])this.disposeHitArea(e);for(const e of[...this.glareSprites.keys()])this.disposeGlare(e);this.disposeCompassLabels();for(const e of this.decorGroups.values())li.dispose(e);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 e=t=>{this.frame(t),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}setAnimationsRunning(e,t=!1){const i=e&&t;if(e===this.animationsRunning&&i===this.framesDriven)return;const n=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!n&&(this.lastFrameTimeMs=void 0,this.resolution.reset()),!e&&this.renderer.getPixelRatio()!==this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render()}stopTwinkle(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}needsAnimationLoop(){return this.animationsRunning&&!this.framesDriven&&this.hasAnimations()}hasAnimations(){return this.starTiers.length>0||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.lensFlare!==void 0&&this.sunVisible}syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(e){const t=this.skyMesh?.geometry??new ri(qc,32,16),i=t.attributes.position,n=t.getAttribute("color")??new ut(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:c}=JS(i.getX(r),i.getY(r),i.getZ(r)),l=rw(o,c,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,l[0],l[1],l[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new yn({vertexColors:!0,side:Bt,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Re(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=Im(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new y0(this.groundRadius,48),i=new za({color:new se(au,au,au),fog:!0});Lr.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Re(t,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 e=this.groundMesh?.material;if(!e)return;const t=this.terrainMesh===void 0;e.depthWrite!==t&&(e.depthWrite=t,e.needsUpdate=!0)}cloudTransmission(e,t=!1){const i=`${e.altitudeDeg.toFixed(1)}:${e.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,o])=>`${r}=${Math.round(o.x/10)},${Math.round(o.z/10)}`).join(";")+(t?":water":""),n=this.cloudTransmissionMemo.get(i);if(n!==void 0)return n;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const s=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,s),s}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=ci(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let n=1;const s=this.lowerCloudCover();s>0&&(n*=1-pt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*uE);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-pt.iceAlphaAt(i,$c,r,this.cloudFieldOffset)*dE),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<Jd){this.disposeMesh(this.bodyMeshes.get(e)),this.bodyMeshes.delete(e),this.disposeHitArea(e),this.disposeGlare(e),e==="sun"&&(this.sunVisible=!1);return}const{x:r,y:o,z:c}=ci(t.altitudeDeg,t.azimuthDeg,sn),l=jp(t.altitudeDeg),h=this.cloudTransmission(t),u=this.arrivingIlluminance(t,s,h),d=kt.unitLuminance(n);let f=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/sn)**2,v=[0,1,2].map(m=>Math.min(kt.BRIGHTEST_RELATIVE,d[m]*u[m]/p));f instanceof Re||(this.disposeMesh(f),f=new Re(new ri(1,16,16),new yn({fog:!1})),this.celestialGroup.add(f),this.bodyMeshes.set(e,f)),f.material.color.setRGB(v[0],v[1],v[2]),f.scale.setScalar(i)}else{if(!(f instanceof vs)){this.disposeMesh(f);const m=new ot;m.setAttribute("position",new tt(new Float32Array(3),3)),m.setAttribute("color",new tt(new Float32Array(3),3)),f=new vs(m,nt.material(To[To.length-1].size,!1)),nt.track(f),this.celestialGroup.add(f),this.bodyMeshes.set(e,f)}const p=f.geometry.getAttribute("color"),v=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*u[0]*v,d[1]*u[1]*v,d[2]*u[2]*v),p.needsUpdate=!0}if(f.position.set(r,o,c),this.setHitArea(e,r,o,c,i),e==="sun"&&(this.sunArriving=u),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,c,u,i/sn*(180/Math.PI),kt.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,o*p+this.celestialGroup.position.y,c*p),this.lensFlare||(this.lensFlare=R5(),this.lensFlare.uniforms.uOpacity.value=SE,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(l)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<Jd){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=ci(e.altitudeDeg,e.azimuthDeg,sn),o=this.cloudTransmission(e),c=this.arrivingIlluminance(e,e.magnitude,o),l=Math.max(_a(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(ho/sn)**2,h=new se(...c.map(f=>Math.min(kt.BRIGHTEST_RELATIVE,f/l))),u=`${e.phase.phaseFraction<.5}:${Math.round(_a(e.phase.illuminatedFraction,0,1)*500)}`;let d=this.bodyMeshes.get(i);if(d instanceof Ja)d.userData.phaseKey!==u&&(d.material.map?.dispose(),d.material.map=ig(e.phase),d.userData.phaseKey=u),d.material.color.copy(h);else{this.disposeMesh(d),d=new Ja(new cl({map:ig(e.phase),color:h,fog:!1})),d.userData.phaseKey=u;const f=ho*2;d.scale.set(f,f,1),this.celestialGroup.add(d),this.bodyMeshes.set(i,d)}d.position.set(n,s,r),this.setHitArea(i,n,s,r,ho),this.setGlare(i,n,s,r,c,ho/sn*(180/Math.PI))}bentLight(e,t,i=lE){const[n,s,r]=this.arrivingIlluminance(e,t,1),o=Math.max(s,1e-30);return{scale:s/i,tint:[n/o,1,r/o]}}static litBySky(e,t){return kt.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new se;pointToPixel(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),t=(this.camera.fov*Math.PI/180/e)**2;return Math.min(1,nt.CONE_SOLID_ANGLE/t)}pointScratch=new Me;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const n=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),s=dt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=On.luminanceOf([e.r,e.g,e.b]);return t>0?[e.r/t,e.g/t,e.b/t]:[1,1,1]}setHitArea(e,t,i,n,s){let r=this.hitAreas.get(e);if(!r){const c=new cl({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Ja(c),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*cE;r.scale.set(o,o,1)}disposeHitArea(e){const t=this.hitAreas.get(e);t&&(t.removeFromParent(),t.material.dispose(),this.hitAreas.delete(e))}setGlare(e,t,i,n,s,r,o=0){if(Ii.radiusDeg(Ii.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let c=this.glareSprites.get(e);c||(c=new Ii(`veil:${e}`),this.celestialGroup.add(c.mesh),this.glareSprites.set(e,c)),c.shine({x:t,y:i,z:n},s,r,o)}disposeGlare(e){const t=this.glareSprites.get(e);t&&(t.mesh.removeFromParent(),t.dispose(),this.glareSprites.delete(e))}buildComet(e,t){const i=e&&`comet:${e.id}`;if(!e||!i||e.magnitude>t){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const n=vo(e.magnitude,t),s=qh(n);this.cometKey=i,this.setBodyMesh(i,e.position,cu*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new an(sn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Ci,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:$c},0);return}const s=this.lowerCloudCover(),r=ft.deckLitUntilDeg(ft.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,c=this.bentLight(o,o===e?Ht.SUN_MAGNITUDE:t.magnitude),l=ft.strength(i,s,o.altitudeDeg,r)*c.scale,{x:h,y:u,z:d}=ci(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},o.altitudeDeg,l,c.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??$c},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??Sv)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Tr,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,n=e.altitudeDeg>0,s=n?e:t,r=this.lowerCloudCover(),o=this.bentLight(s,n?Ht.SUN_MAGNITUDE:t.magnitude,hE),c=rn.strength(i,r,s.altitudeDeg)*o.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}=ci(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},c,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new qs,this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=Rn.galactic(i,n),r=kt.directionOf(s.centre),o=kt.directionOf(s.rotation),c=kt.directionOf(s.pole),l=new Xe().set(r.x,r.y,r.z,o.x,o.y,o.z,c.x,c.y,c.z),h=kt.directionOf(Rn.eclipticPole(i,n)),u=kt.directionOf(e.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:kt.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:qe.phaseAngleOf(e.moon.phase.illuminatedFraction)},skyColor:new R(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=ci(e.altitudeDeg,e.azimuthDeg,1);return new R(t,i,n).normalize()}buildNovae(e,t){const i=new Set;for(const n of e){if(n.magnitude>t)continue;const s=`nova:${n.id}`;i.add(s);const r=vo(n.magnitude,t),o=qh(r);this.setBodyMesh(s,n.position,cu*(.5+.5*r),new se(o,o,o),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(e,t){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const n of e){if(n.magnitude>t)continue;i.add(n.body);const s=vo(n.magnitude,t),r=qh(s),o=VE[n.body]??new se(1,1,1),c=new se(o.r*r,o.g*r,o.b*r),l=cu*(.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(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:n,observer:s}=e,r=new In(n,s),o=Mu(1337),c=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>t)break;const{altitudeDeg:d,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(d<Lm)continue;const{x:p,y:v,z:m}=ci(d,f,ou);c.push({x:p,y:v,z:m,brightness:vo(u,t),illuminance:this.air.transmittanceFromSpace(l,d).map(g=>g*dt.illuminanceOf(u)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of o5){if(h.mag>t)continue;const{altitudeDeg:u,azimuthDeg:d}=r.position(h.raHours,h.decDeg);if(u<Lm)continue;const{x:f,y:p,z:v}=ci(u,d,ou);this.namedStars.push({star:h,direction:new R(f,p,v).normalize(),altitudeDeg:u})}this.starTiers=To.map((h,u)=>{const d=c.filter(S=>b1(S.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),v=new Float32Array(d.length*3),m=new Float32Array(d.length),g=new Float32Array(d.length);d.forEach((S,w)=>{f[w*3]=S.x,f[w*3+1]=S.y,f[w*3+2]=S.z,p[w]=S.brightness,v.set(S.illuminance,w*3),m[w]=S.phase,g[w]=S.speedFactor});const y=new ot;y.setAttribute("position",new tt(f,3)),y.setAttribute("seed",new tt(m.map(S=>S/(2*Math.PI)),1));const b=new tt(new Float32Array(d.length*3),3);y.setAttribute("color",b);let M=this.starTiers[u]?.points;return M?(M.geometry.dispose(),M.geometry=y):(M=new vs(y,nt.material(h.size)),nt.track(M),this.celestialGroup.add(M)),{points:M,colorAttribute:b,brightness:p,illuminance:v,phase:m,speedFactor:g}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){nt.setTime(e);const t=this.relativeScale;if(t!==this.starColoursRelative){this.starColoursRelative=t;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]*t,n[s*3+1]=i.illuminance[s*3+1]*t,n[s*3+2]=i.illuminance[s*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Aa(this.celestialGroup,lu,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 e=this.lowerCloudCover();if(e<=0){this.disposeCloudSystem();return}const t=this.weather.cloudDarkness,i=new se(mr[0]+(du[0]-mr[0])*t,mr[1]+(du[1]-mr[1])*t,mr[2]+(du[2]-mr[2])*t);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=e,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:n,uniforms:s}=Sd(i,e,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=wd(lu);this.cloudMesh=new Re(r,n),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type!=="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(e=>e.type==="cirrus").reduce((e,t)=>e*(1-t.coverage),1):this.weather.highCloudCover}buildCirrus(){const e=this.weather.highCloudCover??0;if(this.layeredClouds||e<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=e,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:t,uniforms:i}=Sd(new se(...mr),e,$c,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Re(wd(lu*1.04),t),this.cirrusMesh.renderOrder=Bm-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 e=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(e)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,e)}faceCloudDeck(e,t){const i=t<0;e.scale.y=i?-1:1,e.renderOrder=i?Aa.deckOrder(!0,0,1):Bm}cloudLayerOffset(){const t=((this.weather.cloudBaseM??Qd)-this.observerElevationM)*hu;return Math.sign(t||1)*Math.max(Math.abs(t),EE)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,o]=this.cloudBeam.map(u=>u/Math.PI),c=this.lightningLevel*vu*this.relativeScale/Math.PI,l=new se(t[0]+Xn.r*c,t[1]+Xn.g*c,t[2]+Xn.b*c);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),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,o*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(e){return LE(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,mu],[this.rainSplashSystem?.points,gr],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:fu[this.weather.precipitationType].poolSize]];for(const[t,i]of e)t&&i!==void 0&&t.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=Wm(gu(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const e=this.weather.precipitationType;if(e==="none")return;if(e==="rain"){this.buildRain();return}const t=fu[e],i=t.poolSize,n=Mu(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=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 b=0;b<i;b++){const M=n()*Math.PI*2,S=n()*t.radiusM;s[b*3]=Math.cos(M)*S,s[b*3+1]=ma+n()*(t.topYM-ma),s[b*3+2]=Math.sin(M)*S,r[b]=n()*Math.PI*2,o[b]=.7+n()*.6,c[b]=.6+n()*.8,l[b]=.4+n()*1.2}const v=new ot;v.setAttribute("position",new tt(s,3)),v.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new se(...this.baseFogColor)},uTexture:{value:WE(e)},uNearFocusDistance:{value:$m},uHazeDistance:{value:t.radiusM*Km}},g=new ct({uniforms:m,vertexShader:ZE,fragmentShader:JE,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const y=new vs(v,g);y.renderOrder=uu,this.scene.add(y),this.precipitationPoints=y,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=c,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(e,t){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=fu[i];if(this.precipitationUniforms?.uColor.value.copy(kt.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*Yi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-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,v=this.precipitationBounceDuration,m=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,y=i==="snow"&&u&&d,b=i==="hail"&&f&&p&&v&&m&&g;for(let M=0,S=0;M<c.length;M+=3,S++){if(b&&f[S]>0){if(f[S]-=t,f[S]<=0){const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(x)*A,c[M+1]=n.topYM,c[M+2]=Math.sin(x)*A,f[S]=0}else{const x=1-f[S]/v[S];c[M+1]=ma+Math.sin(Math.PI*x)*p[S],c[M]=Jc(c[M]+(r+m[S])*t,n.radiusM),c[M+2]=Jc(c[M+2]+(o+g[S])*t,n.radiusM)}continue}let w=0,T=0;if(y){const x=NE*u[S],A=FE*d[S];w=Math.sin(e*x*Math.PI*2+l[S])*A,T=Math.sin(e*x*Math.PI*2+l[S]+Math.PI/2)*A}if(c[M]+=(r+w)*t,c[M+1]-=n.fallSpeedMPerS*h[S]*t,c[M+2]+=(o+T)*t,c[M]=Jc(c[M],n.radiusM),c[M+2]=Jc(c[M+2],n.radiusM),c[M+1]<ma){if(b){p[S]=eg*(.2+Math.random()*1.6),v[S]=UE*(.5+Math.random()),f[S]=v[S];const I=Math.random()*Math.PI*2,C=kE*(p[S]/eg);m[S]=Math.cos(I)*C,g[S]=Math.sin(I)*C,c[M+1]=ma;continue}const x=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*n.radiusM;c[M]=Math.cos(x)*A,c[M+1]=n.topYM,c[M+2]=Math.sin(x)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=gu(this.weather.precipitationIntensity);this.rainSystem=w5({count:mu,radiusM:uo,heightM:TE,bottomYM:Hm,overallSpeed:RE,color:Vm.clone(),opacity:.85,visibleCount:this.precipitationCount(mu),speedStreak:Wm(e),pixelSize:Jm,seed:9001,nearFocusDistanceM:$m,hazeDistanceM:uo*Km,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=uu,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Mu(4242),t=new Float32Array(gr*3),i=new Float32Array(gr),n=new Float32Array(gr),s=new Float32Array(gr);for(let h=0;h<gr;h++){const u=e()*Math.PI*2,d=Math.sqrt(e())*uo;t[h*3]=Math.cos(u)*d,t[h*3+1]=Hm,t[h*3+2]=Math.sin(u)*d,n[h]=tg(Xm,Ym),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new ot;r.setAttribute("position",new tt(t,3));const o=new tt(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(gr));const c=new ct({uniforms:{uMaxSize:{value:PE},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:qm.clone()},uTexture:{value:qE()}},vertexShader:$E,fragmentShader:KE,transparent:!0,depthWrite:!1}),l=new vs(r,c);l.renderOrder=uu,this.scene.add(l),this.rainSplashSystem={points:l,positions:t,life:i,duration:n,lifeAttribute:o}}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 e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*Yi;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-gu(this.weather.precipitationIntensity),-Math.cos(t)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);e.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(e){const t=this.rainSystem;if(!t)return;t.uniforms.uTime.value+=e,t.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),t.uniforms.uColor.value.copy(kt.litBySky(Vm,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(kt.litBySky(qm,this.baseFogColor));const n=this.weather.windDirectionDeg*Yi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=uo,c=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(c(t.uniforms.uWindOffset.value.x+s*e),c(t.uniforms.uWindOffset.value.y+r*e)),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=jm+(1-jm)*(1-l),u=Qm+(1-Qm)*(1-l);t.uniforms.uUvSquash.value=u,t.uniforms.uPixelSize.value=Jm*h*(.5+.5*u)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:n,duration:s,lifeAttribute:r}=t,o=r.array;for(let c=0,l=0;c<i.length;c+=3,l++){if(n[l]+=e,n[l]>=s[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*uo;i[c]=Math.cos(h)*u,i[c+2]=Math.sin(h)*u,s[l]=tg(Xm,Ym),n[l]=0}o[l]=n[l]/s[l]}t.points.geometry.attributes.position.needsUpdate=!0,r.needsUpdate=!0}setLightning(e){this.lightningFlashes=e}updateLightning(e){let t,i=0;if(this.lightningArmed)for(const c of this.lightningFlashes){if(c.t>e)break;const l=hi.brightnessAt(c,e);l>i&&(t=c,i=l)}const n=t?Math.min(1,Math.max(.1,(HE/t.distanceM)**2)):0,s=i*n*(t?.cloudToGround?1:.6);if(s===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=s,this.scene.fog){const c=this.scene.fog,l=s*vu*this.relativeScale/Math.PI;c.color.setRGB(this.airlight[0]+Xn.r*l,this.airlight[1]+Xn.g*l,this.airlight[2]+Xn.b*l)}const r=this.skyMesh?.material?.color;if(r){const c=s*GE;r.setRGB(1+c*Xn.r,1+c*Xn.g,1+c*Xn.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*vu*this.relativeScale,t){const{x:c,y:l,z:h}=ci(25,t.azimuthDeg,sn);this.lightningLight.position.set(c,l,h)}this.lightningBolt||(this.lightningBolt=new $s(sn*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){const e=Fo(navigator.languages,gE),t=mE[e];this.compassSprites=pE.map((i,n)=>{const s=t[n],r=new cl({map:jE(s),depthTest:!1,fog:!1}),o=new Ja(r),{x:c,y:l,z:h}=ci(0,i,Fm);return o.position.set(c,l,h),o.scale.set(Zc,Zc,1),o.renderOrder=xE,o.layers.set(Dm),o.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(o),o}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=Um*Math.PI/360,i=Zc*Math.tan(e)/Math.tan(t);for(const n of this.compassSprites)n.scale.set(i,i,1)}disposeCompassLabels(){for(const e of this.compassSprites)e.removeFromParent(),e.material.map?.dispose(),e.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const e of this.starTiers)this.disposeMesh(e.points);this.starTiers=[]}disposeMesh(e){if(!e)return;e.removeFromParent(),"geometry"in e&&e.geometry.dispose();const t=e.material;for(const i of Array.isArray(t)?t:[t]){const n=i.map;n&&n.dispose(),i.dispose()}}}const Yi=Math.PI/180;function _a(a,e,t){return Math.max(e,Math.min(t,a))}function tg(a,e){return a+Math.random()*(e-a)}function Jc(a,e){return(a%(e*2)+e*3)%(e*2)-e}let jc,Qc;function WE(a){switch(a){case"snow":return XE();case"hail":return YE()}}function XE(){if(jc)return jc;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),jc=new Ps(e),jc}function YE(){if(Qc)return Qc;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),Qc=new Ps(e),Qc}let el;function qE(){if(el)return el;const a=64,e=document.createElement("canvas");e.width=a,e.height=a;const t=e.getContext("2d"),i=t.createRadialGradient(a/2,a/2,0,a/2,a/2,a/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)"),t.fillStyle=i,t.fillRect(0,0,a,a),el=new Ps(e),el}const $E=`
|
|
7598
7598
|
uniform float uMaxSize;
|
|
7599
7599
|
uniform float uScale;
|
|
7600
7600
|
attribute float aLife;
|
|
@@ -7661,4 +7661,4 @@ void main() {
|
|
|
7661
7661
|
}
|
|
7662
7662
|
`;function ig(a){const t=document.createElement("canvas");t.width=128,t.height=128;const i=t.getContext("2d"),n=128/2-2,s=128/2,r=128/2,o="#010101",c="#f4f1e2";i.fillStyle=o,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const l=_a(a.illuminatedFraction,0,1),h=a.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 Ps(t)}function jE(a){const e=document.createElement("canvas");e.width=128,e.height=128;const t=e.getContext("2d");return t.fillStyle="rgba(0, 0, 0, 0.55)",t.beginPath(),t.arc(64,64,60,0,Math.PI*2),t.fill(),t.fillStyle="#ffffff",t.font="bold 52px sans-serif",t.textAlign="center",t.textBaseline="middle",t.fillText(a,64,68),new Ps(e)}function Mu(a){let e=a;return function(){e|=0,e=e+1831565813|0;let i=Math.imul(e^e>>>15,1|e);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}const xu=7.5,yu=9;class qn{static cache=new Map;static load(e){let t=qn.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>qn.parse(i)),qn.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,o)=>o===0||e[o-1].magnitudeLimit<t);if(i.length<=1)return qn.load(e[0].url);const n=i.map(r=>r.url).join(`
|
|
7663
7663
|
`);let s=qn.cache.get(n);return s||(s=Promise.all(i.map(r=>qn.load(r.url))).then(r=>r.reduce((o,c)=>qn.concat(o,c))),qn.cache.set(n,s)),s}static parse(e){const t=e.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=t*Float32Array.BYTES_PER_ELEMENT;return{count:t,ra:new Float32Array(e,0*i,t),dec:new Float32Array(e,1*i,t),mag:new Float32Array(e,2*i,t),ci:new Float32Array(e,3*i,t)}}static concat(e,t){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:e.count+t.count,ra:i(e.ra,t.ra),dec:i(e.dec,t.dec),mag:i(e.mag,t.mag),ci:i(e.ci,t.ci)}}}const QE=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,eA=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,tA=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,iA=20,nA=1;class sA{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};resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",e);return}}this.context.state==="suspended"&&this.context.resume()}setAmbient(e,t,i){if(this.requested={type:e,intensity:t,windSpeed:i},!this.context)return;this.paused&&(e="none",t=0,i=0);const n=e==="rain"||e==="hail"?e:"none";if(this.ambientVolume=n==="hail"?Math.min(1,t*1.3+.2):n==="rain"?t: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(QE,this.ambientVolume).then(o=>this.applyIfCurrent(o,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/iA,1);const s=i>nA;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(eA,this.windVolume).then(o=>this.applyIfCurrent(o,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(e){if(e===this.paused)return;this.paused=e;const{type:t,intensity:i,windSpeed:n}=this.requested;this.setAmbient(t,i,n)}playThunder(){!this.context||this.paused||this.playOneShot(tA,.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.buffers.clear()}applyIfCurrent(e,t,i,n){if(t!==i()){e?.source.stop();return}n(e)}async startLoop(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n,s.loop=!0;const r=i.createGain();return r.gain.value=t,s.connect(r).connect(i.destination),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(e,t){const i=this.context;if(i)try{const n=await this.getBuffer(e),s=i.createBufferSource();s.buffer=n;const r=i.createGain();r.gain.value=t,s.connect(r).connect(i.destination),s.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(e){const t=this.context;if(!t)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(e);return i||(i=fetch(e).then(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${e}`);return n.arrayBuffer()}).then(n=>t.decodeAudioData(n)),this.buffers.set(e,i)),i}stopSource(e,t){try{e?.stop()}catch{}e?.disconnect(),t?.disconnect()}}class gs{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(gs.SUN_GM_AU3_PER_DAY2*(1+t)/i);this.perihelionPosition=this.scale(n,i),this.perihelionVelocity=this.scale(s,r),this.inverseSemiMajorAxis=(1-t)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(e){const t=e-this.elements.perihelionJd,i=this.universalAnomaly(t),n=this.inverseSemiMajorAxis*i*i,s=this.elements.perihelionAu,r=1-i*i/s*gs.stumpffC(n),o=t-i*i*i/Math.sqrt(gs.SUN_GM_AU3_PER_DAY2)*gs.stumpffS(n);return{x:r*this.perihelionPosition.x+o*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+o*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+o*this.perihelionVelocity.z}}heliocentricDistanceAt(e){const t=this.positionAt(e);return Math.hypot(t.x,t.y,t.z)}universalAnomaly(e){if(e===0)return 0;const t=Math.sign(e),i=Math.sqrt(gs.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=o=>{const c=this.inverseSemiMajorAxis*o*o,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*o*o*o*gs.stumpffS(c)+l*o};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let o=0;o<gs.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);o++){const c=(r+s)/2;n(c)<i?r=c:s=c}return t*(r+s)/2}perifocalAxes(){const e=this.elements.ascendingNodeDeg*Math.PI/180,t=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,n=Math.cos(e),s=Math.sin(e),r=Math.cos(t),o=Math.sin(t),c=Math.cos(i),l=Math.sin(i);return[{x:n*r-s*o*c,y:s*r+n*o*c,z:o*l},{x:-n*o-s*r*c,y:-s*o+n*r*c,z:r*l}]}scale(e,t){return{x:e.x*t,y:e.y*t,z:e.z*t}}static stumpffC(e){if(Math.abs(e)<1e-6)return 1/2-e/24+e*e/720;if(e>0)return(1-Math.cos(Math.sqrt(e)))/e;const t=Math.sqrt(-e);return(Math.cosh(t)-1)/-e}static stumpffS(e){if(Math.abs(e)<1e-6)return 1/6-e/120+e*e/5040;if(e>0){const i=Math.sqrt(e);return(i-Math.sin(i))/(i*i*i)}const t=Math.sqrt(-e);return(Math.sinh(t)-t)/(t*t*t)}}const ev=[{id:"halley-1910",designation:"1P/Halley",name:{en:"Halley's Comet",fr:"comète de Halley"},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:{en:"Comet Brooks",fr:"comète 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:{en:"Comet Skjellerup-Maristany",fr:"comète 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:{en:"Comet de Kock-Paraskevopoulos",fr:"comète 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:{en:"the Southern Comet",fr:"comète australe"},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:{en:"the Eclipse Comet",fr:"comète de l'éclipse"},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:{en:"Comet Arend-Roland",fr:"comète 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:{en:"Comet Mrkos",fr:"comète 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:{en:"Comet Seki-Lines",fr:"comète 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:{en:"Comet Ikeya-Seki",fr:"comète 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:{en:"Comet Bennett",fr:"comète 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:{en:"Comet White-Ortiz-Bolelli",fr:"comète 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:{en:"Comet Kohoutek",fr:"comète 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:{en:"Comet West",fr:"comète 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:{en:"Comet IRAS-Araki-Alcock",fr:"comète 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:{en:"Halley's Comet",fr:"comète de Halley"},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:{en:"Comet Hyakutake",fr:"comète 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:{en:"Comet Hale-Bopp",fr:"comète 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:{en:"Comet McNaught",fr:"comète 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:{en:"Comet Lovejoy",fr:"comète 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:{en:"Comet PANSTARRS",fr:"comète 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:{en:"Comet NEOWISE",fr:"comète 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:{en:"Comet Tsuchinshan-ATLAS",fr:"comète 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 rA{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(e){const t=this.julianDayOf(e);return ev.filter(i=>Math.abs(t-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(e,t){return this.aroundDate(e).map(i=>this.appearanceOf(i,e,t)).sort((i,n)=>i.magnitude-n.magnitude)[0]}static appearanceOf(e,t,i){const n=Wt(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),o=this.subtract(r,s),c=this.length(r),l=this.length(o),h=this.tailEndAt(e,r,s,c,n,t,i),u=this.horizontalOf(o,n,t,i);return{apparition:e,position:u,...h,heliocentricDistanceAu:c,earthDistanceAu:l,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,c,l)}}static magnitudeAt(e,t,i){const n=e.absoluteMagnitude+5*Math.log10(i)+2.5*e.activityExponent*Math.log10(t);return Math.max(n,e.peakMagnitude)}static tailEndAt(e,t,i,n,s,r,o){if(e.tailLengthAu===void 0)return{};const c=1+e.tailLengthAu/n,l=this.subtract({x:t.x*c,y:t.y*c,z:t.z*c},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(l,s,r,o),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(e,t,i){const n=this.orbitOf(e);let s=n.positionAt(t);for(let r=0;r<2;r++){const o=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-o)}return s}static horizontalOf(e,t,i,n){const s=Ia(Qw(),new Lt(e.x,e.y,e.z,t)),r=Ia(B1(t),s),o=Pw(t,new U0(n.lat,n.lng,n.elevationM)),c=new Lt(r.x-o.x,r.y-o.y,r.z-o.z,t),l=z0(c);return B0(l.ra,l.dec,i,n)}static earthPositionAt(e){return Ia(jw(),ir(Se.Earth,e))}static julianDayOf(e){return 2451545+Wt(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new gs(e.orbit);return this.orbits.set(e.id,i),i}static subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}static length(e){return Math.hypot(e.x,e.y,e.z)}static angleBetween(e,t){const i=(e.x*t.x+e.y*t.y+e.z*t.z)/(this.length(e)*this.length(t)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const _u=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:{en:"Supernova of 1006",fr:"supernova de 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:{en:"Supernova of 1054",fr:"supernova de 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:{en:"Supernova of 1181",fr:"supernova de 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:{en:"Tycho's Supernova",fr:"supernova de Tycho"},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:{en:"Kepler's Supernova",fr:"supernova de Kepler"},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:{en:"Nova Coronae Borealis 1866",fr:"nova de la Couronne boréale 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:{en:"Nova Aurigae 1891",fr:"nova du Cocher 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:{en:"Nova Persei 1901",fr:"nova de Persée 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:{en:"Nova Geminorum 1912",fr:"nova des Gémeaux 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:{en:"Nova Aquilae 1918",fr:"nova de l'Aigle 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:{en:"Nova Cygni 1920",fr:"nova du Cygne 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:{en:"Nova Pictoris 1925",fr:"nova du Peintre 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:{en:"Nova Herculis 1934",fr:"nova d'Hercule 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:{en:"Nova Lacertae 1936",fr:"nova du Lézard 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:{en:"Nova Puppis 1942",fr:"nova de la Poupe 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:{en:"Nova Coronae Borealis 1946",fr:"nova de la Couronne boréale 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:{en:"Nova Herculis 1960",fr:"nova d'Hercule 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:{en:"Nova Herculis 1963",fr:"nova d'Hercule 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:{en:"Nova Delphini 1967",fr:"nova du Dauphin 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:{en:"Nova Vulpeculae 1968",fr:"nova du Petit Renard 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:{en:"Nova Serpentis 1970",fr:"nova du Serpent 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:{en:"Nova Cygni 1975",fr:"nova du Cygne 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:{en:"Nova Centauri 1986",fr:"nova du Centaure 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:{en:"Supernova 1987A",fr:"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:{en:"Nova Cygni 1992",fr:"nova du Cygne 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:{en:"Nova Velorum 1999",fr:"nova des Voiles 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:{en:"Nova Aquilae 1999",fr:"nova de l'Aigle 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:{en:"Nova Sagittarii 2002",fr:"nova du Sagittaire 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:{en:"Nova Ophiuchi 2006",fr:"nova d'Ophiuchus 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:{en:"Nova Scorpii 2007",fr:"nova du Scorpion 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:{en:"Nova Delphini 2013",fr:"nova du Dauphin 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:{en:"Nova Centauri 2013",fr:"nova du Centaure 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:{en:"Nova Ophiuchi 2021",fr:"nova d'Ophiuchus 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 ng{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return _u.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of _u){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:In.ofJ2000(s.raHours,s.decDeg,e,t),magnitude:r})}return n.sort((s,r)=>s.magnitude-r.magnitude)}static brightestAt(e,t){return this.appearancesAt(e,t)[0]}static byId(e){return _u.find(t=>t.id===e)}static magnitudeAt(e,t){const i=e.lightCurve,n=t-e.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,o]=i[s-1]??i[0],[c,l]=i[s]??i[0];if(c===r)return o;const h=Math.min(1,Math.max(0,(n-r)/(c-r)));return o+h*(l-o)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const aA=[{id:"quadrantids",code:"QUA",name:{en:"Quadrantids",fr:"Quadrantides"},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:{en:"April Lyrids",fr:"Lyrides d'avril"},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:{en:"eta Aquariids",fr:"Êta Aquarides"},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:{en:"alpha Capricornids",fr:"Alpha Capricornides"},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:{en:"Southern delta Aquariids",fr:"Delta Aquarides du Sud"},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:{en:"Perseids",fr:"Perséides"},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:{en:"Southern Taurids",fr:"Taurides du Sud"},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:{en:"October Draconids",fr:"Draconides d'octobre"},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:{en:"Orionids",fr:"Orionides"},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:{en:"Northern Taurids",fr:"Taurides du Nord"},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:{en:"Leonids",fr:"Léonides"},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:{en:"Geminids",fr:"Géminides"},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:{en:"Ursids",fr:"Ursides"},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}],Bl=6.5;class bu{static activeAt(e){return aA.flatMap(t=>{const i=this.nearness(t,e);return i<=0?[]:[{shower:t,zhr:t.peakZhr*i,nearness:i}]})}static nearness(e,t){const i=this.dayOfYear(t),n=this.dayOfYear(this.asDate(e.start)),s=this.dayOfYear(this.asDate(e.peak)),r=this.dayOfYear(this.asDate(e.end)),o=this.wrappedDelta(i,s),c=this.wrappedDelta(s,n),l=this.wrappedDelta(r,s);return o<0?o<-c?0:1+o/c:o>0?o>l?0:1-o/l:1}static observedRatePerHour(e,t,i,n=Bl){if(t<=0)return 0;const s=Bl-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return In.ofJ2000(e.radiantRaHours,e.radiantDecDeg,t,i)}static dayOfYear(e){const t=Date.UTC(e.getUTCFullYear(),0,1);return Math.floor((Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())-t)/864e5)+1}static asDate(e){return new Date(Date.UTC(2001,e.month-1,e.day))}static wrappedDelta(e,t){const i=e-t;return i>182?i-365:i<-182?i+365:i}}class Zt{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=Wt(e),n=new Ql(0,Cw(e).elon-90,1),s=Ia(t5(i),k0(n,i)),r=z0(s);return B0(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=Bl){const i=Zt.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=Bl-t;return(Zt.QUIET_RATE_PER_HOUR+i)/Math.pow(Zt.POPULATION_INDEX,n)}static schedule(e){const t=new ih(e.seed^1542469173);return Pr.schedule(e).map(i=>{const n=Zt.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=Zt.turnAround(n,t.between(0,360)),o={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:Zt.toHorizontal(o),bearingDeg:Zt.bearingFrom(o,n)}})}static turnAround(e,t){const[i,n]=Zt.basisAround(e),s=t*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(e,t){const[i,n]=Zt.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=Zt.normalise({x:t.x-e.x*s,y:t.y-e.y*s,z:t.z-e.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(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=Zt.normalise(Zt.cross(e,t));return[i,Zt.normalise(Zt.cross(e,i))]}static toHorizontal(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,e.y/t)))*180/Math.PI,azimuthDeg:(Math.atan2(e.x,-e.z)*180/Math.PI%360+360)%360}}static appearanceOf(e){const t=Zt.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=Zt.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return Zt.toHorizontal({x:t.x*Math.cos(n)+i.x*Math.sin(n),y:t.y*Math.cos(n)+i.y*Math.sin(n),z:t.z*Math.cos(n)+i.z*Math.sin(n)})}static toCartesian(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,n=Math.cos(t);return{x:n*Math.sin(i),y:Math.sin(t),z:-n*Math.cos(i)}}static cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}static normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}static TYPICAL_VELOCITY_KM_S=40}const sg="https://ufoathome.org/tle/index.json";class Di{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Di.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/tle/index.json",location.href).href),e.includes(sg)||e.push(sg),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${Di.FIRST_SNAPSHOT}T00:00:00Z`)-Di.MAX_ELEMENT_AGE_DAYS*Di.DAY_MS;if(e.getTime()<t)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(n=>e.getTime()>=Date.parse(n.from)-Di.MAX_ELEMENT_AGE_DAYS*Di.DAY_MS&&e.getTime()<=Date.parse(n.to)+Di.MAX_ELEMENT_AGE_DAYS*Di.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const o of Object.keys(i.kinds)){const c=await this.kindAt(o,e,i,n);s.push(...c),r.push(this.coverageOf(o,e,i,c.length>0))}return{objects:s,coverage:r,credit:i.credit,creditUrl:i.source}}async kindAt(e,t,i,n){const s=t.getTime(),r=i.binDays*Di.DAY_MS,o=Math.floor(s/r),c=s-o*r<r/2?o-1:o+1,l=new Set(i.kinds[e].bins),h=[o,c].map(v=>new Date(v*r).toISOString().slice(0,10)).filter(v=>l.has(v));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(v=>this.binary(new URL(`${e}/${v}.bin`,n).href))]),f=new Map;for(const v of d)for(const m of Di.decode(v,i.recordBytes)){const g=f.get(m.norad);(!g||Math.abs(m.epochMs-s)<Math.abs(g.epochMs-s))&&f.set(m.norad,m)}const p=[];for(const v of f.values()){const m=Math.abs(v.epochMs-s)/Di.DAY_MS;if(m>Di.MAX_ELEMENT_AGE_DAYS)continue;const g=u[v.norad]??{name:String(v.norad)};g.launch&&Date.parse(`${g.launch}T00:00:00Z`)>s||p.push({norad:v.norad,name:g.name,kind:e,launch:g.launch,stdMag:g.stdMag,elements:v,ageDays:m})}return p}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],o=t.getTime(),c=Di.MAX_ELEMENT_AGE_DAYS*Di.DAY_MS,l=n?"covered":o<Date.parse(s)-c?"before":o>Date.parse(r)+c?"after":"gap";return{kind:e,status:l,from:s,to:r}}static decode(e,t){const i=new DataView(e),n=[];for(let s=0;s+t<=e.byteLength;s+=t)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 e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;return{index:await t.json(),base:e}}catch{}})(),this.index}json(e){return this.cached(e,async t=>t.json())}binary(e){return this.cached(e,async t=>t.arrayBuffer())}cached(e,t){let i=this.files.get(e);return i||(i=this.fetchImpl(e).then(n=>{if(!n.ok)throw new Error(`${e}: ${n.status}`);return t(n)}),i.catch(()=>this.files.delete(e)),this.files.set(e,i)),i}}class oA{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=Pt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=Pt.sizeMAt(t.inFrontM,e);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(e){return e<=0?{}:{minM:this.lowerM===void 0?void 0:Pt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:Pt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Or{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*Or.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=Or.degOver(e)/t;return i<1?1:Math.min(Or.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class ki{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 Or.DEG_PER_SECOND*3600}static graspOf(e,t={}){const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return ki.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??ki.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,o=ki.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,ki.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,i){const s=(e.detailUm??ki.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*ki.ARCSEC_PER_RADIAN,r=1.22*ki.WAVELENGTH_M/(i/1e3)*ki.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/ki.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=ki.graspOf(e,t),n=ki.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,o=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*o)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:ni.focalLengthMmFor(e,t.fieldOfViewDeg);return ki.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const rg=111320,fo=Math.PI/180,cA=1.02,lA=1;class Co{static of(e,t){const i=Co.sightings(e,t);if(i.length<2)return;const n=Co.baseline(i);if(!n)return;const{near:s,far:r,closedM:o}=n,c=Math.tan(r.widthDeg/2*fo)===0?0:Math.tan(s.widthDeg/2*fo)/Math.tan(r.widthDeg/2*fo);if(c<cA)return;const l=o/(c-1),h=Pt.sizeMAt(l,s.widthDeg),u=i.map(d=>({t:d.t,m:Pt.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:r.t,toT:s.t,closedM:o}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(o=>o.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=Jt(e,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(e){let t;for(const i of e)for(const n of e){if(i.t>=n.t)continue;const s=Co.closedAlongSight(i,n),[r,o,c]=s>=0?[n,i,s]:[i,n,-s];c<lA||r.widthDeg<=o.widthDeg||(!t||c>t.closedM)&&(t={near:r,far:o,closedM:c})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*rg,n=(t.lng-e.lng)*rg*Math.cos(e.lat*fo),s=(e.sightAzimuthDeg??0)*fo;return i*Math.cos(s)+n*Math.sin(s)}}class Ui{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:Ui.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:Ui.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:Ui.atLeastNearest(e.derivedM),basis:"derived"};const t=Ui.largest(e.range?.minM,e.crossing?.behindM),i=Ui.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*Ui.MARGIN,s=i===void 0?void 0:i/Ui.MARGIN;return n!==void 0&&s!==void 0?{distanceM:Ui.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:Ui.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<Ui.CONVENTIONAL_M?{distanceM:Ui.atLeastNearest(s),basis:"bounded"}:{distanceM:Ui.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(Ui.NEAREST_M,e)}static largest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.max(...t)}static smallest(...e){const t=e.filter(i=>i!==void 0&&i>0);return t.length===0?void 0:Math.min(...t)}}const Su=Math.PI/180;class Qe{constructor(e,t,i){this.body=e,this.ground=t;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Qe.collect(this.motionKeys,s.t,s.motions),Qe.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};keys;motionKeys=new Map;lightKeys=new Map;static collect(e,t,i){for(const[n,s]of Object.entries(i??{})){const r=e.get(n)??[];r.push({t,value:s}),e.set(n,r)}}motionsAt(e){return Qe.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?Qe.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let o=r.length-1;for(;o>=0&&r[o].t>t;)o--;if(o<0){i!==void 0&&(n[s]=i);continue}const c=r[o],l=r[Math.min(o+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(t-c.t)/(l.t-c.t));n[s]=Qe.lerp(c.value,l.value,h)}return n}static eyeOf(e,t,i){const n=Jt(e,0),s=Jt(e,t),o=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ii(s.lat,s.lng,n.lat,n.lng):void 0,c=o?o.x:0,l=o?-o.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Qe.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=Qe.directionOf(t,i),r=l=>e.upM+s.upM*l-n.heightAt(e.eastM+s.eastM*l,e.northM+s.northM*l);let o=0,c=0;for(;c<Qe.MAX_RANGE_M;){if(c=o+Math.max(.5,o*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(o+c)/2;r(h)<=0?c=h:o=h}return c}o=c}}static directionOf(e,t){const i=e*Su,n=t*Su;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(e){const t=this.keys;if(t.length===0||e<t[0].t)return;let i=t.length-1;for(;i>0&&t[i].t>e;)i--;const n=t[i];if(!n.present)return;const s=t[Math.min(i+1,t.length-1)],r=s===n||s.t===n.t?0:Math.min(1,(e-n.t)/(s.t-n.t)),o=Qe.lerp(n.eastM,s.eastM,r),c=Qe.lerp(n.northM,s.northM,r),l={widthM:Qe.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:Qe.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:Qe.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},h={headingDeg:Qe.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:Qe.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:Qe.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let u;if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const d=Qe.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);u=this.groundUnderFootprint(o,c,l,h.headingDeg)+d+l.heightM/2}else u=Qe.lerp(this.centreUpOf(n),this.centreUpOf(s),r);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:o,northM:c,upM:u,sizeM:l,attitude:h,appearance:{color:(r<1?n:s).appearance.color,albedo:Qe.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:Qe.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r)},flame:Qe.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(d=>d.flame!==void 0&&d.flame.luminanceCdM2>0)}}static flameBetween(e,t,i){if(!e||e.luminanceCdM2<=0)return i>=1&&t&&t.luminanceCdM2>0?t:void 0;const n=e,s=t??e,r={...i<1?n:s,lengthM:Qe.lerp(n.lengthM,s.lengthM,i),widthM:Qe.lerp(n.widthM,s.widthM,i),luminanceCdM2:Qe.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){return"upM"in e.vertical?e.vertical.upM:this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2}groundUnderFootprint(e,t,i,n){const s=n*Su,r={eastM:Math.cos(s),northM:-Math.sin(s)},o={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(e,t);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(e+r.eastM*u+o.eastM*d,t+r.northM*u+o.northM*d))}return c}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??Qe.DEFAULT_SIZE,o={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??Qe.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Qe.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Qe.DEFAULT_APPEARANCE.luminanceCdM2},l=this.positionOf(s,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;n={t:s.t,...l,sizeM:r,attitude:o,appearance:c,flame:h,present:u},i.push(n)}return i}verticalOf(e){if(e.onGround)return{aboveGroundM:0};if(e.altitudeAboveGroundM!==void 0)return{aboveGroundM:e.altitudeAboveGroundM}}positionOf(e,t){if(e.eastM!==void 0&&e.northM!==void 0)return{eastM:e.eastM,northM:e.northM,vertical:this.verticalOf(e)??{aboveGroundM:0}};if(e.azimuthDeg===void 0||e.altitudeDeg===void 0)return;const i=t(e.t);if(!i)return;const n=e.distanceM??(e.onGround?Qe.lineOfSightMeetsGround(i,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(n===void 0)return;const s=Qe.directionOf(e.azimuthDeg,e.altitudeDeg),r=i.eastM+s.eastM*n,o=i.northM+s.northM*n;return{eastM:r,northM:o,vertical:this.verticalOf(e)??{upM:i.upM+s.upM*n}}}static lerp(e,t,i){return e+(t-e)*i}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}const da=Math.PI/180,po=180/Math.PI;class Kt{constructor(e){this.timeline=e}static DIRECTION_TOLERANCE_DEG=1;static SIZE_TOLERANCE=1.5;static RINGS=12;static SEGMENTS=24;at(e,t,i,n){const s=[];for(const r of t){const o=Kt.projectionOf(r,i,n?.(r));if(o)for(const c of r.explains){const l=this.timeline.getInterpolatedShapeAt(e,c);!l||l.transparency>=1||s.push({...Kt.compare(c,r.id,{aim:l.aim,angular:l.angular},o),title:l.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?Kt.separationDeg(i.aim,n.aim):void 0;if(r!==void 0){const l=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;r>Math.max(Kt.DIRECTION_TOLERANCE_DEG,l)&&s.push("direction")}const o=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,c=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0;return o!==void 0&&!Kt.withinSize(o)&&s.push("width"),c!==void 0&&!Kt.withinSize(c)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:o,heightRatio:c,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:Kt.outlineOf(e),s=i&&i.length>0?Kt.centreOf(i):e,r=Kt.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const o=Kt.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},c=Kt.cross(o,r);let l=1/0,h=-1/0,u=1/0,d=-1/0;for(const f of n){const p={eastM:f.eastM-t.eastM,northM:f.northM-t.northM,upM:f.upM-t.upM},v=Kt.dot(p,r);if(v<=0)return;const m=Math.atan2(Kt.dot(p,o),v),g=Math.atan2(Kt.dot(p,c),v);l=Math.min(l,m),h=Math.max(h,m),u=Math.min(u,g),d=Math.max(d,g)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*po+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*po},angular:{widthDeg:(h-l)*po,heightDeg:(d-u)*po}}}static centreOf(e){const t=i=>(Math.min(...e.map(n=>n[i]))+Math.max(...e.map(n=>n[i])))/2;return{eastM:t("eastM"),northM:t("northM"),upM:t("upM")}}static separationDeg(e,t){const i=e.altitudeDeg*da,n=t.altitudeDeg*da,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*da);return Math.acos(Math.max(-1,Math.min(1,s)))*po}static withinSize(e){return e<=Kt.SIZE_TOLERANCE&&e>=1/Kt.SIZE_TOLERANCE}static outlineOf(e){const t=e.sizeM.widthM/2,i=e.sizeM.lengthM/2,n=e.sizeM.heightM/2,s=[],r=e.model.url===void 0?e.model.id:void 0;if(r!==void 0&&r!=="box"&&J1.includes(r))for(let u=0;u<=Kt.RINGS;u++){const d=u/Kt.RINGS*Math.PI;for(let f=0;f<Kt.SEGMENTS;f++){const p=f/Kt.SEGMENTS*2*Math.PI;s.push([t*Math.sin(d)*Math.cos(p),i*Math.sin(d)*Math.sin(p),n*Math.cos(d)])}}else for(const u of[-t,t])for(const d of[-i,i])for(const f of[-n,n])s.push([u,d,f]);const c=e.attitude.headingDeg*da,l=e.attitude.pitchDeg*da,h=e.attitude.rollDeg*da;return s.map(([u,d,f])=>{const p=u*Math.cos(h)+f*Math.sin(h),v=-u*Math.sin(h)+f*Math.cos(h),m=d*Math.cos(l)-v*Math.sin(l),g=d*Math.sin(l)+v*Math.cos(l);return{eastM:e.eastM+p*Math.cos(c)+m*Math.sin(c),northM:e.northM-p*Math.sin(c)+m*Math.cos(c),upM:e.upM+g}})}static dot(e,t){return e.eastM*t.eastM+e.northM*t.northM+e.upM*t.upM}static cross(e,t){return{eastM:e.northM*t.upM-e.upM*t.northM,northM:e.upM*t.eastM-e.eastM*t.upM,upM:e.eastM*t.northM-e.northM*t.eastM}}static normalized(e){const t=Math.hypot(e.eastM,e.northM,e.upM);return t>1e-9?{eastM:e.eastM/t,northM:e.northM/t,upM:e.upM/t}:void 0}}Dg();const hA={sun:{en:"Sun",fr:"Soleil"},moon:{en:"Moon",fr:"Lune"},Venus:{en:"Venus",fr:"Vénus"},Mars:{en:"Mars",fr:"Mars"},Jupiter:{en:"Jupiter",fr:"Jupiter"},Saturn:{en:"Saturn",fr:"Saturne"}},uA=["en","fr"],dA={en:"{name} — mag {mag}, {alt}° above the horizon",fr:"{name} — mag {mag}, {alt}° au-dessus de l'horizon"},fA={en:"{name} — satellite, mag {mag}, {height} km up",fr:"{name} — satellite, mag {mag}, à {height} km d'altitude"},pA="satellites-change",tv="rr0-confrontation",mA={en:"{name} — mag {mag}, {alt}° below the horizontal",fr:"{name} — mag {mag}, {alt}° sous l'horizontale"},ag="comet:",og="nova:",gA={building:{en:"Building",fr:"Bâtiment"},tree:{en:"Tree",fr:"Arbre"},shrub:{en:"Shrub",fr:"Buisson"},bridge:{en:"Bridge",fr:"Pont"},crop:{en:"Crop row",fr:"Rang de culture"},mound:{en:"Stone heap",fr:"Tas de pierres"},streetlight:{en:"Streetlight",fr:"Lampadaire"},vehicle:{en:"Vehicle",fr:"Véhicule"},observer:{en:"Observer",fr:"Observateur"},aircraft:{en:"Aircraft",fr:"Aéronef"},entity:{en:"Being",fr:"Être"}},vA=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,MA=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,xA=-18,yA={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},wu={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class V0 extends HTMLElement{creditsButton;set ownCredits(e){this.creditsButton.hidden=!e}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Ss,ws]}shadow;stageElement;frameElement;sceneCanvas;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new R;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Di;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;starCatalogDepth=0;weatherAudio=new sA;vehicleAudio=new Yv;vehicleHearing=new vl;animateWhilePausedValue=!1;set animateWhilePaused(e){e!==this.animateWhilePausedValue&&(this.animateWhilePausedValue=e,this.syncAnimationsToPlayback())}get animateWhilePaused(){return this.animateWhilePausedValue}thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{this.sceneRenderer.setCompassHovered(!0);const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*t.width,s=(e.clientY-i.top)/i.height*t.height;if(this.ufoElement.hasVisibleShapeAt(n,s)){this.hoverTooltip.hidden=!0;return}const r=(e.clientX-i.left)/i.width*2-1,o=-((e.clientY-i.top)/i.height*2-1),c=Fo(Ir.preferencesFor(this),uA),l=this.sceneRenderer.pickBodyAt(r,o);if(l){this.showHoverTooltip(e,this.bodyName(l,c));return}const h=this.sceneRenderer.pickDecorAt(r,o),u=h?this.ufoElement.sighting.decor.find(p=>p.id===h):void 0;if(u){this.showHoverTooltip(e,this.said.read(u.title)||gA[u.kind][c]);return}const d=this.sceneRenderer.pickSatelliteAt(r,o);if(d){this.showHoverTooltip(e,fA[c].replace("{name}",d.name).replace("{mag}",d.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(d.heightKm).toLocaleString()));return}const f=this.sceneRenderer.pickStarAt(r,o);if(f){const p=f.star.mag,v=f.altitudeDeg,m=(v<0?mA:dA)[c];this.showHoverTooltip(e,m.replace("{name}",f.star.name[c]).replace("{mag}",p.toLocaleString(void 0,{maximumFractionDigits:Math.abs(p)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(v)))));return}this.hoverTooltip.hidden=!0};bodyName(e,t){const i=e.startsWith(ag)?e.slice(ag.length):void 0,n=i?ev.find(r=>r.id===i):void 0,s=e.startsWith(og)?ng.byId(e.slice(og.length)):void 0;return n?.name[t]??s?.name[t]??hA[e]?.[t]??e}showHoverTooltip(e,t){this.hoverTooltip.textContent=t,this.hoverTooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.hoverTooltip.style.left=`${e.clientX-i.left+12}px`,this.hoverTooltip.style.top=`${e.clientY-i.top+12}px`}handlePointerLeave=()=>{this.hoverTooltip.hidden=!0,this.sceneRenderer.setCompassHovered(!1)};handleLightningFlash(e){clearTimeout(this.thunderTimeoutId),this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),hi.thunderDelayMs(e))}handleFirstInteraction=()=>{this.removeEventListener("pointerdown",this.handleFirstInteraction,!0),this.removeEventListener("keydown",this.handleFirstInteraction,!0),this.weatherAudio.resume(),this.vehicleAudio.resume(),this.setWeather(sf(this.ufoElement.sighting,this.lastTimeMs))};handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now())};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing",t=e||this.animateWhilePaused;this.sceneRenderer.setAnimationsRunning(t,e),this.weatherAudio.setPaused(!t),this.vehicleAudio.setPaused(!t),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${$v}</style>${qv}`,this.shadow.appendChild(e.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 kt(this.sceneCanvas);const t=this.shadow.getElementById("scene-loader");this.sceneRenderer.onFirstFrameHold=r=>{t.hidden=!r},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(Du),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",r=>this.lookToward(r.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",r=>{r.newState==="open"&&Tn.fill(n,this)});const s=Fo(Ir.preferencesFor(this),["en","fr"])==="fr"?"Crédits":"Credits";this.creditsButton.title=s,this.creditsButton.setAttribute("aria-label",s),this.sceneRenderer.onMapSubjectBounds=r=>this.ufoElement.setMapSubjectBounds(r),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("referenceview",r=>this.applyReferenceView(r.detail)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave),this.addEventListener("pointerdown",this.handleFirstInteraction,!0),this.addEventListener("keydown",this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Pn(Ir.preferencesFor(this))}saidTexts;connectedCallback(){this.saidTexts=void 0,this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),document.addEventListener("fullscreenchange",this.handleFullscreenChange);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange),this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(e,t,i){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),(e==="star-catalog-src"||e==="deep-star-catalog-src")&&i!==t&&this.isConnected&&this.loadStars(),e==="show-compass"&&i!==t&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),e==="max-pixel-ratio"&&i!==t){const n=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(n)&&n>0?n:Math.min(window.devicePixelRatio||1,2))}(e===Ss||e===ws)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[Ss,ws]){const t=this.getAttribute(e);t===null?this.ufoElement.removeAttribute(e):this.ufoElement.setAttribute(e,t)}}setCompassForced(e){this.sceneRenderer.setCompassForced(e)}lookToward(e){const t=Jt(this.ufoElement.sighting,this.lastTimeMs);if(e.kind==="observer"||t?.lat===void 0||t.lng===void 0||t.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:n}=ii(e.lat,e.lng,t.lat,t.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-t.headingDeg)%360+540)%360-180,-t.pitchDeg)}setLookOffset(e,t){this.sceneRenderer.setLookOffset(e,t),this.ufoElement.setLookOffset(e,t),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(e,t){this.sceneRenderer.setIndoorLook(e,t)}setCloudRendering(e){this.sceneRenderer.setCloudRendering(e)}setWeather(e){this.sceneRenderer.setWeather(e),this.weatherAudio.setAmbient(e.precipitationType,e.precipitationIntensity*(e.precipitationAmount??1),e.windSpeed)}pickCloudAt(e,t){return this.sceneRenderer.pickCloudAt(e,t)}cloudDirectionAt(e,t){return this.sceneRenderer.cloudDirectionAt(e,t)}pickDecorAt(e,t){return this.sceneRenderer.pickDecorAt(e,t)}bodyScreenBox(e){return this.sceneRenderer.bodyScreenBox(e)}pickPlacedBodyAt(e,t){return this.sceneRenderer.pickPlacedBodyAt(e,t)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume()}async loadFromSrc(e){const t=await bo.json(e);this.documentUrl=new URL(e,location.href).href,this.sightingData=t}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(e){this.sceneRenderer.documentUrl=e}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.ufoElement.sightingData=e,this.interpretationShown=this.inTheRound?this.ufoElement.sighting.interpretation:void 0,this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}referenceAspect(e){return this.sceneRenderer.referenceAspect(e)}screenPointOf(e){return this.sceneRenderer.screenPointOf(e)}directionAt(e,t){return this.sceneRenderer.directionAt(e,t)}referenceFailedToLoad(e){return this.sceneRenderer.referenceFailedToLoad(e)}applyReferenceView(e){this.sceneRenderer.setReferencesShown(e.shown);for(const t of this.ufoElement.sighting.references)this.sceneRenderer.setReferenceView(t.id,{opacity:e.opacity})}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}setTerrainProviders(e){this.sceneRenderer.setTerrainProviders(e)}setDecorModelProvider(e){this.sceneRenderer.setDecorModelProvider(e)}get decorModelCredits(){return this.sceneRenderer.currentDecorModelCredits}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=Pt.CANVAS_HEIGHT_PX,i=ni.frameWidthPx(e,t);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${t}`)}resizeToStage(){const e=this.frameElement.getBoundingClientRect(),t=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height));this.sceneCanvas.width=t,this.sceneCanvas.height=i,this.sceneRenderer.resize(t,i)}async loadStars(){const e=[{magnitudeLimit:xu,url:this.getAttribute("star-catalog-src")??vA},{magnitudeLimit:yu,url:this.getAttribute("deep-star-catalog-src")??MA}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>xu?yu:xu;const n=await qn.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=yu||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=ki.gainFor(e.instrument,{fNumber:Jt(e,0)?.fNumber,fieldOfViewDeg:Ji.fovOf(e,0),exposureSeconds:e.exposure});return ul(xA,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Cn.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=Or.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,Cn.instants(this.ufoElement.sighting.decor,Jt(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,o=>this.applySceneAt(t.fromMs+t.ms*o/(r-1),{sky:Math.floor(o*s/r)!==Math.floor((o-1)*s/r),stepMs:t.ms/r}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(e){const t=this.sceneCanvas.height;return t<=0?0:Ji.fovOf(this.ufoElement.sighting,e)/t}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather(sf(i,e)),this.sceneRenderer.setInstrument(i.instrument),t||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,e)),this.updateMeteorShower(i,e),this.updateLightning(i,e,t!==void 0),this.sceneRenderer.setDecor(i.decor);const n=Jt(i,e);this.sceneRenderer.setReferences(i.references,n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:void 0);const s=Jt(i,0),r=fa(i,0),o=Object.fromEntries(ml(fa(i,e)).map(b=>[b.id,ff(e,i.weatherTrack,r,s,n,b.id)]));this.sceneRenderer.setCloudOffset(ff(e,i.weatherTrack,r,s,n),o),this.sceneRenderer.setObserverPose(n??wu),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(ki.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Ji.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setGait(xt.bodyAt(i,e,this.ufoElement.steadyObserver)),this.sceneRenderer.updateDecorAnchoring(Jt(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.sceneRenderer.setTerrainOrigin(n?.lat,n?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.pushPhenomenaAt(e);const c=n?.lat??wu.lat,l=n?.lng??wu.lng,h=xo(i.event.time??{},l,i.event.utcOffsetHours),u={lat:c,lng:l,elevationM:n?.elevationM??0};if(this.pushSatellitesAt(h,e,u),t&&!t.sky)return;if(!h){this.sceneRenderer.setAstronomy(yA);return}const d=new Date(h.getTime()+e),f=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/Or.DEG_PER_SECOND*1e3)),p=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),v=`${Math.floor(d.getTime()/f)}|${Math.round(c/p)}|${Math.round(l/p)}|${Math.round(u.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(v===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=v;const m={...Zh("Sun",d,u),magnitude:Jh("Sun",d)},g={...Zh("Moon",d,u),phase:n5(d),magnitude:Jh("Moon",d)},y=i5.map(b=>({body:b,position:Zh(b,d,u),magnitude:Jh(b,d)}));this.sceneRenderer.setAstronomy({sun:m,moon:g,planets:y,comet:this.cometAt(d,u),novae:ng.appearancesAt(d,u).map(({outburst:b,position:M,magnitude:S})=>({id:b.id,position:M,magnitude:S})),stars:this.starCatalog?{catalog:this.starCatalog,date:d,observer:u}:void 0,frame:{date:d,observer:u}}),this.ufoElement.setSunAltitude(m.altitudeDeg)}pushSatellitesAt(e,t,i){if(this.ensureSatellites(e),!e||!this.satellites){this.sceneRenderer.setSatellites([]);return}const n=new Date(e.getTime()+t),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)}ensureSatellites(e){const t=e?String(e.getTime()):"";if(t===this.satellitesFor)return;this.satellitesFor=t,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!e){this.satelliteStatus="none";return}this.satelliteStatus="loading";const n=r=>{i===this.satelliteRequest&&(this.satelliteStatus=r,this.isConnected&&this.dispatchEvent(new CustomEvent(pA)))},s=V0.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,o]=await Promise.all([s.at(e),As(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new o.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const e=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:e?.coverage,credit:e?.credit,creditUrl:e?.creditUrl}}satellitePassesDuring(e){const t=this.satellites,i=this.ufoElement.sighting,n=Jt(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,o=n?.lng??s?.lng;if(!t||r===void 0||o===void 0)return[];const c=xo(i.event.time??{},o,i.event.utcOffsetHours);if(!c)return[];const l=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:o,elevationM:n?.elevationM??0},u=JSON.stringify([this.satellitesFor,c.getTime(),r,o,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=t.passes.passesDuring(c,new Date(c.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(e,t){const i=rA.brightestAt(e,t);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}pushPhenomenaAt(e){const t=this.ufoElement.sighting;t!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=t);const i=t.timeline,n=this.ufoElement.canvasElement,s=this.ufoElement.frameShiftPx,r=this.projectionAt(e),o=new Map,c=new Map,l=new Set;for(const p of i.sourceIds){const v=i.getInterpolatedShapeAt(e,p);if(!v)continue;const m={...v,bounds:{...v.bounds,x:v.bounds.x+s.x,y:v.bounds.y+s.y}};o.set(p,m);const g=v.aim?this.sceneRenderer.screenPointOf(Dn.directionOf(v.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=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,b=y?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,p):{};l.add(p),(y||v.aim)&&l.delete(p);const M=v.angular?.widthDeg??r.pxToDeg(v.bounds.width),S=this.sizeEstimateOf(p);S.add(M,b);const w=Co.of(t,p);c.set(p,Ui.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:w&&M>0?Pt.distanceMAt(w.widthM,M):void 0,range:S.distanceRangeAt(M),crossing:b}))}for(const[p,v]of o)for(const[m,g]of o){if(m===p||g.transparency>=1||g.bounds.width*g.bounds.height<=v.bounds.width*v.bounds.height||!(v.bounds.x>=g.bounds.x&&v.bounds.y>=g.bounds.y&&v.bounds.x+v.bounds.width<=g.bounds.x+g.bounds.width&&v.bounds.y+v.bounds.height<=g.bounds.y+g.bounds.height))continue;const b=c.get(m);b&&c.set(p,{distanceM:b.distanceM*.999,basis:b.basis});break}this.depths=c;const h=i.sourceIds,u=[];for(const[p,v]of o)u.push({sourceId:p,shape:v,distanceM:c.get(p).distanceM,renderOrder:h.indexOf(p),aim:v.aim,hidden:l.has(p)||this.interpretationShown!==void 0&&(!this.comparing||v.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=(Jt(t,e)?.rollDeg??0)+xt.bodyAt(t,e,this.ufoElement.steadyObserver).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:ni.starPointsOf(t.instrument),rollRad:f*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=e,this.updateAstronomy(this.lastTimeMs)}get accountInTheRound(){return this.inTheRound}set accountInTheRound(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){this.comparing=e,this.updateAstronomy(this.lastTimeMs)}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=Qe.eyeOf(this.ufoElement.sighting,i,n);return s?Qe.lineOfSightMeetsGround(s,e,t,n):void 0}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=d=>Qe.eyeOf(n,d,i),r=new Qe(e,i,s).at(t),o=s(t);if(!r||!o)return;const c=r.eastM-o.eastM,l=r.northM-o.northM,h=r.upM-o.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}}directionToBody(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=p=>Qe.eyeOf(n,p,i),r=new Qe(e,i,s),o=r.at(t)?t:e.track[0]?.t,c=o===void 0?void 0:r.at(o),l=o===void 0?void 0:s(o);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(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const o=this.sceneRenderer.bodyGround,c=p=>Qe.eyeOf(n,p,o);i&&(s=i.bodies.map(p=>new Qe(p,o,c).at(e)).filter(p=>p!==void 0));const l=fa(n,e),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,e/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?c(e):void 0;if(d&&(r=new Kt(n.timeline).at(e,s,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=r,!t)return;const f=JSON.stringify(r);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(tv,{detail:r})))}setDistanceHypothesis(e,t){t===void 0||!(t>0)?this.distanceHypotheses.delete(e):this.distanceHypotheses.set(e,t),this.updateAstronomy(this.lastTimeMs)}depthOf(e){return this.depths.get(e)}sizeRangeOf(e){return this.sizeEstimateOf(e).sizeRange}distanceRangeAt(e,t){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e);if(!i)return{};const n=i.angular?.widthDeg??this.projectionAt(t).pxToDeg(i.bounds.width);return this.sizeEstimateOf(e).distanceRangeAt(n)}sizeContradictory(e){return this.sizeEstimateOf(e).contradictory}updateMeteorShower(e,t){this.ensureMeteorSchedule(e),this.sceneRenderer.updateMeteors(t)}updateLightning(e,t,i){if(this.ensureLightningSchedule(e),this.sceneRenderer.updateLightning(t),i)return;const n=this.lastLightningT;if(this.lastLightningT=t,n===void 0||t<n||this.ufoElement.playbackState!=="playing")return;const s=this.lightningFlashes.filter(r=>r.t>n&&r.t<=t).pop();s&&fa(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=fa(e,0).precipitationIntensity,i=`${this.meteorInputsOf(e)}|${t}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const n=e.event.time,s=e.event.place?.[0],r=n?.year!==void 0?xo(n,s?.lng??0,e.event.utcOffsetHours):void 0,o=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,c=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=hi.schedule({durationMs:o,seed:c,intensity:t}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(e){const t=this.meteorInputsOf(e);t!==this.meteorScheduleFor&&(this.meteorScheduleFor=t,this.scheduleMeteors(e))}meteorInputsOf(e){const t=e.event.place?.[0],i=e.event.time;return JSON.stringify([t?.lat,t?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,e.event.utcOffsetHours,e.event.durationSeconds,e.timeline.duration])}scheduleMeteors(e){const t=e.event.place?.[0],i=e.event.time,n=t?.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?xo(i,t.lng,e.event.utcOffsetHours):void 0;if(!n||t?.lat===void 0||t.lng===void 0){this.sceneRenderer.setMeteorShower([],0,0);return}const s={lat:t.lat,lng:t.lng,elevationM:0},r=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,o=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),c=Zt.schedule({ratePerHour:Zt.observedRatePerHour(Zt.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:Zt.TYPICAL_VELOCITY_KM_S,seed:o}),l=bu.activeAt(n).map(u=>{const d=bu.radiantPosition(u.shower,n,s);return{entry:u,position:d,rate:bu.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=Pr.schedule({ratePerHour:l.rate,durationMs:r,velocityKmS:l.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...c],l.position.altitudeDeg,l.position.azimuthDeg)}meteorByRank(e){this.ensureMeteorSchedule(this.ufoElement.sighting);const t=[...this.sceneRenderer.meteorSchedule].filter(s=>s.t+s.durationMs<=this.ufoElement.seekableDuration).sort((s,r)=>r.brightness-s.brightness);if(t.length===0)return;const i=t[e%t.length],n=this.sceneRenderer.meteorMidpoint(i);if(n)return{t:Math.round(i.t+i.durationMs*.45),...n}}lensOpticsAt(e){const t=this.ufoElement.sighting,i=t.instrument,n=i.frame,s=Jt(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const o=ni.focalLengthMmFor(i,Ji.fovOf(t,e));if(o!==void 0)return{focalLengthMm:o,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return _s.of(t.instrument,Pt.CANVAS_HEIGHT_PX,Ji.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new oA,this.sizeEstimates.set(e,t)),t}}const jd="rr0-scene";function iv(){Dg(),customElements.get(jd)||customElements.define(jd,V0)}const _A={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)",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"},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",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",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorCrop:"Crop row",decorMound:"Stone heap",decorStreetlight:"Streetlight",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",confirmAccept:"Delete",confirmDecline:"Cancel",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelNone:"Built-in shape",decorModelAdvanced:"Model from an address",decorModelFromCatalogue:"From the catalogue, which the recording names it by. Change a field and it becomes this recording's own address.",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorFloors:"Floors",decorOccupiedFloor:"Occupied floor",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorWindows:"Windows",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},fl={..._A,accountBy:"Account by",unnamedObserver:"Observer {n}",about:"About",close:"Close",observation:"Observation",date:"Date",location:"Location",case:"Case",description:"Description",credits:"Credits",editThisObservation:"Edit this observation",embed:"Embed",embedReplay:"Replay",embedEdit:"Editor",embedCopy:"Copy",embedCopied:"Copied",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"},bA=Object.freeze(Object.defineProperty({__proto__:null,sightingMessages_en:fl},Symbol.toStringTag,{value:"Module"}));iv();const SA="https://ufoathome.org",Eu="compare-account",Au="account",cg=`${SA}/edit/`;class nv extends HTMLElement{static get observedAttributes(){return["src","show-labels",Ss,ws,Eu]}shadow;sceneElement;toolbarElement;accountElement;accountPrefix;observerText;observerSelect;infoButton;infoPanel;infoAppLink;infoObservationHeading;infoObservationList;infoCreditsToggle;infoCreditsList;infoCloseButton;infoEmbedToggle;infoEmbedPanel;embedReplayRadio;embedEditRadio;labelEmbedReplay;labelEmbedEdit;embedMarkup;embedCopyButton;labelsToggle;paramSummary;summaryBuilder=new lf(fl,"en",new Pn(["en"]),new tl({}));summarySignature="";assessmentEntries=[];assessmentToken=0;supportsPopover=typeof HTMLElement.prototype.showPopover=="function";entries=[];caseSource;interpretationChoice;interpretationLabel;interpretationSelect;confrontationElement;confrontationHeading;confrontationList;compareButton;interpretationLoaders=new Map;interpretationToken=0;offeredFor;currentSrc;infoOpen=!1;creditsOpen=!1;embedOpen=!1;labelsShown=!1;language="en";messages=fl;constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${dv}</style>${uv}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(jd),this.forwardPlayerAttributes(),this.sceneElement.ufoElement.creditShownExternally=!0,this.sceneElement.ownCredits=!1,this.sceneElement.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),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.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.infoEmbedToggle=this.shadow.getElementById("info-embed-toggle"),this.infoEmbedPanel=this.shadow.getElementById("info-embed"),this.embedReplayRadio=this.shadow.getElementById("embed-kind-replay"),this.embedEditRadio=this.shadow.getElementById("embed-kind-edit"),this.labelEmbedReplay=this.shadow.getElementById("label-embed-replay"),this.labelEmbedEdit=this.shadow.getElementById("label-embed-edit"),this.embedMarkup=this.shadow.getElementById("embed-markup"),this.embedCopyButton=this.shadow.getElementById("embed-copy"),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.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(tv,t=>this.showConfrontation(t.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",t=>{t.newState==="open"&&(this.populateInfoPanel(),this.bringInfoButtonIntoView())}),this.infoPanel.addEventListener("toggle",t=>this.syncInfoOpen(t.newState==="open"))):this.infoButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCloseButton.addEventListener("click",()=>this.toggleInfoPanel()),this.infoCreditsToggle.addEventListener("click",()=>this.toggleCredits()),this.infoEmbedToggle.addEventListener("click",()=>this.toggleEmbed());for(const t of[this.embedReplayRadio,this.embedEditRadio])t.addEventListener("change",()=>this.refreshEmbedMarkup());this.embedCopyButton.addEventListener("click",()=>void this.copyEmbedMarkup()),this.loadLocaleMessages()}get scene(){return this.sceneElement}async loadLocaleMessages(){const e=++this.localeToken,t=Ir.preferencesFor(this);this.preferences=t;const i=Fo(t,Mg),[n,s]=i==="en"?[fl,{}]:await Promise.all([d2(i),f2(i)]);if(e!==this.localeToken)return;const r=i!==this.language;this.language=i,this.messages=n,this.tags=new tl(s),this.said=new Pn(t),this.summaryBuilder=new lf(this.messages,this.language==="fr"?"fr":"en",this.said,this.tags),this.accountPrefix.textContent=this.messages.accountBy,this.interpretationLabel.textContent=this.messages.interpretation,this.confrontationHeading.textContent=this.messages.confrontation;const o=this.entries.find(c=>c.src===this.currentSrc);o&&this.offerInterpretations(o),this.updateCompareButton(),this.infoButton.title=this.messages.about,this.infoButton.setAttribute("aria-label",this.messages.about),this.infoCloseButton.setAttribute("aria-label",this.messages.close),this.infoObservationHeading.textContent=this.messages.observation,this.infoCreditsToggle.textContent=this.messages.credits,this.syncLabelsToggle(),this.refreshParamSummary(),r&&this.currentSrc&&this.runAssessments(),this.infoEmbedToggle.textContent=this.messages.embed,this.labelEmbedReplay.textContent=this.messages.embedReplay,this.labelEmbedEdit.textContent=this.messages.embedEdit,this.embedCopyButton.textContent=this.messages.embedCopy,this.infoOpen&&this.populateInfoPanel(),this.updateAccountLine()}preferences=[];localeToken=0;said=new Pn(["en"]);tags=new tl({});connectedCallback(){Ir.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("click",this.handleOutsideClick)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e==="show-labels"&&this.applyLabels(this.hasAttribute("show-labels")),(e===Ss||e===ws)&&this.forwardPlayerAttributes(),e===Eu&&this.setComparing(this.hasAttribute(Eu))}forwardPlayerAttributes(){for(const e of[Ss,ws]){const t=this.getAttribute(e);t===null?this.sceneElement.removeAttribute(e):this.sceneElement.setAttribute(e,t)}}async loadFromSrc(e){const t=await bo.json(e);if(Array.isArray(t))throw new Error(`${e} is a bare list of recordings, which is no longer read: list them as the sighting events of a case.json`);if(xs.isCase(t)){const i=xs.sightingUrls(t,new URL(e,location.href).href);if(i.length===0)throw new Error(`${e} is a case with no sighting event: no recording to show`);await this.loadObserverUrls(i,{json:t,url:new URL(e,location.href).href})}else this.setEntries([{src:e,sighting:t}],void 0)}get sightingData(){return this.entries.find(e=>e.src===this.currentSrc)?.sighting}set sightingData(e){this.currentSrc="",this.setEntries([{src:"",sighting:e}],void 0)}get observerUrls(){return this.entries.map(e=>e.src)}set observerUrls(e){this.loadObserverUrls(e)}async loadObserverUrls(e,t){const i=await Promise.all(e.map(async n=>({src:n,sighting:await bo.json(n)})));this.setEntries(i,t)}setEntries(e,t){this.entries=e,this.caseSource=t,this.toolbarElement.hidden=e.length===0;const i=e.length>1;this.observerSelect.hidden=!i,this.observerText.hidden=i,this.observerSelect.innerHTML="";for(const s of e){const r=document.createElement("option");r.value=s.src,r.textContent=this.observerDisplayName(s.sighting.observer)??this.messages.unnamedObserver.replace("{n}",String(e.indexOf(s)+1)),this.observerSelect.appendChild(r)}const n=e.find(s=>s.src===this.currentSrc)??e[0];n?this.selectObserver(n.src):this.updateAccountLine()}editorUrl(){if(!this.currentSrc)return cg;const e=new URL(this.currentSrc,location.href);return`${cg}?sighting=${encodeURIComponent(e.href)}`}embedMarkupFor(e){const t=e==="edit"?"rr0-sighting-editor":"rr0-sighting",i=new URL(`${t}.mjs`,import.meta.url).href,n=this.currentSrc?new URL(this.currentSrc,location.href).href:"";return`<script type="module" src="${i}"><\/script>
|
|
7664
|
-
<${t} src="${n}"></${t}>`}refreshEmbedMarkup(){this.embedMarkup.value=this.embedMarkupFor(this.embedEditRadio.checked?"edit":"replay")}async copyEmbedMarkup(){try{await navigator.clipboard.writeText(this.embedMarkup.value),this.embedCopyButton.textContent=this.messages.embedCopied,window.setTimeout(()=>this.embedCopyButton.textContent=this.messages.embedCopy,1500)}catch{this.embedMarkup.select()}}offerInterpretations(e){const t=this.offeredFor===e.sighting,i=this.interpretationSelect.value;this.offeredFor=e.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(l,h,u)=>{const d=document.createElement("option");d.value=l,d.textContent=h,this.interpretationSelect.appendChild(d),this.interpretationLoaders.set(l,u)},s=e===this.entries.find(l=>l.src===this.currentSrc)?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(Au,this.messages.account,()=>Promise.resolve(s));const r=this.caseSource;r&&xs.interpretationEvents(r.json,e.sighting.id).forEach((l,h)=>{const u=this.said.read(l.title)??`#${h+1}`,d=(l.by??[]).map(f=>this.agentName(f)).filter(Boolean).join(", ");n(`case-${h}`,d?this.messages.interpretationBy.replace("{title}",u).replace("{by}",d):u,()=>xs.interpretationOf(l,r.url,f=>bo.json(f)))});const c=t&&[...this.interpretationSelect.options].some(l=>l.value===i)?i:Au;this.interpretationSelect.value=c,c===Au?this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s):this.sceneElement.interpretation||this.chooseInterpretation(c),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton()}setComparing(e){this.sceneElement.compareAccount=e,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const e=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(e));const t=e?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=t,this.compareButton.setAttribute("aria-label",t)}get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(e){const t=++this.interpretationToken,i=this.interpretationLoaders.get(e),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${e}":`,s)}):void 0;t===this.interpretationToken&&(this.sceneElement.interpretation=n,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation))}agentName(e){if("people"in e){const[t,...i]=e.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,t].join(" ")}return"org"in e?e.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(e)??""}showConfrontation(e){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const t=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of e){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}",t.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(([o,c],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=o,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}selectObserver(e){const t=this.entries.find(i=>i.src===e);t&&(this.currentSrc=e,this.observerSelect.value=e,this.sceneElement.documentUrl=t.src?new URL(t.src,location.href).href:void 0,this.sceneElement.sightingData=t.sighting,this.offerInterpretations(t),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(wA,{detail:{src:e}})))}async runAssessments(){const e=++this.assessmentToken,t=await new Vv(this.messages).read(this.sceneElement.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentEntries=t.entries,this.refreshParamSummary())}updateAccountLine(){const e=this.entries.find(n=>n.src===this.currentSrc),t=e?this.observerDisplayName(e.sighting.observer):void 0,i=t!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=t??""}observerDisplayName(e){if(!e)return;const t=[...e.firstNames??[],e.lastName].filter(Boolean).join(" ");return e.title||t||e.id}formatDate(e){const t=e.place?.[0],i=xo(e.time??{},t?.lng??0,e.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(e,t?.lng??0)*36e5;return new Intl.DateTimeFormat(this.language==="fr"?"fr-FR":"en-US",{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(e,t){return e.utcOffsetHours??Math.round(t/15)}formatLocation(e){const t=e.place?.[0];if(t)return`${t.lat.toFixed(4)}, ${t.lng.toFixed(4)}`}toggleInfoPanel(){const e=!this.infoOpen;if(this.supportsPopover){const t=this.infoPanel.matches(":popover-open");e&&!t?this.infoPanel.showPopover():!e&&t&&this.infoPanel.hidePopover();return}e&&this.bringInfoButtonIntoView(),this.syncInfoOpen(e),this.infoPanel.hidden=!e,e?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const e=this.infoButton.getBoundingClientRect(),t=window.innerHeight||document.documentElement.clientHeight;e.top>=0&&e.bottom<=t||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(e){e!==this.infoOpen&&(this.infoOpen=e,this.infoButton.setAttribute("aria-expanded",String(e)),e?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false"),this.embedOpen=!1,this.infoEmbedPanel.hidden=!0,this.infoEmbedToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=e=>{const t=e.composedPath();!t.includes(this.infoPanel)&&!t.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)}toggleEmbed(){this.embedOpen=!this.embedOpen,this.infoEmbedPanel.hidden=!this.embedOpen,this.infoEmbedToggle.setAttribute("aria-expanded",String(this.embedOpen)),this.embedOpen&&(this.refreshEmbedMarkup(),this.revealInPanel(this.infoEmbedPanel))}revealInPanel(e){e.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(e){this.toggleAttribute("show-labels",e)}applyLabels(e){this.labelsShown=e,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 e=this.sceneElement.ufoElement.sighting,t=[...this.summaryBuilder.entriesFor(e,this.sceneElement.ufoElement.currentTime),...this.assessmentEntries],i=t.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of t){s&&s.group!==r.group&&(s=void 0);const o=r.group==="observer"?this.messages.observerGroup:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(o!==void 0&&!s){const l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=o,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)}paramItem(e){const t=document.createElement("span");t.className=e.fromSource?"param-label from-source":"param-label";const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}populateInfoPanel(){const e=this.entries.find(t=>t.src===this.currentSrc);if(this.infoObservationList.innerHTML="",e){const t=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(t&&this.appendInfoRow(this.infoObservationList,this.messages.case,t),!this.labelsShown){const n=this.formatDate(e.sighting);n&&this.appendInfoRow(this.infoObservationList,this.messages.date,n);const s=this.formatLocation(e.sighting);s&&this.appendInfoRow(this.infoObservationList,this.messages.location,s)}const i=this.said.read(e.sighting.description);i&&this.appendInfoRow(this.infoObservationList,this.messages.description,i),!this.labelsShown&&e.sighting.tags&&e.sighting.tags.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,e.sighting.tags.map(n=>this.tags.name(n)).join(", "))}this.refreshEmbedMarkup(),this.infoAppLink.href=this.editorUrl(),this.infoAppLink.textContent="UFO@home v0.69.2",this.infoAppLink.title=this.messages.editThisObservation,this.infoAppLink.setAttribute("aria-label",this.messages.editThisObservation),Tn.fill(this.infoCreditsList,this.sceneElement)}appendInfoRow(e,t,i){const n=document.createElement("dt");n.textContent=t;const s=document.createElement("dd");s.textContent=i,e.appendChild(n),e.appendChild(s)}}const lg="rr0-sighting",wA="observerchange",hg="rr0-eyeobserver";class EA extends nv{}function AA(){iv(),customElements.get(lg)||customElements.define(lg,nv),customElements.get(hg)||customElements.define(hg,EA)}AA();export{CA as $,ji as A,tt as B,se as C,bp as D,yn as E,NA as F,bt as G,ot as H,PA as I,IA as J,Re as K,Ko as L,dx as M,ac as N,Ft as O,c1 as P,Qi as Q,zo as R,Co as S,TA as T,LA as U,Me as V,jg as W,OA as X,vs as Y,Rt as Z,Zi as _,DA as a,Un as a0,Jg as a1,gp as a2,ex as a3,_l as a4,md as a5,Rl as a6,_i as a7,a1 as a8,b0 as a9,S0 as aa,rt as ab,nr as ac,$o as ad,Gi as ae,Cs as af,RA as b,Zh as c,kA as d,wl as e,Hi as f,UA as g,Ze as h,R as i,rp as j,FA as k,zA as l,ZM as m,Er as n,lh as o,a2 as p,Q2 as q,at as r,xo as s,Et as t,ku as u,bi as v,Qg as w,Is as x,ax as y,yr as z};
|
|
7664
|
+
<${t} src="${n}"></${t}>`}refreshEmbedMarkup(){this.embedMarkup.value=this.embedMarkupFor(this.embedEditRadio.checked?"edit":"replay")}async copyEmbedMarkup(){try{await navigator.clipboard.writeText(this.embedMarkup.value),this.embedCopyButton.textContent=this.messages.embedCopied,window.setTimeout(()=>this.embedCopyButton.textContent=this.messages.embedCopy,1500)}catch{this.embedMarkup.select()}}offerInterpretations(e){const t=this.offeredFor===e.sighting,i=this.interpretationSelect.value;this.offeredFor=e.sighting,this.interpretationToken++,this.interpretationLoaders=new Map,this.interpretationSelect.innerHTML="";const n=(l,h,u)=>{const d=document.createElement("option");d.value=l,d.textContent=h,this.interpretationSelect.appendChild(d),this.interpretationLoaders.set(l,u)},s=e===this.entries.find(l=>l.src===this.currentSrc)?this.sceneElement.ufoElement.sighting.interpretation:void 0;n(Au,this.messages.account,()=>Promise.resolve(s));const r=this.caseSource;r&&xs.interpretationEvents(r.json,e.sighting.id).forEach((l,h)=>{const u=this.said.read(l.title)??`#${h+1}`,d=(l.by??[]).map(f=>this.agentName(f)).filter(Boolean).join(", ");n(`case-${h}`,d?this.messages.interpretationBy.replace("{title}",u).replace("{by}",d):u,()=>xs.interpretationOf(l,r.url,f=>bo.json(f)))});const c=t&&[...this.interpretationSelect.options].some(l=>l.value===i)?i:Au;this.interpretationSelect.value=c,c===Au?this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s):this.sceneElement.interpretation||this.chooseInterpretation(c),this.interpretationChoice.hidden=this.interpretationSelect.options.length<2,this.showConfrontation(this.sceneElement.confrontation),this.updateCompareButton()}setComparing(e){this.sceneElement.compareAccount=e,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation)}updateCompareButton(){const e=this.sceneElement.compareAccount;this.compareButton.hidden=!this.sceneElement.interpretation,this.compareButton.setAttribute("aria-pressed",String(e));const t=e?this.messages.hideComparison:this.messages.showComparison;this.compareButton.title=t,this.compareButton.setAttribute("aria-label",t)}get colon(){return this.language==="fr"?" : ":": "}async chooseInterpretation(e){const t=++this.interpretationToken,i=this.interpretationLoaders.get(e),n=i?await i().catch(s=>{console.warn(`<rr0-sighting>: could not read interpretation "${e}":`,s)}):void 0;t===this.interpretationToken&&(this.sceneElement.interpretation=n,this.updateCompareButton(),this.showConfrontation(this.sceneElement.confrontation))}agentName(e){if("people"in e){const[t,...i]=e.people.replace(/([a-z])([A-Z])/g,"$1 $2").split(" ");return[...i,t].join(" ")}return"org"in e?e.org.replace(/([a-z])([A-Z])/g,"$1 $2"):this.observerDisplayName(e)??""}showConfrontation(e){this.confrontationList.innerHTML="",this.confrontationElement.hidden=!this.sceneElement.interpretation||!this.sceneElement.compareAccount;const t=new Intl.NumberFormat(this.language,{maximumFractionDigits:1,minimumFractionDigits:1}),i=new Intl.NumberFormat(this.language,{maximumFractionDigits:2,minimumFractionDigits:2});for(const n of e){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}",t.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(([o,c],l)=>{l>0&&s.append(" · ");const h=document.createElement("span");h.textContent=o,c&&(h.className="disagrees"),s.append(h)}),this.confrontationList.appendChild(s)}}selectObserver(e){const t=this.entries.find(i=>i.src===e);t&&(this.currentSrc=e,this.observerSelect.value=e,this.sceneElement.documentUrl=t.src?new URL(t.src,location.href).href:void 0,this.sceneElement.sightingData=t.sighting,this.offerInterpretations(t),this.updateAccountLine(),this.refreshParamSummary(),this.runAssessments(),this.infoOpen&&this.populateInfoPanel(),this.dispatchEvent(new CustomEvent(wA,{detail:{src:e}})))}async runAssessments(){const e=++this.assessmentToken,t=await new Vv(this.messages).read(this.sceneElement.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentEntries=t.entries,this.refreshParamSummary())}updateAccountLine(){const e=this.entries.find(n=>n.src===this.currentSrc),t=e?this.observerDisplayName(e.sighting.observer):void 0,i=t!==void 0||this.entries.length>1;this.accountElement.hidden=!i,this.observerText.textContent=t??""}observerDisplayName(e){if(!e)return;const t=[...e.firstNames??[],e.lastName].filter(Boolean).join(" ");return e.title||t||e.id}formatDate(e){const t=e.place?.[0],i=xo(e.time??{},t?.lng??0,e.utcOffsetHours);if(!i)return;const n=i.getTime()+this.utcOffsetHoursOf(e,t?.lng??0)*36e5;return new Intl.DateTimeFormat(this.language==="fr"?"fr-FR":"en-US",{dateStyle:"long",timeStyle:"short",timeZone:"UTC"}).format(new Date(n))}utcOffsetHoursOf(e,t){return e.utcOffsetHours??Math.round(t/15)}formatLocation(e){const t=e.place?.[0];if(t)return`${t.lat.toFixed(4)}, ${t.lng.toFixed(4)}`}toggleInfoPanel(){const e=!this.infoOpen;if(this.supportsPopover){const t=this.infoPanel.matches(":popover-open");e&&!t?this.infoPanel.showPopover():!e&&t&&this.infoPanel.hidePopover();return}e&&this.bringInfoButtonIntoView(),this.syncInfoOpen(e),this.infoPanel.hidden=!e,e?document.addEventListener("click",this.handleOutsideClick):document.removeEventListener("click",this.handleOutsideClick)}bringInfoButtonIntoView(){const e=this.infoButton.getBoundingClientRect(),t=window.innerHeight||document.documentElement.clientHeight;e.top>=0&&e.bottom<=t||this.infoButton.scrollIntoView({block:"center"})}syncInfoOpen(e){e!==this.infoOpen&&(this.infoOpen=e,this.infoButton.setAttribute("aria-expanded",String(e)),e?this.supportsPopover||this.populateInfoPanel():(this.creditsOpen=!1,this.infoCreditsList.hidden=!0,this.infoCreditsToggle.setAttribute("aria-expanded","false"),this.embedOpen=!1,this.infoEmbedPanel.hidden=!0,this.infoEmbedToggle.setAttribute("aria-expanded","false")))}handleOutsideClick=e=>{const t=e.composedPath();!t.includes(this.infoPanel)&&!t.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)}toggleEmbed(){this.embedOpen=!this.embedOpen,this.infoEmbedPanel.hidden=!this.embedOpen,this.infoEmbedToggle.setAttribute("aria-expanded",String(this.embedOpen)),this.embedOpen&&(this.refreshEmbedMarkup(),this.revealInPanel(this.infoEmbedPanel))}revealInPanel(e){e.scrollIntoView?.({block:"nearest"})}get showLabels(){return this.labelsShown}set showLabels(e){this.toggleAttribute("show-labels",e)}applyLabels(e){this.labelsShown=e,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 e=this.sceneElement.ufoElement.sighting,t=[...this.summaryBuilder.entriesFor(e,this.sceneElement.ufoElement.currentTime),...this.assessmentEntries],i=t.map(r=>`${r.field}=${r.label}=${r.value}${r.unit}${r.fromSource?"*":""}`).join("|");if(i===this.summarySignature)return;this.summarySignature=i;const n=[];let s;for(const r of t){s&&s.group!==r.group&&(s=void 0);const o=r.group==="observer"?this.messages.observerGroup:r.group==="assessment"?this.messages.assessmentGroup:void 0;if(o!==void 0&&!s){const l=document.createElement("span");l.className="param-nest";const h=document.createElement("span");h.className="param-nest-label",h.textContent=o,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)}paramItem(e){const t=document.createElement("span");t.className=e.fromSource?"param-label from-source":"param-label";const i=document.createElement("span");if(i.className="param-label-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-label-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-label-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}populateInfoPanel(){const e=this.entries.find(t=>t.src===this.currentSrc);if(this.infoObservationList.innerHTML="",e){const t=this.caseSource&&(this.caseSource.json.title??this.caseSource.json.id);if(t&&this.appendInfoRow(this.infoObservationList,this.messages.case,t),!this.labelsShown){const n=this.formatDate(e.sighting);n&&this.appendInfoRow(this.infoObservationList,this.messages.date,n);const s=this.formatLocation(e.sighting);s&&this.appendInfoRow(this.infoObservationList,this.messages.location,s)}const i=this.said.read(e.sighting.description);i&&this.appendInfoRow(this.infoObservationList,this.messages.description,i),!this.labelsShown&&e.sighting.tags&&e.sighting.tags.length>0&&this.appendInfoRow(this.infoObservationList,this.messages.tags,e.sighting.tags.map(n=>this.tags.name(n)).join(", "))}this.refreshEmbedMarkup(),this.infoAppLink.href=this.editorUrl(),this.infoAppLink.textContent="UFO@home v0.70.0",this.infoAppLink.title=this.messages.editThisObservation,this.infoAppLink.setAttribute("aria-label",this.messages.editThisObservation),Tn.fill(this.infoCreditsList,this.sceneElement)}appendInfoRow(e,t,i){const n=document.createElement("dt");n.textContent=t;const s=document.createElement("dd");s.textContent=i,e.appendChild(n),e.appendChild(s)}}const lg="rr0-sighting",wA="observerchange",hg="rr0-eyeobserver";class EA extends nv{}function AA(){iv(),customElements.get(lg)||customElements.define(lg,nv),customElements.get(hg)||customElements.define(hg,EA)}AA();export{CA as $,ji as A,tt as B,se as C,bp as D,yn as E,NA as F,bt as G,ot as H,PA as I,IA as J,Re as K,Ko as L,dx as M,ac as N,Ft as O,c1 as P,Qi as Q,zo as R,Co as S,TA as T,LA as U,Me as V,jg as W,OA as X,vs as Y,Rt as Z,Zi as _,DA as a,Un as a0,Jg as a1,gp as a2,ex as a3,_l as a4,md as a5,Rl as a6,_i as a7,a1 as a8,b0 as a9,S0 as aa,rt as ab,nr as ac,$o as ad,Gi as ae,Cs as af,RA as b,Zh as c,kA as d,wl as e,Hi as f,UA as g,Ze as h,R as i,rp as j,FA as k,zA as l,ZM as m,Er as n,lh as o,a2 as p,Q2 as q,at as r,xo as s,Et as t,ku as u,bi as v,Qg as w,Is as x,ax as y,yr as z};
|