@rr0/ufoathome 0.86.0 → 0.86.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.
- package/dist-embed-scene/ContrailGrowth-CuAzwIoc.js +1 -0
- package/dist-embed-scene/ContrailSystem-CQsI1Z1v.js +1 -0
- package/dist-embed-scene/rr0-scene.mjs +5 -5
- package/dist-embed-scene/trafficRuntime-_pIg6nkw.js +2 -0
- package/dist-embed-sighting/ContrailGrowth-CuAzwIoc.js +1 -0
- package/dist-embed-sighting/ContrailSystem-CkzapJ6C.js +1 -0
- package/dist-embed-sighting/rr0-sighting.mjs +6 -6
- package/dist-embed-sighting/trafficRuntime-C1HVGEkh.js +2 -0
- package/dist-embed-sighting-editor/ContrailGrowth-CuAzwIoc.js +1 -0
- package/dist-embed-sighting-editor/ContrailSystem-CXV5ZetF.js +1 -0
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +5 -5
- package/dist-embed-sighting-editor/trafficRuntime-CyMwd0OH.js +2 -0
- package/package.json +1 -1
- package/dist-embed-scene/ContrailGrowth-bHuVPHYY.js +0 -1
- package/dist-embed-scene/ContrailSystem-BsPJ-HyA.js +0 -1
- package/dist-embed-scene/trafficRuntime-BNKtP7MU.js +0 -2
- package/dist-embed-sighting/ContrailGrowth-bHuVPHYY.js +0 -1
- package/dist-embed-sighting/ContrailSystem-Ct9SoLDA.js +0 -1
- package/dist-embed-sighting/trafficRuntime-BqsOb_FO.js +0 -2
- package/dist-embed-sighting-editor/ContrailGrowth-bHuVPHYY.js +0 -1
- package/dist-embed-sighting-editor/ContrailSystem-CdlRgS_7.js +0 -1
- package/dist-embed-sighting-editor/trafficRuntime-BKESmiqx.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-CXV5ZetF.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-CyMwd0OH.js","./BodyEditor-B_FBjZDB.js","./BodyEditorMessages_en-DkxURSds.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
const ey="modulepreload",ty=function(a,e){return new URL(a,e).href},_0={},ot=function(e,t,i){let n=Promise.resolve();if(t&&t.length>0){let r=function(h){return Promise.all(h.map(d=>Promise.resolve(d).then(u=>({status:"fulfilled",value:u}),u=>({status:"rejected",reason:u}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");n=r(t.map(h=>{if(h=ty(h,i),h in _0)return;_0[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let v=o.length-1;v>=0;v--){const m=o[v];if(m.href===h&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":ey,d||(p.as="script"),p.crossOrigin="",p.href=h,c&&p.setAttribute("nonce",c),document.head.appendChild(p),d)return new Promise((v,m)=>{p.addEventListener("load",v),p.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return n.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};const Mp={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function _s(a){if(a.cloudLayers!==void 0)return a.cloudLayers;const e=[],t=a.lowerCloudCover??a.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:a.cloudBaseM??1e3,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:a.cloudDarkness}),(a.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:a.highCloudCover,sizeM:2200,density:.35,darkness:a.cloudDarkness,iceCrystalAlignment:a.iceCrystalAlignment}),e}function iy(a,e,t,i,n,s){Zv(a,e,t,r=>r.map(o=>o.id===i?n(o):o),s)}function Zv(a,e,t,i,n){const s=r=>{const o=i(_s(r)),l=v=>1-o.filter(m=>m.type==="cirrus"===v).reduce((m,g)=>m*(1-g.coverage),1),c=l(!1),h=l(!0),d=o.filter(v=>v.coverage>0&&v.type!=="cirrus").map(v=>v.baseM),u=o.filter(v=>v.coverage>0||(v.instances?.length??0)>0),f=u.length?Math.max(...u.flatMap(v=>[v.darkness??r.cloudDarkness,...(v.instances??[]).map(m=>m.darkness??v.darkness??r.cloudDarkness)])):0,p=o.filter(v=>v.type==="cirrus"&&v.coverage>0).sort((v,m)=>m.coverage-v.coverage)[0];return{...r,cloudLayers:o,lowerCloudCover:c,highCloudCover:h,cloudDarkness:f,iceCrystalAlignment:p?.iceCrystalAlignment,cloudCover:1-(1-c)*(1-h),cloudBaseM:d.length?Math.min(...d):void 0}};if(n==="instant"||a.allKeyframes.length===0)a.addKeyframe(n==="observation"?0:t,s(a.getInterpolatedWeatherAt(t)??e));else for(const r of[...a.allKeyframes])a.addKeyframe(r.t,s(r.weather))}const jv=Math.PI/180,ch=111320;function ni(a,e,t,i){const n=ch*Math.cos(t*jv),s=(a-t)*ch;return{x:(e-i)*n,z:-s}}function Dn(a,e,t,i){const n=ch*Math.cos(t*jv),s=-e,r=a;return{lat:t+s/ch,lng:i+r/n}}function hh(a,e,t,i,n,s){const r=i?.lat!==void 0&&i.lng!==void 0&&n?.lat!==void 0&&n.lng!==void 0?ni(n.lat,n.lng,i.lat,i.lng):{x:0,z:0},o=Math.max(0,a),l=[0,...e.allKeyframes.map(c=>c.t).filter(c=>c>0&&c<o),o];for(let c=1;c<l.length;c++){const h=l[c-1],d=l[c]-h;if(d===0)continue;const u=32;for(let f=0;f<=u;f++){const p=e.getInterpolatedWeatherAt(h+d*f/u)??t,v=s===void 0?void 0:p.cloudLayers?.find(y=>y.id===s),m=(v?.windDirectionDeg??p.windDirectionDeg)*Math.PI/180,g=f===0||f===u?1:f%2===0?2:4,x=(v?.windSpeed??p.windSpeed)*d/1e3/u/3*g;r.x-=Math.sin(m)*x,r.z+=Math.cos(m)*x}}return r}class it{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(e){return 2*Math.atan(e.sizeM/(2*e.distanceM))*180/Math.PI}static inMoons(e){return e/it.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(e,t,i){if(!(!e||!t))return{widthDeg:e.widthDeg+(t.widthDeg-e.widthDeg)*i,heightDeg:e.heightDeg+(t.heightDeg-e.heightDeg)*i}}static sizeMAt(e,t){return 2*e*Math.tan(t*Math.PI/360)}static distanceMAt(e,t){return e/(2*Math.tan(t*Math.PI/360))}}function ny(a,e,t){if(!a||!e)return t<1?a:e;const i=((e.azimuthDeg-a.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((a.azimuthDeg+i*t)%360+360)%360,altitudeDeg:a.altitudeDeg+(e.altitudeDeg-a.altitudeDeg)*t}}function sy(a,e="#39ff14"){return{kind:"oval",bounds:a,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function ry(a,e,t="#39ff14"){return{kind:"polygon",bounds:a,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function ay(a,e="#39ff14"){const{width:t,height:i}=a;return ry(a,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const oy={oval:sy,polygon:ay};function A0(a,e){return{...oy[e.presetId](a,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function ly(a,e,t){const{bounds:i}=a;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function Jv(a,e,t){const i=a.bounds.width,n=a.bounds.height;return{...a,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function pn(a,e,t){return a+(e-a)*t}function T0(a){const e=/^#([0-9a-f]{6})$/i.exec(a);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function cy(a){return`#${a.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function hy(a,e,t){const i=T0(a),n=T0(e);return!i||!n?t<1?a:e:cy([pn(i[0],n[0],t),pn(i[1],n[1],t),pn(i[2],n[2],t)])}function dy(a,e,t){const i={x:pn(a.bounds.x,e.bounds.x,t),y:pn(a.bounds.y,e.bounds.y,t),width:pn(a.bounds.width,e.bounds.width,t),height:pn(a.bounds.height,e.bounds.height,t)},n=pn(a.angle,e.angle,t),s=pn(a.transparency,e.transparency,t),r=pn(a.haloScale,e.haloScale,t),o=pn(a.blur??0,e.blur??0,t),l=pn(a.brightness??0,e.brightness??0,t),c=hy(a.color,e.color,t),h=it.lerpAngular(a.angular,e.angular,t),d=ny(a.aim,e.aim,t);return a.kind==="polygon"&&e.kind==="polygon"&&a.points.length===e.points.length?{...a,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d,points:a.points.map((u,f)=>({x:pn(u.x,e.points[f].x,t),y:pn(u.y,e.points[f].y,t)}))}:{...t<1?a:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:o,brightness:l,color:c,angular:h,aim:d}}class Yr{static DEFAULT_COLOR="#e8e6df";static complete(e,t=[]){const i=new Map;return e.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,o)=>{const l=`timeline.keyframes.${s}.shapes.${o}.shape`,c=Yr.completed(r,i.get(r.sourceId),l,t);return i.set(r.sourceId,c),{sourceId:r.sourceId,shape:c}})}))}static completed(e,t,i,n){const s=e.shape??{},r=t??Yr.firstAppearance(s,i,n),o={...r};s.bounds&&t&&(t.aim||t.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete o.aim,s.angular||delete o.angular);const l=s.kind??r.kind??"oval",c={...o,...s,kind:l};if(l==="polygon"&&!c.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:d}=c.bounds;return{...c,points:[{x:0,y:0},{x:h,y:0},{x:h,y:d},{x:0,y:d}]}}return c}static firstAppearance(e,t,i){return e.kind||i.push({kind:"defaulted",path:`${t}.kind`,expected:'"oval"'}),e.color||i.push({kind:"defaulted",path:`${t}.color`,expected:`"${Yr.DEFAULT_COLOR}"`}),!e.bounds&&!e.aim&&i.push({kind:"unplaced",path:t}),!e.bounds&&!e.angular&&i.push({kind:"unsized",path:t}),{kind:e.kind??"oval",bounds:{...Yr.NEUTRAL_BOUNDS},color:Yr.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:it.CANVAS_WIDTH_PX/2,y:it.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Wh{keyframes=[];order=[];groups=[];addKeyframe(e,t){const i=this.findInsertIndex(e);if(this.keyframes[i]?.t===e){const n=new Set(t.map(s=>s.sourceId));this.keyframes[i]={t:e,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...t]}}else this.keyframes.splice(i,0,{t:e,shapes:[...t]});for(const n of t)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getKeyframeAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t];return i?.t===e?i:void 0}getShapeAt(e,t){return this.getKeyframeAt(e)?.shapes.find(i=>i.sourceId===t)?.shape}getLatestShapeAt(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return n.shape}}getInterpolatedShapeAt(e,t){const i=this.findShapeAtOrBefore(e,t);if(i?.t===e)return i.shape;const n=this.findShapeAtOrAfter(e,t);return i?n?dy(i.shape,n.shape,(e-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(e,t){let i=this.findInsertIndex(e);for(this.keyframes[i]?.t!==e&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(e,t){for(let i=this.findInsertIndex(e);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===t);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(e,t,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const o=this.getInterpolatedShapeAt(e,s[r]);if(o&&ly(o,t,i))return{sourceId:s[r],shape:o}}}removeSource(e){for(let t=this.keyframes.length-1;t>=0;t--){const i=this.keyframes[t].shapes.filter(n=>n.sourceId!==e);i.length===0?this.keyframes.splice(t,1):i.length!==this.keyframes[t].shapes.length&&(this.keyframes[t]={t:this.keyframes[t].t,shapes:i})}this.order=this.order.filter(t=>t!==e),this.removeFromGroup(e)}group(e){if(!(e.length<2)){for(const t of e)this.removeFromGroup(t);this.groups.push([...e])}}ungroup(e){const t=this.groups.findIndex(i=>i.includes(e));t!==-1&&this.groups.splice(t,1)}groupMembers(e){return this.groups.find(t=>t.includes(e))}removeFromGroup(e){const t=this.groups.findIndex(n=>n.includes(e));if(t===-1)return;const i=this.groups[t].filter(n=>n!==e);i.length<2?this.groups.splice(t,1):this.groups[t]=i}bringToFront(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.push(e))}sendToBack(e){const t=this.order.indexOf(e);t!==-1&&(this.order.splice(t,1),this.order.unshift(e))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new Wh;for(const n of Yr.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(e.order){const n=i.order.filter(s=>!e.order.includes(s));i.order=[...e.order,...n]}return e.groups&&(i.groups=e.groups.map(n=>n.filter(s=>i.order.includes(s))).filter(n=>n.length>=2)),i}}function uy(a,e,t){return Math.max(e,Math.min(t,a))}function fy(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function wa(a,e,t){return a+(e-a)*t}function py(a,e,t){return{lat:a.lat===void 0||e.lat===void 0?void 0:wa(a.lat,e.lat,t),lng:a.lng===void 0||e.lng===void 0?void 0:wa(a.lng,e.lng,t),elevationM:wa(a.elevationM,e.elevationM,t),headingDeg:a.headingDeg===void 0||e.headingDeg===void 0?void 0:fy(a.headingDeg,e.headingDeg,t),pitchDeg:wa(a.pitchDeg,e.pitchDeg,t),rollDeg:wa(a.rollDeg??0,e.rollDeg??0,t),fovDeg:wa(a.fovDeg,e.fovDeg,t),fNumber:a.fNumber,focusDistanceM:a.focusDistanceM}}class oa{static at(e,t,i,n,s){const r=e[i],l=e[i+1]-r;if(l<=0)return t[i];const c=oa.tangent(e,t,i,s),h=oa.tangent(e,t,i+1,s),d=(n-r)/l,u=d*d,f=u*d;return(2*f-3*u+1)*t[i]+(f-2*u+d)*l*c+(-2*f+3*u)*t[i+1]+(f-u)*l*h}static BRAKE_S=.8;static paced(e,t,i,n){if(!i&&!n)return e;const s=t>0?Math.min(.5,oa.BRAKE_S/t):.5;if(i&&n){const o=1/(1-s);return e<=s?o*e*e/(2*s):e>=1-s?1-o*(1-e)*(1-e)/(2*s):o*(e-s/2)}const r=o=>{const l=1/(1-s/2);if(o<=1-s)return l*o;const c=o-(1-s);return l*(1-s)+l*(c-c*c/(2*s))};return n?r(e):1-r(1-e)}static tangent(e,t,i,n){const s=e.length-1,r=f=>(t[f+1]-t[f])/(e[f+1]-e[f]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const o=r(i-1),l=r(i);if(o*l<=0)return 0;const c=e[i]-e[i-1],h=e[i+1]-e[i],d=2*h+c,u=h+2*c;return(d+u)/(d/o+u/l)}}class El{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,pose:t}:this.keyframes.splice(i,0,{t:e,pose:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestPoseAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].pose:void 0}getInterpolatedPoseAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.pose;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.pose;if(!n)return i.pose;const s=py(i.pose,n.pose,uy((e-i.t)/(n.t-i.t),0,1));return this.humanly(t-1,e,s)}humanly(e,t,i){const n=Math.max(0,e-1),s=Math.min(this.keyframes.length-1,e+2),r=this.keyframes.slice(n,s+1),o=e-n,l=r.map(y=>y.t),c=(y,b)=>{const w=r.map(E=>y(E.pose));if(!w.some(E=>E===void 0))return oa.at(l,w,o,t,b)},h=r.map(y=>y.pose.headingDeg);let d;if(h.every(y=>y!==void 0)){const y=[h[0]];for(let b=1;b<h.length;b++)y.push(y[b-1]+((h[b]-h[b-1])%360+540)%360-180);d=(oa.at(l,y,o,t,!0)%360+360)%360}const u=this.keyframes[e],f=this.keyframes[e+1],p=(y,b)=>y.lat===b.lat&&y.lng===b.lng&&y.elevationM===b.elevationM,v=!p(u.pose,f.pose),m=v&&e>0&&p(this.keyframes[e-1].pose,u.pose),g=v&&e+2<this.keyframes.length&&p(f.pose,this.keyframes[e+2].pose);let x;if(m||g){const y=oa.paced((t-u.t)/(f.t-u.t),(f.t-u.t)/1e3,m,g),b=(w,E)=>w===void 0||E===void 0?void 0:w+(E-w)*y;x={lat:b(u.pose.lat,f.pose.lat),lng:b(u.pose.lng,f.pose.lng),elevationM:b(u.pose.elevationM,f.pose.elevationM)}}return{...i,lat:x?x.lat:c(y=>y.lat,!1)??i.lat,lng:x?x.lng:c(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:c(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:c(y=>y.pitchDeg,!0)??i.pitchDeg,rollDeg:c(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:c(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new El;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class gr{static MAX_CHANGE_PER_S=.05;points;followed;constructor(e){let t="none",i=0;this.points=e.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(t=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:t,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push(gr.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(e){if(this.points.length===0||e<this.points[0].t)return;let t=this.points.length-1;for(;t>0&&this.points[t].t>e;)t--;const i=this.points[t],n=this.points[t+1],s=n?gr.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):gr.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:gr.typeBetween(i,n,e,s),intensity:s,character:gr.characterBetween(i,n,e)}}static characterBetween(e,t,i){return e.type==="none"?t&&t.type!=="none"?t.intensity:e.lastFallingIntensity:!t||t.type==="none"?e.intensity:e.intensity+(t.intensity-e.intensity)*(i-e.t)/(t.t-e.t||1)}static typeBetween(e,t,i,n){return e.type==="none"?t&&t.type!=="none"&&i>e.t?t.type:n>0?e.lastFalling:"none":t&&t.type==="none"&&n<=0?"none":e.type}static follow(e,t,i,n,s){const r=gr.MAX_CHANGE_PER_S,o=n>0?(i-t)/n:0,l=d=>t+o*Math.min(Math.max(d,0),n);let c=e,h=0;for(let d=0;d<8&&h<s;d++){const u=l(h)-c;if(Math.abs(u)<1e-9){const y=h<n?o:0;if(Math.abs(y)<=r){const w=h<n?Math.min(s,n):s;c=l(w),h=w;continue}const b=Math.min(s,n);c+=Math.sign(y)*r*(b-h),h=b;continue}const f=Math.sign(u),p=h<n?o:0,v=r-f*p,m=v>0?h+Math.abs(u)/v:1/0,g=h<n?n:1/0,x=Math.min(s,m,g);c+=f*r*(x-h),h=x,x===m&&(c=l(h))}return Math.min(1,Math.max(0,c))}}function $t(a,e,t){return a+(e-a)*t}function wp(a,e,t){const i=((e-a)%360+540)%360-180;return((a+i*t)%360+360)%360}function my(a,e,t){return Math.max(e,Math.min(t,a))}function gy(a=[],e=[],t){if(!(!a.length&&!e.length))return[...new Set([...a.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=a.find(l=>l.id===i),s=e.find(l=>l.id===i),r=n??{...s,density:0},o=s??{...n,density:0};return{...r,eastM:$t(r.eastM,o.eastM,t),northM:$t(r.northM,o.northM,t),baseM:$t(r.baseM,o.baseM,t),thicknessM:$t(r.thicknessM,o.thicknessM,t),widthM:$t(r.widthM,o.widthM,t),depthM:$t(r.depthM,o.depthM,t),rotationDeg:wp(r.rotationDeg,o.rotationDeg,t),density:$t(r.density,o.density,t),darkness:$t(r.darkness??0,o.darkness??0,t)}})}function vy(a,e,t){if(a.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=_s(a),n=_s(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const o=i.find(d=>d.id===r),l=n.find(d=>d.id===r),c=o??{...l,coverage:0},h=l??{...o,coverage:0};return{...c,instances:gy(o?.instances,l?.instances,t),baseM:$t(c.baseM,h.baseM,t),thicknessM:$t(c.thicknessM,h.thicknessM,t),coverage:$t(c.coverage,h.coverage,t),sizeM:$t(c.sizeM,h.sizeM,t),density:$t(c.density,h.density,t),darkness:$t(c.darkness??a.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:$t(c.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:c.windSpeed===void 0&&h.windSpeed===void 0?void 0:$t(c.windSpeed??a.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:wp(c.windDirectionDeg??a.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function by(a,e,t){return{cloudLayers:vy(a,e,t),cloudCover:$t(a.cloudCover,e.cloudCover,t),cloudDarkness:$t(a.cloudDarkness,e.cloudDarkness,t),highCloudCover:a.highCloudCover===void 0||e.highCloudCover===void 0?void 0:$t(a.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:a.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:$t(a.iceCrystalAlignment,e.iceCrystalAlignment,t),lowerCloudCover:a.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:$t(a.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:a.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:$t(a.cloudBaseM,e.cloudBaseM,t),relativeHumidity:a.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:$t(a.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?a.precipitationType:e.precipitationType,precipitationIntensity:$t(a.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:wp(a.windDirectionDeg,e.windDirectionDeg,t),windSpeed:$t(a.windSpeed,e.windSpeed,t),storm:t<1?a.storm:e.storm}}class _l{keyframes=[];ramp;addKeyframe(e,t){this.ramp=void 0;const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,weather:t}:this.keyframes.splice(i,0,{t:e,weather:t})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(e){this.ramp=void 0;const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}getLatestWeatherAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].weather:void 0}getInterpolatedWeatherAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.weather;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];return i?n?by(i.weather,n.weather,my((e-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(e){const t=this.getInterpolatedWeatherAt(e);if(!t)return;const i=(this.ramp??=new gr(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,o=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,precipitationType:n,precipitationIntensity:r,precipitationAmount:o}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new _l;for(const i of e.keyframes)t.addKeyframe(i.t,i.weather);return t}}class Al{keyframes=[];addKeyframe(e,t){const i=this.findInsertIndex(e);this.keyframes[i]?.t===e?this.keyframes[i]={t:e,sound:t}:this.keyframes.splice(i,0,{t:e,sound:t})}clear(){this.keyframes.length=0}removeKeyframeAt(e){const t=this.findInsertIndex(e);this.keyframes[t]?.t===e&&this.keyframes.splice(t,1)}getLatestSoundAt(e){let t=this.findInsertIndex(e);return this.keyframes[t]?.t!==e&&(t-=1),t>=0?this.keyframes[t].sound:void 0}getInterpolatedSoundAt(e){const t=this.findInsertIndex(e),i=this.keyframes[t]?.t===e?this.keyframes[t]:this.keyframes[t-1];if(i?.t===e)return i.sound;const n=this.keyframes[t]?.t===e?void 0:this.keyframes[t];if(!i)return n?.sound;if(!n)return i.sound;const s=(e-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(e){const t=new Al;for(const i of e.keyframes)t.addKeyframe(i.t,i.sound);return t}lerp(e,t,i){return{kind:i<1?e.kind:t.kind,volume:e.volume+(t.volume-e.volume)*i,pitchHz:e.pitchHz+(t.pitchHz-e.pitchHz)*i,src:i<1?e.src:t.src}}findInsertIndex(e){let t=0,i=this.keyframes.length;for(;t<i;){const n=t+i>>>1;this.keyframes[n].t<e?t=n+1:i=n}return t}}const yy=["none","hum","whistle","rumble","crackle"],My=100,wy={kind:"none",volume:0,pitchHz:My},Xl=[{id:"eye",name:"Naked eye",flare:0,projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"instamatic-126",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"slr-35mm-zoom",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0}},{id:"phone-portrait",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0}}];class Et{static get default(){return Xl[0]}static byId(e){return Xl.find(t=>t.id===e)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(e){const t=e.frame;return t?2*Math.atan(t.heightMm/(2*t.focalLengthMm))*180/Math.PI:Et.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Et.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Et.aspectOf(e))}static availableAt(e){return e===void 0?Xl:Xl.filter(t=>!t.years||e>=t.years.from&&(t.years.to===void 0||e<=t.years.to))}static fieldOfViewDegAt(e,t){const i=e.frame;if(!(!i||t<=0))return 2*Math.atan(i.heightMm/(2*t))*180/Math.PI}static focalLengthMmFor(e,t){const i=e.frame;if(!(!i||t<=0||t>=180))return i.heightMm/(2*Math.tan(t*Math.PI/360))}static bladesShowing(e,t){const i=t??e.fNumber;if(i===void 0||e.apertureBlades===void 0)return 0;const n=e.fNumberRange;return!n||n.max<=n.min?1:Math.max(0,Math.min(1,(i-n.min)/(n.max-n.min)))}static LENS_FLARE_ARTIFACTS=1;static flareArtifactsOf(e){return e.flare??Et.LENS_FLARE_ARTIFACTS}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class Sn{constructor(e){this.entries=e}static empty(){return new Sn(new Map)}get size(){return this.entries.size}at(e){return this.entries.get(e)}paths(){return[...this.entries.keys()]}set(e,t){t.basis==="stated"&&t.rationale===void 0?this.entries.delete(e):this.entries.set(e,t)}clear(e){for(const t of this.entries.keys())(t===e||t.startsWith(`${e}.`))&&this.entries.delete(t)}static strip(e){const t=new Sn(new Map);return{recording:Sn.stripValue(e,[],t),provenance:t}}static restore(e,t){if(t.size===0)return e;const i=structuredClone(e);for(const n of t.paths()){const s=t.at(n),r=n.split("."),o=Sn.holderOf(i,r);if(!o)continue;const l=r[r.length-1],c=o[l];c!==void 0&&(s.of!==void 0&&JSON.stringify(s.of)!==JSON.stringify(c)||(o[l]={value:c,...s.basis==="stated"?{}:{basis:s.basis},...s.rationale===void 0?{}:{rationale:s.rationale}}))}return i}static isWrapper(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&"value"in e}static stripValue(e,t,i){return Sn.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},of:e.value}),Sn.stripValue(e.value,t,i)):Array.isArray(e)?e.map((n,s)=>Sn.stripValue(n,[...t,String(s)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Sn.stripValue(s,[...t,n],i)])):e}static holderOf(e,t){let i=e;for(const n of t.slice(0,-1)){if(typeof i!="object"||i===null)return;i=i[n]}return typeof i=="object"&&i!==null?i:void 0}}const xy=/^(?:(?<year>\d{4}|\d{3}X|\d{2}XX)(-(?<month>0[1-9]|1[0-2]))?(-(?<day>0[1-9]|[12]\d|3[01]))?(?:[T ](?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?)?|(?<timeOnlyHour>[01]?\d|2[0-3]):(?<timeOnlyMinute>[0-5]\d)(?::(?<timeOnlySecond>[0-5]\d))?)[?~%]?$/;function I0(a){const e=xy.exec(a.trim());if(!e?.groups)return;const{year:t,month:i,day:n,hour:s,minute:r,second:o,timeOnlyHour:l,timeOnlyMinute:c,timeOnlySecond:h}=e.groups,d=s??l,u=r??c,f=o??h;return{year:t&&!t.includes("X")?Number(t):void 0,month:i?Number(i):void 0,day:n?Number(n):void 0,hour:d?Number(d):void 0,minute:u?Number(u):void 0,second:f?Number(f):void 0,raw:a.trim()}}function dh(a){if(a.raw!==void 0)return a.raw;if(a.year===void 0){if(a.hour===void 0)return"";let t=`${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`;return a.second!==void 0&&(t+=`:${String(a.second).padStart(2,"0")}`),t}let e=String(a.year).padStart(4,"0");return a.month===void 0||(e+=`-${String(a.month).padStart(2,"0")}`,a.day===void 0)||(e+=`-${String(a.day).padStart(2,"0")}`,a.hour===void 0)||(e+=`T${String(a.hour).padStart(2,"0")}:${String(a.minute??0).padStart(2,"0")}`,a.second!==void 0&&(e+=`:${String(a.second).padStart(2,"0")}`)),e}function zu(a){if(a.year!==void 0)return Date.UTC(a.year,(a.month??1)-1,a.day??1,a.hour??0,a.minute??0,a.second??0)}function D0(a){return(((a.day??0)*24+(a.hour??0))*60+(a.minute??0))*6e4+(a.second??0)*1e3}const Sy=["year","month","day","hour","minute"],Ey=["day","hour","minute"];function R0(a,e){return e.filter(t=>a[t]!==void 0).join(",")}function _o(a){if(a.durationSeconds!==void 0)return a.durationSeconds*1e3;if(!a.time||!a.endTime)return;const e=a.time.year!==void 0&&a.endTime.year!==void 0,t=e?Sy:Ey,i=R0(a.time,t);if(!(i===""||i!==R0(a.endTime,t)))return e?zu(a.endTime)-zu(a.time):D0(a.endTime)-D0(a.time)}function _y(a){if(a.durationSeconds===void 0&&!(!a.time||!a.endTime))return _o(a)===void 0?"imprecise":void 0}class Xh{constructor(e,t,i,n,s,r,o,l,c=[],h,d,u,f=[],p=[],v=[],m=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=o,this.weather=l,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=f,this.references=p,this.roads=v,this.traces=m}provenance=Sn.empty();loadIssues=[];account;sources;interpretation;sway;lightPollution;iso;vehicle;get observerCount(){return 1+this.decor.filter(e=>e.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return Et.byId(this.instrumentId)}static create(e,t,i){return new Xh({eventType:"sighting",time:e,place:t},new Wh,new El,new _l,new Al,i)}}const Ay=0,Ty=0;function et(a,e){const t=a.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=a.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:Ay,headingDeg:void 0,pitchDeg:Ty,fovDeg:Et.fieldOfViewDeg(a.instrument)}}function ii(a,e){return a.weatherTrack.getInterpolatedWeatherAt(e)??a.weather??Mp}function $l(a,e){return a.weatherTrack.getActualWeatherAt(e)??a.weather??Mp}function xp(a,e){return a.soundTrack.getInterpolatedSoundAt(e)??wy}function Iy(a,e,t){const i=(o,l)=>o.x*l.x+o.y*l.y+o.z*l.z,n=i(t,a),s=i(e,a);if(n<=0||s<=.05)return;const r=n/s;return{x:e.x*r-a.x*n,y:e.y*r-a.y*n,z:e.z*r-a.z*n}}const Qv={intro:"Weather records supply coverage and wind when available. Cloud shape, thickness and size are visual estimates; they are not measured individual clouds.",editScope:"Edit scope",scopeInstant:"Current time",scopeObservation:"Whole observation",layer:"Layer",addLayer:"Add layer",deleteLayer:"Delete layer",cloudType:"Cloud type",unknownType:"Unknown",base:"Base (m)",thickness:"Thickness (m)",coverage:"Coverage (%)",cloudSize:"Cloud size (m)",density:"Density",darkness:"Darkness",crystalAlignment:"Crystal alignment",layerWindDirection:"Layer wind direction (°)",layerWindSpeed:"Layer wind speed (m/s)",generalWind:"General wind",patternSeed:"Pattern seed",editHelp:"Edits pause playback and save at the current weather time. Empty layer wind fields inherit the general wind. Whole observation applies the edited property to every weather keyframe.",individualClouds:"Individual clouds",individualCloud:"Individual cloud",addIndividualCloud:"Add individual cloud",pointAtCloud:"Point at cloud",deleteCloud:"Delete cloud",manipulate:"Select and drag clouds in the sky",instanceEast:"East position (m)",instanceNorth:"North position (m)",instanceBase:"Cloud base (m)",instanceThickness:"Cloud thickness (m)",instanceWidth:"Cloud width (m)",instanceDepth:"Cloud depth (m)",instanceRotation:"Cloud rotation (°)",instanceDensity:"Cloud density",layerDarkness:"Layer darkness",individualHelp:"Individual clouds remain present at 0% global coverage. Dragging changes position and altitude; numeric fields provide precise dimensions. Clouds follow their layer's wind.",none:"None",cloud:"Cloud",savedAcrossObservation:"Saved across the observation; winds preserved.",savedAtThisTime:"Weather saved at this time.",noCloudHere:"No individual cloud here.",cloudSelected:"Cloud selected. Drag to move it.",cloudAdded:" Individual cloud added, independent of global coverage."};class C0{static html(e=Qv){const t=n=>`<span data-text="${n}">${e[n]}</span>`,i=(n,s,r="",o="",l)=>`<label>${t(s)}<input id="${n}" type="number" step="any" ${r?`min="${r}"`:""} ${o?`max="${o}"`:""} placeholder="${l?e[l]:""}"${l?` data-placeholder="${l}"`:""}></label>`;return`<div class="cloud-panel">
|
|
3
3
|
<p data-text="intro">${e.intro}</p>
|
|
4
4
|
<div class="cloud-fields">
|
|
@@ -2678,7 +2678,7 @@ canvas[data-cursor="rotate"] {
|
|
|
2678
2678
|
}
|
|
2679
2679
|
`;class uo{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 uo(t)}static TRAVEL_M=50;get travels(){return this.spanM>uo.TRAVEL_M}get moved(){return this.spanM>uo.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(ni(t,e.east,t,e.west).x),Math.abs(ni(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:Dn(0,-s,i,n).lat,south:Dn(0,s,i,n).lat,east:Dn(s,0,i,n).lng,west:Dn(-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 kn{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)>kn.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new kn(Math.max(1-(e.instrument.stabilization??0),kn.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,n=(d,u)=>Math.sin(2*Math.PI*d*t+u),[s,r,o,l,c,h]=kn.HZ;return{eastM:i*kn.SWAY_M*(.7*n(s,.3)+.3*n(l,1.9)),northM:i*kn.SWAY_M*(.6*n(o,2.2)+.4*n(c,.8)),upM:i*kn.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*kn.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(l,2.7)),pitchDeg:i*this.rotationPassed*kn.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(o,.4)),rollDeg:i*this.rotationPassed*kn.DRIFT_ROLL_DEG*n(s,2.9)}}}class Dt{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=uo.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],l=(o.t-r.t)/1e3;if(l<=0)continue;const c=ni(o.lat,o.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),f=u/l,p=Dt.stepHzFor(f);i.push({startMs:r.t,endMs:o.t,speedMPerS:f,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*l}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 Dt(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=Dt.of(e)?.offsetAt(t)??Dt.STILL;return i?n:Dt.add(n,kn.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Dt.SLOWEST_WALK_M_PER_S||e>Dt.FASTEST_WALK_M_PER_S?0:Dt.REFERENCE_STEP_HZ*Math.pow(e/Dt.REFERENCE_SPEED_M_PER_S,Dt.CADENCE_EXPONENT)}offsetAt(e){return Dt.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Dt.REFERENCE_SPEED_M_PER_S,n=(o,l,c,h)=>{if(o<0||o>Dt.JOLT_LASTS_MS)return;const d=o/1e3,u=Math.exp(-d/Dt.JOLT_DECAY_S)*Math.sin(2*Math.PI*Dt.JOLT_HZ*d),f=h*l*i*u;return{eastM:f*t.eastUnit,northM:f*t.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,Dt.STOP_LURCH_M,Dt.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,Dt.START_LURCH_M,Dt.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(l=>e>=l.startMs&&e<=l.endMs);if(!t||t.stepHz===0)return Dt.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=Dt.SWAY_M*s*Math.cos(n/2),o=s*this.rotationPassed*t.speedMPerS/Dt.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Dt.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:Dt.HEAD_ROLL_DEG*o*Math.cos(n/2),pitchDeg:-1.25*o*Math.cos(n),yawDeg:Dt.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 Jy{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)}}class la{static sessionDeclared=!1;static unlock(e){if(la.declarePlayback(),e.state!=="running")try{Promise.resolve(e.resume()).catch(()=>{});const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,22050),t.connect(e.destination),t.start(0)}catch{}}static declarePlayback(){if(!(la.sessionDeclared||typeof navigator>"u")){la.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const H0=.05,G0=.08,V0=2,W0=3,Qy=14,eM=.02;class tM{context;voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}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}}la.unlock(this.context)}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.master=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,H0);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,H0)}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(this.output(e)),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(this.output(e)),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(this.output(e)),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(this.output(e)),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(l){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",l);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(this.output(n)),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*V0),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*V0),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*W0),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(eM*e.sampleRate)),s=Math.round(W0*Qy);for(let r=0;r<s;r++){const o=Math.floor(Math.random()*i.length),l=.4+Math.random()*.6;for(let c=0;c<n&&o+c<i.length;c++)i[o+c]=Math.max(i[o+c],l*(1-c/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,G0/3);const n=i+G0;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()}}}}class Ge{static svg(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor"/></svg>`}static outline(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(e){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${e}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=Ge.outline(Ge.BOOKMARK);static MILESTONES_ON=Ge.solid(Ge.BOOKMARK);static PICTURES_OFF=Ge.outline(`${Ge.PICTURE}${Ge.PICTURE_HILLS}`);static PICTURES_ON=Ge.solid(`${Ge.PICTURE}${Ge.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=Ge.outline(`${Ge.TRACE_LINE}${Ge.TRACE_MARK}`);static TRACES_ON=Ge.solid(`${Ge.TRACE_LINE}${Ge.TRACE_MARK}`);static MAP_OFF=Ge.outline(`${Ge.PIN}${Ge.PIN_HOLE}`);static MAP_ON=Ge.solid(`${Ge.PIN}${Ge.PIN_HOLE}`);static SHARE=Ge.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static FOLDED=Ge.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Ge.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Ge.svg("M7.4 5v14l11-7z");static PAUSE=Ge.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Ge.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=Ge.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=Ge.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Ge.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}function ca(a){return[...a].sort((e,t)=>e.t-t.t)}function ud(a,e){let t;for(const i of ca(a)){if(i.t>e)break;t=i}return t}const fd=Math.PI/180,Zl=180/Math.PI;class is{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*fd/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new is(e.projection,t,i)}degToPx(e){const t=e*fd;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*Zl:2*Math.atan(e/(2*this.focalPx))*Zl}angleDegToRadiusPx(e){const t=e*fd;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*Zl:Math.atan(e/this.focalPx)*Zl}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(it.angularWidthDeg(e))}}class Si{static fovOf(e,t){return et(e,t)?.fovDeg??Et.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,l=t.bounds.height===0?1:s/t.bounds.height;return{...t,bounds:r,points:t.points.map(c=>({x:c.x*o,y:c.y*l}))}})}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)<Si.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<Si.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=is.of(e.instrument,it.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,et(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),l=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,o)-i.width/2,y:r.y-this.offAxisPx(n,l)-i.height/2}}static frameCentre(e){return{x:Et.frameWidthPx(e.instrument,it.CANVAS_HEIGHT_PX)/2,y:it.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=Si.OFF_CANVAS_DEG?Math.sign(t)*Si.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=Et.frameWidthPx(t,it.CANVAS_HEIGHT_PX)/2,s=Et.frameWidthPx(e.instrument,it.CANVAS_HEIGHT_PX)/2,r=it.CANVAS_HEIGHT_PX/2;for(const o of[...e.timeline.allKeyframes]){const l=this.fovOf(e,o.t),c=i?.get(o.t)??l,h=is.of(t,it.CANVAS_HEIGHT_PX,c),d=is.of(e.instrument,it.CANVAS_HEIGHT_PX,l);e.timeline.addKeyframe(o.t,o.shapes.map(u=>{const{bounds:f}=u.shape,p=f.x+f.width/2-n,v=f.y+f.height/2-r,m=Math.hypot(p,v),g=m===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,x={...f,x:s+p*g-f.width/2,y:r+v*g-f.height/2};return{...u,shape:{...u.shape,bounds:x}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=et(e,n.t),r=this.fovOf(e,n.t),o=is.of(e.instrument,it.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(l=>({...l,shape:t(l.shape,o,s)})))}}}function iM(a){return Sn.restore(Yu(a),a.provenance)}function Yu(a){return Si.toAngular(a),Si.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,sources:a.sources?.length?a.sources:void 0,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,traces:a.traces.length>0?a.traces:void 0,weatherSource:a.weatherSource,instrument:a.instrumentId,exposureSeconds:a.exposureSeconds,iso:a.iso,lightPollution:a.lightPollution,interpretation:a.interpretation}}function nM(a){const{recording:e,provenance:t}=Sn.strip(a),i=sM(e);return i.provenance=t,i}function sM(a){const e=[],t=new Xh({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},Wh.fromJSON(a.timeline,e),a.observerTrack?El.fromJSON(a.observerTrack):new El,a.weatherTrack?_l.fromJSON(a.weatherTrack):new _l,a.soundTrack?Al.fromJSON(a.soundTrack):new Al,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(i=>i.pose.exposureSeconds).find(i=>i!==void 0),ca(a.milestones??[]),a.references??[],a.roads??[],a.traces??[]);return t.account=a.account,t.sources=a.sources,t.sway=a.sway,t.iso=a.iso,t.lightPollution=a.lightPollution,t.vehicle=a.vehicle,t.interpretation=a.interpretation,t.loadIssues=e,Si.toBounds(t),Si.toPosition(t),t}class Ao{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(e,t=Ao.EN){return t[e.kind].replace("{path}",e.path).replace("{expected}",e.expected??"").replace("{found}",e.found??"")}static warn(e,t){if(e.length===0)return;const i=e.map(n=>` ${Ao.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
2680
2680
|
${i.join(`
|
|
2681
|
-
`)}`)}}class Xn{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!Xn.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Xn.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const o=i?`${i}.${s}`:s,l=t[s];l?this.field(r,l,o,n):n.push({kind:"unknown-key",path:o})}}field(e,t,i,n){if(Xn.isStated(e)){this.field(e.value,t,i,n);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&n.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,n):Xn.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:Xn.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const o=Xn.isStated(s)?s.value:s;this.object(o,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Xn.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:Xn.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return Xn.isObject(e)&&"value"in e&&Object.keys(e).every(t=>t==="value"||t==="basis"||t==="rationale")}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class Zn{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?Zn.travelDegOver(e,t,i,i+n*1e3)/s/Zn.PIXELS_PER_INSTANT:0,o=Zn.flashesOver(e,n)*Zn.INSTANTS_PER_FLASH,l=Math.ceil(Math.max(r,o));return l<2?1:Math.min(Zn.MAX_INSTANTS,l)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=Zn.directionAt(r,t,i),l=Zn.directionAt(r,t,n),c=Math.min(1,Math.max(-1,o.x*l.x+o.y*l.y+o.z*l.z));s=Math.max(s,Math.acos(c)*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=Dr(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,l=Math.hypot(s,r,o);return l===0?{x:0,y:1,z:0}:{x:s/l,y:r/l,z:o/l}}}function vh(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class qs{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 Qn{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[Qn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>Qn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(Qn.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=>Qn.base(o)===Qn.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 r1={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",mute:"Mute",unmute:"Unmute",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:Ao.EN},rM=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:r1},Symbol.toStringTag,{value:"Module"})),a1=Math.PI/180,aM=180/Math.PI,oM=256,o1=19,lM=1.25;function l1(a,e){return 156543.03392*Math.cos(a*a1)/2**e}function c1(a,e){return l1(a,e)*oM}function cM(a,e){let t=0;for(;t<o1&&c1(a,t+1)>=e;)t++;return t}function h1(a,e){return c1(a,e)}function hM(a,e){const t=e*lM;let i=0;for(;i<o1&&l1(a,i)>t;)i++;return i}function jc(a){const e=a*a1;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function d1(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:jc(e)*i}}function u1(a,e,t){const i=jc(a.north),n=jc(a.south);return{x:(e-a.west)/(a.east-a.west),y:(jc(t)-i)/(n-i)}}function dM(a,e,t){const{x:i,y:n}=d1(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function uM(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=X0(a.y,e);return{south:X0(a.y+1,e),north:n,west:t,east:i}}function X0(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*aM}function f1(a,e,t,i){const n=dM(a,e,t),s=Math.floor(i/2),r=[];for(let c=-s;c<=s;c++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+c,z:t});const o=r.map(uM),l={south:Math.min(...o.map(c=>c.south)),north:Math.max(...o.map(c=>c.north)),west:Math.min(...o.map(c=>c.west)),east:Math.max(...o.map(c=>c.east))};return{tiles:r,bounds:l}}const fM="#2ec4ff";class Kr{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),this.paintTraces(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=u1(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()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const n=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??fM;if(i.kind==="point")t.beginPath(),t.moveTo(n[0].x,n[0].y-6),t.lineTo(n[0].x+6,n[0].y),t.lineTo(n[0].x,n[0].y+6),t.lineTo(n[0].x-6,n[0].y),t.closePath(),t.fillStyle=s,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=s,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=n[0];if(i.kind==="line"&&e.position){const o=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((l,c)=>Math.hypot(c.x-o.x,c.y-o.y)>Math.hypot(l.x-o.x,l.y-o.y)?c:l)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}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),l=(i-90)*Math.PI/180,c=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,o,l-c,l+c),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:Kr.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Kr.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=ni(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Kr.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Kr.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,l=Math.abs(ni(r,e.east,r,e.west).x)/this.width,c=Kr.SCALE_STEPS_M.find(f=>f/l<=this.width/3);if(c===void 0)return;const h=c/l,d=8,u=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,d,u-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 Jt{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(Jt.MAX_ZOOM,Math.max(Jt.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=Jt.mercatorY01(t.north),s=Jt.mercatorY01(t.south),r=Jt.mercatorY01(i.north),o=Jt.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)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=Jt.mercatorY01(n.north),r=Jt.mercatorY01(n.south),o=(t.lng-n.west)/(n.east-n.west),l=(Jt.mercatorY01(t.lat)-s)/(r-s);return o>=i&&o<=1-i&&l>=i&&l<=1-i?!1:(this.panBy(.5-o,.5-l),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=Jt.mercatorY01(e.north),n=Jt.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:Jt.latitudeAt(i+(this.centerY-t)*(n-i)),south:Jt.latitudeAt(i+(this.centerY+t)*(n-i))}}static including(e,t,i=3){const n=(e.north+e.south)/2,s=(e.east+e.west)/2,r=ni(n,e.east,n,s).x;let o=r;for(const l of t){const{x:c,z:h}=ni(l.lat,l.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(o=Math.max(o,d*1.15))}return o<=r?e:{north:Dn(0,-o,n,s).lat,south:Dn(0,o,n,s).lat,east:Dn(o,0,n,s).lng,west:Dn(-o,0,n,s).lng}}static expand(e,t){const i=e.east-e.west,n=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-n*t,north:e.north+n*t}}static pointAt(e,t,i){const n=Jt.mercatorY01(e.north),s=Jt.mercatorY01(e.south);return{lat:Jt.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 Pn=256,$0=3,pM=32768;class p1{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(ni(i,e.east,i,e.west).x),r=Math.abs(ni(e.north,n,e.south,n).z),o=cM(i,Math.max(s,r)),{tiles:l}=f1(n,i,o,$0),c=$0*Pn,h=new Float32Array(c*c),d=l[0];await Promise.all(l.map(f=>this.decodeTileInto(f,d,h,c)));const u=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));u[f*t.width+v]=this.sampleAt(p,m,o,d,h,c)}}return{heights:u,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()),l=document.createElement("canvas");l.width=Pn,l.height=Pn;const c=l.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(o,0,0);const{data:h}=c.getImageData(0,0,Pn,Pn),d=(e.x-t.x)*Pn,u=(e.y-t.y)*Pn;for(let f=0;f<Pn;f++)for(let p=0;p<Pn;p++){const v=(f*Pn+p)*4,m=h[v]*256+h[v+1]+h[v+2]/256-pM,g=d+p,x=u+f;i[x*n+g]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:l}=d1(t,e,i),c=(o-n.x)*Pn,h=(l-n.y)*Pn,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,d+1),p=Math.min(r-1,u+1),v=c-d,m=h-u,g=s[u*r+d],x=s[u*r+f],y=s[p*r+d],b=s[p*r+f],w=g+(x-g)*v,E=y+(b-y)*v;return w+(E-w)*m}}const Jc=256,mM=5;async function m1(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ni(n,a.east,n,a.west).x),o=Math.abs(ni(a.north,s,a.south,s).z),l=Math.max(r,o),{zoom:c,gridSize:h}=gM(n,l,Math.max(e.width,e.height)),{tiles:d,bounds:u}=f1(s,n,c,h),f=h*Jc,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=d[0];await Promise.all(d.map(async b=>{const w=t(b),E=await i(w);if(!E.ok)throw new Error(`Imagery tile fetch failed (${E.status}): ${w}`);const T=await createImageBitmap(await E.blob());v.drawImage(T,(b.x-m.x)*Jc,(b.y-m.y)*Jc)}));const g=Math.min(Math.max(e.width,e.height),f);if(g===f)return{source:p,width:f,height:f,bounds:u};const x=document.createElement("canvas");x.width=g,x.height=g;const y=x.getContext("2d");if(!y)throw new Error("2D canvas context unavailable");return y.drawImage(p,0,0,f,f,0,0,g,g),{source:x,width:g,height:g,bounds:u}}function gM(a,e,t){let i=hM(a,e/Math.max(1,t)),n=Y0(a,i,e);for(;n>mM&&i>0;)i--,n=Y0(a,i,e);return{zoom:i,gridSize:n,mPerPixel:h1(a,i)/Jc}}function Y0(a,e,t){const i=Math.ceil(t/2/h1(a,e));return Math.max(3,2*i+1)}class g1{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 m1(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class $n{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??$n.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"~"^(${$n.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:$n.surfaceOf(s),widthM:$n.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=$n.queue.then(e,e);return $n.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,$n.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:$n.WIDTH_M[e.highway]??$n.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 pd="https://ufoathome.org/roads/index.json";class Ap{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Ap.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.85.1")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==pd?[t,pd]:[pd]).map(i=>i+e)}}function vM(){return{elevation:new p1,imagery:v1(),roads:bM()}}function v1(){return new g1}function bM(){return new Ap({fallback:new $n})}const yM=new Set,ha="show-observer-map",fo="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",ha,fo]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Jt;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Xh.create();issues=[];issueCheck=0;sightingAudio=new tM;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=r1;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");vt.setIcon(this.moreButton,e?Ge.UNFOLDED:Ge.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=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.paintObserverMap(this.currentTime),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)<vt.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>=Jt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Jt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=Jt.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>${jy}</style>${Zy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Tl(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",t=>{t.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Kr(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",t=>{t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}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),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===ha&&this.applyObserverMapDefault(),e===fo&&this.setMilestonesShown(!this.hasAttribute(fo))}async loadFromSrc(e){this.sightingData=await Sp.json(e)}get sightingData(){return iM(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=nM(e),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await ot(async()=>{const{default:r}=await import("./sightingSchema-DKClwkcL.js");return{default:r}},[],import.meta.url);n=new Xn(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Ao.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(MM,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Ao.text(i,this.messages.issueTemplates),n}))}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),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(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.updateTracesButton(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)this.controlsRight.insertBefore(n,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)),vt.setIcon(this.referencesButton,this.referencesShownState?Ge.PICTURES_ON:Ge.PICTURES_OFF);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)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),vt.setIcon(this.tracesButton,this.tracesShownState?Ge.TRACES_ON:Ge.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?ca(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})),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=vt.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?ud(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}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=vt.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?ud(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!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=Zn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.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 l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(c,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=Et.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:yM;this.canvasRenderer.setStarPoints(Et.starPointsOf(this.sighting.instrument));const n=(et(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[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=wt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(xp(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 Jy(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;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};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*vt.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.innerHTML=this.player.playbackState==="playing"?Ge.PLAY:Ge.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},vt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,vt.setIcon(this.playPauseButton,e?Ge.PAUSE:Ge.PLAY);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(),this.updateMuteButton()}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(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear()}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ha),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 e=!this.observerMapPanel.hidden;vt.setIcon(this.observerMapButton,e?Ge.MAP_ON:Ge.MAP_OFF);const t=e?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=uo.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.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Jt.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(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.observerMapImageryLoading||!this.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?Jt.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=v1();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=s.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?Jt.expand(e,vt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}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=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!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=et(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?ud(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?ca(this.currentSighting.milestones):[]){const o=et(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?is.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Et.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(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.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ca(this.sighting.milestones).map(t=>t.t)),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,this.momentsButton.title=this.messages.moments,vt.setIcon(this.milestonesButton,this.milestonesShown?Ge.MILESTONES_ON:Ge.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=et(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Dr(i,e),{lat:s,lng:r}=Dn(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=et(this.currentSighting,this.currentTime),s=is.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Dt.bodyAt(this.currentSighting,e,this.steadyObserver)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=vt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.muted=!this.mutedState}updateMuteButton(){vt.setIcon(this.muteButton,this.mutedState?Ge.MUTED:Ge.VOLUME);const e=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=e,this.muteButton.setAttribute("aria-label",e),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Ge.EXIT_FULLSCREEN:Ge.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Qn(qs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=vh(qs.preferencesFor(this),uh);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Ry(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;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,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=_o(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?zu(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 jl(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?K0(q0(this.realStartMs+i)):jl(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?jl(this.currentSighting.timeline.duration):this.canShowClockTime?K0(q0(this.realStartMs+this.realDurationMs)):jl(this.realDurationMs)}}function q0(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function K0(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 jl(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const qu="rr0-ufo";function $h(){customElements.get(qu)||customElements.define(qu,vt)}const MM="recordingissues";class ml{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+ml.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ml.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ml.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}const wM=.08,Z0=.15,j0=2,xM=2e3;class SM{context;noiseBuffer;voices=new Map;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}la.unlock(this.context),this.apply()}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<xM),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(e.destination);const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*j0*.5,w},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const f=c(),p=e.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const v=e.createGain();f.connect(p).connect(v).connect(n);const m=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const x=e.createGain();m.connect(g).connect(x).connect(n);const y=[s,r,h,f,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,p,v,g,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:v,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,wM),d=n.rpm/60,u=d*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*p**1.5*.8);const v=!r||o;h(t.windGain.gain,p**2*(v?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const g=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,g*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,Z0/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},Z0*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*j0,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Il{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Il.BY_KIND[e??"generic"]??Il.BY_KIND.generic}}class ta{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=ta.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const o=[];let l=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<ta.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,f=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&f(l)>e.shiftUpRpm;)l++;for(;l>1&&f(l)<e.shiftDownRpm;)l--;const p=Math.max(f(l),e.idleRpm*(1+.3*Math.min(1,h/3))),v=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,v+d/2.5):d<-.3?.05:v;o.push({speedMps:h,rpm:p,load:m,gear:l})}return new ta(o,i)}at(e){const t=(e-this.startMs)/ta.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class bh{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const f=ni(d,u,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Il.of(o.kind),h=this.drive(`observer:${o.kind}`,bh.trackKey(e),()=>ta.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Il.of(c.engine.kind),d=v=>{const m=Dr(c,v);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,bh.decorKey(c,r),()=>ta.of(h,d,0,r));if(!u)continue;const f=Dr(c,t),p=Math.hypot(f.eastM-l.eastM,f.northM-l.northM,f.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const EM=`
|
|
2681
|
+
`)}`)}}class Xn{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!Xn.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Xn.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const o=i?`${i}.${s}`:s,l=t[s];l?this.field(r,l,o,n):n.push({kind:"unknown-key",path:o})}}field(e,t,i,n){if(Xn.isStated(e)){this.field(e.value,t,i,n);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&n.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,n):Xn.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:Xn.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const o=Xn.isStated(s)?s.value:s;this.object(o,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Xn.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:Xn.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return Xn.isObject(e)&&"value"in e&&Object.keys(e).every(t=>t==="value"||t==="basis"||t==="rationale")}static typeOf(e){return Array.isArray(e)?"array":e===null?"null":typeof e}}class Zn{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?Zn.travelDegOver(e,t,i,i+n*1e3)/s/Zn.PIXELS_PER_INSTANT:0,o=Zn.flashesOver(e,n)*Zn.INSTANTS_PER_FLASH,l=Math.ceil(Math.max(r,o));return l<2?1:Math.min(Zn.MAX_INSTANTS,l)}static travelDegOver(e,t,i,n){let s=0;for(const r of e){if(!r.track||r.track.length<2)continue;const o=Zn.directionAt(r,t,i),l=Zn.directionAt(r,t,n),c=Math.min(1,Math.max(-1,o.x*l.x+o.y*l.y+o.z*l.z));s=Math.max(s,Math.acos(c)*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=Dr(e,i),s=n.eastM,r=n.altitudeM-t,o=n.northM,l=Math.hypot(s,r,o);return l===0?{x:0,y:1,z:0}:{x:s/l,y:r/l,z:o/l}}}function vh(a,e){for(const t of a){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class qs{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 Qn{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[Qn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>Qn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(Qn.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=>Qn.base(o)===Qn.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 r1={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",mute:"Mute",unmute:"Unmute",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:Ao.EN},rM=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:r1},Symbol.toStringTag,{value:"Module"})),a1=Math.PI/180,aM=180/Math.PI,oM=256,o1=19,lM=1.25;function l1(a,e){return 156543.03392*Math.cos(a*a1)/2**e}function c1(a,e){return l1(a,e)*oM}function cM(a,e){let t=0;for(;t<o1&&c1(a,t+1)>=e;)t++;return t}function h1(a,e){return c1(a,e)}function hM(a,e){const t=e*lM;let i=0;for(;i<o1&&l1(a,i)>t;)i++;return i}function jc(a){const e=a*a1;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function d1(a,e,t){const i=2**t;return{x:(a+180)/360*i,y:jc(e)*i}}function u1(a,e,t){const i=jc(a.north),n=jc(a.south);return{x:(e-a.west)/(a.east-a.west),y:(jc(t)-i)/(n-i)}}function dM(a,e,t){const{x:i,y:n}=d1(a,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function uM(a){const e=2**a.z,t=a.x/e*360-180,i=(a.x+1)/e*360-180,n=X0(a.y,e);return{south:X0(a.y+1,e),north:n,west:t,east:i}}function X0(a,e){const t=a/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*aM}function f1(a,e,t,i){const n=dM(a,e,t),s=Math.floor(i/2),r=[];for(let c=-s;c<=s;c++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+c,z:t});const o=r.map(uM),l={south:Math.min(...o.map(c=>c.south)),north:Math.max(...o.map(c=>c.north)),west:Math.min(...o.map(c=>c.west)),east:Math.max(...o.map(c=>c.east))};return{tiles:r,bounds:l}}const fM="#2ec4ff";class Kr{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),this.paintTraces(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=u1(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()}paintTraces(e){const{ctx:t}=this;for(const i of e.traces??[]){const n=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??fM;if(i.kind==="point")t.beginPath(),t.moveTo(n[0].x,n[0].y-6),t.lineTo(n[0].x+6,n[0].y),t.lineTo(n[0].x,n[0].y+6),t.lineTo(n[0].x-6,n[0].y),t.closePath(),t.fillStyle=s,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))t.lineTo(r.x,r.y);i.kind==="polygon"&&t.closePath(),t.lineJoin="round",t.setLineDash([]),t.strokeStyle="rgba(0, 0, 0, 0.65)",t.lineWidth=4.5,t.stroke(),t.setLineDash([9,5]),t.strokeStyle=s,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=n[0];if(i.kind==="line"&&e.position){const o=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((l,c)=>Math.hypot(c.x-o.x,c.y-o.y)>Math.hypot(l.x-o.x,l.y-o.y)?c:l)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}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),l=(i-90)*Math.PI/180,c=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,o,l-c,l+c),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:Kr.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,Kr.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=ni(r.lat,r.lng,t.lat,t.lng);return Math.hypot(o.x,o.z)<=Kr.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?Kr.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,l=Math.abs(ni(r,e.east,r,e.west).x)/this.width,c=Kr.SCALE_STEPS_M.find(f=>f/l<=this.width/3);if(c===void 0)return;const h=c/l,d=8,u=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(d,u),i.lineTo(d+h,u),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(c>=1e3?`${c/1e3} km`:`${c} m`,d,u-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 Jt{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(Jt.MAX_ZOOM,Math.max(Jt.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=Jt.mercatorY01(t.north),s=Jt.mercatorY01(t.south),r=Jt.mercatorY01(i.north),o=Jt.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)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=Jt.mercatorY01(n.north),r=Jt.mercatorY01(n.south),o=(t.lng-n.west)/(n.east-n.west),l=(Jt.mercatorY01(t.lat)-s)/(r-s);return o>=i&&o<=1-i&&l>=i&&l<=1-i?!1:(this.panBy(.5-o,.5-l),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=Jt.mercatorY01(e.north),n=Jt.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:Jt.latitudeAt(i+(this.centerY-t)*(n-i)),south:Jt.latitudeAt(i+(this.centerY+t)*(n-i))}}static including(e,t,i=3){const n=(e.north+e.south)/2,s=(e.east+e.west)/2,r=ni(n,e.east,n,s).x;let o=r;for(const l of t){const{x:c,z:h}=ni(l.lat,l.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(o=Math.max(o,d*1.15))}return o<=r?e:{north:Dn(0,-o,n,s).lat,south:Dn(0,o,n,s).lat,east:Dn(o,0,n,s).lng,west:Dn(-o,0,n,s).lng}}static expand(e,t){const i=e.east-e.west,n=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-n*t,north:e.north+n*t}}static pointAt(e,t,i){const n=Jt.mercatorY01(e.north),s=Jt.mercatorY01(e.south);return{lat:Jt.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 Pn=256,$0=3,pM=32768;class p1{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(ni(i,e.east,i,e.west).x),r=Math.abs(ni(e.north,n,e.south,n).z),o=cM(i,Math.max(s,r)),{tiles:l}=f1(n,i,o,$0),c=$0*Pn,h=new Float32Array(c*c),d=l[0];await Promise.all(l.map(f=>this.decodeTileInto(f,d,h,c)));const u=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));u[f*t.width+v]=this.sampleAt(p,m,o,d,h,c)}}return{heights:u,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()),l=document.createElement("canvas");l.width=Pn,l.height=Pn;const c=l.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(o,0,0);const{data:h}=c.getImageData(0,0,Pn,Pn),d=(e.x-t.x)*Pn,u=(e.y-t.y)*Pn;for(let f=0;f<Pn;f++)for(let p=0;p<Pn;p++){const v=(f*Pn+p)*4,m=h[v]*256+h[v+1]+h[v+2]/256-pM,g=d+p,x=u+f;i[x*n+g]=m}}sampleAt(e,t,i,n,s,r){const{x:o,y:l}=d1(t,e,i),c=(o-n.x)*Pn,h=(l-n.y)*Pn,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,d+1),p=Math.min(r-1,u+1),v=c-d,m=h-u,g=s[u*r+d],x=s[u*r+f],y=s[p*r+d],b=s[p*r+f],w=g+(x-g)*v,E=y+(b-y)*v;return w+(E-w)*m}}const Jc=256,mM=5;async function m1(a,e,t,i){const n=(a.south+a.north)/2,s=(a.west+a.east)/2,r=Math.abs(ni(n,a.east,n,a.west).x),o=Math.abs(ni(a.north,s,a.south,s).z),l=Math.max(r,o),{zoom:c,gridSize:h}=gM(n,l,Math.max(e.width,e.height)),{tiles:d,bounds:u}=f1(s,n,c,h),f=h*Jc,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=d[0];await Promise.all(d.map(async b=>{const w=t(b),E=await i(w);if(!E.ok)throw new Error(`Imagery tile fetch failed (${E.status}): ${w}`);const T=await createImageBitmap(await E.blob());v.drawImage(T,(b.x-m.x)*Jc,(b.y-m.y)*Jc)}));const g=Math.min(Math.max(e.width,e.height),f);if(g===f)return{source:p,width:f,height:f,bounds:u};const x=document.createElement("canvas");x.width=g,x.height=g;const y=x.getContext("2d");if(!y)throw new Error("2D canvas context unavailable");return y.drawImage(p,0,0,f,f,0,0,g,g),{source:x,width:g,height:g,bounds:u}}function gM(a,e,t){let i=hM(a,e/Math.max(1,t)),n=Y0(a,i,e);for(;n>mM&&i>0;)i--,n=Y0(a,i,e);return{zoom:i,gridSize:n,mPerPixel:h1(a,i)/Jc}}function Y0(a,e,t){const i=Math.ceil(t/2/h1(a,e));return Math.max(3,2*i+1)}class g1{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 m1(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class $n{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??$n.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"~"^(${$n.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:$n.surfaceOf(s),widthM:$n.widthOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}queued(e){const t=$n.queue.then(e,e);return $n.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,$n.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:$n.WIDTH_M[e.highway]??$n.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 pd="https://ufoathome.org/roads/index.json";class Ap{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Ap.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.86.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==pd?[t,pd]:[pd]).map(i=>i+e)}}function vM(){return{elevation:new p1,imagery:v1(),roads:bM()}}function v1(){return new g1}function bM(){return new Ap({fallback:new $n})}const yM=new Set,ha="show-observer-map",fo="hide-milestones";class vt extends HTMLElement{static get observedAttributes(){return["src",ha,fo]}shadow;stageElement;canvas;canvasRenderer;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;static OBSERVER_MAP_MIN_SPAN_M=400;static OBSERVER_MAP_MARGIN=.6;static OBSERVER_MAP_IMAGERY_PX=768;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Jt;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=Xh.create();issues=[];issueCheck=0;sightingAudio=new tM;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=r1;realDurationMs;realStartMs;showClockTime=!0;handleFullscreenChange=()=>{this.updateFullscreenButton(),this.updateMuteButton(),this.resizeObserverMap()};controlsFitObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.fitControls());controlsMutations;fitControls(){const e=this.controlsRow,t=e.classList.contains("more-open"),i=()=>e.scrollWidth>e.clientWidth+1,n=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,e.classList.remove("narrow","more-open","nomoments","compact","tiny"),e.clientWidth>0&&i()){e.classList.add("narrow");for(const s of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(s)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");vt.setIcon(this.moreButton,e?Ge.UNFOLDED:Ge.FOLDED);const t=e?this.messages.fewerControls:this.messages.moreControls;this.moreButton.title=t,this.moreButton.setAttribute("aria-label",t),this.moreButton.setAttribute("aria-expanded",String(e))}addControl(e){this.controlsRight.insertBefore(e,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=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.paintObserverMap(this.currentTime),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)<vt.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>=Jt.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Jt.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},vt.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(e){const t=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!t||i.width===0||i.height===0)return;const n=Jt.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>${jy}</style>${Zy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Tl(this.canvas.getContext("2d")),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",t=>{t.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Kr(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",t=>{t.key!=="Enter"&&t.key!==" "||(t.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>this.player.seek(this.snapSeekToMark(Number(this.seekInput.value)))),this.seekInput.addEventListener("pointerdown",t=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(t),this.beginTouchScrub(t)}),this.seekInput.addEventListener("pointerup",t=>{this.seekSnapArmed=!1,this.endTouchScrub(t)}),this.seekInput.addEventListener("pointercancel",t=>this.endTouchScrub(t)),this.seekInput.addEventListener("pointermove",t=>{this.nameMarkUnder(t),this.hoverSeek(t),this.touchScrub(t)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const t of["touchend","click"])this.stageElement.addEventListener(t,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",t=>{if(this.enableClickToPlay){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}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),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.loadFromSrc(e)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===ha&&this.applyObserverMapDefault(),e===fo&&this.setMilestonesShown(!this.hasAttribute(fo))}async loadFromSrc(e){this.sightingData=await Sp.json(e)}get sightingData(){return iM(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=nM(e),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await ot(async()=>{const{default:r}=await import("./sightingSchema-DKClwkcL.js");return{default:r}},[],import.meta.url);n=new Xn(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],Ao.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(MM,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){const e=this.issues.length;this.issuesBox.hidden=e===0,this.shadow.getElementById("issues-count").textContent=String(e);const t=this.messages.recordingIssues.replace("{count}",String(e));this.issuesButton.title=t,this.issuesButton.setAttribute("aria-label",t),this.shadow.getElementById("issues-title").textContent=t,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const n=document.createElement("li");return n.textContent=Ao.text(i,this.messages.issueTemplates),n}))}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),e?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(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.updateTracesButton(),this.player.seek(this.player.time)}hostControls(e){const t=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(e)for(const i of t)e.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const n of t)this.controlsRight.insertBefore(n,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)),vt.setIcon(this.referencesButton,this.referencesShownState?Ge.PICTURES_ON:Ge.PICTURES_OFF);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)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),vt.setIcon(this.tracesButton,this.tracesShownState?Ge.TRACES_ON:Ge.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?ca(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})),this.refreshSeekSegments(e,t.map(i=>i.t)),this.refreshMomentsPicker(t)}refreshMomentsPicker(e){const t=this.milestonesShown&&e.length>0;this.momentsBox.hidden=!t,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...e.map(i=>{const n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",o=this.said.read(i.note);return s.textContent=o?`${r} — ${o}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(e){const i=(e?this.said.read(e.label)??"":"")||this.messages.moments;this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=e!==void 0&&Number(n.dataset.t)===e.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=e=>{if(!this.momentsMenu.hidden){if(e instanceof KeyboardEvent){e.key==="Escape"&&this.closeMomentsMenu();return}e.composedPath().some(t=>t===this.momentsMenu||t===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(e,t){const n=[0,...this.milestonesShown&&e>0?[...new Set(t.filter(r=>r>0&&r<e))].sort((r,o)=>r-o):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const o=document.createElement("div");o.className="seek-segment",o.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",o.append(l,c),s.push(o),this.seekSegmentList.push({start:n[r],end:n[r+1],element:o,played:c,hover:l})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,n=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(n,0),1)*100}%`}paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=vt.fillOf(i,e);const t=this.player.seekableDuration;this.seekDot.style.left=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`}hoverSeek(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=vt.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const o=this.milestonesShown?this.sighting.milestones:[],l=o.length>0?ud(o,s):void 0,c=l?this.said.read(l.label)??"":"",h=l?this.said.read(l.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(s)}leaveSeek(){for(const e of this.seekSegmentList)e.hover.style.width="0",e.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(e){const t=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=t===void 0,t?.(e,this.seekPreviewCanvas)}scrubbingPointer;beginTouchScrub(e){if(e.pointerType!=="mouse"){this.scrubbingPointer=e.pointerId;try{this.seekInput.setPointerCapture(e.pointerId)}catch{}this.seekToPointer(e)}}touchScrub(e){e.pointerId===this.scrubbingPointer&&this.seekToPointer(e)}endTouchScrub(e){e.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(e))}seekToPointer(e){const t=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(t.width<=0||i<=0)return;const n=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(n*i))}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=vt.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?ud(this.sighting.milestones,e):void 0;if(this.milestoneCaption.hidden=t===void 0,this.showCurrentMoment(t),!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=Zn.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<vt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(vt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/vt.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/vt.EXPOSURE_STEP_PX),s=Math.min(vt.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 l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(o.bounds.x+o.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(o.bounds.y+o.bounds.height/2);s=Math.max(s,Math.hypot(c,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=Et.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:yM;this.canvasRenderer.setStarPoints(Et.starPointsOf(this.sighting.instrument));const n=(et(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[,l]of o.shapes){const c=o.share,h=c===1?l:{...l,transparency:1-(1-l.transparency)*c};this.canvasRenderer.paintShape(this.shifted(h,r))}for(const[o,l]of s[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));if(this.selectionShown&&i.size>1){const o=wt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds));this.canvasRenderer.paintGroupHandles(o)}this.overlayPainter?.(this.canvasRenderer),this.mapShapeBounds=s.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(xp(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 Jy(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;handleFullscreenKey=e=>{e.key.toLowerCase()!=="f"||e.altKey||e.ctrlKey||e.metaKey||!this.enableClickToPlay||e.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(e.preventDefault(),this.toggleFullscreen())};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*vt.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.innerHTML=this.player.playbackState==="playing"?Ge.PLAY:Ge.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){vt.icons.get(e)!==t&&(vt.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(e){this.quietControlsValue=e,this.stageElement.classList.toggle("quiet",e)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},vt.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const e=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!e),e!==this.wasPlaying&&e&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=e,vt.setIcon(this.playPauseButton,e?Ge.PAUSE:Ge.PLAY);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(),this.updateMuteButton()}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(),this.updateMuteButton()}toggleObserverMap(){const e=this.observerMapPanel.hidden;this.observerMapAsked=e,this.setObserverMapOpen(e),this.keepObserverMapClear()}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ha),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 e=!this.observerMapPanel.hidden;vt.setIcon(this.observerMapButton,e?Ge.MAP_ON:Ge.MAP_OFF);const t=e?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=uo.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.tracesShownState?this.currentSighting.traces.flatMap(n=>n.points):[],i=Jt.including(this.observerPath.boundsAround(vt.OBSERVER_MAP_MIN_SPAN_M,vt.OBSERVER_MAP_MARGIN),t);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(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.observerMapImageryLoading||!this.observerMapImageryNeededFor(e))return;const t=this.observerMapView.changed,i=t?Jt.expand(e,vt.OBSERVER_MAP_IMAGERY_AHEAD):e,n=vt.OBSERVER_MAP_IMAGERY_PX*(t?1+2*vt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=v1();try{const r=await s.getImageryTexture(i,{width:n,height:n});if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=s.attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(e){const t=this.observerMapImageryBounds;if(!t)return!0;const i=this.observerMapImagery?.bounds??t,n=this.observerMapView.changed?Jt.expand(e,vt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!s||!r}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=(c,h,d)=>{for(const u of t)if(!(u.x+u.width<c-d||u.x>h+d)&&!(u.y>e.bottom+d||u.y+u.height<e.top-d))return!0;return!1},n=[this.canvas.width-e.width,this.canvas.width],s=[0,e.width],r=vt.OBSERVER_MAP_CLEARANCE_PX,o=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",o&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!o&&(l||!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=et(this.currentSighting,e);t?.lat!==void 0&&t.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:t.lat,lng:t.lng},vt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?ud(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?ca(this.currentSighting.milestones):[]){const o=et(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?is.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Et.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(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.momentsBox.hidden=!e||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,ca(this.sighting.milestones).map(t=>t.t)),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,this.momentsButton.title=this.messages.moments,vt.setIcon(this.milestonesButton,this.milestonesShown?Ge.MILESTONES_ON:Ge.MILESTONES_OFF);const e=this.milestonesShown?this.messages.hideMilestones:this.messages.showMilestones;this.milestonesButton.title=e,this.milestonesButton.setAttribute("aria-label",e)}observerMapDecorAt(e){const t=et(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Dr(i,e),{lat:s,lng:r}=Dn(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=et(this.currentSighting,this.currentTime),s=is.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Dt.bodyAt(this.currentSighting,e,this.steadyObserver)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=vt.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(e){this.setVolume(e)}setVolume(e){this.volumeState=Math.min(Math.max(e,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.muted=!this.mutedState}updateMuteButton(){vt.setIcon(this.muteButton,this.mutedState?Ge.MUTED:Ge.VOLUME);const e=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=e,this.muteButton.setAttribute("aria-label",e),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;vt.setIcon(this.fullscreenButton,e?Ge.EXIT_FULLSCREEN:Ge.ENTER_FULLSCREEN),this.fullscreenButton.title=e?this.messages.exitFullscreen:this.messages.fullscreen,this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new Qn(qs.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=vh(qs.preferencesFor(this),uh);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await Ry(e);this.messagesLanguage===e&&this.applyMessages(t)}messagesLanguage;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,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(e){this.messages=e,this.updateTimeLabelTitles(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.renderIssues()}updateTimeLabels(){const e=this.currentSighting.event,t=_o(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?zu(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 jl(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?K0(q0(this.realStartMs+i)):jl(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?jl(this.currentSighting.timeline.duration):this.canShowClockTime?K0(q0(this.realStartMs+this.realDurationMs)):jl(this.realDurationMs)}}function q0(a){const e=new Date(a);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function K0(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 jl(a){const e=Math.round(a/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const qu="rr0-ufo";function $h(){customElements.get(qu)||customElements.define(qu,vt)}const MM="recordingissues";class ml{constructor(e,t){this.seekInput=e,this.layer=t,e.addEventListener("pointerdown",i=>{this.snapArmed=!0,this.nameMarkUnder(i)}),e.addEventListener("pointerup",()=>this.snapArmed=!1),e.addEventListener("pointermove",i=>this.nameMarkUnder(i)),e.addEventListener("pointerleave",()=>e.removeAttribute("title"))}static SNAP_PX=6;marks=[];duration=0;drawn="";snapArmed=!1;show(e,t){const i=t>0?[...e].sort((s,r)=>s.t-r.t):[],n=`${t}|${i.map(s=>`${s.kind}:${s.t}:${s.label}`).join("|")}`;n!==this.drawn&&(this.drawn=n,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(s=>{const r=document.createElement("span");return r.className=`timeline-mark ${s.kind}`,r.style.left=`${Math.min(Math.max(s.t/t,0),1)*100}%`,r})))}snap(e){return this.snapArmed?(this.snapArmed=!1,this.markNear(e)?.t??e):e}next(e){return this.marks.find(t=>t.t>e+ml.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ml.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ml.SNAP_PX/t*this.duration;let n;for(const s of this.marks)Math.abs(s.t-e)>i||(!n||Math.abs(s.t-e)<Math.abs(n.t-e)||s.t===n.t&&s.kind==="milestone")&&(n=s);return n}nameMarkUnder(e){const t=this.seekInput.getBoundingClientRect();if(t.width<=0||this.duration<=0)return;const i=this.marksNear((e.clientX-t.left)/t.width*this.duration);i?this.seekInput.title=i:this.seekInput.removeAttribute("title")}marksNear(e){const t=this.markNear(e);if(t)return[...new Set(this.marks.filter(i=>i.t===t.t).map(i=>i.label))].join(" · ")}}const wM=.08,Z0=.15,j0=2,xM=2e3;class SM{context;noiseBuffer;voices=new Map;paused=!0;requested=[];resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(e){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",e);return}}la.unlock(this.context),this.apply()}setPaused(e){e!==this.paused&&(this.paused=e,this.apply())}setVoices(e){this.requested=e,this.apply()}dispose(){for(const e of[...this.voices.keys()])this.release(e);this.context?.close(),this.context=void 0}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<xM),i=new Set(t.map(n=>n.id));for(const n of[...this.voices.keys()])i.has(n)||this.release(n);for(const n of t){const s=this.voices.get(n.id)??this.build(e,n.id);this.retarget(e,s,n)}}build(e,t){const i=e.createGain();i.gain.value=0;const n=e.createBiquadFilter();n.type="lowpass",n.connect(i).connect(e.destination);const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const o=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(o).connect(n);const c=()=>{const w=e.createBufferSource();return w.buffer=this.noise(e),w.loop=!0,w.loopStart=Math.random()*j0*.5,w},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const f=c(),p=e.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const v=e.createGain();f.connect(p).connect(v).connect(n);const m=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const x=e.createGain();m.connect(g).connect(x).connect(n);const y=[s,r,h,f,m];for(const w of y)w.start();const b={nodes:[i,n,o,l,d,u,p,v,g,x,...y],sources:y,firing:s,crank:r,knock:d,engineGain:o,knockGain:u,roadGain:v,windGain:x,cabin:n,output:i};return this.voices.set(t,b),b}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:o,distanceM:l}){const c=e.currentTime,h=(x,y)=>x.setTargetAtTime(y,c,wM),d=n.rpm/60,u=d*i.cylinders/2,f=Math.min(1,n.rpm/i.shiftUpRpm),p=Math.min(1.5,n.speedMps/30);h(t.firing.frequency,u),h(t.crank.frequency,d),h(t.knock.frequency,u*3),h(t.engineGain.gain,i.engineGain*(.25+.75*n.load)*(.5+.5*f)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*p**1.5*.8);const v=!r||o;h(t.windGain.gain,p**2*(v?.5:.06));const m=r?o?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const g=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,g*s)}release(e){const t=this.voices.get(e);if(!t)return;this.voices.delete(e);const i=this.context;i&&(t.output.gain.setTargetAtTime(0,i.currentTime,Z0/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},Z0*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*j0,e.sampleRate),i=t.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;return this.noiseBuffer=t,t}}class Il{static BY_KIND={car:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},generic:{cylinders:4,idleRpm:800,kmhPer1000Rpm:[8,14,21,29,37,45],shiftUpRpm:3e3,shiftDownRpm:1300,engineGain:.6,roadGain:.5,roughness:.15},van:{cylinders:4,idleRpm:750,kmhPer1000Rpm:[7,12,19,27,35,42],shiftUpRpm:2600,shiftDownRpm:1200,engineGain:.8,roadGain:.7,roughness:.45},truck:{cylinders:6,idleRpm:600,kmhPer1000Rpm:[5,8,12,17,23,30,38,48],shiftUpRpm:1900,shiftDownRpm:1e3,engineGain:1,roadGain:.9,roughness:.55},motorcycle:{cylinders:2,idleRpm:1100,kmhPer1000Rpm:[12,18,24,30,35,40],shiftUpRpm:6e3,shiftDownRpm:2500,engineGain:.9,roadGain:.3,roughness:.3}};static of(e){return Il.BY_KIND[e??"generic"]??Il.BY_KIND.generic}}class ta{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,n){const s=ta.SAMPLE_MS,r=[];for(let c=i;c<=n+s/2;c+=s){const h=t(c-s/2),d=t(c+s/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(s/1e3))}const o=[];let l=1;for(let c=0;c<r.length;c++){const h=r[c],d=(r[Math.min(c+1,r.length-1)]-r[Math.max(c-1,0)])/(2*s/1e3);if(h<ta.STANDING_MPS){l=1,o.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,f=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&f(l)>e.shiftUpRpm;)l++;for(;l>1&&f(l)<e.shiftDownRpm;)l--;const p=Math.max(f(l),e.idleRpm*(1+.3*Math.min(1,h/3))),v=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,v+d/2.5):d<-.3?.05:v;o.push({speedMps:h,rpm:p,load:m,gear:l})}return new ta(o,i)}at(e){const t=(e-this.startMs)/ta.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),n=this.samples[i],s=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:n.speedMps+(s.speedMps-n.speedMps)*r,rpm:n.rpm+(s.rpm-n.rpm)*r,load:n.load+(s.load-n.load)*r,gear:r<.5?n.gear:s.gear}}}class bh{drives=new Map;at(e,t){const i=[],n=e.event.place?.[0],s=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??n?.lat,u=h?.lng??n?.lng;if(d===void 0||u===void 0||!n)return;const f=ni(d,u,n.lat,n.lng);return{eastM:f.x,northM:-f.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),o=e.vehicle;if(o){const c=Il.of(o.kind),h=this.drive(`observer:${o.kind}`,bh.trackKey(e),()=>ta.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:o.noise??1,inside:!0,windowsOpen:o.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Il.of(c.engine.kind),d=v=>{const m=Dr(c,v);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,bh.decorKey(c,r),()=>ta.of(h,d,0,r));if(!u)continue;const f=Dr(c,t),p=Math.hypot(f.eastM-l.eastM,f.northM-l.northM,f.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:p})}return i}drive(e,t,i){const n=this.drives.get(e);if(n&&n.key===t)return n.drive;const s=i();return this.drives.set(e,{key:t,drive:s}),s}static trackKey(e){return e.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(e,t){return`${t}|${e.eastM},${e.northM}|`+(e.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const EM=`
|
|
2682
2682
|
<div class="stage" id="stage">
|
|
2683
2683
|
<div class="frame" id="frame">
|
|
2684
2684
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -8799,7 +8799,7 @@ void main()
|
|
|
8799
8799
|
if (ice <= 0.0) discard;
|
|
8800
8800
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
8801
8801
|
}
|
|
8802
|
-
`,transparent:!0,blending:Pi,depthWrite:!1,side:Qt,fog:!1}),this.object=new Te(new bi(Hi.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)<Hi.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Hi.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)<Hi.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Hi.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)<Hi.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Hi.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?Hi.URGENT_BUDGET_MS:Hi.BUDGET_MS;do this.sky.trace(Hi.RAYS_PER_BATCH);while(this.sky.tracedRays<Hi.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Hi.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]=ss.toHalfFloat(t[n]),this.texels[i+1]=ss.toHalfFloat(t[n+1]),this.texels[i+2]=ss.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 Ii{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Ii.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Ii.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=Ii.MAX_CONCURRENT*Ii.SEGMENTS*Ii.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new rt;t.setAttribute("position",new Ze(this.positions,3)),t.setAttribute("color",new Ze(this.colors,3)),t.setDrawRange(0,0),this.object=new Te(t,new Rn({vertexColors:!0,transparent:!0,blending:Pi,depthWrite:!1,fog:!1,side:nn})),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=ua.aliveAt(this.meteors,e).slice(0,Ii.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const l=ti(o.altitudeDeg,o.azimuthDeg,1),[c,h]=this.basisAround(l),d=s.fromRadiantDeg+r*s.lengthDeg,u=Math.max(s.fromRadiantDeg,d-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(c,h,s.bearingDeg),v=(.15+.85*s.brightness)*f,m=y=>v*y**1.6,g=y=>this.onSphere(l,p,u+(d-u)*y),x=y=>Ii.RADIUS*((Ii.MIN_HALF_WIDTH_DEG+Ii.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<Ii.POINTS;y++){const b=(y-1)/Ii.SEGMENTS,w=y/Ii.SEGMENTS;n=this.pushRibbon(n,g(b),g(w),x(b),x(w),m(b),m(w))}}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=ti(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),l=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/l)*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 l=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Ii.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,l,n,h),f=this.across(i,l,s,h),p=this.across(t,l,n,d),v=this.across(i,l,s,d),m=(g,x)=>g===0?x:0;e=this.push(e,u,m(h,r)),e=this.push(e,f,m(h,o)),e=this.push(e,p,m(d,r)),e=this.push(e,f,m(h,o)),e=this.push(e,v,m(d,o)),e=this.push(e,p,m(d,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)*Ii.RADIUS,y:(e.y*s+t.y*r)*Ii.RADIUS,z:(e.z*s+t.z*r)*Ii.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 Ht{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??Ht.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Ht.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Ht.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Ht.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(Ht.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const l of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&n.push(Ht.box(e+1,c,Ht.ABUTMENT_THICKNESS_M,0,c/2,l*(i-Ht.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Ht.box(e,.04,this.span,0,t+.02,0));const r=[];for(const l of[-1,1])this.bank<=0||(r.push(this.embankment(l)),s.push(this.bankRoad(l)));const o=[];for(const l of[-1,1])o.push(...this.railing(l*(e/2-Ht.POST_SIDE_M)));return{concrete:Ht.merge(n),road:Ht.merge(s),earth:Ht.merge(r),railing:Ht.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(c,h,d,u)=>{n.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Ht.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,f=(p,v,m,g)=>u?s(p,v,m,g):s(g,m,v,p);f(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),f(h.leftTop,h.rightTop,d.rightTop,d.leftTop),f(h.rightTop,h.rightFoot,d.rightFoot,d.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 l=new rt;return l.setAttribute("position",new pt(n,3)),l.computeVertexNormals(),l}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],l=i[r],c=this.roadAt(o)+.02,h=this.roadAt(l)+.02,d=e>0?[[-t,c,o],[t,c,o],[t,h,l],[-t,h,l]]:[[-t,h,l],[t,h,l],[t,c,o],[-t,c,o]];for(const u of[0,2,1,0,3,2])n.push(...d[u])}const s=new rt;return s.setAttribute("position",new pt(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=Ht.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Ht.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=Ht.POST_SIDE_M;for(const o of n)s.push(Ht.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const l=this.railHeight*o/this.rails-Ht.RAIL_HEIGHT_M/2;for(let c=1;c<n.length;c++){const h=new D(e,this.roadAt(n[c-1])+l,n[c-1]),d=new D(e,this.roadAt(n[c])+l,n[c]);s.push(Ht.beam(h,d))}}return s}static box(e,t,i,n,s,r){return new rn(e,t,i).translate(n,s,r)}static beam(e,t){const i=new D().subVectors(t,e),n=new rn(Ht.RAIL_DEPTH_M,Ht.RAIL_HEIGHT_M,i.length()),s=new qi().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new je().compose(r,s,new D(1,1,1)))}static merge(e){const t=e.map(l=>l.getIndex()?l.toNonIndexed():l),i=t.reduce((l,c)=>l+c.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const l of t){const c=l.getAttribute("position"),h=l.getAttribute("normal");n.set(c.array,r*3),h&&s.set(h.array,r*3),r+=c.count}const o=new rt;o.setAttribute("position",new pt(n,3)),o.setAttribute("normal",new pt(s,3));for(const l of e)l.dispose();for(const l of t)l.dispose();return o}}const au=Math.PI/180;function Wt(a,e,t,i,n=!1){const s=n?new Rn({color:new se(...t)}):new va({color:new se(...t)}),r=new Te(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const ou=.25,_A=.002,AA=100,TA=1500,IA=.25,DA=1e3,RA=.15;function CA(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 PA=[.32,.32,.3],Cb=[1,.85,.5],LA=[.25,.25,.25],Pb=[1,.97,.85],kA=[.55,.68,.72],ws=.03,xs=.05,Lb={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 Qi(a,e){return a?.[e]}function Ss(a,e,t,i,n,s,r,o){if(o===void 0)return;const l=new va({color:new se(...kA),transparent:!0,opacity:o/100}),c=new Te(new rn(e,t,i),l);c.position.set(n,s,r),a.add(c)}const Nn=.05,lu=[.6,.58,.53],Fg=[.5,.5,.48];function oo(a,e,t,i,n,s,r,o){const l=new va({color:new se(...o),side:Qt}),c=new Te(new rn(e,t,i),l);c.position.set(n,s,r),a.add(c)}function OA(a,e,t,i,n,s,r,o,l){const c=(i-s)/2,h=(p,v,m,g)=>{p<=0||(e?oo(a,p,v,Nn,m,o+g,r,l):oo(a,Nn,v,p,r,o+g,m,l))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...n].sort((p,v)=>p.center-v.center);let u=-t/2;for(const p of d){const m=p.center-p.main/2-u;h(m,s,u+m/2,0),u=p.center+p.main/2}const f=t/2-u;h(f,s,u+f/2,0)}function kb(a,e,t,i,n,s,r,o,l,c){const h=(i+n)/2,d=n-i,u=(f,p,v,m)=>{f.length===0?p?oo(a,v,d,Nn,0,h,m,lu):oo(a,Nn,d,v,m,h,0,lu):OA(a,p,v,d,f,s,m,h,lu)};u(r,!0,e*2,-t+Nn),u(o,!0,e*2,t-Nn),u(l,!1,t*2,-e+Nn),u(c,!1,t*2,e-Nn),oo(a,e*2,Nn,t*2,0,i+Nn,0,Fg),oo(a,e*2,Nn,t*2,0,n-Nn,0,Fg)}function fp(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:-Es};case"front-right":return{x:e-i,z:-Es};case"behind-left":return{x:-(e-i),z:Es};case"behind-right":return{x:e-i,z:Es}}}function Ob(a,e,t,i,n,s,r){const o=gp();o.scale.setScalar(i),o.rotation.y=Lb[e];const{x:l,z:c}=fp(e,n,s,r);o.position.set(l,t,c),a.add(o)}const pp=6,mp=6,Mr=3,Qo=1.4,el=Mr*.5,Nb=1.2,Fb=.35,NA=.75,FA=1.6;function Ug(a,e,t,i){const n=new Nt,s=Math.max(1,a+1),r=s*Mr;Wt(n,new rn(pp,r,mp),[.55,.54,.5],r/2);const o=pp/2,l=mp/2;for(let c=0;c<s;c++){const h=c*Mr+Mr/2;Ss(n,Qo,el,xs,0,h,-l-ws,Qi(e,"front")),Ss(n,Qo,el,xs,0,h,l+ws,Qi(e,"behind")),Ss(n,xs,el,Qo,-o-ws,h,0,Qi(e,"left")),Ss(n,xs,el,Qo,o+ws,h,0,Qi(e,"right"))}if(t){const c=Math.min(Math.max(i??0,0),s-1);Ob(n,t,c*Mr,.72,o,l,Nb);const h=d=>Qi(e,d)!==void 0?[{main:Qo,center:0}]:[];kb(n,o,l,c*Mr,(c+1)*Mr,el,h("front"),h("behind"),h("left"),h("right"))}return n}function Bg(){const a=new Nt,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 bi(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Wt(a,r,[.26,.28,.17],s)}return a}function UA(a){const e=new Nt,t=new Ht(gi.sizeOf(a),a.bridge).build();Wt(e,t.concrete,[.6,.6,.58],0);const i=Wt(e,t.road,[.2,.2,.21],0),n=Wt(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=nn;return Wt(e,t.railing,[.5,.52,.55],0),e}function zg(){const a=new Nt;return Wt(a,new Ls(.15,.22,2,8),[.32,.22,.14],1),Wt(a,new Lo(1.4,3,8),[.16,.32,.14],3.5),a}const Hg=.275,BA=.35,zA=.9,HA=34,GA=8,VA=1.4;function Gg(){const a=new Nt,e=new bi(Hg,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,BA/Hg,1);const t=gi.repeatOnGrid(e,HA,zA,GA,VA),i=Wt(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 Vg(){const a=new Nt,e=new bi(1,7,3,0,Math.PI*2,0,Math.PI/2);return Wt(a,e,[.38,.36,.32],0),a}function Wg(a){const e=new Nt;return Wt(e,new Ls(.05,.08,5,8),[.28,.28,.3],2.5),Wt(e,new bi(.25,12,8),a?Cb:PA,5.1,!0),e}const WA=[.08,.08,.08],mr=.8,Ja=1,ps=1.7,cu=.6,Hr=.4,Fc=1.2,Ya=.7,Es=.5,XA=ps;function Xg(a,e,t){const i=new Nt;Wt(i,new rn(1.8,1.4,4.2),[.45,.14,.14],.7),Wt(i,new rn(mr*2,cu,Ja*2),[.4,.12,.12],ps);for(const s of[-1.4,1.4])for(const r of[-.95,.95]){const o=Wt(i,new Ls(.4,.4,.3,12),WA,.4);o.rotation.z=Math.PI/2,o.position.x=r,o.position.z=s}const n=a?Pb:LA;for(const s of[-.7,.7])Wt(i,new bi(.15,8,6),n,.7,!0).position.set(s,.7,-2.1);if(Ss(i,Fc,Hr,xs,0,ps,-Ja-ws,Qi(e,"front")),Ss(i,Fc,Hr,xs,0,ps,Ja+ws,Qi(e,"behind")),Ss(i,xs,Hr,Ya,-mr-ws,ps,-Es,Qi(e,"front-left")),Ss(i,xs,Hr,Ya,-mr-ws,ps,Es,Qi(e,"behind-left")),Ss(i,xs,Hr,Ya,mr+ws,ps,-Es,Qi(e,"front-right")),Ss(i,xs,Hr,Ya,mr+ws,ps,Es,Qi(e,"behind-right")),t){Ob(i,t,NA,.5,mr,Ja,Fb);const s=(l,c)=>{const h=[];return Qi(e,l)!==void 0&&h.push({main:Ya,center:-Es}),Qi(e,c)!==void 0&&h.push({main:Ya,center:Es}),h},r=Qi(e,"front")!==void 0?[{main:Fc,center:0}]:[],o=Qi(e,"behind")!==void 0?[{main:Fc,center:0}]:[];kb(i,mr,Ja,ps-cu/2,ps+cu/2,Hr,r,o,s("front-left","behind-left"),s("front-right","behind-right"))}return i}const $g=new Map;function Yg(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 hu(a,e){return e>1e-6?a/e:1}const Ub=[.95,.9,.82],qg=[.72,.74,.78];function Kg(){const a=new Nt;Wt(a,new Ls(.25,.3,1.5,10),qg,.75),Wt(a,new bi(.26,10,8),qg,1.74);const e=Wt(a,new Lo(.07,.16,8),Ub,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function gp(){const a=new Nt;Wt(a,new Ls(.25,.3,1.5,10),[.3,.3,.35],.75),Wt(a,new bi(.22,10,8),[.62,.52,.46],1.72);const e=Wt(a,new Lo(.07,.16,8),Ub,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const $A=17,Zg=18.5,du=[.16,.16,.18];function jg(){const a=new Nt,e=Wt(a,new Ls(1.8,1.8,Zg*2,10),du,0);e.rotation.x=Math.PI/2,Wt(a,new rn($A*2,.5,4.5),du,0);const t=Wt(a,new rn(.4,5.5,4),du,3);return t.position.z=-Zg+2,a}class gi{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=gi.sizeOf(e);if(r>o.heightM)return s(t,i);const l=(n??0)*Math.PI/180,c=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)),d=gi.GROWS_FROM_GROUND.has(e.kind);let u=d?1/0:-1/0;for(let f=0;f<c;f++){const p=(f/(c-1)-.5)*o.lengthM;for(let v=0;v<h;v++){const m=(v/(h-1)-.5)*o.widthM,g=t+Math.sin(l)*p+Math.cos(l)*m,x=i-Math.cos(l)*p+Math.sin(l)*m;u=d?Math.min(u,s(g,x)):Math.max(u,s(g,x))}}return Number.isFinite(u)?u: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"?fp(t,mr,Ja,Fb):fp(t,pp/2,mp/2,Nb),s=e.kind==="vehicle"?XA:(e.occupiedFloor??0)*Mr+FA,r=(e.headingDeg??0)-Lb[t]/au,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(gi.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),l=e.getIndex();if(!l)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*n,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),f=new Uint32Array(l.count*h),p=-((t-1)*i)/2,v=-((n-1)*s)/2;let m=0;for(let x=0;x<n;x++)for(let y=0;y<t;y++,m++){const b=v+x*s,w=p+y*i;for(let E=0;E<c;E++){const T=(m*c+E)*3;d[T]=r.getX(E)+b,d[T+1]=r.getY(E),d[T+2]=r.getZ(E)+w,u[T]=o.getX(E),u[T+1]=o.getY(E),u[T+2]=o.getZ(E)}for(let E=0;E<l.count;E++)f[m*l.count+E]=l.getX(E)+m*c}const g=new rt;return g.setAttribute("position",new pt(d,3)),g.setAttribute("normal",new pt(u,3)),g.setIndex(new Gp(f,1)),g}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const l=s.geometry.getAttribute("position"),c=new je().copy(s.matrixWorld).invert();for(let h=0;h<l.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(c);for(let d=h;d<h+o;d++)l.setY(d,r[d*3+1]+i.y)}l.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"?Ug(e.floors??ho,e.windows,e.observerSide,e.occupiedFloor):e.kind==="tree"?zg():e.kind==="shrub"?Bg():e.kind==="bridge"?UA(e):e.kind==="crop"?Gg():e.kind==="mound"?Vg():e.kind==="streetlight"?Wg(t):e.kind==="vehicle"?Xg(t,e.windows,e.observerSide):e.kind==="aircraft"?jg():e.kind==="entity"?Kg():gp();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Nt;return i.name=gi.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*au),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:hu(t.widthM,i.widthM),t.heightM===void 0?1:hu(t.heightM,i.heightM),t.lengthM===void 0?1:hu(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??ho)+1):0;if(e==="bridge")return Ht.NATURAL_SIZE;const n=`${e}:${i}`,s=$g.get(n);if(s)return s;const r=e==="building"?Ug(i-1,void 0,void 0,void 0):e==="tree"?zg():e==="shrub"?Bg():e==="crop"?Gg():e==="mound"?Vg():e==="streetlight"?Wg(!1):e==="vehicle"?Xg(!1,void 0,void 0):e==="aircraft"?jg():e==="entity"?Kg():gp(),o=new sn().setFromObject(r),l={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),$g.set(n,l),l}static usesModel(e){return e.model!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Nt;r.name=gi.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*au,i.updateMatrixWorld(!0);const o=new sn().setFromObject(i),l={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},c=Yg(t.sizeM,l)??Yg(n.depictedSizeM,l)??1;i.scale.multiplyScalar(c);const h=o.getCenter(new D).multiplyScalar(c);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*c,i.traverse(d=>{d instanceof Te&&(d.castShadow=!0,d.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=CA(i.color),s=Wt(e,new bi(ou,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;const r=s.material;r.blending=Pi,r.transparent=!0,r.depthWrite=!1,r.fog=!1}}static setLights(e,t,i,n,s=0,r=1,o=_A,l=[1,1,1]){if(!t||t.length===0)return;const c=new Map(t.map(f=>[f.id,f])),h=Math.max(1,n*o/ou),d=ou*h,u=r/(Math.PI*d*d);for(const f of e.children){if(!(f instanceof Te))continue;const p=f.userData.lightId;if(!p)continue;const v=c.get(p);if(!v)continue;const m=s>0?s1(v,i,i+s):Xy(v,i)?1:0;f.visible=m>0;const g=f.material,x=f.userData.lightColor;if(x){const y=m*AA*(v.intensity??1)*u;g.color.setRGB(x[0]*y*l[0],x[1]*y*l[1],x[2]*y*l[2])}f.scale.setScalar(h)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[TA,IA,Cb]:[DA,RA,Pb],l=i?s*n/(Math.PI*r*r):0,c=[o[0]*l,o[1]*l,o[2]*l];e.traverse(h=>{const d=h.userData;!(h instanceof Te)||!d.emissive||d.lightId||h.material.color.setRGB(...c)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Te))return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const uu="https://ufoathome.org/models/index.json";class YA{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??qA()}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 qA(){const a=`?v=${encodeURIComponent("0.85.1")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==uu?[e,uu]:[uu]).map(t=>t+a)}const oh=[{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 YA}];async function Jg(a){const{GLTFLoader:e}=await ot(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-CeRN5jhy.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 Bb=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class _n{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Te(new an(2,2),new mt({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:_n.VERTEX,fragmentShader:_n.FRAGMENT,transparent:!0,depthWrite:!1,blending:Pi,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*_n.MIN_ANGLE_RAD),r=_n.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(_n.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(_n.MAX_SHARE*_n.FILL*Math.PI))}static VERTEX=`
|
|
8802
|
+
`,transparent:!0,blending:Pi,depthWrite:!1,side:Qt,fog:!1}),this.object=new Te(new bi(Hi.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)<Hi.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<Hi.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)<Hi.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<Hi.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)<Hi.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<Hi.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?Hi.URGENT_BUDGET_MS:Hi.BUDGET_MS;do this.sky.trace(Hi.RAYS_PER_BATCH);while(this.sky.tracedRays<Hi.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=Hi.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]=ss.toHalfFloat(t[n]),this.texels[i+1]=ss.toHalfFloat(t[n+1]),this.texels[i+2]=ss.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 Ii{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Ii.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Ii.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=Ii.MAX_CONCURRENT*Ii.SEGMENTS*Ii.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new rt;t.setAttribute("position",new Ze(this.positions,3)),t.setAttribute("color",new Ze(this.colors,3)),t.setDrawRange(0,0),this.object=new Te(t,new Rn({vertexColors:!0,transparent:!0,blending:Pi,depthWrite:!1,fog:!1,side:nn})),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=ua.aliveAt(this.meteors,e).slice(0,Ii.MAX_CONCURRENT);let n=0;for(const{meteor:s,progress:r}of i){const o=this.radiantOf(s);if(!o)continue;const l=ti(o.altitudeDeg,o.azimuthDeg,1),[c,h]=this.basisAround(l),d=s.fromRadiantDeg+r*s.lengthDeg,u=Math.max(s.fromRadiantDeg,d-s.lengthDeg*.6),f=Math.min(1,(1-r)*2.5),p=this.turn(c,h,s.bearingDeg),v=(.15+.85*s.brightness)*f,m=y=>v*y**1.6,g=y=>this.onSphere(l,p,u+(d-u)*y),x=y=>Ii.RADIUS*((Ii.MIN_HALF_WIDTH_DEG+Ii.BRIGHT_HALF_WIDTH_DEG*s.brightness*y)*Math.PI/180);for(let y=1;y<Ii.POINTS;y++){const b=(y-1)/Ii.SEGMENTS,w=y/Ii.SEGMENTS;n=this.pushRibbon(n,g(b),g(w),x(b),x(w),m(b),m(w))}}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=ti(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),l=Math.hypot(o.x,o.y,o.z)||1;return{altitudeDeg:Math.asin(o.y/l)*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 l=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Ii.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,l,n,h),f=this.across(i,l,s,h),p=this.across(t,l,n,d),v=this.across(i,l,s,d),m=(g,x)=>g===0?x:0;e=this.push(e,u,m(h,r)),e=this.push(e,f,m(h,o)),e=this.push(e,p,m(d,r)),e=this.push(e,f,m(h,o)),e=this.push(e,v,m(d,o)),e=this.push(e,p,m(d,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)*Ii.RADIUS,y:(e.y*s+t.y*r)*Ii.RADIUS,z:(e.z*s+t.z*r)*Ii.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 Ht{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??Ht.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Ht.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Ht.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Ht.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(Ht.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const l of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&n.push(Ht.box(e+1,c,Ht.ABUTMENT_THICKNESS_M,0,c/2,l*(i-Ht.ABUTMENT_THICKNESS_M/2)))}}const s=[];this.span>0&&s.push(Ht.box(e,.04,this.span,0,t+.02,0));const r=[];for(const l of[-1,1])this.bank<=0||(r.push(this.embankment(l)),s.push(this.bankRoad(l)));const o=[];for(const l of[-1,1])o.push(...this.railing(l*(e/2-Ht.POST_SIDE_M)));return{concrete:Ht.merge(n),road:Ht.merge(s),earth:Ht.merge(r),railing:Ht.merge(o)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),n=[],s=(c,h,d,u)=>{n.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Ht.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,f=(p,v,m,g)=>u?s(p,v,m,g):s(g,m,v,p);f(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),f(h.leftTop,h.rightTop,d.rightTop,d.leftTop),f(h.rightTop,h.rightFoot,d.rightFoot,d.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 l=new rt;return l.setAttribute("position",new pt(n,3)),l.computeVertexNormals(),l}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],l=i[r],c=this.roadAt(o)+.02,h=this.roadAt(l)+.02,d=e>0?[[-t,c,o],[t,c,o],[t,h,l],[-t,h,l]]:[[-t,h,l],[t,h,l],[t,c,o],[-t,c,o]];for(const u of[0,2,1,0,3,2])n.push(...d[u])}const s=new rt;return s.setAttribute("position",new pt(n,3)),s.computeVertexNormals(),s}stations(e){const t=[];for(let i=0;i<=Ht.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Ht.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=Ht.POST_SIDE_M;for(const o of n)s.push(Ht.box(r,this.railHeight,r,e,this.roadAt(o)+this.railHeight/2,o));for(let o=1;o<=this.rails;o++){const l=this.railHeight*o/this.rails-Ht.RAIL_HEIGHT_M/2;for(let c=1;c<n.length;c++){const h=new D(e,this.roadAt(n[c-1])+l,n[c-1]),d=new D(e,this.roadAt(n[c])+l,n[c]);s.push(Ht.beam(h,d))}}return s}static box(e,t,i,n,s,r){return new rn(e,t,i).translate(n,s,r)}static beam(e,t){const i=new D().subVectors(t,e),n=new rn(Ht.RAIL_DEPTH_M,Ht.RAIL_HEIGHT_M,i.length()),s=new qi().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return n.applyMatrix4(new je().compose(r,s,new D(1,1,1)))}static merge(e){const t=e.map(l=>l.getIndex()?l.toNonIndexed():l),i=t.reduce((l,c)=>l+c.getAttribute("position").count,0),n=new Float32Array(i*3),s=new Float32Array(i*3);let r=0;for(const l of t){const c=l.getAttribute("position"),h=l.getAttribute("normal");n.set(c.array,r*3),h&&s.set(h.array,r*3),r+=c.count}const o=new rt;o.setAttribute("position",new pt(n,3)),o.setAttribute("normal",new pt(s,3));for(const l of e)l.dispose();for(const l of t)l.dispose();return o}}const au=Math.PI/180;function Wt(a,e,t,i,n=!1){const s=n?new Rn({color:new se(...t)}):new va({color:new se(...t)}),r=new Te(e,s);return r.position.y=i,r.userData={emissive:n},r.castShadow=!n,r.receiveShadow=!n,a.add(r),r}const ou=.25,_A=.002,AA=100,TA=1500,IA=.25,DA=1e3,RA=.15;function CA(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 PA=[.32,.32,.3],Cb=[1,.85,.5],LA=[.25,.25,.25],Pb=[1,.97,.85],kA=[.55,.68,.72],ws=.03,xs=.05,Lb={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 Qi(a,e){return a?.[e]}function Ss(a,e,t,i,n,s,r,o){if(o===void 0)return;const l=new va({color:new se(...kA),transparent:!0,opacity:o/100}),c=new Te(new rn(e,t,i),l);c.position.set(n,s,r),a.add(c)}const Nn=.05,lu=[.6,.58,.53],Fg=[.5,.5,.48];function oo(a,e,t,i,n,s,r,o){const l=new va({color:new se(...o),side:Qt}),c=new Te(new rn(e,t,i),l);c.position.set(n,s,r),a.add(c)}function OA(a,e,t,i,n,s,r,o,l){const c=(i-s)/2,h=(p,v,m,g)=>{p<=0||(e?oo(a,p,v,Nn,m,o+g,r,l):oo(a,Nn,v,p,r,o+g,m,l))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...n].sort((p,v)=>p.center-v.center);let u=-t/2;for(const p of d){const m=p.center-p.main/2-u;h(m,s,u+m/2,0),u=p.center+p.main/2}const f=t/2-u;h(f,s,u+f/2,0)}function kb(a,e,t,i,n,s,r,o,l,c){const h=(i+n)/2,d=n-i,u=(f,p,v,m)=>{f.length===0?p?oo(a,v,d,Nn,0,h,m,lu):oo(a,Nn,d,v,m,h,0,lu):OA(a,p,v,d,f,s,m,h,lu)};u(r,!0,e*2,-t+Nn),u(o,!0,e*2,t-Nn),u(l,!1,t*2,-e+Nn),u(c,!1,t*2,e-Nn),oo(a,e*2,Nn,t*2,0,i+Nn,0,Fg),oo(a,e*2,Nn,t*2,0,n-Nn,0,Fg)}function fp(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:-Es};case"front-right":return{x:e-i,z:-Es};case"behind-left":return{x:-(e-i),z:Es};case"behind-right":return{x:e-i,z:Es}}}function Ob(a,e,t,i,n,s,r){const o=gp();o.scale.setScalar(i),o.rotation.y=Lb[e];const{x:l,z:c}=fp(e,n,s,r);o.position.set(l,t,c),a.add(o)}const pp=6,mp=6,Mr=3,Qo=1.4,el=Mr*.5,Nb=1.2,Fb=.35,NA=.75,FA=1.6;function Ug(a,e,t,i){const n=new Nt,s=Math.max(1,a+1),r=s*Mr;Wt(n,new rn(pp,r,mp),[.55,.54,.5],r/2);const o=pp/2,l=mp/2;for(let c=0;c<s;c++){const h=c*Mr+Mr/2;Ss(n,Qo,el,xs,0,h,-l-ws,Qi(e,"front")),Ss(n,Qo,el,xs,0,h,l+ws,Qi(e,"behind")),Ss(n,xs,el,Qo,-o-ws,h,0,Qi(e,"left")),Ss(n,xs,el,Qo,o+ws,h,0,Qi(e,"right"))}if(t){const c=Math.min(Math.max(i??0,0),s-1);Ob(n,t,c*Mr,.72,o,l,Nb);const h=d=>Qi(e,d)!==void 0?[{main:Qo,center:0}]:[];kb(n,o,l,c*Mr,(c+1)*Mr,el,h("front"),h("behind"),h("left"),h("right"))}return n}function Bg(){const a=new Nt,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 bi(n,10,7);r.scale(1,.85,1),r.translate(t,0,i),Wt(a,r,[.26,.28,.17],s)}return a}function UA(a){const e=new Nt,t=new Ht(gi.sizeOf(a),a.bridge).build();Wt(e,t.concrete,[.6,.6,.58],0);const i=Wt(e,t.road,[.2,.2,.21],0),n=Wt(e,t.earth,[.3,.36,.22],0);for(const s of[i,n])s.material.side=nn;return Wt(e,t.railing,[.5,.52,.55],0),e}function zg(){const a=new Nt;return Wt(a,new Ls(.15,.22,2,8),[.32,.22,.14],1),Wt(a,new Lo(1.4,3,8),[.16,.32,.14],3.5),a}const Hg=.275,BA=.35,zA=.9,HA=34,GA=8,VA=1.4;function Gg(){const a=new Nt,e=new bi(Hg,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,BA/Hg,1);const t=gi.repeatOnGrid(e,HA,zA,GA,VA),i=Wt(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 Vg(){const a=new Nt,e=new bi(1,7,3,0,Math.PI*2,0,Math.PI/2);return Wt(a,e,[.38,.36,.32],0),a}function Wg(a){const e=new Nt;return Wt(e,new Ls(.05,.08,5,8),[.28,.28,.3],2.5),Wt(e,new bi(.25,12,8),a?Cb:PA,5.1,!0),e}const WA=[.08,.08,.08],mr=.8,Ja=1,ps=1.7,cu=.6,Hr=.4,Fc=1.2,Ya=.7,Es=.5,XA=ps;function Xg(a,e,t){const i=new Nt;Wt(i,new rn(1.8,1.4,4.2),[.45,.14,.14],.7),Wt(i,new rn(mr*2,cu,Ja*2),[.4,.12,.12],ps);for(const s of[-1.4,1.4])for(const r of[-.95,.95]){const o=Wt(i,new Ls(.4,.4,.3,12),WA,.4);o.rotation.z=Math.PI/2,o.position.x=r,o.position.z=s}const n=a?Pb:LA;for(const s of[-.7,.7])Wt(i,new bi(.15,8,6),n,.7,!0).position.set(s,.7,-2.1);if(Ss(i,Fc,Hr,xs,0,ps,-Ja-ws,Qi(e,"front")),Ss(i,Fc,Hr,xs,0,ps,Ja+ws,Qi(e,"behind")),Ss(i,xs,Hr,Ya,-mr-ws,ps,-Es,Qi(e,"front-left")),Ss(i,xs,Hr,Ya,-mr-ws,ps,Es,Qi(e,"behind-left")),Ss(i,xs,Hr,Ya,mr+ws,ps,-Es,Qi(e,"front-right")),Ss(i,xs,Hr,Ya,mr+ws,ps,Es,Qi(e,"behind-right")),t){Ob(i,t,NA,.5,mr,Ja,Fb);const s=(l,c)=>{const h=[];return Qi(e,l)!==void 0&&h.push({main:Ya,center:-Es}),Qi(e,c)!==void 0&&h.push({main:Ya,center:Es}),h},r=Qi(e,"front")!==void 0?[{main:Fc,center:0}]:[],o=Qi(e,"behind")!==void 0?[{main:Fc,center:0}]:[];kb(i,mr,Ja,ps-cu/2,ps+cu/2,Hr,r,o,s("front-left","behind-left"),s("front-right","behind-right"))}return i}const $g=new Map;function Yg(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 hu(a,e){return e>1e-6?a/e:1}const Ub=[.95,.9,.82],qg=[.72,.74,.78];function Kg(){const a=new Nt;Wt(a,new Ls(.25,.3,1.5,10),qg,.75),Wt(a,new bi(.26,10,8),qg,1.74);const e=Wt(a,new Lo(.07,.16,8),Ub,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,a}function gp(){const a=new Nt;Wt(a,new Ls(.25,.3,1.5,10),[.3,.3,.35],.75),Wt(a,new bi(.22,10,8),[.62,.52,.46],1.72);const e=Wt(a,new Lo(.07,.16,8),Ub,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,a}const $A=17,Zg=18.5,du=[.16,.16,.18];function jg(){const a=new Nt,e=Wt(a,new Ls(1.8,1.8,Zg*2,10),du,0);e.rotation.x=Math.PI/2,Wt(a,new rn($A*2,.5,4.5),du,0);const t=Wt(a,new rn(.4,5.5,4),du,3);return t.position.z=-Zg+2,a}class gi{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound"]);static groundUnderFootprint(e,t,i,n,s,r=0){const o=gi.sizeOf(e);if(r>o.heightM)return s(t,i);const l=(n??0)*Math.PI/180,c=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)),d=gi.GROWS_FROM_GROUND.has(e.kind);let u=d?1/0:-1/0;for(let f=0;f<c;f++){const p=(f/(c-1)-.5)*o.lengthM;for(let v=0;v<h;v++){const m=(v/(h-1)-.5)*o.widthM,g=t+Math.sin(l)*p+Math.cos(l)*m,x=i-Math.cos(l)*p+Math.sin(l)*m;u=d?Math.min(u,s(g,x)):Math.max(u,s(g,x))}}return Number.isFinite(u)?u: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"?fp(t,mr,Ja,Fb):fp(t,pp/2,mp/2,Nb),s=e.kind==="vehicle"?XA:(e.occupiedFloor??0)*Mr+FA,r=(e.headingDeg??0)-Lb[t]/au,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(gi.BODY_NAME)??e}static repeatOnGrid(e,t,i,n,s){const r=e.getAttribute("position"),o=e.getAttribute("normal"),l=e.getIndex();if(!l)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*n,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),f=new Uint32Array(l.count*h),p=-((t-1)*i)/2,v=-((n-1)*s)/2;let m=0;for(let x=0;x<n;x++)for(let y=0;y<t;y++,m++){const b=v+x*s,w=p+y*i;for(let E=0;E<c;E++){const T=(m*c+E)*3;d[T]=r.getX(E)+b,d[T+1]=r.getY(E),d[T+2]=r.getZ(E)+w,u[T]=o.getX(E),u[T+1]=o.getY(E),u[T+2]=o.getZ(E)}for(let E=0;E<l.count;E++)f[m*l.count+E]=l.getX(E)+m*c}const g=new rt;return g.setAttribute("position",new pt(d,3)),g.setAttribute("normal",new pt(u,3)),g.setIndex(new Gp(f,1)),g}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(n=>{const s=n,r=s.userData.cropBasePositions,o=s.userData.cropVerticesPerClump;if(!s.isMesh||!r||!o)return;const l=s.geometry.getAttribute("position"),c=new je().copy(s.matrixWorld).invert();for(let h=0;h<l.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(c);for(let d=h;d<h+o;d++)l.setY(d,r[d*3+1]+i.y)}l.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"?Ug(e.floors??ho,e.windows,e.observerSide,e.occupiedFloor):e.kind==="tree"?zg():e.kind==="shrub"?Bg():e.kind==="bridge"?UA(e):e.kind==="crop"?Gg():e.kind==="mound"?Vg():e.kind==="streetlight"?Wg(t):e.kind==="vehicle"?Xg(t,e.windows,e.observerSide):e.kind==="aircraft"?jg():e.kind==="entity"?Kg():gp();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Nt;return i.name=gi.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*au),this.addLights(s,e.lights),s}static scaleFor(e){const t=e.sizeM;if(!t||e.kind==="bridge")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:hu(t.widthM,i.widthM),t.heightM===void 0?1:hu(t.heightM,i.heightM),t.lengthM===void 0?1:hu(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??ho)+1):0;if(e==="bridge")return Ht.NATURAL_SIZE;const n=`${e}:${i}`,s=$g.get(n);if(s)return s;const r=e==="building"?Ug(i-1,void 0,void 0,void 0):e==="tree"?zg():e==="shrub"?Bg():e==="crop"?Gg():e==="mound"?Vg():e==="streetlight"?Wg(!1):e==="vehicle"?Xg(!1,void 0,void 0):e==="aircraft"?jg():e==="entity"?Kg():gp(),o=new sn().setFromObject(r),l={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),$g.set(n,l),l}static usesModel(e){return e.model!==void 0&&!(e.observerSide!==void 0&&eo(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Nt;r.name=gi.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*au,i.updateMatrixWorld(!0);const o=new sn().setFromObject(i),l={lengthM:o.max.z-o.min.z,heightM:o.max.y-o.min.y,widthM:o.max.x-o.min.x},c=Yg(t.sizeM,l)??Yg(n.depictedSizeM,l)??1;i.scale.multiplyScalar(c);const h=o.getCenter(new D).multiplyScalar(c);i.position.x-=h.x,i.position.z-=h.z,i.position.y-=t.kind==="aircraft"?h.y:o.min.y*c,i.traverse(d=>{d instanceof Te&&(d.castShadow=!0,d.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=CA(i.color),s=Wt(e,new bi(ou,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;const r=s.material;r.blending=Pi,r.transparent=!0,r.depthWrite=!1,r.fog=!1}}static setLights(e,t,i,n,s=0,r=1,o=_A,l=[1,1,1]){if(!t||t.length===0)return;const c=new Map(t.map(f=>[f.id,f])),h=Math.max(1,n*o/ou),d=ou*h,u=r/(Math.PI*d*d);for(const f of e.children){if(!(f instanceof Te))continue;const p=f.userData.lightId;if(!p)continue;const v=c.get(p);if(!v)continue;const m=s>0?s1(v,i,i+s):Xy(v,i)?1:0;f.visible=m>0;const g=f.material,x=f.userData.lightColor;if(x){const y=m*AA*(v.intensity??1)*u;g.color.setRGB(x[0]*y*l[0],x[1]*y*l[1],x[2]*y*l[2])}f.scale.setScalar(h)}}static setLit(e,t,i,n=1){const[s,r,o]=t==="streetlight"?[TA,IA,Cb]:[DA,RA,Pb],l=i?s*n/(Math.PI*r*r):0,c=[o[0]*l,o[1]*l,o[2]*l];e.traverse(h=>{const d=h.userData;!(h instanceof Te)||!d.emissive||d.lightId||h.material.color.setRGB(...c)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Te))return;t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const uu="https://ufoathome.org/models/index.json";class YA{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??qA()}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 qA(){const a=`?v=${encodeURIComponent("0.86.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==uu?[e,uu]:[uu]).map(t=>t+a)}const oh=[{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 YA}];async function Jg(a){const{GLTFLoader:e}=await ot(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-CeRN5jhy.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 Bb=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class _n{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Te(new an(2,2),new mt({uniforms:{uColor:{value:new se(0,0,0)},uRadius:{value:1}},vertexShader:_n.VERTEX,fragmentShader:_n.FRAGMENT,transparent:!0,depthWrite:!1,blending:Pi,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*_n.MIN_ANGLE_RAD),r=_n.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(_n.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(_n.MAX_SHARE*_n.FILL*Math.PI))}static VERTEX=`
|
|
8803
8803
|
uniform float uRadius;
|
|
8804
8804
|
varying vec2 vOffset;
|
|
8805
8805
|
void main() {
|
|
@@ -9362,7 +9362,7 @@ cloudPoint = (modelMatrix * vec4(transformed, 1.0)).xyz - cameraPosition;`);let
|
|
|
9362
9362
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
9363
9363
|
gl_FragColor = vec4(light, 1.0);
|
|
9364
9364
|
}
|
|
9365
|
-
`,transparent:!0,blending:Pi,depthWrite:!1,side:Qt,fog:!1});this.object=new Te(new bi(f0.RADIUS,128,32,0,Math.PI*2,0,ft.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<ft.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ss.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=ss.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Bh{constructor(e){this.generator=e}static SIZE=128;target=new Nl(Bh.SIZE,{type:si,generateMipmaps:!1,minFilter:ut,magFilter:ut});camera=new Kp(.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;let r=!1;t.traverse(l=>{const c=l;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const o=n.map(l=>l.visible);for(const l of n)l.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((l,c)=>{l.visible=o[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 xn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){xn.install(),this.generator=new Bf(e),this.eye=new Bh(this.generator)}static decor;refresh(e,t,i,n,s,r,o,l=[],c,h=xn.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(g=>g.id===m&&g.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let g=this.probes.get(m.id);g||(g=new Bh(this.generator),this.probes.set(m.id,g)),d.push({probe:g,reflector:m})}const u=performance.now(),f=()=>d.filter(({probe:m})=>m.capturedVersion!==o),p=f().filter(({probe:m})=>u-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((g,x)=>x.probe.capturedAtMs<g.probe.capturedAtMs?x:g);if(m.reflector){const g=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,g,[m.reflector.holder,...s]),xn.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),xn.decor=m.probe.filtered;for(const g of r)xn.reflectOn(g,m.probe);for(const g of n)g.shiny||xn.reflectOn(g.holder,m.probe)}m.probe.capturedVersion=o}const v=f();if(v.length!==0)return Math.max(16,Math.min(...v.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:xn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Ul?t.sharp&&s.setSurroundings(t.sharp):s instanceof jr&&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(xn.installed)return;xn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!Ye.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}Ye.lights_fragment_maps=Ye.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function jA(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 zc=900,fu=1,Qg=4,pu=5,ev=.5,pl=900,JA=6371e3,QA=3e4;function tv(a){const e=Math.sqrt(2*JA*Math.max(a,0));return Math.max(pl,Math.min(e,QA))}const mu=.5,gu=850,vu=.03,yn=850,il=300,fr=120,eT=700,tT=.04,nl=4,bu=1.5,iv=-1,iT=6,vp=-4,nT=2,sT=20,Hc=2600,rT=.97,aT=.38,Gc=vp,nv=1500,oT=400,lT=[0,45,90,135,180,225,270,315],cT=2,hT=16,sv=4e3,rv=880,Vc=40,av=60,dT=10,uT=1,fT=150,pT=55,mT=.5,gT=17,ov=.265,lv=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*ov,Math.sin(t)*ov]})],yu=700,Mu=250/1e3,vT=12,cv=5,wu=6,Gr=[.92,.92,.95],xu=[.15,.15,.19],Su={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}},Qa=0,Eu=0,bT=150,_u=3e3,sl=20,yT=15,hv=Qa,MT=40,dv=1,wT=9;function Au(a){return dv+(wT-dv)*a}const uv=new se(.75,.82,.92),xT=10,ST=.5;function fv(a){return lo(a/xT,ST,1)}const Vr=200,pv=.18,mv=.32,ET=.35,gv=new se(.85,.9,.98),vv=5,bv=.85,yv=.01;function _T(a,e,t=1){return Math.round(a*(yv+(1-yv)*e)*t)}function AT(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 Mv=230,wv=.7,xv=.05,TT=.6,IT=.7,DT=.15,Sv=.35,RT=3,CT=1/12,PT=.5,fs=new se(.82,.86,1),LT=2500,kT=1.6,Tu=15,OT={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 It{renderer;scene=new js;phenomena=new qn(this.scene);references=new Yn(this.scene,()=>this.render());camera;celestialGroup=new Nt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=t===void 0?void 0:setTimeout(n,t);return t!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+t),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),t+20))),e.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(e){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),e&&this.awaitArrival(e).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+sv,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),sv+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new On;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ye;decorModelProvider=oh[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new bt(e=>this.awaitArrival(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;decorPresence=new Map;decorSunlight=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Xm(16777215,0);celestialLightTarget=new Xt;skyLight=new ww(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 sh;weather=Mp;observerElevationM=0;siteElevationM=0;air=new Fn;groundRadius=pl;terrainRadius=pl;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new ye;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Xm(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new sh;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new sh;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;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;iceHalos;lunarDiffraction;lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=vM()){this.renderer=new N_({canvas:e,antialias:!0}),this.resolution=new St(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=gl,this.camera=new mn(60,e.width/Math.max(e.height,1),.1,zc*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=-fr,this.celestialLight.shadow.camera.right=fr,this.celestialLight.shadow.camera.top=fr,this.celestialLight.shadow.camera.bottom=-fr,this.celestialLight.shadow.camera.near=yn-il,this.celestialLight.shadow.camera.far=yn+il,this.celestialLight.shadow.bias=-.03/(2*il),this.celestialLight.shadow.normalBias=tT,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(fs),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 Gt(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*Mu,0,e.z*Mu);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)*ln,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ln;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ln,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(tv(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/pl),this.camera.far=Math.max(zc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ni(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:l,z:c}=ni(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+c*c)<fT*(n/pl))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;this.awaitArrival(oA(e,t,this.terrainProviders,n),It.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:c,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const d=this.terrainMesh,u=s?ni(e,t,s.lat,s.lng):void 0;d&&u&&Math.hypot(u.x,u.z)<=r&&(l.position.y=d.position.y+this.groundYOfPatch(d,u.x,u.z)),d&&u&&Math.hypot(u.x,u.z)<=r?this.crossfadeTerrain(l,d):this.disposeMesh(this.terrainMesh),l.renderOrder=uT,this.terrainMesh=l,this.compileNextFrameOffThread(),this.terrainAttribution=c,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),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)/It.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>It.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}this.awaitArrival(n.getRoads(Rb(e,t,i)),It.ROADS_PATIENCE_MS).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)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=ot(async()=>{const{TraceSystem:e}=await import("./TraceSystem-DG5-88i4.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(pu);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(t,n,s)))}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())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyLensFlareTint(e){if(!this.lensFlare)return;const t=pT*(this.sunArriving[1]/gT);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=Xi.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(jA(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!AT(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Fn.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Ys.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>=PT,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(),gi.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=gi.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),this.awaitArrival(this.loadDecorModel(t,this.decorModelToken))}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}setDecorSunlight(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=ot(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-CdlRgS_7.js");return{ContrailSystem:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ContrailSystem:e})=>{const t=new e;this.scene.add(t.group),this.contrailSystem=t})}contrailTint(e){const t=this.contrailSunlight.get(e),i=this.lastAstronomy?.sun,n=It.CONTRAIL_ALBEDO/Math.PI,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const o=An.litFraction(t.sunElevationDeg,t.heightM);if(o>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=ft.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*o}}return r}static CONTRAIL_ALBEDO=.8;updateContrails(){this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad()},e=>this.contrailTint(e))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}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,l=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,d)=>this.groundYUnder(h,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,d,u)=>this.transmittanceTo(h,d,u)},t,l?(h,d)=>l.relativeOfLuminance(h,d):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const c=this.bodySystem.furthestFrom(this.camera.position)*1.2;c>this.camera.far&&(this.camera.far=c,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,l,c)=>(o*t+(l+c)/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 Jg(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}async loadDecorModel(e,t){const i=e.model;if(!(!i||!gi.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 Jg(s);if(t!==this.decorModelToken)return;const l=this.decorGroups.get(e.id);if(!l)return;xn.reflectOn(o),gi.applyModel(l,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?ni(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(c=>c.observerSide!==void 0&&eo(c.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const c=ni(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=c.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=c.z+(s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)}s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let o=0;if(s){const c=gi.occupantView(s),h=-(s.headingDeg??0)*ln,d=c.x*Math.cos(h)+c.z*Math.sin(h),u=-c.x*Math.sin(h)+c.z*Math.cos(h),f=s.eastM+n.x,p=-s.northM+n.z;r.x=-(f+d),r.z=-(p+u),this.camera.position.y=this.groundYUnder(f,p)+c.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ln,-(c.headingDeg+this.indoorLookYawDeg)*ln,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum();for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const d=Dr(c,i),u=d.eastM+n.x+r.x,f=-d.northM+n.z+r.z,p=this.terrainMesh,v=`${p?.geometry.uuid}:${(u-(p?.position.x??0)).toFixed(3)}:${(f-(p?.position.z??0)).toFixed(3)}:${(p?.position.y??0).toFixed(3)}:${d.headingDeg}:${d.altitudeM}`;if(h.userData.footprintKey!==v&&(h.userData.footprintGroundY=this.groundUnderFootprint(c,u,f,d.headingDeg,d.altitudeM),h.userData.footprintKey=v),h.position.set(u,h.userData.footprintGroundY+d.altitudeM,f),c.kind==="crop"){const y=Math.hypot(u,f);h.visible=y<=bT}const m=this.decorPresence.get(c.id),g=m!==void 0&&(i<m.fromMs||i>m.untilMs);m&&(h.visible=!g);const x=this.decorSunlight.get(c.id);if(x&&!g&&this.lightFromAbove(h,x),d.headingDeg!==void 0&&(h.rotation.y=-d.headingDeg*ln),c.kind==="crop"&&h.visible){const y=this.terrainMesh,b=[y?.geometry.uuid,u-(y?.position.x??0),f-(y?.position.z??0),h.position.y-(y?.position.y??0),d.headingDeg,d.altitudeM].map(w=>typeof w=="number"?w.toFixed(4):w).join(":");h.userData.cropGroundKey!==b&&(gi.fitCropToGround(h,(w,E)=>this.groundYUnder(w,E)+d.altitudeM),h.userData.cropGroundKey=b)}g||(o=Math.max(o,h.position.distanceTo(this.camera.position)))}this.updateContrails();const l=Math.max(zc*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-l)>1&&(this.camera.far=l,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):Eu}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 Eu;const r=n.getX(0),o=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=lo((t-r)/(o-r)*(s-1),0,s-1),d=lo((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return Eu;const u=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(d),s-2),p=h-u,v=d-f,m=(w,E)=>n.getY(w*s+E),g=m(f,u),x=m(f,u+1),y=m(f+1,u),b=m(f+1,u+1);return p+v<=1?g+(x-g)*p+(y-g)*v:b+(y-b)*(1-p)+(x-b)*(1-v)}groundUnderFootprint(e,t,i,n,s=0){return gi.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){en.uMedium.value=0;return}en.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;en.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 ye;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}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&&gi.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(s)),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=mh(n,e);gi.setLit(r,n.kind,o,this.relativeScale);const l=this.streetlightLights.get(n.id);l&&(l.visible=o)}}addStreetlightLight(e,t){const i=gi.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new j1(16764006,nv*this.relativeScale,oT);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.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);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=ts.luminanceOf(r);if(!(o>0))return[0,0,0];const l=Ee.relativeOfResponse(o)/o;return[r[0]*l,r[1]*l,r[2]*l]},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,nl,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,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon));const t=this.scatteredSky?.ambient??It.relativeSkyOf(qf(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),at.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=nv*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:Ys.opticalDepth(i))*Ne.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=ft.aureoleScale(n,ft.airMass(e.altitudeDeg))*s,l=ft.coronaScale(r),c=ft.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),l.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 f0,this.celestialGroup.add(this.lunarDiffraction.object));const d=ft.profile(ft.HAZE_COARSE_MODE),u=ft.profile(ft.CLOUD_DROPLETS),f=xg(e.altitudeDeg),p=new Float32Array(ft.STEPS*3);let v=0;for(let y=0;y<ft.STEPS;y++){const b=y*3,w=[0,1,2].map(T=>c*f[T]*(o*d[b+T]+l*u[b+T])),E=ts.shown(w,ts.luminanceOf(w),(T,M)=>t.relativeOfLuminance(T,M));p.set(E,b),v=Math.max(v,ts.response(E))}const{x:m,y:g,z:x}=ti(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(v>1/200?{x:m,y:g,z:x}:void 0,p)}applyAir(){this.scene.fog instanceof fa||(this.scene.fog=new fa),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,lightPollution:this.lightPollution,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:le.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?hT:cT),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 EA(gu),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):_r(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new hn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):_r(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(vu*this.camera.fov*Math.PI/180);let s,r=n;const o=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(jn.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(i);h>r&&(r=h,s=l)}return s&&!this.groundHides(e,t)?s:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(vu*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>=Gc,s=!n&&e.moon.altitudeDeg>=Gc,r=n?e.sun:e.moon,o=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ln)),c=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(c,1e-6)),d=Math.max(0,1/(1+.1125*h)-c),u=[0,0,0];if(n||s){const x=ft.illuminanceOf(r.magnitude)*i,y=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let T=0;T<3;T++)o[T]=x*y[T]*c,u[T]=x*y[T]*d*l,this.cloudBeam[T]=x*y[T];const{x:b,y:w,z:E}=ti(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(b,w,E)}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 x=this.skyCloudTransmission(),y=t.skyIrradiance,b=[0,1,2].map(E=>y[E]*x+u[E]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const w=Xe.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(w*(b[0]+o[0]*l),w*(b[1]+o[1]*l),w*(b[2]+o[2]*l))}if(this.skyLight.intensity=1,this.sceneSunBeam=n?[o[0],o[1],o[2]]:[0,0,0],!n&&!s){this.celestialLight.intensity=0;return}const{x:p,y:v,z:m}=ti(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}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=An.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),o=ft.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=It.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,o*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof va)||s.userData.emissive)return;const o=It.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*o,r.color.g*n[1]*o,r.color.b*n[2]*o)})}lightDirection=new D(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=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(eT,Math.max(fr,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(il,t*(il/fr));this.shadowLightDistanceM=Math.max(yn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*fr?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=fr;shadowLightDistanceM=yn;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*ln,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 D(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 Ii,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=Et.starPointsOf(e),i=Et.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())}magnitudeLimitOf(e){const t=le.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:le.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return _r(e.sun.altitudeDeg,this.instrumentMagnitudeGain,t)}setLightPollution(e){e!==this.lightPollution&&(this.lightPollution=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}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.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){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const 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()+It.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(e=!1){this.reflections??=new xn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof ys),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,o=>this.measureSurroundings(o,n,s),e?0:xn.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ml;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>ti(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const o=f=>f.map(p=>p/t),l=this.surroundings,c={up:o(r.up),down:o(r.down)},h=(f,p)=>f.some((v,m)=>Math.abs(v-p[m])>.03*Math.max(Math.abs(v),Math.abs(p[m]),1e-12)),d=!l||h(l.up,c.up)||h(l.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Math.exp(r.logAverage)/t)??!1;if(!d&&!u){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=Gc?e.sun:e.moon.altitudeDeg>=Gc?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,CT);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,l)=>this.directionAtScreenPoint(r,o,l),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()),en.uRodShare.value=this.scatteredSky?.rodShare??0,en.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);en.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){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(s=>s.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(pu),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}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(Hb),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 D)}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&&It.markDecorDepth(s,n.kind!=="crop")}e.layers.set(fu),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(zb),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Rn({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Te))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Pi?i.layers.enable(fu):i.layers.disable(fu)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ye),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new W_(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()+It.EXPOSURE_BUDGET_MS,s=It.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(l=>l.visible);for(const l of this.compassSprites)l.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((l,c)=>{l.visible=o[c]})}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(en.uRodShare.value=this.scatteredSky?.rodShare??0,en.uHasOverlay.value=1,en.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 js,t=new rs(-1,1,1,-1,0,2),i=Vc/(rv*Math.tan(av*ln/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const l=new Wo(s.material);l.position.set(o.ndcX,o.ndcY,-1),l.scale.set(i/this.camera.aspect,i,1),e.add(l)}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 sn,i=new D,n=this.camera.getWorldDirection(new D),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)<It.MAP_SUBJECT_NEAREST_M)continue;let l=1/0,c=-1/0,h=1/0,d=-1/0;for(const u 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(u,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;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,g),d=Math.max(d,g)}l=Math.max(l,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=l&&d>=h&&e.push({x:l,y:h,width:c-l,height:d-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 ye),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new wl(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 ye);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new u0(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ye);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ei(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new ye(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 D)}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 ei.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*ln);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new qi;screenPointSize=new ye;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(Qg),this.camera.layers.set(Qg),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 lv)this.isSunOccluded(t[0],t[1])||e++;return e/lv.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,l=this.sunOcclusionRightScratch.set(n.z,0,-n.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const c=this.sunOcclusionUpScratch.crossVectors(l,n).normalize();n.addScaledVector(l,e*o).addScaledVector(c,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,x=e.z+t.z*m-s.position.z;if(Math.hypot(g,x)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(o.count));if(l<2||l*l!==o.count)return!1;const c=[r.position.x+o.getX(0),r.position.x+o.getX(l-1)],h=[r.position.z+o.getZ(0),r.position.z+o.getZ((l-1)*l)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(l-1);if(!(d>0))return!1;let u=n,f=i;for(const[m,g,x]of[[e.x,t.x,c],[e.z,t.z,h]]){const y=Math.min(x[0],x[1]),b=Math.max(x[0],x[1]);if(Math.abs(g)<1e-12){if(m<y||m>b)return!1;continue}const w=(y-m)/g,E=(b-m)/g;u=Math.max(u,Math.min(w,E)),f=Math.min(f,Math.max(w,E))}if(!(f>u))return!1;const p=Math.hypot(t.x,t.z),v=Math.min(4096,Math.max(8,Math.ceil((f-u)*p/(d/2))));for(let m=0;m<=v;m++){const g=u+(f-u)*m/v,x=e.x+t.x*g,y=e.y+t.y*g,b=e.z+t.z*g;if(y<=this.groundYUnder(x,b))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=ev;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 l=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];l&&(r.occludesSourceIds?.includes(i)?n=n===void 0?l.distance:Math.max(n,l.distance):s=s===void 0?l.distance:Math.min(s,l.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(vu*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const l=o.direction.dot(i);l>r&&(r=l,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,ev)}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 l=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),c=this.screenPointOf(l.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),s=Math.max(s,c.ndcX),n=Math.min(n,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new sn;bodyCornerScratch=new D;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.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.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())gi.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());const s=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}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 bi(zc,32,16),i=t.attributes.position,n=t.getAttribute("color")??new pt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:l}=Y_(i.getX(r),i.getY(r),i.getZ(r)),c=t5(o,l,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,c[0],c[1],c[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new Rn({vertexColors:!0,side:Qt,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Te(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=tv(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Wp(this.groundRadius,48),i=new va({color:new se(mu,mu,mu),fog:!0});fa.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Te(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=ti(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-xt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*rT);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-xt.iceAlphaAt(i,Hc,r,this.cloudFieldOffset)*aT),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<vp){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:l}=ti(t.altitudeDeg,t.azimuthDeg,yn),c=xg(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=It.unitLuminance(n);let f=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/yn)**2,v=[0,1,2].map(m=>Math.min(It.BRIGHTEST_RELATIVE,u[m]*d[m]/p));f instanceof Te||(this.disposeMesh(f),f=new Te(new bi(1,16,16),new Rn({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 ys)){this.disposeMesh(f);const m=new rt;m.setAttribute("position",new Ze(new Float32Array(3),3)),m.setAttribute("color",new Ze(new Float32Array(3),3)),f=new ys(m,at.material(yo[yo.length-1].size,!1)),at.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,u[0]*d[0]*v,u[1]*d[1]*v,u[2]*d[2]*v),p.needsUpdate=!0}if(f.position.set(r,o,l),this.setHitArea(e,r,o,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,l,d,i/yn*(180/Math.PI),It.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,l*p),this.lensFlare||(this.lensFlare=SA(),this.lensFlare.uniforms.uOpacity.value=mT,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(c)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<vp){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=ti(e.altitudeDeg,e.azimuthDeg,yn),o=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,o),c=Math.max(lo(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(nl/yn)**2,h=new se(...l.map(f=>Math.min(It.BRIGHTEST_RELATIVE,f/c))),d=`${e.phase.phaseFraction<.5}:${Math.round(lo(e.phase.illuminatedFraction,0,1)*500)}`;let u=this.bodyMeshes.get(i);if(u instanceof Wo)u.userData.phaseKey!==d&&(u.material.map?.dispose(),u.material.map=_v(e.phase),u.userData.phaseKey=d),u.material.color.copy(h);else{this.disposeMesh(u),u=new Wo(new nh({map:_v(e.phase),color:h,fog:!1})),u.userData.phaseKey=d;const f=nl*2;u.scale.set(f,f,1),this.celestialGroup.add(u),this.bodyMeshes.set(i,u)}u.position.set(n,s,r),this.setHitArea(i,n,s,r,nl),this.setGlare(i,n,s,r,l,nl/yn*(180/Math.PI))}bentLight(e,t,i=nT){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 It.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,at.CONE_SOLID_ANGLE/t)}pointScratch=new ye;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=ft.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=ts.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 l=new nh({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Wo(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*iT;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(Xi.radiusDeg(Xi.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new Xi(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.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=no(e.magnitude,t),s=iu(n);this.cometKey=i,this.setBodyMesh(i,e.position,bu*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new wn(yn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Hi,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:Hc},0);return}const s=this.lowerCloudCover(),r=ht.deckLitUntilDeg(ht.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,l=this.bentLight(o,o===e?Gt.SUN_MAGNITUDE:t.magnitude),c=ht.strength(i,s,o.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=ti(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},o.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Hc},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??.65)}buildRainbow(e,t){this.rainbow||(this.rainbow=new sa,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?Gt.SUN_MAGNITUDE:t.magnitude,sT),l=Wi.strength(i,r,s.altitudeDeg)*o.scale;if(l<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=ti(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new vr,this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=En.galactic(i,n),r=It.directionOf(s.centre),o=It.directionOf(s.rotation),l=It.directionOf(s.pole),c=new $e().set(r.x,r.y,r.z,o.x,o.y,o.z,l.x,l.y,l.z),h=It.directionOf(En.eclipticPole(i,n)),d=It.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:It.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:le.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=ti(e.altitudeDeg,e.azimuthDeg,1);return new D(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=no(n.magnitude,t),o=iu(r);this.setBodyMesh(s,n.position,bu*(.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=no(n.magnitude,t),r=iu(s),o=OT[n.body]??new se(1,1,1),l=new se(o.r*r,o.g*r,o.b*r),c=bu*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,l,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 Jn(n,s),o=Iu(1337),l=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const d=i.mag[h];if(d>t)break;const{altitudeDeg:u,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(u<iv)continue;const{x:p,y:v,z:m}=ti(u,f,gu);l.push({x:p,y:v,z:m,brightness:no(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*ft.illuminanceOf(d)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of iA){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<iv)continue;const{x:f,y:p,z:v}=ti(d,u,gu);this.namedStars.push({star:h,direction:new D(f,p,v).normalize(),altitudeDeg:d})}this.starTiers=yo.map((h,d)=>{const u=l.filter(w=>e0(w.brightness)===d),f=new Float32Array(u.length*3),p=new Float32Array(u.length),v=new Float32Array(u.length*3),m=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((w,E)=>{f[E*3]=w.x,f[E*3+1]=w.y,f[E*3+2]=w.z,p[E]=w.brightness,v.set(w.illuminance,E*3),m[E]=w.phase,g[E]=w.speedFactor});const x=new rt;x.setAttribute("position",new Ze(f,3)),x.setAttribute("seed",new Ze(m.map(w=>w/(2*Math.PI)),1));const y=new Ze(new Float32Array(u.length*3),3);x.setAttribute("color",y);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=x):(b=new ys(x,at.material(h.size)),at.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:y,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){at.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 vo(this.celestialGroup,yu,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(Gr[0]+(xu[0]-Gr[0])*t,Gr[1]+(xu[1]-Gr[1])*t,Gr[2]+(xu[2]-Gr[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}=Vf(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=Wf(yu);this.cloudMesh=new Te(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}=Vf(new se(...Gr),e,Hc,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Te(Wf(yu*1.04),t),this.cirrusMesh.renderOrder=cv-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?vo.deckOrder(!0,0,1):cv}cloudLayerOffset(){const t=((this.weather.cloudBaseM??1e3)-this.observerElevationM)*Mu;return Math.sign(t||1)*Math.max(Math.abs(t),vT)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,o]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*Tu*this.relativeScale/Math.PI,c=new se(t[0]+fs.r*l,t[1]+fs.g*l,t[2]+fs.b*l);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),c,c);const h=Math.max(0,n.y);for(const d of i)d.sunDir.value.copy(n),d.sunColor.value.setRGB(s*h,r*h,o*h),d.ambientColor.value.copy(c)}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 _T(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,_u],[this.rainSplashSystem?.points,Vr],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Su[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=fv(Au(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=Su[e],i=t.poolSize,n=Iu(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let y=0;y<i;y++){const b=n()*Math.PI*2,w=n()*t.radiusM;s[y*3]=Math.cos(b)*w,s[y*3+1]=Qa+n()*(t.topYM-Qa),s[y*3+2]=Math.sin(b)*w,r[y]=n()*Math.PI*2,o[y]=.7+n()*.6,l[y]=.6+n()*.8,c[y]=.4+n()*1.2}const v=new rt;v.setAttribute("position",new Ze(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:NT(e)},uNearFocusDistance:{value:vv},uHazeDistance:{value:t.radiusM*bv}},g=new mt({uniforms:m,vertexShader:GT,fragmentShader:VT,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const x=new ys(v,g);x.renderOrder=wu,this.scene.add(x),this.precipitationPoints=x,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=l,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,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=Su[i];if(this.precipitationUniforms?.uColor.value.copy(It.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*ln,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,v=this.precipitationBounceDuration,m=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,x=i==="snow"&&d&&u,y=i==="hail"&&f&&p&&v&&m&&g;for(let b=0,w=0;b<l.length;b+=3,w++){if(y&&f[w]>0){if(f[w]-=t,f[w]<=0){const M=Math.random()*Math.PI*2,I=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*I,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*I,f[w]=0}else{const M=1-f[w]/v[w];l[b+1]=Qa+Math.sin(Math.PI*M)*p[w],l[b]=Wc(l[b]+(r+m[w])*t,n.radiusM),l[b+2]=Wc(l[b+2]+(o+g[w])*t,n.radiusM)}continue}let E=0,T=0;if(x){const M=TT*d[w],I=IT*u[w];E=Math.sin(e*M*Math.PI*2+c[w])*I,T=Math.sin(e*M*Math.PI*2+c[w]+Math.PI/2)*I}if(l[b]+=(r+E)*t,l[b+1]-=n.fallSpeedMPerS*h[w]*t,l[b+2]+=(o+T)*t,l[b]=Wc(l[b],n.radiusM),l[b+2]=Wc(l[b+2],n.radiusM),l[b+1]<Qa){if(y){p[w]=Sv*(.2+Math.random()*1.6),v[w]=DT*(.5+Math.random()),f[w]=v[w];const A=Math.random()*Math.PI*2,R=RT*(p[w]/Sv);m[w]=Math.cos(A)*R,g[w]=Math.sin(A)*R,l[b+1]=Qa;continue}const M=Math.random()*Math.PI*2,I=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*I,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*I}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=Au(this.weather.precipitationIntensity);this.rainSystem=yA({count:_u,radiusM:sl,heightM:yT,bottomYM:hv,overallSpeed:MT,color:uv.clone(),opacity:.85,visibleCount:this.precipitationCount(_u),speedStreak:fv(e),pixelSize:Mv,seed:9001,nearFocusDistanceM:vv,hazeDistanceM:sl*bv,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=wu,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Iu(4242),t=new Float32Array(Vr*3),i=new Float32Array(Vr),n=new Float32Array(Vr),s=new Float32Array(Vr);for(let h=0;h<Vr;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*sl;t[h*3]=Math.cos(d)*u,t[h*3+1]=hv,t[h*3+2]=Math.sin(d)*u,n[h]=Ev(pv,mv),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new rt;r.setAttribute("position",new Ze(t,3));const o=new Ze(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(Vr));const l=new mt({uniforms:{uMaxSize:{value:ET},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:gv.clone()},uTexture:{value:BT()}},vertexShader:zT,fragmentShader:HT,transparent:!0,depthWrite:!1}),c=new ys(r,l);c.renderOrder=wu,this.scene.add(c),this.rainSplashSystem={points:c,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*ln;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-Au(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(It.litBySky(uv,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(It.litBySky(gv,this.baseFogColor));const n=this.weather.windDirectionDeg*ln,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=sl,l=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(l(t.uniforms.uWindOffset.value.x+s*e),l(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=wv+(1-wv)*(1-c),d=xv+(1-xv)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=Mv*h*(.5+.5*d)}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 l=0,c=0;l<i.length;l+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*sl;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Ev(pv,mv),n[c]=0}o[c]=n[c]/s[c]}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 l of this.lightningFlashes){if(l.t>e)break;const c=wi.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(LT/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 l=this.scene.fog,c=s*Tu*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+fs.r*c,this.airlight[1]+fs.g*c,this.airlight[2]+fs.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*kT;r.setRGB(1+l*fs.r,1+l*fs.g,1+l*fs.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Tu*this.relativeScale,t){const{x:l,y:c,z:h}=ti(25,t.azimuthDeg,yn);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new yr(yn*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){this.compassSprites=lT.map(e=>{const t=da.point(e,this.compassPoints),i=new nh({map:WT(t),depthTest:!1,fog:!1}),n=new Wo(i),{x:s,y:r,z:o}=ti(0,e,rv);return n.position.set(s,r,o),n.scale.set(Vc,Vc,1),n.renderOrder=dT,n.layers.set(pu),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=av*Math.PI/360,i=Vc*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 ln=Math.PI/180;function lo(a,e,t){return Math.max(e,Math.min(t,a))}function Ev(a,e){return a+Math.random()*(e-a)}function Wc(a,e){return(a%(e*2)+e*3)%(e*2)-e}let Xc,$c;function NT(a){switch(a){case"snow":return FT();case"hail":return UT()}}function FT(){if(Xc)return Xc;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),Xc=new tr(e),Xc}function UT(){if($c)return $c;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),$c=new tr(e),$c}let Yc;function BT(){if(Yc)return Yc;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),Yc=new tr(e),Yc}const zT=`
|
|
9365
|
+
`,transparent:!0,blending:Pi,depthWrite:!1,side:Qt,fog:!1});this.object=new Te(new bi(f0.RADIUS,128,32,0,Math.PI*2,0,ft.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<ft.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ss.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=ss.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class Bh{constructor(e){this.generator=e}static SIZE=128;target=new Nl(Bh.SIZE,{type:si,generateMipmaps:!1,minFilter:ut,magFilter:ut});camera=new Kp(.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;let r=!1;t.traverse(l=>{const c=l;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?s:!1;const o=n.map(l=>l.visible);for(const l of n)l.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),n.forEach((l,c)=>{l.visible=o[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 xn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){xn.install(),this.generator=new Bf(e),this.eye=new Bh(this.generator)}static decor;refresh(e,t,i,n,s,r,o,l=[],c,h=xn.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(g=>g.id===m&&g.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let g=this.probes.get(m.id);g||(g=new Bh(this.generator),this.probes.set(m.id,g)),d.push({probe:g,reflector:m})}const u=performance.now(),f=()=>d.filter(({probe:m})=>m.capturedVersion!==o),p=f().filter(({probe:m})=>u-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((g,x)=>x.probe.capturedAtMs<g.probe.capturedAtMs?x:g);if(m.reflector){const g=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,g,[m.reflector.holder,...s]),xn.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),xn.decor=m.probe.filtered;for(const g of r)xn.reflectOn(g,m.probe);for(const g of n)g.shiny||xn.reflectOn(g.holder,m.probe)}m.probe.capturedVersion=o}const v=f();if(v.length!==0)return Math.max(16,Math.min(...v.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:xn.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Ul?t.sharp&&s.setSurroundings(t.sharp):s instanceof jr&&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(xn.installed)return;xn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!Ye.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}Ye.lights_fragment_maps=Ye.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function jA(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 zc=900,fu=1,Qg=4,pu=5,ev=.5,pl=900,JA=6371e3,QA=3e4;function tv(a){const e=Math.sqrt(2*JA*Math.max(a,0));return Math.max(pl,Math.min(e,QA))}const mu=.5,gu=850,vu=.03,yn=850,il=300,fr=120,eT=700,tT=.04,nl=4,bu=1.5,iv=-1,iT=6,vp=-4,nT=2,sT=20,Hc=2600,rT=.97,aT=.38,Gc=vp,nv=1500,oT=400,lT=[0,45,90,135,180,225,270,315],cT=2,hT=16,sv=4e3,rv=880,Vc=40,av=60,dT=10,uT=1,fT=150,pT=55,mT=.5,gT=17,ov=.265,lv=[[0,0],...Array.from({length:8},(a,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*ov,Math.sin(t)*ov]})],yu=700,Mu=250/1e3,vT=12,cv=5,wu=6,Gr=[.92,.92,.95],xu=[.15,.15,.19],Su={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}},Qa=0,Eu=0,bT=150,_u=3e3,sl=20,yT=15,hv=Qa,MT=40,dv=1,wT=9;function Au(a){return dv+(wT-dv)*a}const uv=new se(.75,.82,.92),xT=10,ST=.5;function fv(a){return lo(a/xT,ST,1)}const Vr=200,pv=.18,mv=.32,ET=.35,gv=new se(.85,.9,.98),vv=5,bv=.85,yv=.01;function _T(a,e,t=1){return Math.round(a*(yv+(1-yv)*e)*t)}function AT(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 Mv=230,wv=.7,xv=.05,TT=.6,IT=.7,DT=.15,Sv=.35,RT=3,CT=1/12,PT=.5,fs=new se(.82,.86,1),LT=2500,kT=1.6,Tu=15,OT={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 It{renderer;scene=new js;phenomena=new qn(this.scene);references=new Yn(this.scene,()=>this.render());camera;celestialGroup=new Nt;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const n=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},s=t===void 0?void 0:setTimeout(n,t);return t!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+t),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),t+20))),e.finally(()=>{clearTimeout(s),n()})}static ROADS_PATIENCE_MS=4e3;static TERRAIN_PATIENCE_MS=12e3;arrivalDeadlineMs=0;redrawHeld(){this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))}holdForNewScene(e){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),e&&this.awaitArrival(e).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+sv,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),sv+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new On;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ye;decorModelProvider=oh[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new bt(e=>this.awaitArrival(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;decorPresence=new Map;decorSunlight=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Xm(16777215,0);celestialLightTarget=new Xt;skyLight=new ww(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 sh;weather=Mp;observerElevationM=0;siteElevationM=0;air=new Fn;groundRadius=pl;terrainRadius=pl;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new D;cloudFieldOffset=new D;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new D;rainLastVerticalFacing=-1;rainViewportSize=new ye;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Xm(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new sh;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new sh;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;lightPollution;meteorSystem;cometTail;satelliteField;reentrySystem;iceHalos;lunarDiffraction;lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=vM()){this.renderer=new N_({canvas:e,antialias:!0}),this.resolution=new St(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=gl,this.camera=new mn(60,e.width/Math.max(e.height,1),.1,zc*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=-fr,this.celestialLight.shadow.camera.right=fr,this.celestialLight.shadow.camera.top=fr,this.celestialLight.shadow.camera.bottom=-fr,this.celestialLight.shadow.camera.near=yn-il,this.celestialLight.shadow.camera.far=yn+il,this.celestialLight.shadow.bias=-.03/(2*il),this.celestialLight.shadow.normalBias=tT,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(fs),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 Gt(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*Mu,0,e.z*Mu);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)*ln,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ln;if(e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ln,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(tv(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/pl),this.camera.far=Math.max(zc*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),this.terrainMesh&&this.terrainOrigin&&e.lat!==void 0&&e.lng!==void 0){const n=ni(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:l,z:c}=ni(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(l*l+c*c)<fT*(n/pl))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;this.awaitArrival(oA(e,t,this.terrainProviders,n),It.TERRAIN_PATIENCE_MS).then(({mesh:l,attribution:c,originElevationM:h})=>{if(o!==this.terrainBuildToken)return;this.setSiteElevation(h??0);const d=this.terrainMesh,u=s?ni(e,t,s.lat,s.lng):void 0;d&&u&&Math.hypot(u.x,u.z)<=r&&(l.position.y=d.position.y+this.groundYOfPatch(d,u.x,u.z)),d&&u&&Math.hypot(u.x,u.z)<=r?this.crossfadeTerrain(l,d):this.disposeMesh(this.terrainMesh),l.renderOrder=uT,this.terrainMesh=l,this.compileNextFrameOffThread(),this.terrainAttribution=c,this.scene.add(l),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(l=>{console.warn("Terrain build failed, keeping the flat ground fallback:",l),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)/It.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>It.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}this.awaitArrival(n.getRoads(Rb(e,t,i)),It.ROADS_PATIENCE_MS).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)))}setTraces(e,t=new Map){e===this.traces&&t===this.traceLabels||(this.traces=e,this.traceLabels=t,!(e.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(e){e!==this.tracesShown&&(this.tracesShown=e,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=ot(async()=>{const{TraceSystem:e}=await import("./TraceSystem-DG5-88i4.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(pu);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainOrigin;!e||!t||!i||(e.group.position.copy(t.position),e.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(n,s)=>this.groundYOfPatch(t,n,s)))}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())}setCompassPoints(e){this.compassPoints!==e&&(this.compassPoints=e,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyLensFlareTint(e){if(!this.lensFlare)return;const t=pT*(this.sunArriving[1]/gT);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=Xi.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(jA(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!AT(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Fn.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Ys.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>=PT,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(),gi.dispose(t);this.decorGroups.clear(),this.streetlightLights.clear();for(const t of e){const i=gi.build(t,t.lit??!1);this.scene.add(i),this.decorGroups.set(t.id,i),t.kind==="streetlight"&&this.addStreetlightLight(t.id,i),this.awaitArrival(this.loadDecorModel(t,this.decorModelToken))}this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}}setDecorSunlight(e){this.decorSunlight=e}setContrails(e){e!==this.contrails&&(this.contrails=e,!(e.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(e){this.contrailSunlight=e}loadContrailSystem(){return this.contrailSystemLoading??=ot(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-CXV5ZetF.js");return{ContrailSystem:e}},__vite__mapDeps([0,1]),import.meta.url).then(({ContrailSystem:e})=>{const t=new e;this.scene.add(t.group),this.contrailSystem=t})}contrailTint(e){const t=this.contrailSunlight.get(e),i=this.lastAstronomy?.sun,n=It.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const o=An.litFraction(t.sunElevationDeg,t.heightM);if(o>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=ft.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*o}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);updateContrails(){this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad()},e=>this.contrailTint(e))}contrailPixelRad(){const e=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/e)}setDecorPresence(e){this.decorPresence=e}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,l=this.scatteredSky;this.bodySystem.set(e,{originX:r,originZ:o,originGroundY:this.groundYUnder(r,o),eye:this.camera.position,groundYAt:(h,d)=>this.groundYUnder(h,d),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(h,d,u)=>this.transmittanceTo(h,d,u)},t,l?(h,d)=>l.relativeOfLuminance(h,d):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const c=this.bodySystem.furthestFrom(this.camera.position)*1.2;c>this.camera.far&&(this.camera.far=c,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,l,c)=>(o*t+(l+c)/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 Jg(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}async loadDecorModel(e,t){const i=e.model;if(!(!i||!gi.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 Jg(s);if(t!==this.decorModelToken)return;const l=this.decorGroups.get(e.id);if(!l)return;xn.reflectOn(o),gi.applyModel(l,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?ni(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(c=>c.observerSide!==void 0&&eo(c.kind));if(this.terrainMesh&&this.terrainOrigin&&t?.lat!==void 0&&t.lng!==void 0){const c=ni(this.terrainOrigin.lat,this.terrainOrigin.lng,t.lat,t.lng);this.terrainMesh.position.x=c.x-(s?0:this.gaitOffset.eastM),this.terrainMesh.position.z=c.z+(s?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)}s||(n.x-=this.gaitOffset.eastM,n.z+=this.gaitOffset.northM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);const r={x:0,z:0};let o=0;if(s){const c=gi.occupantView(s),h=-(s.headingDeg??0)*ln,d=c.x*Math.cos(h)+c.z*Math.sin(h),u=-c.x*Math.sin(h)+c.z*Math.cos(h),f=s.eastM+n.x,p=-s.northM+n.z;r.x=-(f+d),r.z=-(p+u),this.camera.position.y=this.groundYUnder(f,p)+c.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ln,-(c.headingDeg+this.indoorLookYawDeg)*ln,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z},this.placeShadowFrustum();for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const d=Dr(c,i),u=d.eastM+n.x+r.x,f=-d.northM+n.z+r.z,p=this.terrainMesh,v=`${p?.geometry.uuid}:${(u-(p?.position.x??0)).toFixed(3)}:${(f-(p?.position.z??0)).toFixed(3)}:${(p?.position.y??0).toFixed(3)}:${d.headingDeg}:${d.altitudeM}`;if(h.userData.footprintKey!==v&&(h.userData.footprintGroundY=this.groundUnderFootprint(c,u,f,d.headingDeg,d.altitudeM),h.userData.footprintKey=v),h.position.set(u,h.userData.footprintGroundY+d.altitudeM,f),c.kind==="crop"){const y=Math.hypot(u,f);h.visible=y<=bT}const m=this.decorPresence.get(c.id),g=m!==void 0&&(i<m.fromMs||i>m.untilMs);m&&(h.visible=!g);const x=this.decorSunlight.get(c.id);if(x&&!g&&this.lightFromAbove(h,x),d.headingDeg!==void 0&&(h.rotation.y=-d.headingDeg*ln),c.kind==="crop"&&h.visible){const y=this.terrainMesh,b=[y?.geometry.uuid,u-(y?.position.x??0),f-(y?.position.z??0),h.position.y-(y?.position.y??0),d.headingDeg,d.altitudeM].map(w=>typeof w=="number"?w.toFixed(4):w).join(":");h.userData.cropGroundKey!==b&&(gi.fitCropToGround(h,(w,E)=>this.groundYUnder(w,E)+d.altitudeM),h.userData.cropGroundKey=b)}g||(o=Math.max(o,h.position.distanceTo(this.camera.position)))}this.updateContrails();const l=Math.max(zc*1.2,this.groundRadius*2.5,o*1.2);Math.abs(this.camera.far-l)>1&&(this.camera.far=l,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):Eu}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 Eu;const r=n.getX(0),o=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=lo((t-r)/(o-r)*(s-1),0,s-1),d=lo((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return Eu;const u=Math.min(Math.floor(h),s-2),f=Math.min(Math.floor(d),s-2),p=h-u,v=d-f,m=(w,E)=>n.getY(w*s+E),g=m(f,u),x=m(f,u+1),y=m(f+1,u),b=m(f+1,u+1);return p+v<=1?g+(x-g)*p+(y-g)*v:b+(y-b)*(1-p)+(x-b)*(1-v)}groundUnderFootprint(e,t,i,n,s=0){return gi.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){en.uMedium.value=0;return}en.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const i=e.autoExposure?this.scatteredSky?.sceneAdaptation:void 0;en.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 ye;lampTransmittance(e){const t=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+e.position.y;return this.air.transmittance(t,i,e.position.distanceTo(this.camera.position))}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&&gi.setLights(s,n.lights,e,s.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(s)),n.kind!=="streetlight"&&n.kind!=="vehicle")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const o=mh(n,e);gi.setLit(r,n.kind,o,this.relativeScale);const l=this.streetlightLights.get(n.id);l&&(l.visible=o)}}addStreetlightLight(e,t){const i=gi.bodyOf(t),n=i.children.find(r=>r.userData.emissive);if(!n)return;const s=new j1(16764006,nv*this.relativeScale,oT);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.startHold(),this.pumpScatteredSky(),this.lastSunPosition=e.sun,this.buildSky(e.sun),this.buildGround();const t=this.magnitudeLimitOf(e);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=ts.luminanceOf(r);if(!(o>0))return[0,0,0];const l=Ee.relativeOfResponse(o)/o;return[r[0]*l,r[1]*l,r[2]*l]},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,nl,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,this.magnitudeLimitOf(e)),this.applyDazzleStrength(),this.buildIceHalos(e.sun,e.moon),this.buildRainbow(e.sun,e.moon));const t=this.scatteredSky?.ambient??It.relativeSkyOf(qf(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),at.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=nv*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:Ys.opticalDepth(i))*Ne.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),o=ft.aureoleScale(n,ft.airMass(e.altitudeDeg))*s,l=ft.coronaScale(r),c=ft.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),o.toExponential(2),l.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 f0,this.celestialGroup.add(this.lunarDiffraction.object));const d=ft.profile(ft.HAZE_COARSE_MODE),u=ft.profile(ft.CLOUD_DROPLETS),f=xg(e.altitudeDeg),p=new Float32Array(ft.STEPS*3);let v=0;for(let y=0;y<ft.STEPS;y++){const b=y*3,w=[0,1,2].map(T=>c*f[T]*(o*d[b+T]+l*u[b+T])),E=ts.shown(w,ts.luminanceOf(w),(T,M)=>t.relativeOfLuminance(T,M));p.set(E,b),v=Math.max(v,ts.response(E))}const{x:m,y:g,z:x}=ti(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(v>1/200?{x:m,y:g,z:x}:void 0,p)}applyAir(){this.scene.fog instanceof fa||(this.scene.fog=new fa),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,lightPollution:this.lightPollution,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:le.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?hT:cT),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 EA(gu),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):_r(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setReentries(e){if(e.length===0&&!this.reentrySystem?.count)return;this.reentrySystem||(this.reentrySystem=new hn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):_r(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}get reentryCount(){return this.reentrySystem?.count??0}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(vu*this.camera.fov*Math.PI/180);let s,r=n;const o=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(jn.ID_PREFIX))continue;o.copy(c.position).sub(this.camera.position).normalize();const h=o.dot(i);h>r&&(r=h,s=l)}return s&&!this.groundHides(e,t)?s:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(vu*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>=Gc,s=!n&&e.moon.altitudeDeg>=Gc,r=n?e.sun:e.moon,o=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ln)),c=n||s?this.cloudTransmission(r):1,h=-Math.log(Math.max(c,1e-6)),d=Math.max(0,1/(1+.1125*h)-c),u=[0,0,0];if(n||s){const x=ft.illuminanceOf(r.magnitude)*i,y=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,r.altitudeDeg);for(let T=0;T<3;T++)o[T]=x*y[T]*c,u[T]=x*y[T]*d*l,this.cloudBeam[T]=x*y[T];const{x:b,y:w,z:E}=ti(r.altitudeDeg,r.azimuthDeg,1);this.cloudBeamDirection.set(b,w,E)}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 x=this.skyCloudTransmission(),y=t.skyIrradiance,b=[0,1,2].map(E=>y[E]*x+u[E]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const w=Xe.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(w*(b[0]+o[0]*l),w*(b[1]+o[1]*l),w*(b[2]+o[2]*l))}if(this.skyLight.intensity=1,this.sceneSunBeam=n?[o[0],o[1],o[2]]:[0,0,0],!n&&!s){this.celestialLight.intensity=0;return}const{x:p,y:v,z:m}=ti(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}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(e,t){const i=this.lastAstronomy?.sun,n=[0,0,0];if(i){const s=An.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),o=ft.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=It.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,o*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof va)||s.userData.emissive)return;const o=It.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*o,r.color.g*n[1]*o,r.color.b*n[2]*o)})}lightDirection=new D(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=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,0,0).addScaledVector(n,o(n)).addScaledVector(s,o(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToBodies(){const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(eT,Math.max(fr,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(il,t*(il/fr));this.shadowLightDistanceM=Math.max(yn,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*fr?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=fr;shadowLightDistanceM=yn;shadowUp=new D(0,1,0);shadowAxisX=new D;shadowAxisY=new D;shadowWorld=new D;skyCloudTransmission(){let e=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),t=1;for(const i of[20,45,70]){const n=i*ln,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 D(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 Ii,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=Et.starPointsOf(e),i=Et.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())}magnitudeLimitOf(e){const t=le.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:le.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return _r(e.sun.altitudeDeg,this.instrumentMagnitudeGain,t)}setLightPollution(e){e!==this.lightPollution&&(this.lightPollution=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}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.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){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.developingExposure&&this.startExposure()}}}drawn=0;get framesDrawn(){return this.drawn}compileBeforeNextDraw=!1;compiling;static COMPILE_WAIT_MS=1500;compileOffThread(){const 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()+It.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(e=!1){this.reflections??=new xn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof ys),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0)],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,o=>this.measureSurroundings(o,n,s),e?0:xn.REFRESH_MS);r===void 0||this.reflectionTimer||(this.reflectionTimer=setTimeout(()=>{this.reflectionTimer=void 0,this.frameDirty=!0,!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))},r))}measureSurroundings(e,t,i){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ml;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>ti(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const o=f=>f.map(p=>p/t),l=this.surroundings,c={up:o(r.up),down:o(r.down)},h=(f,p)=>f.some((v,m)=>Math.abs(v-p[m])>.03*Math.max(Math.abs(v),Math.abs(p[m]),1e-12)),d=!l||h(l.up,c.up)||h(l.down,c.down);d&&(this.surroundings=c),this.eyeSettledVersion=-1;const u=this.scatteredSky?.adaptToSurroundings(Math.exp(r.logAverage)/t)??!1;if(!d&&!u){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(e){const t=this.surroundings;if(!t)return;const i=e.sun.altitudeDeg>=Gc?e.sun:e.moon.altitudeDeg>=Gc?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,CT);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,l)=>this.directionAtScreenPoint(r,o,l),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()),en.uRodShare.value=this.scatteredSky?.rodShare??0,en.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);en.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){const t=this.traceSystem?.any&&this.tracesShown;if(!t&&!this.compassSprites.some(s=>s.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,n=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(pu),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}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(Hb),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 D)}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&&It.markDecorDepth(s,n.kind!=="crop")}e.layers.set(fu),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(zb),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Rn({colorWrite:!1});static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Te))return;const n=Array.isArray(i.material)?i.material[0]:i.material;t&&n.depthWrite!==!1&&n.blending!==Pi?i.layers.enable(fu):i.layers.disable(fu)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ye),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new W_(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()+It.EXPOSURE_BUDGET_MS,s=It.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const o=this.compassSprites.map(l=>l.visible);for(const l of this.compassSprites)l.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((l,c)=>{l.visible=o[c]})}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(en.uRodShare.value=this.scatteredSky?.rodShare??0,en.uHasOverlay.value=1,en.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 js,t=new rs(-1,1,1,-1,0,2),i=Vc/(rv*Math.tan(av*ln/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),o=this.screenPointOf(r);if(!o)continue;const l=new Wo(s.material);l.position.set(o.ndcX,o.ndcY,-1),l.scale.set(i/this.camera.aspect,i,1),e.add(l)}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 sn,i=new D,n=this.camera.getWorldDirection(new D),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)<It.MAP_SUBJECT_NEAREST_M)continue;let l=1/0,c=-1/0,h=1/0,d=-1/0;for(const u 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(u,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;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,g),d=Math.max(d,g)}l=Math.max(l,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=l&&d>=h&&e.push({x:l,y:h,width:c-l,height:d-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 ye),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new wl(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 ye);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new u0(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ye);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new ei(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new ye(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 D)}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 ei.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*ln);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new qi;screenPointSize=new ye;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(Qg),this.camera.layers.set(Qg),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 lv)this.isSunOccluded(t[0],t[1])||e++;return e/lv.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,l=this.sunOcclusionRightScratch.set(n.z,0,-n.x);l.lengthSq()<1e-9&&l.set(1,0,0),l.normalize();const c=this.sunOcclusionUpScratch.crossVectors(l,n).normalize();n.addScaledVector(l,e*o).addScaledVector(c,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,x=e.z+t.z*m-s.position.z;if(Math.hypot(g,x)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const o=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(o.count));if(l<2||l*l!==o.count)return!1;const c=[r.position.x+o.getX(0),r.position.x+o.getX(l-1)],h=[r.position.z+o.getZ(0),r.position.z+o.getZ((l-1)*l)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(l-1);if(!(d>0))return!1;let u=n,f=i;for(const[m,g,x]of[[e.x,t.x,c],[e.z,t.z,h]]){const y=Math.min(x[0],x[1]),b=Math.max(x[0],x[1]);if(Math.abs(g)<1e-12){if(m<y||m>b)return!1;continue}const w=(y-m)/g,E=(b-m)/g;u=Math.max(u,Math.min(w,E)),f=Math.min(f,Math.max(w,E))}if(!(f>u))return!1;const p=Math.hypot(t.x,t.z),v=Math.min(4096,Math.max(8,Math.ceil((f-u)*p/(d/2))));for(let m=0;m<=v;m++){const g=u+(f-u)*m/v,x=e.x+t.x*g,y=e.y+t.y*g,b=e.z+t.z*g;if(y<=this.groundYUnder(x,b))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=ev;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 l=this.ufoOcclusionRaycaster.intersectObject(o,!0)[0];l&&(r.occludesSourceIds?.includes(i)?n=n===void 0?l.distance:Math.max(n,l.distance):s=s===void 0?l.distance:Math.min(s,l.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(vu*this.camera.fov*Math.PI/180);let s,r=n;for(const o of this.namedStars){const l=o.direction.dot(i);l>r&&(r=l,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,ev)}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 l=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),c=this.screenPointOf(l.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),s=Math.max(s,c.ndcX),n=Math.min(n,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:n,maxX:s,maxY:r}}bodyBoxScratch=new sn;bodyCornerScratch=new D;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.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.reentrySystem?.dispose(),this.reentrySystem=void 0,this.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())gi.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());const s=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;s&&this.applyPixelRatio(this.resolution.maximum),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),s&&this.drawIfDirty()}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 bi(zc,32,16),i=t.attributes.position,n=t.getAttribute("color")??new pt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:o,azimuthDeg:l}=Y_(i.getX(r),i.getY(r),i.getZ(r)),c=t5(o,l,e.azimuthDeg,e.altitudeDeg);n.setXYZ(r,c[0],c[1],c[2])}if(n.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",n);const s=new Rn({vertexColors:!0,side:Qt,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Te(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=tv(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Wp(this.groundRadius,48),i=new va({color:new se(mu,mu,mu),fog:!0});fa.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Te(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=ti(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-xt.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*rT);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-xt.iceAlphaAt(i,Hc,r,this.cloudFieldOffset)*aT),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<vp){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:l}=ti(t.altitudeDeg,t.azimuthDeg,yn),c=xg(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=It.unitLuminance(n);let f=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/yn)**2,v=[0,1,2].map(m=>Math.min(It.BRIGHTEST_RELATIVE,u[m]*d[m]/p));f instanceof Te||(this.disposeMesh(f),f=new Te(new bi(1,16,16),new Rn({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 ys)){this.disposeMesh(f);const m=new rt;m.setAttribute("position",new Ze(new Float32Array(3),3)),m.setAttribute("color",new Ze(new Float32Array(3),3)),f=new ys(m,at.material(yo[yo.length-1].size,!1)),at.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,u[0]*d[0]*v,u[1]*d[1]*v,u[2]*d[2]*v),p.needsUpdate=!0}if(f.position.set(r,o,l),this.setHitArea(e,r,o,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,o,l,d,i/yn*(180/Math.PI),It.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,l*p),this.lensFlare||(this.lensFlare=SA(),this.lensFlare.uniforms.uOpacity.value=mT,this.lensFlare.uniforms.uFlareIntensity.value=this.lensFlareArtifactIntensity,this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyLensFlareTint(c)}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<vp){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=ti(e.altitudeDeg,e.azimuthDeg,yn),o=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,o),c=Math.max(lo(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(nl/yn)**2,h=new se(...l.map(f=>Math.min(It.BRIGHTEST_RELATIVE,f/c))),d=`${e.phase.phaseFraction<.5}:${Math.round(lo(e.phase.illuminatedFraction,0,1)*500)}`;let u=this.bodyMeshes.get(i);if(u instanceof Wo)u.userData.phaseKey!==d&&(u.material.map?.dispose(),u.material.map=_v(e.phase),u.userData.phaseKey=d),u.material.color.copy(h);else{this.disposeMesh(u),u=new Wo(new nh({map:_v(e.phase),color:h,fog:!1})),u.userData.phaseKey=d;const f=nl*2;u.scale.set(f,f,1),this.celestialGroup.add(u),this.bodyMeshes.set(i,u)}u.position.set(n,s,r),this.setHitArea(i,n,s,r,nl),this.setGlare(i,n,s,r,l,nl/yn*(180/Math.PI))}bentLight(e,t,i=nT){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 It.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,at.CONE_SOLID_ANGLE/t)}pointScratch=new ye;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=ft.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=ts.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 l=new nh({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Wo(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const o=s*iT;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(Xi.radiusDeg(Xi.K*Math.max(...s))<=Math.max(r,o)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new Xi(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.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=no(e.magnitude,t),s=iu(n);this.cometKey=i,this.setBodyMesh(i,e.position,bu*(.5+.5*n),new se(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new wn(yn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Hi,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:Hc},0);return}const s=this.lowerCloudCover(),r=ht.deckLitUntilDeg(ht.DECK_HEIGHT_M),o=e.altitudeDeg>-r?e:t,l=this.bentLight(o,o===e?Gt.SUN_MAGNITUDE:t.magnitude),c=ht.strength(i,s,o.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=ti(o.altitudeDeg,o.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},o.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Hc},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??.65)}buildRainbow(e,t){this.rainbow||(this.rainbow=new sa,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?Gt.SUN_MAGNITUDE:t.magnitude,sT),l=Wi.strength(i,r,s.altitudeDeg)*o.scale;if(l<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=ti(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,o.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new vr,this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=En.galactic(i,n),r=It.directionOf(s.centre),o=It.directionOf(s.rotation),l=It.directionOf(s.pole),c=new $e().set(r.x,r.y,r.z,o.x,o.y,o.z,l.x,l.y,l.z),h=It.directionOf(En.eclipticPole(i,n)),d=It.directionOf(e.sun),u=d.clone().addScaledVector(h,-d.dot(h)).normalize();this.skyGlow.update({galactic:c,eclipticPole:h,sunLongitude:u,sunDirection:d,sunAltitudeDeg:e.sun.altitudeDeg,moon:{direction:It.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:le.phaseAngleOf(e.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new D(t[0],t[1],t[2])})}static directionOf(e){const{x:t,y:i,z:n}=ti(e.altitudeDeg,e.azimuthDeg,1);return new D(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=no(n.magnitude,t),o=iu(r);this.setBodyMesh(s,n.position,bu*(.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=no(n.magnitude,t),r=iu(s),o=OT[n.body]??new se(1,1,1),l=new se(o.r*r,o.g*r,o.b*r),c=bu*(.5+.5*s);this.setBodyMesh(n.body,n.position,c,l,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 Jn(n,s),o=Iu(1337),l=[],c=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const d=i.mag[h];if(d>t)break;const{altitudeDeg:u,azimuthDeg:f}=r.position(i.ra[h],i.dec[h]);if(u<iv)continue;const{x:p,y:v,z:m}=ti(u,f,gu);l.push({x:p,y:v,z:m,brightness:no(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*ft.illuminanceOf(d)),phase:o()*Math.PI*2,speedFactor:.7+o()*.6})}for(const h of iA){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<iv)continue;const{x:f,y:p,z:v}=ti(d,u,gu);this.namedStars.push({star:h,direction:new D(f,p,v).normalize(),altitudeDeg:d})}this.starTiers=yo.map((h,d)=>{const u=l.filter(w=>e0(w.brightness)===d),f=new Float32Array(u.length*3),p=new Float32Array(u.length),v=new Float32Array(u.length*3),m=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((w,E)=>{f[E*3]=w.x,f[E*3+1]=w.y,f[E*3+2]=w.z,p[E]=w.brightness,v.set(w.illuminance,E*3),m[E]=w.phase,g[E]=w.speedFactor});const x=new rt;x.setAttribute("position",new Ze(f,3)),x.setAttribute("seed",new Ze(m.map(w=>w/(2*Math.PI)),1));const y=new Ze(new Float32Array(u.length*3),3);x.setAttribute("color",y);let b=this.starTiers[d]?.points;return b?(b.geometry.dispose(),b.geometry=x):(b=new ys(x,at.material(h.size)),at.track(b),this.celestialGroup.add(b)),{points:b,colorAttribute:y,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){at.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 vo(this.celestialGroup,yu,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(Gr[0]+(xu[0]-Gr[0])*t,Gr[1]+(xu[1]-Gr[1])*t,Gr[2]+(xu[2]-Gr[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}=Vf(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=Wf(yu);this.cloudMesh=new Te(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}=Vf(new se(...Gr),e,Hc,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Te(Wf(yu*1.04),t),this.cirrusMesh.renderOrder=cv-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?vo.deckOrder(!0,0,1):cv}cloudLayerOffset(){const t=((this.weather.cloudBaseM??1e3)-this.observerElevationM)*Mu;return Math.sign(t||1)*Math.max(Math.abs(t),vT)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const n=this.cloudBeamDirection,[s,r,o]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*Tu*this.relativeScale/Math.PI,c=new se(t[0]+fs.r*l,t[1]+fs.g*l,t[2]+fs.b*l);this.layeredClouds?.setLighting(n.clone(),new se(s,r,o),c,c);const h=Math.max(0,n.y);for(const d of i)d.sunDir.value.copy(n),d.sunColor.value.setRGB(s*h,r*h,o*h),d.ambientColor.value.copy(c)}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 _T(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,_u],[this.rainSplashSystem?.points,Vr],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:Su[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=fv(Au(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=Su[e],i=t.poolSize,n=Iu(9001),s=new Float32Array(i*3),r=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let y=0;y<i;y++){const b=n()*Math.PI*2,w=n()*t.radiusM;s[y*3]=Math.cos(b)*w,s[y*3+1]=Qa+n()*(t.topYM-Qa),s[y*3+2]=Math.sin(b)*w,r[y]=n()*Math.PI*2,o[y]=.7+n()*.6,l[y]=.6+n()*.8,c[y]=.4+n()*1.2}const v=new rt;v.setAttribute("position",new Ze(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:NT(e)},uNearFocusDistance:{value:vv},uHazeDistance:{value:t.radiusM*bv}},g=new mt({uniforms:m,vertexShader:GT,fragmentShader:VT,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const x=new ys(v,g);x.renderOrder=wu,this.scene.add(x),this.precipitationPoints=x,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=o,this.precipitationWobbleFreqJitter=l,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,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=Su[i];if(this.precipitationUniforms?.uColor.value.copy(It.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*ln,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,o=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,v=this.precipitationBounceDuration,m=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,x=i==="snow"&&d&&u,y=i==="hail"&&f&&p&&v&&m&&g;for(let b=0,w=0;b<l.length;b+=3,w++){if(y&&f[w]>0){if(f[w]-=t,f[w]<=0){const M=Math.random()*Math.PI*2,I=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*I,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*I,f[w]=0}else{const M=1-f[w]/v[w];l[b+1]=Qa+Math.sin(Math.PI*M)*p[w],l[b]=Wc(l[b]+(r+m[w])*t,n.radiusM),l[b+2]=Wc(l[b+2]+(o+g[w])*t,n.radiusM)}continue}let E=0,T=0;if(x){const M=TT*d[w],I=IT*u[w];E=Math.sin(e*M*Math.PI*2+c[w])*I,T=Math.sin(e*M*Math.PI*2+c[w]+Math.PI/2)*I}if(l[b]+=(r+E)*t,l[b+1]-=n.fallSpeedMPerS*h[w]*t,l[b+2]+=(o+T)*t,l[b]=Wc(l[b],n.radiusM),l[b+2]=Wc(l[b+2],n.radiusM),l[b+1]<Qa){if(y){p[w]=Sv*(.2+Math.random()*1.6),v[w]=DT*(.5+Math.random()),f[w]=v[w];const A=Math.random()*Math.PI*2,R=RT*(p[w]/Sv);m[w]=Math.cos(A)*R,g[w]=Math.sin(A)*R,l[b+1]=Qa;continue}const M=Math.random()*Math.PI*2,I=Math.sqrt(Math.random())*n.radiusM;l[b]=Math.cos(M)*I,l[b+1]=n.topYM,l[b+2]=Math.sin(M)*I}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=Au(this.weather.precipitationIntensity);this.rainSystem=yA({count:_u,radiusM:sl,heightM:yT,bottomYM:hv,overallSpeed:MT,color:uv.clone(),opacity:.85,visibleCount:this.precipitationCount(_u),speedStreak:fv(e),pixelSize:Mv,seed:9001,nearFocusDistanceM:vv,hazeDistanceM:sl*bv,hazeColor:new se(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=wu,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=Iu(4242),t=new Float32Array(Vr*3),i=new Float32Array(Vr),n=new Float32Array(Vr),s=new Float32Array(Vr);for(let h=0;h<Vr;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*sl;t[h*3]=Math.cos(d)*u,t[h*3+1]=hv,t[h*3+2]=Math.sin(d)*u,n[h]=Ev(pv,mv),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new rt;r.setAttribute("position",new Ze(t,3));const o=new Ze(s,1);r.setAttribute("aLife",o),r.setDrawRange(0,this.precipitationCount(Vr));const l=new mt({uniforms:{uMaxSize:{value:ET},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:gv.clone()},uTexture:{value:BT()}},vertexShader:zT,fragmentShader:HT,transparent:!0,depthWrite:!1}),c=new ys(r,l);c.renderOrder=wu,this.scene.add(c),this.rainSplashSystem={points:c,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*ln;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-Au(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(It.litBySky(uv,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(It.litBySky(gv,this.baseFogColor));const n=this.weather.windDirectionDeg*ln,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,o=sl,l=h=>(h%(o*2)+o*3)%(o*2)-o;t.uniforms.uWindOffset.value.set(l(t.uniforms.uWindOffset.value.x+s*e),l(t.uniforms.uWindOffset.value.y+r*e)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const c=Math.abs(this.rainCameraDirection.y);if(Math.abs(c-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=c;const h=wv+(1-wv)*(1-c),d=xv+(1-xv)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=Mv*h*(.5+.5*d)}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 l=0,c=0;l<i.length;l+=3,c++){if(n[c]+=e,n[c]>=s[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*sl;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Ev(pv,mv),n[c]=0}o[c]=n[c]/s[c]}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 l of this.lightningFlashes){if(l.t>e)break;const c=wi.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(LT/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 l=this.scene.fog,c=s*Tu*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+fs.r*c,this.airlight[1]+fs.g*c,this.airlight[2]+fs.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*kT;r.setRGB(1+l*fs.r,1+l*fs.g,1+l*fs.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*Tu*this.relativeScale,t){const{x:l,y:c,z:h}=ti(25,t.azimuthDeg,yn);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new yr(yn*.95),this.celestialGroup.add(this.lightningBolt.object));const o=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,o),this.render()}buildCompassLabels(){this.compassSprites=lT.map(e=>{const t=da.point(e,this.compassPoints),i=new nh({map:WT(t),depthTest:!1,fog:!1}),n=new Wo(i),{x:s,y:r,z:o}=ti(0,e,rv);return n.position.set(s,r,o),n.scale.set(Vc,Vc,1),n.renderOrder=dT,n.layers.set(pu),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=av*Math.PI/360,i=Vc*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 ln=Math.PI/180;function lo(a,e,t){return Math.max(e,Math.min(t,a))}function Ev(a,e){return a+Math.random()*(e-a)}function Wc(a,e){return(a%(e*2)+e*3)%(e*2)-e}let Xc,$c;function NT(a){switch(a){case"snow":return FT();case"hail":return UT()}}function FT(){if(Xc)return Xc;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),Xc=new tr(e),Xc}function UT(){if($c)return $c;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),$c=new tr(e),$c}let Yc;function BT(){if(Yc)return Yc;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),Yc=new tr(e),Yc}const zT=`
|
|
9366
9366
|
uniform float uMaxSize;
|
|
9367
9367
|
uniform float uScale;
|
|
9368
9368
|
attribute float aLife;
|
|
@@ -9428,4 +9428,4 @@ void main() {
|
|
|
9428
9428
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
9429
9429
|
}
|
|
9430
9430
|
`;function _v(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",l="#f4f1e2";i.fillStyle=o,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const c=lo(a.illuminatedFraction,0,1),h=a.phaseFraction<.5,d=n*Math.abs(1-2*c),u=c<.5;return i.save(),i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.clip(),i.fillStyle=l,i.beginPath(),h?(i.arc(s,r,n,-Math.PI/2,Math.PI/2,!1),i.ellipse(s,r,d,n,0,Math.PI/2,-Math.PI/2,u)):(i.arc(s,r,n,Math.PI/2,-Math.PI/2,!1),i.ellipse(s,r,d,n,0,-Math.PI/2,Math.PI/2,u)),i.fill(),i.restore(),new tr(t)}function WT(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 tr(e)}function Iu(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}}class zh{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=320;paint(e,t){this.disposed||(this.wanted={t:e,canvas:t},this.pumping||this.pump())}recordingChanged(e){this.scene&&(this.scene.sightingData=e)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const e=this.create();return e.setAttribute("max-pixel-ratio","1"),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${zh.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(e),e.documentUrl=this.source.documentUrl,e.accountInTheRound=this.source.accountInTheRound,e.sightingData=this.source.sightingData,this.scene=e,e}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t:e,canvas:t}=this.wanted;this.wanted=void 0;const i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(e);for(let n=0;n<zh.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(s=>requestAnimationFrame(()=>s())),!this.wanted);n++)if(i.snapshotTo(t)){t.dataset.ready="true";break}}}finally{this.pumping=!1}}}const Du=7.5,xl=9;class gs{static cache=new Map;static load(e){let t=gs.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>gs.parse(i)),gs.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 gs.load(e[0].url);const n=i.map(r=>r.url).join(`
|
|
9431
|
-
`);let s=gs.cache.get(n);return s||(s=Promise.all(i.map(r=>gs.load(r.url))).then(r=>r.reduce((o,l)=>gs.concat(o,l))),gs.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)}}}class Hh{constructor(e){this.names=e}body(e,t){return this.names?.bodies[e]??t}star(e){return this.names?.stars[e.name]??e.name}comet(e){return this.names?.comets[e.id]??e.name}nova(e){return this.names?.novae[e.id]??e.name}satelliteClass(e){return this.names?.satelliteClasses[e.id]??e.name}shower(e){return this.names?.showers[e.id]??e.name}lightRig(e){return this.names?.lightRigs[e.id]??e.name}instrument(e){return this.names?.instruments[e.id]??e.name}decorKind(e,t){return this.names?.decorKinds[e]??t}point(e){return da.point(e,this.names?.compassPoints)}towards(e){return da.towards(e,this.names)}}const XT="Global Meteor Network",$T="https://globalmeteornetwork.org/data/",YT="“Thunder” by Jerimee",qT="https://creativecommons.org/licenses/by/3.0/",KT="CC BY 3.0";class un{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(un.text(n));const s=t.currentRoadAttribution;s&&i(un.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(un.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(un.link(h.sourceUrl,h.title),document.createTextNode(`${d} (${h.license})`)):u.textContent=`${h.title}${d} (${h.license})`,i(u)}for(const h of t.ufoElement.sighting.references){if(!h.credit)continue;const d=document.createElement("li");h.creditUrl?d.appendChild(un.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new Qn(qs.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(un.text(u))}const o=t.satelliteState;if(o.status==="ready"&&o.credit){const h=document.createElement("li");h.appendChild(un.link(o.creditUrl??"",o.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(un.link($T,XT),document.createTextNode(" (CC BY 4.0)")),i(h)}const l=t.aircraftState;if(l.status==="ready"&&l.shown>0){const h=document.createElement("li");if(h.appendChild(un.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(un.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=un.text(`${YT} (`);c.append(un.link(qT,KT),document.createTextNode(")")),i(c)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const ZT=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,jT=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,JT=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,QT=20,eI=1;class tI{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}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}}la.unlock(this.context)}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(ZT,this.ambientVolume).then(o=>this.applyIfCurrent(o,r,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/QT,1);const s=i>eI;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(jT,this.windVolume).then(o=>this.applyIfCurrent(o,r,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.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(JT,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(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(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(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(this.output(i)),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 Ws{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Ws.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*Ws.stumpffC(n),o=t-i*i*i/Math.sqrt(Ws.SUN_GM_AU3_PER_DAY2)*Ws.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(Ws.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Ws.stumpffS(l)+c*o};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let o=0;o<Ws.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);o++){const l=(r+s)/2;n(l)<i?r=l:s=l}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),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*o*l,y:s*r+n*o*l,z:o*c},{x:-n*o-s*r*l,y:-s*o+n*r*l,z:r*c}]}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 Gb=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class lh{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 Gb.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=ri(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),o=this.subtract(r,s),l=this.length(r),c=this.length(o),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(o,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,c)}}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 l=1+e.tailLengthAu/n,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,o),tailLengthDeg:this.angleBetween(h,c)}}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=So(K5(),new Vt(e.x,e.y,e.z,t)),r=So(Ib(t),s),o=I5(t,new l0(n.lat,n.lng,n.elevationM)),l=new Vt(r.x-o.x,r.y-o.y,r.z-o.z,t),c=h0(l);return d0(c.ra,c.dec,i,n)}static earthPositionAt(e){return So(q5(),Ir(_e.Earth,e))}static julianDayOf(e){return 2451545+ri(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Ws(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 Ru=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class Gh{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return Ru.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of Ru){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Jn.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 Ru.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],[l,c]=i[s]??i[0];if(l===r)return o;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return o+h*(c-o)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const iI=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],Po=6.5;class Eo{static activeAt(e){return iI.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),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,i,n=Po){if(t<=0)return 0;const s=Po-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Jn.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 jt{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=ri(e),n=new nd(0,A5(e).elon-90,1),s=So(j5(i),c0(n,i)),r=h0(s);return d0(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=Po){const i=jt.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=Po-t;return(jt.QUIET_RATE_PER_HOUR+i)/Math.pow(jt.POPULATION_INDEX,n)}static schedule(e){const t=new ad(e.seed^1542469173);return ua.schedule(e).map(i=>{const n=jt.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=jt.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:jt.toHorizontal(o),bearingDeg:jt.bearingFrom(o,n)}})}static turnAround(e,t){const[i,n]=jt.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]=jt.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=jt.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=jt.normalise(jt.cross(e,t));return[i,jt.normalise(jt.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=jt.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=jt.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return jt.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 Av="https://ufoathome.org/tle/index.json";class zi{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??zi.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(Av)||e.push(Av),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${zi.FIRST_SNAPSHOT}T00:00:00Z`)-zi.MAX_ELEMENT_AGE_DAYS*zi.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)-zi.MAX_ELEMENT_AGE_DAYS*zi.DAY_MS&&e.getTime()<=Date.parse(n.to)+zi.MAX_ELEMENT_AGE_DAYS*zi.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 l=await this.kindAt(o,e,i,n);s.push(...l),r.push(this.coverageOf(o,e,i,l.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*zi.DAY_MS,o=Math.floor(s/r),l=s-o*r<r/2?o-1:o+1,c=new Set(i.kinds[e].bins),h=[o,l].map(v=>new Date(v*r).toISOString().slice(0,10)).filter(v=>c.has(v));if(h.length===0)return[];const[d,...u]=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 u)for(const m of zi.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)/zi.DAY_MS;if(m>zi.MAX_ELEMENT_AGE_DAYS)continue;const g=d[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(),l=zi.MAX_ELEMENT_AGE_DAYS*zi.DAY_MS,c=n?"covered":o<Date.parse(s)-l?"before":o>Date.parse(r)+l?"after":"gap";return{kind:e,status:c,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 nI{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=it.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=it.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:it.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:it.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class pa{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*pa.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=pa.degOver(e)/t;return i<1?1:Math.min(pa.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Vi{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 pa.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 Vi.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??Vi.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,o=Vi.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Vi.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,i){const s=(e.detailUm??Vi.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Vi.ARCSEC_PER_RADIAN,r=1.22*Vi.WAVELENGTH_M/(i/1e3)*Vi.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/Vi.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Vi.graspOf(e,t),n=Vi.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:Et.focalLengthMmFor(e,t.fieldOfViewDeg);return Vi.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const Tv=111320,rl=Math.PI/180,sI=1.02,rI=1;class Sl{static of(e,t){const i=Sl.sightings(e,t);if(i.length<2)return;const n=Sl.baseline(i);if(!n)return;const{near:s,far:r,closedM:o}=n,l=Math.tan(r.widthDeg/2*rl)===0?0:Math.tan(s.widthDeg/2*rl)/Math.tan(r.widthDeg/2*rl);if(l<sI)return;const c=o/(l-1),h=it.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:it.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.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=et(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=Sl.closedAlongSight(i,n),[r,o,l]=s>=0?[n,i,s]:[i,n,-s];l<rI||r.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:o,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*Tv,n=(t.lng-e.lng)*Tv*Math.cos(e.lat*rl),s=(e.sightAzimuthDeg??0)*rl;return i*Math.cos(s)+n*Math.sin(s)}}class ji{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:ji.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:ji.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:ji.atLeastNearest(e.derivedM),basis:"derived"};const t=ji.largest(e.range?.minM,e.crossing?.behindM),i=ji.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*ji.MARGIN,s=i===void 0?void 0:i/ji.MARGIN;return n!==void 0&&s!==void 0?{distanceM:ji.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:ji.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<ji.CONVENTIONAL_M?{distanceM:ji.atLeastNearest(s),basis:"bounded"}:{distanceM:ji.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(ji.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 Cu=Math.PI/180;class st{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)st.collect(this.motionKeys,s.t,s.motions),st.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 st.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?st.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 l=r[o],c=r[Math.min(o+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=st.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=et(e,0),s=et(e,t),o=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ni(s.lat,s.lng,n.lat,n.lng):void 0,l=o?o.x:0,c=o?-o.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+st.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=st.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let o=0,l=0;for(;l<st.MAX_RANGE_M;){if(l=o+Math.max(.5,o*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(o+l)/2;r(h)<=0?l=h:o=h}return l}o=l}}static directionOf(e,t){const i=e*Cu,n=t*Cu;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=st.lerp(n.eastM,s.eastM,r),l=st.lerp(n.northM,s.northM,r),c={widthM:st.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:st.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:st.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},h={headingDeg:st.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:st.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:st.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let d;if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const u=st.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);d=this.groundUnderFootprint(o,l,c,h.headingDeg)+u+c.heightM/2}else d=st.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:l,upM:d,sizeM:c,attitude:h,appearance:{color:(r<1?n:s).appearance.color,albedo:st.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:st.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r)},flame:st.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(u=>u.flame!==void 0&&u.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:st.lerp(n.lengthM,s.lengthM,i),widthM:st.lerp(n.widthM,s.widthM,i),luminanceCdM2:st.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*Cu,r={eastM:Math.cos(s),northM:-Math.sin(s)},o={eastM:Math.sin(s),northM:Math.cos(s)};let l=this.ground.heightAt(e,t);for(const[c,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const d=c*i.widthM/2,u=h*i.lengthM/2;l=Math.max(l,this.ground.heightAt(e+r.eastM*d+o.eastM*u,t+r.northM*d+o.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??st.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},l={color:s.appearance?.color??n?.appearance.color??st.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??st.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??st.DEFAULT_APPEARANCE.luminanceCdM2},c=this.positionOf(s,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;n={t:s.t,...c,sizeM:r,attitude:o,appearance:l,flame:h,present:d},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?st.lineOfSightMeetsGround(i,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(n===void 0)return;const s=st.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}}class Mt{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(e,t){const i=e.track;if(i.length<2||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<t;)n++;const s=i[n],r=i[n+1],o=r.t-s.t,l=o>0?(t-s.t)/o:0,[c,h]=Mt.alongGreatCircle(s,r,l);return{lat:c,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*l)*1e3}}static viewsAt(e,t,i){const n=[];for(const s of e){const r=s.track[0]?.t??0,o=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??o;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,f=Mt.leadAt(s,t-u);if(!f)return;const p=Mt.seenFrom(i,f);if(p.altitudeDeg<0)return;const v=Math.min(Mt.FADE_MS,(d-h)/4),m=v>0?Math.min(1,(t-h)/v,(d-t)/v):1,g=-2.5*Math.log10(Math.max(m,.001)),x=l.absoluteMagnitude+5*Math.log10(p.distanceKm/Mt.STANDARD_DISTANCE_KM)+g,y=[p],b=(l.trainS??Mt.DEFAULT_TRAIN_S)*1e3;for(let w=1;w<=Mt.TRAIN_POINTS;w++){const E=Math.min(b*w/Mt.TRAIN_POINTS,t-h),T=Mt.leadAt(s,t-u-E);if(!T||(y.push(Mt.seenFrom(i,T)),E>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:p,magnitude:x,color:l.color??Mt.DEFAULT_COLOR,train:y})})}return n}static seenFrom(e,t){const i=Mt.ecef(e),n=Mt.ecef(t),s=n[0]-i[0],r=n[1]-i[1],o=n[2]-i[2],l=e.lat*Mt.DEG,c=e.lng*Mt.DEG,h=-Math.sin(c)*s+Math.cos(c)*r,d=-Math.sin(l)*Math.cos(c)*s-Math.sin(l)*Math.sin(c)*r+Math.cos(l)*o,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*o,f=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/f)/Mt.DEG,azimuthDeg:(Math.atan2(h,d)/Mt.DEG+360)%360,distanceKm:f/1e3}}static ecef(e){const t=e.lat*Mt.DEG,i=e.lng*Mt.DEG,n=Math.sin(t),s=Mt.A/Math.sqrt(1-Mt.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-Mt.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*Mt.DEG,u=h.lng*Mt.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),o=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(o);let c;if(l<1e-12)c=s;else{const h=Math.sin((1-i)*l)/Math.sin(l),d=Math.sin(i*l)/Math.sin(l);c=[s[0]*h+r[0]*d,s[1]*h+r[1]*d,s[2]*h+r[2]*d]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/Mt.DEG,Math.atan2(c[1],c[0])/Mt.DEG]}}class p0{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=p0.FIRST_DAY}}class aI{constructor(e,t,i){this.citation=e,this.covers=t,this.load=i}loading;mayCover(e){return this.covers(e)}async between(e,t,i,n){try{return await(await this.provider()).between(e,t,i,n)}catch{return{status:"failed"}}}async describe(e,t){try{return await(await this.provider()).describe?.(e,t)}catch{return}}provider(){if(!this.loading){const e=this.load();this.loading=e,e.catch(()=>{this.loading===e&&(this.loading=void 0)})}return this.loading}}const oI="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",bp=[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new aI(oI,a=>p0.mayCover(a),async()=>new(await ot(async()=>{const{AdsbLolArchiveProvider:a}=await import("./AdsbLolArchiveProvider-Ir8tinqO.js");return{AdsbLolArchiveProvider:a}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Ji{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=Ji.positionAt(e,i);if(!n)return;const s=Mt.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Ji.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>Ji.seenFrom(n,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,n=Math.sin((t.lat-e.lat)*i/2)**2+Math.cos(e.lat*i)*Math.cos(t.lat*i)*Math.sin((t.lng-e.lng)*i/2)**2;return 2*Ji.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(e){return((e+180)%360+360)%360-180}static positionAt(e,t){const i=e.points;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=t;)n++;const s=i[n],r=i[n+1]??s,o=r.t-s.t;if(o>Ji.MAX_GAP_S*1e3)return;const l=o>0?(t-s.t)/o:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*l,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*l,lng:Ji.wrapLongitude(s.lng+h*l),heightM:c*Ji.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=Ji.positionAt(e,i-500),s=Ji.positionAt(e,i+500);if(!n||!s)return;const r=Ji.unit(Mt.seenFrom(t,n.geo)),o=Ji.unit(Mt.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*o[0]+r[1]*o[1]+r[2]*o[2]));return Math.acos(l)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const Iv="https://ufoathome.org/fireballs/index.json";class Bn{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Bn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/fireballs/index.json",location.href).href),e.includes(Iv)||e.push(Iv),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Bn.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Bn.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(e).toISOString().slice(0,7),new Date(t).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=e&&r.t<=t):void 0}static seenFrom(e,t){const i=Bn.peakFraction(e),n={lat:e.from[0]+(e.to[0]-e.from[0])*i,lng:e.from[1]+(e.to[1]-e.from[1])*i,heightM:e.peakHeightKm*1e3},s=Mt.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/Mt.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,n=i+Math.max(e.durationS,.1)*1e3;return{id:`gmn-${e.id}`,track:[{t:i,lat:e.from[0],lng:e.from[1],altitudeKm:e.from[2]},{t:n,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:Bn.COLOR,trainS:Bn.TRAIN_S}]}}static peakFraction(e){const t=e.from[2]-e.to[2];return Math.abs(t)<1e-6?.5:Math.min(1,Math.max(0,(e.from[2]-e.peakHeightKm)/t))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}monthOf(e,t){let i=this.months.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(e,i)),i}}const qa=Math.PI/180,al=180/Math.PI;class hi{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=hi.projectionOf(r,i,n?.(r));if(o)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...hi.compare(l,r.id,{aim:c.aim,angular:c.angular},o),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?hi.separationDeg(i.aim,n.aim):void 0;if(r!==void 0){const c=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;r>Math.max(hi.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const o=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0;return o!==void 0&&!hi.withinSize(o)&&s.push("width"),l!==void 0&&!hi.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:o,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:hi.outlineOf(e),s=i&&i.length>0?hi.centreOf(i):e,r=hi.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const o=hi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=hi.cross(o,r);let c=1/0,h=-1/0,d=1/0,u=-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=hi.dot(p,r);if(v<=0)return;const m=Math.atan2(hi.dot(p,o),v),g=Math.atan2(hi.dot(p,l),v);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,g),u=Math.max(u,g)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*al+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*al},angular:{widthDeg:(h-c)*al,heightDeg:(u-d)*al}}}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*qa,n=t.altitudeDeg*qa,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*qa);return Math.acos(Math.max(-1,Math.min(1,s)))*al}static withinSize(e){return e<=hi.SIZE_TOLERANCE&&e>=1/hi.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"&&Bb.includes(r))for(let d=0;d<=hi.RINGS;d++){const u=d/hi.RINGS*Math.PI;for(let f=0;f<hi.SEGMENTS;f++){const p=f/hi.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(p),i*Math.sin(u)*Math.sin(p),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const f of[-n,n])s.push([d,u,f]);const l=e.attitude.headingDeg*qa,c=e.attitude.pitchDeg*qa,h=e.attitude.rollDeg*qa;return s.map(([d,u,f])=>{const p=d*Math.cos(h)+f*Math.sin(h),v=-d*Math.sin(h)+f*Math.cos(h),m=u*Math.cos(c)-v*Math.sin(c),g=u*Math.sin(c)+v*Math.cos(c);return{eastM:e.eastM+p*Math.cos(l)+m*Math.sin(l),northM:e.northM-p*Math.sin(l)+m*Math.cos(l),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}}$h();const lI={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},cI="{name} — mag {mag}, {alt}° above the horizon",hI="{name} — satellite, mag {mag}, {height} km up",Vb="satellites-change",Wb="fireballs-change",dI="aircraft-change",uI="rr0-confrontation",fI="{name} — mag {mag}, {alt}° below the horizontal",Pu="Credits",Dv="comet:",Rv="nova:",pI={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",crop:"Crop row",mound:"Stone heap",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},mI=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,gI=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,vI=-18,bI={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Lu={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class fi 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",ha,fo]}shadow;stageElement;frameElement;sceneCanvas;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new zi;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Bn;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=bp[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return fi.trafficRuntimeLoading??=ot(()=>import("./trafficRuntime-BKESmiqx.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>fi.trafficRuntime=e),fi.trafficRuntimeLoading.catch(()=>{fi.trafficRuntimeLoading=void 0}),fi.trafficRuntimeLoading}traffic;lastSun;decorMemo;starCatalogDepth=0;weatherAudio=new tI;vehicleAudio=new SM;aircraftAudio;vehicleHearing=new bh;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),l=this.naming,c=l.names,h=this.sceneRenderer.pickBodyAt(r,o);if(h){this.showHoverTooltip(e,this.bodyName(h));return}const d=this.sceneRenderer.pickDecorAt(r,o),u=d?this.ufoElement.sighting.decor.find(m=>m.id===d):void 0;if(u){this.showHoverTooltip(e,this.said.read(u.title)||l.decorKind(u.kind,pI[u.kind]));return}const f=this.trafficTooltipAt(r,o);if(f){this.showHoverTooltip(e,f);return}const p=this.sceneRenderer.pickSatelliteAt(r,o);if(p){this.showHoverTooltip(e,(c?.satelliteTooltip??hI).replace("{name}",p.name).replace("{mag}",p.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(p.heightKm).toLocaleString()));return}const v=this.sceneRenderer.pickStarAt(r,o);if(v){const m=v.star.mag,g=v.altitudeDeg,x=g<0?c?.starTooltipBelow??fI:c?.starTooltip??cI;this.showHoverTooltip(e,x.replace("{name}",l.star(v.star)).replace("{mag}",m.toLocaleString(void 0,{maximumFractionDigits:Math.abs(m)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(g)))));return}this.hoverTooltip.hidden=!0};bodyName(e){const t=e.startsWith(Dv)?e.slice(Dv.length):void 0,i=t?Gb.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(Rv)?Gh.byId(e.slice(Rv.length)):void 0;if(n)return this.naming.nova(n);const s=lI[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Hh;namesLanguage="en";async loadSceneNames(){const e=vh(qs.preferencesFor(this),uh);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await e1(e);e===this.namesLanguage&&this.applySceneNaming(new Hh(t))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((o,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,c.append(d)}s.append(c),i++})};n(this.loaderNotVideo,e),i+=6,n(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??Pu;this.creditsButton.title=t,this.creditsButton.setAttribute("aria-label",t),e.names&&this.renderLoaderText(e.names.notAVideo,e.names.isASimulation),this.sceneRenderer.setCompassPoints(e.names?.compassPoints)}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(),wi.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather($l(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;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(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${_M}</style>${EM}`,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 It(this.sceneCanvas);const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.sceneRenderer.onFirstFrameHold=s=>{t.hidden=!s,this.ufoElement.captionHeld=s},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(qu),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&un.fill(n,this)}),this.creditsButton.title=Pu,this.creditsButton.setAttribute("aria-label",Pu),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.weatherAudio.setLevel(this.ufoElement.level)),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of["pointerdown","pointerup","touchend","click","keydown"])this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Qn(qs.preferencesFor(this))}saidTexts;traceLabelsFor;traceLabels(e){const t=qs.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const n of e){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:e,language:t,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),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(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,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===ha||e===fo)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[ha,fo]){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=et(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}=ni(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(),this.aircraftAudio?.resume()}async loadFromSrc(e){const t=Sp.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.sightingData=i}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}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.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?this.ufoElement.sighting.interpretation:void 0,this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new zh(this,()=>document.createElement(Vh))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}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=it.CANVAS_HEIGHT_PX,i=Et.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:Du,url:this.getAttribute("star-catalog-src")??mI},{magnitudeLimit:xl,url:this.getAttribute("deep-star-catalog-src")??gI}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>Du?xl:Du;const n=await gs.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=xl||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=Vi.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure});return _r(vI,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Zn.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=pa.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,Zn.instants(this.decorWithTraffic(this.ufoElement.sighting),et(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:Si.fovOf(this.ufoElement.sighting,e)/t}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather($l(i,e)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),t||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,e)),t||this.pushAircraftSound(i,e),this.updateMeteorShower(i,e),this.updateLightning(i,e,t!==void 0),this.sceneRenderer.setDecor(this.decorWithTraffic(i)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??fi.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??fi.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=et(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=et(i,0),r=ii(i,0),o=Object.fromEntries(_s(ii(i,e)).map(b=>[b.id,hh(e,i.weatherTrack,r,s,n,b.id)]));this.sceneRenderer.setCloudOffset(hh(e,i.weatherTrack,r,s,n),o),this.sceneRenderer.setObserverPose(n??Lu),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(Vi.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Si.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(Dt.bodyAt(i,e,this.ufoElement.steadyObserver)),this.sceneRenderer.updateDecorAnchoring(et(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.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(e);const l=n?.lat??Lu.lat,c=n?.lng??Lu.lng,h=Un(i.event.time??{},c,i.event.utcOffsetHours),d={lat:l,lng:c,elevationM:n?.elevationM??0};this.pushSatellitesAt(h,e,d),this.ensureFireballs(h);const u=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];if(this.sceneRenderer.setReentries(u.length===0?[]:Mt.viewsAt(u,e,{lat:l,lng:c,heightM:d.elevationM})),t&&!t.sky)return;if(!h){this.sceneRenderer.setAstronomy(bI);return}const f=new Date(h.getTime()+e),p=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/pa.DEG_PER_SECOND*1e3)),v=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),m=`${Math.floor(f.getTime()/p)}|${Math.round(l/v)}|${Math.round(c/v)}|${Math.round(d.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(m===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=m;const g={...Li("Sun",f,d),magnitude:ru("Sun",f)};this.lastSun={altitudeDeg:g.altitudeDeg,azimuthDeg:g.azimuthDeg};const x={...Li("Moon",f,d),phase:ao(f),magnitude:ru("Moon",f)},y=J5.map(b=>({body:b,position:Li(b,f,d),magnitude:ru(b,f)}));this.sceneRenderer.setAstronomy({sun:g,moon:x,planets:y,comet:this.cometAt(f,d),novae:Gh.appearancesAt(f,d).map(({outburst:b,position:w,magnitude:E})=>({id:b.id,position:w,magnitude:E})),stars:this.starCatalog?{catalog:this.starCatalog,date:f,observer:d}:void 0,frame:{date:f,observer:d}}),this.ufoElement.setSunAltitude(g.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)}ensureFireballs(e){const t=this.ufoElement.sighting,i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=e?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Bn.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,fi.fireballArchive.between(n,n+i).then(o=>{r.status=o?"ready":"unavailable",r.records=o??[],r.reentries=r.records.map(l=>Bn.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Wb)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(e){const t=this.ensureTraffic(e);if(!t||t.objects.length===0)return e.decor;const i=this.decorMemo;if(i&&i.base===e.decor&&i.traffic===t.objects)return i.merged;const n=[...e.decor,...t.objects];return this.decorMemo={base:e.decor,traffic:t.objects,merged:n},n}ensureTraffic(e){const t=et(e,0),i=t?.lng===void 0?void 0:Un(e.event.time??{},t.lng,e.event.utcOffsetHours),n=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||t?.lat===void 0||t.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${t.lat.toFixed(3)},${t.lng.toFixed(3)}|${Math.round(t.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let o=fi.aircraftProviders.get(this.aircraftSource.id);if(o||fi.aircraftProviders.set(this.aircraftSource.id,o=this.aircraftSource.create()),o.mayCover&&!o.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const l={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=l;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=Ji.MAX_GAP_S*1e3,d=fi.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},f=(p,v)=>p.TrafficDecor.from(l.tracks??[],c,s,p.TrafficDecor.MAX_OBJECTS,{models:v,sunElevationAt:m=>this.sunElevationAt(m,u)});o.between(c,s-d,s+n+h).then(async p=>{if(this.traffic!==l)return;if(p.status!=="found"){l.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let v;try{v=await fi.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=p.tracks,l.set=f(v),this.startAircraftSound(l,v),this.announceTraffic(),this.describeTraffic(o,l,v,f),l.set.shown>0&&this.readUpperAir(l,v,s-d,s+n+h))})}trafficSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return t;for(const[r,o]of n.presence){if(e<o.fromMs||e>o.untilMs)continue;const l=n.flights.get(r),c=l?Ji.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:An.sunElevationDeg(s,i.observer,c.geo)})}return t}trafficTooltipAt(e,t){const i=this.sceneRenderer.pickTrafficAt(e,t),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=fi.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,o=>s.towards(o))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=fi.trafficRuntime;if(!n)return;const s=t.descriptions?.get(jn.keyOf(i)),r=et(this.ufoElement.sighting,this.lastTimeMs),o={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA($l(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,o,t.startMs+this.lastTimeMs,{ambientDbA:l}),h=c&&this.contrailAt(e,this.lastTimeMs);return c&&h?{...c,contrail:h}:c}contrailAt(e,t){const i=this.traffic?.contrails?.find(s=>s.id===e);if(!i)return;let n;for(const s of i.points){if(s.tMs>t)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(e,t){this.aircraftAudio||(this.aircraftAudio=new t.AircraftAudio,this.interacted&&this.aircraftAudio.resume(),this.aircraftAudio.setPaused(this.ufoElement.playbackState!=="playing")),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,jn.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){const i=this.aircraftAudio;if(!i)return;const n=fi.trafficRuntime,s=this.traffic,r=s?.set;if(!n||!s||!r||!s.audible||s.startMs===void 0||!s.observer){i.setVoices([]);return}const o=et(e,t),l={lat:s.observer.lat,lng:s.observer.lng,heightM:o?.elevationM??0},c=$l(e,t),h=n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,jn.keyOf,l,s.startMs+t,{ambientDbA:n.AmbientNoise.dbA(c),referenceAmplitude:n.AmbientNoise.referenceAmplitude(c)});i.setVoices(h,o?.headingDeg??0)}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(dI)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(e,t,i,n){if(!e.describe||!t.set||!t.tracks)return;const s=new Set([...t.set.flights.values()].map(c=>jn.keyOf(c))),r=t.tracks.filter(c=>s.has(jn.keyOf(c))&&c.points.length>0),o=new Map,l=new Map;await Promise.all(r.map(async c=>{const h=new Date(c.points[0].t).toISOString().slice(0,10),d=await e.describe(c,h).catch(()=>{});d&&(l.set(jn.keyOf(c),d),o.set(jn.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||o.size===0)&&(t.descriptions=l,t.models=o,t.set=n(i,o),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=this.upperAirSource??t.UPPER_AIR_SOURCES[0];let r=fi.upperAirProviders.get(s.id);r||fi.upperAirProviders.set(s.id,r=s.create());const o=await r.between(e.observer,i,n);this.traffic!==e||o.status!=="found"||(e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){!e.set||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(e.set,e.models,e.air,e.startMs))}contrailSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return t;for(const r of i.contrails){const o=n.presence.get(r.id),l=n.flights.get(r.id);if(!o||!l)continue;const c=Ji.positionAt(l,i.startMs+Math.min(o.untilMs,Math.max(o.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:An.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Li("Sun",new Date(e.t),t);return An.sunElevationDeg(i,t,e)}upperAirSource;setUpperAirSource(e){e.id!==this.upperAirSource?.id&&(this.upperAirSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(e){e.id!==this.aircraftSource.id&&(this.aircraftSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const e=this.traffic?.contrails?.length?this.upperAirSource??fi.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:e&&{credit:e.credit,creditUrl:e.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(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(Vb)))},s=fi.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,o]=await Promise.all([s.at(e),ot(()=>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=et(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 l=Un(i.event.time??{},o,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:o,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,o,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),f=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:f},f}cometAt(e,t){const i=lh.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,l=new Map,c=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(qn.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)},x=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,y=x?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,p):{};c.add(p),(x||v.aim)&&c.delete(p);const b=v.angular?.widthDeg??r.pxToDeg(v.bounds.width),w=this.sizeEstimateOf(p);w.add(b,y);const E=Sl.of(t,p);l.set(p,ji.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:E&&b>0?it.distanceMAt(E.widthM,b):void 0,range:w.distanceRangeAt(b),crossing:y}))}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 y=l.get(m);y&&l.set(p,{distanceM:y.distanceM*.999,basis:y.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[p,v]of o)d.push({sourceId:p,shape:v,distanceM:l.get(p).distanceM,renderOrder:h.indexOf(p),aim:v.aim,hidden:c.has(p)||this.interpretationShown!==void 0&&(!this.comparing||v.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=(et(t,e)?.rollDeg??0)+Dt.bodyAt(t,e,this.ufoElement.steadyObserver).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Et.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=st.eyeOf(this.ufoElement.sighting,i,n);return s?st.lineOfSightMeetsGround(s,e,t,n):void 0}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>st.eyeOf(n,u,i),r=new st(e,i,s).at(t),o=s(t);if(!r||!o)return;const l=r.eastM-o.eastM,c=r.northM-o.northM,h=r.upM-o.upM,d=Math.hypot(l,c);return{azimuthDeg:(Math.atan2(l,c)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,d)*180/Math.PI,distanceM:Math.hypot(d,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=>st.eyeOf(n,p,i),r=new st(e,i,s),o=r.at(t)?t:e.track[0]?.t,l=o===void 0?void 0:r.at(o),c=o===void 0?void 0:s(o);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.upM-c.upM,f=Math.hypot(h,d);if(!(f===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,f)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const o=this.sceneRenderer.bodyGround,l=p=>st.eyeOf(n,p,o);i&&(s=i.bodies.map(p=>new st(p,o,l).at(e)).filter(p=>p!==void 0));const c=ii(n,e),h=c.windDirectionDeg*Math.PI/180,d={x:c.windSpeed*Math.sin(h),z:-c.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,e/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],d);const u=i&&this.comparing?l(e):void 0;if(u&&(r=new hi(n.timeline).at(e,s,u,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(uI,{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&&ii(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=ii(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?Un(n,s?.lng??0,e.event.utcOffsetHours):void 0,o=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,l=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=wi.schedule({durationMs:o,seed:l,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?Un(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),l=jt.schedule({ratePerHour:jt.observedRatePerHour(jt.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:jt.TYPICAL_VELOCITY_KM_S,seed:o}),c=Eo.activeAt(n).map(d=>{const u=Eo.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:Eo.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=ua.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.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=et(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const o=Et.focalLengthMmFor(i,Si.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 is.of(t.instrument,it.CANVAS_HEIGHT_PX,Si.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new nI,this.sizeEstimates.set(e,t)),t}}const Vh="rr0-scene";function yI(){$h(),customElements.get(Vh)||customElements.define(Vh,fi)}class MI{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=Jv(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class wI{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const i=performance.now()-this.startTime;i-this.lastTick>=this.intervalMs&&(this.lastTick=i,e(i)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const xI=[{id:"echo",name:"the Echo balloons",from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:"the Iridium flares",from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:"the International Space Station",from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:"the Starlink trains",from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],SI=23493,Cv=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class Kn{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return Kn.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Kn.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return xI.filter(i=>{const n=Date.parse(`${i.from}T00:00:00Z`),s=i.to===void 0?1/0:Date.parse(`${i.to}T23:59:59Z`);return t>=n&&t<=s})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-SI;if(!(t<0))return Cv[Math.min(t,Cv.length-1)]}static visibilityAt(e,t){const i=Li("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:Kn.shadowHeightKm(i),lowOrbitLit:Kn.isLitOverhead(Kn.LOW_ORBIT_KM,i),classes:Kn.classesAt(e),trackedObjects:Kn.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Kn.FIRST_ORBIT}T00:00:00Z`)}}}const Pv="https://ufoathome.org/reentries/index.json";class fn{static MINUTE_SLACK_MS=60*6e4;static WINDOW_SLACK_MS=60*6e4;static VISIBLE_KM=1500;static VISIBLE_DEG=fn.VISIBLE_KM/111.2;static EARTH_RADIUS_KM=6371;fetchImpl;indexUrls;index;years=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??fn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/reentries/index.json",location.href).href),e.includes(Pv)||e.push(Pv),e}async credit(){return(await this.loadIndex())?.index.credit}async candidates(e,t,i){const n=await this.loadIndex();if(!n)return;const s=new Set;for(const o of[e-fn.DAY_MS,t+fn.DAY_MS])s.add(String(new Date(o).getUTCFullYear()));const r=(await Promise.all([...s].filter(o=>n.index.years.includes(o)).map(o=>this.yearOf(o,n.base)))).flat();return fn.match(r,e,t,i)}static DAY_MS=864e5;static match(e,t,i,n){const s=[];for(const o of e){if(o.inclinationDeg!==void 0&&Math.abs(n.lat)>o.inclinationDeg+fn.VISIBLE_DEG)continue;const l=Date.parse(o.precision==="day"?`${o.time}T00:00Z`:o.time);if(Number.isFinite(l))if(o.precision==="minute"){const c=l<t?t-l:l>i?l-i:0;if(c>fn.MINUTE_SLACK_MS)continue;let h;if(o.seenLat!==void 0&&o.seenLng!==void 0&&(h=fn.distanceKm(n.lat,n.lng,o.seenLat,o.seenLng),h>fn.VISIBLE_KM))continue;s.push({record:o,timeMs:l,offsetMinutes:Math.round(c/6e4),seenKm:h})}else{const c=o.precision==="day"?fn.DAY_MS/2:(o.uncertaintyHours??0)*36e5,h=o.precision==="day"?l+c:l,d=fn.WINDOW_SLACK_MS;if(h+c+d<t||h-c-d>i)continue;s.push({record:o,timeMs:h})}}const r={minute:0,hours:1,day:2};return s.sort((o,l)=>r[o.record.precision]-r[l.record.precision]||(o.record.uncertaintyHours??0)-(l.record.uncertaintyHours??0)||o.timeMs-l.timeMs)}static distanceKm(e,t,i,n){const s=Math.PI/180,r=Math.sin(e*s)*Math.sin(i*s)+Math.cos(e*s)*Math.cos(i*s)*Math.cos((n-t)*s);return fn.EARTH_RADIUS_KM*Math.acos(Math.max(-1,Math.min(1,r)))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}yearOf(e,t){let i=this.years.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.years.set(e,i)),i}}const EI="https://ufoathome.org/light-pollution/index.json";class ea{year=2015;citation="World Atlas of the artificial night sky brightness (Falchi et al. 2016, doi:10.1126/sciadv.1600377; data doi:10.5880/GFZ.1.4.2016.001, CC BY-NC 4.0)";static NATURAL_MCD=.171168;fetchImpl;indexUrls;index;tiles=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??ea.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,EI].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+ea.NATURAL_MCD)/108e6)}static mcdOf(e,t){return e===0?0:t.floorMcd*10**((e-1)/t.subdivisions)}async lookUp(e,t){const i=await this.loadIndex();if(!i)return{status:"failed"};const{index:n,base:s,present:r}=i;if(!(e<n.north&&e>=n.south))return{status:"outside"};const o=((t+180)%360+360)%360-180,l=Math.floor((n.north-e)/n.tileDeg),c=Math.floor((o+180)/n.tileDeg),h=l*(360/n.tileDeg)+c;if(!(r[h>>3]&1<<(h&7)))return{status:"natural"};const d=n.north-l*n.tileDeg,u=-180+c*n.tileDeg,f=ea.nameOf(d-n.tileDeg,u),p=await this.tile(`${s}${f}.bin`);if(!p)return{status:"failed"};const v=n.tileDeg/n.cells,m=Math.min(n.cells-1,Math.floor((d-e)/v)),g=Math.min(n.cells-1,Math.floor((o-u)/v)),x=ea.mcdOf(p[m*n.cells+g],n);return x===0?{status:"natural"}:{status:"found",lightPollution:Math.round(ea.magPerArcsec2Of(x)*100)/100,artificialMcdPerM2:x,lat:d-(m+.5)*v,lng:u+(g+.5)*v}}static nameOf(e,t){const i=`${e<0?"S":"N"}${String(Math.abs(e)).padStart(2,"0")}`,n=`${t<0?"W":"E"}${String(Math.abs(t)).padStart(3,"0")}`;return i+n}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json(),n=Uint8Array.from(atob(i.present),s=>s.charCodeAt(0));return{index:i,base:new URL(".",e).href,present:n}}catch{}})(),this.index.then(e=>{e||(this.index=void 0)}),this.index}tile(e){let t=this.tiles.get(e);return t||(t=(async()=>{try{const i=await this.fetchImpl(e);if(!i.ok||!i.body)return;const n=i.body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(n).arrayBuffer())}catch{return}})(),this.tiles.set(e,t),t.then(i=>{i||this.tiles.delete(e)})),t}}const Lv=[{id:"falchi-2015",name:"World Atlas 2015",credit:"Falchi et al. 2016, CC BY-NC 4.0",creditUrl:"https://doi.org/10.5880/GFZ.1.4.2016.001",create:()=>new ea}];class yt{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new lt;dust=new Zt;assess(e,t,i){const n=Li("Sun",e,t),s=Li("Moon",e,t),r={altitudeDeg:s.altitudeDeg,phaseAngleDeg:le.phaseAngleOf(ao(e).illuminatedFraction)},o=En.galactic(e,t),l=yt.unit(o.centre),c=yt.unit(o.rotation),h=yt.unit(o.pole),d=yt.unit(En.eclipticPole(e,t)),u=yt.unit(n),f=yt.unit(s),p=yt.normalize(yt.reject(u,d));let v,m,g=0;const x=(y,b)=>{const w=yt.unit({altitudeDeg:y,azimuthDeg:b}),E=yt.between(w,u),T=le.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:E},{...r,separationDeg:yt.between(w,f)},y,i);T>g&&(g=T);const M=Js.fromMagPerArcsec2(T),I=10**(-.4*le.EXTINCTION_PER_AIR_MASS*(le.airMass(y)-1)),A=this.galaxy.surfaceBrightnessS10(Math.atan2(yt.dot(w,c),yt.dot(w,l))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,yt.dot(w,h))))*180/Math.PI)*I;v=yt.better(v,A,M,T,y,b,E);const R=Math.max(-1,Math.min(1,yt.dot(w,d))),P=yt.normalize(yt.reject(w,d)),U=this.dust.surfaceBrightnessS10(yt.between(P,p),Math.asin(R)*180/Math.PI)*I;m=yt.better(m,U,M,T,y,b,E)};for(let y=yt.LOWEST_DEG;y<=90;y+=yt.COARSE_STEP_DEG)for(let b=0;b<360;b+=yt.COARSE_STEP_DEG)x(y,b);for(const y of[v,m]){if(!y)continue;const b=yt.FINE_SPAN_DEG,w=yt.FINE_STEP_DEG;for(let E=y.altitudeDeg-b;E<=y.altitudeDeg+b;E+=w)if(!(E<yt.LOWEST_DEG||E>90))for(let T=y.azimuthDeg-b;T<=y.azimuthDeg+b;T+=w)x(E,(T+360)%360)}return{milkyWay:v&&v.contrast>=yt.THRESHOLD_CONTRAST?v:void 0,zodiacal:m&&m.contrast>=yt.THRESHOLD_CONTRAST?m:void 0,darkestSkyMagPerArcsec2:g}}static better(e,t,i,n,s,r,o){const l=t/i;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:r,magPerArcsec2:Js.toMagPerArcsec2(t),skyMagPerArcsec2:n,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,n=Math.cos(t);return[n*Math.sin(i),Math.sin(t),-n*Math.cos(i)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,yt.dot(e,t))))*180/Math.PI}static reject(e,t){const i=yt.dot(e,t);return[e[0]-i*t[0],e[1]-i*t[1],e[2]-i*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}const _I=.5,qc=40,AI=4e5,Wr=Math.PI/180,Ka=180/Math.PI;class cn{static localDirection(e,t,i,n=new D){const s=Math.tan(t/2*Wr);return n.set((e.u*2-1)*s*i,(1-e.v*2)*s,-1).normalize()}static picturePoint(e,t,i){if(e.z>=0)return;const n=Math.tan(t/2*Wr),s=e.x/-e.z/(n*i),r=e.y/-e.z/n;return{u:(s+1)/2,v:(1-r)/2}}static worldDirection(e,t=new D){const i=e.azimuthDeg*Wr,n=e.altitudeDeg*Wr;return t.set(Math.sin(i)*Math.cos(n),Math.sin(n),-Math.cos(i)*Math.cos(n))}static aimOf(e){const t=Math.hypot(e.x,e.z);return{azimuthDeg:(Math.atan2(e.x,-e.z)*Ka+360)%360,altitudeDeg:Math.atan2(e.y,t)*Ka}}static rotationOf(e){const t=new Xt;return t.rotation.set(e.pitchDeg*Wr,-e.headingDeg*Wr,-(e.rollDeg??0)*Wr,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Ps().setFromQuaternion(e,"YXZ"),i=(-t.y*Ka%360+360)%360,n=-t.z*Ka;return{headingDeg:i,pitchDeg:t.x*Ka,rollDeg:Math.abs(n)<1e-9?0:n}}static worldDirectionOf(e,t,i,n=new D){return this.localDirection(e,t.fovDeg,i,n).applyQuaternion(this.rotationOf(t))}static picturePointOf(e,t,i){const n=e.clone().applyQuaternion(this.rotationOf(t).invert()),s=this.picturePoint(n,t.fovDeg,i);if(!(!s||s.u<0||s.u>1||s.v<0||s.v>1))return s}static solve(e,t,i,n=e.length>=3){if(e.length<2)return;if(!n)return this.solveAtField(e,t,i);let s=1,r=179;const o=(Math.sqrt(5)-1)/2;let l=r-o*(r-s),c=s+o*(r-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let f=0;f<60&&r-s>1e-4;f++){if(!h||!d)return;h.residualDeg<d.residualDeg?(r=c,c=l,d=h,l=r-o*(r-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+o*(r-s),d=this.solveAtField(e,t,c))}return h&&d?h.residualDeg<d.residualDeg?h:d:h??d}static solveAtField(e,t,i){const n=e.map(c=>this.localDirection(c.picture,i,t)),s=e.map(c=>this.worldDirection(c.scene)),r=this.triad(n,s);if(!r)return;const o=this.refine(r,n,s);return{registration:{...this.anglesOf(o),fovDeg:i},residualDeg:this.residualDeg(o,n,s)}}static triad(e,t){let i=0,n=1,s=-1;for(let h=0;h<e.length;h++)for(let d=h+1;d<e.length;d++){const u=e[h].clone().cross(e[d]).lengthSq();u>s&&(s=u,i=h,n=d)}if(s<1e-12)return;const r=(h,d)=>{const u=h.clone().normalize(),f=h.clone().cross(d).normalize(),p=f.clone().cross(u);return new $e().set(u.x,p.x,f.x,u.y,p.y,f.y,u.z,p.z,f.z)},o=r(e[i],e[n]),c=r(t[i],t[n]).multiply(o.transpose());return new qi().setFromRotationMatrix(new je().setFromMatrix3(c))}static refine(e,t,i){const n=e.clone(),s=new D;for(let r=0;r<20;r++){const o=new $e().set(0,0,0,0,0,0,0,0,0),l=o.elements,c=new D;for(let f=0;f<t.length;f++){s.copy(t[f]).applyQuaternion(n);const p=s,v=[[0,p.z,-p.y],[-p.z,0,p.x],[p.y,-p.x,0]],m=[i[f].x-p.x,i[f].y-p.y,i[f].z-p.z];for(let g=0;g<3;g++){for(let x=0;x<3;x++)for(let y=0;y<3;y++)l[x*3+g]+=v[y][g]*v[y][x];c.setComponent(g,c.getComponent(g)+v[0][g]*m[0]+v[1][g]*m[1]+v[2][g]*m[2])}}for(let f=0;f<3;f++)l[f*3+f]+=1e-9;const h=c.applyMatrix3(o.invert()),d=h.length();if(d<1e-12)break;const u=new qi().setFromAxisAngle(h.normalize(),d);if(n.premultiply(u).normalize(),d<1e-10)break}return n}static residualDeg(e,t,i){let n=0;const s=new D;for(let r=0;r<t.length;r++){s.copy(t[r]).applyQuaternion(e);const o=s.angleTo(i[r])*Ka;n+=o*o}return Math.sqrt(n/t.length)}}const kv=6371e3,ol=Math.PI/180;class co{constructor(e=t=>fetch(t).then(i=>{if(!i.ok)throw new Error(`${t}: HTTP ${i.status}`);return i.json()})){this.fetchJson=e}static API="https://api.panoramax.xyz/api";static CREDIT="Panoramax";static CREDIT_URL="https://panoramax.fr/";async nearby(e,t,i=300,n=50){const s=i/111320,r=i/(111320*Math.cos(e*ol)),o=[t-r,e-s,t+r,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${co.API}/search?bbox=${o}&limit=${n}`)).features??[]).map(h=>this.picture(h,e,t)).filter(h=>h!==void 0&&h.distanceM<=i).sort((h,d)=>h.distanceM-d.distanceM)}picture(e,t,i){const[n,s]=e.geometry.coordinates,r=e.assets.sd?.href??e.assets.hd?.href;if(!r)return;const{distanceM:o,bearingDeg:l}=co.offset(t,i,s,n),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(f=>f.name).filter(f=>!!f),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:n,distanceM:o,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:r,srcFull:e.assets.hd?.href,credit:`${co.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${co.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,i,n){const s=(i-e)*ol*kv,r=(n-t)*ol*kv*Math.cos((e+i)/2*ol);return{distanceM:Math.hypot(r,s),bearingDeg:(Math.atan2(r,s)/ol+360)%360}}}const Kc=36e5,Ov=25;class ku{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:i,start:n}=t,s=_o(e.event)??0,r=this.sampleTimings(e,n,s);let o;try{o=await this.provider.getWeather({points:r.map(l=>this.pointAt(e,l,i))})}catch{return{status:"failed",at:n}}return o?{status:"inferred",at:n,source:o.source,keyframes:o.samples.map((l,c)=>({t:r[c].t,weather:l.weather}))}:{status:"unavailable",at:n}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const i of t.keyframes)e.weatherTrack.addKeyframe(i.t,i.weather);e.weatherSource=t.source}}sampleTimes(e,t){const i=[e],n=e.getTime()+t;let s=Math.floor(e.getTime()/Kc)*Kc+Kc;for(;s<=n&&i.length<Ov;)i.push(new Date(s)),s+=Kc;return t>0&&i[i.length-1].getTime()!==n&&i.length<Ov&&i.push(new Date(n)),i}sampleTimings(e,t,i){const n=e.timeline.duration>0?e.timeline.duration:i;return i<=0||n<=0?[{time:t,t:0}]:this.sampleTimes(t,i).map(s=>{const r=(s.getTime()-t.getTime())/i;return{time:s,t:Math.round(n*Math.max(0,Math.min(1,r)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const i=e.event.time;if(i?.year===void 0||i.month===void 0||i.day===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);return n?{origin:t,start:n}:void 0}originOf(e){const t=et(e,0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return n===void 0||s===void 0?void 0:{lat:n,lng:s}}pointAt(e,t,i){const n=et(e,t.t);return{lat:n?.lat??i.lat,lng:n?.lng??i.lng,time:t.time}}}const TI=Date.UTC(1940,0,1),Nv=36e5,Fv=.25,II=.7,DI=.45,RI=.1,CI=2,PI=.3,LI=.2,kI=8,Ou=.125,OI=.05,Uv=125,Bv=100,zv=2500,Nu=3500,Fu=8e3,NI=95,FI=99,UI=[96,99],BI=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"];class Xb{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),i=Math.min(...t);if(i<TI)return;const n=new Map;for(const f of e.points){const p=this.cellKey(f);n.has(p)||n.set(p,{lat:f.lat,lng:f.lng,index:n.size})}const s=this.requestUrl([...n.values()],new Date(i),new Date(Math.max(...t))),r=this.cache.get(s);if(r)return r;const o=await this.fetchImpl(s);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<n.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:s},d=e.points.map(f=>this.sampleAt(c[n.get(this.cellKey(f)).index].hourly,f.time));if(d.some(f=>f===void 0))return;const u={samples:d,source:h};return this.cache.set(s,u),u}cellKey(e){return`${Math.round(e.lat/Fv)},${Math.round(e.lng/Fv)}`}requestUrl(e,t,i){const n=new URLSearchParams({latitude:e.map(s=>s.lat).join(","),longitude:e.map(s=>s.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:BI.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${n}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const i=this.recordAt(e,t);return i&&{time:t,weather:this.toWeather(i)}}recordAt(e,t){const i=e.time.map(o=>Date.parse(`${o}Z`)),n=t.getTime();if(i.length===0||n<i[0]-Nv||n>i[i.length-1]+Nv)return;if(n<=i[0])return this.recordFrom(e,0);if(n>=i[i.length-1])return this.recordFrom(e,i.length-1);let s=0;for(;s+1<i.length&&i[s+1]<=n;)s++;const r=i[s+1]-i[s];return this.blendRecords(this.recordFrom(e,s),this.recordFrom(e,s+1),r>0?(n-i[s])/r:0)}recordFrom(e,t){const i={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(i).some(n=>n===void 0||Number.isNaN(n))?void 0:i}blendRecords(e,t,i){if(!e||!t)return e??t;const n=(r,o)=>r+(o-r)*i,s=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:n(e.cloudCover,t.cloudCover),cloudCoverLow:n(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:n(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:n(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:n(e.precipitationMm,t.precipitationMm),snowfallCm:n(e.snowfallCm,t.snowfallCm),weatherCode:i<.5?e.weatherCode:t.weatherCode,windSpeedMs:n(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+s*i)%360+360)%360,temperatureC:n(e.temperatureC,t.temperatureC),dewPointC:n(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(Uv*(e.temperatureC-e.dewPointC),Bv,zv)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:Nu,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Fu,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=NI&&e.weatherCode<=FI,i=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),relativeHumidity:Math.round(Ys.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/kI),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":UI.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const i=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(i<=0)return 0;const n=(II*e.cloudCoverLow+DI*e.cloudCoverMid+RI*e.cloudCoverHigh)/i,s=Math.min(1,e.precipitationMm/CI);return this.clamp(n+PI*s+(t?LI:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<OI)return;const t=this.clamp(Uv*(e.temperatureC-e.dewPointC),Bv,zv);if(e.cloudCoverLow>=Ou)return Math.round(t);if(e.cloudCoverMid>=Ou)return Nu;if(e.cloudCoverHigh>=Ou)return Fu;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?Nu:Fu}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function zI(){return new Xb}const HI=5;class $b{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,i={}){const n=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});i.language&&n.set("accept-language",i.language);const s=`${this.reverseUrl}?${n}`,r=this.cache.get(s);if(r)return r[0];const o=await this.fetchImpl(s,{signal:i.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(s,c?[c]:[]),c}async search(e,t={}){const i=e.trim();if(i==="")return[];const n=this.requestUrl(i,t),s=this.cache.get(n);if(s)return s;const r=await this.fetchImpl(n,{signal:t.signal});if(!r.ok)throw new Error(`Nominatim HTTP ${r.status}`);const o=await r.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(n,l),l}requestUrl(e,t){const i=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??HI)});return t.language&&i.set("accept-language",t.language),`${this.baseUrl}?${i}`}toMatch(e){const t=e.display_name??e.name,i=this.coordinate(e.lat),n=this.coordinate(e.lon);return t&&i!==void 0&&n!==void 0?{name:t,lat:i,lng:n}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function GI(){return new $b}const VI=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new $b}],WI=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Xb}];class XI{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return m1(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const Uu=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new p1}],Hv=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new g1},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new XI}];class m0{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=m0.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class $I{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),n=this.zoneOffsetHours(e,new Date(i));if(n!==void 0)return this.zoneOffsetHours(e,new Date(i-n*36e5))??n}zoneOffsetHours(e,t){let i;try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(s=>s.type==="timeZoneName")?.value??""}catch{return}const n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(i);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[3])/60):0}}function zs(a,e){return a.find(t=>t.id===e)??a[0]}class YI{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const n=await fetch(i.toString());if(!n.ok)return;const s=await n.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const qI=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new YI}],KI={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)",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},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"},yp={...KI,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the observer's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",previousKeyframe:"Previous keyframe",nextKeyframe:"Next keyframe",keyframeMark:"Keyframe",shapesTrack:"shapes",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",confirmDeleteMilestone:"Stop naming moment {name}? The recording itself is unchanged.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The observer's altitude above sea level — the ground at the location entered sets its floor: an observer in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",shapesSubgroup:"Shapes",bodiesSubgroup:"Bodies",soundGroup:"Sound",temporalGroup:"Moment",timeQualifierExact:"Exact",timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Location",observationGroup:"Observation",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't an account: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the observer reported, which then override the record.",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",lightPollutionLookingUp:"Looking up the atlas…",lightPollutionFound:"{artificial} µcd/m² of artificial light,",lightPollutionNatural:"No artificial light here,",lightPollutionOutside:"Beyond the atlas (85°N to 60°S),",lightPollutionFailed:"Atlas unreachable for now",lightPollutionTooEarly:"The atlas describes {atlasYear}; the sky of {year} was darker, give it yourself if it is known",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",fieldOfViewReadout:"{deg}° of field",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the observer's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the observer's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",traceImport:"Investigator's lines (KML, KMZ)",trace:"Trace",deleteTrace:"Delete trace",traceTitle:"Name",traceSource:"Source",traceImported:"{n} imported from {name}.",traceSkipped:"Left out: {what}.",traceNone:"No line, place or outline found in this file.",traceFailed:"This file could not be read.",traceKindPoint:"place",traceKindLine:"line",traceKindPolygon:"outline",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the observer's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the observer's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skyNova:"{name}, a new star of magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyNovaBelowHorizon:"{name} was shining at magnitude {magnitude}, but below the horizon: nobody here saw it",showNova:"Show me the new star",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",skyReentries:"re-entries on record: {list}",skyReentriesMore:"{count} more",skyReentrySeen:"{name} came down at {time}, seen from {place} ({distance} km away)",skyReentryObserved:"{name} came down at {time}, seen",skyReentryOffset:", {minutes} min outside the observation",skyReentryPredicted:"{name} came down around {time} ± {hours} h, where unknown",skyReentryDay:"{name} came down on {date} (UTC), neither hour nor place known",skyFireballs:"{count} fireballs recorded by the Global Meteor Network, the brightest magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",skyFireballsOne:"a fireball recorded by the Global Meteor Network: magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",showFireball:"Show me the fireball",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the observer",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a faint tilted cone of light with blurred edges, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTowns:"no Milky Way and no zodiacal light: the towns' glow held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the observer: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",decorSightingUrl:"Their own recording URL",viewAccount:"View the account",noObserverRecording:"No recording URL set for this observer",masks:"Masks",addObserver:"Add observer",narrativePlaceholder:"What the observer reported, in their own words",narrativeSource:"Drafted by",narrativeNeedsSetting:'Fill in "{setting}" ({source}) to generate a reconstruction from the account',narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the observer said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",observerAge:"Age then",observerOccupation:"Occupation",accountSource:"Account obtained",accountUrl:"Source (URL)",accountSourceUnknown:"unknown",accountSourceOnSite:"on-site investigation",accountSourceInterview:"interview in person",accountSourceTelephone:"by telephone",accountSourceQuestionnaire:"questionnaire",accountSourceLetter:"the observer wrote it",accountSourceSocialMedia:"the observer posted it online",accountSourcePress:"press or broadcast",accountFollowedUp:"Followed up",accountUnknown:"unknown",accountYes:"yes",accountNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},ZI=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:yp},Symbol.toStringTag,{value:"Module"})),Gv=new Set;$h();yI();const Za={width:48,height:28},jI=2500,Vv=40,JI=10,Wv=600,Xv=900,ja=2e-4,QI=900,e4=-1.46,t4=3,Zc=.2,i4=3,n4=.01,s4=1.6,Bu=2e3,r4=250,$v=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),pr=4,ll="ufo-1",Yv=["oval","polygon"],a4={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function o4(a){return a.kind==="oval"?"oval":"polygon"}const l4=-6,c4=21;class qt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=qI[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;autoFilledTimeZone;timeZones=new $I;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=GI();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsTimeNativeInput;obsEndTimeNativeInput;obsTimeQualifier;obsEndTimeQualifier;edtfModeButton;edtfMode=!1;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new ku(zI());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=oh[0].create();confirmOverlay;confirmMessage;confirmAcceptButton;confirmDeclineButton;confirmAnswer;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorCrop;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=yp;currentAppearance={...a4};currentSourceId=ll;selectedSourceIds=new Set([ll]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new co;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.confirmOverlay.hidden||this.answerConfirm(!1),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),$v.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;$v.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0;this.endDrag(),e!==void 0&&this.selectDecor(e)};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${qy}</style>${Yy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(Vh),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.setAttribute(ha,""),this.sceneElement.animateWhilePaused=!0,this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",t=>{const{lat:i,lng:n}=t.detail;this.latInput.value=String(Number(i.toFixed(6))),this.lngInput.value=String(Number(n.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new ml(this.seekInput,this.shadow.getElementById("timeline-marks")),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.switchTimeDisplay()),t.addEventListener("keydown",i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),this.switchTimeDisplay())});this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.obsTimeNativeInput=this.shadow.getElementById("obs-time-native"),this.obsEndTimeNativeInput=this.shadow.getElementById("obs-end-time-native"),this.obsTimeQualifier=this.shadow.getElementById("obs-time-qualifier"),this.obsEndTimeQualifier=this.shadow.getElementById("obs-end-time-qualifier"),this.edtfModeButton=this.shadow.getElementById("edtf-mode"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.labelTrace=this.shadow.getElementById("label-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.confirmOverlay=this.shadow.getElementById("confirm-overlay"),this.confirmMessage=this.shadow.getElementById("confirm-message"),this.confirmAcceptButton=this.shadow.getElementById("confirm-ok"),this.confirmDeclineButton=this.shadow.getElementById("confirm-cancel"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>{this.focus({preventScroll:!0}),this.onPointerDown(t)}),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()}),this.lightPollutionInput.addEventListener("input",()=>{const t=this.ufoElement.sighting;t.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),t.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),t.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeSettings()),this.renderNarrativeSettings(),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const t of this.referenceFields)t.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onReferenceWheel(t),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onBodyWheel(t),{passive:!1});for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const t of[this.milestoneLabelInput,this.milestoneNoteInput])t.addEventListener("input",()=>this.updateMilestone());this.confirmAcceptButton.addEventListener("click",()=>this.answerConfirm(!0)),this.confirmDeclineButton.addEventListener("click",()=>this.answerConfirm(!1)),this.confirmOverlay.addEventListener("click",t=>{t.target===this.confirmOverlay&&this.answerConfirm(!1)});for(const t of xa)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(Wb,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Vb,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const t of Yv)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());for(const t of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.instrumentSelect.addEventListener("change",()=>{const t=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const i=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(n=>[n.t,Si.fovOf(this.ufoElement.sighting,n.t)]));this.retuneFieldOfView(t),this.retuneExposure(t),Si.reproject(this.ufoElement.sighting,t,i),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()}),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.obsTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.edtfModeButton.addEventListener("click",()=>this.setEdtfMode(!this.edtfMode)),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])t.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields){if(t===this.iceCrystalAlignmentInput){t.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}t.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(t=>this.shadow.getElementById(t.getAttribute("aria-controls")));for(const t of this.groupTabs)t.addEventListener("click",()=>this.toggleGroup(t,!this.isGroupOpen(t)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const t of this.subgroupTabs)t.addEventListener("click",()=>this.openSubgroup(t));Gi.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dd(this.messages,this.naming,this.said,this.tagNames),this.paramSummary.addEventListener("click",t=>this.onParamSummaryClick(t)),this.toggleGroup(this.groupTabs[this.groupTabs.length-1],!0),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=Ny(this.shadow.getElementById("cloud-editor"),this.sceneElement,(t=!0)=>{t&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(t,i)=>{this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.updateObserver()},vh(qs.preferencesFor(this),uh)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeQualifierOptions(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),qs.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??ll,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)}),i=JSON.parse(t);this.sceneElement.documentUrl=void 0,this.sightingData=i,this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{const t=await Sp.json(e);this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=t,this.importUrlInput.value=new URL(e,location.href).href}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Xr))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=ql[0].create();get narrativeSourceId(){return zs(ql,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:qt.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Mn&&i.kind==="cancelled";this.narrativeStatus.textContent=n?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!n)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:n,...s}=i,r=i.timeZone?s:i,o=vs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Yu(this.ufoElement.sighting);this.sightingData=vs.apply(c,gh.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,n=new Set(t);for(const s of e.claims)!n.has(s.path)&&!t.some(r=>s.path.startsWith(`${r}.`))||i.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:qt.valueAt(Yu(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let i=e;for(const n of t.split(".")){if(typeof i!="object"||i===null)return;i=i[n]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(n=>n.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[h4[t]]));for(const n of i){const s=document.createElement("div");s.className=`claim ${t}`;const r=document.createElement("code");r.textContent=n.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const n=document.createElement("li");n.textContent=i,t.append(n)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=zs(ql,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(n=>n.required&&(this.narrativeSettingInputs.get(n.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"",this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.settings.some(n=>n.remembered==="credential");for(const n of this.narrativeProvider.settings){const s=this.narrativeSettingInputs.get(n.id);if(!s||!n.suspect)continue;const r=s.value.trim(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":this.said.read(n.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const n=document.createElement("label"),s=document.createElement("span");s.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),n.append(s,document.createTextNode(" "),r),n});this.narrativeSettingsBox.replaceChildren(...t),this.narrativeRememberInput.checked=this.narrativeProvider.settings.some(i=>i.remembered==="credential"&&this.storedNarrativeSetting(i.id)!==void 0),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const n=i.value.trim();n!==""&&(e[t]=n)}return e}narrativeErrorFor(e){if(!(e instanceof Mn))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeSettings(){try{for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";(e.remembered==="preference"||e.remembered==="credential"&&this.narrativeRememberInput.checked)&&i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}localStorage.removeItem(qt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(qt.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){try{const t=localStorage.getItem(this.narrativeStorageKey(e));if(t!==null)return t;if(this.narrativeSourceId!=="claude")return;const i=e==="key"?qt.NARRATIVE_KEY_STORAGE:e==="workspace"?qt.NARRATIVE_SCOPE_STORAGE:void 0;return i&&localStorage.getItem(i)||void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",VI,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",WI,e=>{this.weatherInference=new ku(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",Lv,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",ql,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uu,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,Hv,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,bp,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,oh,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=zs(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(zs(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:zs(Uu,this.chosenSourceId.get("elevation")).create(),imagery:zs(Hv,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(zs(bp,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=zs(oh,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<ja&&Math.abs(t-this.namedCoordinates.lng)<ja||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),Xv))}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&i!==this.autoFilledTimeZone)return;const n=this.timeZoneLookedUpAt;n&&Math.abs(e-n.lat)<ja&&Math.abs(t-n.lng)<ja||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),Xv))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t),n=this.ufoElement.sighting.event.timeZone;!i||n&&n!==this.autoFilledTimeZone||this.timeZones.available().includes(i)&&(this.autoFilledTimeZone=i,this.timeZoneSelect.value=i,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const i=++this.placeSearchToken;let n;try{n=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}i===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=n?.name??"",this.placeNameInput.title=n?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=n?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!n,this.updateObserver())}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),n=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,f=this.numberOrUndefined(this.focalLengthInput.value),p=(u.frame&&f!==void 0?Et.fieldOfViewDegAt(u,f):f)??this.currentFovDeg(),v=this.numberOrUndefined(this.fNumberInput.value),m=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=m===u.exposureSeconds?void 0:m;const g=this.numberOrUndefined(this.focusDistanceInput.value),x=Math.abs(p-Et.fieldOfViewDeg(u))>.01||v!==u.fNumber||g!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!x?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:p,fNumber:v,focusDistanceM:g}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const i=e.value.trim();if(i==="")t(void 0);else{const n=I0(i);if(!n)return;t(n)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&_o({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||I0(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(n=>{const s=document.createElement("option");return s.value=n,s.textContent=n,s})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.stringOrUndefined(this.observerTitleInput.value),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0};e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.account=Object.values(i).some(n=>n!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...n]=e.sources??[],{url:s,...r}=i??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...ii(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...ii(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(n=>n.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>AI?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const r=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||qc))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg;return{...s,kind:this.referenceKindSelect.value,src:r,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:o,from:c?this.observerPositionNow()??s.from:s.from}});const n=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(n),this.syncReferenceStatus(n),this.ufoElement.refresh()}useObserverPoseForReference(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const n=this.ufoElement.sighting,s=et(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:_I,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:qc},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const n=this.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&cn.picturePointOf(this.directionAtCanvasPoint(e),t.registration,n)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(cn.worldDirectionOf(s.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=n)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(cn.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=n)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const n=i.x-t.startPointer.x,s=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(n,s)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+n*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const n=this.currentReference(),s=n?this.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:cn.aimOf(r)};const l=cn.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||qc,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=cn.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:cn.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=cn.solve(i,t,e.registration.fovDeg);n?(this.referenceFit={n:i.length,residualDeg:n.residualDeg},this.referenceHeadingInput.value=String(this.rounded(n.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(n.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(n.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(n.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return cn.worldDirectionOf(e.picture,t.registration,i).angleTo(cn.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const n=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=n===void 0,this.referenceLandmarkLabelInput.disabled=n===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(n?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.sceneElement.referenceAspect(t.id);if(i===void 0)return;const{registration:n}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(cn.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(cn.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(cn.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(cn.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:n}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(n??0)),this.updateObserver();const s=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=et(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const n=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(n))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:qc}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,t);this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(n=>n.id!==this.currentTraceId?n:{...n,title:this.said.write(n.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(n.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(n=>n.value===this.currentTraceId),i=e.traces.find(n=>n.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await ot(async()=>{const{KmlImport:d}=await import("./KmlImport-ByKlq2_E.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const f=new FileReader;f.onload=()=>d(f.result),f.onerror=()=>u(f.error),f.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,this.ufoElement.refresh()}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of yy){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),jI)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=xp(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new ku(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),Wv))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const n=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=n,this.labelWeatherInferred.title=n;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&Un(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=Lv[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),Wv)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,n=this.lightPollutionProvider,s=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||s===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(s<n.year){r(),this.lightPollutionLookup={status:"too-early",year:s},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=_o(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=_y(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",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),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[n,s]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])n.title=s,n.setAttribute("aria-label",s);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,n]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${n} — ${t}`:n,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}static TIME_QUALIFIERS=[{value:"",key:"timeQualifierExact"},{value:"~",key:"timeQualifierApproximate"},{value:"?",key:"timeQualifierUncertain"},{value:"%",key:"timeQualifierBoth"}];refreshTimeQualifierOptions(){for(const e of[this.obsTimeQualifier,this.obsEndTimeQualifier]){const t=e.value;e.replaceChildren(...qt.TIME_QUALIFIERS.map(i=>{const n=document.createElement("option");return n.value=i.value,n.textContent=this.messages[i.key],n})),e.value=t}}qualifierOf(e){const t=e.trim().slice(-1);return"?~%".includes(t)?t:""}isPickable(e){return e?e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0:!1}pickerValueOf(e){if(!this.isPickable(e))return"";const t=(n,s=2)=>String(n).padStart(s,"0"),i=e.second?`:${t(e.second)}`:"";return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}${i}`}static stepFor(e){return e?.second?"1":"60"}writeFromPicker(e,t,i,n){e.value===""&&e.validity.badInput||(i.value=e.value===""?"":`${e.value.replace(/\.\d+$/,"")}${t.value}`,n())}chooseTimeInputMode(){const e=this.ufoElement.sighting.event,t=i=>i===void 0||this.isPickable(i);this.setEdtfMode(!(t(e.time)&&t(e.endTime)))}setEdtfMode(e){this.edtfMode=e,this.edtfModeButton.setAttribute("aria-pressed",String(e));for(const[t,i,n]of[[this.obsTimeInput,this.obsTimeNativeInput,this.obsTimeQualifier],[this.obsEndTimeInput,this.obsEndTimeNativeInput,this.obsEndTimeQualifier]])t.hidden=!e,i.hidden=e,n.hidden=e}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?dh(e):"",this.obsTimeNativeInput.step=qt.stepFor(e),this.obsTimeNativeInput.value=this.pickerValueOf(e),this.obsTimeQualifier.value=this.qualifierOf(this.obsTimeInput.value),this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?dh(e):"",this.obsEndTimeNativeInput.step=qt.stepFor(e),this.obsEndTimeNativeInput.value=this.pickerValueOf(e),this.obsEndTimeQualifier.value=this.qualifierOf(this.obsEndTimeInput.value),this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),n=e!==void 0&&i!==void 0&&Math.abs(e-i)>t4;this.utcOffsetInput.classList.toggle("invalid",n),this.utcOffsetInput.title=n?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),QI))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<ja&&Math.abs(e.lng-i)<ja}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=zs(Uu,this.chosenSourceId.get("elevation")),s=await new m0(n.create()).at(e,t);if(i!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(r),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(et(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=ii(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??.65)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],n=this.shadow.activeElement;n!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),n!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),n!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),n!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),n!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=i.getInterpolatedShapeAt(n,this.currentSourceId),r=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(n,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const n=A0(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[i,n]of this.groupTabs.entries()){const s=n===e&&t;n.setAttribute("aria-expanded",String(s)),this.groupPanels[i].hidden=!s}this.syncCanvasMode(),this.refreshTimelineMarks()}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?n():this.isGroupIdOpen("group-weather")?s():this.isGroupIdOpen("group-sound")?r():[...i(!1),...n(),...s(),...r()];for(const l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")?"shape":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",n=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:void 0,n&&this.ufoElement.refresh(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability(),this.syncBodiesShown()}syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=t!==void 0,this.sceneElement.interpretation!==t&&(this.sceneElement.interpretation=t)}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const n=i===e;i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),this.syncCanvasMode()}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,groundElevationM:this.groundElevationM??0}).map(n=>({...n,panel:qt.SUMMARY_GROUPS.indexOf(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=qt.NESTED_GROUPS,t=[];let i;for(const n of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==n.group&&(i=void 0),e.includes(n.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=n.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:qt.tabLabel(this.groupTabs[qt.SUMMARY_GROUPS.indexOf(n.group)]),r.append(o),i={group:n.group,element:r},t.push(r)}const s=this.paramChip(n);i?i.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t)}static NESTED_GROUPS=["observer","decor","assessment"];static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new Gy(this.messages).read(this.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=qt.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(qt.QUESTION_FIELDS))for(const o of qt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(qt.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),o=i.get(r)??0,l=r===n,c=qt.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:o4(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,it.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,it.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(it.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(it.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Et.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=qt.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=et(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Et.fieldOfViewDeg(t),r=n?Et.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),Gi.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":qt.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Et.fieldOfViewDeg(e),n=Et.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>n4||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return et(e,this.ufoElement.currentTime)?.fovDeg??Et.fieldOfViewDeg(e.instrument)}currentProjection(){return is.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=it.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=et(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?Et.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Gu*e/l*i.heightMm,h=r*r/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(v,m)=>Number(v.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??JI,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(it.sizeMAt(c,h),2),lengthM:n(it.sizeMAt(c,h),2),heightM:n(it.sizeMAt(c,d),2)}:void 0,f={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},p={t,...f,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=ot(async()=>{const{BodyEditor:e}=await import("./BodyEditor-B_FBjZDB.js");return{BodyEditor:e}},__vite__mapDeps([3,4]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,modelProvider:()=>this.decorModelProvider,shapes:()=>this.ufoElement.sighting.timeline.sourceIds.map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:it.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=is.of(i.instrument,it.CANVAS_HEIGHT_PX,Si.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Si.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(n=>this.selectedSourceIds.has(n));if(t.length===0)return;const i=t.length===1?this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0])):this.messages.confirmDeleteShapes.replace("{count}",String(t.length));this.askConfirm(i,()=>this.removeShapes(t))}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??ll,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}askConfirm(e,t){this.answerConfirm(!1),this.confirmMessage.textContent=e,this.confirmOverlay.hidden=!1,this.confirmAcceptButton.focus(),this.confirmAnswer=t}answerConfirm(e){const t=this.confirmAnswer;this.confirmAnswer=void 0,this.confirmOverlay.hidden=!0,e&&t?.()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){const t=this.ufoElement.sighting,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:ho}:{},windows:n1(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh()}defaultAircraft(){const e=2*Bu,t=Math.round(e/r4*1e3);return{lights:hd.byId("airliner")?.create(),track:[{t:0,eastM:-Bu,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Bu,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(f=>f.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((f,p)=>f.t-p.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?gi.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??""))}shownDecorEntry;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);if(t?.sizeM&&i&&!i.sizeM){const n=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[s,r]of n)r!==void 0&&(s.value=String(this.roundedMeters(r)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=ca([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&this.askConfirm(this.messages.confirmDeleteMilestone.replace("{name}",this.said.read(i.label)??""),()=>{t.milestones=t.milestones.filter(n=>n.t!==e),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh()})}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=ca(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const i={};for(const n of xa){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Wu(t.kind,n)?0:Vu,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?mh(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??ho),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of xa){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,i=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!t,this.setRowVisible(this.decorLitInput,t&&e?.kind!=="aircraft");const n=t&&i!==void 0&&_p(i);this.setRowVisible(this.labelDecorWindows,n);const s=i!==void 0?Ep(i):[];for(const c of xa)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(i!==void 0&&Wu(i,c)?0:Vu),this.setRowVisible(this.decorWindowInputs[c],n&&s.includes(c));const r=t&&i!==void 0&&eo(i);this.setRowVisible(this.decorObserverSideSelect,r);const o=i!==void 0?Vy(i):[];for(const c of xa)this.optionObserverSide[c].hidden=!o.includes(c);const l=t&&i==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ho)}showDecorPlacement(e){const t=e?Dr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new fn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Hh;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new Qn(["en"]);tagNames=new $u({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Un(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,ii(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return Vi.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Li("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=_r(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<e4)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(_r(i,0,s)));return r<=xl?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(xl))}showerClause(e,t){const i=jt.observedRatePerHour(jt.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=Eo.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=Eo.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Eo.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=lh.brightestAt(e,t);if(!i||i.magnitude>Po){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Gh.brightestAt(e,t);if(!i||i.magnitude>Po){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Kn.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=_r(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,qt.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Kn.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Li("Sun",i.peak.date,t);return n<=_r(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=et(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Un(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>Bn.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Bn.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=ii(this.ufoElement.sighting,0),n=Li("Sun",e,t),s=Li("Moon",e,t),r=ht.deckLitUntilDeg(ht.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(ht.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(ht.formsAt(l.altitudeDeg,r).map(f=>this.opticsFormName(f))),u=i.iceCrystalAlignment??.65;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=ii(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Li("Sun",e,t),s=Li("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(Wi.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Wi.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(Wi.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(ao(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Li("Sun",e,t);if(i.altitudeDeg>l4)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const f=n.zodiacal.sunSeparationDeg<=yt.CONE_SEPARATION_DEG;s.push((f?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),o=Li("Moon",e,t),l=n.darkestSkyMagPerArcsec2<c4,c=this.ufoElement.sighting.lightPollution,h=le.scatteringAt(90-o.altitudeDeg)*le.moonOutput(le.phaseAngleOf(ao(e).illuminatedFraction),o.altitudeDeg)*le.scatteredFraction(90),d=le.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const f=Math.round(ao(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(f)).replace("{sky}",r)}const u=le.artificialZenithNanolamberts(c)>le.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Li("Sun",e,t),n=Li("Moon",e,t);return le.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:le.phaseAngleOf(ao(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new yt;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<lh.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=lh.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Gh.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=Dr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-s4,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?hd.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=hd.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=mh(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of Yv)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return A0(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Za.width/2,y:e.height/2-Za.height/2,width:Za.width,height:Za.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new MI(this.ufoElement.sighting.timeline,new wI(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=++this.localeToken,t=qs.preferencesFor(this);this.preferences=t;const i=vh(t,uh),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[yp,{},void 0]:await Promise.all([Py(i),Ly(i),e1(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Hh(o),this.said=new Qn(t),this.tagNames=new $u(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dd(s,this.naming,this.said,this.tagNames),this.refreshParamSummary()),l?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===ll&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(n);r&&(r.textContent=s)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.confirmAcceptButton.textContent=e.confirmAccept,this.confirmDeclineButton.textContent=e.confirmDecline,this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of xa)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.refreshTimeQualifierOptions(),this.edtfModeButton.title=e.edtfModeTitle,this.edtfModeButton.setAttribute("aria-label",e.edtfModeTitle),this.paramSummaryBuilder=new dd(e,this.naming,this.said,this.tagNames),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);return}const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new cd(this.selectedMembers()),d=wt.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(r)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?wt.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&wt.hitTestHandle(h,t);if(h&&u){if(r)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Gv);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){r?this.selectDecor(h):this.beginCameraDrag(t,h);return}r||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),r||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:n.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,o)=>s.indexOf(r)-s.indexOf(o)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,o=s?.kind==="polygon"&&wt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Gv);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(f=>this.selectedSourceIds.has(f)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(f=>this.selectedSourceIds.has(f)),o=n.length>0&&i.slice(0,n.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?wt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=i1;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const i=document.createElement("label"),n=document.createElement("input");n.type="checkbox",n.checked=e.occludesSourceIds?.includes(t)??!1,n.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,n.checked)),i.appendChild(n),i.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(i)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=wt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=wt.hitTestVertex(i,e);if(n===void 0)return;const s=wt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId,t=e===void 0?void 0:this.sceneElement.bodyScreenBox(e);if(!t)return;const i=this.ufoElement.canvasElement,n=Math.max(Vv,(t.maxX-t.minX)/2*i.width),s=Math.max(Vv,(t.maxY-t.minY)/2*i.height),r=((t.minX+t.maxX)/2+1)/2*i.width,o=(1-(t.minY+t.maxY)/2)/2*i.height;return{x:r-n/2,y:o-s/2,width:n,height:s}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginBodyHandleDrag(e){const t=this.bodyCanvasBounds(),i=this.bodyEditor?.readingNow();if(!t||!i)return!1;const n=wt.hitTestHandle({bounds:t,angle:0},e);if(!n)return!1;if(n==="rotate")this.dragState={kind:"body-rotate",startPointer:e,startAttitude:{...i.attitude}};else{const s={x:t.x+t.width/2,y:t.y+t.height/2};this.dragState={kind:"body-resize",handle:n,centre:s,startPointer:e,startSizeM:{...i.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,0)),this.startDragListening(),!0}onBodyHandleDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="body-rotate"){const u=(i.x-t.startPointer.x)*Zc,f=(t.startPointer.y-i.y)*Zc,p=t.startAttitude;this.bodyEditor?.turnTo(e.shiftKey?{headingDeg:p.headingDeg,pitchDeg:p.pitchDeg+f,rollDeg:p.rollDeg+u}:{headingDeg:p.headingDeg+u,pitchDeg:p.pitchDeg,rollDeg:p.rollDeg});return}if(t.kind!=="body-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:o}=t,l=(u,f)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(f))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));this.bodyEditor?.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="body-resize"||this.dragState?.kind==="body-rotate"){this.onBodyHandleDragPointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,o=wt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?wt.resizeShape(r,o,t):wt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<i4)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Zc,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Zc));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(xr,i.width-pr);break;case"ArrowRight":i.width+=pr;break;case"ArrowUp":i.height=Math.max(xr,i.height-pr);break;case"ArrowDown":i.height+=pr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=pr;break;case"ArrowRight":i.x+=pr;break;case"ArrowUp":i.y-=pr;break;case"ArrowDown":i.y+=pr;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new cd(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const l=r?this.bodyCanvasBounds():void 0,c=l&&wt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=wt.hitTestHandle({bounds:new cd(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&wt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&wt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${wt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(Jv(this.buildPrototype({x:0,y:0,width:Za.width,height:Za.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const h4={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},qv="rr0-sighting-editor",Kv="rr0-ufo-recorder";class d4 extends qt{}function u4(){$h(),customElements.get(qv)||customElements.define(qv,qt),customElements.get(Kv)||customElements.define(Kv,d4)}u4();export{aw as $,la as A,Bb as B,se as C,fM as D,Ze as E,pt as F,Nt as G,Rn as H,T4 as I,nn as J,p4 as K,Xu as L,Te as M,Gi as N,g4 as O,G1 as P,m4 as Q,Mt as R,Sl as S,jn as T,uh as U,D as V,x4 as W,Hl as X,A4 as Y,S4 as Z,ot as _,Ji as a,Eh as a0,tn as a1,_4 as a2,j1 as a3,Xm as a4,y4 as a5,qi as a6,Tm as a7,Xt as a8,E4 as a9,Ci as aA,K1 as aB,$p as aC,Yp as aD,dt as aE,Rr as aF,zl as aG,I4 as aa,U1 as ab,ia as ac,Jl as ad,vd as ae,qM as af,ut as ag,Ot as ah,Cl as ai,sf as aj,ki as ak,er as al,ew as am,jr as an,Pt as ao,b4 as ap,M4 as aq,H1 as ar,w4 as as,mn as at,rs as au,z1 as av,Bm as aw,q2 as ax,wh as ay,Of as az,oI as b,p0 as c,Li as d,D4 as e,Ih as f,sn as g,Qs as h,mt as i,Ms as j,nw as k,f4 as l,ye as m,me as n,ct as o,Yu as p,R4 as q,je as r,Un as s,v4 as t,rt as u,ys as v,nh as w,tr as x,Wo as y,ni as z};
|
|
9431
|
+
`);let s=gs.cache.get(n);return s||(s=Promise.all(i.map(r=>gs.load(r.url))).then(r=>r.reduce((o,l)=>gs.concat(o,l))),gs.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)}}}class Hh{constructor(e){this.names=e}body(e,t){return this.names?.bodies[e]??t}star(e){return this.names?.stars[e.name]??e.name}comet(e){return this.names?.comets[e.id]??e.name}nova(e){return this.names?.novae[e.id]??e.name}satelliteClass(e){return this.names?.satelliteClasses[e.id]??e.name}shower(e){return this.names?.showers[e.id]??e.name}lightRig(e){return this.names?.lightRigs[e.id]??e.name}instrument(e){return this.names?.instruments[e.id]??e.name}decorKind(e,t){return this.names?.decorKinds[e]??t}point(e){return da.point(e,this.names?.compassPoints)}towards(e){return da.towards(e,this.names)}}const XT="Global Meteor Network",$T="https://globalmeteornetwork.org/data/",YT="“Thunder” by Jerimee",qT="https://creativecommons.org/licenses/by/3.0/",KT="CC BY 3.0";class un{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(un.text(n));const s=t.currentRoadAttribution;s&&i(un.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(un.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(un.link(h.sourceUrl,h.title),document.createTextNode(`${d} (${h.license})`)):u.textContent=`${h.title}${d} (${h.license})`,i(u)}for(const h of t.ufoElement.sighting.references){if(!h.credit)continue;const d=document.createElement("li");h.creditUrl?d.appendChild(un.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new Qn(qs.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(un.text(u))}const o=t.satelliteState;if(o.status==="ready"&&o.credit){const h=document.createElement("li");h.appendChild(un.link(o.creditUrl??"",o.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(un.link($T,XT),document.createTextNode(" (CC BY 4.0)")),i(h)}const l=t.aircraftState;if(l.status==="ready"&&l.shown>0){const h=document.createElement("li");if(h.appendChild(un.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(un.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=un.text(`${YT} (`);c.append(un.link(qT,KT),document.createTextNode(")")),i(c)}static text(e){const t=document.createElement("li");return t.textContent=e,t}static link(e,t){const i=document.createElement("a");return i.href=e,i.target="_blank",i.rel="noopener",i.textContent=t,i}}const ZT=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,jT=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,JT=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,QT=20,eI=1;class tI{context;buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};level=1;master;output(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}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}}la.unlock(this.context)}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(ZT,this.ambientVolume).then(o=>this.applyIfCurrent(o,r,()=>this.ambientToken,l=>{this.ambientSource=l?.source,this.ambientGain=l?.gain,l&&(l.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/QT,1);const s=i>eI;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(jT,this.windVolume).then(o=>this.applyIfCurrent(o,r,()=>this.windToken,l=>{this.windSource=l?.source,this.windGain=l?.gain,l&&(l.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(JT,.9)}dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0,this.context?.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(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(this.output(i)),s.start(),{source:s,gain:r}}catch(n){console.warn("Weather ambient sound failed to load, staying silent:",n);return}}async playOneShot(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(this.output(i)),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 Ws{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(Ws.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*Ws.stumpffC(n),o=t-i*i*i/Math.sqrt(Ws.SUN_GM_AU3_PER_DAY2)*Ws.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(Ws.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=o=>{const l=this.inverseSemiMajorAxis*o*o,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*o*o*o*Ws.stumpffS(l)+c*o};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let o=0;o<Ws.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);o++){const l=(r+s)/2;n(l)<i?r=l:s=l}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),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*o*l,y:s*r+n*o*l,z:o*c},{x:-n*o-s*r*l,y:-s*o+n*r*l,z:r*c}]}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 Gb=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class lh{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 Gb.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=ri(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),o=this.subtract(r,s),l=this.length(r),c=this.length(o),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(o,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(o,this.subtract({x:0,y:0,z:0},s)),magnitude:this.magnitudeAt(e,l,c)}}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 l=1+e.tailLengthAu/n,c=this.subtract({x:t.x*l,y:t.y*l,z:t.z*l},i),h=this.subtract(t,i);return{tailEnd:this.horizontalOf(c,s,r,o),tailLengthDeg:this.angleBetween(h,c)}}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=So(K5(),new Vt(e.x,e.y,e.z,t)),r=So(Ib(t),s),o=I5(t,new l0(n.lat,n.lng,n.elevationM)),l=new Vt(r.x-o.x,r.y-o.y,r.z-o.z,t),c=h0(l);return d0(c.ra,c.dec,i,n)}static earthPositionAt(e){return So(q5(),Ir(_e.Earth,e))}static julianDayOf(e){return 2451545+ri(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new Ws(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 Ru=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class Gh{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return Ru.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of Ru){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Jn.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 Ru.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],[l,c]=i[s]??i[0];if(l===r)return o;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return o+h*(c-o)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const iI=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],Po=6.5;class Eo{static activeAt(e){return iI.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),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return o<0?o<-l?0:1+o/l:o>0?o>c?0:1-o/c:1}static observedRatePerHour(e,t,i,n=Po){if(t<=0)return 0;const s=Po-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Jn.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 jt{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=ri(e),n=new nd(0,A5(e).elon-90,1),s=So(j5(i),c0(n,i)),r=h0(s);return d0(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=Po){const i=jt.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=Po-t;return(jt.QUIET_RATE_PER_HOUR+i)/Math.pow(jt.POPULATION_INDEX,n)}static schedule(e){const t=new ad(e.seed^1542469173);return ua.schedule(e).map(i=>{const n=jt.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=jt.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:jt.toHorizontal(o),bearingDeg:jt.bearingFrom(o,n)}})}static turnAround(e,t){const[i,n]=jt.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]=jt.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=jt.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=jt.normalise(jt.cross(e,t));return[i,jt.normalise(jt.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=jt.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=jt.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return jt.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 Av="https://ufoathome.org/tle/index.json";class zi{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??zi.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(Av)||e.push(Av),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${zi.FIRST_SNAPSHOT}T00:00:00Z`)-zi.MAX_ELEMENT_AGE_DAYS*zi.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)-zi.MAX_ELEMENT_AGE_DAYS*zi.DAY_MS&&e.getTime()<=Date.parse(n.to)+zi.MAX_ELEMENT_AGE_DAYS*zi.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 l=await this.kindAt(o,e,i,n);s.push(...l),r.push(this.coverageOf(o,e,i,l.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*zi.DAY_MS,o=Math.floor(s/r),l=s-o*r<r/2?o-1:o+1,c=new Set(i.kinds[e].bins),h=[o,l].map(v=>new Date(v*r).toISOString().slice(0,10)).filter(v=>c.has(v));if(h.length===0)return[];const[d,...u]=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 u)for(const m of zi.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)/zi.DAY_MS;if(m>zi.MAX_ELEMENT_AGE_DAYS)continue;const g=d[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(),l=zi.MAX_ELEMENT_AGE_DAYS*zi.DAY_MS,c=n?"covered":o<Date.parse(s)-l?"before":o>Date.parse(r)+l?"after":"gap";return{kind:e,status:c,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 nI{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=it.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=it.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:it.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:it.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class pa{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*pa.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=pa.degOver(e)/t;return i<1?1:Math.min(pa.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Vi{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 pa.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 Vi.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??Vi.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,o=Vi.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,Vi.trailLimitedSeconds(o)),resolutionArcsec:o}}static resolutionArcsec(e,t,i){const s=(e.detailUm??Vi.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*Vi.ARCSEC_PER_RADIAN,r=1.22*Vi.WAVELENGTH_M/(i/1e3)*Vi.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/Vi.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=Vi.graspOf(e,t),n=Vi.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:Et.focalLengthMmFor(e,t.fieldOfViewDeg);return Vi.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const Tv=111320,rl=Math.PI/180,sI=1.02,rI=1;class Sl{static of(e,t){const i=Sl.sightings(e,t);if(i.length<2)return;const n=Sl.baseline(i);if(!n)return;const{near:s,far:r,closedM:o}=n,l=Math.tan(r.widthDeg/2*rl)===0?0:Math.tan(s.widthDeg/2*rl)/Math.tan(r.widthDeg/2*rl);if(l<sI)return;const c=o/(l-1),h=it.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:it.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.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=et(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=Sl.closedAlongSight(i,n),[r,o,l]=s>=0?[n,i,s]:[i,n,-s];l<rI||r.widthDeg<=o.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:o,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*Tv,n=(t.lng-e.lng)*Tv*Math.cos(e.lat*rl),s=(e.sightAzimuthDeg??0)*rl;return i*Math.cos(s)+n*Math.sin(s)}}class ji{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:ji.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:ji.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:ji.atLeastNearest(e.derivedM),basis:"derived"};const t=ji.largest(e.range?.minM,e.crossing?.behindM),i=ji.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*ji.MARGIN,s=i===void 0?void 0:i/ji.MARGIN;return n!==void 0&&s!==void 0?{distanceM:ji.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:ji.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<ji.CONVENTIONAL_M?{distanceM:ji.atLeastNearest(s),basis:"bounded"}:{distanceM:ji.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(ji.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 Cu=Math.PI/180;class st{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)st.collect(this.motionKeys,s.t,s.motions),st.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 st.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?st.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 l=r[o],c=r[Math.min(o+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=st.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=et(e,0),s=et(e,t),o=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?ni(s.lat,s.lng,n.lat,n.lng):void 0,l=o?o.x:0,c=o?-o.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+st.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=st.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let o=0,l=0;for(;l<st.MAX_RANGE_M;){if(l=o+Math.max(.5,o*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(o+l)/2;r(h)<=0?l=h:o=h}return l}o=l}}static directionOf(e,t){const i=e*Cu,n=t*Cu;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=st.lerp(n.eastM,s.eastM,r),l=st.lerp(n.northM,s.northM,r),c={widthM:st.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:st.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:st.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},h={headingDeg:st.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:st.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:st.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let d;if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const u=st.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);d=this.groundUnderFootprint(o,l,c,h.headingDeg)+u+c.heightM/2}else d=st.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:l,upM:d,sizeM:c,attitude:h,appearance:{color:(r<1?n:s).appearance.color,albedo:st.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:st.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r)},flame:st.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(u=>u.flame!==void 0&&u.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:st.lerp(n.lengthM,s.lengthM,i),widthM:st.lerp(n.widthM,s.widthM,i),luminanceCdM2:st.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*Cu,r={eastM:Math.cos(s),northM:-Math.sin(s)},o={eastM:Math.sin(s),northM:Math.cos(s)};let l=this.ground.heightAt(e,t);for(const[c,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const d=c*i.widthM/2,u=h*i.lengthM/2;l=Math.max(l,this.ground.heightAt(e+r.eastM*d+o.eastM*u,t+r.northM*d+o.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??st.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},l={color:s.appearance?.color??n?.appearance.color??st.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??st.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??st.DEFAULT_APPEARANCE.luminanceCdM2},c=this.positionOf(s,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;n={t:s.t,...c,sizeM:r,attitude:o,appearance:l,flame:h,present:d},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?st.lineOfSightMeetsGround(i,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(n===void 0)return;const s=st.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}}class Mt{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=1.5;static FADE_MS=600;static TRAIN_POINTS=8;static leadAt(e,t){const i=e.track;if(i.length<2||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-2&&i[n+1].t<t;)n++;const s=i[n],r=i[n+1],o=r.t-s.t,l=o>0?(t-s.t)/o:0,[c,h]=Mt.alongGreatCircle(s,r,l);return{lat:c,lng:h,heightM:(s.altitudeKm+(r.altitudeKm-s.altitudeKm)*l)*1e3}}static viewsAt(e,t,i){const n=[];for(const s of e){const r=s.track[0]?.t??0,o=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??o;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,f=Mt.leadAt(s,t-u);if(!f)return;const p=Mt.seenFrom(i,f);if(p.altitudeDeg<0)return;const v=Math.min(Mt.FADE_MS,(d-h)/4),m=v>0?Math.min(1,(t-h)/v,(d-t)/v):1,g=-2.5*Math.log10(Math.max(m,.001)),x=l.absoluteMagnitude+5*Math.log10(p.distanceKm/Mt.STANDARD_DISTANCE_KM)+g,y=[p],b=(l.trainS??Mt.DEFAULT_TRAIN_S)*1e3;for(let w=1;w<=Mt.TRAIN_POINTS;w++){const E=Math.min(b*w/Mt.TRAIN_POINTS,t-h),T=Mt.leadAt(s,t-u-E);if(!T||(y.push(Mt.seenFrom(i,T)),E>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:p,magnitude:x,color:l.color??Mt.DEFAULT_COLOR,train:y})})}return n}static seenFrom(e,t){const i=Mt.ecef(e),n=Mt.ecef(t),s=n[0]-i[0],r=n[1]-i[1],o=n[2]-i[2],l=e.lat*Mt.DEG,c=e.lng*Mt.DEG,h=-Math.sin(c)*s+Math.cos(c)*r,d=-Math.sin(l)*Math.cos(c)*s-Math.sin(l)*Math.sin(c)*r+Math.cos(l)*o,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*o,f=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/f)/Mt.DEG,azimuthDeg:(Math.atan2(h,d)/Mt.DEG+360)%360,distanceKm:f/1e3}}static ecef(e){const t=e.lat*Mt.DEG,i=e.lng*Mt.DEG,n=Math.sin(t),s=Mt.A/Math.sqrt(1-Mt.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-Mt.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*Mt.DEG,u=h.lng*Mt.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),o=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(o);let c;if(l<1e-12)c=s;else{const h=Math.sin((1-i)*l)/Math.sin(l),d=Math.sin(i*l)/Math.sin(l);c=[s[0]*h+r[0]*d,s[1]*h+r[1]*d,s[2]*h+r[2]*d]}return[Math.atan2(c[2],Math.hypot(c[0],c[1]))/Mt.DEG,Math.atan2(c[1],c[0])/Mt.DEG]}}class p0{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=p0.FIRST_DAY}}class aI{constructor(e,t,i){this.citation=e,this.covers=t,this.load=i}loading;mayCover(e){return this.covers(e)}async between(e,t,i,n){try{return await(await this.provider()).between(e,t,i,n)}catch{return{status:"failed"}}}async describe(e,t){try{return await(await this.provider()).describe?.(e,t)}catch{return}}provider(){if(!this.loading){const e=this.load();this.loading=e,e.catch(()=>{this.loading===e&&(this.loading=void 0)})}return this.loading}}const oI="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",bp=[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new aI(oI,a=>p0.mayCover(a),async()=>new(await ot(async()=>{const{AdsbLolArchiveProvider:a}=await import("./AdsbLolArchiveProvider-Ir8tinqO.js");return{AdsbLolArchiveProvider:a}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Ji{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=Ji.positionAt(e,i);if(!n)return;const s=Mt.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Ji.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>Ji.seenFrom(n,t,i)??[])}static groundDistanceKm(e,t){const i=Math.PI/180,n=Math.sin((t.lat-e.lat)*i/2)**2+Math.cos(e.lat*i)*Math.cos(t.lat*i)*Math.sin((t.lng-e.lng)*i/2)**2;return 2*Ji.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(n)))}static wrapLongitude(e){return((e+180)%360+360)%360-180}static positionAt(e,t){const i=e.points;if(i.length===0||t<i[0].t||t>i[i.length-1].t)return;let n=0;for(;n<i.length-1&&i[n+1].t<=t;)n++;const s=i[n],r=i[n+1]??s,o=r.t-s.t;if(o>Ji.MAX_GAP_S*1e3)return;const l=o>0?(t-s.t)/o:0,c=s.altitudeFt+(r.altitudeFt-s.altitudeFt)*l,h=(r.lng-s.lng+540)%360-180;return{geo:{lat:s.lat+(r.lat-s.lat)*l,lng:Ji.wrapLongitude(s.lng+h*l),heightM:c*Ji.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=Ji.positionAt(e,i-500),s=Ji.positionAt(e,i+500);if(!n||!s)return;const r=Ji.unit(Mt.seenFrom(t,n.geo)),o=Ji.unit(Mt.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*o[0]+r[1]*o[1]+r[2]*o[2]));return Math.acos(l)*180/Math.PI}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180;return[Math.cos(t)*Math.sin(i),Math.cos(t)*Math.cos(i),Math.sin(t)]}}const Iv="https://ufoathome.org/fireballs/index.json";class Bn{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Bn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/fireballs/index.json",location.href).href),e.includes(Iv)||e.push(Iv),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Bn.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Bn.mayCover(t))return;const i=await this.loadIndex();if(!i)return;const n=new Set([new Date(e).toISOString().slice(0,7),new Date(t).toISOString().slice(0,7)]);return[...n].some(r=>r>=i.index.from&&r<=i.index.to)?(await Promise.all([...n].filter(r=>i.index.months.includes(r)).map(r=>this.monthOf(r,i.base)))).flat().filter(r=>r.t>=e&&r.t<=t):void 0}static seenFrom(e,t){const i=Bn.peakFraction(e),n={lat:e.from[0]+(e.to[0]-e.from[0])*i,lng:e.from[1]+(e.to[1]-e.from[1])*i,heightM:e.peakHeightKm*1e3},s=Mt.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/Mt.STANDARD_DISTANCE_KM)}}static asReentry(e,t){const i=e.t-t,n=i+Math.max(e.durationS,.1)*1e3;return{id:`gmn-${e.id}`,track:[{t:i,lat:e.from[0],lng:e.from[1],altitudeKm:e.from[2]},{t:n,lat:e.to[0],lng:e.to[1],altitudeKm:e.to[2]}],fragments:[{absoluteMagnitude:e.peakMagnitude,color:Bn.COLOR,trainS:Bn.TRAIN_S}]}}static peakFraction(e){const t=e.from[2]-e.to[2];return Math.abs(t)<1e-6?.5:Math.min(1,Math.max(0,(e.from[2]-e.peakHeightKm)/t))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}monthOf(e,t){let i=this.months.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.months.set(e,i)),i}}const qa=Math.PI/180,al=180/Math.PI;class hi{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=hi.projectionOf(r,i,n?.(r));if(o)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...hi.compare(l,r.id,{aim:c.aim,angular:c.angular},o),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?hi.separationDeg(i.aim,n.aim):void 0;if(r!==void 0){const c=Math.max(i.angular?.widthDeg??0,n.angular.widthDeg)/2;r>Math.max(hi.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const o=i.angular&&i.angular.widthDeg>0?n.angular.widthDeg/i.angular.widthDeg:void 0,l=i.angular&&i.angular.heightDeg>0?n.angular.heightDeg/i.angular.heightDeg:void 0;return o!==void 0&&!hi.withinSize(o)&&s.push("width"),l!==void 0&&!hi.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:o,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:hi.outlineOf(e),s=i&&i.length>0?hi.centreOf(i):e,r=hi.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const o=hi.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=hi.cross(o,r);let c=1/0,h=-1/0,d=1/0,u=-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=hi.dot(p,r);if(v<=0)return;const m=Math.atan2(hi.dot(p,o),v),g=Math.atan2(hi.dot(p,l),v);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,g),u=Math.max(u,g)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*al+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*al},angular:{widthDeg:(h-c)*al,heightDeg:(u-d)*al}}}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*qa,n=t.altitudeDeg*qa,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*qa);return Math.acos(Math.max(-1,Math.min(1,s)))*al}static withinSize(e){return e<=hi.SIZE_TOLERANCE&&e>=1/hi.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"&&Bb.includes(r))for(let d=0;d<=hi.RINGS;d++){const u=d/hi.RINGS*Math.PI;for(let f=0;f<hi.SEGMENTS;f++){const p=f/hi.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(p),i*Math.sin(u)*Math.sin(p),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const f of[-n,n])s.push([d,u,f]);const l=e.attitude.headingDeg*qa,c=e.attitude.pitchDeg*qa,h=e.attitude.rollDeg*qa;return s.map(([d,u,f])=>{const p=d*Math.cos(h)+f*Math.sin(h),v=-d*Math.sin(h)+f*Math.cos(h),m=u*Math.cos(c)-v*Math.sin(c),g=u*Math.sin(c)+v*Math.cos(c);return{eastM:e.eastM+p*Math.cos(l)+m*Math.sin(l),northM:e.northM-p*Math.sin(l)+m*Math.cos(l),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}}$h();const lI={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},cI="{name} — mag {mag}, {alt}° above the horizon",hI="{name} — satellite, mag {mag}, {height} km up",Vb="satellites-change",Wb="fireballs-change",dI="aircraft-change",uI="rr0-confrontation",fI="{name} — mag {mag}, {alt}° below the horizontal",Pu="Credits",Dv="comet:",Rv="nova:",pI={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",crop:"Crop row",mound:"Stone heap",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},mI=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,gI=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,vI=-18,bI={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Lu={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class fi 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",ha,fo]}shadow;stageElement;frameElement;sceneCanvas;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;distanceHypotheses=new Map;depths=new Map;directionScratch=new D;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new zi;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Bn;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=bp[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return fi.trafficRuntimeLoading??=ot(()=>import("./trafficRuntime-CyMwd0OH.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>fi.trafficRuntime=e),fi.trafficRuntimeLoading.catch(()=>{fi.trafficRuntimeLoading=void 0}),fi.trafficRuntimeLoading}traffic;lastSun;decorMemo;starCatalogDepth=0;weatherAudio=new tI;vehicleAudio=new SM;aircraftAudio;vehicleHearing=new bh;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),l=this.naming,c=l.names,h=this.sceneRenderer.pickBodyAt(r,o);if(h){this.showHoverTooltip(e,this.bodyName(h));return}const d=this.sceneRenderer.pickDecorAt(r,o),u=d?this.ufoElement.sighting.decor.find(m=>m.id===d):void 0;if(u){this.showHoverTooltip(e,this.said.read(u.title)||l.decorKind(u.kind,pI[u.kind]));return}const f=this.trafficTooltipAt(r,o);if(f){this.showHoverTooltip(e,f);return}const p=this.sceneRenderer.pickSatelliteAt(r,o);if(p){this.showHoverTooltip(e,(c?.satelliteTooltip??hI).replace("{name}",p.name).replace("{mag}",p.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(p.heightKm).toLocaleString()));return}const v=this.sceneRenderer.pickStarAt(r,o);if(v){const m=v.star.mag,g=v.altitudeDeg,x=g<0?c?.starTooltipBelow??fI:c?.starTooltip??cI;this.showHoverTooltip(e,x.replace("{name}",l.star(v.star)).replace("{mag}",m.toLocaleString(void 0,{maximumFractionDigits:Math.abs(m)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(g)))));return}this.hoverTooltip.hidden=!0};bodyName(e){const t=e.startsWith(Dv)?e.slice(Dv.length):void 0,i=t?Gb.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(Rv)?Gh.byId(e.slice(Rv.length)):void 0;if(n)return this.naming.nova(n);const s=lI[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new Hh;namesLanguage="en";async loadSceneNames(){const e=vh(qs.preferencesFor(this),uh);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await e1(e);e===this.namesLanguage&&this.applySceneNaming(new Hh(t))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((o,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of o){const d=document.createElement("span");d.className="scene-loader-letter",d.style.setProperty("--i",String(i++)),d.textContent=h,c.append(d)}s.append(c),i++})};n(this.loaderNotVideo,e),i+=6,n(this.loaderNote,t)}applySceneNaming(e){this.sceneNaming=e;const t=e.names?.credits??Pu;this.creditsButton.title=t,this.creditsButton.setAttribute("aria-label",t),e.names&&this.renderLoaderText(e.names.notAVideo,e.names.isASimulation),this.sceneRenderer.setCompassPoints(e.names?.compassPoints)}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(),wi.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather($l(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;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(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${_M}</style>${EM}`,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 It(this.sceneCanvas);const t=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.renderLoaderText("This is not a video","It is a real-time simulation."),this.sceneRenderer.onFirstFrameHold=s=>{t.hidden=!s,this.ufoElement.captionHeld=s},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(qu),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",s=>this.lookToward(s.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),n=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",s=>{s.newState==="open"&&un.fill(n,this)}),this.creditsButton.title=Pu,this.creditsButton.setAttribute("aria-label",Pu),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.weatherAudio.setLevel(this.ufoElement.level)),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of["pointerdown","pointerup","touchend","click","keydown"])this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new Qn(qs.preferencesFor(this))}saidTexts;traceLabelsFor;traceLabels(e){const t=qs.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==e||this.traceLabelsFor.language!==t){const i=new Map;for(const n of e){const s=this.said.read(n.title);s&&i.set(n.id,s)}this.traceLabelsFor={traces:e,language:t,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){this.saidTexts=void 0,this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),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(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,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===ha||e===fo)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[ha,fo]){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=et(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}=ni(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(),this.aircraftAudio?.resume()}async loadFromSrc(e){const t=Sp.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.sightingData=i}holdForNewScene(e){this.sceneRenderer.holdForNewScene(e)}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.seekPreview?.recordingChanged(e),this.interpretationShown=this.inTheRound?this.ufoElement.sighting.interpretation:void 0,this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}seekPreview;seekPreviewOf(e){const t=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(e.width/t);return e.height!==i&&(e.height=i),this.seekPreview??=new zh(this,()=>document.createElement(Vh))}showAt(e){this.ufoElement.currentTime=e,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(e){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const t=e.getContext("2d");return t?(t.drawImage(this.sceneCanvas,0,0,e.width,e.height),!0):!1}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=it.CANVAS_HEIGHT_PX,i=Et.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:Du,url:this.getAttribute("star-catalog-src")??mI},{magnitudeLimit:xl,url:this.getAttribute("deep-star-catalog-src")??gI}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>Du?xl:Du;const n=await gs.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=xl||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=Vi.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure});return _r(vI,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=Zn.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=pa.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,Zn.instants(this.decorWithTraffic(this.ufoElement.sighting),et(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:Si.fovOf(this.ufoElement.sighting,e)/t}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather($l(i,e)),this.sceneRenderer.setInstrument(i.instrument),this.sceneRenderer.setLightPollution(i.lightPollution),t||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,e)),t||this.pushAircraftSound(i,e),this.updateMeteorShower(i,e),this.updateLightning(i,e,t!==void 0),this.sceneRenderer.setDecor(this.decorWithTraffic(i)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??fi.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??fi.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=et(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=et(i,0),r=ii(i,0),o=Object.fromEntries(_s(ii(i,e)).map(b=>[b.id,hh(e,i.weatherTrack,r,s,n,b.id)]));this.sceneRenderer.setCloudOffset(hh(e,i.weatherTrack,r,s,n),o),this.sceneRenderer.setObserverPose(n??Lu),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(Vi.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:Si.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(Dt.bodyAt(i,e,this.ufoElement.steadyObserver)),this.sceneRenderer.updateDecorAnchoring(et(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.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(e);const l=n?.lat??Lu.lat,c=n?.lng??Lu.lng,h=Un(i.event.time??{},c,i.event.utcOffsetHours),d={lat:l,lng:c,elevationM:n?.elevationM??0};this.pushSatellitesAt(h,e,d),this.ensureFireballs(h);const u=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];if(this.sceneRenderer.setReentries(u.length===0?[]:Mt.viewsAt(u,e,{lat:l,lng:c,heightM:d.elevationM})),t&&!t.sky)return;if(!h){this.sceneRenderer.setAstronomy(bI);return}const f=new Date(h.getTime()+e),p=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/pa.DEG_PER_SECOND*1e3)),v=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),m=`${Math.floor(f.getTime()/p)}|${Math.round(l/v)}|${Math.round(c/v)}|${Math.round(d.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(m===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=m;const g={...Li("Sun",f,d),magnitude:ru("Sun",f)};this.lastSun={altitudeDeg:g.altitudeDeg,azimuthDeg:g.azimuthDeg};const x={...Li("Moon",f,d),phase:ao(f),magnitude:ru("Moon",f)},y=J5.map(b=>({body:b,position:Li(b,f,d),magnitude:ru(b,f)}));this.sceneRenderer.setAstronomy({sun:g,moon:x,planets:y,comet:this.cometAt(f,d),novae:Gh.appearancesAt(f,d).map(({outburst:b,position:w,magnitude:E})=>({id:b.id,position:w,magnitude:E})),stars:this.starCatalog?{catalog:this.starCatalog,date:f,observer:d}:void 0,frame:{date:f,observer:d}}),this.ufoElement.setSunAltitude(g.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)}ensureFireballs(e){const t=this.ufoElement.sighting,i=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=e?.getTime(),s=n===void 0?"":`${n}+${i}`;if(this.fireballs?.key===s)return;if(n===void 0||!Bn.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,fi.fireballArchive.between(n,n+i).then(o=>{r.status=o?"ready":"unavailable",r.records=o??[],r.reentries=r.records.map(l=>Bn.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Wb)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(e){const t=this.ensureTraffic(e);if(!t||t.objects.length===0)return e.decor;const i=this.decorMemo;if(i&&i.base===e.decor&&i.traffic===t.objects)return i.merged;const n=[...e.decor,...t.objects];return this.decorMemo={base:e.decor,traffic:t.objects,merged:n},n}ensureTraffic(e){const t=et(e,0),i=t?.lng===void 0?void 0:Un(e.event.time??{},t.lng,e.event.utcOffsetHours),n=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=i?.getTime(),r=s===void 0||t?.lat===void 0||t.lng===void 0?"":`${this.aircraftSource.id}|${s}+${n}|${t.lat.toFixed(3)},${t.lng.toFixed(3)}|${Math.round(t.elevationM??0)}`;if(this.traffic?.key===r)return this.traffic.set;if(r===""||s===void 0||t?.lat===void 0||t.lng===void 0){this.traffic={key:r,status:"outside"};return}let o=fi.aircraftProviders.get(this.aircraftSource.id);if(o||fi.aircraftProviders.set(this.aircraftSource.id,o=this.aircraftSource.create()),o.mayCover&&!o.mayCover(s+n)){this.traffic={key:r,status:"outside"};return}const l={key:r,status:"loading",startMs:s,observer:{lat:t.lat,lng:t.lng}};this.traffic=l;const c={lat:t.lat,lng:t.lng,heightM:t.elevationM??0},h=Ji.MAX_GAP_S*1e3,d=fi.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},f=(p,v)=>p.TrafficDecor.from(l.tracks??[],c,s,p.TrafficDecor.MAX_OBJECTS,{models:v,sunElevationAt:m=>this.sunElevationAt(m,u)});o.between(c,s-d,s+n+h).then(async p=>{if(this.traffic!==l)return;if(p.status!=="found"){l.status=p.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let v;try{v=await fi.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=p.tracks,l.set=f(v),this.startAircraftSound(l,v),this.announceTraffic(),this.describeTraffic(o,l,v,f),l.set.shown>0&&this.readUpperAir(l,v,s-d,s+n+h))})}trafficSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||i.startMs===void 0||!i.observer)return t;for(const[r,o]of n.presence){if(e<o.fromMs||e>o.untilMs)continue;const l=n.flights.get(r),c=l?Ji.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:An.sunElevationDeg(s,i.observer,c.geo)})}return t}trafficTooltipAt(e,t){const i=this.sceneRenderer.pickTrafficAt(e,t),n=i?this.trafficInfoAt(i):void 0;if(!n)return;const s=this.naming,r=fi.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,o=>s.towards(o))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=fi.trafficRuntime;if(!n)return;const s=t.descriptions?.get(jn.keyOf(i)),r=et(this.ufoElement.sighting,this.lastTimeMs),o={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA($l(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,o,t.startMs+this.lastTimeMs,{ambientDbA:l}),h=c&&this.contrailAt(e,this.lastTimeMs);return c&&h?{...c,contrail:h}:c}contrailAt(e,t){const i=this.traffic?.contrails?.find(s=>s.id===e);if(!i)return;let n;for(const s of i.points){if(s.tMs>t)break;n=s}return n?.forms?{persistent:n.persistent,iceRelativeHumidity:n.iceRelativeHumidity}:void 0}startAircraftSound(e,t){this.aircraftAudio||(this.aircraftAudio=new t.AircraftAudio,this.interacted&&this.aircraftAudio.resume(),this.aircraftAudio.setPaused(this.ufoElement.playbackState!=="playing")),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,jn.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){const i=this.aircraftAudio;if(!i)return;const n=fi.trafficRuntime,s=this.traffic,r=s?.set;if(!n||!s||!r||!s.audible||s.startMs===void 0||!s.observer){i.setVoices([]);return}const o=et(e,t),l={lat:s.observer.lat,lng:s.observer.lng,heightM:o?.elevationM??0},c=$l(e,t),h=n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,jn.keyOf,l,s.startMs+t,{ambientDbA:n.AmbientNoise.dbA(c),referenceAmplitude:n.AmbientNoise.referenceAmplitude(c)});i.setVoices(h,o?.headingDeg??0)}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(dI)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(e,t,i,n){if(!e.describe||!t.set||!t.tracks)return;const s=new Set([...t.set.flights.values()].map(c=>jn.keyOf(c))),r=t.tracks.filter(c=>s.has(jn.keyOf(c))&&c.points.length>0),o=new Map,l=new Map;await Promise.all(r.map(async c=>{const h=new Date(c.points[0].t).toISOString().slice(0,10),d=await e.describe(c,h).catch(()=>{});d&&(l.set(jn.keyOf(c),d),o.set(jn.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||o.size===0)&&(t.descriptions=l,t.models=o,t.set=n(i,o),this.planContrails(t,i),this.sortOutAudible(t,i),this.announceTraffic())}async readUpperAir(e,t,i,n){if(!e.observer)return;const s=this.upperAirSource??t.UPPER_AIR_SOURCES[0];let r=fi.upperAirProviders.get(s.id);r||fi.upperAirProviders.set(s.id,r=s.create());const o=await r.between(e.observer,i,n);this.traffic!==e||o.status!=="found"||(e.air=o.samples,e.airSource=o.source,this.planContrails(e,t),this.announceTraffic())}planContrails(e,t){!e.set||!e.air||e.startMs===void 0||(e.contrails=t.AircraftContrails.plan(e.set,e.models,e.air,e.startMs))}contrailSunlight(e){const t=new Map,i=this.traffic,n=i?.set,s=this.lastSun;if(!n||!s||!i.contrails?.length||i.startMs===void 0||!i.observer)return t;for(const r of i.contrails){const o=n.presence.get(r.id),l=n.flights.get(r.id);if(!o||!l)continue;const c=Ji.positionAt(l,i.startMs+Math.min(o.untilMs,Math.max(o.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:An.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Li("Sun",new Date(e.t),t);return An.sunElevationDeg(i,t,e)}upperAirSource;setUpperAirSource(e){e.id!==this.upperAirSource?.id&&(this.upperAirSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(e){e.id!==this.aircraftSource.id&&(this.aircraftSource=e,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const e=this.traffic?.contrails?.length?this.upperAirSource??fi.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:e&&{credit:e.credit,creditUrl:e.creditUrl},status:this.traffic?.status??"none",total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(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(Vb)))},s=fi.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,o]=await Promise.all([s.at(e),ot(()=>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=et(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 l=Un(i.event.time??{},o,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:o,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,o,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),f=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:f},f}cometAt(e,t){const i=lh.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,l=new Map,c=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(qn.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)},x=g!==void 0&&Math.abs(g.ndcX)<=1&&Math.abs(g.ndcY)<=1,y=x?this.sceneRenderer.decorDistancesAt(g.ndcX,g.ndcY,p):{};c.add(p),(x||v.aim)&&c.delete(p);const b=v.angular?.widthDeg??r.pxToDeg(v.bounds.width),w=this.sizeEstimateOf(p);w.add(b,y);const E=Sl.of(t,p);l.set(p,ji.resolve({hypothesisM:this.distanceHypotheses.get(p),derivedM:E&&b>0?it.distanceMAt(E.widthM,b):void 0,range:w.distanceRangeAt(b),crossing:y}))}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 y=l.get(m);y&&l.set(p,{distanceM:y.distanceM*.999,basis:y.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[p,v]of o)d.push({sourceId:p,shape:v,distanceM:l.get(p).distanceM,renderOrder:h.indexOf(p),aim:v.aim,hidden:c.has(p)||this.interpretationShown!==void 0&&(!this.comparing||v.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=(et(t,e)?.rollDeg??0)+Dt.bodyAt(t,e,this.ufoElement.steadyObserver).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Et.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=st.eyeOf(this.ufoElement.sighting,i,n);return s?st.lineOfSightMeetsGround(s,e,t,n):void 0}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>st.eyeOf(n,u,i),r=new st(e,i,s).at(t),o=s(t);if(!r||!o)return;const l=r.eastM-o.eastM,c=r.northM-o.northM,h=r.upM-o.upM,d=Math.hypot(l,c);return{azimuthDeg:(Math.atan2(l,c)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,d)*180/Math.PI,distanceM:Math.hypot(d,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=>st.eyeOf(n,p,i),r=new st(e,i,s),o=r.at(t)?t:e.track[0]?.t,l=o===void 0?void 0:r.at(o),c=o===void 0?void 0:s(o);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.upM-c.upM,f=Math.hypot(h,d);if(!(f===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,f)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const o=this.sceneRenderer.bodyGround,l=p=>st.eyeOf(n,p,o);i&&(s=i.bodies.map(p=>new st(p,o,l).at(e)).filter(p=>p!==void 0));const c=ii(n,e),h=c.windDirectionDeg*Math.PI/180,d={x:c.windSpeed*Math.sin(h),z:-c.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(s,e/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],d);const u=i&&this.comparing?l(e):void 0;if(u&&(r=new hi(n.timeline).at(e,s,u,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(uI,{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&&ii(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=ii(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?Un(n,s?.lng??0,e.event.utcOffsetHours):void 0,o=(e.event.durationSeconds??0)*1e3||e.timeline.duration||2e4,l=Math.round((r?.getTime()??0)/1e3)+Math.round((s?.lat??0)*1e3)+7;this.lightningFlashes=wi.schedule({durationMs:o,seed:l,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?Un(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),l=jt.schedule({ratePerHour:jt.observedRatePerHour(jt.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:jt.TYPICAL_VELOCITY_KM_S,seed:o}),c=Eo.activeAt(n).map(d=>{const u=Eo.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:Eo.observedRatePerHour(d.zhr,u.altitudeDeg,d.shower.populationIndex)}}).sort((d,u)=>u.rate-d.rate)[0];if(!c||c.rate<=0){this.sceneRenderer.setMeteorShower(l,0,0);return}const h=ua.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:o+1});this.sceneRenderer.setMeteorShower([...h,...l],c.position.altitudeDeg,c.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=et(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const o=Et.focalLengthMmFor(i,Si.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 is.of(t.instrument,it.CANVAS_HEIGHT_PX,Si.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new nI,this.sizeEstimates.set(e,t)),t}}const Vh="rr0-scene";function yI(){$h(),customElements.get(Vh)||customElements.define(Vh,fi)}class MI{constructor(e,t){this.timeline=e,this.clock=t}currentPointer=null;shapePrototype=null;sourceId="";start(e,t){this.sourceId=e,this.shapePrototype=t,this.currentPointer=null,this.clock.start(i=>this.recordSample(i))}onPointerMove(e,t){this.currentPointer={x:e,y:t}}stop(){this.clock.stop()}recordSample(e){if(!this.currentPointer||!this.shapePrototype)return;const t=Jv(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class wI{constructor(e){this.intervalMs=e}rafId=null;startTime=0;lastTick=0;start(e){this.startTime=performance.now(),this.lastTick=0;const t=()=>{const i=performance.now()-this.startTime;i-this.lastTick>=this.intervalMs&&(this.lastTick=i,e(i)),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}stop(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}}const xI=[{id:"echo",name:"the Echo balloons",from:"1960-08-12",to:"1969-06-07",peakMagnitude:-1,note:"Echo 1 and 2 were 30- and 40-metre reflective balloons, as bright as the brightest stars and moving slowly enough to be watched — deliberately visible, widely announced in newspapers, and the first objects most people ever saw crossing the night sky. They fall squarely inside the sighting waves this project reconstructs."},{id:"iridium-flares",name:"the Iridium flares",from:"1997-05-05",to:"2019-12-27",peakMagnitude:-8,note:"The original Iridium satellites carried flat, mirror-finish antennas that threw a sunbeam a few kilometres wide across the ground: a still point of sky flaring to magnitude -8 over five seconds and vanishing again. Nothing else in the sky does that."},{id:"iss",name:"the International Space Station",from:"1998-11-20",peakMagnitude:-5.9,note:"Since its first module, and much brighter as it grew: at its best it outshines everything in the sky but the Sun and the Moon, crossing in a straight silent line in about four minutes."},{id:"starlink-trains",name:"the Starlink trains",from:"2019-05-24",peakMagnitude:1,note:"In the days after a launch, satellites still bunched in their deployment string cross as an evenly spaced line of lights — the most reported 'formation of UFOs' of the era. They spread out within weeks, so a train is a fact about the days after a launch rather than about the year."}],SI=23493,Cv=[2,3,2,1,2,5,4,6,5,6,6,6,6,6,6,6,9,9,9,9,9,9,14,14,15,16,16,16,16,16,18,22,25,24,29,28,29,33,34,35,40,40,42,42,43,46,48,48,49,53,53,54,58,61,70,70,74,78,79,83,92,92,99,97,101,102,109,115,126,125,123,125,127,130,139,153,157,156,161,156,165,174,193,193,201,203,212,215,224,244,255,263,262,281,293,307,312,327,339,336,343,353,359,369,386,396,405,410,421,419,424,434,443,450,460,480,492,504,509,516,519,524,527,530,527,535,543,549,564,571,573,576,582,584,600,600,608,618,625,632,637,642,648,654,661,667,669,667,671,671,697,692,703,697,710,714,724,731,747,755,764,770,782,802,801,815,819,837,846,856,878,881,877,900,906,907,917,932,932,936,954,973,989,986,991,990,1002,1009,1021,1024,1040,1038,1058,1078,1098,1092,1094,1099,1122,1132,1140,1151,1154,1161,1176,1185,1202,1206,1227,1228,1243,1265,1281,1288,1296,1325,1328,1336,1354,1373,1375,1393,1398,1411,1432,1457,1462,1476,1487,1485,1506,1509,1521,1524,1537,1543,1563,1586,1598,1614,1621,1620,1640,1658,1660,1673,1670,1686,1708,1715,1726,1726,1745,1749,1767,1774,1790,1798,1803,1805,1815,1818,1819,1820,1833,1822,1821,1819,1838,1835,1845,1841,1851,1869,1865,1868,1871,1870,1879,1882,1886,1900,1899,1908,1921,1928,1954,1966,1976,1986,1999,2007,2015,2030,2036,2057,2067,2072,2077,2088,2101,2106,2112,2119,2127,2142,2171,2176,2203,2226,2242,2241,2244,2254,2263,2284,2300,2320,2327,2345,2364,2367,2402,2423,2425,2434,2443,2461,2476,2495,2505,2520,2531,2535,2556,2567,2599,2608,2625,2639,2660,2663,2668,2681,2695,2702,2709,2719,2720,2738,2746,2763,2778,2788,2796,2807,2822,2831,2831,2853,2863,2866,2883,2892,2895,2921,2919,2937,2941,2947,2964,2987,2992,2987,2995,3002,3021,3025,3026,3036,3052,3049,3059,3077,3075,3083,3086,3107,3123,3124,3146,3155,3168,3179,3204,3205,3211,3233,3252,3253,3276,3287,3294,3293,3297,3314,3326,3335,3338,3355,3362,3358,3365,3364,3376,3375,3382,3418,3429,3432,3455,3463,3483,3490,3502,3509,3521,3532,3542,3544,3553,3571,3580,3588,3596,3603,3633,3639,3649,3655,3660,3670,3699,3699,3707,3723,3747,3752,3754,3766,3772,3778,3781,3798,3815,3814,3824,3832,3853,3859,3879,3885,3899,3912,3910,3924,3937,3951,3951,3961,3963,3961,3976,3977,3988,4004,4018,4025,4047,4074,4086,4108,4133,4136,4159,4168,4182,4192,4200,4215,4230,4239,4257,4678,4698,4694,4713,4719,4739,4750,4756,4764,4771,4788,4792,4790,4809,4821,4829,4834,4836,4843,4853,4863,4872,4881,4890,4898,4901,4897,4895,4884,4886,4886,4894,4897,4905,4905,4909,4907,4925,4918,4920,4929,4925,4928,4936,4943,4944,4951,4955,4952,4974,4976,4975,4981,4994,4997,5022,5023,5032,5043,5048,5051,5066,5062,5068,5075,5082,5082,5098,5102,5110,5113,5119,5123,5138,5138,5145,5149,5157,5165,5166,5169,5178,5183,5190,5192,5203,5204,5207,5214,5228,5234,5245,5249,5256,5262,5275,5278,5305,5303,5315,5321,5348,5358,5369,5369,5372,5385,5402,5409,5427,5429,5429,5439,5456,5464,5481,5485,5494,5509,5520,5526,5543,5555,5568,5575,5585,5596,5602,5620,5627,5644,5647,5660,5678,5680,5684,5692,5700,5711,5727,5733,5736,5756,5776,5797,5805,5804,5807,5800,5808,5814,5822,5839,5856,5869,5889,5902,5919,5921,5936,5937,5936,5957,5961,5975,5981,6002,6015,6027,6035,6042,6059,6062,6080,6081,6092,6097,6106,6127,6129,6198,6227,6231,6243,6249,6262,6255,6279,6304,6315,6326,6330,6334,6361,6358,6359,6379,6381,6389,6388,6404,6404,6443,6465,6473,6497,6500,6513,6524,6532,6538,6578,6572,6576,6584,6582,6608,6639,6656,6761,6764,6768,6772,6836,6905,6916,6925,6951,6984,7009,7072,7092,7110,7122,7140,7148,7170,7168,7180,7194,7247,7374,7391,7393,7382,7425,7485,7530,7568,7587,7602,7602,7715,7771,7900,8004,8103,8153,8162,8296,8319,8437,8566,8746,8860,8913,9128,9275,9585,9739,10014,10123,10167,10203,10288,10323,10398,10544,10721,10883,11044,11157,11442,11515,11787,12070,12269,12468,12484,12619,12883,13008,13264,13317,13549,13859,14049,14175,14360,14498,14687,14843,14984,15093,15279,15431,15623,15741,15788,15966,16025,16132,16419,16568,16791,16892,17060,17269,17598,17959,18194,18482,18804,19136,19564,19990,20249,20509,20943,21248,21539,21845,22196,22412];class Kn{static FIRST_ORBIT="1957-10-04";static EARTH_RADIUS_KM=6371;static LOW_ORBIT_KM=500;static shadowHeightKm(e){if(e>=0)return 0;const t=-e*Math.PI/180;return Kn.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Kn.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return xI.filter(i=>{const n=Date.parse(`${i.from}T00:00:00Z`),s=i.to===void 0?1/0:Date.parse(`${i.to}T23:59:59Z`);return t>=n&&t<=s})}static trackedInOrbitAt(e){const t=e.getUTCFullYear()*12+e.getUTCMonth()-SI;if(!(t<0))return Cv[Math.min(t,Cv.length-1)]}static visibilityAt(e,t){const i=Li("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:Kn.shadowHeightKm(i),lowOrbitLit:Kn.isLitOverhead(Kn.LOW_ORBIT_KM,i),classes:Kn.classesAt(e),trackedObjects:Kn.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Kn.FIRST_ORBIT}T00:00:00Z`)}}}const Pv="https://ufoathome.org/reentries/index.json";class fn{static MINUTE_SLACK_MS=60*6e4;static WINDOW_SLACK_MS=60*6e4;static VISIBLE_KM=1500;static VISIBLE_DEG=fn.VISIBLE_KM/111.2;static EARTH_RADIUS_KM=6371;fetchImpl;indexUrls;index;years=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??fn.defaultIndexUrls()}static defaultIndexUrls(){const e=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&e.push(new URL("/reentries/index.json",location.href).href),e.includes(Pv)||e.push(Pv),e}async credit(){return(await this.loadIndex())?.index.credit}async candidates(e,t,i){const n=await this.loadIndex();if(!n)return;const s=new Set;for(const o of[e-fn.DAY_MS,t+fn.DAY_MS])s.add(String(new Date(o).getUTCFullYear()));const r=(await Promise.all([...s].filter(o=>n.index.years.includes(o)).map(o=>this.yearOf(o,n.base)))).flat();return fn.match(r,e,t,i)}static DAY_MS=864e5;static match(e,t,i,n){const s=[];for(const o of e){if(o.inclinationDeg!==void 0&&Math.abs(n.lat)>o.inclinationDeg+fn.VISIBLE_DEG)continue;const l=Date.parse(o.precision==="day"?`${o.time}T00:00Z`:o.time);if(Number.isFinite(l))if(o.precision==="minute"){const c=l<t?t-l:l>i?l-i:0;if(c>fn.MINUTE_SLACK_MS)continue;let h;if(o.seenLat!==void 0&&o.seenLng!==void 0&&(h=fn.distanceKm(n.lat,n.lng,o.seenLat,o.seenLng),h>fn.VISIBLE_KM))continue;s.push({record:o,timeMs:l,offsetMinutes:Math.round(c/6e4),seenKm:h})}else{const c=o.precision==="day"?fn.DAY_MS/2:(o.uncertaintyHours??0)*36e5,h=o.precision==="day"?l+c:l,d=fn.WINDOW_SLACK_MS;if(h+c+d<t||h-c-d>i)continue;s.push({record:o,timeMs:h})}}const r={minute:0,hours:1,day:2};return s.sort((o,l)=>r[o.record.precision]-r[l.record.precision]||(o.record.uncertaintyHours??0)-(l.record.uncertaintyHours??0)||o.timeMs-l.timeMs)}static distanceKm(e,t,i,n){const s=Math.PI/180,r=Math.sin(e*s)*Math.sin(i*s)+Math.cos(e*s)*Math.cos(i*s)*Math.cos((n-t)*s);return fn.EARTH_RADIUS_KM*Math.acos(Math.max(-1,Math.min(1,r)))}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(t.ok)return{index:await t.json(),base:e}}catch{}})(),this.index}yearOf(e,t){let i=this.years.get(e);return i||(i=this.fetchImpl(new URL(`${e}.json`,t).href).then(n=>n.ok?n.json():[]).catch(()=>[]),this.years.set(e,i)),i}}const EI="https://ufoathome.org/light-pollution/index.json";class ea{year=2015;citation="World Atlas of the artificial night sky brightness (Falchi et al. 2016, doi:10.1126/sciadv.1600377; data doi:10.5880/GFZ.1.4.2016.001, CC BY-NC 4.0)";static NATURAL_MCD=.171168;fetchImpl;indexUrls;index;tiles=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??ea.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,EI].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+ea.NATURAL_MCD)/108e6)}static mcdOf(e,t){return e===0?0:t.floorMcd*10**((e-1)/t.subdivisions)}async lookUp(e,t){const i=await this.loadIndex();if(!i)return{status:"failed"};const{index:n,base:s,present:r}=i;if(!(e<n.north&&e>=n.south))return{status:"outside"};const o=((t+180)%360+360)%360-180,l=Math.floor((n.north-e)/n.tileDeg),c=Math.floor((o+180)/n.tileDeg),h=l*(360/n.tileDeg)+c;if(!(r[h>>3]&1<<(h&7)))return{status:"natural"};const d=n.north-l*n.tileDeg,u=-180+c*n.tileDeg,f=ea.nameOf(d-n.tileDeg,u),p=await this.tile(`${s}${f}.bin`);if(!p)return{status:"failed"};const v=n.tileDeg/n.cells,m=Math.min(n.cells-1,Math.floor((d-e)/v)),g=Math.min(n.cells-1,Math.floor((o-u)/v)),x=ea.mcdOf(p[m*n.cells+g],n);return x===0?{status:"natural"}:{status:"found",lightPollution:Math.round(ea.magPerArcsec2Of(x)*100)/100,artificialMcdPerM2:x,lat:d-(m+.5)*v,lng:u+(g+.5)*v}}static nameOf(e,t){const i=`${e<0?"S":"N"}${String(Math.abs(e)).padStart(2,"0")}`,n=`${t<0?"W":"E"}${String(Math.abs(t)).padStart(3,"0")}`;return i+n}loadIndex(){return this.index??=(async()=>{for(const e of this.indexUrls)try{const t=await this.fetchImpl(e);if(!t.ok)continue;const i=await t.json(),n=Uint8Array.from(atob(i.present),s=>s.charCodeAt(0));return{index:i,base:new URL(".",e).href,present:n}}catch{}})(),this.index.then(e=>{e||(this.index=void 0)}),this.index}tile(e){let t=this.tiles.get(e);return t||(t=(async()=>{try{const i=await this.fetchImpl(e);if(!i.ok||!i.body)return;const n=i.body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(n).arrayBuffer())}catch{return}})(),this.tiles.set(e,t),t.then(i=>{i||this.tiles.delete(e)})),t}}const Lv=[{id:"falchi-2015",name:"World Atlas 2015",credit:"Falchi et al. 2016, CC BY-NC 4.0",creditUrl:"https://doi.org/10.5880/GFZ.1.4.2016.001",create:()=>new ea}];class yt{static COARSE_STEP_DEG=10;static FINE_STEP_DEG=2;static FINE_SPAN_DEG=10;static LOWEST_DEG=5;static THRESHOLD_CONTRAST=.5;static CONE_SEPARATION_DEG=60;galaxy=new lt;dust=new Zt;assess(e,t,i){const n=Li("Sun",e,t),s=Li("Moon",e,t),r={altitudeDeg:s.altitudeDeg,phaseAngleDeg:le.phaseAngleOf(ao(e).illuminatedFraction)},o=En.galactic(e,t),l=yt.unit(o.centre),c=yt.unit(o.rotation),h=yt.unit(o.pole),d=yt.unit(En.eclipticPole(e,t)),u=yt.unit(n),f=yt.unit(s),p=yt.normalize(yt.reject(u,d));let v,m,g=0;const x=(y,b)=>{const w=yt.unit({altitudeDeg:y,azimuthDeg:b}),E=yt.between(w,u),T=le.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:E},{...r,separationDeg:yt.between(w,f)},y,i);T>g&&(g=T);const M=Js.fromMagPerArcsec2(T),I=10**(-.4*le.EXTINCTION_PER_AIR_MASS*(le.airMass(y)-1)),A=this.galaxy.surfaceBrightnessS10(Math.atan2(yt.dot(w,c),yt.dot(w,l))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,yt.dot(w,h))))*180/Math.PI)*I;v=yt.better(v,A,M,T,y,b,E);const R=Math.max(-1,Math.min(1,yt.dot(w,d))),P=yt.normalize(yt.reject(w,d)),U=this.dust.surfaceBrightnessS10(yt.between(P,p),Math.asin(R)*180/Math.PI)*I;m=yt.better(m,U,M,T,y,b,E)};for(let y=yt.LOWEST_DEG;y<=90;y+=yt.COARSE_STEP_DEG)for(let b=0;b<360;b+=yt.COARSE_STEP_DEG)x(y,b);for(const y of[v,m]){if(!y)continue;const b=yt.FINE_SPAN_DEG,w=yt.FINE_STEP_DEG;for(let E=y.altitudeDeg-b;E<=y.altitudeDeg+b;E+=w)if(!(E<yt.LOWEST_DEG||E>90))for(let T=y.azimuthDeg-b;T<=y.azimuthDeg+b;T+=w)x(E,(T+360)%360)}return{milkyWay:v&&v.contrast>=yt.THRESHOLD_CONTRAST?v:void 0,zodiacal:m&&m.contrast>=yt.THRESHOLD_CONTRAST?m:void 0,darkestSkyMagPerArcsec2:g}}static better(e,t,i,n,s,r,o){const l=t/i;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:r,magPerArcsec2:Js.toMagPerArcsec2(t),skyMagPerArcsec2:n,sunSeparationDeg:o}}static unit(e){const t=e.altitudeDeg*Math.PI/180,i=e.azimuthDeg*Math.PI/180,n=Math.cos(t);return[n*Math.sin(i),Math.sin(t),-n*Math.cos(i)]}static dot(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}static between(e,t){return Math.acos(Math.max(-1,Math.min(1,yt.dot(e,t))))*180/Math.PI}static reject(e,t){const i=yt.dot(e,t);return[e[0]-i*t[0],e[1]-i*t[1],e[2]-i*t[2]]}static normalize(e){const t=Math.hypot(...e)||1;return[e[0]/t,e[1]/t,e[2]/t]}}const _I=.5,qc=40,AI=4e5,Wr=Math.PI/180,Ka=180/Math.PI;class cn{static localDirection(e,t,i,n=new D){const s=Math.tan(t/2*Wr);return n.set((e.u*2-1)*s*i,(1-e.v*2)*s,-1).normalize()}static picturePoint(e,t,i){if(e.z>=0)return;const n=Math.tan(t/2*Wr),s=e.x/-e.z/(n*i),r=e.y/-e.z/n;return{u:(s+1)/2,v:(1-r)/2}}static worldDirection(e,t=new D){const i=e.azimuthDeg*Wr,n=e.altitudeDeg*Wr;return t.set(Math.sin(i)*Math.cos(n),Math.sin(n),-Math.cos(i)*Math.cos(n))}static aimOf(e){const t=Math.hypot(e.x,e.z);return{azimuthDeg:(Math.atan2(e.x,-e.z)*Ka+360)%360,altitudeDeg:Math.atan2(e.y,t)*Ka}}static rotationOf(e){const t=new Xt;return t.rotation.set(e.pitchDeg*Wr,-e.headingDeg*Wr,-(e.rollDeg??0)*Wr,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Ps().setFromQuaternion(e,"YXZ"),i=(-t.y*Ka%360+360)%360,n=-t.z*Ka;return{headingDeg:i,pitchDeg:t.x*Ka,rollDeg:Math.abs(n)<1e-9?0:n}}static worldDirectionOf(e,t,i,n=new D){return this.localDirection(e,t.fovDeg,i,n).applyQuaternion(this.rotationOf(t))}static picturePointOf(e,t,i){const n=e.clone().applyQuaternion(this.rotationOf(t).invert()),s=this.picturePoint(n,t.fovDeg,i);if(!(!s||s.u<0||s.u>1||s.v<0||s.v>1))return s}static solve(e,t,i,n=e.length>=3){if(e.length<2)return;if(!n)return this.solveAtField(e,t,i);let s=1,r=179;const o=(Math.sqrt(5)-1)/2;let l=r-o*(r-s),c=s+o*(r-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let f=0;f<60&&r-s>1e-4;f++){if(!h||!d)return;h.residualDeg<d.residualDeg?(r=c,c=l,d=h,l=r-o*(r-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+o*(r-s),d=this.solveAtField(e,t,c))}return h&&d?h.residualDeg<d.residualDeg?h:d:h??d}static solveAtField(e,t,i){const n=e.map(c=>this.localDirection(c.picture,i,t)),s=e.map(c=>this.worldDirection(c.scene)),r=this.triad(n,s);if(!r)return;const o=this.refine(r,n,s);return{registration:{...this.anglesOf(o),fovDeg:i},residualDeg:this.residualDeg(o,n,s)}}static triad(e,t){let i=0,n=1,s=-1;for(let h=0;h<e.length;h++)for(let d=h+1;d<e.length;d++){const u=e[h].clone().cross(e[d]).lengthSq();u>s&&(s=u,i=h,n=d)}if(s<1e-12)return;const r=(h,d)=>{const u=h.clone().normalize(),f=h.clone().cross(d).normalize(),p=f.clone().cross(u);return new $e().set(u.x,p.x,f.x,u.y,p.y,f.y,u.z,p.z,f.z)},o=r(e[i],e[n]),c=r(t[i],t[n]).multiply(o.transpose());return new qi().setFromRotationMatrix(new je().setFromMatrix3(c))}static refine(e,t,i){const n=e.clone(),s=new D;for(let r=0;r<20;r++){const o=new $e().set(0,0,0,0,0,0,0,0,0),l=o.elements,c=new D;for(let f=0;f<t.length;f++){s.copy(t[f]).applyQuaternion(n);const p=s,v=[[0,p.z,-p.y],[-p.z,0,p.x],[p.y,-p.x,0]],m=[i[f].x-p.x,i[f].y-p.y,i[f].z-p.z];for(let g=0;g<3;g++){for(let x=0;x<3;x++)for(let y=0;y<3;y++)l[x*3+g]+=v[y][g]*v[y][x];c.setComponent(g,c.getComponent(g)+v[0][g]*m[0]+v[1][g]*m[1]+v[2][g]*m[2])}}for(let f=0;f<3;f++)l[f*3+f]+=1e-9;const h=c.applyMatrix3(o.invert()),d=h.length();if(d<1e-12)break;const u=new qi().setFromAxisAngle(h.normalize(),d);if(n.premultiply(u).normalize(),d<1e-10)break}return n}static residualDeg(e,t,i){let n=0;const s=new D;for(let r=0;r<t.length;r++){s.copy(t[r]).applyQuaternion(e);const o=s.angleTo(i[r])*Ka;n+=o*o}return Math.sqrt(n/t.length)}}const kv=6371e3,ol=Math.PI/180;class co{constructor(e=t=>fetch(t).then(i=>{if(!i.ok)throw new Error(`${t}: HTTP ${i.status}`);return i.json()})){this.fetchJson=e}static API="https://api.panoramax.xyz/api";static CREDIT="Panoramax";static CREDIT_URL="https://panoramax.fr/";async nearby(e,t,i=300,n=50){const s=i/111320,r=i/(111320*Math.cos(e*ol)),o=[t-r,e-s,t+r,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${co.API}/search?bbox=${o}&limit=${n}`)).features??[]).map(h=>this.picture(h,e,t)).filter(h=>h!==void 0&&h.distanceM<=i).sort((h,d)=>h.distanceM-d.distanceM)}picture(e,t,i){const[n,s]=e.geometry.coordinates,r=e.assets.sd?.href??e.assets.hd?.href;if(!r)return;const{distanceM:o,bearingDeg:l}=co.offset(t,i,s,n),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(f=>f.name).filter(f=>!!f),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:n,distanceM:o,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:r,srcFull:e.assets.hd?.href,credit:`${co.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${co.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,i,n){const s=(i-e)*ol*kv,r=(n-t)*ol*kv*Math.cos((e+i)/2*ol);return{distanceM:Math.hypot(r,s),bearingDeg:(Math.atan2(r,s)/ol+360)%360}}}const Kc=36e5,Ov=25;class ku{constructor(e){this.provider=e}async infer(e){const t=this.questionOf(e);if(!t)return{status:"incomplete"};const{origin:i,start:n}=t,s=_o(e.event)??0,r=this.sampleTimings(e,n,s);let o;try{o=await this.provider.getWeather({points:r.map(l=>this.pointAt(e,l,i))})}catch{return{status:"failed",at:n}}return o?{status:"inferred",at:n,source:o.source,keyframes:o.samples.map((l,c)=>({t:r[c].t,weather:l.weather}))}:{status:"unavailable",at:n}}applyTo(e,t){if(!(t.status!=="inferred"||!t.keyframes||!t.source)){e.weatherTrack.clear();for(const i of t.keyframes)e.weatherTrack.addKeyframe(i.t,i.weather);e.weatherSource=t.source}}sampleTimes(e,t){const i=[e],n=e.getTime()+t;let s=Math.floor(e.getTime()/Kc)*Kc+Kc;for(;s<=n&&i.length<Ov;)i.push(new Date(s)),s+=Kc;return t>0&&i[i.length-1].getTime()!==n&&i.length<Ov&&i.push(new Date(n)),i}sampleTimings(e,t,i){const n=e.timeline.duration>0?e.timeline.duration:i;return i<=0||n<=0?[{time:t,t:0}]:this.sampleTimes(t,i).map(s=>{const r=(s.getTime()-t.getTime())/i;return{time:s,t:Math.round(n*Math.max(0,Math.min(1,r)))}})}canInfer(e){return this.questionOf(e)!==void 0}questionOf(e){const t=this.originOf(e);if(!t)return;const i=e.event.time;if(i?.year===void 0||i.month===void 0||i.day===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);return n?{origin:t,start:n}:void 0}originOf(e){const t=et(e,0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return n===void 0||s===void 0?void 0:{lat:n,lng:s}}pointAt(e,t,i){const n=et(e,t.t);return{lat:n?.lat??i.lat,lng:n?.lng??i.lng,time:t.time}}}const TI=Date.UTC(1940,0,1),Nv=36e5,Fv=.25,II=.7,DI=.45,RI=.1,CI=2,PI=.3,LI=.2,kI=8,Ou=.125,OI=.05,Uv=125,Bv=100,zv=2500,Nu=3500,Fu=8e3,NI=95,FI=99,UI=[96,99],BI=["cloud_cover","cloud_cover_low","cloud_cover_mid","cloud_cover_high","precipitation","snowfall","weather_code","wind_speed_10m","wind_direction_10m","temperature_2m","dew_point_2m"];class Xb{fetchImpl;baseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive"}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(f=>f.time.getTime()),i=Math.min(...t);if(i<TI)return;const n=new Map;for(const f of e.points){const p=this.cellKey(f);n.has(p)||n.set(p,{lat:f.lat,lng:f.lng,index:n.size})}const s=this.requestUrl([...n.values()],new Date(i),new Date(Math.max(...t))),r=this.cache.get(s);if(r)return r;const o=await this.fetchImpl(s);if(!o.ok)throw new Error(`Open-Meteo HTTP ${o.status}`);const l=await o.json(),c=Array.isArray(l)?l:[l];if(c.length<n.size||c.some(f=>f.error||!f.hourly))return;const h={id:"era5",name:"ERA5 (Open-Meteo)",url:s},d=e.points.map(f=>this.sampleAt(c[n.get(this.cellKey(f)).index].hourly,f.time));if(d.some(f=>f===void 0))return;const u={samples:d,source:h};return this.cache.set(s,u),u}cellKey(e){return`${Math.round(e.lat/Fv)},${Math.round(e.lng/Fv)}`}requestUrl(e,t,i){const n=new URLSearchParams({latitude:e.map(s=>s.lat).join(","),longitude:e.map(s=>s.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:BI.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${this.baseUrl}?${n}`}isoDate(e){return e.toISOString().slice(0,10)}sampleAt(e,t){const i=this.recordAt(e,t);return i&&{time:t,weather:this.toWeather(i)}}recordAt(e,t){const i=e.time.map(o=>Date.parse(`${o}Z`)),n=t.getTime();if(i.length===0||n<i[0]-Nv||n>i[i.length-1]+Nv)return;if(n<=i[0])return this.recordFrom(e,0);if(n>=i[i.length-1])return this.recordFrom(e,i.length-1);let s=0;for(;s+1<i.length&&i[s+1]<=n;)s++;const r=i[s+1]-i[s];return this.blendRecords(this.recordFrom(e,s),this.recordFrom(e,s+1),r>0?(n-i[s])/r:0)}recordFrom(e,t){const i={cloudCover:e.cloud_cover[t]/100,cloudCoverLow:e.cloud_cover_low[t]/100,cloudCoverMid:e.cloud_cover_mid[t]/100,cloudCoverHigh:e.cloud_cover_high[t]/100,precipitationMm:e.precipitation[t],snowfallCm:e.snowfall[t],weatherCode:e.weather_code[t],windSpeedMs:e.wind_speed_10m[t],windFromDeg:e.wind_direction_10m[t],temperatureC:e.temperature_2m[t],dewPointC:e.dew_point_2m[t]};return Object.values(i).some(n=>n===void 0||Number.isNaN(n))?void 0:i}blendRecords(e,t,i){if(!e||!t)return e??t;const n=(r,o)=>r+(o-r)*i,s=((t.windFromDeg-e.windFromDeg)%360+540)%360-180;return{cloudCover:n(e.cloudCover,t.cloudCover),cloudCoverLow:n(e.cloudCoverLow,t.cloudCoverLow),cloudCoverMid:n(e.cloudCoverMid,t.cloudCoverMid),cloudCoverHigh:n(e.cloudCoverHigh,t.cloudCoverHigh),precipitationMm:n(e.precipitationMm,t.precipitationMm),snowfallCm:n(e.snowfallCm,t.snowfallCm),weatherCode:i<.5?e.weatherCode:t.weatherCode,windSpeedMs:n(e.windSpeedMs,t.windSpeedMs),windFromDeg:((e.windFromDeg+s*i)%360+360)%360,temperatureC:n(e.temperatureC,t.temperatureC),dewPointC:n(e.dewPointC,t.dewPointC)}}cloudLayersFrom(e){return[{id:"record-low",type:"unknown",baseM:Math.round(this.clamp(Uv*(e.temperatureC-e.dewPointC),Bv,zv)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:Nu,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Fu,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=NI&&e.weatherCode<=FI,i=this.precipitationTypeFrom(e);return{cloudLayers:this.cloudLayersFrom(e),cloudCover:this.clamp(e.cloudCover,0,1),cloudDarkness:this.cloudDarknessFrom(e,t),cloudBaseM:this.cloudBaseFrom(e),highCloudCover:e.cloudCoverHigh,lowerCloudCover:Math.max(e.cloudCoverLow,e.cloudCoverMid),relativeHumidity:Math.round(Ys.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/kI),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":UI.includes(e.weatherCode)?"hail":e.precipitationMm>0?"rain":"none"}cloudDarknessFrom(e,t){const i=e.cloudCoverLow+e.cloudCoverMid+e.cloudCoverHigh;if(i<=0)return 0;const n=(II*e.cloudCoverLow+DI*e.cloudCoverMid+RI*e.cloudCoverHigh)/i,s=Math.min(1,e.precipitationMm/CI);return this.clamp(n+PI*s+(t?LI:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<OI)return;const t=this.clamp(Uv*(e.temperatureC-e.dewPointC),Bv,zv);if(e.cloudCoverLow>=Ou)return Math.round(t);if(e.cloudCoverMid>=Ou)return Nu;if(e.cloudCoverHigh>=Ou)return Fu;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?Nu:Fu}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function zI(){return new Xb}const HI=5;class $b{attribution={text:"© OpenStreetMap",url:"https://osm.org/copyright"};fetchImpl;baseUrl;reverseUrl;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://nominatim.openstreetmap.org/search",this.reverseUrl=e.reverseUrl??"https://nominatim.openstreetmap.org/reverse"}async reverse(e,t,i={}){const n=new URLSearchParams({lat:String(e),lon:String(t),format:"jsonv2"});i.language&&n.set("accept-language",i.language);const s=`${this.reverseUrl}?${n}`,r=this.cache.get(s);if(r)return r[0];const o=await this.fetchImpl(s,{signal:i.signal});if(!o.ok)throw new Error(`Nominatim HTTP ${o.status}`);const l=await o.json(),c=l.error?void 0:this.toMatch(l);return this.cache.set(s,c?[c]:[]),c}async search(e,t={}){const i=e.trim();if(i==="")return[];const n=this.requestUrl(i,t),s=this.cache.get(n);if(s)return s;const r=await this.fetchImpl(n,{signal:t.signal});if(!r.ok)throw new Error(`Nominatim HTTP ${r.status}`);const o=await r.json(),l=(Array.isArray(o)?o:[]).map(c=>this.toMatch(c)).filter(c=>c!==void 0);return this.cache.set(n,l),l}requestUrl(e,t){const i=new URLSearchParams({q:e,format:"jsonv2",limit:String(t.limit??HI)});return t.language&&i.set("accept-language",t.language),`${this.baseUrl}?${i}`}toMatch(e){const t=e.display_name??e.name,i=this.coordinate(e.lat),n=this.coordinate(e.lon);return t&&i!==void 0&&n!==void 0?{name:t,lat:i,lng:n}:void 0}coordinate(e){if(e===void 0||e.trim()==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}}function GI(){return new $b}const VI=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new $b}],WI=[{id:"era5",name:"ERA5 (Open-Meteo)",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new Xb}];class XI{attribution;fetchImpl;tileUrlTemplate;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis);const t=e.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${t}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${t})`}async getImageryTexture(e,t){return m1(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const Uu=[{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new p1}],Hv=[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:()=>new g1},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:()=>new XI}];class m0{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=m0.SPAN_DEG;try{const s=(await this.provider.getElevationGrid({south:e-i,north:e+i,west:t-i,east:t+i},{width:2,height:2})).heights[0];return Number.isFinite(s)?s:void 0}catch{return}}}class $I{available(){const e=Intl.supportedValuesOf;return e?[...e.call(Intl,"timeZone")].sort():[]}offsetHoursAt(e,t){if(t.year===void 0)return;const i=Date.UTC(t.year,(t.month??1)-1,t.day??1,t.hour??12,t.minute??0,t.second??0),n=this.zoneOffsetHours(e,new Date(i));if(n!==void 0)return this.zoneOffsetHours(e,new Date(i-n*36e5))??n}zoneOffsetHours(e,t){let i;try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"}).formatToParts(t).find(s=>s.type==="timeZoneName")?.value??""}catch{return}const n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(i);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[3])/60):0}}function zs(a,e){return a.find(t=>t.id===e)??a[0]}class YI{constructor(e="https://api.open-meteo.com/v1/forecast"){this.endpoint=e}async zoneAt(e,t){const i=new URL(this.endpoint);i.searchParams.set("latitude",String(e)),i.searchParams.set("longitude",String(t)),i.searchParams.set("timezone","auto"),i.searchParams.set("forecast_days","1");try{const n=await fetch(i.toString());if(!n.ok)return;const s=await n.json();return s.timezone&&s.timezone!=="GMT"?s.timezone:void 0}catch{return}}}const qI=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new YI}],KI={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)",lightPollution:"Night sky",lightPollutionTitle:'The zenith of a moonless night at this place, in magnitudes per square arcsecond, as a Sky Quality Meter reads it or as the World Atlas of artificial sky brightness (Falchi et al. 2016, lightpollutionmap.info, "SQM") gives it. 22 is a natural sky; a suburb is about 19, a city centre 17. Blank: a natural sky',observationTime:"Observation start",observationEndTime:"Observation end",assessmentGroup:"Assessment",assessmentNames:{coverage:"Observer info"},assessmentVerdicts:{"hynek.nl":"NL — nocturnal light","hynek.dd":"DD — daylight disc","hynek.rv":"RV — radar-visual","hynek.ce1":"CE1 — close encounter","hynek.ce2":"CE2 — with a physical trace","hynek.ce3":"CE3 — with entities"},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"},yp={...KI,oval:"Oval",polygon:"Polygon",addVertex:"Add vertex",deleteVertex:"Delete vertex",notAPolygon:"Select a single polygon shape",tooFewVertices:"A shape needs at least 3 points",shape:"Shape",apparentWidth:"Apparent width",realWidth:"Real width",distance:"Distance",sizeLock:"Hold",lockNone:"nothing",lockApparent:"the apparent width",lockReal:"the real width",lockDistance:"the distance",apparentSize:"{moons}× the Moon",utcOffsetPlaceholder:"from longitude",realSizeBetween:"The scene bounds that width: between {min} and {max} m, from what it crosses",realSizeAtLeast:"The scene bounds that width: at least {min} m, from what it passes behind",realSizeAtMost:"The scene bounds that width: at most {max} m, from what it passes in front of",realSizeUnknown:"Nothing in the scene bounds that width: it is only what the distance implies",realSizeOutside:" — the width above is outside that",blurBound:"Blurred through this lens: nearer than {max} m",blurBoundNoInstrument:"Blur through the naked eye bounds no distance — an eye has no aperture to be out of focus with",blurBoundNotAtInfinity:"Blur bounds a distance only for a lens focused at infinity: this one is focused at {focus} m, which blurs on both sides of it",realSizeContradiction:"Contradiction: the declared crossings cannot all be true",realDistanceHere:" — i.e. between {min} and {max} m here",clearDistanceHypothesis:"Withdraw the distance hypothesis",clearDistanceHypothesisTitle:"Back to what the recording establishes",depthStated:"Drawn at {m} m, as the recording states",depthHypothesis:"Drawn at {m} m: your hypothesis — what the decor hides of it is what a thing that far would lose",depthDerived:"Drawn at {m} m, from the observer's own walk",depthBounded:"Drawn at {m} m, from what it passes behind and in front of",depthConventional:"Drawn at {m} m by convention: nothing in the recording establishes a distance",addShape:"Add shape",deleteShape:"Delete shape",play:"Play",pause:"Pause",noDuration:"No observation duration",previousKeyframe:"Previous keyframe",nextKeyframe:"Next keyframe",keyframeMark:"Keyframe",shapesTrack:"shapes",observerTrack:"observer",weatherTrack:"weather",soundTrack:"sound",group:"Group",ungroup:"Ungroup",bringToFront:"Bring to front",sendToBack:"Send to back",contextMenuDelete:"Delete",confirmDeleteShape:"Delete {name}? This can't be undone.",confirmDeleteShapes:"Delete {count} shapes? This can't be undone.",confirmDeleteMilestone:"Stop naming moment {name}? The recording itself is unchanged.",onlyOneShape:"There is only one shape",alreadyAtFront:"This shape is already at the front",alreadyAtBack:"This shape is already at the back",needTwoShapesToGroup:"Select at least two shapes to group them",notGrouped:"This shape isn't part of a group",multipleShapesSelected:"Multiple shapes selected — select just one to edit this",samplingRate:"Sampling rate",currentPosition:"Current position",switchToElapsed:"click to show elapsed time",switchToClockTime:"click to show the time of day",durationPlaceholder:"observation length",durationImprecise:"These dates don't precisely enough determine a duration — enter it manually.",export:"Export",importFile:"Load JSON file",importUrl:"Or load from URL",importUrlPlaceholder:"https://…/sighting.json",importButton:"Load",importError:"Couldn't load that recording — check the file or URL and try again.",importErrorCors:'That address answers, but the browser is not allowed to read it from this page. The file itself is fine — its server needs to send the header "Access-Control-Allow-Origin: *" with it. If it is not your server, that is what to ask its administrator for.',importErrorMixedContent:"A secure page cannot load an address starting with http://. Use https:// if that server offers it.",importErrorUnreachable:"Nothing answered at that address. Check the spelling, and that you are online.",importErrorStatus:"That server answered with an error ({status}). The address is probably wrong, or the file has moved.",importErrorMalformed:"That address answered, but what came back is not a recording.",record:"Record",stop:"Stop",according:"according to",sourceElevation:"Relief",sourceImagery:"Imagery",sourceAircraft:"Air traffic",placeNamePlaceholder:"Valensole, France",searchPlace:"Locate",placeMatch:"Matches",placeSearching:"Looking up the place…",placeMatchFound:"place found",placeMatchesFound:"places found",placeNotFound:"No place by that name",placeSearchFailed:"Place search temporarily unavailable",utcOffsetImplausible:"This time zone doesn't match the longitude entered, whose own solar time is UTC{solar} — yet the scene and the weather record both obey what is declared here. Clear the field to derive it from the longitude.",timeZoneManual:"offset entered",altitudeAboveSeaLevel:"The observer's altitude above sea level — the ground at the location entered sets its floor: an observer in the Alps is not at 0 m.",groundAt:"ground at {m} m",headingPlaceholder:"unknown",edtfInvalid:"Not a valid EDTF date/time (e.g. 1965-07-01T05:00, 2025-06?, 2025~).",edtfPlaceholder:"YYYY-MM-DDThh:mm[?~%] or hh:mm",observationTimeHint:"EDTF — e.g. 1965-07-01T05:00, 2025-06? (uncertain), 2025~ (approximate), or just 05:00 if the date isn't known",observationEndTimeHint:"EDTF — e.g. 1965-07-01T05:10, 2025-06? (uncertain), 2025~ (approximate), or just 05:10 if the date isn't known",presetsGroupLabel:"UFO shape",description:"Description",tagsPlaceholder:"comma-separated",weather:"Weather",shapeGroup:"Phenomenon",shapesSubgroup:"Shapes",bodiesSubgroup:"Bodies",soundGroup:"Sound",temporalGroup:"Moment",timeQualifierExact:"Exact",timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",edtfModeTitle:"Type an imprecise date instead: a year alone, a month, a time with no date",locationGroup:"Location",observationGroup:"Observation",weatherWhilePlaying:"Pause the recording to state the weather — while it plays, the instant these would be written at is moving",weatherInferred:"From weather records",weatherInferredTitle:"Weather isn't an account: it's a measurable fact, on record for the observation's own date, time and place. Uncheck to state the conditions the observer reported, which then override the record.",weatherLookingUp:"Looking up the record…",weatherNeedsDateAndPlace:"A full date and a place are needed to look up the record",weatherNoRecord:"No record for this date and place",weatherLookupFailed:"Weather records temporarily unreachable",lightPollutionLookingUp:"Looking up the atlas…",lightPollutionFound:"{artificial} µcd/m² of artificial light,",lightPollutionNatural:"No artificial light here,",lightPollutionOutside:"Beyond the atlas (85°N to 60°S),",lightPollutionFailed:"Atlas unreachable for now",lightPollutionTooEarly:"The atlas describes {atlasYear}; the sky of {year} was darker, give it yourself if it is known",instrumentOutOfPeriod:"{name} — not of this date",unitMillimetres:"mm",unitDegrees:"°",fieldOfViewReadout:"{deg}° of field",soundSrcPlaceholder:"URL of a real recording",referenceGroup:"Pictures",reference:"Picture",referenceTitle:"Name",referenceSrc:"Address",referenceSrcPlaceholder:"https://…/photo.jpg",referenceKind:"Kind",referencePhoto:"Photo",referencePanorama:"Panorama (360°)",referenceCredit:"Credit",referenceCreditUrl:"Credit link",referenceT:"Taken at",referenceDrawing:"Drawn on",referenceOpacity:"Opacity",referenceHeading:"Heading",referencePitch:"Pitch",referenceRoll:"Roll",referenceFov:"Vertical field",referenceUsePose:"Use the observer's pose",addReferenceUrl:"Add from an address",addReferenceFile:"Add a file",deleteReference:"Delete picture",referenceEmbedded:"{kb} kB embedded in the recording — an address would keep it light",referenceUnreachable:"The picture could not be loaded: check the address, and that its site allows other sites to read it",referenceRegisterHint:"Drag to turn the picture, wheel to change its field; “Add a landmark” to point at a detail on the picture, then at the same one in the render",referenceLandmarkPicture:"Landmark {n}: click the point on the picture",referenceLandmarkScene:"Landmark {n}: click the same point in the render",referenceLandmarkOffPicture:"That click is not on the picture",referenceNotLoaded:"The picture has not arrived yet",referenceLandmarksFit:"{n} landmarks — {deg}° off on average",referenceLandmarks:"Landmarks",addReferenceLandmark:"Add a landmark",deleteReferenceLandmark:"Delete landmark",referenceLandmarkLabel:"Name",referenceLandmarkLabelPlaceholder:"Masking tree, fence…",referenceAdoptPose:"Adopt as the observer's pose",referenceAdoptRationale:"Measured on the picture “{title}”: {n} landmarks lined up, {deg}° of residual",referenceStreetSearch:"Street-level pictures nearby",referenceStreetSearching:"Looking for pictures taken nearby…",referenceStreetNone:"No street-level picture within {m} m (Panoramax)",referenceStreetFailed:"Panoramax could not be reached",referenceStreetAdd:"Add",traceImport:"Investigator's lines (KML, KMZ)",trace:"Trace",deleteTrace:"Delete trace",traceTitle:"Name",traceSource:"Source",traceImported:"{n} imported from {name}.",traceSkipped:"Left out: {what}.",traceNone:"No line, place or outline found in this file.",traceFailed:"This file could not be read.",traceKindPoint:"place",traceKindLine:"line",traceKindPolygon:"outline",referenceStreetItem:"{distance} m at {bearing}°, {date}{panorama}",referenceStreetPanorama:" — 360°",referenceStreetTitle:"Street-level picture {distance} m away at {bearing}°, {date}",skyLine:"Sky: {parts}",skyStarsEye:"stars down to magnitude {limit}, which is as faint as an eye went under this sky",skyStarsDeeper:"stars down to magnitude {limit} through a {device} — {gain} magnitudes past the {eye} the observer's own eyes reached",skyStarsShallower:"stars down to magnitude {limit} through a {device} — {gain} magnitudes short of the {eye} the observer's own eyes reached",skyStarsCatalogue:", drawn to {catalogue}, where this project's catalogue stops",skyStarsNone:"no star could be picked out of a sky this bright",skyDetails:"Show the records in full",skyDetailsHide:"Hide the records",skyShowerActive:"{name} — radiant {altitude}° above the horizon, {bearing} — about {rate}/h under this sky, over a sporadic background of {sporadic}/h",skyShowerBelowHorizon:"{name} is active, but its radiant is below the horizon — it can have produced nothing",skyNothingActive:"no meteor shower active on this date — a sporadic background of about {sporadic}/h",showMeteor:"Show me one",skyComet:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}, tail {tail}° long",skyCometNoTail:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyCometBelowHorizon:"{name} was there at magnitude {magnitude}, but below the horizon — nobody here saw it",skyCometInDaylight:"{name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} — but only {elongation}° from the Sun",showComet:"Show me the comet",skyNova:"{name}, a new star of magnitude {magnitude}, {altitude}° above the horizon {bearing}",skyNovaBelowHorizon:"{name} was shining at magnitude {magnitude}, but below the horizon: nobody here saw it",showNova:"Show me the new star",skySatellitePasses:"{count} satellites crossed this sky bright enough to be seen, the brightest {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatellitePassesOne:"one satellite crossed this sky bright enough to be seen: {name}, magnitude {magnitude}, {altitude}° above the horizon {bearing} at {time}",skySatelliteTrain:"among them a train of {count} Starlinks launched on {date}",skySatellitePassesNone:"by the orbital elements archived for that date, no lit satellite crossed this sky brightly enough to be seen",skySatelliteElementsGap:"no orbital elements archived near that date",skyReentries:"re-entries on record: {list}",skyReentriesMore:"{count} more",skyReentrySeen:"{name} came down at {time}, seen from {place} ({distance} km away)",skyReentryObserved:"{name} came down at {time}, seen",skyReentryOffset:", {minutes} min outside the observation",skyReentryPredicted:"{name} came down around {time} ± {hours} h, where unknown",skyReentryDay:"{name} came down on {date} (UTC), neither hour nor place known",skyFireballs:"{count} fireballs recorded by the Global Meteor Network, the brightest magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",skyFireballsOne:"a fireball recorded by the Global Meteor Network: magnitude {magnitude} at {time}, {altitude}° up {bearing}, {distance} km away ({stations} stations)",showFireball:"Show me the fireball",showSatellite:"Show me a satellite",skyOpticsPossible:"ice cloud enough, around the {source}, for {forms}",skyOpticsAlignment:" — everything but the rings needs crystals falling level, stated here at {alignment}% since no record holds it",skyOpticsHalo22:"a {angle}° ring",skyOpticsHalo46:"a {angle}° ring",skyOpticsParhelia:"sundogs {angle}° to either side",skyOpticsTangentArc:"an arc tangent on top of it",skyOpticsParhelicCircle:"a white circle right round the sky at its own height",skyOpticsCircumzenithal:"a circumzenithal arc {angle}° up",skyOpticsCircumhorizontal:"a circumhorizontal arc far below it",skyOpticsPillar:"a pillar standing over it",skyOpticsNoIce:"no ice cloud: no halo and no sundogs",skyOpticsHidden:"ice cloud above, but a lower deck between it and the observer",skyOpticsSun:"Sun",skyOpticsMoon:"Moon",skyBowPossible:"rain and sunlight enough for {forms}",skyBowMoon:"rain under a Moon {lit}% lit, enough for {forms} — a moonbow, which the eye sees as a white arc",skyGlowBand:"the Milky Way {contrast}× the sky behind it, {altitude}° up {bearing}",skyGlowCone:"the zodiacal light {contrast}× the sky behind it, {altitude}° up {bearing}, {elongation}° from the Sun — a faint tilted cone of light with blurred edges, gone within the hour",skyGlowZodiacalBand:"the zodiacal band {contrast}× the sky behind it, {altitude}° up {bearing} — the whole ecliptic faintly alight, which is not the sight people report",skyGlowMoon:"no Milky Way and no zodiacal light: a Moon {lit}% lit held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTwilight:"no Milky Way and no zodiacal light: twilight still held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowTowns:"no Milky Way and no zodiacal light: the towns' glow held the sky at {sky} magnitudes a square arcsecond, where they need 22",skyGlowNothingUp:"sky dark enough ({sky} magnitudes a square arcsecond) but neither the galactic plane nor the ecliptic stood high enough in it",skyBowPrimary:"a bow {radius}° across, its top {top}° up",skyBowSecondary:"a second, fainter one at {radius}° with its colours reversed",skyBowSourceTooHigh:"rain, but with the source {altitude}° up no bow could clear the horizon: they stand {radius}° from the point opposite it",skyBowHidden:"rain, but an unbroken deck between it and the light: no bow",skyBowNoSource:"rain, and nothing lit to make a bow of it",skySatellitesLit:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month",skySatellitesLitWith:"the Earth's shadow stood {height} km above the observer, so low orbit was still in sunlight — {count} tracked objects were in orbit that month, among them {eras}",skySatellitesShadowed:"the Earth's shadow stood {height} km above the observer: of the {count} tracked objects in orbit that month, nothing in low orbit was lit",skySatellitesNotYet:"nothing had been put in orbit yet",skySatellitesDaylight:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skySatellitesDaylightOne:"everything in orbit was sunlit, as it always is by day, and {eras} could outshine even this sky",skyUnknown:"cannot be worked out without a date and a place",lookAtDecor:"Look at it",addDecor:"Add",deleteDecor:"Delete decor",decorSightingUrl:"Their own recording URL",viewAccount:"View the account",noObserverRecording:"No recording URL set for this observer",masks:"Masks",addObserver:"Add observer",narrativePlaceholder:"What the observer reported, in their own words",narrativeSource:"Drafted by",narrativeNeedsSetting:'Fill in "{setting}" ({source}) to generate a reconstruction from the account',narrativeNeedsAsk:"Nothing to send yet",narrativeRemember:"Remember on this device",narrativeDraft:"Generate reconstruction",narrativeStop:"Stop",narrativeWorking:"Reading the account…",narrativeApplied:"{count} fields written into the editor",narrativeUnchanged:"The account states nothing the recording can hold yet",narrativeStated:"What the observer said",narrativeDerived:"Worked out from the account",narrativeAssumed:"Guessed, so the reconstruction runs — check these",narrativeGaps:"What nothing could settle",narrativeErrorCredential:"No key, or one that was refused — check it at console.anthropic.com",narrativeErrorRateLimited:"Too many requests on your account: wait a moment and ask again",narrativeErrorRefused:"The account was not answered. Rephrasing may help; asking again will not",narrativeErrorMalformed:"The answer was not a usable draft — worth asking once more",narrativeErrorUnreachable:"Nothing answered: check the connection",narrativeErrorRejected:"Refused: {detail}",observerAge:"Age then",observerOccupation:"Occupation",accountSource:"Account obtained",accountUrl:"Source (URL)",accountSourceUnknown:"unknown",accountSourceOnSite:"on-site investigation",accountSourceInterview:"interview in person",accountSourceTelephone:"by telephone",accountSourceQuestionnaire:"questionnaire",accountSourceLetter:"the observer wrote it",accountSourceSocialMedia:"the observer posted it online",accountSourcePress:"press or broadcast",accountFollowedUp:"Followed up",accountUnknown:"unknown",accountYes:"yes",accountNo:"no",questionUnanswered:"Nothing in this recording answers one of the questions a reconstruction needs settled",durationRequired:"The observation needs a length to be replayed at all — state one, or an end time, which may be approximate",questionsUnanswered:"{count} of the questions a full reconstruction answers are unanswered here"},ZI=Object.freeze(Object.defineProperty({__proto__:null,sightingEditorMessages_en:yp},Symbol.toStringTag,{value:"Module"})),Gv=new Set;$h();yI();const Za={width:48,height:28},jI=2500,Vv=40,JI=10,Wv=600,Xv=900,ja=2e-4,QI=900,e4=-1.46,t4=3,Zc=.2,i4=3,n4=.01,s4=1.6,Bu=2e3,r4=250,$v=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),pr=4,ll="ufo-1",Yv=["oval","polygon"],a4={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function o4(a){return a.kind==="oval"?"oval":"polygon"}const l4=-6,c4=21;class qt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=qI[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;autoFilledTimeZone;timeZones=new $I;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=GI();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;obsTimeNativeInput;obsEndTimeNativeInput;obsTimeQualifier;obsEndTimeQualifier;edtfModeButton;edtfMode=!1;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new ku(zI());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;focalLengthInput;labelFocalLength;focalFovOutput;unitFocalLength;labelFNumber;labelExposure;labelFocusDistance;fNumberInput;exposureInput;focusDistanceInput;labelColor;labelTransparency;labelHalo;labelBlur;labelBrightness;labelShape;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelLatitude;labelLongitude;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;highCloudCoverInput;iceCrystalAlignmentInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorKindSelect;addDecorObserverButton;addDecorBuildingButton;deleteDecorButton;decorSelect;decorTitleInput;decorEastInput;decorNorthInput;decorHeadingInput;decorColorInput;decorLitInput;decorLightRigSelect;lookAtDecorButton;decorAltitudeInput;labelDecorAltitude;decorSightingUrlInput;decorModelProvider=oh[0].create();confirmOverlay;confirmMessage;confirmAcceptButton;confirmDeclineButton;confirmAnswer;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorWidthInput;decorLengthInput;decorHeightInput;decorModelSelect;decorModelAdvanced;decorModelCatalogueNote;decorModelUrlInput;decorModelTitleInput;decorModelAuthorInput;decorModelLicenseInput;decorModelSourceInput;decorFloorsInput;decorOccupiedFloorInput;decorObserverSideSelect;decorWindowInputs;labelDecorSide;optionObserverSide;labelDecor;labelDecorGroup;labelDecorTitle;labelDecorEast;labelDecorNorth;labelDecorHeading;labelDecorColor;labelDecorLit;labelDecorSightingUrl;labelMilestones;labelMilestoneLabel;labelMilestoneNote;labelDecorWidth;labelDecorLength;labelDecorHeight;labelDecorModel;labelDecorModelAdvanced;labelDecorModelUrl;labelDecorModelTitle;labelDecorModelAuthor;labelDecorModelLicense;labelDecorModelSource;labelDecorFloors;labelDecorOccupiedFloor;labelDecorObserverSide;labelDecorWindows;optionObserverSideNone;optionDecorBuilding;optionDecorTree;optionDecorShrub;optionDecorBridge;optionDecorCrop;optionDecorMound;optionDecorStreetlight;optionDecorVehicle;optionDecorAircraft;optionDecorEntity;labelDecorLights;optionDecorObserver;recorder;isRecording=!1;messages=yp;currentAppearance={...a4};currentSourceId=ll;selectedSourceIds=new Set([ll]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSrcInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;addReferenceUrlButton;addReferenceFileInput;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;referenceStreetSearchButton;addTraceFileInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;labelTrace;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$=new co;referenceFields;labelReferenceGroup;labelReference;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;labelAddReferenceFile;contextMenuDecorId;contextMenuPoint;dragState;cameraDragState;hoverCursor;indoorLookYawDeg=0;indoorLookPitchDeg=0;lastInhabitedKey;handleKeyDown=e=>{if(e.key==="Escape"&&(this.isRecording&&this.toggleRecording(),this.confirmOverlay.hidden||this.answerConfirm(!1),(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),$v.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return;$v.has(e.key)?this.moveOrResizeSelectedShapes(e):this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0;this.endDrag(),e!==void 0&&this.selectDecor(e)};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${qy}</style>${Yy}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.sceneElement=document.createElement(Vh),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.setAttribute(ha,""),this.sceneElement.animateWhilePaused=!0,this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",t=>{const{lat:i,lng:n}=t.detail;this.latInput.value=String(Number(i.toFixed(6))),this.lngInput.value=String(Number(n.toFixed(6))),this.updateObserver()}),this.ufoElement.enableClickToPlay=!1,this.ufoElement.showToolbar=!1,this.shadow.getElementById("ufo-slot").replaceWith(this.sceneElement),this.ufoElement.hostControls(this.shadow.getElementById("scene-controls")),this.recordButton=this.shadow.getElementById("record"),this.samplingRateInput=this.shadow.getElementById("samplingRate"),this.presetsGroup=this.shadow.getElementById("presets-group"),this.presetButtons={oval:this.shadow.getElementById("preset-oval"),polygon:this.shadow.getElementById("preset-polygon")},this.colorInput=this.shadow.getElementById("color"),this.transparencyInput=this.shadow.getElementById("transparency"),this.haloScaleInput=this.shadow.getElementById("haloScale"),this.blurInput=this.shadow.getElementById("blur"),this.brightnessInput=this.shadow.getElementById("brightness"),this.blurBoundOutput=this.shadow.getElementById("blur-bound"),this.sourceSelect=this.shadow.getElementById("source"),this.shapeTitleInput=this.shadow.getElementById("shapeTitle"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.apparentWidthInput=this.shadow.getElementById("apparentWidth"),this.realWidthInput=this.shadow.getElementById("realWidth"),this.objectDistanceInput=this.shadow.getElementById("objectDistance"),this.sizeLockSelect=this.shadow.getElementById("sizeLock"),this.apparentSizeOutput=this.shadow.getElementById("apparent-size"),this.realSizeOutput=this.shadow.getElementById("real-size"),this.clearDistanceHypothesisButton=this.shadow.getElementById("clear-distance-hypothesis"),this.depthBasisOutput=this.shadow.getElementById("depth-basis"),this.addShapeButton=this.shadow.getElementById("add-shape"),this.deleteShapeButton=this.shadow.getElementById("delete-shape"),this.contextMenu=this.shadow.getElementById("context-menu"),this.contextGroupButton=this.shadow.getElementById("context-group"),this.contextUngroupButton=this.shadow.getElementById("context-ungroup"),this.contextBringToFrontButton=this.shadow.getElementById("context-bring-to-front"),this.contextSendToBackButton=this.shadow.getElementById("context-send-to-back"),this.contextDeleteButton=this.shadow.getElementById("context-delete"),this.contextAddVertexButton=this.shadow.getElementById("context-add-vertex"),this.contextDeleteVertexButton=this.shadow.getElementById("context-delete-vertex"),this.decorContextMenu=this.shadow.getElementById("decor-context-menu"),this.contextViewAccountButton=this.shadow.getElementById("context-view-account"),this.contextMasksSubmenu=this.shadow.getElementById("context-masks-submenu"),this.labelContextMasks=this.shadow.getElementById("label-context-masks"),this.playPauseButton=this.shadow.getElementById("play-pause"),this.seekInput=this.shadow.getElementById("seek"),this.previousMarkButton=this.shadow.getElementById("previous-mark"),this.nextMarkButton=this.shadow.getElementById("next-mark"),this.timelineMarks=new ml(this.seekInput,this.shadow.getElementById("timeline-marks")),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.switchTimeDisplay()),t.addEventListener("keydown",i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),this.switchTimeDisplay())});this.durationInput=this.shadow.getElementById("durationSeconds"),this.exportButton=this.shadow.getElementById("export"),this.importFileInput=this.shadow.getElementById("import-file"),this.importUrlInput=this.shadow.getElementById("import-url"),this.importUrlButton=this.shadow.getElementById("import-url-button"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),this.narrativeRememberInput=this.shadow.getElementById("narrativeRemember"),this.narrativeDraftButton=this.shadow.getElementById("narrative-draft"),this.narrativeStopButton=this.shadow.getElementById("narrative-stop"),this.narrativeStatus=this.shadow.getElementById("narrative-status"),this.narrativeReport=this.shadow.getElementById("narrative-report"),this.placeNameInput=this.shadow.getElementById("placeName"),this.searchPlaceButton=this.shadow.getElementById("search-place"),this.placeMatchRow=this.shadow.getElementById("place-match-row"),this.placeMatchSelect=this.shadow.getElementById("placeMatch"),this.placeStatusText=this.shadow.getElementById("place-status-text"),this.latInput=this.shadow.getElementById("lat"),this.lngInput=this.shadow.getElementById("lng"),this.headingInput=this.shadow.getElementById("heading"),this.headingUnit=this.shadow.getElementById("heading-unit"),this.pitchInput=this.shadow.getElementById("pitch"),this.rollInput=this.shadow.getElementById("roll"),this.swayInput=this.shadow.getElementById("sway"),this.lightPollutionInput=this.shadow.getElementById("lightPollution"),this.lightPollutionStatusText=this.shadow.getElementById("light-pollution-status-text"),this.lightPollutionSourceRow=this.shadow.getElementById("light-pollution-source-row"),this.elevationInput=this.shadow.getElementById("elevation"),this.groundElevationOutput=this.shadow.getElementById("ground-elevation"),this.obsTimeInput=this.shadow.getElementById("obs-time"),this.obsEndTimeInput=this.shadow.getElementById("obs-end-time"),this.obsTimeNativeInput=this.shadow.getElementById("obs-time-native"),this.obsEndTimeNativeInput=this.shadow.getElementById("obs-end-time-native"),this.obsTimeQualifier=this.shadow.getElementById("obs-time-qualifier"),this.obsEndTimeQualifier=this.shadow.getElementById("obs-end-time-qualifier"),this.edtfModeButton=this.shadow.getElementById("edtf-mode"),this.observerIdInput=this.shadow.getElementById("observerId"),this.observerTitleInput=this.shadow.getElementById("observerTitle"),this.observerLastNameInput=this.shadow.getElementById("observerLastName"),this.observerFirstNamesInput=this.shadow.getElementById("observerFirstNames"),this.observerAgeInput=this.shadow.getElementById("observerAge"),this.observerOccupationInput=this.shadow.getElementById("observerOccupation"),this.accountSourceSelect=this.shadow.getElementById("accountSource"),this.accountUrlInput=this.shadow.getElementById("accountUrl"),this.labelAccountUrl=this.shadow.getElementById("label-account-url"),this.accountFollowedUpSelect=this.shadow.getElementById("accountFollowedUp"),this.sightingIdInput=this.shadow.getElementById("sightingId"),this.descriptionInput=this.shadow.getElementById("description"),this.tagsInput=this.shadow.getElementById("tags"),this.cloudCoverInput=this.shadow.getElementById("cloudCover"),this.highCloudCoverInput=this.shadow.getElementById("highCloudCover"),this.iceCrystalAlignmentInput=this.shadow.getElementById("iceCrystalAlignment"),this.cloudDarknessInput=this.shadow.getElementById("cloudDarkness"),this.cloudBaseInput=this.shadow.getElementById("cloudBase"),this.precipitationTypeSelect=this.shadow.getElementById("precipitationType"),this.precipitationIntensityInput=this.shadow.getElementById("precipitationIntensity"),this.windDirectionInput=this.shadow.getElementById("windDirection"),this.windSpeedInput=this.shadow.getElementById("windSpeed"),this.stormInput=this.shadow.getElementById("storm"),this.weatherInferredInput=this.shadow.getElementById("weatherInferred"),this.weatherSourceText=this.shadow.getElementById("weather-source-text"),this.skyCandidatesOutput=this.shadow.getElementById("sky-candidates"),this.showMeteorButton=this.shadow.getElementById("show-meteor"),this.showCometButton=this.shadow.getElementById("show-comet"),this.showNovaButton=this.shadow.getElementById("show-nova"),this.showSatelliteButton=this.shadow.getElementById("show-satellite"),this.showFireballButton=this.shadow.getElementById("show-fireball"),this.weatherSourceLink=this.shadow.getElementById("weather-source-link"),this.weatherFields=[this.cloudCoverInput,this.highCloudCoverInput,this.iceCrystalAlignmentInput,this.cloudDarknessInput,this.cloudBaseInput,this.precipitationTypeSelect,this.precipitationIntensityInput,this.windDirectionInput,this.windSpeedInput,this.stormInput],this.soundKindSelect=this.shadow.getElementById("soundKind"),this.soundVolumeInput=this.shadow.getElementById("soundVolume"),this.soundPitchInput=this.shadow.getElementById("soundPitch"),this.soundPitchValue=this.shadow.getElementById("sound-pitch-value"),this.soundSrcInput=this.shadow.getElementById("soundSrc"),this.soundFields=[this.soundKindSelect,this.soundVolumeInput,this.soundPitchInput,this.soundSrcInput],this.buildSoundKindOptions(),this.instrumentSelect=this.shadow.getElementById("instrument"),this.focalLengthInput=this.shadow.getElementById("focalLength"),this.labelFocalLength=this.shadow.getElementById("label-focal-length"),this.focalFovOutput=this.shadow.getElementById("focal-fov"),this.unitFocalLength=this.shadow.getElementById("unit-focal-length"),this.labelFNumber=this.shadow.getElementById("label-f-number"),this.labelExposure=this.shadow.getElementById("label-exposure"),this.fNumberInput=this.shadow.getElementById("fNumber"),this.exposureInput=this.shadow.getElementById("exposureSeconds"),this.focusDistanceInput=this.shadow.getElementById("focusDistance"),this.labelFocusDistance=this.shadow.getElementById("label-focus-distance"),this.refreshInstrumentOptions(),this.labelColor=this.shadow.getElementById("label-color"),this.labelTransparency=this.shadow.getElementById("label-transparency"),this.labelHalo=this.shadow.getElementById("label-halo"),this.labelBlur=this.shadow.getElementById("label-blur"),this.labelBrightness=this.shadow.getElementById("label-brightness"),this.labelShape=this.shadow.getElementById("label-shape"),this.labelShapeTitle=this.shadow.getElementById("label-shape-title"),this.labelUtcOffset=this.shadow.getElementById("label-utc-offset"),this.labelApparentWidth=this.shadow.getElementById("label-apparent-width"),this.labelRealWidth=this.shadow.getElementById("label-real-width"),this.labelObjectDistance=this.shadow.getElementById("label-object-distance"),this.labelSizeLock=this.shadow.getElementById("label-size-lock"),this.labelSamplingRate=this.shadow.getElementById("label-sampling-rate"),this.labelSoundGroup=this.shadow.getElementById("label-sound-group"),this.labelSoundKind=this.shadow.getElementById("label-sound-kind"),this.labelSoundVolume=this.shadow.getElementById("label-sound-volume"),this.labelSoundPitch=this.shadow.getElementById("label-sound-pitch"),this.labelSoundSrc=this.shadow.getElementById("label-sound-src"),this.labelReferenceGroup=this.shadow.getElementById("label-reference-group"),this.labelReference=this.shadow.getElementById("label-reference"),this.labelReferenceTitle=this.shadow.getElementById("label-reference-title"),this.labelReferenceSrc=this.shadow.getElementById("label-reference-src"),this.labelReferenceKind=this.shadow.getElementById("label-reference-kind"),this.labelReferenceCredit=this.shadow.getElementById("label-reference-credit"),this.labelReferenceCreditUrl=this.shadow.getElementById("label-reference-credit-url"),this.labelReferenceT=this.shadow.getElementById("label-reference-t"),this.labelReferenceDrawing=this.shadow.getElementById("label-reference-drawing"),this.labelReferenceOpacity=this.shadow.getElementById("label-reference-opacity"),this.labelReferenceHeading=this.shadow.getElementById("label-reference-heading"),this.labelReferencePitch=this.shadow.getElementById("label-reference-pitch"),this.labelReferenceRoll=this.shadow.getElementById("label-reference-roll"),this.labelReferenceFov=this.shadow.getElementById("label-reference-fov"),this.labelAddReferenceFile=this.shadow.getElementById("label-add-reference-file"),this.labelDuration=this.shadow.getElementById("label-duration"),this.placeSourceRow=this.shadow.getElementById("place-source-row"),this.weatherSourceRow=this.shadow.getElementById("weather-source-row"),this.terrainSourceRows=this.shadow.getElementById("terrain-source-rows"),this.labelPlaceName=this.shadow.getElementById("label-place-name"),this.labelPlaceMatch=this.shadow.getElementById("label-place-match"),this.labelLatitude=this.shadow.getElementById("label-lat"),this.labelLongitude=this.shadow.getElementById("label-lng"),this.labelHeading=this.shadow.getElementById("label-heading"),this.labelPitch=this.shadow.getElementById("label-pitch"),this.labelRoll=this.shadow.getElementById("label-roll"),this.labelSway=this.shadow.getElementById("label-sway"),this.labelLightPollution=this.shadow.getElementById("label-light-pollution"),this.labelElevation=this.shadow.getElementById("label-elevation"),this.labelObservationTime=this.shadow.getElementById("label-observation-time"),this.labelObservationEndTime=this.shadow.getElementById("label-observation-end-time"),this.labelObserverId=this.shadow.getElementById("label-observer-id"),this.labelObserverTitle=this.shadow.getElementById("label-observer-title"),this.labelObserverLastName=this.shadow.getElementById("label-observer-last-name"),this.labelObserverFirstNames=this.shadow.getElementById("label-observer-first-names"),this.labelObserverAge=this.shadow.getElementById("label-observer-age"),this.labelObserverOccupation=this.shadow.getElementById("label-observer-occupation"),this.labelAccountSource=this.shadow.getElementById("label-account-source"),this.labelAccountFollowedUp=this.shadow.getElementById("label-account-followed-up"),this.labelSightingId=this.shadow.getElementById("label-sighting-id"),this.labelDescription=this.shadow.getElementById("label-description"),this.labelTags=this.shadow.getElementById("label-tags"),this.labelImportFile=this.shadow.getElementById("label-import-file"),this.labelImportUrl=this.shadow.getElementById("label-import-url"),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),this.labelNarrativeRemember=this.shadow.getElementById("label-narrative-remember"),this.labelShapeGroup=this.shadow.getElementById("label-shape-group"),this.labelTemporalGroup=this.shadow.getElementById("label-temporal-group"),this.labelLocationGroup=this.shadow.getElementById("label-location-group"),this.labelObservationGroup=this.shadow.getElementById("label-observation-group"),this.labelObserverGroup=this.shadow.getElementById("label-observer-group"),this.labelWeatherGroup=this.shadow.getElementById("label-weather-group"),this.labelCloudCover=this.shadow.getElementById("label-cloud-cover"),this.labelHighCloud=this.shadow.getElementById("label-high-cloud"),this.labelIceAlignment=this.shadow.getElementById("label-ice-alignment"),this.labelCloudDarkness=this.shadow.getElementById("label-cloud-darkness"),this.labelCloudBase=this.shadow.getElementById("label-cloud-base"),this.labelPrecipitationType=this.shadow.getElementById("label-precipitation-type"),this.labelPrecipitationIntensity=this.shadow.getElementById("label-precipitation-intensity"),this.labelWindDirection=this.shadow.getElementById("label-wind-direction"),this.labelWindSpeed=this.shadow.getElementById("label-wind-speed"),this.labelStorm=this.shadow.getElementById("label-storm"),this.labelCloudsGroup=this.shadow.getElementById("label-clouds-group"),this.labelShapesSubgroup=this.shadow.getElementById("label-shapes-subgroup"),this.labelBodiesSubgroup=this.shadow.getElementById("label-bodies-subgroup"),this.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.labelInstrument=this.shadow.getElementById("label-instrument"),this.optionPrecipitationNone=this.shadow.getElementById("option-precipitation-none"),this.optionPrecipitationRain=this.shadow.getElementById("option-precipitation-rain"),this.optionPrecipitationSnow=this.shadow.getElementById("option-precipitation-snow"),this.optionPrecipitationHail=this.shadow.getElementById("option-precipitation-hail"),this.decorKindSelect=this.shadow.getElementById("decorKind"),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.addDecorBuildingButton=this.shadow.getElementById("add-decor-building"),this.deleteDecorButton=this.shadow.getElementById("delete-decor"),this.decorSelect=this.shadow.getElementById("decor"),this.referenceSelect=this.shadow.getElementById("reference"),this.deleteReferenceButton=this.shadow.getElementById("delete-reference"),this.referenceTitleInput=this.shadow.getElementById("referenceTitle"),this.referenceSrcInput=this.shadow.getElementById("referenceSrc"),this.referenceKindSelect=this.shadow.getElementById("referenceKind"),this.referenceCreditInput=this.shadow.getElementById("referenceCredit"),this.referenceCreditUrlInput=this.shadow.getElementById("referenceCreditUrl"),this.referenceTInput=this.shadow.getElementById("referenceT"),this.referenceDrawingInput=this.shadow.getElementById("referenceDrawing"),this.referenceOpacityInput=this.shadow.getElementById("referenceOpacity"),this.referenceHeadingInput=this.shadow.getElementById("referenceHeading"),this.referencePitchInput=this.shadow.getElementById("referencePitch"),this.referenceRollInput=this.shadow.getElementById("referenceRoll"),this.referenceFovInput=this.shadow.getElementById("referenceFov"),this.referenceUsePoseButton=this.shadow.getElementById("reference-use-pose"),this.referenceStatus=this.shadow.getElementById("reference-status"),this.addReferenceUrlButton=this.shadow.getElementById("add-reference-url"),this.addReferenceFileInput=this.shadow.getElementById("add-reference-file"),this.referenceLandmarksSelect=this.shadow.getElementById("reference-landmarks"),this.addReferenceLandmarkButton=this.shadow.getElementById("add-reference-landmark"),this.deleteReferenceLandmarkButton=this.shadow.getElementById("delete-reference-landmark"),this.referenceLandmarkLabelInput=this.shadow.getElementById("referenceLandmarkLabel"),this.labelReferenceLandmarks=this.shadow.getElementById("label-reference-landmarks"),this.labelReferenceLandmarkLabel=this.shadow.getElementById("label-reference-landmark-label"),this.referenceAdoptPoseButton=this.shadow.getElementById("reference-adopt-pose"),this.referenceStreetSearchButton=this.shadow.getElementById("reference-street-search"),this.addTraceFileInput=this.shadow.getElementById("add-trace-file"),this.traceSelect=this.shadow.getElementById("trace"),this.deleteTraceButton=this.shadow.getElementById("delete-trace"),this.traceTitleInput=this.shadow.getElementById("traceTitle"),this.traceSourceInput=this.shadow.getElementById("traceSource"),this.traceStatus=this.shadow.getElementById("trace-status"),this.labelTraceImport=this.shadow.getElementById("label-trace-import"),this.labelTrace=this.shadow.getElementById("label-trace"),this.labelTraceTitle=this.shadow.getElementById("label-trace-title"),this.labelTraceSource=this.shadow.getElementById("label-trace-source"),this.referenceStreetSelect=this.shadow.getElementById("reference-street"),this.referenceStreetAddButton=this.shadow.getElementById("reference-street-add"),this.referenceFields=[this.referenceTitleInput,this.referenceSrcInput,this.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceDrawingInput,this.referenceOpacityInput,this.referenceHeadingInput,this.referencePitchInput,this.referenceRollInput,this.referenceFovInput],this.decorTitleInput=this.shadow.getElementById("decorTitle"),this.decorEastInput=this.shadow.getElementById("decorEast"),this.decorNorthInput=this.shadow.getElementById("decorNorth"),this.decorHeadingInput=this.shadow.getElementById("decorHeading"),this.decorColorInput=this.shadow.getElementById("decorColor"),this.decorLitInput=this.shadow.getElementById("decorLit"),this.decorLightRigSelect=this.shadow.getElementById("decorLightRig"),this.lookAtDecorButton=this.shadow.getElementById("look-at-decor"),this.decorAltitudeInput=this.shadow.getElementById("decorAltitude"),this.labelDecorAltitude=this.shadow.getElementById("label-decor-altitude"),this.decorSightingUrlInput=this.shadow.getElementById("decorSightingUrl"),this.confirmOverlay=this.shadow.getElementById("confirm-overlay"),this.confirmMessage=this.shadow.getElementById("confirm-message"),this.confirmAcceptButton=this.shadow.getElementById("confirm-ok"),this.confirmDeclineButton=this.shadow.getElementById("confirm-cancel"),this.milestoneSelect=this.shadow.getElementById("milestone"),this.milestoneLabelInput=this.shadow.getElementById("milestoneLabel"),this.milestoneNoteInput=this.shadow.getElementById("milestoneNote"),this.addMilestoneButton=this.shadow.getElementById("add-milestone"),this.deleteMilestoneButton=this.shadow.getElementById("delete-milestone"),this.goToMilestoneButton=this.shadow.getElementById("go-to-milestone"),this.decorWidthInput=this.shadow.getElementById("decorWidth"),this.decorLengthInput=this.shadow.getElementById("decorLength"),this.decorHeightInput=this.shadow.getElementById("decorHeight"),this.decorModelSelect=this.shadow.getElementById("decorModel"),this.decorModelAdvanced=this.shadow.getElementById("decor-model-advanced"),this.decorModelCatalogueNote=this.shadow.getElementById("decor-model-catalogue"),this.decorModelUrlInput=this.shadow.getElementById("decorModelUrl"),this.decorModelTitleInput=this.shadow.getElementById("decorModelTitle"),this.decorModelAuthorInput=this.shadow.getElementById("decorModelAuthor"),this.decorModelLicenseInput=this.shadow.getElementById("decorModelLicense"),this.decorModelSourceInput=this.shadow.getElementById("decorModelSource"),this.decorFloorsInput=this.shadow.getElementById("decorFloors"),this.decorOccupiedFloorInput=this.shadow.getElementById("decorOccupiedFloor"),this.decorObserverSideSelect=this.shadow.getElementById("decorObserverSide"),this.decorWindowInputs={front:this.shadow.getElementById("decorWindowFront"),behind:this.shadow.getElementById("decorWindowBehind"),left:this.shadow.getElementById("decorWindowLeft"),right:this.shadow.getElementById("decorWindowRight"),"front-left":this.shadow.getElementById("decorWindowFrontLeft"),"front-right":this.shadow.getElementById("decorWindowFrontRight"),"behind-left":this.shadow.getElementById("decorWindowBehindLeft"),"behind-right":this.shadow.getElementById("decorWindowBehindRight")},this.labelDecorSide={front:this.shadow.getElementById("label-decor-window-front"),behind:this.shadow.getElementById("label-decor-window-behind"),left:this.shadow.getElementById("label-decor-window-left"),right:this.shadow.getElementById("label-decor-window-right"),"front-left":this.shadow.getElementById("label-decor-window-front-left"),"front-right":this.shadow.getElementById("label-decor-window-front-right"),"behind-left":this.shadow.getElementById("label-decor-window-behind-left"),"behind-right":this.shadow.getElementById("label-decor-window-behind-right")},this.optionObserverSide={front:this.shadow.getElementById("option-observer-side-front"),behind:this.shadow.getElementById("option-observer-side-behind"),left:this.shadow.getElementById("option-observer-side-left"),right:this.shadow.getElementById("option-observer-side-right"),"front-left":this.shadow.getElementById("option-observer-side-front-left"),"front-right":this.shadow.getElementById("option-observer-side-front-right"),"behind-left":this.shadow.getElementById("option-observer-side-behind-left"),"behind-right":this.shadow.getElementById("option-observer-side-behind-right")},this.optionObserverSideNone=this.shadow.getElementById("option-observer-side-none"),this.labelDecor=this.shadow.getElementById("label-decor"),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelDecorTitle=this.shadow.getElementById("label-decor-title"),this.labelDecorEast=this.shadow.getElementById("label-decor-east"),this.labelDecorNorth=this.shadow.getElementById("label-decor-north"),this.labelDecorHeading=this.shadow.getElementById("label-decor-heading"),this.labelDecorColor=this.shadow.getElementById("label-decor-color"),this.labelDecorLit=this.shadow.getElementById("label-decor-lit"),this.labelDecorSightingUrl=this.shadow.getElementById("label-decor-sighting-url"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.labelDecorWidth=this.shadow.getElementById("label-decor-width"),this.labelDecorLength=this.shadow.getElementById("label-decor-length"),this.labelDecorHeight=this.shadow.getElementById("label-decor-height"),this.labelDecorModel=this.shadow.getElementById("label-decor-model"),this.labelDecorModelAdvanced=this.shadow.getElementById("label-decor-model-advanced"),this.labelDecorModelUrl=this.shadow.getElementById("label-decor-model-url"),this.labelDecorModelTitle=this.shadow.getElementById("label-decor-model-title"),this.labelDecorModelAuthor=this.shadow.getElementById("label-decor-model-author"),this.labelDecorModelLicense=this.shadow.getElementById("label-decor-model-license"),this.labelDecorModelSource=this.shadow.getElementById("label-decor-model-source"),this.labelDecorFloors=this.shadow.getElementById("label-decor-floors"),this.labelDecorOccupiedFloor=this.shadow.getElementById("label-decor-occupied-floor"),this.labelDecorObserverSide=this.shadow.getElementById("label-decor-observer-side"),this.labelDecorWindows=this.shadow.getElementById("label-decor-windows"),this.optionDecorBuilding=this.shadow.getElementById("option-decor-building"),this.optionDecorTree=this.shadow.getElementById("option-decor-tree"),this.optionDecorShrub=this.shadow.getElementById("option-decor-shrub"),this.optionDecorBridge=this.shadow.getElementById("option-decor-bridge"),this.optionDecorCrop=this.shadow.getElementById("option-decor-crop"),this.optionDecorMound=this.shadow.getElementById("option-decor-mound"),this.optionDecorStreetlight=this.shadow.getElementById("option-decor-streetlight"),this.optionDecorVehicle=this.shadow.getElementById("option-decor-vehicle"),this.optionDecorAircraft=this.shadow.getElementById("option-decor-aircraft"),this.optionDecorEntity=this.shadow.getElementById("option-decor-entity"),this.labelDecorLights=this.shadow.getElementById("label-decor-lights"),this.optionDecorObserver=this.shadow.getElementById("option-decor-observer"),this.ufoElement.canvasElement.addEventListener("pointerdown",t=>{this.focus({preventScroll:!0}),this.onPointerDown(t)}),this.ufoElement.canvasElement.addEventListener("pointermove",t=>this.onPointerMove(t)),this.ufoElement.canvasElement.addEventListener("contextmenu",t=>this.onContextMenu(t)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextBringToFrontButton.addEventListener("click",()=>this.bringSelectedToFront()),this.contextSendToBackButton.addEventListener("click",()=>this.sendSelectedToBack()),this.contextDeleteButton.addEventListener("click",()=>{this.hideContextMenu(),this.deleteShape()}),this.contextAddVertexButton.addEventListener("click",()=>this.addVertexAtContextMenu()),this.contextDeleteVertexButton.addEventListener("click",()=>this.deleteVertexAtContextMenu()),this.contextViewAccountButton.addEventListener("click",()=>this.viewObserverAccount()),this.playPauseButton.addEventListener("click",()=>{this.sceneElement.resumeWeatherAudio(),this.ufoElement.togglePlayPause(),this.syncPlaybackControls()}),this.seekInput.addEventListener("input",()=>this.ufoElement.currentTime=this.timelineMarks.snap(Number(this.seekInput.value))),this.previousMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.previous(this.ufoElement.currentTime))),this.nextMarkButton.addEventListener("click",()=>this.goToMark(this.timelineMarks.next(this.ufoElement.currentTime))),this.recordButton.addEventListener("click",()=>this.toggleRecording()),this.addShapeButton.addEventListener("click",()=>this.addShape()),this.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.importFileInput.addEventListener("change",()=>this.importFromFile()),this.importUrlButton.addEventListener("click",()=>this.importFromUrl()),this.accountSourceSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.accountUrlInput.addEventListener("input",()=>this.updateSourceUrl()),this.accountFollowedUpSelect.addEventListener("change",()=>this.updateObserverMetadata()),this.swayInput.addEventListener("input",()=>{this.ufoElement.sighting.sway=this.numberOrUndefined(this.swayInput.value),this.ufoElement.refresh()}),this.lightPollutionInput.addEventListener("input",()=>{const t=this.ufoElement.sighting;t.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),t.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),t.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.narrativeRememberInput.addEventListener("change",()=>this.rememberNarrativeSettings()),this.renderNarrativeSettings(),this.durationInput.addEventListener("input",()=>{this.ufoElement.durationSeconds=this.durationInput.value===""?void 0:Number(this.durationInput.value),this.ufoElement.refresh(),this.updateDurationValidity(),this.scheduleWeatherLookup()}),this.sourceSelect.addEventListener("change",()=>this.selectUnit(this.sourceSelect.value)),this.shapeTitleInput.addEventListener("input",()=>this.updateShapeTitle()),this.apparentWidthInput.addEventListener("input",()=>this.typing(this.apparentWidthInput,()=>this.onApparentWidthInput())),this.realWidthInput.addEventListener("input",()=>this.typing(this.realWidthInput,()=>this.onRealWidthInput())),this.objectDistanceInput.addEventListener("input",()=>this.typing(this.objectDistanceInput,()=>this.onDistanceInput())),this.sizeLockSelect.addEventListener("change",()=>this.applySizeLock()),this.clearDistanceHypothesisButton.addEventListener("click",()=>this.clearDistanceHypothesis()),this.addDecorObserverButton.addEventListener("click",()=>this.addDecor("observer")),this.addDecorBuildingButton.addEventListener("click",()=>this.addDecor()),this.deleteDecorButton.addEventListener("click",()=>this.deleteDecor()),this.decorSelect.addEventListener("change",()=>this.selectDecor(this.decorSelect.value)),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const t of this.referenceFields)t.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.addReferenceUrlButton.addEventListener("click",()=>this.addReferenceFromAddress()),this.addReferenceFileInput.addEventListener("change",()=>void this.addReferenceFromFile()),this.addReferenceLandmarkButton.addEventListener("click",()=>this.armLandmark()),this.deleteReferenceLandmarkButton.addEventListener("click",()=>this.deleteLandmark()),this.referenceLandmarksSelect.addEventListener("change",()=>this.selectLandmark(this.referenceLandmarksSelect.value)),this.referenceLandmarkLabelInput.addEventListener("input",()=>this.updateLandmarkLabel()),this.referenceAdoptPoseButton.addEventListener("click",()=>this.adoptReferencePose()),this.referenceStreetSearchButton.addEventListener("click",()=>void this.searchStreetPictures()),this.addTraceFileInput.addEventListener("change",()=>void this.addTracesFromFile()),this.traceSelect.addEventListener("change",()=>this.selectTrace(this.traceSelect.value)),this.deleteTraceButton.addEventListener("click",()=>this.deleteTrace()),this.traceTitleInput.addEventListener("input",()=>this.writeTraceFields()),this.traceSourceInput.addEventListener("input",()=>this.writeTraceFields()),this.referenceStreetAddButton.addEventListener("click",()=>this.addStreetPicture()),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onReferenceWheel(t),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",t=>this.onBodyWheel(t),{passive:!1});for(const t of[this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorAltitudeInput,this.decorHeadingInput,this.decorColorInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput])t.addEventListener("input",()=>this.updateDecor());this.decorObserverSideSelect.addEventListener("change",()=>this.updateDecor()),this.decorModelSelect.addEventListener("change",()=>this.updateDecorModelChoice()),this.addMilestoneButton.addEventListener("click",()=>this.addMilestone()),this.deleteMilestoneButton.addEventListener("click",()=>this.deleteMilestone()),this.goToMilestoneButton.addEventListener("click",()=>{this.currentMilestoneT!==void 0&&this.goToMark(this.currentMilestoneT)}),this.milestoneSelect.addEventListener("change",()=>this.selectMilestone(Number(this.milestoneSelect.value)));for(const t of[this.milestoneLabelInput,this.milestoneNoteInput])t.addEventListener("input",()=>this.updateMilestone());this.confirmAcceptButton.addEventListener("click",()=>this.answerConfirm(!0)),this.confirmDeclineButton.addEventListener("click",()=>this.answerConfirm(!1)),this.confirmOverlay.addEventListener("click",t=>{t.target===this.confirmOverlay&&this.answerConfirm(!1)});for(const t of xa)this.decorWindowInputs[t].addEventListener("input",()=>this.updateDecorWindows());this.decorLitInput.addEventListener("input",()=>this.updateDecorLit()),this.decorLightRigSelect.addEventListener("change",()=>this.updateDecorLightRig()),this.lookAtDecorButton.addEventListener("click",()=>this.lookAtDecor()),this.showMeteorButton.addEventListener("click",()=>this.showNextMeteor()),this.showCometButton.addEventListener("click",()=>this.lookAtComet()),this.showNovaButton.addEventListener("click",()=>this.lookAtNova()),this.showSatelliteButton.addEventListener("click",()=>this.showNextSatellite()),this.showFireballButton.addEventListener("click",()=>this.showNextFireball()),this.sceneElement.addEventListener(Wb,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(Vb,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const t of Yv)this.presetButtons[t].addEventListener("click",()=>this.setAppearance({presetId:t}));this.colorInput.addEventListener("input",()=>this.setAppearance({color:this.colorInput.value})),this.transparencyInput.addEventListener("input",()=>this.setAppearance({transparency:Number(this.transparencyInput.value)})),this.brightnessInput.addEventListener("input",()=>this.setAppearance({brightness:Number(this.brightnessInput.value)})),this.blurInput.addEventListener("input",()=>{this.setAppearance({blur:Number(this.blurInput.value)}),this.refreshBlurDistanceBound()}),this.haloScaleInput.addEventListener("input",()=>this.setAppearance({haloScale:Number(this.haloScaleInput.value)}));for(const t of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])t.addEventListener("input",()=>this.updateObserver());for(const t of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])t.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",t=>{t.key==="Enter"&&(t.preventDefault(),this.searchPlace())}),this.placeMatchSelect.addEventListener("change",()=>this.applyPlaceMatch(this.placeMatchSelect.selectedIndex)),this.placeNameInput.addEventListener("input",()=>this.updatePlaceName()),this.headingInput.addEventListener("focus",()=>this.sceneElement.setCompassForced(!0)),this.headingInput.addEventListener("input",()=>this.refreshHeadingPoint()),this.headingInput.addEventListener("blur",()=>this.sceneElement.setCompassForced(!1)),this.instrumentSelect.addEventListener("change",()=>{const t=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const i=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(n=>[n.t,Si.fovOf(this.ufoElement.sighting,n.t)]));this.retuneFieldOfView(t),this.retuneExposure(t),Si.reproject(this.ufoElement.sighting,t,i),this.sceneElement.applyFrameFormat(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()}),this.obsTimeInput.addEventListener("input",()=>this.updateObservationTime()),this.obsEndTimeInput.addEventListener("input",()=>this.updateObservationEndTime()),this.obsTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeNativeInput.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.obsTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsTimeNativeInput,this.obsTimeQualifier,this.obsTimeInput,()=>this.updateObservationTime())),this.obsEndTimeQualifier.addEventListener("change",()=>this.writeFromPicker(this.obsEndTimeNativeInput,this.obsEndTimeQualifier,this.obsEndTimeInput,()=>this.updateObservationEndTime())),this.edtfModeButton.addEventListener("click",()=>this.setEdtfMode(!this.edtfMode)),this.obsTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsTimeInput)),this.obsEndTimeInput.addEventListener("blur",()=>this.validateEdtfTimeInput(this.obsEndTimeInput));for(const t of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])t.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const t of this.weatherFields){if(t===this.iceCrystalAlignmentInput){t.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}t.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const t of this.soundFields)t.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.skyDetailsButton=this.shadow.getElementById("sky-details"),this.clampedLines=[this.shadow.getElementById("weather-source"),this.shadow.getElementById("sky-candidates")],this.skyDetailsButton.addEventListener("click",()=>this.toggleSkyDetails()),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(t=>this.shadow.getElementById(t.getAttribute("aria-controls")));for(const t of this.groupTabs)t.addEventListener("click",()=>this.toggleGroup(t,!this.isGroupOpen(t)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const t of this.subgroupTabs)t.addEventListener("click",()=>this.openSubgroup(t));Gi.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new dd(this.messages,this.naming,this.said,this.tagNames),this.paramSummary.addEventListener("click",t=>this.onParamSummaryClick(t)),this.toggleGroup(this.groupTabs[this.groupTabs.length-1],!0),this.updatePresetButtons(),this.setRecordButtonLabel(!1),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.sceneElement.setCloudRendering("volume"),this.cloudEditor=Ny(this.shadow.getElementById("cloud-editor"),this.sceneElement,(t=!0)=>{t&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(t,i)=>{this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.updateObserver()},vh(qs.preferencesFor(this),uh)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeQualifierOptions(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),qs.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages();const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag()}setCloudRendering(e){this.sceneElement.setCloudRendering(e)}showWeatherEditor(){const e=this.groupPanels.findIndex(t=>t.id==="group-weather");e>=0&&this.toggleGroup(this.groupTabs[e],!0)}get sightingData(){return this.ufoElement.sightingData}set sightingData(e){this.endDrag(),this.ufoElement.sightingData=e,this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??ll,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.currentDecorId=this.ufoElement.sighting.decor[0]?.id,this.refreshDecorList(),this.currentReferenceId=this.ufoElement.sighting.references[0]?.id,this.refreshReferenceList(),this.currentTraceId=this.ufoElement.sighting.traces[0]?.id,this.refreshTraceList(),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncObservationTimeFields(),this.syncObservationEndTimeFields(),this.chooseTimeInputMode(),this.syncObserverMetadataFields(),this.refreshTimeZoneOptions(),this.utcOffsetInput.readOnly=this.ufoElement.sighting.event.timeZone!==void 0,this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.syncWeatherOwnership()}exportJson(){const e=this.sightingData,t=`${e.observer?.id??"sighting"}-sighting.json`,i=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,s.click(),URL.revokeObjectURL(n)}async importFromFile(){const e=this.importFileInput.files?.[0];if(e)try{const t=await new Promise((n,s)=>{const r=new FileReader;r.onload=()=>n(r.result),r.onerror=()=>s(r.error),r.readAsText(e)}),i=JSON.parse(t);this.sceneElement.documentUrl=void 0,this.sightingData=i,this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}async importFromUrl(e=this.importUrlInput.value.trim()){if(e)try{const t=await Sp.json(e);this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=t,this.importUrlInput.value=new URL(e,location.href).href}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Xr))return this.messages.importError;switch(e.kind){case"cors":return this.messages.importErrorCors;case"mixed-content":return this.messages.importErrorMixedContent;case"unreachable":return this.messages.importErrorUnreachable;case"status":return this.messages.importErrorStatus.replace("{status}",String(e.status??""));case"malformed":return this.messages.importErrorMalformed;default:return this.messages.importError}}static NARRATIVE_KEY_STORAGE="rr0-sighting-editor.narrative-key";static NARRATIVE_SCOPE_STORAGE="rr0-sighting-editor.narrative-workspace";narrativeProvider=ql[0].create();get narrativeSourceId(){return zs(ql,this.chosenSourceId.get("narrative")).id}narrativeAbort;async draftFromDescription(){const e=this.descriptionInput.value.trim();if(e===""||this.narrativeAbort)return;const t=this.narrativeAbort=new AbortController;this.setNarrativeBusy(!0);try{const i=await this.narrativeProvider.draft({ask:e,current:this.sightingData,language:qt.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof Mn&&i.kind==="cancelled";this.narrativeStatus.textContent=n?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!n)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:n,...s}=i,r=i.timeZone?s:i,o=vs.stated(r);if(o.length>0){const l=this.ufoElement.sighting.provenance,c=Yu(this.ufoElement.sighting);this.sightingData=vs.apply(c,gh.loadable(r),o),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,o),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=o.length>0?this.messages.narrativeApplied.replace("{count}",String(o.length)):this.messages.narrativeUnchanged,this.narrativeStatus.classList.remove("error"),this.showNarrativeReport(e),this.syncNarrativeEnabled()}recordNarrativeProvenance(e,t){const i=this.ufoElement.sighting,n=new Set(t);for(const s of e.claims)!n.has(s.path)&&!t.some(r=>s.path.startsWith(`${r}.`))||i.provenance.set(s.path,{basis:s.basis,rationale:s.rationale,of:qt.valueAt(Yu(this.ufoElement.sighting),s.path)})}static valueAt(e,t){let i=e;for(const n of t.split(".")){if(typeof i!="object"||i===null)return;i=i[n]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(n=>n.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[h4[t]]));for(const n of i){const s=document.createElement("div");s.className=`claim ${t}`;const r=document.createElement("code");r.textContent=n.path;const o=document.createElement(t==="stated"?"q":"span");o.textContent=n.rationale,s.append(r,o),this.narrativeReport.append(s)}}}if(e.gaps.length>0){this.narrativeReport.append(this.narrativeHeading(this.messages.narrativeGaps));const t=document.createElement("ul");t.className="gaps";for(const i of e.gaps){const n=document.createElement("li");n.textContent=i,t.append(n)}this.narrativeReport.append(t)}this.narrativeReport.hidden=this.narrativeReport.childElementCount===0}narrativeHeading(e){const t=document.createElement("h4");return t.textContent=e,t}setNarrativeBusy(e){this.descriptionInput.disabled=e,this.narrativeStopButton.hidden=!e,e&&(this.narrativeStatus.textContent=this.messages.narrativeWorking,this.narrativeStatus.classList.remove("error")),this.syncNarrativeEnabled()}syncNarrativeEnabled(){const e=zs(ql,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(n=>n.required&&(this.narrativeSettingInputs.get(n.id)?.value.trim()??"")===""),i=this.descriptionInput.value.trim()==="";this.narrativeDraftButton.disabled=!!this.narrativeAbort||t!==void 0||i,this.narrativeDraftButton.title=t?this.messages.narrativeNeedsSetting.replace("{setting}",this.said.read(t.label)??t.id).replace("{source}",e):i?this.messages.narrativeNeedsAsk:"",this.narrativeRememberInput.parentElement.hidden=!this.narrativeProvider.settings.some(n=>n.remembered==="credential");for(const n of this.narrativeProvider.settings){const s=this.narrativeSettingInputs.get(n.id);if(!s||!n.suspect)continue;const r=s.value.trim(),o=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",o!==void 0),s.title=o?this.said.read(o)??"":this.said.read(n.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const n=document.createElement("label"),s=document.createElement("span");s.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const l of i.choices??[]){const c=document.createElement("option");c.value=l.value,c.textContent=this.said.read(l.label)??l.value,r.appendChild(c)}}else r=document.createElement("input"),r.type=i.kind==="secret"?"password":"text",r.autocomplete="off",r.spellcheck=!1,r.placeholder=this.said.read(i.placeholder)??"";r.id=`narrative-${i.id}`,r.title=this.said.read(i.hint)??"";const o=e[i.id]??this.storedNarrativeSetting(i.id);return o!==void 0&&(r.value=o),r.addEventListener(i.kind==="choice"?"change":"input",()=>{this.rememberNarrativeSettings(),this.syncNarrativeEnabled()}),this.narrativeSettingInputs.set(i.id,r),n.append(s,document.createTextNode(" "),r),n});this.narrativeSettingsBox.replaceChildren(...t),this.narrativeRememberInput.checked=this.narrativeProvider.settings.some(i=>i.remembered==="credential"&&this.storedNarrativeSetting(i.id)!==void 0),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const n=i.value.trim();n!==""&&(e[t]=n)}return e}narrativeErrorFor(e){if(!(e instanceof Mn))return this.messages.narrativeErrorMalformed;switch(e.kind){case"rejected":return this.messages.narrativeErrorRejected.replace("{detail}",e.detail??"");case"credential":return this.messages.narrativeErrorCredential;case"rate-limited":return this.messages.narrativeErrorRateLimited;case"refused":return this.messages.narrativeErrorRefused;case"unreachable":return this.messages.narrativeErrorUnreachable;default:return this.messages.narrativeErrorMalformed}}rememberNarrativeSettings(){try{for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";(e.remembered==="preference"||e.remembered==="credential"&&this.narrativeRememberInput.checked)&&i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}localStorage.removeItem(qt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(qt.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){try{const t=localStorage.getItem(this.narrativeStorageKey(e));if(t!==null)return t;if(this.narrativeSourceId!=="claude")return;const i=e==="key"?qt.NARRATIVE_KEY_STORAGE:e==="workspace"?qt.NARRATIVE_SCOPE_STORAGE:void 0;return i&&localStorage.getItem(i)||void 0}catch{return}}numberOrUndefined(e){return e===""?void 0:Number(e)}stringOrUndefined(e){return e===""?void 0:e}wrapDegrees(e,t){if(e===void 0)return;const i=(e%360+360)%360;return String(i)!==t.value&&(t.value=String(i)),i}refreshSourceRows(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("place",VI,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",WI,e=>{this.weatherInference=new ku(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",Lv,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",ql,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.terrainSourceRows.replaceChildren(this.labelledPicker("elevation",this.messages.sourceElevation,Uu,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,Hv,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,bp,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,oh,()=>this.applyDecorModelSource()))}sourcePicker(e,t,i){const n=document.createDocumentFragment(),s=document.createElement("select");s.id=`${e}Source`;for(const l of t){const c=document.createElement("option");c.value=l.id,c.textContent=l.name,c.title=l.credit,s.appendChild(c)}s.value=this.chosenSourceId.get(e)??t[0].id;const r=document.createElement("a");r.className="source-credit",r.target="_blank",r.rel="noopener noreferrer";const o=()=>{const l=zs(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return o(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),o(),i(zs(t,s.value))}),n.append(s,document.createTextNode(" "),r),n}labelledPicker(e,t,i,n){const s=document.createElement("label"),r=document.createElement("span");return r.textContent=t,s.append(r,this.sourcePicker(e,i,n)),s}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:zs(Uu,this.chosenSourceId.get("elevation")).create(),imagery:zs(Hv,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(zs(bp,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=zs(oh,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.refreshDecorModelOptions(),this.ufoElement.refresh()}get placeSearchLanguage(){return navigator.languages?.[0]}set placeSearchProvider(e){this.placeProvider=e}async searchPlace(){const e=this.placeNameInput.value.trim();if(e==="")return;const t=++this.placeSearchToken;this.placeStatusText.textContent=this.messages.placeSearching;let i;try{i=await this.placeProvider.search(e,{language:this.placeSearchLanguage})}catch{if(t!==this.placeSearchToken)return;this.placeStatusText.textContent=this.messages.placeSearchFailed;return}t===this.placeSearchToken&&(this.placeMatches=i,this.refreshPlaceMatches(),i.length>0&&this.applyPlaceMatch(0))}refreshPlaceMatches(){this.placeMatchSelect.replaceChildren(...this.placeMatches.map(t=>{const i=document.createElement("option");return i.textContent=t.name,i.title=t.name,i})),this.placeMatchRow.hidden=this.placeMatches.length===0;const e=this.placeMatches.length===1?this.messages.placeMatchFound:this.messages.placeMatchesFound;this.placeStatusText.textContent=this.placeMatches.length===0?this.messages.placeNotFound:`${this.placeMatches.length} ${e} `,this.placeSourceRow.hidden=this.placeMatches.length===0}applyPlaceMatch(e){const t=this.placeMatches[e];t&&(this.placeMatchSelect.selectedIndex=e,this.placeNameInput.value=t.name,this.placeNameInput.title=t.name,this.latInput.value=String(t.lat),this.lngInput.value=String(t.lng),this.namedCoordinates={lat:t.lat,lng:t.lng},this.updateObserver())}updatePlaceName(){this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent="",this.placeSourceRow.hidden=!0,this.placeNameInput.title=this.placeNameInput.value,this.namedCoordinates=void 0,this.updateObserver()}schedulePlaceReverse(){if(!this.namedCoordinates)return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||Math.abs(e-this.namedCoordinates.lat)<ja&&Math.abs(t-this.namedCoordinates.lng)<ja||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),Xv))}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&i!==this.autoFilledTimeZone)return;const n=this.timeZoneLookedUpAt;n&&Math.abs(e-n.lat)<ja&&Math.abs(t-n.lng)<ja||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),Xv))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t),n=this.ufoElement.sighting.event.timeZone;!i||n&&n!==this.autoFilledTimeZone||this.timeZones.available().includes(i)&&(this.autoFilledTimeZone=i,this.timeZoneSelect.value=i,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange")))}async reversePlace(e,t){const i=++this.placeSearchToken;let n;try{n=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}i===this.placeSearchToken&&(this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=n?.name??"",this.placeNameInput.title=n?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=n?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!n,this.updateObserver())}updateObserver(){if(this.refreshHeadingPoint(),this.ufoElement.playbackState==="playing")return;const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value),i=this.wrapDegrees(this.numberOrUndefined(this.headingInput.value),this.headingInput),n=this.numberOrUndefined(this.pitchInput.value)??0,s=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,o=Math.max(0,r-(this.groundElevationM??0)),l=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());l.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,f=this.numberOrUndefined(this.focalLengthInput.value),p=(u.frame&&f!==void 0?Et.fieldOfViewDegAt(u,f):f)??this.currentFovDeg(),v=this.numberOrUndefined(this.fNumberInput.value),m=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=m===u.exposureSeconds?void 0:m;const g=this.numberOrUndefined(this.focusDistanceInput.value),x=Math.abs(p-Et.fieldOfViewDeg(u))>.01||v!==u.fNumber||g!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&o===0&&!x?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:o,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:p,fNumber:v,focusDistanceM:g}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}applyEdtfTimeInput(e,t){const i=e.value.trim();if(i==="")t(void 0);else{const n=I0(i);if(!n)return;t(n)}e.setCustomValidity(""),e.classList.remove("invalid"),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&_o({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.durationSeconds=void 0)}validateEdtfTimeInput(e){const t=e.value.trim();t===""||I0(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}refreshTimeZoneOptions(){let e=this.timeZoneSelect.options[0];if(!e){e=document.createElement("option"),e.value="";const t=this.timeZoneSelect.parentNode,i=this.timeZoneSelect.nextSibling;this.timeZoneSelect.remove(),this.timeZoneSelect.replaceChildren(e,...this.timeZones.available().map(n=>{const s=document.createElement("option");return s.value=n,s.textContent=n,s})),t?.insertBefore(this.timeZoneSelect,i)}e.textContent=this.messages.timeZoneManual,this.timeZoneSelect.value=this.ufoElement.sighting.event.timeZone??""}updateTimeZone(){const e=this.stringOrUndefined(this.timeZoneSelect.value);this.ufoElement.sighting.event.timeZone=e,this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event,t=e.timeZone&&e.time?this.timeZones.offsetHoursAt(e.timeZone,e.time):void 0;t!==void 0&&(e.utcOffsetHours=t),this.utcOffsetInput.readOnly=e.timeZone!==void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateUtcOffset(){this.ufoElement.sighting.event.utcOffsetHours=this.numberOrUndefined(this.utcOffsetInput.value),this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}updateObservationTime(){this.applyEdtfTimeInput(this.obsTimeInput,e=>{this.ufoElement.sighting.event.time=e})}updateObservationEndTime(){this.applyEdtfTimeInput(this.obsEndTimeInput,e=>{this.ufoElement.sighting.event.endTime=e})}updateObserverMetadata(){const e=this.ufoElement.sighting,t=this.observerFirstNamesInput.value.split(",").map(n=>n.trim()).filter(n=>n.length>0),i={id:this.stringOrUndefined(this.observerIdInput.value),title:this.stringOrUndefined(this.observerTitleInput.value),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0};e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,e.id=this.stringOrUndefined(this.sightingIdInput.value),this.updateAccount(),this.ufoElement.refresh()}updateAccount(){const e=this.ufoElement.sighting,t=this.accountFollowedUpSelect.value,i={observerAgeYears:this.numberOrUndefined(this.observerAgeInput.value),observerOccupation:this.observerOccupationInput.value.trim()===""?void 0:this.said.write(e.account?.observerOccupation,this.observerOccupationInput.value,this.writingLanguage),source:this.stringOrUndefined(this.accountSourceSelect.value),followedUp:t===""?void 0:t==="yes"};e.account=Object.values(i).some(n=>n!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...n]=e.sources??[],{url:s,...r}=i??{},o=t===""?r:{...r,url:t},l=Object.keys(o).length>0?[o,...n]:n;e.sources=l.length>0?l:void 0}updateDescription(){this.ufoElement.sighting.event.description=this.said.write(this.ufoElement.sighting.event.description,this.descriptionInput.value,this.writingLanguage),this.ufoElement.refresh()}updateTags(){const e=this.tagsInput.value.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>this.tagNames.stored(t));this.ufoElement.sighting.event.tags=e.length>0?e:void 0,this.ufoElement.refresh()}applyWeatherAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio(),this.weatherFromRecords&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...ii(this.ufoElement.sighting,this.ufoElement.currentTime),cloudCover:Number(this.cloudCoverInput.value),highCloudCover:Number(this.highCloudCoverInput.value),lowerCloudCover:Number(this.cloudCoverInput.value),cloudDarkness:Number(this.cloudDarknessInput.value),cloudBaseM:this.numberOrUndefined(this.cloudBaseInput.value),precipitationType:this.precipitationTypeSelect.value,precipitationIntensity:Number(this.precipitationIntensityInput.value),windDirectionDeg:this.wrapDegrees(this.numberOrUndefined(this.windDirectionInput.value),this.windDirectionInput)??0,windSpeed:Number(this.windSpeedInput.value),storm:this.stormInput.checked};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}applyIceAlignmentAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;this.sceneElement.resumeWeatherAudio();const e={...ii(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value)};this.ufoElement.sighting.weatherTrack.addKeyframe(this.ufoElement.currentTime,e),this.ufoElement.refresh()}referenceLabel(e){return this.said.read(e.title)||e.src.replace(/^data:.*$/,"…")||e.id}refreshReferenceList(){const e=this.ufoElement.sighting.references;this.referenceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.referenceLabel(t),this.referenceSelect.appendChild(i)}this.currentReferenceId!==void 0&&(this.referenceSelect.value=this.currentReferenceId),this.syncReferenceFields()}selectReference(e){this.currentReferenceId=e,this.referenceSelect.value=e,this.disarmLandmark(),this.currentLandmarkId=void 0,this.referenceFit=void 0,this.syncReferenceFields()}syncReferenceFields(){const e=this.ufoElement.sighting.references.find(n=>n.id===this.currentReferenceId),t=e!==void 0;this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const n of[this.referenceSelect,...this.referenceFields])n.disabled=!t,this.setRowVisible(n,t);this.setRowVisible(this.referenceUsePoseButton,t);for(const n of[this.referenceLandmarksSelect,this.addReferenceLandmarkButton,this.deleteReferenceLandmarkButton,this.referenceLandmarkLabelInput])this.setRowVisible(n,t);if(this.refreshLandmarkList(),this.setRowVisible(this.referenceAdoptPoseButton,t),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSrcInput.value=i?"":e.src,this.referenceSrcInput.disabled=i,this.referenceKindSelect.value=e.kind,this.referenceCreditInput.value=e.credit??"",this.referenceCreditUrlInput.value=e.creditUrl??"",this.referenceTInput.value=e.t===void 0?"":String(e.t/1e3),this.referenceDrawingInput.checked=e.drawing===!0,this.referenceOpacityInput.value=String(e.opacity),this.referenceHeadingInput.value=String(e.registration.headingDeg),this.referencePitchInput.value=String(e.registration.pitchDeg),this.referenceRollInput.value=String(e.registration.rollDeg??0),this.referenceFovInput.value=String(e.registration.fovDeg),this.syncReferenceStatus(e)}syncReferenceStatus(e){if(this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const t=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>AI?this.messages.referenceEmbedded.replace("{kb}",String(t)):"";return}this.referenceStatus.textContent=this.sceneElement.referenceFailedToLoad(e.src)?this.messages.referenceUnreachable:""}updateReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.referenceHeadingInput.value),this.referenceHeadingInput)??0,i=this.referenceTInput.value.trim()===""?void 0:Number(this.referenceTInput.value);e.references=e.references.map(s=>{if(s.id!==this.currentReferenceId)return s;const r=s.src.startsWith("data:")?s.src:this.referenceSrcInput.value.trim(),o={headingDeg:t,pitchDeg:Number(this.referencePitchInput.value)||0,rollDeg:Number(this.referenceRollInput.value)||void 0,fovDeg:Math.min(179,Math.max(1,Number(this.referenceFovInput.value)||qc))},l=s.registration,c=o.headingDeg!==l.headingDeg||o.pitchDeg!==l.pitchDeg||o.rollDeg!==l.rollDeg||o.fovDeg!==l.fovDeg;return{...s,kind:this.referenceKindSelect.value,src:r,title:this.said.write(s.title,this.referenceTitleInput.value,this.writingLanguage),credit:this.stringOrUndefined(this.referenceCreditInput.value),creditUrl:this.stringOrUndefined(this.referenceCreditUrlInput.value),t:i===void 0||Number.isNaN(i)?void 0:Math.round(i*1e3),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),registration:o,from:c?this.observerPositionNow()??s.from:s.from}});const n=e.references.find(s=>s.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(n),this.syncReferenceStatus(n),this.ufoElement.refresh()}useObserverPoseForReference(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);e&&(this.referenceHeadingInput.value=String(this.rounded(e.headingDeg??0)),this.referencePitchInput.value=String(this.rounded(e.pitchDeg)),this.referenceRollInput.value=String(this.rounded(e.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=et(this.ufoElement.sighting,this.ufoElement.currentTime);return e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0}addReference(e,t,i={}){const n=this.ufoElement.sighting,s=et(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,o={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:_I,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:qc},from:this.observerPositionNow(),...i};n.references=[...n.references,o],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSrcInput.focus()}async addReferenceFromFile(){const e=this.addReferenceFileInput.files?.[0];if(!e)return;const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsDataURL(e)});this.addReferenceFileInput.value="",this.addReference(t,e.name.replace(/\.[^.]+$/,""))}currentReference(){return this.ufoElement.sighting.references.find(e=>e.id===this.currentReferenceId)}currentLandmarks(){return this.currentReference()?.landmarks??[]}writeLandmarks(e){const t=this.ufoElement.sighting;t.references=t.references.map(i=>i.id===this.currentReferenceId?{...i,landmarks:e.length>0?e:void 0}:i)}beginReferenceDrag(e){const t=this.currentReference();if(!t)return;if(this.armingLandmark||this.pendingLandmark){this.nameLandmarkAt(e);return}const i=this.landmarkEndAt(e);if(i){this.selectLandmark(i.landmarkId),this.referenceDragState={kind:"anchor",...i},this.setCanvasCursor("landmark"),this.startDragListening();return}const n=this.sceneElement.referenceAspect(t.id);if(!(n!==void 0&&cn.picturePointOf(this.directionAtCanvasPoint(e),t.registration,n)!==void 0)){this.beginCameraDrag(e);return}this.referenceDragState={kind:"picture",startPointer:e,startHeadingDeg:t.registration.headingDeg,startPitchDeg:t.registration.pitchDeg,moved:!1},this.setCanvasCursor("panning"),this.startDragListening()}landmarkEndAt(e){const t=this.currentReference(),i=t?this.sceneElement.referenceAspect(t.id):void 0;if(!t||i===void 0)return;const n=8;for(const s of this.currentLandmarks()){const r=this.canvasPointOfDirection(cn.worldDirectionOf(s.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=n)return{landmarkId:s.id,end:"picture"};const o=this.canvasPointOfDirection(cn.worldDirection(s.scene));if(o&&Math.hypot(o.x-e.x,o.y-e.y)<=n)return{landmarkId:s.id,end:"scene"}}}onReferenceDragPointerMove(e){const t=this.referenceDragState,i=this.canvasPointFromEvent(e);if(!t||!i)return;if(t.kind==="anchor"){this.moveLandmarkEnd(t.landmarkId,t.end,i);return}const n=i.x-t.startPointer.x,s=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(n,s)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+n*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-s*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const n=this.currentReference(),s=n?this.sceneElement.referenceAspect(n.id):void 0;if(!n||s===void 0)return;const r=this.directionAtCanvasPoint(i);this.writeLandmarks(this.currentLandmarks().map(o=>{if(o.id!==e)return o;if(t==="scene")return{...o,scene:cn.aimOf(r)};const l=cn.picturePointOf(r,n.registration,s);return l?{...o,picture:l}:o})),this.ufoElement.refresh()}endReferenceDrag(){const e=this.referenceDragState;this.referenceDragState=void 0,this.setCanvasCursor(this.canvasMode()==="picture"?"pan":this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp),e?.kind==="anchor"&&this.fitReferenceToLandmarks()}onReferenceWheel(e){if(this.canvasMode()!=="picture")return;e.preventDefault();const t=Number(this.referenceFovInput.value)||qc,i=Math.min(179,Math.max(1,t*Math.exp(Math.sign(e.deltaY)*.05)));this.referenceFovInput.value=String(this.rounded(i)),this.updateReference()}directionAtCanvasPoint(e){const t=this.ufoElement.canvasElement;return this.sceneElement.directionAt(e.x/t.width*2-1,-(e.y/t.height*2-1))}armLandmark(){this.currentReference()&&(this.armingLandmark=!0,this.pendingLandmark=void 0,this.setCanvasCursor("landmark"),this.syncRegisterStatus(),this.ufoElement.refresh())}disarmLandmark(){this.armingLandmark=!1,this.pendingLandmark=void 0,this.canvasMode()==="picture"&&(this.setCanvasCursor("pan"),this.syncRegisterStatus()),this.ufoElement.refresh()}nameLandmarkAt(e){const t=this.currentReference();if(!t)return;const i=this.directionAtCanvasPoint(e);if(!this.pendingLandmark){const r=this.sceneElement.referenceAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const o=cn.picturePointOf(i,t.registration,r);if(!o){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=o,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:cn.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=s,this.setCanvasCursor("pan"),this.fitReferenceToLandmarks()}nextLandmarkId(e){let t=e.length+1;for(;e.some(i=>i.id===`landmark-${t}`);)t++;return`landmark-${t}`}fitReferenceToLandmarks(){const e=this.currentReference(),t=e?this.sceneElement.referenceAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),n=cn.solve(i,t,e.registration.fovDeg);n?(this.referenceFit={n:i.length,residualDeg:n.residualDeg},this.referenceHeadingInput.value=String(this.rounded(n.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(n.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(n.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(n.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return cn.worldDirectionOf(e.picture,t.registration,i).angleTo(cn.worldDirection(e.scene))*180/Math.PI}landmarkLabel(e,t){const i=this.said.read(e.label);return i?`${t+1} · ${i}`:String(t+1)}refreshLandmarkList(){const e=this.currentReference(),t=this.currentLandmarks(),i=e?this.sceneElement.referenceAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[s,r]of t.entries()){const o=document.createElement("option");o.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";o.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(o)}this.currentLandmarkId!==void 0&&!t.some(s=>s.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const n=t.find(s=>s.id===this.currentLandmarkId);this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=n===void 0,this.referenceLandmarkLabelInput.disabled=n===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(n?.label)??"")}selectLandmark(e){this.currentLandmarkId=e,this.refreshLandmarkList(),this.ufoElement.refresh()}updateLandmarkLabel(){const e=this.currentLandmarkId;if(e===void 0)return;this.writeLandmarks(this.currentLandmarks().map(o=>o.id===e?{...o,label:this.said.write(o.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:o));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(o=>o.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const o=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+o}this.ufoElement.refresh()}deleteLandmark(){const e=this.currentLandmarkId;if(e===void 0)return;const t=this.currentLandmarks().filter(i=>i.id!==e);this.writeLandmarks(t),this.currentLandmarkId=t[t.length-1]?.id,this.fitReferenceToLandmarks()}landmarkHint(){const e=this.currentLandmarks().length+1;if(this.pendingLandmark)return this.messages.referenceLandmarkScene.replace("{n}",String(e));if(this.armingLandmark)return this.messages.referenceLandmarkPicture.replace("{n}",String(e))}syncRegisterStatus(){const e=this.landmarkHint();e?this.referenceStatus.textContent=e:this.referenceFit?this.referenceStatus.textContent=this.messages.referenceLandmarksFit.replace("{n}",String(this.referenceFit.n)).replace("{deg}",this.referenceFit.residualDeg.toFixed(1)):this.referenceStatus.textContent=this.messages.referenceRegisterHint}canvasPointOfDirection(e){const t=this.sceneElement.screenPointOf(e);if(!t)return;const i=this.ufoElement.canvasElement;return{x:(t.ndcX+1)/2*i.width,y:(1-t.ndcY)/2*i.height}}paintPictureOverlay=e=>{const t=this.currentReference();if(!t)return;const i=this.sceneElement.referenceAspect(t.id);if(i===void 0)return;const{registration:n}=t,s=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(o=>this.canvasPointOfDirection(cn.worldDirectionOf(o,n,i))),r=this.currentLandmarks().map((o,l)=>({picture:this.canvasPointOfDirection(cn.worldDirectionOf(o.picture,n,i)),scene:this.canvasPointOfDirection(cn.worldDirection(o.scene)),label:this.landmarkLabel(o,l),selected:o.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(o,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(cn.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(o=>o!==void 0)?s:void 0,r.filter(o=>o.picture!==void 0),this.landmarkHint())};adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:n}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(n??0)),this.updateObserver();const s=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===s);if(r<0)return;const o=this.messages.referenceAdoptRationale.replace("{title}",this.referenceLabel(e)).replace("{n}",String(this.currentLandmarks().length)).replace("{deg}",(this.referenceFit?.residualDeg??0).toFixed(1)),l=[["headingDeg",t],["pitchDeg",i],["rollDeg",n??0]];for(const[c,h]of l)this.ufoElement.sighting.provenance.set(`observerTrack.keyframes.${r}.pose.${c}`,{basis:"derived",rationale:o,of:this.rounded(h)})}syncStreetSearchAvailability(){const e=this.numberOrUndefined(this.latInput.value)!==void 0&&this.numberOrUndefined(this.lngInput.value)!==void 0;this.referenceStreetSearchButton.disabled=!e}async searchStreetPictures(){const e=et(this.ufoElement.sighting,0),t=e?.lat??this.numberOrUndefined(this.latInput.value),i=e?.lng??this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const n=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.referenceStreetSearchButton.disabled=!0;try{this.streetPictures=await this.streetPictures$.nearby(t,i,n)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.referenceStreetSearchButton.disabled=!1;return}this.referenceStreetSearchButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,o]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(o,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(l)}const s=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!s,this.referenceStreetAddButton.hidden=!s,this.referenceStatus.textContent=s?"":this.messages.referenceStreetNone.replace("{m}",String(n))}streetPictureLabel(e,t){return t.replace("{distance}",String(Math.round(e.distanceM))).replace("{bearing}",String(Math.round(e.bearingDeg))).replace("{date}",e.takenAt.slice(0,10)).replace("{panorama}",e.panorama?this.messages.referenceStreetPanorama:"")}addStreetPicture(){const e=this.streetPictures[Number(this.referenceStreetSelect.value)];e&&this.addReference(e.src,this.streetPictureLabel(e,this.messages.referenceStreetTitle),{kind:e.panorama?"panorama":"photo",credit:e.credit,creditUrl:e.creditUrl,registration:{headingDeg:e.azimuthDeg??0,pitchDeg:0,fovDeg:qc}})}traceLabel(e){const t=e.kind==="point"?this.messages.traceKindPoint:e.kind==="line"?this.messages.traceKindLine:this.messages.traceKindPolygon,i=this.said.read(e.title);return i?`${i} (${t})`:`${e.id} (${t})`}refreshTraceList(){const e=this.ufoElement.sighting.traces;this.traceSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.traceLabel(t),this.traceSelect.appendChild(i)}e.some(t=>t.id===this.currentTraceId)||(this.currentTraceId=e[0]?.id),this.currentTraceId!==void 0&&(this.traceSelect.value=this.currentTraceId),this.syncTraceFields()}selectTrace(e){this.currentTraceId=e,this.syncTraceFields()}syncTraceFields(){const e=this.ufoElement.sighting.traces.find(i=>i.id===this.currentTraceId),t=e!==void 0;for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!t,this.setRowVisible(i,t);this.traceTitleInput.value=this.said.read(e?.title)??"",this.traceSourceInput.value=this.said.read(e?.source)??""}writeTraceFields(){const e=this.ufoElement.sighting;if(this.currentTraceId===void 0)return;e.traces=e.traces.map(n=>n.id!==this.currentTraceId?n:{...n,title:this.said.write(n.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(n.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(n=>n.value===this.currentTraceId),i=e.traces.find(n=>n.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTracesFromFile(){const e=this.addTraceFileInput.files?.[0];if(!e)return;this.addTraceFileInput.value="";let t;try{const{KmlImport:c}=await ot(async()=>{const{KmlImport:d}=await import("./KmlImport-ByKlq2_E.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const f=new FileReader;f.onload=()=>d(f.result),f.onerror=()=>u(f.error),f.readAsArrayBuffer(e)});t=await c.fromBytes(new Uint8Array(h))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(t.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const i=this.ufoElement.sighting,n=new Set(i.traces.map(c=>c.id));let s=1;const r=this.said.write(void 0,t.documentName??e.name,this.writingLanguage),o=t.traces.map(c=>{for(;n.has(`trace-${s}`);)s++;const h=`trace-${s}`;return n.add(h),{...c,id:h,title:c.title===void 0?void 0:this.said.write(void 0,c.title,this.writingLanguage),source:r}});i.traces=[...i.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const l=t.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",t.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",e.name)+l,this.ufoElement.refresh()}deleteTrace(){if(this.currentTraceId===void 0)return;const e=this.ufoElement.sighting;e.traces=e.traces.filter(t=>t.id!==this.currentTraceId),this.currentTraceId=e.traces[0]?.id,this.refreshTraceList(),this.ufoElement.refresh()}deleteReference(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting;e.references=e.references.filter(t=>t.id!==this.currentReferenceId),this.currentReferenceId=e.references[0]?.id,this.refreshReferenceList(),this.ufoElement.refresh()}buildSoundKindOptions(){for(const e of yy){const t=document.createElement("option");t.value=e,t.textContent=this.soundKindLabel(e,this.messages),this.soundKindOptions.set(e,t),this.soundKindSelect.appendChild(t)}}soundKindLabel(e,t){switch(e){case"hum":return t.soundHum;case"whistle":return t.soundWhistle;case"rumble":return t.soundRumble;case"crackle":return t.soundCrackle;default:return t.soundNone}}applySoundAtPlayhead(){if(this.ufoElement.playbackState==="playing")return;const e=this.readSound();this.ufoElement.sighting.soundTrack.addKeyframe(this.ufoElement.currentTime,e),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e),this.ufoElement.refresh(),this.previewSound(e)}previewSound(e){clearTimeout(this.soundPreviewTimer),this.ufoElement.previewSound(e),this.soundPreviewTimer=setTimeout(()=>this.ufoElement.stopSoundPreview(),jI)}readSound(){return{kind:this.soundKindSelect.value,volume:Number(this.soundVolumeInput.value),pitchHz:Number(this.soundPitchInput.value),src:this.soundSrcInput.value.trim()||void 0}}syncSoundFromTimeline(){if(this.ufoElement.playbackState==="playing")return;const e=xp(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.soundKindSelect&&(this.soundKindSelect.value=e.kind),t!==this.soundVolumeInput&&(this.soundVolumeInput.value=String(e.volume)),t!==this.soundPitchInput&&(this.soundPitchInput.value=String(e.pitchHz)),t!==this.soundSrcInput&&(this.soundSrcInput.value=e.src??""),this.updateSoundPitchReadout(e.pitchHz),this.updateSoundFieldsDisabledState(e)}updateSoundPitchReadout(e){this.soundPitchValue.textContent=`${Math.round(e)} Hz`}updateSoundFieldsDisabledState(e){const t=e.kind==="none"&&!e.src;this.soundVolumeInput.disabled=t,this.soundSrcInput.disabled=t,this.soundPitchInput.disabled=t||e.src!==void 0}set weatherProvider(e){this.weatherInference=new ku(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup():(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(){this.weatherFromRecords&&(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),Wv))}cancelWeatherLookup(){clearTimeout(this.weatherLookupTimer),this.weatherLookupToken++,this.weatherLookupPending=!1}async inferWeather(){if(!this.weatherFromRecords)return;const e=++this.weatherLookupToken;this.weatherLookupPending=!0,this.syncWeatherSourceState();const t=await this.weatherInference.infer(this.ufoElement.sighting);e!==this.weatherLookupToken||!this.weatherFromRecords||(this.weatherLookupPending=!1,this.weatherLookupResult=t,t.status==="inferred"?(this.weatherInference.applyTo(this.ufoElement.sighting,t),this.weatherTrackSpan=this.ufoElement.seekableDuration,this.ufoElement.refresh(),this.syncWeatherFromTimeline()):this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}ensureWeatherTrackSpan(){if(!this.weatherFromRecords||this.ufoElement.sighting.weatherSource===void 0)return;const e=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||e===this.weatherTrackSpan||(this.weatherTrackSpan=e,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const o of this.weatherFields)o.disabled=t&&e!==void 0&&o!==this.iceCrystalAlignmentInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?o.title=this.messages.weatherWhilePlaying:o.title===this.messages.weatherWhilePlaying&&(o.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting);this.weatherInferredInput.disabled=!i,this.weatherInferredInput.checked=i&&this.weatherFromRecords;const n=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=n,this.labelWeatherInferred.title=n;const s=t&&e!==void 0;if(this.weatherSourceLink.hidden=!s,s){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=this.observationInstantLabel();return}const r=t?this.weatherStatusMessage():"";this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""}weatherStatusMessage(){if(this.weatherLookupPending)return this.messages.weatherLookingUp;switch(this.weatherLookupResult?.status){case"unavailable":return this.messages.weatherNoRecord;case"failed":return this.messages.weatherLookupFailed;default:return""}}observationInstantLabel(){const e=this.ufoElement.sighting.event,t=e.time&&Un(e.time,e.place?.[0]?.lng??0,e.utcOffsetHours);return t?`, ${t.toISOString().slice(0,16).replace("T"," ")} UTC`:""}syncWeatherOwnership(){const e=this.ufoElement.sighting;this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.weatherFromRecords=e.weatherSource!==void 0||e.weatherTrack.allKeyframes.length===0,this.syncWeatherSourceState(),this.weatherFromRecords&&e.weatherSource===void 0&&this.scheduleWeatherLookup(),this.lightPollutionToken++,this.lightPollutionLookup=void 0,this.scheduleLightPollutionLookup()}lightPollutionProvider=Lv[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(e.lightPollution===void 0)return!0;const t=e.provenance.at("lightPollution");return t?.basis==="derived"&&(t.of===void 0||t.of===e.lightPollution)}scheduleLightPollutionLookup(){if(clearTimeout(this.lightPollutionTimer),!this.lightPollutionFromRecord()){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}this.lightPollutionTimer=setTimeout(()=>void this.lookUpLightPollution(),Wv)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,n=this.lightPollutionProvider,s=e.event.time?.year,r=()=>{e.lightPollution!==void 0&&(e.lightPollution=void 0,e.provenance.clear("lightPollution"),this.lightPollutionInput.value="",this.ufoElement.refresh())};if(!t||t.lat===void 0||t.lng===void 0||s===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(s<n.year){r(),this.lightPollutionLookup={status:"too-early",year:s},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const o=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=o,o.status==="found"?(e.lightPollution=o.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${o.lat.toFixed(4)}, ${o.lng.toFixed(4)}: ${Math.round(o.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:o.lightPollution}),this.lightPollutionInput.value=String(o.lightPollution),this.ufoElement.refresh()):o.status==="natural"&&r(),this.syncLightPollutionStatus())}syncLightPollutionStatus(){const e=this.lightPollutionLookup,t=this.messages;let i="";switch(e?.status){case"pending":i=t.lightPollutionLookingUp;break;case"found":i=t.lightPollutionFound.replace("{artificial}",Math.round(e.artificialMcdPerM2*1e3).toLocaleString(this.language));break;case"natural":i=t.lightPollutionNatural;break;case"outside":i=t.lightPollutionOutside;break;case"failed":i=t.lightPollutionFailed;break;case"too-early":i=t.lightPollutionTooEarly.replace("{atlasYear}",String(this.lightPollutionProvider.year)).replace("{year}",String(e.year));break}this.lightPollutionStatusText.textContent=i===""?"":`${i} `,this.lightPollutionSourceRow.hidden=!(e?.status==="found"||e?.status==="natural"||e?.status==="outside")}syncDurationField(){if(this.shadow.activeElement!==this.durationInput){const e=_o(this.ufoElement.sighting.event);this.durationInput.value=e!==void 0?String(e/1e3):""}this.updateDurationValidity()}updateDurationValidity(){const e=this.durationInput.value==="";this.durationInput.classList.toggle("missing-required",e),this.markUnansweredQuestions(),this.durationInput.setAttribute("aria-invalid",String(e));const t=_y(this.ufoElement.sighting.event);this.durationInput.title=t==="imprecise"?this.messages.durationImprecise:""}syncPlaybackControls(){this.ensureWeatherTrackSpan();const e=this.ufoElement.playbackState==="playing",t=this.ufoElement.seekableDuration>0;this.playPauseButton.textContent=e?"⏸":"▶",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),this.seekInput.max=String(this.ufoElement.seekableDuration),this.shadow.activeElement!==this.seekInput&&(this.seekInput.value=String(this.ufoElement.currentTime)),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch();for(const[n,s]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])n.title=s,n.setAttribute("aria-label",s);this.refreshTimelineMarks()}switchTimeDisplay(){this.ufoElement.toggleTimeDisplay(),this.timeStartLabel.textContent=this.ufoElement.positionLabel,this.timeEndLabel.textContent=this.ufoElement.durationLabel,this.syncTimeDisplaySwitch()}syncTimeDisplaySwitch(){const e=this.ufoElement.canSwitchTimeDisplay,t=this.ufoElement.showingClockTime?this.messages.switchToElapsed:this.messages.switchToClockTime;for(const[i,n]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${n} — ${t}`:n,i.classList.toggle("switchable",e),e?(i.setAttribute("role","button"),i.setAttribute("tabindex","0")):(i.removeAttribute("role"),i.removeAttribute("tabindex"))}static TIME_QUALIFIERS=[{value:"",key:"timeQualifierExact"},{value:"~",key:"timeQualifierApproximate"},{value:"?",key:"timeQualifierUncertain"},{value:"%",key:"timeQualifierBoth"}];refreshTimeQualifierOptions(){for(const e of[this.obsTimeQualifier,this.obsEndTimeQualifier]){const t=e.value;e.replaceChildren(...qt.TIME_QUALIFIERS.map(i=>{const n=document.createElement("option");return n.value=i.value,n.textContent=this.messages[i.key],n})),e.value=t}}qualifierOf(e){const t=e.trim().slice(-1);return"?~%".includes(t)?t:""}isPickable(e){return e?e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0:!1}pickerValueOf(e){if(!this.isPickable(e))return"";const t=(n,s=2)=>String(n).padStart(s,"0"),i=e.second?`:${t(e.second)}`:"";return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}T${t(e.hour)}:${t(e.minute)}${i}`}static stepFor(e){return e?.second?"1":"60"}writeFromPicker(e,t,i,n){e.value===""&&e.validity.badInput||(i.value=e.value===""?"":`${e.value.replace(/\.\d+$/,"")}${t.value}`,n())}chooseTimeInputMode(){const e=this.ufoElement.sighting.event,t=i=>i===void 0||this.isPickable(i);this.setEdtfMode(!(t(e.time)&&t(e.endTime)))}setEdtfMode(e){this.edtfMode=e,this.edtfModeButton.setAttribute("aria-pressed",String(e));for(const[t,i,n]of[[this.obsTimeInput,this.obsTimeNativeInput,this.obsTimeQualifier],[this.obsEndTimeInput,this.obsEndTimeNativeInput,this.obsEndTimeQualifier]])t.hidden=!e,i.hidden=e,n.hidden=e}syncObservationTimeFields(){const e=this.ufoElement.sighting.event.time;this.obsTimeInput.value=e?dh(e):"",this.obsTimeNativeInput.step=qt.stepFor(e),this.obsTimeNativeInput.value=this.pickerValueOf(e),this.obsTimeQualifier.value=this.qualifierOf(this.obsTimeInput.value),this.obsTimeInput.setCustomValidity(""),this.obsTimeInput.classList.remove("invalid")}syncObservationEndTimeFields(){const e=this.ufoElement.sighting.event.endTime;this.obsEndTimeInput.value=e?dh(e):"",this.obsEndTimeNativeInput.step=qt.stepFor(e),this.obsEndTimeNativeInput.value=this.pickerValueOf(e),this.obsEndTimeQualifier.value=this.qualifierOf(this.obsEndTimeInput.value),this.obsEndTimeInput.setCustomValidity(""),this.obsEndTimeInput.classList.remove("invalid")}syncUtcOffsetField(){const e=this.ufoElement.sighting.event.utcOffsetHours;this.utcOffsetInput.value=e===void 0?"":String(e),this.updateUtcOffsetValidity()}updateUtcOffsetValidity(){const e=this.ufoElement.sighting.event.utcOffsetHours,t=this.ufoElement.sighting.event.place?.[0]?.lng,i=t===void 0?void 0:Math.round(t/15),n=e!==void 0&&i!==void 0&&Math.abs(e-i)>t4;this.utcOffsetInput.classList.toggle("invalid",n),this.utcOffsetInput.title=n?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):""}scheduleGroundElevation(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);e===void 0||t===void 0||this.groundElevationFor&&this.isSamePlace(this.groundElevationFor,e,t)||(clearTimeout(this.groundElevationTimer),this.groundElevationTimer=setTimeout(()=>void this.applyGroundElevation(e,t),QI))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<ja&&Math.abs(e.lng-i)<ja}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=zs(Uu,this.chosenSourceId.get("elevation")),s=await new m0(n.create()).at(e,t);if(i!==this.groundElevationToken||s===void 0)return;this.groundElevationFor={lat:e,lng:t};const r=Math.max(0,(this.numberOrUndefined(this.elevationInput.value)??0)-(this.groundElevationM??0));this.groundElevationM=Math.round(s),this.syncElevationField(r),this.updateObserver()}syncElevationField(e){const t=this.groundElevationM;this.elevationInput.value=String(Math.round((t??0)+e)),this.elevationInput.min=t===void 0?"":String(t),this.elevationInput.title=t===void 0?"":this.messages.altitudeAboveSeaLevel,this.groundElevationOutput.textContent=t===void 0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(et(this.ufoElement.sighting,0)?.elevationM??0),this.scheduleGroundElevation()}syncPlaceNameField(){const e=this.ufoElement.sighting.event.place?.[0],t=e?.name??"";this.placeNameInput.value=t,this.placeNameInput.title=t,this.namedCoordinates=e&&t?{lat:e.lat,lng:e.lng}:void 0,this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=""}syncObserverMetadataFields(){const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=e.observer?.title??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.observerOccupationInput.value=this.said.read(e.account?.observerOccupation)??"",this.accountSourceSelect.value=e.account?.source??"",this.accountUrlInput.value=e.sources?.[0]?.url??"",this.accountFollowedUpSelect.value=e.account?.followedUp===void 0?"":e.account.followedUp?"yes":"no",this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"",this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=ii(this.ufoElement.sighting,this.ufoElement.currentTime),t=this.shadow.activeElement;t!==this.cloudCoverInput&&(this.cloudCoverInput.value=String(e.cloudCover)),t!==this.highCloudCoverInput&&(this.highCloudCoverInput.value=String(e.highCloudCover??0)),t!==this.iceCrystalAlignmentInput&&(this.iceCrystalAlignmentInput.value=String(e.iceCrystalAlignment??.65)),t!==this.cloudDarknessInput&&(this.cloudDarknessInput.value=String(e.cloudDarkness)),t!==this.cloudBaseInput&&(this.cloudBaseInput.value=e.cloudBaseM===void 0?"":String(e.cloudBaseM)),t!==this.precipitationTypeSelect&&(this.precipitationTypeSelect.value=e.precipitationType),t!==this.precipitationIntensityInput&&(this.precipitationIntensityInput.value=String(e.precipitationIntensity)),t!==this.windDirectionInput&&(this.windDirectionInput.value=String(Math.round(e.windDirectionDeg))),t!==this.windSpeedInput&&(this.windSpeedInput.value=String(Math.round(e.windSpeed*2)/2)),t!==this.stormInput&&(this.stormInput.checked=e.storm)}syncObserverFromTimeline(){if(this.ufoElement.playbackState==="playing")return;this.syncStreetSearchAvailability();const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime),i=e.event.place?.[0],n=this.shadow.activeElement;n!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),n!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),n!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),n!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),n!==this.elevationInput&&this.syncElevationField(t?.elevationM??0)}get appearance(){return{...this.currentAppearance}}set appearance(e){this.setAppearance(e)}setAppearance(e){const t="presetId"in e;this.currentAppearance={...this.currentAppearance,...e},this.updatePresetButtons(),!(this.isRecording||this.ufoElement.playbackState==="playing")&&this.ufoElement.sighting.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,t)}applyAppearanceAtPlayhead(e,t=!0){const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=i.getInterpolatedShapeAt(n,this.currentSourceId),r=this.buildAppearanceShape(e??s?.bounds??this.defaultBounds(),s,t);this.commitShapes(n,[{sourceId:this.currentSourceId,shape:r}]),this.ufoElement.refresh()}buildAppearanceShape(e,t,i=!0){if(t&&!i)return{...t,color:this.currentAppearance.color,transparency:this.currentAppearance.transparency,haloScale:this.currentAppearance.haloScale,blur:this.currentAppearance.blur,brightness:this.currentAppearance.brightness};const n=A0(e,this.currentAppearance);return t?{...n,angle:t.angle,title:t.title,selected:t.selected}:n}toggleSkyDetails(){const e=this.skyDetailsButton.getAttribute("aria-expanded")!=="true";this.skyDetailsButton.setAttribute("aria-expanded",String(e)),this.skyDetailsButton.textContent=e?"▴":"▾",this.skyDetailsButton.title=e?this.messages.skyDetailsHide:this.messages.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title);for(const t of this.clampedLines)t.classList.toggle("clamped",!e)}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.cloudEditor?.stopManipulation();for(const[i,n]of this.groupTabs.entries()){const s=n===e&&t;n.setAttribute("aria-expanded",String(s)),this.groupPanels[i].hidden=!s}this.syncCanvasMode(),this.refreshTimelineMarks()}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(l,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${l})`})),i=l=>t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(c=>!l||c.shapes.some(h=>this.selectedSourceIds.has(h.sourceId))).map(c=>c.t)),n=()=>t(this.messages.observerTrack,e.observerTrack.allKeyframes.map(l=>l.t)),s=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(l=>l.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(l=>l.t)),o=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?n():this.isGroupIdOpen("group-weather")?s():this.isGroupIdOpen("group-sound")?r():[...i(!1),...n(),...s(),...r()];for(const l of e.milestones)o.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(o,this.ufoElement.seekableDuration)}goToMark(e){e!==void 0&&(this.ufoElement.currentTime=e,this.syncPlaybackControls())}isGroupIdOpen(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);return t!==void 0&&this.isGroupOpen(t)}canvasMode(){return this.isGroupIdOpen("group-reference")&&this.currentReferenceId!==void 0?"picture":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")?"shape":"scene"}syncCanvasMode(){const e=this.canvasMode(),t=e==="picture",i=this.lastCanvasMode==="picture",n=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:void 0,n&&this.ufoElement.refresh(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const s=this.currentReference();s&&this.syncReferenceStatus(s),this.syncStreetSearchAvailability(),this.syncBodiesShown()}syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=t!==void 0,this.sceneElement.interpretation!==t&&(this.sceneElement.interpretation=t)}openSubgroup(e){this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const i of this.subgroupTabs){if(i.parentElement!==t)continue;const n=i===e;i.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(i.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(i=>i.sync()),this.syncCanvasMode()}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}static SUMMARY_GROUPS=["observation","observer","location","decor","temporal","weather","sound"];panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){const t=this.paramSummaryBuilder.entriesFor(this.ufoElement.sighting,this.ufoElement.currentTime,{decorId:this.currentDecorId,decorPicker:!0,groundElevationM:this.groundElevationM??0}).map(n=>({...n,panel:qt.SUMMARY_GROUPS.indexOf(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=qt.NESTED_GROUPS,t=[];let i;for(const n of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==n.group&&(i=void 0),e.includes(n.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=n.group;const o=document.createElement("span");o.className="param-nest-label",o.textContent=n.group==="assessment"?this.messages.assessmentGroup:qt.tabLabel(this.groupTabs[qt.SUMMARY_GROUPS.indexOf(n.group)]),r.append(o),i={group:n.group,element:r},t.push(r)}const s=this.paramChip(n);i?i.element.append(s):t.push(s)}this.paramSummary.replaceChildren(...t)}static NESTED_GROUPS=["observer","decor","assessment"];static QUESTION_FIELDS={when:{panel:"temporal",fields:["obs-time","obs-time-native"]},where:{panel:"location",fields:["lat","lng"]},facing:{panel:"location",fields:["heading"]},"apparent-size":{panel:"shape",fields:[]},"sky-position":{panel:"shape",fields:[]},"how-long":{panel:"temporal",fields:["durationSeconds","obs-end-time","obs-end-time-native"]},appearance:{panel:"shape",fields:["shapeTitle","color"]},movement:{panel:"shape",fields:[]},sound:{panel:"sound",fields:["soundKind"]},conditions:{panel:"weather",fields:["cloudCover"]}};assessmentChips=[];assessmentToken=0;async runAssessments(){const e=++this.assessmentToken,t=await new Gy(this.messages).read(this.ufoElement.sighting);e===this.assessmentToken&&(this.assessmentChips=t.entries.map(i=>({...i,panel:this.panelIndex(i.about??"")})),this.markUnansweredQuestions(t.unanswered),this.renderParamSummary())}static tabLabel(e){return(e.querySelector("span:not(.tab-badge)")??e).textContent.trim()}static badgeOn(e){const t=e.querySelector(".tab-badge");if(t)return t;const i=document.createElement("span");return i.className="tab-badge",i.hidden=!0,e.append(i),i}unansweredQuestions=new Set;markUnansweredQuestions(e=this.unansweredQuestions){this.unansweredQuestions=e;const t=new Set;for(const s of e){const r=qt.QUESTION_FIELDS[s];if(r&&!r.fields.some(o=>this.shadow.getElementById(o)?.classList.contains("missing-required")))for(const o of r.fields){const l=this.shadow.getElementById(o);l&&!l.hidden&&l.value===""&&t.add(o)}}for(const[s,r]of Object.entries(qt.QUESTION_FIELDS))for(const o of qt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=t.has(o)&&!l.classList.contains("missing-required");l.classList.toggle("wanted",c),(c||l.title===this.messages.questionUnanswered)&&(l.title=c?this.messages.questionUnanswered:"")}const i=new Map;let n;for(const[s,r]of Object.entries(qt.QUESTION_FIELDS))for(const o of r.fields){const l=this.shadow.getElementById(o);if(!l)continue;const c=l.classList.contains("missing-required");!c&&!l.classList.contains("wanted")||(c&&(n=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const s of this.groupTabs){const r=this.panelOf(s),o=i.get(r)??0,l=r===n,c=qt.badgeOn(s);c.hidden=o===0,c.textContent=String(o),c.classList.toggle("optional",!l),s.title=o===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(o))}}paramChip(e){const t=document.createElement("button");t.type="button",t.className=e.fromSource?"param-chip from-source":"param-chip",t.dataset.panel=String(e.panel),t.dataset.field=e.field;const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const s=document.createElement("span");s.className="param-chip-swatch",s.style.background=e.color,t.append(s)}const n=document.createElement("span");return n.className="param-chip-value",n.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(n),t}onParamSummaryClick(e){const t=e.target.closest(".param-chip");if(t==null)return;const i=Number(t.dataset.panel);if(i<0)return;const n=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const s=t.dataset.field;if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorSelect.focus();return}const r=this.shadow.getElementById(s);r===null||!n.contains(r)||(this.revealSubgroupOf(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe(),this.syncAppearanceFromTimeline(),this.syncObserverFromTimeline(),this.syncWeatherFromTimeline(),this.syncWeatherSourceState(),this.syncSoundFromTimeline(),this.syncDecorLitFromTimeline(),this.syncDecorPlacementFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.syncOpticsFromInstrument(),this.ufoElement.selectedSourceIds=this.selectedSourceIds;const t=this.ufoElement.sighting.timeline.sourceIds.filter(i=>this.selectedSourceIds.has(i)).length;this.deleteShapeButton.disabled=this.isRecording||this.ufoElement.playbackState==="playing"||t===0,this.refreshParamSummary()}updateAppearanceFieldsDisabledState(){const e=this.selectedSourceIds.size>1,t=e?this.messages.multipleShapesSelected:"";for(const i of[this.shapeTitleInput,this.colorInput,this.transparencyInput,this.haloScaleInput,this.blurInput,this.brightnessInput,this.apparentWidthInput,this.realWidthInput,this.objectDistanceInput,this.sizeLockSelect,this.clearDistanceHypothesisButton,this.sourceSelect,...Object.values(this.presetButtons)])i.disabled=e,i.title=t}syncAppearanceFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.selectedSourceIds.size>1)return;const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);e&&(this.currentAppearance={presetId:o4(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},this.updatePresetButtons(),this.colorInput.value=this.currentAppearance.color,this.transparencyInput.value=String(this.currentAppearance.transparency),this.haloScaleInput.value=String(this.currentAppearance.haloScale),this.blurInput.value=String(this.currentAppearance.blur),this.brightnessInput.value=String(this.currentAppearance.brightness),this.shadow.activeElement!==this.shapeTitleInput&&(this.shapeTitleInput.value=this.said.read(e.title)??""),this.refreshApparentSize())}updateShapeTitle(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime,i=e.getInterpolatedShapeAt(t,this.currentSourceId);i&&(this.commitShapes(t,[{sourceId:this.currentSourceId,shape:{...i,title:this.said.write(i.title,this.shapeTitleInput.value,this.writingLanguage)}}]),this.ufoElement.refresh(),this.refreshSourceList(),this.updateShapeTitleValidity())}sizeLock="none";onApparentWidthInput(){const e=this.numberOrUndefined(this.apparentWidthInput.value);if(!(e===void 0||e<=0||this.selectedSourceIds.size!==1)){if(this.sizeLock==="real"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.sceneElement.setDistanceHypothesis(this.currentSourceId,it.distanceMAt(t,e))}this.applyApparentWidth(e)}}onRealWidthInput(){const e=this.numberOrUndefined(this.realWidthInput.value);if(e===void 0||e<=0||this.selectedSourceIds.size!==1)return;if(this.sizeLock==="apparent"){const i=this.currentApparentWidthDeg();i!==void 0&&i>0&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,it.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(it.angularWidthDeg({sizeM:e,distanceM:t}))}onDistanceInput(){const e=this.numberOrUndefined(this.objectDistanceInput.value);e===void 0||e<=0||this.applyDistance(e)}applyDistance(e){if(this.selectedSourceIds.size===1){if(this.sizeLock!=="apparent"){const t=this.numberOrUndefined(this.realWidthInput.value);t!==void 0&&t>0&&this.applyApparentWidth(it.angularWidthDeg({sizeM:t,distanceM:e}))}this.sceneElement.setDistanceHypothesis(this.currentSourceId,e),this.refreshDepth()}}applySizeLock(){this.sizeLock=this.sizeLockSelect.value,this.apparentWidthInput.readOnly=this.sizeLock==="apparent",this.realWidthInput.readOnly=this.sizeLock==="real",this.objectDistanceInput.readOnly=this.sizeLock==="distance"}currentApparentWidthDeg(){const e=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId);if(e)return e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width)}currentDistanceM(){return this.sceneElement.depthOf(this.currentSourceId)?.distanceM}applyApparentWidth(e){const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,n=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!n)return;const s=this.currentProjection(),r=s.degToPx(e),o=n.bounds.height*(n.bounds.width===0?1:r/n.bounds.width),l={x:n.bounds.x+(n.bounds.width-r)/2,y:n.bounds.y+(n.bounds.height-o)/2,width:r,height:o},c=s.ofBounds(l),h=n.kind==="oval"?{...n,bounds:l,angular:c}:{...n,bounds:l,angular:c,points:this.scalePoints(n,l)};this.commitShapes(i,[{sourceId:this.currentSourceId,shape:h}]),this.ufoElement.refresh(),this.refreshApparentSize()}scalePoints(e,t){const i=e.bounds.width===0?1:t.width/e.bounds.width,n=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(s=>({x:s.x*i,y:s.y*n}))}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=Et.availableAt(t),n=e.instrument,s=i.includes(n)?i:[...i,n],r=this.instrumentSelect.value||n.id;this.instrumentSelect.replaceChildren();for(const o of s){const l=document.createElement("option");l.value=o.id;const c=this.naming.instrument(o);l.textContent=i.includes(o)?c:this.messages.instrumentOutOfPeriod.replace("{name}",c),this.instrumentSelect.appendChild(l)}this.instrumentSelect.value=s.some(o=>o.id===r)?r:n.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=qt.exposureSeconds(this.exposureInput.value),i=e.exposureRangeSeconds;if(!i)return e.exposureSeconds??t;if(t!==void 0)return Math.min(i.max,Math.max(i.min,t))}static exposureSeconds(e){const t=e.trim();if(!t)return;const i=/^(\d*\.?\d+)\s*\/\s*(\d*\.?\d+)$/.exec(t);if(i){const s=Number(i[1]),r=Number(i[2]);return r>0?s/r:void 0}const n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=et(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Et.fieldOfViewDeg(t),r=n?Et.focalLengthMmFor(t,s):s;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=n?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=n?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=n!==void 0&&n.focalRangeMm===void 0,this.focalLengthInput.min=String(n?n.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(n?n.focalRangeMm?.maxMm??2e3:179),Gi.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=n&&s!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(s,s<10?1:0)):"";const o=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=o===void 0?"":String(o)),this.setRowVisible(this.fNumberInput,t.fNumber!==void 0),this.fNumberInput.disabled=t.fNumberRange===void 0,this.fNumberInput.min=String(t.fNumberRange?.min??.7),this.fNumberInput.max=String(t.fNumberRange?.max??64);const l=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=l===void 0?"":qt.exposureText(l)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0),this.exposureInput.disabled=t.exposureRangeSeconds===void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,n!==void 0&&t.fNumber!==void 0)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Et.fieldOfViewDeg(e),n=Et.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>n4||t.observerTrack.addKeyframe(s.t,{...s.pose,fovDeg:n})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,n=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!n){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(n.max,Math.max(n.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return et(e,this.ufoElement.currentTime)?.fovDeg??Et.fieldOfViewDeg(e.instrument)}currentProjection(){return is.of(this.ufoElement.sighting.instrument,this.ufoElement.canvasElement.height,this.currentFovDeg())}refreshApparentSize(){const e=this.selectedSourceIds.size===1?this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId):void 0;if(!e){this.apparentSizeOutput.textContent="",this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=""),this.refreshRealSize();return}const t=e.angular?.widthDeg??this.currentProjection().pxToDeg(e.bounds.width),i=it.inMoons(t);this.hasFocus(this.apparentWidthInput)||(this.apparentWidthInput.value=this.plain(t,t<1?2:1)),this.apparentSizeOutput.textContent=this.messages.apparentSize.replace("{moons}",i.toLocaleString(void 0,{maximumFractionDigits:i<10?1:0})),this.refreshRealSize()}hasFocus(e){return this.typingIn===e}typingIn;typing(e,t){this.typingIn=e;try{t()}finally{this.typingIn=void 0}}plain(e,t){return String(Number(e.toFixed(t)))}refreshBlurDistanceBound(){const e=this.currentAppearance.blur;if(e<=0||this.selectedSourceIds.size!==1){this.blurBoundOutput.textContent="";return}const t=this.ufoElement.sighting.instrument,i=t.frame;if(!i){this.blurBoundOutput.textContent=this.messages.blurBoundNoInstrument;return}const n=et(this.ufoElement.sighting,this.ufoElement.currentTime),s=n?.focusDistanceM;if(s!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(s));return}const r=(n?Et.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,o=n?.fNumber??t.fNumber;if(o===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Gu*e/l*i.heightMm,h=r*r/(o*c)/1e3;this.blurBoundOutput.textContent=this.messages.blurBound.replace("{max}",this.meters(h))}refreshRealSize(){if(this.refreshDepth(),this.selectedSourceIds.size!==1){this.realSizeOutput.textContent="";return}const e=this.currentSourceId;if(this.sceneElement.sizeContradictory(e)){this.realSizeOutput.textContent=this.messages.realSizeContradiction;return}const{minM:t,maxM:i}=this.sceneElement.sizeRangeOf(e);if(t===void 0&&i===void 0){this.realSizeOutput.textContent=this.messages.realSizeUnknown;return}const n=this.numberOrUndefined(this.realWidthInput.value),s=n!==void 0&&(t!==void 0&&n<t||i!==void 0&&n>i)?this.messages.realSizeOutside:"";if(t!==void 0&&i!==void 0){const r=this.sceneElement.distanceRangeAt(e,this.ufoElement.currentTime),o=r.minM===void 0||r.maxM===void 0?"":this.messages.realDistanceHere.replace("{min}",this.meters(r.minM)).replace("{max}",this.meters(r.maxM));this.realSizeOutput.textContent=this.messages.realSizeBetween.replace("{min}",this.meters(t)).replace("{max}",this.meters(i))+o+s;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+s}decimal(e,t){return e.toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}clearDistanceHypothesis(){this.selectedSourceIds.size===1&&(this.sceneElement.setDistanceHypothesis(this.currentSourceId,void 0),this.refreshDepth())}newBodyStart(){const e=this.currentSourceId,t=this.ufoElement.currentTime,i=e===void 0?void 0:this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,e),n=(v,m)=>Number(v.toFixed(m)),s=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??JI,o=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=o!==void 0&&o<r,c=n(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:n(it.sizeMAt(c,h),2),lengthM:n(it.sizeMAt(c,h),2),heightM:n(it.sizeMAt(c,d),2)}:void 0,f={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},p={t,...f,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:p}:{keyframe:p}}loadBodyEditor(){return this.bodyEditorLoading??=ot(async()=>{const{BodyEditor:e}=await import("./BodyEditor-B_FBjZDB.js");return{BodyEditor:e}},__vite__mapDeps([3,4]),import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,modelProvider:()=>this.decorModelProvider,shapes:()=>this.ufoElement.sighting.timeline.sourceIds.map(t=>({id:t,label:this.shapeLabel(t)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()},newBodyStart:()=>this.newBodyStart(),lookAt:t=>this.lookAtBody(t),currentTime:()=>this.ufoElement.currentTime,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}lookAtBody(e){const t=this.sceneElement.directionToBody(e,this.ufoElement.currentTime);t&&(this.headingInput.value=String(Math.round(t.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(t.altitudeDeg*10)/10),this.updateObserver())}refreshDepth(){const e=this.selectedSourceIds.size===1?this.sceneElement.depthOf(this.currentSourceId):void 0;if(!e){this.depthBasisOutput.textContent="",this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=""),this.hasFocus(this.realWidthInput)||(this.realWidthInput.value="");return}const t=this.meters(e.distanceM);this.hasFocus(this.objectDistanceInput)||(this.objectDistanceInput.value=this.plain(e.distanceM,e.distanceM<10?1:0));const i=this.currentApparentWidthDeg();if(!this.hasFocus(this.realWidthInput)){const s=i===void 0||i<=0?void 0:it.sizeMAt(e.distanceM,i);this.realWidthInput.value=s===void 0?"":this.plain(s,s<1?2:s<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const n={stated:this.messages.depthStated,hypothesis:this.messages.depthHypothesis,derived:this.messages.depthDerived,bounded:this.messages.depthBounded,conventional:this.messages.depthConventional}[e.basis];this.depthBasisOutput.textContent=n.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,n=is.of(i.instrument,it.CANVAS_HEIGHT_PX,Si.fovOf(i,e));i.timeline.addKeyframe(e,t.map(s=>{const r=Si.aimOf(i,e,s.shape.bounds),o=n.ofBounds(s.shape.bounds);return{...s,shape:r?{...s.shape,aim:r,angular:o}:{...s.shape,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.shapeTitleInput.value==="";this.shapeTitleInput.classList.toggle("invalid",e),this.shapeTitleInput.setAttribute("aria-invalid",String(e))}shapeLabel(e){const t=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,e),i=this.said.read(t?.title);if(i)return i;const n=/^ufo-(\d+)$/.exec(e);return n?`${this.messages.shape} ${n[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;if(e.sourceIds.length>0||this.currentSourceId===void 0){const t=new Set([...e.sourceIds,this.currentSourceId]);let i=t.size+1;for(;t.has(`ufo-${i}`);)i++;this.currentSourceId=`ufo-${i}`}this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}deleteShape(){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline.sourceIds.filter(n=>this.selectedSourceIds.has(n));if(t.length===0)return;const i=t.length===1?this.messages.confirmDeleteShape.replace("{name}",this.shapeLabel(t[0])):this.messages.confirmDeleteShapes.replace("{count}",String(t.length));this.askConfirm(i,()=>this.removeShapes(t))}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??ll,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}askConfirm(e,t){this.answerConfirm(!1),this.confirmMessage.textContent=e,this.confirmOverlay.hidden=!1,this.confirmAcceptButton.focus(),this.confirmAnswer=t}answerConfirm(e){const t=this.confirmAnswer;this.confirmAnswer=void 0,this.confirmOverlay.hidden=!0,e&&t?.()}offsetDefaultBounds(e){const t=this.defaultBounds(),i=24;return{...t,x:t.x+e*i,y:t.y+e*i}}refreshSourceList(){const e=this.ufoElement.sighting.timeline,t=e.sourceIds.length>0?[...new Set([...e.sourceIds,this.currentSourceId])]:[];this.sourceSelect.innerHTML="";for(const i of t){const n=document.createElement("option");n.value=i,n.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(n)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const n=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorKindSelect.querySelector(`option[value="${e.kind}"]`)?.textContent??e.kind} ${n}`}addDecor(e=this.decorKindSelect.value){const t=this.ufoElement.sighting,n={id:`decor-${t.decor.length+1}`,kind:e,title:this.nextDecorLabel(e),eastM:8*t.decor.length,northM:15,headingDeg:0,lit:!1,...e==="aircraft"?this.defaultAircraft():{},...e==="building"?{floors:ho}:{},windows:n1(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh()}defaultAircraft(){const e=2*Bu,t=Math.round(e/r4*1e3);return{lights:hd.byId("airliner")?.create(),track:[{t:0,eastM:-Bu,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Bu,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorKindSelect.querySelector(`option[value="${e}"]`)?.textContent??e} ${t+1}`}deleteDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.filter(t=>t.id!==this.currentDecorId),this.currentDecorId=e.decor[0]?.id,this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.decorSelect.value=e,this.syncDecorFields()}updateDecor(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting,t=this.wrapDegrees(Number(this.decorHeadingInput.value),this.decorHeadingInput)??0,i=this.decorObserverSideSelect.value;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=eo(n.kind)&&i!==""?i:void 0,r=Number(this.decorEastInput.value),o=Number(this.decorNorthInput.value),l=Number(this.decorAltitudeInput.value),c=n.track??(l!==0?[]:void 0);if(c){const h=this.ufoElement.currentTime,d={t:h,eastM:r,northM:o,altitudeM:l,headingDeg:t},u=c.filter(f=>f.t!==h);return{...n,title:this.said.write(n.title,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),track:[...u,d].sort((f,p)=>f.t-p.t),sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}return{...n,title:this.said.write(void 0,this.decorTitleInput.value,this.writingLanguage),color:this.statedDecorColor(n),eastM:r,northM:o,headingDeg:t,sightingUrl:this.stringOrUndefined(this.decorSightingUrlInput.value),observerSide:s,sizeM:this.statedDecorSize(),model:this.statedDecorModel(),floors:n.kind==="building"?Number(this.decorFloorsInput.value):void 0,occupiedFloor:n.kind==="building"?Number(this.decorOccupiedFloorInput.value):void 0}}),this.decorSelect.options[this.decorSelect.selectedIndex].textContent=this.decorLabel(e.decor.find(n=>n.id===this.currentDecorId)),this.syncDecorVisibility(),this.updateDecorTitleValidity(),this.ufoElement.refresh()}syncDecorSizeFields(e){const t=e?gi.naturalSize(e.kind,e.floors):void 0,i=[[this.decorWidthInput,e?.sizeM?.widthM,t?.widthM],[this.decorLengthInput,e?.sizeM?.lengthM,t?.lengthM],[this.decorHeightInput,e?.sizeM?.heightM,t?.heightM]];for(const[n,s,r]of i)n.value=s===void 0?"":String(this.roundedMeters(s)),n.placeholder=r===void 0?"":String(this.roundedMeters(r))}syncDecorModelFields(e){this.refreshDecorModelOptions(e),this.decorModelSelect.value=e?.model?.id??"",this.decorModelUrlInput.value=e?.model?.url??"",this.decorModelTitleInput.value=e?.model?.credit?.title??"",this.decorModelAuthorInput.value=e?.model?.credit?.author??"",this.decorModelLicenseInput.value=e?.model?.credit?.license??"",this.decorModelSourceInput.value=e?.model?.credit?.sourceUrl??"",this.decorModelAdvanced.open=e?.model?.url!==void 0,this.showDecorCatalogueModel(e)}async showDecorCatalogueModel(e){const t=e?.model?.url===void 0?e?.model?.id:void 0,i=t===void 0?void 0:await this.decorModelProvider.entry(t).catch(()=>{});e?.id===this.currentDecorId&&(this.shownDecorEntry=i,this.decorModelCatalogueNote.hidden=i===void 0,i&&(this.decorModelUrlInput.value=i.url,this.decorModelTitleInput.value=i.credit.title,this.decorModelAuthorInput.value=i.credit.author??"",this.decorModelLicenseInput.value=i.credit.license,this.decorModelSourceInput.value=i.credit.sourceUrl??""))}shownDecorEntry;async refreshDecorModelOptions(e){const t=e??this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),i=t?await this.decorModelProvider.entries(t.kind).catch(()=>[]):[],n=t?.model?.id??"",s=document.createElement("option");s.value="",s.textContent=this.messages.decorModelNone,this.decorModelSelect.replaceChildren(s,...i.map(r=>{const o=document.createElement("option");return o.value=r.id,o.textContent=r.name,o.title=`${r.credit.title}${r.credit.author?` — ${r.credit.author}`:""} (${r.credit.license})`,o})),this.decorModelSelect.value=n}updateDecorModelChoice(){const e=this.decorModelSelect.value;(async()=>{const t=e?await this.decorModelProvider.entry(e).catch(()=>{}):void 0,i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);if(t?.sizeM&&i&&!i.sizeM){const n=[[this.decorWidthInput,t.sizeM.widthM],[this.decorLengthInput,t.sizeM.lengthM],[this.decorHeightInput,t.sizeM.heightM]];for(const[s,r]of n)r!==void 0&&(s.value=String(this.roundedMeters(r)))}this.updateDecor()})()}roundedMeters(e){return Math.round(e*100)/100}positiveMeters(e){const t=Number(e);return e.trim()===""||!Number.isFinite(t)||t<=0?void 0:t}statedDecorColor(e){const t=this.decorColorInput.value;return t==="#808080"&&e.color===void 0?void 0:t}statedDecorSize(){const e=this.positiveMeters(this.decorWidthInput.value),t=this.positiveMeters(this.decorLengthInput.value),i=this.positiveMeters(this.decorHeightInput.value);return e===void 0&&t===void 0&&i===void 0?void 0:{widthM:e,lengthM:t,heightM:i}}statedDecorModel(){const e=this.stringOrUndefined(this.decorModelUrlInput.value),t=this.shownDecorEntry;if(t&&e===t.url&&this.stringOrUndefined(this.decorModelTitleInput.value)===t.credit.title&&this.stringOrUndefined(this.decorModelAuthorInput.value)===t.credit.author&&this.stringOrUndefined(this.decorModelLicenseInput.value)===t.credit.license&&this.stringOrUndefined(this.decorModelSourceInput.value)===t.credit.sourceUrl)return{id:t.id};if(e){const n=this.stringOrUndefined(this.decorModelTitleInput.value),s=this.stringOrUndefined(this.decorModelLicenseInput.value);return{url:e,credit:n!==void 0&&s!==void 0?{title:n,license:s,author:this.stringOrUndefined(this.decorModelAuthorInput.value),sourceUrl:this.stringOrUndefined(this.decorModelSourceInput.value)}:void 0}}const i=this.stringOrUndefined(this.decorModelSelect.value);return i===void 0?void 0:{id:i}}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=ca([...t.milestones,{t:e,label:this.nextMilestoneLabel()}])),this.currentMilestoneT=e,this.refreshMilestoneList(),this.ufoElement.refresh()}nextMilestoneLabel(){const e=new Set(this.ufoElement.sighting.milestones.map(t=>t.label));for(let t=0;t<26;t++){const i=String.fromCharCode(65+t);if(!e.has(i))return i}return String(this.ufoElement.sighting.milestones.length+1)}deleteMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting,i=t.milestones.find(n=>n.t===e);i&&this.askConfirm(this.messages.confirmDeleteMilestone.replace("{name}",this.said.read(i.label)??""),()=>{t.milestones=t.milestones.filter(n=>n.t!==e),this.currentMilestoneT=t.milestones[0]?.t,this.refreshMilestoneList(),this.ufoElement.refresh()})}selectMilestone(e){this.currentMilestoneT=e,this.syncMilestoneFields(),this.goToMark(e)}updateMilestone(){const e=this.currentMilestoneT;if(e===void 0)return;const t=this.ufoElement.sighting;t.milestones=t.milestones.map(i=>i.t===e?{...i,label:this.said.write(i.label,this.milestoneLabelInput.value,this.writingLanguage)??"",note:this.said.write(i.note,this.milestoneNoteInput.value,this.writingLanguage)}:i),this.refreshMilestoneList(),this.ufoElement.refresh()}refreshMilestoneList(){const e=ca(this.ufoElement.sighting.milestones);e.some(t=>t.t===this.currentMilestoneT)||(this.currentMilestoneT=e[0]?.t),this.milestoneSelect.replaceChildren(...e.map(t=>{const i=document.createElement("option");return i.value=String(t.t),i.textContent=`${this.said.read(t.label)??""} — ${this.formatSeconds(t.t)}`,i.title=this.said.read(t.note)??"",i})),this.currentMilestoneT!==void 0&&(this.milestoneSelect.value=String(this.currentMilestoneT)),this.syncMilestoneFields()}formatSeconds(e){return`${(e/1e3).toFixed(1)} s`}syncMilestoneFields(){const e=this.ufoElement.sighting.milestones.find(i=>i.t===this.currentMilestoneT),t=e!==void 0;for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.milestoneLabelInput,this.milestoneNoteInput,this.deleteMilestoneButton])i.disabled=!t,this.setRowVisible(i,t);this.milestoneLabelInput.value=this.said.read(e?.label)??"",this.milestoneNoteInput.value=this.said.read(e?.note)??""}updateDecorTitleValidity(){const e=this.currentDecorId!==void 0&&this.decorTitleInput.value==="";this.decorTitleInput.classList.toggle("invalid",e),this.decorTitleInput.setAttribute("aria-invalid",String(e))}updateDecorWindows(){if(this.currentDecorId===void 0)return;const e=this.ufoElement.sighting;e.decor=e.decor.map(t=>{if(t.id!==this.currentDecorId)return t;const i={};for(const n of xa){const s=this.decorWindowInputs[n];if(s.value==="")continue;const r=Wu(t.kind,n)?0:Vu,o=Math.max(r,Math.min(100,Number(s.value)));i[n]=o,String(o)!==s.value&&(s.value=String(o))}return{...t,windows:i}}),this.ufoElement.refresh()}updateDecorLit(){if(this.currentDecorId===void 0||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting,t=this.ufoElement.currentTime,i=this.decorLitInput.checked;e.decor=e.decor.map(n=>{if(n.id!==this.currentDecorId)return n;const s=[...(n.litKeyframes??[]).filter(r=>r.t!==t),{t,lit:i}].sort((r,o)=>r.t-o.t);return{...n,litKeyframes:s}}),this.ufoElement.refresh()}refreshDecorList(){const e=this.ufoElement.sighting.decor;this.decorSelect.innerHTML="";for(const t of e){const i=document.createElement("option");i.value=t.id,i.textContent=this.decorLabel(t),this.decorSelect.appendChild(i)}this.currentDecorId!==void 0&&(this.decorSelect.value=this.currentDecorId),this.syncDecorFields()}syncDecorFields(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId),t=e!==void 0;this.deleteDecorButton.disabled=!t;for(const i of[this.decorSelect,this.decorTitleInput,this.decorEastInput,this.decorNorthInput,this.decorHeadingInput,this.decorLitInput,this.decorSightingUrlInput,this.decorWidthInput,this.decorLengthInput,this.decorHeightInput,this.decorModelSelect,this.decorModelUrlInput,this.decorModelTitleInput,this.decorModelAuthorInput,this.decorModelLicenseInput,this.decorModelSourceInput,this.decorFloorsInput,this.decorOccupiedFloorInput,this.decorObserverSideSelect,this.decorLightRigSelect,this.decorAltitudeInput,this.lookAtDecorButton])i.disabled=!t;this.decorTitleInput.value=this.said.read(e?.title)??"",this.decorColorInput.value=e?.color??"#808080",this.showDecorPlacement(e),this.decorLitInput.checked=e?mh(e,this.ufoElement.currentTime):!1,this.refreshDecorLightRigOptions(e),this.decorSightingUrlInput.value=e?.sightingUrl??"",this.syncDecorSizeFields(e),this.syncDecorModelFields(e),this.decorFloorsInput.value=String(e?.floors??ho),this.decorOccupiedFloorInput.value=String(e?.occupiedFloor??0),this.decorObserverSideSelect.value=e?.observerSide??"";for(const i of xa){const n=e?.windows?.[i];this.decorWindowInputs[i].value=n===void 0?"":String(n)}this.syncDecorVisibility(),this.updateDecorTitleValidity()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId),t=e!==void 0,i=e?.kind;this.setRowVisible(this.decorSelect,t),this.setRowVisible(this.deleteDecorButton,t),this.setRowVisible(this.decorTitleInput,t),this.setRowVisible(this.decorEastInput,t),this.setRowVisible(this.decorNorthInput,t),this.setRowVisible(this.decorAltitudeInput,t),this.setRowVisible(this.decorHeadingInput,t),this.setRowVisible(this.decorWidthInput,t),this.setRowVisible(this.decorLengthInput,t),this.setRowVisible(this.decorHeightInput,t),this.setRowVisible(this.decorModelSelect,t),this.decorModelAdvanced.hidden=!t,this.setRowVisible(this.decorLitInput,t&&e?.kind!=="aircraft");const n=t&&i!==void 0&&_p(i);this.setRowVisible(this.labelDecorWindows,n);const s=i!==void 0?Ep(i):[];for(const c of xa)this.decorWindowInputs[c].disabled=!t,this.decorWindowInputs[c].min=String(i!==void 0&&Wu(i,c)?0:Vu),this.setRowVisible(this.decorWindowInputs[c],n&&s.includes(c));const r=t&&i!==void 0&&eo(i);this.setRowVisible(this.decorObserverSideSelect,r);const o=i!==void 0?Vy(i):[];for(const c of xa)this.optionObserverSide[c].hidden=!o.includes(c);const l=t&&i==="building";this.setRowVisible(this.decorFloorsInput,l),this.setRowVisible(this.decorOccupiedFloorInput,l),this.decorOccupiedFloorInput.max=String(e?.floors??ho)}showDecorPlacement(e){const t=e?Dr(e,this.ufoElement.currentTime):void 0,i=[[this.decorEastInput,t?.eastM??0],[this.decorNorthInput,t?.northM??0],[this.decorAltitudeInput,t?.altitudeM??0],[this.decorHeadingInput,t?.headingDeg??0]];for(const[n,s]of i)this.shadow.activeElement!==n&&(n.value=String(this.rounded(s)))}syncDecorPlacementFromTimeline(){this.ufoElement.playbackState!=="playing"&&this.showDecorPlacement(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}showNextMeteor(){const e=this.sceneElement.meteorByRank(this.meteorRank++);e&&(this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=e.t,this.headingInput.value=String(Math.round(e.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(e.altitudeDeg*10)/10),this.updateObserver())}resetMeteorRankIfSkyChanged(){const e=this.sceneElement.meteorByRank(0),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;skyCandidatesKey;static reentryArchive=new fn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new Hh;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new Qn(["en"]);tagNames=new $u({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,n=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?Un(i,t.lng,e.event.utcOffsetHours):void 0,s=JSON.stringify([n?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,ii(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status]);if(s===this.skyCandidatesKey)return;if(this.skyCandidatesKey=s,!n||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.hidden=!0,this.showCometButton.hidden=!0,this.showNovaButton.hidden=!0,this.showSatelliteButton.hidden=!0,this.showFireballButton.hidden=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown);return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},o=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.satelliteClause(n,r),this.reentryClause(n,r),this.fireballClause(n,r),this.opticsClause(n,r),this.rainbowClause(n,r),this.glowClause(n,r)].filter(l=>l!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",o.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return Vi.gainFor(e.instrument,{fNumber:et(e,0)?.fNumber,fieldOfViewDeg:Si.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Li("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=_r(i,n,s),o=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<e4)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",o(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",o(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",o(Math.abs(n))).replace("{eye}",o(_r(i,0,s)));return r<=xl?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",o(xl))}showerClause(e,t){const i=jt.observedRatePerHour(jt.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=Eo.activeAt(e);if(n.length===0)return this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyNothingActive.replace("{sporadic}",i);const s=n.map(r=>{const o=Eo.radiantPosition(r.shower,e,t);return{entry:r,position:o,rate:Eo.observedRatePerHour(r.zhr,o.altitudeDeg,r.shower.populationIndex)}}).sort((r,o)=>o.rate-r.rate)[0];return s.rate<=0?(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(s.entry.shower))):(this.showMeteorButton.hidden=!this.sceneElement.meteorByRank(0),this.messages.skyShowerActive.replace("{name}",this.naming.shower(s.entry.shower)).replace("{altitude}",String(Math.round(s.position.altitudeDeg))).replace("{bearing}",this.naming.towards(s.position.azimuthDeg)).replace("{rate}",s.rate.toLocaleString(void 0,{maximumFractionDigits:s.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=lh.brightestAt(e,t);if(!i||i.magnitude>Po){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=Gh.brightestAt(e,t);if(!i||i.magnitude>Po){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}novaText(e){return(e.position.altitudeDeg<=0?this.messages.skyNovaBelowHorizon:this.messages.skyNova).replace("{name}",this.naming.nova(e.outburst)).replace("{magnitude}",e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg))}satelliteClause(e,t){const i=Kn.visibilityAt(e,t),n=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(n!==void 0)return n;if(this.showSatelliteButton.hidden=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const s=_r(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),o=this.listed(r.map(d=>this.naming.satelliteClass(d)));if(i.sunAltitudeDeg>=0)return r.length===0?void 0:(r.length===1?this.messages.skySatellitesDaylightOne:this.messages.skySatellitesDaylight).replace("{eras}",o);const l=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",l).replace("{count}",c);return i.lowOrbitLit?r.length===0?h(this.messages.skySatellitesLit):h(this.messages.skySatellitesLitWith).replace("{eras}",o):h(this.messages.skySatellitesShadowed)}reentryClause(e,t){const i=e.getTime(),n=i+this.satelliteSpanMs(),s=[i,n,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==s){const c={key:s,status:"loading"};this.reentries=c,qt.reentryArchive.candidates(i,n,t).then(h=>{c.status=h?"ready":"unavailable",c.candidates=h,this.reentries===c&&(this.skyCandidatesKey=void 0,this.refreshSkyCandidates())});return}if(this.reentries.status!=="ready")return;const r=Kn.visibilityAt(e,t).sunAltitudeDeg<-6,o=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(o.length===0)return;const l=o.slice(0,3).map(c=>this.reentryText(c));return o.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(o.length-3))),this.messages.skyReentries.replace("{list}",l.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,n=new Date(e.timeMs);if(t.precision==="day"){const o=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",o)}const s=this.observerClock(n).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",s).replace("{hours}",(t.uncertaintyHours??0).toLocaleString(this.showerLanguage()));const r=e.offsetMinutes?this.messages.skyReentryOffset.replace("{minutes}",String(e.offsetMinutes)):"";return t.seenFrom&&e.seenKm!==void 0?this.messages.skyReentrySeen.replace("{name}",i).replace("{time}",s).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",s)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(h=>h.status!=="covered"))return this.showSatelliteButton.hidden=!0,t.coverage.some(h=>h.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses(),n=i.filter(h=>this.passTimelineMs(h)<=this.ufoElement.seekableDuration);if(this.showSatelliteButton.hidden=n.length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const r=i[0].peak,l=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",r.object.name).replace("{magnitude}",r.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(r.altitudeDeg))).replace("{bearing}",this.naming.towards(r.azimuthDeg)).replace("{time}",this.observerClock(r.date)),c=this.starlinkTrain(i);return c?`${l}, ${c}`:l}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const n=i.peak.magnitude;if(n===void 0)return!1;const s=Li("Sun",i.peak.date,t);return n<=_r(s.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,n)=>i.peak.magnitude-n.peak.magnitude)}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:o,launch:l}=r.peak.object;o!=="starlink"||!l||(r.peak.date.getTime()-Date.parse(`${l}T00:00:00Z`))/864e5>60||t.set(l,(t.get(l)??0)+1)}const[i,n]=[...t.entries()].sort((r,o)=>o[1]-r[1])[0]??[];if(!i||!n||n<3)return;const s=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(n)).replace("{date}",s)}satelliteSpanMs(){const e=(this.ufoElement.sighting.event.durationSeconds??0)*1e3;return Math.max(e,this.ufoElement.seekableDuration)}observerAtStart(){const e=this.ufoElement.sighting.event.place?.[0],t=et(this.ufoElement.sighting,0);return{lat:t?.lat??e?.lat??0,lng:t?.lng??e?.lng??0,elevationM:this.groundElevationM??0}}passTimelineMs(e){const t=this.ufoElement.sighting,i=Un(t.event.time??{},this.observerAtStart().lng,t.event.utcOffsetHours);return i?e.peak.date.getTime()-i.getTime():1/0}observerClock(e){const i=this.ufoElement.sighting.event.utcOffsetHours??Math.round(this.observerAtStart().lng/15);return new Date(e.getTime()+i*36e5).toLocaleTimeString(this.showerLanguage(),{hour:"2-digit",minute:"2-digit",second:"2-digit",timeZone:"UTC"})}showNextSatellite(){const e=this.visibleSatellitePasses().filter(n=>this.passTimelineMs(n)<=this.ufoElement.seekableDuration);if(e.length===0)return;const t=e.map(n=>`${n.object.norad}@${n.peak.date.getTime()}`).join();t!==this.satelliteRankFor&&(this.satelliteRankFor=t,this.satelliteRank=0);const i=e[this.satelliteRank++%e.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.passTimelineMs(i),this.headingInput.value=String(Math.round(i.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(i.peak.altitudeDeg*10)/10),this.updateObserver()}satelliteRankFor;satelliteRank=0;strikingFireballs(e,t){return this.sceneElement.fireballState.records.map(i=>Bn.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Bn.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,n)=>i.magnitude-n.magnitude)}fireballTimelineMs(e,t){const{record:i}=e,n=i.from[2]-i.to[2],s=Math.abs(n)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/n));return i.t-t.getTime()+s*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.hidden=!i.some(r=>this.fireballTimelineMs(r,e)<=this.ufoElement.seekableDuration),i.length===0)return;const n=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",n.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(n.record.t))).replace("{altitude}",String(Math.round(n.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(n.peak.azimuthDeg)).replace("{distance}",String(Math.round(n.peak.distanceKm/10)*10)).replace("{stations}",String(n.record.stations??2))}showNextFireball(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lng===void 0||!i)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(o=>this.fireballTimelineMs(o,n)<=this.ufoElement.seekableDuration);if(s.length===0)return;const r=s[this.fireballRank++%s.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,n),this.headingInput.value=String(Math.round(r.peak.azimuthDeg*10)/10),this.pitchInput.value=String(Math.round(r.peak.altitudeDeg*10)/10),this.updateObserver()}fireballRank=0;opticsClause(e,t){const i=ii(this.ufoElement.sighting,0),n=Li("Sun",e,t),s=Li("Moon",e,t),r=ht.deckLitUntilDeg(ht.DECK_HEIGHT_M),o=n.altitudeDeg>-r,l=o?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(ht.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=o?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(ht.formsAt(l.altitudeDeg,r).map(f=>this.opticsFormName(f))),u=i.iceCrystalAlignment??.65;return this.messages.skyOpticsPossible.replace("{forms}",d).replace("{source}",h)+this.messages.skyOpticsAlignment.replace("{alignment}",String(Math.round(u*100)))}rainbowClause(e,t){const i=ii(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Li("Sun",e,t),s=Li("Moon",e,t),r=n.altitudeDeg>0,o=r?n:s;if(o.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(Wi.strength(i.precipitationIntensity,l,o.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Wi.formsAt(o.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(o.altitudeDeg))).replace("{radius}",String(Math.round(Wi.primary().radiusDeg)));const h=this.listed(c.map(u=>this.bowFormName(u)));if(r)return this.messages.skyBowPossible.replace("{forms}",h);const d=Math.round(ao(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Li("Sun",e,t);if(i.altitudeDeg>l4)return;const n=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),s=[];if(n.milkyWay&&s.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(n.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(n.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(n.milkyWay.azimuthDeg))),n.zodiacal){const f=n.zodiacal.sunSeparationDeg<=yt.CONE_SEPARATION_DEG;s.push((f?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(n.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(n.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(n.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(n.zodiacal.sunSeparationDeg))))}if(s.length>0)return this.listed(s);const r=this.decimal(n.darkestSkyMagPerArcsec2,1),o=Li("Moon",e,t),l=n.darkestSkyMagPerArcsec2<c4,c=this.ufoElement.sighting.lightPollution,h=le.scatteringAt(90-o.altitudeDeg)*le.moonOutput(le.phaseAngleOf(ao(e).illuminatedFraction),o.altitudeDeg)*le.scatteredFraction(90),d=le.artificialZenithNanolamberts(c)>h;if(l&&o.altitudeDeg>0&&!d){const f=Math.round(ao(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(f)).replace("{sky}",r)}const u=le.artificialZenithNanolamberts(c)>le.twilightExcessNanolamberts(i.altitudeDeg);return l&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):l?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Li("Sun",e,t),n=Li("Moon",e,t);return le.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:le.phaseAngleOf(ao(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new yt;bowFormName(e){return(e.id==="primary"?this.messages.skyBowPrimary:this.messages.skyBowSecondary).replace("{radius}",String(Math.round(e.radiusDeg))).replace("{top}",String(Math.round(e.topAltitudeDeg)))}opticsFormName(e){const t=i=>String(Math.round(i??0));switch(e.id){case"halo22":return this.messages.skyOpticsHalo22.replace("{angle}",t(e.angleDeg));case"halo46":return this.messages.skyOpticsHalo46.replace("{angle}",t(e.angleDeg));case"parhelia":return this.messages.skyOpticsParhelia.replace("{angle}",t(e.angleDeg));case"tangentArc":return this.messages.skyOpticsTangentArc;case"parhelicCircle":return this.messages.skyOpticsParhelicCircle;case"circumzenithal":return this.messages.skyOpticsCircumzenithal.replace("{angle}",t(e.angleDeg));case"circumhorizontal":return this.messages.skyOpticsCircumhorizontal;case"pillar":return this.messages.skyOpticsPillar}}listed(e){return new Intl.ListFormat(this.showerLanguage(),{style:"long",type:"conjunction"}).format(e)}cometText(e){const t=this.naming.comet(e.apparition),i=e.magnitude.toLocaleString(void 0,{maximumFractionDigits:1});return e.position.altitudeDeg<=0?this.messages.skyCometBelowHorizon.replace("{name}",t).replace("{magnitude}",i):(e.elongationDeg<lh.TWILIGHT_ELONGATION_DEG?this.messages.skyCometInDaylight:e.tailLengthDeg===void 0?this.messages.skyCometNoTail:this.messages.skyComet).replace("{name}",t).replace("{magnitude}",i).replace("{altitude}",String(Math.round(e.position.altitudeDeg))).replace("{bearing}",this.naming.towards(e.position.azimuthDeg)).replace("{tail}",String(Math.round(e.tailLengthDeg??0))).replace("{elongation}",String(Math.round(e.elongationDeg)))}lookAtComet(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=lh.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}lookAtNova(){const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time;if(!t||t.lat===void 0||t.lng===void 0||i?.year===void 0)return;const n=Un(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=Gh.brightestAt(n,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});s&&(this.headingInput.value=String(this.rounded(s.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(s.position.altitudeDeg)),this.updateObserver())}refreshHeadingPoint(){const e=this.numberOrUndefined(this.headingInput.value);this.headingUnit.textContent=e===void 0?"°":`° (${this.naming.point(e)})`}rounded(e){return Math.round(e*10)/10}lookAtDecor(){const e=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:n}=Dr(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,o=Math.atan2(n-s4,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(o*10)/10),this.updateObserver()}refreshDecorLightRigOptions(e){const t=e?hd.forKind(e.kind):[],i=document.createElement("option");i.value="",i.textContent=this.messages.decorLightsNone,this.decorLightRigSelect.replaceChildren(i,...t.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=this.naming.lightRig(s),r}));const n=e?.lights?.map(s=>s.id).join()??"";this.decorLightRigSelect.value=t.find(s=>s.create().map(r=>r.id).join()===n)?.id??""}updateDecorLightRig(){const e=this.ufoElement.sighting,t=e.decor.find(n=>n.id===this.currentDecorId);if(!t)return;const i=hd.byId(this.decorLightRigSelect.value);e.decor=e.decor.map(n=>n.id===t.id?{...n,lights:i?i.create():void 0}:n),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorLitFromTimeline(){if(this.ufoElement.playbackState==="playing"||this.shadow.activeElement===this.decorLitInput)return;const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);e&&(this.decorLitInput.checked=mh(e,this.ufoElement.currentTime))}updatePresetButtons(){for(const e of Yv)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return A0(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-Za.width/2,y:e.height/2-Za.height/2,width:Za.width,height:Za.height}}toggleRecording(){this.endDrag();const e=this.ufoElement.canvasElement;this.isRecording?(this.recorder?.stop(),this.isRecording=!1,this.setRecordButtonLabel(!1),this.setCanvasCursor(void 0),e.style.touchAction="",this.sourceSelect.disabled=!1,this.addShapeButton.disabled=!1,this.ufoElement.refresh(),this.refreshSourceList()):(this.recorder=new MI(this.ufoElement.sighting.timeline,new wI(this.samplingRate)),this.recorder.start(this.currentSourceId,this.buildPrototype()),this.isRecording=!0,this.setRecordButtonLabel(!0),this.setCanvasCursor("record"),e.style.touchAction="none",this.sourceSelect.disabled=!0,this.addShapeButton.disabled=!0,this.deleteShapeButton.disabled=!0)}setRecordButtonLabel(e){this.recordButton.textContent=e?"⏹":"⏺";const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t)}async loadLocaleMessages(){const e=++this.localeToken,t=qs.preferencesFor(this);this.preferences=t;const i=vh(t,uh),n=this.narrativeProvider.localize?.(i),[s,r,o]=i==="en"?[yp,{},void 0]:await Promise.all([Py(i),Ly(i),e1(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new Hh(o),this.said=new Qn(t),this.tagNames=new $u(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new dd(s,this.naming,this.said,this.tagNames),this.refreshParamSummary()),l?this.showSaidTexts():this.showTags()}preferences=[];language="en";localeToken=0;showSaidTexts(){this.refreshSourceList(),this.refreshDecorList(),this.refreshReferenceList(),this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncObserverMetadataFields()}showTags(){this.tagsInput.value=this.ufoElement.sighting.event.tags?.map(e=>this.tagNames.name(e)).join(", ")??""}applyMessages(e){this.currentSourceId===ll&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.presetButtons.oval.textContent=e.oval,this.presetButtons.polygon.textContent=e.polygon,this.contextAddVertexButton.textContent=e.addVertex,this.contextDeleteVertexButton.textContent=e.deleteVertex,this.labelColor.textContent=e.color,this.labelTransparency.textContent=e.transparency,this.labelHalo.textContent=e.halo,this.labelBlur.textContent=e.blur,this.labelBrightness.textContent=e.brightness,this.labelShape.textContent=e.shape,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder,this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.labelSizeLock.textContent=e.sizeLock;for(const[n,s]of[["option-lock-none",e.lockNone],["option-lock-apparent",e.lockApparent],["option-lock-real",e.lockReal],["option-lock-distance",e.lockDistance]])this.shadow.getElementById(n).textContent=s;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.labelDuration.textContent=e.duration,this.durationInput.placeholder=e.durationPlaceholder,this.addShapeButton.title=e.addShape,this.addShapeButton.setAttribute("aria-label",e.addShape),this.deleteShapeButton.title=e.deleteShape,this.deleteShapeButton.setAttribute("aria-label",e.deleteShape),this.contextGroupButton.textContent=e.group,this.contextUngroupButton.textContent=e.ungroup,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.labelImportFile.textContent=e.importFile,this.labelImportUrl.textContent=e.importUrl,this.importUrlInput.placeholder=e.importUrlPlaceholder,this.importUrlButton.textContent=e.importButton,this.labelObserverAge.textContent=e.observerAge,this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,this.labelAccountUrl.textContent=e.accountUrl,this.labelAccountFollowedUp.textContent=e.accountFollowedUp;for(const[n,s]of[["option-source-unknown",e.accountSourceUnknown],["option-source-on-site",e.accountSourceOnSite],["option-source-interview",e.accountSourceInterview],["option-source-telephone",e.accountSourceTelephone],["option-source-questionnaire",e.accountSourceQuestionnaire],["option-source-letter",e.accountSourceLetter],["option-source-social-media",e.accountSourceSocialMedia],["option-source-press",e.accountSourcePress],["option-followed-unknown",e.accountUnknown],["option-followed-yes",e.accountYes],["option-followed-no",e.accountNo]]){const r=this.shadow.getElementById(n);r&&(r.textContent=s)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),this.labelNarrativeRemember.textContent=e.narrativeRemember,this.narrativeStopButton.textContent=e.narrativeStop,this.narrativeDraftButton.textContent=e.narrativeDraft,this.descriptionInput.placeholder=e.narrativePlaceholder,this.syncNarrativeEnabled(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.labelPlaceName.textContent=e.placeName,this.placeNameInput.placeholder=e.placeNamePlaceholder,this.searchPlaceButton.textContent=e.searchPlace,this.labelPlaceMatch.textContent=e.placeMatch,this.labelLatitude.textContent=e.latitude,this.labelLongitude.textContent=e.longitude,this.labelHeading.textContent=e.heading,this.headingInput.placeholder=e.headingPlaceholder,this.labelPitch.textContent=e.pitch,this.labelRoll.textContent=e.roll,this.labelSway.textContent=e.sway,this.swayInput.title=e.swayTitle,this.labelLightPollution.textContent=e.lightPollution,this.lightPollutionInput.title=e.lightPollutionTitle,this.syncLightPollutionStatus(),this.labelElevation.textContent=e.elevation,this.labelObservationTime.textContent=e.observationTime,this.labelObservationEndTime.textContent=e.observationEndTime,this.obsTimeInput.placeholder=e.edtfPlaceholder,this.obsTimeInput.title=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.obsEndTimeInput.title=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecor.textContent=e.decor,this.labelDecorGroup.textContent=e.decor,this.optionDecorBuilding.textContent=e.decorBuilding,this.optionDecorTree.textContent=e.decorTree,this.optionDecorShrub.textContent=e.decorShrub,this.optionDecorBridge.textContent=e.decorBridge,this.optionDecorCrop.textContent=e.decorCrop,this.optionDecorMound.textContent=e.decorMound,this.optionDecorStreetlight.textContent=e.decorStreetlight,this.optionDecorVehicle.textContent=e.decorVehicle,this.optionDecorAircraft.textContent=e.decorAircraft,this.optionDecorEntity.textContent=e.decorEntity,this.labelDecorLights.textContent=e.decorLights,this.labelDecorAltitude.textContent=e.decorAltitude,this.showMeteorButton.title=e.showMeteor,this.showMeteorButton.setAttribute("aria-label",e.showMeteor),this.showCometButton.title=e.showComet,this.showCometButton.setAttribute("aria-label",e.showComet),this.showNovaButton.title=e.showNova,this.showNovaButton.setAttribute("aria-label",e.showNova),this.showSatelliteButton.title=e.showSatellite,this.showSatelliteButton.setAttribute("aria-label",e.showSatellite),this.showFireballButton.title=e.showFireball,this.showFireballButton.setAttribute("aria-label",e.showFireball),this.lookAtDecorButton.title=e.lookAtDecor,this.lookAtDecorButton.setAttribute("aria-label",e.lookAtDecor),this.optionDecorObserver.textContent=e.decorObserver,this.deleteDecorButton.title=e.deleteDecor,this.deleteDecorButton.setAttribute("aria-label",e.deleteDecor),this.labelDecorTitle.textContent=e.decorTitle,this.labelDecorEast.textContent=e.decorEast,this.labelDecorNorth.textContent=e.decorNorth,this.labelDecorHeading.textContent=e.decorHeading,this.labelDecorColor.textContent=e.decorColor,this.labelDecorLit.textContent=e.decorLit,this.labelDecorSightingUrl.textContent=e.decorSightingUrl,this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.addDecorBuildingButton.title=e.addDecor,this.addDecorBuildingButton.setAttribute("aria-label",e.addDecor),this.confirmAcceptButton.textContent=e.confirmAccept,this.confirmDeclineButton.textContent=e.confirmDecline,this.labelMilestones.textContent=e.milestones,this.labelMilestoneLabel.textContent=e.milestoneLabel,this.labelMilestoneNote.textContent=e.milestoneNote;for(const[n,s]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=s,n.setAttribute("aria-label",s);this.labelDecorWidth.textContent=e.decorWidth,this.labelDecorLength.textContent=e.decorLength,this.labelDecorHeight.textContent=e.decorHeight,this.labelDecorModel.textContent=e.decorModel,this.labelDecorModelAdvanced.textContent=e.decorModelAdvanced,this.decorModelCatalogueNote.textContent=e.decorModelFromCatalogue,this.labelDecorModelUrl.textContent=e.decorModelUrl,this.labelDecorModelTitle.textContent=e.decorModelTitle,this.labelDecorModelAuthor.textContent=e.decorModelAuthor,this.labelDecorModelLicense.textContent=e.decorModelLicense,this.labelDecorModelSource.textContent=e.decorModelSource,this.labelDecorFloors.textContent=e.decorFloors,this.labelDecorOccupiedFloor.textContent=e.decorOccupiedFloor,this.labelDecorObserverSide.textContent=e.decorObserverSide,this.labelDecorWindows.textContent=e.decorWindows,this.optionObserverSideNone.textContent=e.decorObserverSideNone;const t={front:e.decorSideFront,behind:e.decorSideBehind,left:e.decorSideLeft,right:e.decorSideRight,"front-left":e.decorSideFrontLeft,"front-right":e.decorSideFrontRight,"behind-left":e.decorSideBehindLeft,"behind-right":e.decorSideBehindRight};for(const n of xa)this.labelDecorSide[n].textContent=t[n],this.optionObserverSide[n].textContent=t[n];this.refreshDecorList(),this.labelObserverId.textContent=e.observerId,this.labelObserverTitle.textContent=e.observerTitle,this.labelObserverLastName.textContent=e.observerLastName,this.labelObserverFirstNames.textContent=e.observerFirstNames,this.observerFirstNamesInput.placeholder=e.tagsPlaceholder,this.labelSightingId.textContent=e.sightingId,this.labelDescription.textContent=e.description,this.labelTags.textContent=e.tags,this.tagsInput.placeholder=e.tagsPlaceholder,this.labelShapeGroup.textContent=e.shapeGroup,this.labelShapesSubgroup.textContent=e.shapesSubgroup,this.labelBodiesSubgroup.textContent=e.bodiesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.refreshTimeQualifierOptions(),this.edtfModeButton.title=e.edtfModeTitle,this.edtfModeButton.setAttribute("aria-label",e.edtfModeTitle),this.paramSummaryBuilder=new dd(e,this.naming,this.said,this.tagNames),this.refreshParamSummary();const i=this.skyDetailsButton.getAttribute("aria-expanded")==="true";this.skyDetailsButton.title=i?e.skyDetailsHide:e.skyDetails,this.skyDetailsButton.setAttribute("aria-label",this.skyDetailsButton.title),this.labelCloudCover.textContent=e.cloudCover,this.labelHighCloud.textContent=e.highCloudCover,this.labelIceAlignment.textContent=e.iceCrystalAlignment,this.labelFNumber.textContent=e.aperture,this.labelExposure.textContent=e.exposure,this.labelFocusDistance.textContent=e.focusDistance,this.syncOpticsFromInstrument(),this.labelCloudDarkness.textContent=e.cloudDarkness,this.labelCloudBase.textContent=e.cloudBase,this.labelPrecipitationType.textContent=e.precipitationType,this.optionPrecipitationNone.textContent=e.precipitationNone,this.optionPrecipitationRain.textContent=e.precipitationRain,this.optionPrecipitationSnow.textContent=e.precipitationSnow,this.optionPrecipitationHail.textContent=e.precipitationHail,this.labelPrecipitationIntensity.textContent=e.precipitationIntensity,this.labelWindDirection.textContent=e.windDirection,this.labelWindSpeed.textContent=e.windSpeed,this.labelStorm.textContent=e.storm,this.labelCloudsGroup.textContent=e.cloudsGroup,this.labelPrecipitationGroup.textContent=e.precipitationGroup,this.labelWindGroup.textContent=e.windGroup,this.labelWeatherInferred.textContent=e.weatherInferred,this.syncWeatherSourceState(),this.labelSoundGroup.textContent=e.soundGroup,this.labelSoundKind.textContent=e.soundKind,this.labelSoundVolume.textContent=e.soundVolume,this.labelSoundPitch.textContent=e.soundPitch,this.labelSoundSrc.textContent=e.soundSrc,this.soundSrcInput.placeholder=e.soundSrcPlaceholder,this.labelReferenceGroup.textContent=e.referenceGroup,this.labelReference.textContent=e.reference,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSrcInput.placeholder=e.referenceSrcPlaceholder,this.labelReferenceKind.textContent=e.referenceKind,this.referenceKindSelect.querySelector("#reference-kind-photo").textContent=e.referencePhoto,this.referenceKindSelect.querySelector("#reference-kind-panorama").textContent=e.referencePanorama,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=e.referenceT,this.labelReferenceDrawing.textContent=e.referenceDrawing,this.labelReferenceOpacity.textContent=e.referenceOpacity,this.labelReferenceHeading.textContent=e.referenceHeading,this.labelReferencePitch.textContent=e.referencePitch,this.labelReferenceRoll.textContent=e.referenceRoll,this.labelReferenceFov.textContent=e.referenceFov,this.referenceUsePoseButton.textContent=e.referenceUsePose,this.addReferenceUrlButton.textContent=e.addReferenceUrl,this.labelAddReferenceFile.textContent=e.addReferenceFile,this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.textContent=e.addReferenceLandmark,this.deleteReferenceLandmarkButton.title=e.deleteReferenceLandmark,this.deleteReferenceLandmarkButton.setAttribute("aria-label",e.deleteReferenceLandmark),this.labelReferenceLandmarkLabel.textContent=e.referenceLandmarkLabel,this.referenceLandmarkLabelInput.placeholder=e.referenceLandmarkLabelPlaceholder,this.referenceAdoptPoseButton.textContent=e.referenceAdoptPose,this.referenceStreetSearchButton.textContent=e.referenceStreetSearch,this.labelTraceImport.textContent=e.traceImport,this.labelTrace.textContent=e.trace,this.labelTraceTitle.textContent=e.traceTitle,this.labelTraceSource.textContent=e.traceSource,this.deleteTraceButton.title=e.deleteTrace,this.deleteTraceButton.setAttribute("aria-label",e.deleteTrace),this.refreshTraceList(),this.referenceStreetAddButton.textContent=e.referenceStreetAdd;for(const[n,s]of this.soundKindOptions)s.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls()}onPointerDown(e){if(this.isRecording){this.onPointerMove(e);return}const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode();if(i==="picture"){this.ufoElement.playbackState!=="playing"&&this.beginReferenceDrag(t);return}if(i==="body"){if(this.ufoElement.playbackState==="playing")return;!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)&&this.beginCameraDrag(t);return}const n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const h=new cd(this.selectedMembers()),d=wt.hitTestHandle({bounds:h.bounds(),angle:0},t);if(d==="rotate"){if(r)return;this.dragState={kind:"group-rotate",group:h,startPointer:t},this.startDragListening();return}if(d){if(r)return;this.dragState={kind:"group-resize",group:h,handle:d},this.startDragListening();return}}else{const h=n.getInterpolatedShapeAt(s,this.currentSourceId),d=h?.kind==="polygon"?wt.hitTestVertex(h,t):void 0;if(h?.kind==="polygon"&&d!==void 0){if(r)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:h,vertexIndex:d},this.startDragListening();return}const u=h&&wt.hitTestHandle(h,t);if(h&&u){if(r)return;this.beginDrag(u==="rotate"?"rotate":"resize",this.currentSourceId,h,t,u);return}}const l=this.ufoElement.shapeAt(t.x,t.y,Gv);if(!l){const h=this.pickDecorAt(e);if(h!==void 0){r?this.selectDecor(h):this.beginCameraDrag(t,h);return}r||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(l.sourceId):this.selectedSourceIds.has(l.sourceId)||this.selectUnit(l.sourceId),r||!o)return;const c=[...this.selectedSourceIds].map(h=>({sourceId:h,original:h===l.sourceId?l.shape:n.getInterpolatedShapeAt(s,h)??l.shape}));this.dragState={kind:"move",sources:c,startPointer:t},this.startDragListening()}revealShapePanel(){const e=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-shape");e&&this.toggleGroup(e,!0);const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-shapes");t&&this.openSubgroup(t)}selectedMembers(){const e=this.ufoElement.sighting.timeline,t=this.ufoElement.currentTime;return[...this.selectedSourceIds].map(i=>({sourceId:i,shape:e.getInterpolatedShapeAt(t,i)})).filter(i=>!!i.shape)}selectUnit(e){const t=this.ufoElement.sighting.timeline.groupMembers(e)??[e];t.length===this.selectedSourceIds.size&&t.every(i=>this.selectedSourceIds.has(i))&&e===this.currentSourceId||(this.selectedSourceIds=new Set(t),this.currentSourceId=e,this.refreshSourceList(),this.onSelectionOrTimeChanged())}toggleUnitSelection(e){const t=this.ufoElement.sighting.timeline,i=t.groupMembers(e)??[e];if(i.every(s=>this.selectedSourceIds.has(s))){if(i.length>=this.selectedSourceIds.size)return;for(const s of i)this.selectedSourceIds.delete(s);if(!this.selectedSourceIds.has(this.currentSourceId)){const s=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,o)=>s.indexOf(r)-s.indexOf(o)).pop()}}else{for(const s of i)this.selectedSourceIds.add(s);this.currentSourceId=e}this.refreshSourceList(),this.onSelectionOrTimeChanged()}onContextMenu(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing")return;this.hideContextMenu(),this.hideDecorContextMenu();const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,s=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(n,this.currentSourceId):void 0,o=s?.kind==="polygon"&&wt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Gv);if(o){this.selectedSourceIds.has(o.sourceId)||this.selectUnit(o.sourceId),this.currentSourceId=o.sourceId,this.contextMenuPoint=t,this.showContextMenu(e.clientX,e.clientY);return}const l=this.pickDecorAt(e),c=l?this.ufoElement.sighting.decor.find(h=>h.id===l):void 0;c&&this.showDecorContextMenu(e.clientX,e.clientY,c)}pickDecorAt(e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(n,s)}showContextMenu(e,t){this.contextMenu.style.left=`${e}px`,this.contextMenu.style.top=`${t}px`,this.contextMenu.hidden=!1;const i=this.ufoElement.sighting.timeline.sourceIds,n=i.filter(f=>this.selectedSourceIds.has(f)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(f=>this.selectedSourceIds.has(f)),o=n.length>0&&i.slice(0,n.length).every(f=>this.selectedSourceIds.has(f));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||o,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:o?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const l=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!l,this.contextUngroupButton.title=l?"":this.messages.notGrouped,this.contextDeleteButton.disabled=this.deleteShapeButton.disabled,this.contextDeleteButton.title="";const c=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(this.ufoElement.currentTime,this.currentSourceId),h=this.selectedSourceIds.size===1&&c?.kind==="polygon";this.contextAddVertexButton.disabled=!h,this.contextAddVertexButton.title=h?"":this.messages.notAPolygon;const d=h&&this.contextMenuPoint?wt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=i1;this.contextDeleteVertexButton.disabled=!h||d===void 0||u,this.contextDeleteVertexButton.title=h?u?this.messages.tooFewVertices:"":this.messages.notAPolygon,document.addEventListener("click",this.handleOutsideContextMenuClick)}hideContextMenu(){this.contextMenu.hidden=!0,this.contextMenuPoint=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}handleOutsideContextMenuClick=e=>{e.composedPath().includes(this.contextMenu)||e.composedPath().includes(this.decorContextMenu)||(this.hideContextMenu(),this.hideDecorContextMenu())};showDecorContextMenu(e,t,i){this.contextMenuDecorId=i.id,this.decorContextMenu.style.left=`${e}px`,this.decorContextMenu.style.top=`${t}px`,this.decorContextMenu.hidden=!1,this.contextViewAccountButton.disabled=!i.sightingUrl,this.contextViewAccountButton.title=i.sightingUrl?"":this.messages.noObserverRecording,this.refreshContextMasksSubmenu(i),document.addEventListener("click",this.handleOutsideContextMenuClick)}hideDecorContextMenu(){this.decorContextMenu.hidden=!0,this.contextMenuDecorId=void 0,document.removeEventListener("click",this.handleOutsideContextMenuClick)}refreshContextMasksSubmenu(e){this.contextMasksSubmenu.innerHTML="";for(const t of this.ufoElement.sighting.timeline.sourceIds){const i=document.createElement("label"),n=document.createElement("input");n.type="checkbox",n.checked=e.occludesSourceIds?.includes(t)??!1,n.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,t,n.checked)),i.appendChild(n),i.appendChild(document.createTextNode(this.shapeLabel(t))),this.contextMasksSubmenu.appendChild(i)}}updateDecorOccludesShape(e,t,i){const n=this.ufoElement.sighting;n.decor=n.decor.map(s=>{if(s.id!==e)return s;const r=i?[...new Set([...s.occludesSourceIds??[],t])]:(s.occludesSourceIds??[]).filter(o=>o!==t);return{...s,occludesSourceIds:r.length>0?r:void 0}}),this.ufoElement.refresh()}viewObserverAccount(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.contextMenuDecorId);this.hideDecorContextMenu(),e?.sightingUrl&&this.importFromUrl(e.sightingUrl)}addVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=wt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),this.ufoElement.refresh()}deleteVertexAtContextMenu(){const e=this.contextMenuPoint;if(this.hideContextMenu(),!e)return;const t=this.ufoElement.currentTime,i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(t,this.currentSourceId);if(i?.kind!=="polygon")return;const n=wt.hitTestVertex(i,e);if(n===void 0)return;const s=wt.deleteVertex(i,n);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),this.ufoElement.refresh()}bringSelectedToFront(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)))e.bringToFront(t);this.hideContextMenu(),this.ufoElement.refresh()}sendSelectedToBack(){const e=this.ufoElement.sighting.timeline;for(const t of e.sourceIds.filter(i=>this.selectedSourceIds.has(i)).reverse())e.sendToBack(t);this.hideContextMenu(),this.ufoElement.refresh()}groupSelected(){this.selectedSourceIds.size<2||(this.ufoElement.sighting.timeline.group([...this.selectedSourceIds]),this.hideContextMenu(),this.ufoElement.refresh())}ungroupSelected(){this.ufoElement.sighting.timeline.ungroup(this.currentSourceId),this.selectedSourceIds=new Set([this.currentSourceId]),this.hideContextMenu(),this.ufoElement.refresh()}beginDrag(e,t,i,n,s){this.dragState={kind:e,sourceId:t,original:i,handle:s,startPointer:n},this.startDragListening()}ndcOf(e){const t=this.ufoElement.canvasElement.getBoundingClientRect();if(!(t.width===0||t.height===0))return{x:(e.clientX-t.left)/t.width*2-1,y:-((e.clientY-t.top)/t.height*2-1)}}skyDirectionOf(e){const t=this.ndcOf(e);if(!t)return;const i=this.sceneElement.directionAt(t.x,t.y);return{azimuthDeg:(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,i.y)))*180/Math.PI}}beginBodyDrag(e){const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!n||!i)return!1;i.show(n);const s=i.readingNow(),r=this.skyDirectionOf(e);return!s||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:s.azimuthDeg,bodyAltitudeDeg:s.altitudeDeg},this.setCanvasCursor("move"),this.startDragListening(),!0)}onBodyDragPointerMove(e){const t=this.dragState;if(t?.kind!=="body")return;const i=this.skyDirectionOf(e);if(!i)return;const n=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+n,t.bodyAltitudeDeg+i.altitudeDeg-t.pointerAltitudeDeg)}bodyCanvasBounds(){const e=this.bodyEditor?.currentBodyId,t=e===void 0?void 0:this.sceneElement.bodyScreenBox(e);if(!t)return;const i=this.ufoElement.canvasElement,n=Math.max(Vv,(t.maxX-t.minX)/2*i.width),s=Math.max(Vv,(t.maxY-t.minY)/2*i.height),r=((t.minX+t.maxX)/2+1)/2*i.width,o=(1-(t.minY+t.maxY)/2)/2*i.height;return{x:r-n/2,y:o-s/2,width:n,height:s}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginBodyHandleDrag(e){const t=this.bodyCanvasBounds(),i=this.bodyEditor?.readingNow();if(!t||!i)return!1;const n=wt.hitTestHandle({bounds:t,angle:0},e);if(!n)return!1;if(n==="rotate")this.dragState={kind:"body-rotate",startPointer:e,startAttitude:{...i.attitude}};else{const s={x:t.x+t.width/2,y:t.y+t.height/2};this.dragState={kind:"body-resize",handle:n,centre:s,startPointer:e,startSizeM:{...i.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,0)),this.startDragListening(),!0}onBodyHandleDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="body-rotate"){const u=(i.x-t.startPointer.x)*Zc,f=(t.startPointer.y-i.y)*Zc,p=t.startAttitude;this.bodyEditor?.turnTo(e.shiftKey?{headingDeg:p.headingDeg,pitchDeg:p.pitchDeg+f,rollDeg:p.rollDeg+u}:{headingDeg:p.headingDeg+u,pitchDeg:p.pitchDeg,rollDeg:p.rollDeg});return}if(t.kind!=="body-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:o}=t,l=(u,f)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(f))),c=o==="e"||o==="w",h=o==="n"||o==="s",d=c?l(i.x-n.x,s.x-n.x):h?l(i.y-n.y,s.y-n.y):l(Math.hypot(i.x-n.x,i.y-n.y),Math.hypot(s.x-n.x,s.y-n.y));this.bodyEditor?.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}onBodyWheel(e){if(this.canvasMode()!=="body"||this.ufoElement.playbackState==="playing")return;const t=this.ndcOf(e),i=this.bodyEditor,n=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!n||!i||(e.preventDefault(),i.show(n),i.scaleDistance(Math.exp(Math.sign(e.deltaY)*.1)))}beginCameraDrag(e,t){const i=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,moved:!1,startPointer:e,startHeadingDeg:i?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:i?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:i},i||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&eo(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&eo(i.kind)),t=e?`${e.id}:${e.observerSide}`:void 0;t!==this.lastInhabitedKey&&(this.lastInhabitedKey=t,this.indoorLookYawDeg=0,this.indoorLookPitchDeg=0,this.sceneElement.setIndoorLook(0,0))}startDragListening(){document.addEventListener("pointermove",this.handleDragPointerMove),document.addEventListener("pointerup",this.handleDragPointerUp)}onDragPointerMove(e){if(this.referenceDragState){this.onReferenceDragPointerMove(e);return}if(this.dragState?.kind==="body"){this.onBodyDragPointerMove(e);return}if(this.dragState?.kind==="body-resize"||this.dragState?.kind==="body-rotate"){this.onBodyHandleDragPointerMove(e);return}if(this.cameraDragState){this.onCameraDragPointerMove(e);return}if(!this.dragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.ufoElement.currentTime;if(this.dragState.kind==="move"){const{sources:n,startPointer:s}=this.dragState,r=t.x-s.x,o=t.y-s.y,l=n.map(({sourceId:c,original:h})=>({sourceId:c,shape:{...h,bounds:{...h.bounds,x:h.bounds.x+r,y:h.bounds.y+o}}}));this.commitShapes(i,l)}else if(this.dragState.kind==="group-resize"){const{group:n,handle:s}=this.dragState;this.commitShapes(i,n.resize(s,t))}else if(this.dragState.kind==="group-rotate"){const{group:n,startPointer:s}=this.dragState;this.commitShapes(i,n.rotate(t,s))}else if(this.dragState.kind==="vertex"){const{sourceId:n,original:s,vertexIndex:r}=this.dragState,o=wt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}else{const{kind:n,sourceId:s,original:r,handle:o}=this.dragState,l=n==="resize"?wt.resizeShape(r,o,t):wt.rotateShape(r,t);this.commitShapes(i,[{sourceId:s,shape:l}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:n,startPitchDeg:s,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<i4)return;this.cameraDragState.moved=!0}const o=n+(t.x-i.x)*Zc,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Zc));if(r){this.indoorLookYawDeg=o,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(o,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(o)),this.pitchInput.value=String(this.rounded(l)),this.updateObserver()}endDrag(){if(this.referenceDragState){this.endReferenceDrag();return}!this.dragState&&!this.cameraDragState||(this.cameraDragState&&!this.cameraDragState.insideDecor&&this.sceneElement.setCompassForced(!1),this.dragState=void 0,this.cameraDragState=void 0,this.setCanvasCursor(this.hoverCursor),document.removeEventListener("pointermove",this.handleDragPointerMove),document.removeEventListener("pointerup",this.handleDragPointerUp))}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(xr,i.width-pr);break;case"ArrowRight":i.width+=pr;break;case"ArrowUp":i.height=Math.max(xr,i.height-pr);break;case"ArrowDown":i.height+=pr;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=pr;break;case"ArrowRight":i.x+=pr;break;case"ArrowUp":i.y-=pr;break;case"ArrowDown":i.y+=pr;break}return i}moveOrResizeSelectedShapes(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.currentTime,i=this.selectedMembers();if(i.length!==0){if(e.preventDefault(),i.length===1){const{sourceId:n,shape:s}=i[0];this.commitShapes(t,[{sourceId:n,shape:{...s,bounds:this.nudgeBounds(s.bounds,e)}}])}else{const n=new cd(i),s=this.nudgeBounds(n.bounds(),e);this.commitShapes(t,n.scaleTo(s))}this.ufoElement.refresh()}}updateHoverCursor(e){this.isRecording||this.dragState||this.cameraDragState||(this.hoverCursor=this.hoverCursorAt(e),this.setCanvasCursor(this.hoverCursor))}hoverCursorAt(e){const t=this.canvasPointFromEvent(e);if(!t)return;const i=this.canvasMode(),n=this.ufoElement.sighting.timeline,s=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const l=r?this.bodyCanvasBounds():void 0,c=l&&wt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.ndcOf(e),d=h&&this.bodyEditor?this.sceneElement.pickPlacedBodyAt(h.x,h.y):void 0;return r&&d?"move":r?"pan":void 0}const o=i==="shape";if(r&&o)if(this.selectedSourceIds.size>1){const l=wt.hitTestHandle({bounds:new cd(this.selectedMembers()).bounds(),angle:0},t);if(l)return this.cursorForHandle(l,0)}else{const l=n.getInterpolatedShapeAt(s,this.currentSourceId);if(l?.kind==="polygon"&&wt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&wt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&o?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${wt.resizeAxisFor(e,t)}`}setCanvasCursor(e){const t=this.ufoElement.canvasElement;e?t.dataset.cursor=e:delete t.dataset.cursor}onPointerMove(e){if(!this.isRecording){this.updateHoverCursor(e);return}const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect(),n=e.clientX-i.left,s=e.clientY-i.top;this.recorder?.onPointerMove(n,s),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(Jv(this.buildPrototype({x:0,y:0,width:Za.width,height:Za.height}),n,s))}canvasPointFromEvent(e){const t=this.ufoElement.canvasElement,i=t.getBoundingClientRect();if(!(i.width===0||i.height===0))return{x:(e.clientX-i.left)/i.width*t.width,y:(e.clientY-i.top)/i.height*t.height}}}const h4={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},qv="rr0-sighting-editor",Kv="rr0-ufo-recorder";class d4 extends qt{}function u4(){$h(),customElements.get(qv)||customElements.define(qv,qt),customElements.get(Kv)||customElements.define(Kv,d4)}u4();export{aw as $,la as A,Bb as B,se as C,fM as D,Ze as E,pt as F,Nt as G,Rn as H,T4 as I,nn as J,p4 as K,Xu as L,Te as M,Gi as N,g4 as O,G1 as P,m4 as Q,Mt as R,Sl as S,jn as T,uh as U,D as V,x4 as W,Hl as X,A4 as Y,S4 as Z,ot as _,Ji as a,Eh as a0,tn as a1,_4 as a2,j1 as a3,Xm as a4,y4 as a5,qi as a6,Tm as a7,Xt as a8,E4 as a9,Ci as aA,K1 as aB,$p as aC,Yp as aD,dt as aE,Rr as aF,zl as aG,I4 as aa,U1 as ab,ia as ac,Jl as ad,vd as ae,qM as af,ut as ag,Ot as ah,Cl as ai,sf as aj,ki as ak,er as al,ew as am,jr as an,Pt as ao,b4 as ap,M4 as aq,H1 as ar,w4 as as,mn as at,rs as au,z1 as av,Bm as aw,q2 as ax,wh as ay,Of as az,oI as b,p0 as c,Li as d,D4 as e,Ih as f,sn as g,Qs as h,mt as i,Ms as j,nw as k,f4 as l,ye as m,me as n,ct as o,Yu as p,R4 as q,je as r,Un as s,v4 as t,rt as u,ys as v,nh as w,tr as x,Wo as y,ni as z};
|