@rr0/ufoathome 0.122.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-C1ugmbHe.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-XVgt3vom.js","./ModelThumbnails-B2MXsKrk.js","./ModelSource-C3dP1aBw.js","./ModelViewer-BltV6g37.js","./SightingFileEditor-C0NC8jbz.js","./sightingSchema-kkSSrggd.js","./BodyEditor-ChwDW_Ws.js","./BodyEditorMessages_en-C3VGB1gD.js","./LaunchEditor-BCbplrLt.js","./LaunchEditorMessages_en-j4RgQPZu.js","./InterviewElement-wiGHrsHB.js","./InterviewMessages_en-C-7vNgM2.js","./InterviewMedia-CvAxC62V.js","./interviewJson-78rX1Ar1.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./ContrailSystem-C1ugmbHe.js","./ContrailGrowth-CuAzwIoc.js","./trafficRuntime-XVgt3vom.js","./ModelThumbnails-B2MXsKrk.js","./ModelSource-C3dP1aBw.js","./ModelViewer-BltV6g37.js","./SightingFileEditor-C0NC8jbz.js","./sightingSchema-kkSSrggd.js","./BodyEditor-ChwDW_Ws.js","./BodyEditorMessages_en-C3VGB1gD.js","./LaunchEditor-BCbplrLt.js","./LaunchEditorMessages_en-j4RgQPZu.js","./InterviewEditorElement-CT26rBmp.js","./InterviewMessages_en-cs-wWpmz.js","./InterviewMedia-CvAxC62V.js","./interviewJson-CfwBPiuG.js"])))=>i.map(i=>d[i]);
2
2
  const Z2="modulepreload",j2=function(o,e){return new URL(o,e).href},vv={},_e=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 a=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");n=r(t.map(h=>{if(h=j2(h,i),h in vv)return;vv[h]=!0;const d=h.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(!!i)for(let g=a.length-1;g>=0;g--){const m=a[g];if(m.href===h&&(!d||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${u}`))return;const f=document.createElement("link");if(f.rel=d?"stylesheet":Z2,d||(f.as="script"),f.crossOrigin="",f.href=h,c&&f.setAttribute("nonce",c),document.head.appendChild(f),d)return new Promise((g,m)=>{f.addEventListener("load",g),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function s(r){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=r,window.dispatchEvent(a),!a.defaultPrevented)throw r}return n.then(r=>{for(const a of r||[])a.status==="rejected"&&s(a.reason);return e().catch(s)})};class Un{constructor(e){this.entries=e}static empty(){return new Un(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 Un(new Map);return{recording:Un.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("."),a=Un.holderOf(i,r);if(!a)continue;const l=r[r.length-1],c=a[l];c!==void 0&&(s.of!==void 0&&JSON.stringify(s.of)!==JSON.stringify(c)||(a[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 Un.isWrapper(e)?(i.set(t.join("."),{basis:e.basis??"stated",...e.rationale===void 0?{}:{rationale:e.rationale},of:e.value}),Un.stripValue(e.value,t,i)):Array.isArray(e)?e.map((n,s)=>Un.stripValue(n,[...t,String(s)],i)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,s])=>[n,Un.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}}class Ci{static SIGHTING_EVENT="sighting";static INTERPRETATION_EVENT="interpretation";static INTERVIEW_EVENT="interview";static isCase(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Array.isArray(e.events)&&!("timeline"in e)}static sightingUrls(e,t){return(e.events??[]).filter(i=>i.eventType===Ci.SIGHTING_EVENT&&!i.interpretationOf&&typeof i.url=="string"&&i.url!=="").map(i=>new URL(i.url,t).href)}static accountIds(e,t,i,n){const s=(e.events??[]).filter(r=>r.eventType===Ci.SIGHTING_EVENT&&r.id!==void 0&&typeof r.url=="string"&&i!==void 0&&new URL(r.url,t).href===i).map(r=>r.id);return n!==void 0&&s.push(n),s}static interpretationEvents(e,t){const i=[t].flat().filter(n=>!!n);return i.length===0?[]:(e.events??[]).filter(n=>n.eventType===Ci.INTERPRETATION_EVENT?n.sighting!==void 0&&i.includes(n.sighting):n.eventType!==Ci.SIGHTING_EVENT||n.interpretationOf===void 0?!1:[n.interpretationOf].flat().some(s=>i.includes(s))).map(n=>n)}static problems(e,t){const i=e.events??[],n=new Set,s=new Set;for(const a of i)a.id!==void 0&&(n.has(a.id)&&s.add(a.id),n.add(a.id));const r=[];for(const a of i){const l=a.eventType===Ci.SIGHTING_EVENT?a.interpretationOf:a.eventType===Ci.INTERVIEW_EVENT?a.interviewOf:void 0;if(l!==void 0)for(const c of[l].flat())!n.has(c)&&!t.includes(c)&&r.push({reading:a.url??a.id??"",reference:c})}return{duplicateIds:[...s],unresolved:r}}static async interpretationOf(e,t,i){if(e.bodies||e.reentries||e.launches)return Ci.withModelsFrom(Un.strip({title:e.title,bodies:e.bodies??[],smoke:e.smoke,reentries:e.reentries,launches:e.launches}).recording,t);if(!e.url)return{title:e.title,bodies:[]};const n=new URL(e.url,t).href,s=await i(n),r="timeline"in s&&s.interpretation?s.interpretation:s;return Ci.withModelsFrom(Un.strip({title:e.title??r.title,bodies:r.bodies??[],smoke:r.smoke,reentries:r.reentries,launches:r.launches}).recording,n)}static withModelsFrom(e,t){return{...e,bodies:e.bodies.map(i=>i.model?.url?{...i,model:{...i.model,url:new URL(i.model.url,t).href}}:i)}}}class Ja extends Error{constructor(e,t,i){super(`${e}: ${t}${i===void 0?"":` (HTTP ${i})`}`),this.kind=e,this.url=t,this.status=i,this.name="SightingFetchError"}}class ho{static async json(e){const t=new URL(e,location.href);if(location.protocol==="https:"&&t.protocol==="http:")throw new Ja("mixed-content",e);let i;try{i=await fetch(e)}catch{throw await this.diagnose(e,t)}if(!i.ok)throw new Ja("status",e,i.status);try{return await i.json()}catch{throw new Ja("malformed",e)}}static async diagnose(e,t){if(t.origin===location.origin)return new Ja("unreachable",e);try{return await fetch(e,{mode:"no-cors"}),new Ja("cors",e)}catch{return new Ja("unreachable",e)}}}class zn{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[zn.base(i)];if(n)return n}const t=new Set(this.preferences.map(i=>zn.base(i)));for(const[i,n]of Object.entries(e))if(n&&t.has(zn.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(a=>a===i)??Object.keys(s).find(a=>zn.base(a)===zn.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]}}function yh(o,e){for(const t of o){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class Is{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 Nn{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(e){const t=e.trim().toUpperCase(),i=Nn.ISO.exec(t);if(!i||t==="P"||t.endsWith("T"))return;const[,n,s,r,a,l]=i,c=d=>d===void 0?0:Number(d.replace(",",".")),h=c(n)*604800+c(s)*86400+c(r)*3600+c(a)*60+c(l);return Number.isFinite(h)?h:void 0}static parse(e){let t=e.trim();if(t==="")return;const i=t.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(t=t.slice(0,-1).trim());const s=t.split("/");if(s.length>2)return;const r=s.map(d=>Nn.seconds(d));if(r.some(d=>d===void 0))return;const[a,l]=r,c=Math.min(a,l??a),h=Math.max(a,l??a);return{doubt:n,minSeconds:c,maxSeconds:h,chosenSeconds:(c+h)/2}}static isExact(e){const t=Nn.parse(e);return t!==void 0&&t.doubt===""&&t.minSeconds===t.maxSeconds}static format(e){const t=Math.max(0,Math.round(e*10)/10),i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(e){const t=Math.round(e*10)/10;if(t<60)return`${t} s`;const i=Math.floor(t/3600),n=Math.floor(t%3600/60),s=Math.round(t%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class mt{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/mt.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 J2(o,e,t){if(!o||!e)return t<1?o:e;const i=((e.azimuthDeg-o.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((o.azimuthDeg+i*t)%360+360)%360,altitudeDeg:o.altitudeDeg+(e.altitudeDeg-o.altitudeDeg)*t}}function Q2(o,e="#39ff14"){return{kind:"oval",bounds:o,color:e,angle:0,transparency:0,haloScale:0,selected:!1}}function ex(o,e,t="#39ff14"){return{kind:"polygon",bounds:o,points:e,color:t,angle:0,transparency:0,haloScale:0,selected:!1}}function tx(o,e="#39ff14"){const{width:t,height:i}=o;return ex(o,[{x:0,y:0},{x:t,y:0},{x:t,y:i},{x:0,y:i}],e)}const ix={oval:Q2,polygon:tx};function yv(o,e){return{...ix[e.presetId](o,e.color),transparency:e.transparency,haloScale:e.haloScale,blur:e.blur,brightness:e.brightness}}function nx(o,e,t){const{bounds:i}=o;return e>=i.x&&e<=i.x+i.width&&t>=i.y&&t<=i.y+i.height}function MM(o,e,t){const i=o.bounds.width,n=o.bounds.height;return{...o,bounds:{x:e-i/2,y:t-n/2,width:i,height:n}}}function Jn(o,e,t){return o+(e-o)*t}function bv(o){const e=/^#([0-9a-f]{6})$/i.exec(o);if(!e)return;const t=parseInt(e[1],16);return[t>>16&255,t>>8&255,t&255]}function sx(o){return`#${o.map(e=>Math.round(e).toString(16).padStart(2,"0")).join("")}`}function rx(o,e,t){const i=bv(o),n=bv(e);return!i||!n?t<1?o:e:sx([Jn(i[0],n[0],t),Jn(i[1],n[1],t),Jn(i[2],n[2],t)])}function ax(o,e,t){const i={x:Jn(o.bounds.x,e.bounds.x,t),y:Jn(o.bounds.y,e.bounds.y,t),width:Jn(o.bounds.width,e.bounds.width,t),height:Jn(o.bounds.height,e.bounds.height,t)},n=Jn(o.angle,e.angle,t),s=Jn(o.transparency,e.transparency,t),r=Jn(o.haloScale,e.haloScale,t),a=Jn(o.blur??0,e.blur??0,t),l=Jn(o.brightness??0,e.brightness??0,t),c=rx(o.color,e.color,t),h=mt.lerpAngular(o.angular,e.angular,t),d=J2(o.aim,e.aim,t);return o.kind==="polygon"&&e.kind==="polygon"&&o.points.length===e.points.length?{...o,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:l,color:c,angular:h,aim:d,points:o.points.map((u,p)=>({x:Jn(u.x,e.points[p].x,t),y:Jn(u.y,e.points[p].y,t)}))}:{...t<1?o:e,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:l,color:c,angular:h,aim:d}}class eo{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,a)=>{const l=`timeline.keyframes.${s}.shapes.${a}.shape`,c=eo.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??eo.firstAppearance(s,i,n),a={...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 a.aim,s.angular||delete a.angular);const l=s.kind??r.kind??"oval",c={...a,...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:`"${eo.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:{...eo.NEUTRAL_BOUNDS},color:eo.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:mt.CANVAS_WIDTH_PX/2,y:mt.CANVAS_HEIGHT_PX/2,width:1,height:1}}class xp{keyframes=[];order=[];groups=[];span=0;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?ax(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 a=this.getInterpolatedShapeAt(e,s[r]);if(a&&nx(a,t,i))return{sourceId:s[r],shape:a}}}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(){const e=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(e,this.span)}get hasSpan(){return this.span>0}setSpan(e){this.span=Math.max(0,e)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groups,span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groups}}static fromJSON(e,t){const i=new xp;for(const n of eo.complete(e.keyframes??[],t))i.addKeyframe(n.t,n.shapes);if(e.span!==void 0&&e.span>0&&(i.span=e.span),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 ox(o,e,t){return Math.max(e,Math.min(t,o))}function lx(o,e,t){const i=((e-o)%360+540)%360-180;return((o+i*t)%360+360)%360}function Jo(o,e,t){return o+(e-o)*t}function cx(o,e,t){return{lat:o.lat===void 0||e.lat===void 0?void 0:Jo(o.lat,e.lat,t),lng:o.lng===void 0||e.lng===void 0?void 0:Jo(o.lng,e.lng,t),elevationM:Jo(o.elevationM,e.elevationM,t),headingDeg:o.headingDeg===void 0||e.headingDeg===void 0?void 0:lx(o.headingDeg,e.headingDeg,t),pitchDeg:Jo(o.pitchDeg,e.pitchDeg,t),rollDeg:Jo(o.rollDeg??0,e.rollDeg??0,t),fovDeg:Jo(o.fovDeg,e.fovDeg,t),fNumber:o.fNumber,focusDistanceM:o.focusDistanceM,filter:o.filter}}class ko{static at(e,t,i,n,s){const r=e[i],l=e[i+1]-r;if(l<=0)return t[i];const c=ko.tangent(e,t,i,s),h=ko.tangent(e,t,i+1,s),d=(n-r)/l,u=d*d,p=u*d;return(2*p-3*u+1)*t[i]+(p-2*u+d)*l*c+(-2*p+3*u)*t[i+1]+(p-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,ko.BRAKE_S/t):.5;if(i&&n){const a=1/(1-s);return e<=s?a*e*e/(2*s):e>=1-s?1-a*(1-e)*(1-e)/(2*s):a*(e-s/2)}const r=a=>{const l=1/(1-s/2);if(a<=1-s)return l*a;const c=a-(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=p=>(t[p+1]-t[p])/(e[p+1]-e[p]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),l=r(i);if(a*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/a+u/l)}}class bh{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=cx(i.pose,n.pose,ox((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),a=e-n,l=r.map(M=>M.t),c=(M,y)=>{const x=r.map(S=>M(S.pose));if(!x.some(S=>S===void 0))return ko.at(l,x,a,t,y)},h=r.map(M=>M.pose.headingDeg);let d;if(h.every(M=>M!==void 0)){const M=[h[0]];for(let y=1;y<h.length;y++)M.push(M[y-1]+((h[y]-h[y-1])%360+540)%360-180);d=(ko.at(l,M,a,t,!0)%360+360)%360}const u=this.keyframes[e],p=this.keyframes[e+1],f=(M,y)=>M.lat===y.lat&&M.lng===y.lng&&M.elevationM===y.elevationM,g=!f(u.pose,p.pose),m=g&&e>0&&f(this.keyframes[e-1].pose,u.pose),v=g&&e+2<this.keyframes.length&&f(p.pose,this.keyframes[e+2].pose);let b;if(m||v){const M=ko.paced((t-u.t)/(p.t-u.t),(p.t-u.t)/1e3,m,v),y=(x,S)=>x===void 0||S===void 0?void 0:x+(S-x)*M;b={lat:y(u.pose.lat,p.pose.lat),lng:y(u.pose.lng,p.pose.lng),elevationM:y(u.pose.elevationM,p.pose.elevationM)}}return{...i,lat:b?b.lat:c(M=>M.lat,!1)??i.lat,lng:b?b.lng:c(M=>M.lng,!1)??i.lng,elevationM:b?b.elevationM:c(M=>M.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:c(M=>M.pitchDeg,!0)??i.pitchDeg,rollDeg:c(M=>M.rollDeg??0,!0)??i.rollDeg,fovDeg:c(M=>M.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 bh;for(const i of e.keyframes)t.addKeyframe(i.t,i.pose);return t}}class fa{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(fa.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?fa.follow(this.followed[t],i.intensity,n.intensity,(n.t-i.t)/1e3,(e-i.t)/1e3):fa.follow(this.followed[t],i.intensity,i.intensity,1,(e-i.t)/1e3);return{type:fa.typeBetween(i,n,e,s),intensity:s,character:fa.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=fa.MAX_CHANGE_PER_S,a=n>0?(i-t)/n:0,l=d=>t+a*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 M=h<n?a:0;if(Math.abs(M)<=r){const x=h<n?Math.min(s,n):s;c=l(x),h=x;continue}const y=Math.min(s,n);c+=Math.sign(M)*r*(y-h),h=y;continue}const p=Math.sign(u),f=h<n?a:0,g=r-p*f,m=g>0?h+Math.abs(u)/g:1/0,v=h<n?n:1/0,b=Math.min(s,m,v);c+=p*r*(b-h),h=b,b===m&&(c=l(h))}return Math.min(1,Math.max(0,c))}}const ag=1e3,gu=.65,wM=.05,Sp={cloudCover:0,cloudDarkness:0,precipitationType:"none",precipitationIntensity:0,windDirectionDeg:0,windSpeed:0,storm:!1};function Ca(o){if(o.cloudLayers!==void 0)return o.cloudLayers;const e=[],t=o.lowerCloudCover??o.cloudCover;return t>0&&e.push({id:"lower",type:"cumulus",baseM:o.cloudBaseM??ag,thicknessM:650,coverage:t,sizeM:1400,density:1,darkness:o.cloudDarkness}),(o.highCloudCover??0)>0&&e.push({id:"cirrus",type:"cirrus",baseM:8e3,thicknessM:400,coverage:o.highCloudCover,sizeM:2200,density:.35,darkness:o.cloudDarkness,iceCrystalAlignment:o.iceCrystalAlignment}),e}function hi(o,e,t){return o+(e-o)*t}function og(o,e,t){const i=((e-o)%360+540)%360-180;return((o+i*t)%360+360)%360}function hx(o,e,t){return Math.max(e,Math.min(t,o))}function dx(o=[],e=[],t){if(!(!o.length&&!e.length))return[...new Set([...o.map(i=>i.id),...e.map(i=>i.id)])].map(i=>{const n=o.find(l=>l.id===i),s=e.find(l=>l.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:hi(r.eastM,a.eastM,t),northM:hi(r.northM,a.northM,t),baseM:hi(r.baseM,a.baseM,t),thicknessM:hi(r.thicknessM,a.thicknessM,t),widthM:hi(r.widthM,a.widthM,t),depthM:hi(r.depthM,a.depthM,t),rotationDeg:og(r.rotationDeg,a.rotationDeg,t),density:hi(r.density,a.density,t),darkness:hi(r.darkness??0,a.darkness??0,t)}})}function ux(o,e,t){if(o.cloudLayers===void 0&&e.cloudLayers===void 0)return;const i=Ca(o),n=Ca(e);return t>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(d=>d.id===r),l=n.find(d=>d.id===r),c=a??{...l,coverage:0},h=l??{...a,coverage:0};return{...c,instances:dx(a?.instances,l?.instances,t),baseM:hi(c.baseM,h.baseM,t),thicknessM:hi(c.thicknessM,h.thicknessM,t),coverage:hi(c.coverage,h.coverage,t),sizeM:hi(c.sizeM,h.sizeM,t),density:hi(c.density,h.density,t),darkness:hi(c.darkness??o.cloudDarkness,h.darkness??e.cloudDarkness,t),iceCrystalAlignment:c.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:hi(c.iceCrystalAlignment,h.iceCrystalAlignment,t),windSpeed:c.windSpeed===void 0&&h.windSpeed===void 0?void 0:hi(c.windSpeed??o.windSpeed,h.windSpeed??e.windSpeed,t),windDirectionDeg:c.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:og(c.windDirectionDeg??o.windDirectionDeg,h.windDirectionDeg??e.windDirectionDeg,t)}})}function px(o,e,t){return{cloudLayers:ux(o,e,t),cloudCover:hi(o.cloudCover,e.cloudCover,t),cloudDarkness:hi(o.cloudDarkness,e.cloudDarkness,t),highCloudCover:o.highCloudCover===void 0||e.highCloudCover===void 0?void 0:hi(o.highCloudCover,e.highCloudCover,t),iceCrystalAlignment:o.iceCrystalAlignment===void 0||e.iceCrystalAlignment===void 0?void 0:hi(o.iceCrystalAlignment,e.iceCrystalAlignment,t),rareIceCrystals:o.rareIceCrystals===void 0||e.rareIceCrystals===void 0?void 0:hi(o.rareIceCrystals,e.rareIceCrystals,t),lowerCloudCover:o.lowerCloudCover===void 0||e.lowerCloudCover===void 0?void 0:hi(o.lowerCloudCover,e.lowerCloudCover,t),cloudBaseM:o.cloudBaseM===void 0||e.cloudBaseM===void 0?void 0:hi(o.cloudBaseM,e.cloudBaseM,t),relativeHumidity:o.relativeHumidity===void 0||e.relativeHumidity===void 0?void 0:hi(o.relativeHumidity,e.relativeHumidity,t),precipitationType:t<1?o.precipitationType:e.precipitationType,precipitationIntensity:hi(o.precipitationIntensity,e.precipitationIntensity,t),windDirectionDeg:og(o.windDirectionDeg,e.windDirectionDeg,t),windSpeed:hi(o.windSpeed,e.windSpeed,t),storm:t<1?o.storm:e.storm}}class Mh{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?px(i.weather,n.weather,hx((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 fa(this.keyframes)).at(e);if(!i)return t;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...t,precipitationType:n,precipitationIntensity:r,precipitationAmount:a}}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 Mh;for(const i of e.keyframes)t.addKeyframe(i.t,{...Sp,...i.weather});return t}}class wh{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 wh;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 fx=["none","hum","whistle","rumble","crackle"],mx=100,gx={kind:"none",volume:0,pitchHz:mx};class kl{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return kl.BODIES.map(e=>({id:e.id,category:"dslr",name:e.name,projection:"rectilinear",frame:{widthMm:e.widthMm,heightMm:e.heightMm,focalLengthMm:kl.DEFAULT_FOCAL_MM,focalRangeMm:kl.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:e.year},apertureBlades:7,detailUm:e.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(kl.BODIES.map(e=>[e.id,e.name]))}}class Ls{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*Ls.DEFAULT_EYEPIECE_MM*Math.tan(Ls.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const e=Ls.BINOCULARS.map(n=>({id:n.id,category:"binoculars",name:n.name,projection:"rectilinear",visualAid:{apertureMm:n.apertureMm,magnification:n.magnification,trueFieldDeg:n.trueFieldDeg},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}})),t=Ls.FIELD_STOP_MM,i=Ls.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:t*16/9,heightMm:t,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*Ls.RANGE.min,maxMm:n.focalLengthMm*Ls.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:Ls.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...e,...i]}static names(){return Object.fromEntries(Ls.instruments().map(e=>[e.id,e.name]))}}const Jc=[{id:"eye",category:"eye",name:"Naked eye",flare:0,projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",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:"roamer-1-120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",category:"camera",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",category:"camera",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",category:"camera",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",category:"phone",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",category:"phone",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}},...kl.instruments(),...Ls.instruments()];class Ut{static get default(){return Jc[0]}static byId(e){return Jc.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:e.visualAid?.trueFieldDeg??Ut.UNAIDED_FIELD_DEG}static aspectOf(e){const t=e.frame;return t?t.widthMm/t.heightMm:Ut.UNAIDED_ASPECT}static frameWidthPx(e,t){return Math.round(t*Ut.aspectOf(e))}static CATEGORIES=["eye","camera","dslr","phone","binoculars","telescope"];static unavailability(e,t){const i=e.years;if(!(t===void 0||!i)){if(t<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&t>i.to)return{kind:"after",to:i.to}}}static availableAt(e){return e===void 0?Jc:Jc.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??Ut.LENS_FLARE_ARTIFACTS}static starPointsOf(e){const t=e.apertureBlades;return t===void 0||t<3?0:t%2===0?t:t*2}}class Go extends Error{}class Ep{constructor(e){this.name=e}validate(e){return!0}}class xM extends Ep{min;max;constructor(e,t,i){super(e),this.min=t,this.max=i}validate(e){if(typeof e!="number")throw new Go(`${this.name} value must be a number, but was ${e}`);if(e<this.min||e>this.max)throw new Go(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${e}`);return super.validate(e)}}class Xi{name;min;max;duration;subUnit;validator;constructor(e,t,i,n,s=new xM(e,t,i)){this.name=e,this.min=t,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(e){return this.validator.validate(e)}[Symbol.iterator](){let e=this.min;return{next:()=>{const t={done:e>this.max,value:e};return e++,t}}}}class SM{millisecond;second;minute;hour;day;month;year}class vx extends SM{}class EM extends vx{millisecond=new Xi("millisecond",0,999,void 0);second=new Xi("second",0,59,this.millisecond);minute=new Xi("minute",0,59,this.second);hour=new Xi("hour",0,23,this.minute);day=new Xi("day",1,31,this.hour);month=new Xi("month",1,12,this.day);year=new Xi("year",0,9999,this.month)}const et=new EM;class yx extends xM{constructor(e=1,t=12){super("month",e,t)}}class vr{static instance=new vr;render(e){return e.value.toString()}}class An{unit;#e;constructor(e,t){this.unit=t,this.value=typeof e=="number"?e:e.value}get value(){return this.#e}set value(e){this.unit.validate(e),this.#e=e}get duration(){return this.value*this.unit.duration}#t(e){if(this.constructor.name!==e.constructor.name)throw new Ep(`${this.unit.name} "${this.toString()}" cannot be compared with ${e.unit?.name} "${e.toString()}"`)}compare(e){return this.#t(e),this.value-e.value}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}previous(e=this.unit){const t=this.value-1;return new this.constructor(t,e)}next(e=this.unit){const t=this.value+1;return new this.constructor(t,e)}toString(e=vr.instance){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class ri{static#e=new Map;static register(e,t){ri.#e.set(e,t)}static get(e){const t=ri.#e.get(e);if(!t)throw new Go(`No default parser registered for ${e.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return t()}}class vu extends An{constructor(e=new Date().getFullYear(),t=et.year){super(e,t)}static fromString(e,t=ri.get(vu)){return new vu(t.parse(e))}}class Ir extends vr{static default=new Ir("0",2);constructor(e,t){super(),this.char=e,this.size=t}render(e){return super.render(e).padStart(this.size,this.char)}}class yu extends An{constructor(e=new Date().getMonth()+1,t=et.month){super(e,t)}static fromString(e,t=ri.get(yu)){return new yu(t.parse(e))}toString(e=Ir.default){return super.toString(e)}}class bu extends An{constructor(e=new Date().getDate(),t=et.day){super(e,t)}static fromString(e,t=ri.get(bu)){const i=t.parse(e);return new bu(i)}toString(e=Ir.default){return super.toString(e)}}class Mu extends An{constructor(e=new Date().getHours(),t=et.hour){super(e,t)}static fromString(e,t=ri.get(Mu)){return new Mu(t.parse(e))}toString(e=Ir.default){return super.toString(e)}}class wu extends An{constructor(e=new Date().getMinutes(),t=et.minute){super(e,t)}static fromString(e,t=ri.get(wu)){return new wu(t.parse(e))}toString(e=Ir.default){return super.toString(e)}}class xu extends An{constructor(e=new Date().getSeconds(),t=et.second){super(e,t)}static fromString(e,t=ri.get(xu)){return new xu(t.parse(e),et.second)}toString(e=Ir.default){return super.toString(e)}}class qo extends An{static renderer=new Ir("0",3);constructor(e,t=et.millisecond){super(e,t)}static parseFraction(e){return parseInt(e.padEnd(3,"0").substring(0,3),10)}toString(e=qo.renderer){return super.toString(e)}}class bx{render(e){return e.toString()}}class Mx extends bx{render(e){const t=e.value,i=Math.abs(t),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=t<0?"-":"+",a=n.toString().padStart(2,"0"),l=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+l}}}class oc{value;name="timeshift";renderer;constructor(e=0){this.value=e}static fromString(e,t=ri.get(oc),i=void 0){const n=t.parse(e,i);return new oc(n)}toString(e=new Mx){return e.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class xn{static timeshift(e,t){return e+(xn.isDaylight(t)?60:0)}static isDaylight(e){const{year:t,month:i,day:n}=e,s=e.hour??12;if(![t,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=xn.rule(t);if(!r)return!1;const a=xn.rank(i,n,s);return a>=xn.rank(r.start.month,r.start.day,2)&&a<xn.rank(r.end.month,r.end.day,2)}static rule(e){if(e<1967)return;const t={month:10,day:xn.sunday(e,10,-1)};return e>=2007?{start:{month:3,day:xn.sunday(e,3,2)},end:{month:11,day:xn.sunday(e,11,1)}}:e>=1987?{start:{month:4,day:xn.sunday(e,4,1)},end:t}:e===1975?{start:{month:2,day:23},end:t}:e===1974?{start:{month:1,day:6},end:t}:{start:{month:4,day:xn.sunday(e,4,-1)},end:t}}static sunday(e,t,i){const n=new Date(Date.UTC(2e3,t-1,1));n.setUTCFullYear(e);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,xn.isLeap(e)?29:28,31,30,31,30,31,31,30,31,30,31][t-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(e){return e%4===0&&(e%100!==0||e%400===0)}static rank(e,t,i){return(e*100+t)*100+i}}const wx={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},xx={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},Sx={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},Ex={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},Ax={name:"PT",timeshift:o=>xn.timeshift(-480,o),title:"Pacific Time (US)"},Tx={name:"MT",timeshift:o=>xn.timeshift(-420,o),title:"Mountain Time (US)"},_x={name:"CT",timeshift:o=>xn.timeshift(-360,o),title:"Central Time (US)"},Ix={name:"ET",timeshift:o=>xn.timeshift(-300,o),title:"Eastern Time (US)"},Dx={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},Rx={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},Cx={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},kx={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},Lx={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},Ox={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},Px={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},Nx={name:"Z",timeshift:"Z",title:"UTC"},Fx={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},Ux={name:"BST",timeshift:"+01",title:"British Summer Time"},Bx={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},zx={name:"CET",timeshift:"+01",title:"Central European Time"},Hx={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},Gx={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},Vx={name:"BJT",timeshift:"+08",title:"Beijing Time"},Wx={name:"CST",timeshift:"-06",title:"Central Standard Time"},Xx={name:"JST",timeshift:"+09",title:"Japan Standard Time"},$x={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},Yx={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},qx={name:"LST",timeshift:"?",title:"Local Sideral Time"},Mv=[Ox,$x,Lx,Vx,Ux,Wx,Rx,zx,Bx,_x,Dx,kx,Cx,Ix,Fx,Gx,Xx,qx,Sx,Hx,Ex,Tx,Yx,xx,wx,Ax,Px,Nx];class Ap{static instance=new Ap;renderComponent(e,t){return e[t].toString()}renderSecond(e){return this.renderComponent(e,"second")+(e.millisecond?"."+e.millisecond.toString():"")}render(e){const t=[];e.year&&t.push(this.renderComponent(e,"year")),e.month&&t.push(this.renderComponent(e,"month")),e.day&&t.push(this.renderComponent(e,"day"));const i=[];e.hour&&i.push(this.renderComponent(e,"hour")),e.minute&&i.push(this.renderComponent(e,"minute")),e.second&&i.push(this.renderSecond(e));const n=t.join("-"),s=e.timeshift?e.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class Qa extends Go{constructor(e="method is abstract"){super(e)}}class lg{units;constructor(e){this.units=e}newYear(e){throw new Qa}newMonth(e){throw new Qa}newDay(e){throw new Qa}newHour(e){throw new Qa}newMinute(e){throw new Qa}newSecond(e){throw new Qa}}class Kx extends SM{millisecond=new Xi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new Xi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new Xi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new Xi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new Xi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new Xi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new Xi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const cg=new Kx;class hg{static instance=new hg;render(e){const t=uo.toSpec(e);let i="P";const n=t.years;n&&(i+=n.toString()+"Y");const s=t.months;s&&(i+=s.toString(vr.instance)+"MM");const r=t.days;r&&(i+=r.toString(vr.instance)+"D");const a=t.hours;a&&(i+=a.toString(vr.instance)+"H");const l=t.minutes;l&&(i+=l.toString(vr.instance)+"M");const c=t.seconds;return c&&(i+=c.toString(vr.instance)+"S"),i}}class uo extends An{constructor(e={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof e=="number"?e:+(e.years?e.years*et.year.duration:0)+(e.months?e.months*et.month.duration:0)+(e.days?e.days*et.day.duration:0)+(e.hours?e.hours*et.hour.duration:0)+(e.minutes?e.minutes*et.minute.duration:0)+(e.seconds?e.seconds*et.second.duration:0)},new Xi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(e,t=jx){let i=typeof e=="number"?e:e.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/et.year.duration,a=Math.floor(r);a>0&&(s.years=t.newYear(n*a),i-=a*et.year.duration);const l=i/et.month.duration,c=Math.floor(l);c>0&&(s.months=t.newMonth(n*c),i-=c*et.month.duration);const h=i/et.day.duration,d=Math.floor(h);d>0&&(s.days=t.newDay(n*d),i-=d*et.day.duration);const u=i/et.hour.duration,p=Math.floor(u);p>0&&(s.hours=t.newHour(n*p),i-=p*et.hour.duration);const f=i/et.minute.duration,g=Math.floor(f);g>0&&(s.minutes=t.newMinute(n*g),i-=g*et.minute.duration);const m=i/et.second.duration,v=Math.floor(n*m);return v>0&&(s.seconds=t.newSecond(v)),s}static fromString(e,t=ri.get(uo)){return new uo(t.parse(e))}static between(e,t){const i=t.getTime(),n=e.getTime();return new uo(i-n)}toSpec(){return uo.toSpec(this)}toString(e=hg.instance){return e.render(this)}}class AM extends lg{constructor(e){super(e)}newYear(e){return new vu(e,this.units.year)}newMonth(e){return new yu(e,this.units.month)}newDay(e){return new bu(e,this.units.day)}newHour(e){return new Mu(e,this.units.hour)}newMinute(e){return new wu(e,this.units.minute)}newSecond(e){return new xu(e,this.units.second)}newMillisecond(e){return new qo(e,this.units.millisecond)}newTimeshift(e){return new oc(typeof e=="number"?e:e.value)}}const Zx=new AM(et),jx=new AM(cg);class Bs{#e;#t;#i;#n;#s;#r;#a;#o;constructor(e={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:Bs.timeshiftOf(new Date)}){this.year=e.year,this.month=e.month,this.day=e.day,this.hour=e.hour,this.minute=e.minute,this.second=e.second,this.millisecond=e.millisecond,this.timeshift=e.timeshift}get year(){return this.#e}set year(e){const t=typeof e=="number";this.#e&&t?this.#e.value=e:this.#e=t?this.factory.newYear(e):!e||e.start||e instanceof An?e:this.factory.newYear(e)}get month(){return this.#t}set month(e){const t=typeof e=="number";this.#t&&t?this.#t.value=e:this.#t=t?this.factory.newMonth(e):!e||e.start||e instanceof An?e:this.factory.newMonth(e)}get day(){return this.#i}set day(e){const t=typeof e=="number";this.#i&&t?this.#i.value=e:this.#i=t?this.factory.newDay(e):!e||e.start||e instanceof An?e:this.factory.newDay(e)}get hour(){return this.#n}set hour(e){const t=typeof e=="number";this.#n&&t?this.#n.value=e:this.#n=t?this.factory.newHour(e):!e||e.start||e instanceof An?e:this.factory.newHour(e)}get minute(){return this.#s}set minute(e){const t=typeof e=="number";this.#s&&t?this.#s.value=e:this.#s=t?this.factory.newMinute(e):!e||e.start||e instanceof An?e:this.factory.newMinute(e)}get second(){return this.#r}set second(e){const t=typeof e=="number";this.#r&&t?this.#r.value=e:this.#r=t?this.factory.newSecond(e):!e||e.start||e instanceof An?e:this.factory.newSecond(e)}get millisecond(){return this.#a}set millisecond(e){const t=typeof e=="number";this.#a&&t?this.#a.value=e:this.#a=t||e&&!(e instanceof An)?this.factory.newMillisecond(e):e}get timeshift(){return this.#o}set timeshift(e){const t=typeof e=="number";this.#o&&t?this.#o.value=e:this.#o=t||e&&!(e instanceof oc)?this.factory.newTimeshift(e):e}get factory(){return Zx}static fromString(e,t=ri.get(Bs)){const{year:i,month:n,day:s,hour:r,minute:a,second:l,millisecond:c,timeshift:h}=t.parse(e);return new Bs({year:i,month:n,day:s,hour:r,minute:a,second:l,millisecond:c,timeshift:h})}static timeshiftOf(e){return-e.getTimezoneOffset()||0}static fromDate(e){return new Bs({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Bs.timeshiftOf(e)})}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return Bs.fromString(i)}#l(e){if(this.constructor.name!==e.constructor.name)throw new Ep(`Date "${this.toString()}" cannot be compared with "${e.toString()}"`)}compare(e){return this.#l(e),this.getTime()-e.getTime()}delta(e){const t=this.compare(e);return new uo(t)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(e){return this.compare(e)===0}isBefore(e){return this.compare(e)<0}isAfter(e){return this.compare(e)>0}clone(){return new Bs(this.toSpec())}previous(){let e=this.clone();try{e.second=this.second.previous()}catch{try{e.minute=this.minute.previous()}catch{try{e.hour=this.hour.previous()}catch{try{e.day=this.day.previous()}catch{try{e.month=this.month.previous()}catch{e.year=this.year.previous()}}}}}return e}next(){let e=this.clone();try{e.second=this.second.next()}catch{try{e.minute=this.minute.next()}catch{try{e.hour=this.hour.next()}catch{try{e.day=this.day.next()}catch{try{e.month=this.month.next()}catch{e.year=this.year.next()}}}}}return e}toString(e=Ap.instance){return e.render(this)}toSpec(){const e={},t=this.year?.toSpec();t&&(e.year=t);const i=this.month?.toSpec();i&&(e.month=i);const n=this.day?.toSpec();n&&(e.day=n);const s=this.hour?.toSpec();s&&(e.hour=s);const r=this.minute?.toSpec();r&&(e.minute=r);const a=this.second?.toSpec();a&&(e.second=a);const l=this.millisecond?.toSpec();l&&(e.millisecond=l);const c=this.timeshift?.toSpec();return c&&(e.timeshift=c),e}toJSON(){return this.toSpec()}}class Fh extends vr{static instance=new Fh(Ir.default);constructor(e){super(),this.valueRenderer=e}render(e){return(this.valueRenderer?this.valueRenderer.render(e):super.render(e))+this.qualifier(e)}qualifier(e){return e.uncertain?e.approximate?"%":"?":e.approximate?"~":""}}class Ko extends An{#e;#t;constructor(e,t){super(e,t),this.#e=e.uncertain||!1,this.#t=e.approximate||!1}get uncertain(){return this.#e}set uncertain(e){return this.#e=e}get approximate(){return this.#t}set approximate(e){return this.#t=e}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(e){return this.isCertainAndPrecise()&&super.isEqual(e)}isBefore(e){return this.isCertainAndPrecise()&&super.isBefore(e)}isAfter(e){return this.isCertainAndPrecise()&&super.isAfter(e)}toString(e=Fh.instance){return super.toString(e)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class TM extends EM{year=new Xi("year",-9999,9999,this.month);yearExtended=new Xi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Qd=new TM;class po extends Ko{constructor(e,t=Qd.year){super(e,t)}static fromString(e,t=Qd.year,i=ri.get(po)){const n=i.parse(e),s=n.value.start;if(e.startsWith("Y")&&(t=Qd.yearExtended),s!==void 0){const r=new po(Object.assign({...n},{value:Math.max(s,t.min)})),a=new po(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new po(n,t)}}class _M extends Ep{monthValidator=new yx;validate(e){switch(e){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(e)}}}class fo extends Ko{constructor(e,t=new Xi(et.month.name,1,24,et.day,new _M)){super(e,t)}static fromString(e,t=ri.get(fo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=et.month;const r=new fo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new fo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new fo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class mo extends Ko{constructor(e,t=et.day){super(e,t)}static fromString(e,t=ri.get(mo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=et.day;const r=new mo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new mo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new mo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class go extends Ko{constructor(e,t=et.hour){super(e,t)}static fromString(e,t=ri.get(go)){const i=t.parse(e),n=i.value.start;if(n!==void 0){let s=et.hour;const r=new go(Object.assign({...i},{value:Math.max(n,s.min)})),a=new go(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new go(i)}}class vo extends Ko{constructor(e,t=et.minute){super(e,t)}static fromString(e,t=ri.get(vo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.minute,r=new vo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new vo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new vo(i)}toString(e=Fh.instance){return super.toString(e)}}class yo extends Ko{constructor(e,t=et.second){super(e,t)}static fromString(e,t=ri.get(yo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.second,r=new yo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new yo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new yo(i)}}class lc extends oc{static fromString(e,t=ri.get(lc),i=void 0){return new lc(t.parse(e,i))}}class IM extends lg{constructor(e){super(e)}newYear(e){return new po(e,this.units.year)}newMonth(e){return new fo(e,this.units.month)}newDay(e){return new mo(e,this.units.day)}newHour(e){return new go(e,this.units.hour)}newMinute(e){return new vo(e,this.units.minute)}newSecond(e){return new yo(e,this.units.second)}newMillisecond(e){return new qo(e,this.units.millisecond)}newTimeshift(e){return new lc(typeof e=="number"?e:e.value)}}const Jx=new IM(Qd);new IM(cg);class to extends Bs{constructor(e){super(e)}get factory(){return Jx}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(e){return new to({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Bs.timeshiftOf(e)})}static fromString(e,t=ri.get(to)){const i=t.parse(e);return new to(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return to.fromString(i)}clone(){return new to(this.toSpec())}}class Mc extends Ko{uncertainComponent;approximateComponent;constructor(e,t){super(e,t),this.uncertainComponent=e.uncertainComponent||!1,this.approximateComponent=e.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(e){return super.uncertain=e}get approximate(){return super.approximate||this.approximateComponent}set approximate(e){return super.approximate=e}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class Qx extends TM{year=new Xi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Am=new Qx;class bo extends Mc{constructor(e,t=Am.year){super(e,t)}static fromString(e,t=Am.year,i=ri.get(bo)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new bo(Object.assign({...n},{value:Math.max(s,t.min)})),a=new bo(Object.assign({...n},{value:Math.min(n.value.end,t.max)})),l={start:r,end:a},c=n.value.estimate;return c&&(l.estimate=c),l}else return new bo(n)}}class eS extends _M{validate(e){switch(e){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(e)}}}class Mo extends Mc{constructor(e,t=new Xi(et.month.name,1,41,et.day,new eS)){super(e,t)}static fromString(e,t=ri.get(Mo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.month,r=new Mo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Mo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Mo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class wo extends Mc{constructor(e,t=et.day){super(e,t)}static fromString(e,t=ri.get(wo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.day,r=new wo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new wo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new wo(i)}toString(e){return super.toString(e).padStart(2,"0")}}class xo extends Mc{constructor(e,t=et.hour){super(e,t)}static fromString(e,t=ri.get(xo)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.hour,r=new xo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new xo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new xo(i)}}class So extends Mc{constructor(e,t=et.minute){super(e,t)}static fromString(e,t=ri.get(So)){const i=t.parse(e),n=i.value.start;if(n!==void 0){const s=et.minute,r=new So(Object.assign({...i},{value:Math.max(n,s.min)})),a=new So(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new So(i)}}class Eo extends Mc{constructor(e,t=et.second){super(e,t)}static fromString(e,t=et.second,i=ri.get(Eo)){const n=i.parse(e),s=n.value.start;if(s!==void 0){const r=new Eo(Object.assign({...n},{value:Math.max(s,t.min)})),a=new Eo(Object.assign({...n},{value:Math.min(n.value.end,t.max)}));return{start:r,end:a}}else return new Eo(n,t)}}class DM extends lc{}class tS extends Fh{qualifier(){return""}}class ma extends Ap{static instance=new ma;static valueRenderer=new tS(Ir.default);static names=["year","month","day","hour","minute","second"];static qualifier(e,t){return e?t?"%":"?":t?"~":""}renderComponent(e,t){const i=e[t],n=ma.names.slice(ma.names.indexOf(t)+1).map(a=>e[a]).filter(Boolean),s=ma.qualifier(i.uncertainComponent,i.approximateComponent),r=ma.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(ma.valueRenderer)+r}}class RM extends lg{constructor(e){super(e)}newYear(e){return new bo(e,this.units.year)}newMonth(e){return new Mo(e,this.units.month)}newDay(e){return new wo(e,this.units.day)}newHour(e){return new xo(e,this.units.hour)}newMinute(e){return new So(e,this.units.minute)}newSecond(e){return new Eo(e,this.units.second)}newMillisecond(e){return new qo(e,this.units.millisecond)}newTimeshift(e){return new DM(typeof e=="number"?e:e.value)}}const iS=new RM(Am);new RM(cg);class io extends to{constructor(e){super(e)}toString(e=ma.instance){return super.toString(e)}get year(){return super.year}set year(e){super.year=e}get month(){return super.month}set month(e){super.month=e}get factory(){return iS}static fromDate(e){return new io({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hour:e.getHours(),minute:e.getMinutes(),second:e.getSeconds(),timeshift:Bs.timeshiftOf(e)})}static fromString(e,t=ri.get(io)){const i=t.parse(e);return new io(i)}static newInstance(){const e=new Date().toISOString(),t=e.indexOf("."),i=e.substring(0,t)+e.substring(t+4);return io.fromString(i)}clone(){return new io(this.toSpec())}}class Tp{regExp;constructor(e,t){this.name=e,this.regExp=new RegExp(`^(?:${t})$`)}regexGroups(e){const t=this.regExp.exec(e);if(!t)throw new Go(`Invalid ${this.name} "${e}"`);return t.groups}parseGroups(e){throw new Qa(`${this.constructor.name} is abstract`)}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}class dg extends Tp{constructor(e,t){super(e,t)}static read(e){return{value:e?parseInt(e,10):void 0}}parseGroups(e){return dg.read(e[this.name])}parse(e){if(e.startsWith("-"))throw new Go(`${this.name} cannot be negative`);return super.parse(e)}}class oe{static groupName(...e){return e.reduce((t,i)=>t?t+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(e,...t){return`(?<${e}>${t.join("")})`}static optional(e){return e+"?"}static nonCapturingGroup(...e){return`(?:${e.join("")})`}static optionalGroup(e,...t){return oe.optional(oe.group(e,...t))}static optionalNonCapturingGroup(...e){return oe.optional(oe.nonCapturingGroup(...e))}static numberGroup(e,t,i,n="\\d"){return oe.group(e,`${i||""}[${n}]${t}`)}}const wv="timeshiftValue",xv="shiftHour",Sv="shiftMinute";class ug extends Tp{static format(e=""){return Mv.map(t=>t.name).join("|")+"|"+oe.nonCapturingGroup(oe.group(e+xv,oe.numberGroup(oe.groupName(e,wv),"{2}","[+-]")),oe.optionalNonCapturingGroup(":?",oe.numberGroup(oe.groupName(e,Sv),"{2}",void 0)))}constructor(){super(wv,ug.format())}parse(e,t){let i=0;const n=Mv.find(s=>s.name===e);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(t??{})}catch(s){throw new Go(`The time zone ${e} depends on the date: ${s.message}`)}e=n.timeshift}if(e!=="Z"){const s=this.regexGroups(e),r=s[xv];r&&(i+=parseInt(r,10)*60);const a=s[Sv];a&&(i+=parseInt(a,10))}return i}}class xi extends dg{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=xi.uncertainGroup+xi.approximateGroup;constructor(e,t){super(e,t)}static qualifierFormat(e,t){return oe.optionalGroup(e,`\\${t}`)}static formatSuffix(e){return this.qualifierFormat(oe.groupName(xi.uncertainGroup,e),"?")+this.qualifierFormat(oe.groupName(xi.approximateGroup,e),"~")+this.qualifierFormat(oe.groupName(xi.uncertainAndApproximateGroup,e),"%")}static numberFormat(e,t,i){return oe.numberGroup(e,t,i,"\\dX")+this.formatSuffix(e)}getValueAndSign(e){let t=e[this.name],i;return t.charAt(0)==="-"?(i=-1,t=t.substring(1)):i=1,{valueStr:t,sign:i}}parseGroups(e){const{valueStr:t,sign:i}=this.getValueAndSign(e);let n=0,s;for(s=0;s<t.length;s++){const c=t[s];if(c==="X")break;n=n*10+parseInt(c,10)}if(s<t.length){let c=1;for(let u=0;u<t.length-s;u++)c*=10;const h=i*n*c,d=h+c-1;n={start:h,end:d}}else n*=i;const r=e[oe.groupName(xi.uncertainAndApproximateGroup,this.name)],a=e[oe.groupName(xi.approximateGroup,this.name)]||r,l=e[oe.groupName(xi.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:l?!!l:!1}}}const Ev="yearValue";class Su extends xi{constructor(){super(Ev,Su.format())}static format(e=""){return"Y?"+xi.numberFormat(oe.groupName(e,Ev),"+","[-]?")}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const Av="monthValue";class Eu extends xi{static format(e=""){return xi.numberFormat(oe.groupName(e,Av),"{1,2}",void 0)}constructor(){super(Av,Eu.format())}}const Tv="dayValue";class Au extends xi{static format(e=""){return xi.numberFormat(oe.groupName(e,Tv),"{1,2}",void 0)}constructor(){super(Tv,Au.format())}}const _v="hourValue";class Tu extends xi{static format(e=""){return xi.numberFormat(oe.groupName(e,_v),"{1,2}",void 0)}constructor(){super(_v,Tu.format())}}const Iv="minuteValue";class _u extends xi{static format(e=""){return xi.numberFormat(oe.groupName(e,Iv),"{1,2}",void 0)}constructor(){super(Iv,_u.format())}}const Dv="secondValue";class Iu extends xi{static format(e=""){return xi.numberFormat(oe.groupName(e,Dv),"{1,2}",void 0)}constructor(){super(Dv,Iu.format())}}class Du extends ug{}class Ki extends Tp{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(e=Ki.format()){super("date",e)}static format(e=""){return oe.group(oe.groupName(e,Ki.yearGroup),Su.format(e))+oe.optionalNonCapturingGroup("-",oe.group(oe.groupName(e,Ki.monthGroup),Eu.format(e)),oe.optionalNonCapturingGroup("-",oe.group(oe.groupName(e,Ki.dayGroup),Au.format(e)),oe.optionalNonCapturingGroup("[T ]",oe.group(oe.groupName(e,Ki.hourGroup),Tu.format(e)),":",oe.group(oe.groupName(e,Ki.minuteGroup),_u.format(e)),oe.optionalNonCapturingGroup(":",oe.group(oe.groupName(e,Ki.secondGroup),Iu.format(e)),oe.optionalNonCapturingGroup("[.,]",oe.group(oe.groupName(e,Ki.millisecondGroup),"\\d+"))),oe.optionalGroup(oe.groupName(e,Ki.timeshiftGroup),Du.format(e)))))}parseGroups(e){const t=e[Ki.millisecondGroup],i=t?qo.parseFraction(t):void 0,n=e[Ki.secondGroup],s=n?yo.fromString(n,new Iu):void 0,r=e[Ki.minuteGroup];let a;r&&(a=vo.fromString(r,new _u),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const l=e[Ki.hourGroup];let c;l&&(c=go.fromString(l,new Tu),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[Ki.dayGroup];let d;h&&(d=mo.fromString(h,new Au),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Ki.monthGroup];let p;u&&(p=fo.fromString(u,new Eu),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Ki.yearGroup];let g;f&&(g=po.fromString(f,void 0,new Su),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[Ki.timeshiftGroup],v=m?lc.fromString(m,new Du,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:v}}}class Bi extends xi{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=Bi.uncertainGroup+Bi.approximateGroup;constructor(e,t){super(e,t)}static numberFormat(e,t,i){return this.qualifierFormat(oe.groupName(Bi.uncertainGroup,e),"?")+this.qualifierFormat(oe.groupName(Bi.approximateGroup,e),"~")+this.qualifierFormat(oe.groupName(Bi.uncertainAndApproximateGroup,e),"%")+xi.numberFormat(e,t,i)}parseGroups(e){const t=super.parseGroups(e),i=e[oe.groupName(Bi.uncertainAndApproximateGroup,this.name)];return(e[oe.groupName(Bi.uncertainGroup,this.name)]||i)&&(t.uncertainComponent=!0),(e[oe.groupName(Bi.approximateGroup,this.name)]||i)&&(t.approximateComponent=!0),t}}const Ac="yearValue",Rv="exp",Cv="signif";class Ru extends Bi{constructor(){super(Ac,Ru.format())}static format(e=""){return"Y?"+oe.nonCapturingGroup(oe.group(oe.groupName(e,Rv),"[-]?\\d+E\\d+")+"|"+Bi.numberFormat(oe.groupName(e,Ac),"+","[-]?")+oe.optionalGroup(oe.groupName(e,Cv),"S\\d+"))}parseGroups(e){const t=e[Rv];if(t){const r=t.indexOf("E"),a=parseInt(t.substring(r+1),10),c=parseInt(t.substring(0,r),10)*Math.pow(10,a);e[Ac]=c.toString()}const i=e[Cv],n=e[Ac];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:l}=this.getValueAndSign(e);let c="";for(let h=0;h<a.length;h++)c+=h<r?a.charAt(h):"X";e[Ac]=(l<0?"-":"")+c}const s=super.parseGroups(e);return i&&(s.value.estimate=parseInt(n,10)),s}parse(e){const t=this.regexGroups(e);return this.parseGroups(t)}}const kv="monthValue";class Cu extends Bi{static format(e=""){return Bi.numberFormat(oe.groupName(e,kv),"{1,2}",void 0)}constructor(){super(kv,Cu.format())}}const Lv="dayValue";class ku extends Bi{static format(e=""){return Bi.numberFormat(oe.groupName(e,Lv),"{1,2}",void 0)}constructor(){super(Lv,ku.format())}}const Ov="hourValue";class Lu extends Bi{static format(e=""){return Bi.numberFormat(oe.groupName(e,Ov),"{1,2}",void 0)}constructor(){super(Ov,Lu.format())}}const Pv="secondValue";class Ou extends Bi{static format(e=""){return Bi.numberFormat(oe.groupName(e,Pv),"{1,2}",void 0)}constructor(){super(Pv,Ou.format())}}const Nv="minuteValue";class Pu extends Bi{static format(e=""){return Bi.numberFormat(oe.groupName(e,Nv),"{1,2}",void 0)}constructor(){super(Nv,Pu.format())}}class nS extends Du{}class Zi extends Tp{static yearGroup=Ki.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",Zi.format())}static format(e=""){return oe.group(oe.groupName(e,Zi.yearGroup),Ru.format(e))+oe.optionalNonCapturingGroup("-",oe.group(oe.groupName(e,Zi.monthGroup),Cu.format(e)),oe.optionalNonCapturingGroup("-",oe.group(oe.groupName(e,Zi.dayGroup),ku.format(e)),oe.optionalNonCapturingGroup("[T ]",oe.group(oe.groupName(e,Zi.hourGroup),Lu.format(e)),":",oe.group(oe.groupName(e,Zi.minuteGroup),Pu.format(e)),oe.optionalNonCapturingGroup(":",oe.group(oe.groupName(e,Zi.secondGroup),Ou.format(e)),oe.optionalNonCapturingGroup("[.,]",oe.group(oe.groupName(e,Zi.millisecondGroup),"\\d+"))),oe.optionalGroup(oe.groupName(e,Zi.timeshiftGroup),nS.format(e)))))}parseGroups(e){const t=e[Zi.millisecondGroup],i=t?qo.parseFraction(t):void 0,n=e[Zi.secondGroup];let s;n&&(s=Eo.fromString(n,void 0,new Ou),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=e[Zi.minuteGroup];let a;r&&(a=So.fromString(r,new Pu),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const l=e[Zi.hourGroup];let c;l&&(c=xo.fromString(l,new Lu),c.uncertain=c.uncertain||a?.uncertain||!1,c.approximate=c.approximate||a?.approximate||!1);const h=e[Zi.dayGroup];let d;h&&(d=wo.fromString(h,new ku),d.uncertain=d.uncertain||c?.uncertain||!1,d.approximate=d.approximate||c?.approximate||!1);const u=e[Zi.monthGroup];let p;u&&(p=Mo.fromString(u,new Cu),p.uncertain=p.uncertain||d?.uncertain||!1,p.approximate=p.approximate||d?.approximate||!1);const f=e[Zi.yearGroup];let g;f&&(g=bo.fromString(f,void 0,new Ru),g.uncertain=g.uncertain||p?.uncertain||!1,g.approximate=g.approximate||p?.approximate||!1);const m=e[Zi.timeshiftGroup],v=m?DM.fromString(m,new Du,{year:g?.value,month:p?.value,day:d?.value,hour:c?.value}):void 0;return{year:g,month:p,day:d,hour:c,minute:a,second:s,millisecond:i,timeshift:v}}}const CM=["spring","summer","autumn","winter"],Tm=21,sS=32,rS=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let aS;function oS(){return aS??=new Zi}function Qo(o){return typeof o?.value=="number"?o.value:void 0}function eu(o){const e=o.trim();if(/^\d{1,2}:/.test(e)){const r=rS.exec(e)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:e}:void 0}let t;try{t=io.fromString(e,oS())}catch{return}const i=Qo(t.year),n=Qo(t.month),s=n!==void 0&&n>=Tm&&n<=sS;if(!(t.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(t.day||t.hour)))return{year:i,month:s?void 0:n,...s?{season:CM[(n-Tm)%4]}:{},day:Qo(t.day),hour:Qo(t.hour),minute:Qo(t.minute),second:Qo(t.second),raw:e}}function Ao(o){if(o.raw!==void 0)return o.raw;if(o.year===void 0){if(o.hour===void 0)return"";let t=`${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`;return o.second!==void 0&&(t+=`:${String(o.second).padStart(2,"0")}`),t}let e=String(o.year).padStart(4,"0");return o.season!==void 0?`${e}-${Tm+CM.indexOf(o.season)}`:(o.month===void 0||(e+=`-${String(o.month).padStart(2,"0")}`,o.day===void 0)||(e+=`-${String(o.day).padStart(2,"0")}`,o.hour===void 0)||(e+=`T${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`,o.second!==void 0&&(e+=`:${String(o.second).padStart(2,"0")}`)),e)}function _m(o){if(o.year!==void 0)return Date.UTC(o.year,(o.month??1)-1,o.day??1,o.hour??0,o.minute??0,o.second??0)}function Fv(o){return(((o.day??0)*24+(o.hour??0))*60+(o.minute??0))*6e4+(o.second??0)*1e3}const lS=["year","month","day","hour","minute"],cS=["day","hour","minute"];function Uv(o,e){return e.filter(t=>o[t]!==void 0).join(",")}function cc(o){if(o.durationSeconds!==void 0)return o.durationSeconds*1e3;const e=o.durationText===void 0?void 0:Nn.parse(o.durationText);if(e)return e.chosenSeconds*1e3;if(!o.time||!o.endTime)return;const t=o.time.year!==void 0&&o.endTime.year!==void 0,i=t?lS:cS,n=Uv(o.time,i);if(!(n===""||n!==Uv(o.endTime,i)))return t?_m(o.endTime)-_m(o.time):Fv(o.endTime)-Fv(o.time)}function hS(o){if(o.durationSeconds===void 0&&!(!o.time||!o.endTime))return cc(o)===void 0?"imprecise":void 0}class _p{constructor(e,t,i,n,s,r,a,l,c=[],h,d,u,p=[],f=[],g=[],m=[]){this.event=e,this.timeline=t,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=l,this.decor=c,this.weatherSource=h,this.instrumentId=d,this.exposureSeconds=u,this.milestones=p,this.references=f,this.roads=g,this.traces=m}provenance=Un.empty();loadIssues=[];account;sources;interpretation;sway;lightPollution;observerMap;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 Ut.byId(this.instrumentId)}static create(e,t,i){return new _p({eventType:"sighting",time:e,place:t},new xp,new bh,new Mh,new wh,i)}}const dS=0,uS=0;function ot(o,e){const t=o.observerTrack.getInterpolatedPoseAt(e);if(t)return t;const i=o.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:dS,headingDeg:void 0,pitchDeg:uS,fovDeg:Ut.fieldOfViewDeg(o.instrument)}}function Fi(o,e){return o.weatherTrack.getInterpolatedWeatherAt(e)??o.weather??Sp}function $h(o,e){return o.weatherTrack.getActualWeatherAt(e)??o.weather??Sp}function pg(o,e){return o.soundTrack.getInterpolatedSoundAt(e)??gx}class xh{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Ci.SIGHTING_EVENT&&typeof i.url=="string"&&i.url!=="").map(i=>({event:i,url:new URL(i.url,t).href,kind:i.interpretationOf===void 0?"observer":"reading"}))}tracks;caseChanged=!1;transcripts=new Map;static around(e,t,i,n,s){const r=(e.observer?.id??e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",a={id:e.id??"case",...t!==void 0?{time:t}:{},events:[{type:"event",eventType:Ci.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},l=new xh(a,new URL("case.json",s).href),c=l.tracks[0];return c.recording=e,c.base={url:n},c.event.id=l.proposedId(c),l.caseChanged=!0,l}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(n=>n.kind==="observer");return i.find(n=>n.event.id!==void 0&&t.includes(n.event.id))??i.find(n=>n.recording?.id!==void 0&&t.includes(n.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Ci.INTERVIEW_EVENT)}intervieweeOf(e){return this.intervieweesOf(e)[0]}intervieweesOf(e){const t=this.tracks.filter(i=>i.kind==="observer");return[e.interviewOf].flat().filter(i=>typeof i=="string").flatMap(i=>{const n=t.find(s=>s.event.id===i)??t.find(s=>s.recording?.id===i);return n?[n]:[]})}addInterview(e,t,i,n,s){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let l=1;for(;r.has(`interview-${a}-${l}`);)l++;const c={type:"event",eventType:Ci.INTERVIEW_EVENT,id:`interview-${a}-${l}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...s!==void 0?{medium:s}:{},...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{}};return this.json.events=[...this.json.events??[],c],this.caseChanged=!0,c}transcriptText(e){return this.transcripts.get(e)?.text}keepTranscript(e,t){this.transcripts.set(e,{text:t,loaded:this.transcripts.get(e)?.loaded})}transcriptChanged(e){return e.loaded!==e.text}deleteInterview(e){return this.interviews.includes(e)?(this.json.events=(this.json.events??[]).filter(t=>t!==e),this.transcripts.delete(e),this.caseChanged=!0,!0):!1}keep(e,t,i=!1){e.recording=t,i&&(e.loaded=JSON.stringify(t)),e.kind==="reading"&&t.interpretation?.title!==void 0&&(e.event.title=t.interpretation.title)}replaceJson(e){const i=(e.events??[]).filter(s=>s.eventType===Ci.SIGHTING_EVENT&&typeof s.url=="string"&&s.url!=="").map(s=>{const r=new URL(s.url,this.url).href,a=s.interpretationOf===void 0?"observer":"reading",l=this.tracks.find(c=>c.url===r);return l?(l.event=s,l.kind=a,l):{event:s,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const n=new Map;for(const[s,r]of this.transcripts){const a=(e.events??[]).find(l=>l.eventType===Ci.INTERVIEW_EVENT&&(s.id!==void 0&&l.id===s.id||s.url!==void 0&&l.url===s.url));a&&n.set(a,r)}this.transcripts.clear();for(const[s,r]of n)this.transcripts.set(s,r);this.json=e,this.caseChanged=!0}touch(){this.caseChanged=!0}get dirty(){return this.caseChanged||this.tracks.some(e=>this.changed(e))||[...this.transcripts.values()].some(e=>this.transcriptChanged(e))}markExported(e){if(this.caseChanged=!1,!!e){for(const t of this.tracks)t.recording&&(t.loaded=JSON.stringify(t.recording));for(const t of this.transcripts.values())t.loaded=t.text}}changed(e){return e.recording!==void 0&&(e.loaded===void 0||JSON.stringify(e.recording)!==e.loaded)}static ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;eventIds(e){return new Set((this.json.events??[]).filter(t=>t!==e?.event).map(t=>t.id).filter(t=>t!==void 0))}proposedId(e){const t=a=>(a??"").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""),i=typeof e.event.title=="string"?e.event.title:void 0,n=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),s=this.eventIds(e);if(n!==""){let a=n;for(let l=2;s.has(a);l++)a=`${n}-${l}`;return a}let r=1;for(;s.has(`sighting-${r}`);)r++;return`sighting-${r}`}ensureId(e){return e.event.id===void 0&&(e.event.id=this.proposedId(e),this.caseChanged=!0),e.event.id}setId(e,t){const i=e.event.id,n=a=>a===i||a===e.recording?.id,s=(this.json.events??[]).filter(a=>a.eventType===Ci.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(l=>l!==void 0&&n(l))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(l=>l!==void 0&&n(l)));if(t==="")return i===void 0?"ok":s.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!xh.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of s){const l=[a.interpretationOf].flat().map(c=>n(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?l:l[0]}for(const a of r){const l=[a.interviewOf].flat().map(c=>c!==void 0&&n(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?l:l[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Ci.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,n){const s=e.recording;if(!s)throw new Error("A reading is added to an account that has been loaded");const r=e.event.url.replace(/^.*\//,"").replace(/^observer-/,"").replace(/\.json$/,""),a=new Set(this.tracks.map(I=>I.event.url)),l=new Set(this.tracks.map(I=>I.recording?.id));let c=this.tracks.filter(I=>I.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||l.has(`${s.id??r}-interpretation-${c}`);)c++;const h=`interpretation-${r}-${c}.json`,d=e.event.url.includes("/")?e.event.url.replace(/[^/]*$/,""):"",{id:u,version:p,observer:f,account:g,description:m,sources:v,tags:b,timeline:M,milestones:y,interpretation:x,...S}=structuredClone(s),A={version:1,id:`${s.id??r}-interpretation-${c}`,...S,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},w={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...n!==void 0&&n.length>0?{by:n}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],w],this.caseChanged=!0;const T={event:w,url:new URL(w.url,this.url).href,kind:"reading",recording:A};return this.tracks.push(T),T}idsOf(e){return[e.event.id,e.recording?.id].filter(t=>t!==void 0)}readingsOf(e){const t=this.idsOf(e);return this.tracks.filter(i=>i.kind==="reading"&&[i.event.interpretationOf].flat().some(n=>n!==void 0&&t.includes(n)))}addObservation(e,t,i,n){const s=new Set(this.tracks.map(g=>g.event.url)),r=new Set(this.tracks.map(g=>g.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",l=n?"interpretation":"observer";let c=`${l}-${a}.json`,h=e.id??a;for(let g=2;s.has(c)||r.has(h);g++)c=`${l}-${a}-${g}.json`,h=`${e.id??a}-${g}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...n?{interpretationOf:this.ensureId(n.account)}:{},...t!==void 0?{time:t}:{},...n?.by&&n.by.length>0?{by:n.by}:{},...i!==void 0?{title:i}:{},url:u+c};this.json.events=[...this.json.events??[],p],this.caseChanged=!0;const f={event:p,url:new URL(p.url,this.url).href,kind:n?"reading":"observer",recording:d};return this.tracks.push(f),n||(p.id=this.proposedId(f)),f}deleteObservation(e){if(e.kind!=="observer")return{deleted:!1,readings:0};const t=this.readingsOf(e).length;if(t>0)return{deleted:!1,readings:t};const i=this.tracks.indexOf(e);return i<0?{deleted:!1,readings:0}:(this.tracks.splice(i,1),this.json.events=(this.json.events??[]).filter(n=>n!==e.event),this.caseChanged=!0,{deleted:!0})}deleteReading(e){if(e.kind!=="reading")return!1;const t=this.tracks.indexOf(e);return t<0?!1:(this.tracks.splice(t,1),this.json.events=(this.json.events??[]).filter(i=>i!==e.event),this.caseChanged=!0,!0)}files(e=!0,t=!1){const i=this.url.replace(/[^/]*$/,""),n=l=>l.startsWith(i)?l.slice(i.length):l,s=this.tracks.filter(l=>e&&l.recording!==void 0&&(t||this.changed(l))).map(l=>({path:n(l.url),content:JSON.stringify(l.recording,null,2)+`
3
3
  `})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([l,c])=>e&&l.url!==void 0&&(t||this.transcriptChanged(c))).map(([l,c])=>({path:n(new URL(l.url,this.url).href),content:c.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
4
4
  `},...s,...a]}}class ln{constructor(e,t,i,n="en"){this.parts=e,this.messages=t,this.onChange=i,this.locale=n,this.setMessages(t),e.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),e.picker.addEventListener("change",()=>this.writeFromPicker()),e.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),e.text.addEventListener("blur",()=>this.validate()),e.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";get isPrecise(){return this.precise}setMessages(e,t=this.locale){this.messages=e,this.locale=t,e.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=e.edtfPlaceholder),this.parts.mode.title=e.edtfModeTitle,this.parts.mode.setAttribute("aria-label",e.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(e){this.precise=e,this.parts.picker.hidden=!e,this.parts.text.hidden=e,this.parts.mode.textContent=e?this.messages.datePrecise:this.messages.dateEdtf,this.parts.mode.setAttribute("aria-pressed",String(!e)),this.parts.help&&(this.parts.help.hidden=e),this.showDeduction()}set(e){const{text:t,picker:i}=this.parts;t.value=e?Ao(e):"",i.type!=="date"&&(i.step=ln.stepFor(e)),i.value=i.type==="date"?ln.pickerDateOf(e):ln.pickerValueOf(e),t.setCustomValidity(""),t.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...e){return e.every(t=>t===void 0||ln.isPickable(t)&&ln.qualifierOf(Ao(t))==="")}static opensPreciseDate(...e){return e.every(t=>t===void 0||ln.isFullDate(t)&&ln.qualifierOf(Ao(t))==="")}static isFullDate(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0}static pickerDateOf(e){if(!ln.isFullDate(e))return"";const t=(i,n=2)=>String(i).padStart(n,"0");return`${t(e.year,4)}-${t(e.month)}-${t(e.day)}`}static isPickable(e){return!!e&&e.year!==void 0&&e.month!==void 0&&e.day!==void 0&&e.hour!==void 0&&e.minute!==void 0}static pickerValueOf(e){if(!ln.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"}static qualifierOf(e){const t=/[?%]/.test(e),i=/[~%]/.test(e);return t&&i?"%":t?"?":i?"~":""}describe(e){return ln.describeTime(e,this.messages,this.locale)}static describeTime(e,t,i){const n=Ao(e),s=ln.qualifierOf(n),r=h=>String(h).padStart(2,"0"),a=[];if(e.season!==void 0){const h={spring:t.timeSeasonSpring,summer:t.timeSeasonSummer,autumn:t.timeSeasonAutumn,winter:t.timeSeasonWinter}[e.season];a.push(e.year!==void 0?`${h} ${e.year}`:h)}else if(e.year!==void 0){const h=e.day!==void 0?{...e.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:e.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},d=new Date(Date.UTC(e.year,(e.month??1)-1,e.day??1));a.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(d))}e.hour!==void 0&&a.push(`${r(e.hour)}:${r(e.minute??0)}${e.second!==void 0?`:${r(e.second)}`:""}`);const l=a.join(", "),c=s==="~"?t.timeQualifierApproximate:s==="?"?t.timeQualifierUncertain:s==="%"?t.timeQualifierBoth:"";return c?`${l} — ${c.toLowerCase()}`:l}setHint(e){this.hint=e,this.showDeduction()}showDeduction(){const{text:e}=this.parts,t=e.value.trim();if(this.precise||t===""){e.title=this.hint;return}const i=eu(t);e.title=i?`→ ${this.describe(i)}`:this.messages.edtfInvalid}readText(){const e=this.parts.text.value.trim();if(e===""){this.clean(),this.onChange(void 0);return}const t=eu(e);t&&(this.clean(),this.onChange(t))}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:e,text:t}=this.parts;e.value===""&&e.validity.badInput||(t.value=e.value===""?"":e.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:e}=this.parts,t=e.value.trim();t===""||eu(t)||(e.setCustomValidity(this.messages.edtfInvalid),e.classList.add("invalid"))}}const pS={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"},timeQualifierApproximate:"Approximate",timeQualifierUncertain:"Uncertain",timeQualifierBoth:"Uncertain and approximate",timeSeasonSpring:"Spring",timeSeasonSummer:"Summer",timeSeasonAutumn:"Autumn",timeSeasonWinter:"Winter",summaryGroups:{observation:"Observation",location:"Position",temporal:"Time",weather:"Weather",sound:"Sound"},summaryGroup:"Summary",summaryDescription:"Description",closeDescription:"Close the description",observerGroup:"Observer",observerId:"ID",observerTitle:"Title",observerLastName:"Last name",observerFirstNames:"First names",sightingId:"ID",tags:"Tags",cloudCover:"Cloud cover",highCloudCover:"Ice cloud (cirrus)",focalLength:"Focal length",fieldOfView:"Field of view",aperture:"Aperture",exposure:"Exposure",focusDistance:"Focused at",iceCrystalAlignment:"Crystal alignment",rareIceCrystals:"Rare crystals",cloudDarkness:"Cloud darkness",precipitationType:"Precipitation",precipitationNone:"None",precipitationRain:"Rain",precipitationSnow:"Snow",precipitationHail:"Hail",precipitationIntensity:"Intensity",windDirection:"Wind direction",windSpeed:"Wind speed",storm:"Storm",cloudsGroup:"Clouds",precipitationGroup:"Precipitation",windGroup:"Wind",soundKind:"Sound",soundNone:"None (silent)",soundHum:"Hum",soundWhistle:"Whistle",soundRumble:"Rumble",soundCrackle:"Crackle",soundVolume:"Loudness",soundPitch:"Pitch",soundSrc:"Recording",instrument:"Observed through",filter:"In front of it",filterNone:"nothing",filterSolarVisual:"a solar filter for the eye (eclipse glasses, density 5)",filterSolarPhoto:"a solar film for a camera (density 3.8)",decorAircraft:"Aircraft",decorEntity:"Being",decorAltitude:"Altitude",decorLights:"Lights",decorLightsNone:"none",decor:"Environment",decorBuilding:"Building",decorTree:"Tree",decorShrub:"Shrub",decorBridge:"Bridge",decorWire:"Overhead line",decorCrop:"Crop row",decorTerrace:"Terrace (restanque)",decorMound:"Stone heap",decorWall:"Dry-stone wall",decorStreetlight:"Streetlight",decorVehicle:"Vehicle",decorObserver:"Other observer",decorEast:"Distance east",decorNorth:"Distance north",decorHeading:"Heading",decorColor:"Colour",decorLit:"Lit",decorTitle:"Name",milestones:"Moments",milestoneLabel:"Label",milestoneNote:"What happens",addMilestone:"Name this moment",deleteMilestone:"Delete moment",goToMilestone:"Go to this moment",decorWidth:"Width",decorLength:"Length",decorHeight:"Height",decorModel:"3D model",decorModelAdvanced:"Model from an address",decorModelUrl:"glTF/GLB address",decorModelTitle:"Model name",decorModelAuthor:"Author",decorModelLicense:"Licence",decorModelSource:"Where it came from",decorObserverSide:"Observer location",decorObserverSideNone:"Not present",decorSideFront:"Front",decorSideBehind:"Behind",decorSideLeft:"Left",decorSideRight:"Right",decorSideFrontLeft:"Front-left",decorSideFrontRight:"Front-right",decorSideBehindLeft:"Behind-left",decorSideBehindRight:"Behind-right"},ka={...pS,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",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:"Save",identityHint:"Name someone only if they agreed to it or published their own account; otherwise initials are enough.",identityAsk:"This recording names or locates a person. You answer for what you publish: name someone only if they agreed to it, or published their own account. Otherwise initials are enough.",identityLastName:"Last name: {value}",identityFirstNames:"First name: {value}",identityNameInId:"Name in an identifier: {value}",identityNameInText:"Name in the text: {value}",identityAddress:"Address: {value}",identityEmail:"E-mail address: {value}",identityPhone:"Telephone number: {value}",identityInitials:"Replace with initials",identityKeep:"Save anyway",identityBack:"Go back",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",utcOffsetNoZone:"No time zone reads this offset on that day",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:"unknown",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",launchesSubgroup:"Launches",soundGroup:"Sound",temporalGroup:"Time",fileGroup:"File",fileLoading:"Loading the editor…",weatherEditedAsk:"This edit touches the weather, data read dynamically from {source}. Stop reading it from {source}?",weatherEditedStop:"Stop reading it",weatherEditedKeep:"Keep reading it (undo my edit)",fileEditorLabel:"The recording as JSON text",fileSearchPhrases:{},timeQualifierExact:"Exact",durationPrecise:"precise",durationIso:"imprecise",durationModeTitle:"Say the length exactly, or as stated: about, between two lengths",durationInvalid:"Not a duration: PT10M, PT1H30M, PT5M/PT10M…",durationHelpTitle:"What the text takes (EDTF)",durationHelpLines:`PT45S — 45 seconds
@@ -41,7 +41,7 @@ rr0-date-input [hidden] { display: none !important; }
41
41
  <label><input id="cloud-manipulate" type="checkbox">${t("manipulate")}</label>
42
42
  <div id="cloud-instance-parameters" class="cloud-parameters"></div>
43
43
  </div><p data-text="individualHelp">${e.individualHelp}</p></details>
44
- <p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text]}}const Sh=["en","fr","es","it"],xS={en:()=>_e(()=>Promise.resolve().then(()=>sE),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>_e(()=>import("./UfoMessages_fr-bJNAf-AU.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>_e(()=>import("./UfoMessages_es-LFW_B5H2.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>_e(()=>import("./UfoMessages_it-B-jnc4M-.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function SS(o){return xS[o]()}const ES={en:()=>_e(()=>Promise.resolve().then(()=>fS),void 0,import.meta.url).then(o=>o.sightingEditorMessages_en),fr:()=>_e(()=>import("./SightingEditorMessages_fr-Dhw6ob5Y.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_fr),es:()=>_e(()=>import("./SightingEditorMessages_es-DkPZhcr_.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_es),it:()=>_e(()=>import("./SightingEditorMessages_it-7r9D-wed.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_it)};function NM(o){return ES[o]()}function AS(o){switch(o){case"fr":return _e(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return _e(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return _e(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const TS={en:()=>_e(()=>import("./BodyEditorMessages_en-C3VGB1gD.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_en),fr:()=>_e(()=>import("./BodyEditorMessages_fr-BLypXEkB.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_fr),es:()=>_e(()=>import("./BodyEditorMessages_es-DN2YBKTK.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_es),it:()=>_e(()=>import("./BodyEditorMessages_it-W1myJQbG.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_it)},_S={en:()=>_e(()=>import("./LaunchEditorMessages_en-j4RgQPZu.js"),[],import.meta.url).then(o=>o.launchEditorMessages_en),fr:()=>_e(()=>import("./LaunchEditorMessages_fr-BUEdQmMO.js"),[],import.meta.url).then(o=>o.launchEditorMessages_fr),es:()=>_e(()=>import("./LaunchEditorMessages_es-9JZv0fqZ.js"),[],import.meta.url).then(o=>o.launchEditorMessages_es),it:()=>_e(()=>import("./LaunchEditorMessages_it-CrRnOg0x.js"),[],import.meta.url).then(o=>o.launchEditorMessages_it)};function hL(o){return _S[o]()}const IS={en:()=>_e(()=>Promise.resolve().then(()=>oL),void 0,import.meta.url).then(o=>o.caseEditorMessages_en),fr:()=>_e(()=>import("./CaseEditorMessages_fr-DN3xxn9o.js"),[],import.meta.url).then(o=>o.caseEditorMessages_fr),es:()=>_e(()=>import("./CaseEditorMessages_es-CNLEMPjy.js"),[],import.meta.url).then(o=>o.caseEditorMessages_es),it:()=>_e(()=>import("./CaseEditorMessages_it-B6aG-baK.js"),[],import.meta.url).then(o=>o.caseEditorMessages_it)},DS={en:()=>_e(()=>import("./InterviewMessages_en-C-7vNgM2.js"),[],import.meta.url).then(o=>o.interviewMessages_en),fr:()=>_e(()=>import("./InterviewMessages_fr-B_Tl9ZcL.js"),[],import.meta.url).then(o=>o.interviewMessages_fr),es:()=>_e(()=>import("./InterviewMessages_es-gh_1UJfY.js"),[],import.meta.url).then(o=>o.interviewMessages_es),it:()=>_e(()=>import("./InterviewMessages_it-ECgJT3FK.js"),[],import.meta.url).then(o=>o.interviewMessages_it)};function dL(o){return DS[o]()}function RS(o){return IS[o]()}function uL(o){return TS[o]()}function FM(o){switch(o){case"fr":return _e(()=>import("./SceneNames_fr-ZUtpsigH.js"),[],import.meta.url).then(e=>e.sceneNames_fr);case"es":return _e(()=>import("./SceneNames_es-cN-l95fv.js"),[],import.meta.url).then(e=>e.sceneNames_es);case"it":return _e(()=>import("./SceneNames_it-DLqJc0Rc.js"),[],import.meta.url).then(e=>e.sceneNames_it);default:return Promise.resolve(void 0)}}function CS(o){switch(o){case"fr":return _e(()=>import("./CloudEditorMessages_fr-CAnkW7tI.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_fr);case"es":return _e(()=>import("./CloudEditorMessages_es-RrGoxm6z.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_es);case"it":return _e(()=>import("./CloudEditorMessages_it-Batpxtii.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_it);default:return Promise.resolve(void 0)}}class Im{constructor(e){this.options=e,this.pickerRow=document.createElement("label"),this.labelText=document.createElement("span"),e.ids.label&&(this.labelText.id=e.ids.label),this.select=document.createElement("select"),this.select.id=e.ids.list,this.select.addEventListener("change",()=>e.onSelect(this.select.value)),this.pickerRow.append(this.labelText," ",this.select);const t=document.createElement("div");t.className="element-list-row",t.style.cssText="display: flex; align-items: flex-end; gap: .4em; flex: 1 1 100%; min-width: 0;",this.pickerRow.style.cssText="flex: 1 1 8em; min-width: 0; display: flex; flex-direction: column;",this.select.style.cssText="width: 100%; min-width: 0; max-width: 100%; box-sizing: border-box;",e.header.append(t),t.append(this.pickerRow);const i=e.navigation;i&&(this.previousButton=this.iconButton(`${e.ids.list}-previous`,"▲"),this.nextButton=this.iconButton(`${e.ids.list}-next`,"▼"),this.previousButton.addEventListener("click",()=>i.onStep(-1)),this.nextButton.addEventListener("click",()=>i.onStep(1)),t.append(this.previousButton,this.nextButton),i.scope.addEventListener("keydown",n=>{if(!n.altKey||n.ctrlKey||n.metaKey||n.shiftKey||n.key!=="ArrowUp"&&n.key!=="ArrowDown"||this.pickerRow.closest("[hidden]")||!this.pickerRow.isConnected)return;n.preventDefault(),n.stopPropagation();const s=n.key==="ArrowUp"?this.previousButton:this.nextButton;s&&!s.disabled&&i.onStep(n.key==="ArrowUp"?-1:1)}));for(const n of e.actions??[]){const s=this.iconButton(n.id,n.glyph);s.addEventListener("click",()=>n.onClick()),this.actionButtons.set(n.id,s),t.append(s)}if(this.removeButton=this.iconButton(e.ids.remove,"🗑"),this.removeButton.addEventListener("click",()=>e.onRemove()),this.addButton=this.iconButton(e.ids.add,"+"),this.addButton.addEventListener("click",()=>e.onAdd(this.kindSelect?.value)),e.ids.kinds){t.append(this.removeButton);const n=document.createElement("div");n.className=e.rowClass??"decor-add-row",n.style.cssText="display: flex; align-items: center; gap: .4em;",this.kindSelect=document.createElement("select"),this.kindSelect.id=e.ids.kinds,n.append(this.addButton,this.kindSelect),e.footer.append(n)}else t.append(this.addButton,this.removeButton)}select;labelText;pickerRow;removeButton;addButton;addReason;kindSelect;previousButton;nextButton;actionButtons=new Map;kinds=[];items=[];noneLabel="—";addLabel="";iconButton(e,t){const i=document.createElement("button");return i.type="button",i.className="icon-btn",i.id=e,i.textContent=t,i}setLabels(e){if(this.previousButton&&this.nextButton)for(const[t,i,n]of[[this.previousButton,e.previous??"","Alt+↑"],[this.nextButton,e.next??"","Alt+↓"]]){const s=i===""?n:`${i} (${n})`;t.title=s,t.setAttribute("aria-label",i||s),t.setAttribute("aria-keyshortcuts",n.replace("↑","ArrowUp").replace("↓","ArrowDown"))}this.labelText.textContent=e.list,this.noneLabel=e.none??this.noneLabel,this.addLabel=e.add,this.kindSelect&&(this.addButton.textContent=`+ ${e.add}`,this.addButton.style.cssText="width: auto; min-width: 0; white-space: nowrap; padding-left: .6em; padding-right: .6em;"),this.options.optional&&this.listed(this.items,this.select.value);for(const[t,i]of[[this.removeButton,e.remove],[this.addButton,e.add],...[...this.actionButtons].map(([n,s])=>[s,e.actions?.[n]??""])])t.title=i,t.setAttribute("aria-label",i)}setKinds(e){this.kinds=e;const t=this.kindSelect;if(!t)return;const i=t.value;t.replaceChildren(...e.map(n=>{const s=new Option(n.label,n.value);return this.options.ids.kind&&(s.id=this.options.ids.kind(n.value)),s.hidden=n.hidden===!0,s})),e.some(n=>n.value===i&&!n.hidden)&&(t.value=i)}kindLabel(e){return this.kinds.find(t=>t.value===e)?.label??e}get pickedKind(){return this.kindSelect?.value}setItems(e,t){this.items=e,this.listed(e,t)}listed(e,t){this.select.replaceChildren(...this.options.optional?[new Option(this.noneLabel,"")]:[],...e.map(i=>new Option(i.label,i.id))),t!==void 0&&(this.select.value=t),this.select.selectedIndex<0&&(this.select.selectedIndex=0),this.setPresent(this.options.optional?this.select.value!=="":e.length>0)}setStepState(e,t){this.previousButton&&(this.previousButton.disabled=!e),this.nextButton&&(this.nextButton.disabled=!t)}setRemoveEnabled(e){this.removeButton.disabled=!e}get value(){return this.select.value}setAddState(e,t){this.addButton.disabled=!e;const i=t??this.addLabel;this.addButton.title=i,this.addButton.setAttribute("aria-label",i),this.addReason||(this.addReason=this.addButton.ownerDocument.createElement("span"),this.addReason.className="add-reason",this.addReason.style.cssText="font-size: .85em; opacity: .8; align-self: center;",this.addButton.after(this.addReason)),this.addReason.textContent=!e&&t?t:"",this.addReason.hidden=e||!t}rename(e,t){const i=[...this.select.options].find(n=>n.value===e);i&&(i.textContent=t)}show(e){this.select.value=e,this.options.optional&&this.setPresent(this.select.value!=="")}setPresent(e){const t=this.options.optional===!0;this.pickerRow.hidden=!e&&!t,this.removeButton.hidden=!e&&!t,this.removeButton.disabled=!e,this.select.disabled=!e&&!t;for(const i of this.actionButtons.values())i.hidden=!e&&!t,i.disabled=!e}focus(){this.select.focus()}}class Tn{static read(e,t){let i=e;for(const n of t.split(".")){if(i=Tn.bare(i),i===null||typeof i!="object")return;i=i[n]}return Tn.bare(i)}static write(e,t,i){const n=t.split("."),s=[];let r=e;for(let l=0;l<n.length-1;l++){let c=Tn.bare(r[n[l]]);if(c===null||typeof c!="object"||Array.isArray(c)){if(i===void 0)return;c={}}r[n[l]]=c,s.push({owner:r,part:n[l]}),r=c}const a=n[n.length-1];i===void 0?delete r[a]:r[a]=i;for(let l=s.length-1;l>=0;l--){const c=s[l].owner[s[l].part];if(Object.keys(c).length>0)break;delete s[l].owner[s[l].part]}}static stated(e,t){return Tn.read(e,t)!==void 0}static bare(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"value"in e&&"basis"in e?e.value:e}}class tu{static sets=new Map;static publish(e){tu.sets.set(e.kind,e)}static of(e){return tu.sets.get(e)}static kinds(){return[...tu.sets.keys()]}}class gn{static CHROME="2.6em";static UNBOUNDED=9999;static fit(e){const t=[...e.querySelectorAll('input[type="number"]')];for(const i of t)i.style.width=`calc(${gn.charsFor(i)}ch + ${gn.CHROME})`,gn.hold(i,!0),i.dataset.held!==""&&(i.dataset.held="",i.addEventListener("input",()=>gn.hold(i)),i.addEventListener("change",()=>gn.hold(i,!0)));return t.length}static hold(e,t=!1){const i=gn.heldValue(e.value,e,t);i!==e.value&&(e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})))}static heldValue(e,t,i=!1){if(e===""||!/^-?\d+(\.\d+)?$/.test(e))return e;const n=gn.wholeOnly(t.step)?0:gn.decimalsOf(t.step),s=e.indexOf("."),r=s>=0&&e.length-s-1>n?n===0?e.slice(0,s):e.slice(0,s+n+1):e,a=Number(r),l=t.min===""?void 0:Number(t.min),c=t.max===""?void 0:Number(t.max);return c!==void 0&&a>c?String(c):i&&l!==void 0&&a<l?String(l):r}static charsFor(e){const t=a=>a===""?void 0:Math.abs(Number(a)),i=Math.max(t(e.max)??gn.UNBOUNDED,t(e.min)??0),n=String(Math.floor(Number.isFinite(i)?i:gn.UNBOUNDED)).length,s=e.min!==""&&Number(e.min)<0?1:0,r=gn.wholeOnly(e.step)?0:gn.decimalsOf(e.step);return n+s+(r>0?r+1:0)}static decimalsOf(e){if(e===""||e==="any")return 2;const t=e.indexOf(".");return Math.max(2,t<0?0:e.length-t-1)}static wholeOnly(e){return e!==""&&e!=="any"&&!e.includes(".")}}class Pa{constructor(e,t,i=()=>{}){this.read=e,this.edit=t,this.context=i}static inPlace(e){return new Pa(()=>e,t=>t(e))}}class Gs{constructor(e,t,i="",n,s){this.container=e,this.idPrefix=i,this.values=n,this.enhance=s,this.said=new zn([t,"en"])}set;target;changed=()=>{};said;setLanguage(e){this.said=new zn([e,"en"]),this.set&&this.target&&this.show(this.set,this.target,this.changed)}show(e,t,i){this.set=e,this.target=t instanceof Pa?t:Pa.inPlace(t),this.changed=i,this.container.replaceChildren();const n=new Map;for(const s of e.parameters){const r=this.read(s.group)??"";let a=n.get(r);if(!a){if(a=document.createElement("fieldset"),a.className="parameter-group",r!==""){const l=document.createElement("legend");l.textContent=r,a.append(l)}n.set(r,a),this.container.append(a)}a.append(this.fieldOf(s))}gn.fit(this.container),this.sync()}clear(){this.set=void 0,this.target=void 0,this.container.replaceChildren()}field(e){return this.container.querySelector(`[data-key="${e}"]`)??void 0}sync(e=!1){const t=this.target?.read();if(!this.set||!t)return;const i=this.target.context(),n=e?null:this.container.getRootNode().activeElement;for(const s of this.set.parameters){const r=this.field(s.key);if(!r)continue;const a=r.closest("label, .parameter-row")??r;a.hidden=s.visibleWhen!==void 0&&!s.visibleWhen(t,i);const l=Tn.read(t,s.key);if(s.type==="number"){const c=r;c!==n&&(c.value=typeof l=="number"?Gs.shown(l,s):"");const h=Gs.boundsOf(s,t,i);c.min=String(h.min),c.max=String(h.max);const d=s.effective?.(t,i);c.placeholder=d!==void 0?Gs.shown(d,s):this.read(s.placeholder)??"",c.classList.toggle("parameter-derived",l===void 0)}else if(s.type==="choice"){const c=r,h=s.optionsOf?.(t,i)??s.choices;if([...c.options].filter(d=>d.value!=="").map(d=>d.value).join(`
44
+ <p id="cloud-status" role="status"></p></div>`}static localize(e,t){for(const i of e.querySelectorAll("[data-text]"))i.textContent=t[i.dataset.text]}}const Sh=["en","fr","es","it"],xS={en:()=>_e(()=>Promise.resolve().then(()=>sE),void 0,import.meta.url).then(o=>o.ufoMessages_en),fr:()=>_e(()=>import("./UfoMessages_fr-bJNAf-AU.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>_e(()=>import("./UfoMessages_es-LFW_B5H2.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>_e(()=>import("./UfoMessages_it-B-jnc4M-.js"),[],import.meta.url).then(o=>o.ufoMessages_it)};function SS(o){return xS[o]()}const ES={en:()=>_e(()=>Promise.resolve().then(()=>fS),void 0,import.meta.url).then(o=>o.sightingEditorMessages_en),fr:()=>_e(()=>import("./SightingEditorMessages_fr-Dhw6ob5Y.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_fr),es:()=>_e(()=>import("./SightingEditorMessages_es-DkPZhcr_.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_es),it:()=>_e(()=>import("./SightingEditorMessages_it-7r9D-wed.js"),[],import.meta.url).then(o=>o.sightingEditorMessages_it)};function NM(o){return ES[o]()}function AS(o){switch(o){case"fr":return _e(()=>import("./TagNames_fr-Dnqq6HQ5.js"),[],import.meta.url).then(e=>e.tagNames_fr);case"es":return _e(()=>import("./TagNames_es-BfnMpc3D.js"),[],import.meta.url).then(e=>e.tagNames_es);case"it":return _e(()=>import("./TagNames_it-n6E4EGYO.js"),[],import.meta.url).then(e=>e.tagNames_it);default:return Promise.resolve({})}}const TS={en:()=>_e(()=>import("./BodyEditorMessages_en-C3VGB1gD.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_en),fr:()=>_e(()=>import("./BodyEditorMessages_fr-BLypXEkB.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_fr),es:()=>_e(()=>import("./BodyEditorMessages_es-DN2YBKTK.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_es),it:()=>_e(()=>import("./BodyEditorMessages_it-W1myJQbG.js"),[],import.meta.url).then(o=>o.bodyEditorMessages_it)},_S={en:()=>_e(()=>import("./LaunchEditorMessages_en-j4RgQPZu.js"),[],import.meta.url).then(o=>o.launchEditorMessages_en),fr:()=>_e(()=>import("./LaunchEditorMessages_fr-BUEdQmMO.js"),[],import.meta.url).then(o=>o.launchEditorMessages_fr),es:()=>_e(()=>import("./LaunchEditorMessages_es-9JZv0fqZ.js"),[],import.meta.url).then(o=>o.launchEditorMessages_es),it:()=>_e(()=>import("./LaunchEditorMessages_it-CrRnOg0x.js"),[],import.meta.url).then(o=>o.launchEditorMessages_it)};function hL(o){return _S[o]()}const IS={en:()=>_e(()=>Promise.resolve().then(()=>oL),void 0,import.meta.url).then(o=>o.caseEditorMessages_en),fr:()=>_e(()=>import("./CaseEditorMessages_fr-DN3xxn9o.js"),[],import.meta.url).then(o=>o.caseEditorMessages_fr),es:()=>_e(()=>import("./CaseEditorMessages_es-CNLEMPjy.js"),[],import.meta.url).then(o=>o.caseEditorMessages_es),it:()=>_e(()=>import("./CaseEditorMessages_it-B6aG-baK.js"),[],import.meta.url).then(o=>o.caseEditorMessages_it)},DS={en:()=>_e(()=>import("./InterviewMessages_en-cs-wWpmz.js"),[],import.meta.url).then(o=>o.interviewMessages_en),fr:()=>_e(()=>import("./InterviewMessages_fr-CmScqfza.js"),[],import.meta.url).then(o=>o.interviewMessages_fr),es:()=>_e(()=>import("./InterviewMessages_es-D5d2JVA3.js"),[],import.meta.url).then(o=>o.interviewMessages_es),it:()=>_e(()=>import("./InterviewMessages_it-2SNw5xMp.js"),[],import.meta.url).then(o=>o.interviewMessages_it)};function dL(o){return DS[o]()}function RS(o){return IS[o]()}function uL(o){return TS[o]()}function FM(o){switch(o){case"fr":return _e(()=>import("./SceneNames_fr-ZUtpsigH.js"),[],import.meta.url).then(e=>e.sceneNames_fr);case"es":return _e(()=>import("./SceneNames_es-cN-l95fv.js"),[],import.meta.url).then(e=>e.sceneNames_es);case"it":return _e(()=>import("./SceneNames_it-DLqJc0Rc.js"),[],import.meta.url).then(e=>e.sceneNames_it);default:return Promise.resolve(void 0)}}function CS(o){switch(o){case"fr":return _e(()=>import("./CloudEditorMessages_fr-CAnkW7tI.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_fr);case"es":return _e(()=>import("./CloudEditorMessages_es-RrGoxm6z.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_es);case"it":return _e(()=>import("./CloudEditorMessages_it-Batpxtii.js"),[],import.meta.url).then(e=>e.cloudEditorMessages_it);default:return Promise.resolve(void 0)}}class Im{constructor(e){this.options=e,this.pickerRow=document.createElement("label"),this.labelText=document.createElement("span"),e.ids.label&&(this.labelText.id=e.ids.label),this.select=document.createElement("select"),this.select.id=e.ids.list,this.select.addEventListener("change",()=>e.onSelect(this.select.value)),this.pickerRow.append(this.labelText," ",this.select);const t=document.createElement("div");t.className="element-list-row",t.style.cssText="display: flex; align-items: flex-end; gap: .4em; flex: 1 1 100%; min-width: 0;",this.pickerRow.style.cssText="flex: 1 1 8em; min-width: 0; display: flex; flex-direction: column;",this.select.style.cssText="width: 100%; min-width: 0; max-width: 100%; box-sizing: border-box;",e.header.append(t),t.append(this.pickerRow);const i=e.navigation;i&&(this.previousButton=this.iconButton(`${e.ids.list}-previous`,"▲"),this.nextButton=this.iconButton(`${e.ids.list}-next`,"▼"),this.previousButton.addEventListener("click",()=>i.onStep(-1)),this.nextButton.addEventListener("click",()=>i.onStep(1)),t.append(this.previousButton,this.nextButton),i.scope.addEventListener("keydown",n=>{if(!n.altKey||n.ctrlKey||n.metaKey||n.shiftKey||n.key!=="ArrowUp"&&n.key!=="ArrowDown"||this.pickerRow.closest("[hidden]")||!this.pickerRow.isConnected)return;n.preventDefault(),n.stopPropagation();const s=n.key==="ArrowUp"?this.previousButton:this.nextButton;s&&!s.disabled&&i.onStep(n.key==="ArrowUp"?-1:1)}));for(const n of e.actions??[]){const s=this.iconButton(n.id,n.glyph);s.addEventListener("click",()=>n.onClick()),this.actionButtons.set(n.id,s),t.append(s)}if(this.removeButton=this.iconButton(e.ids.remove,"🗑"),this.removeButton.addEventListener("click",()=>e.onRemove()),this.addButton=this.iconButton(e.ids.add,"+"),this.addButton.addEventListener("click",()=>e.onAdd(this.kindSelect?.value)),e.ids.kinds){t.append(this.removeButton);const n=document.createElement("div");n.className=e.rowClass??"decor-add-row",n.style.cssText="display: flex; align-items: center; gap: .4em;",this.kindSelect=document.createElement("select"),this.kindSelect.id=e.ids.kinds,n.append(this.addButton,this.kindSelect),e.footer.append(n)}else t.append(this.addButton,this.removeButton)}select;labelText;pickerRow;removeButton;addButton;addReason;kindSelect;previousButton;nextButton;actionButtons=new Map;kinds=[];items=[];noneLabel="—";addLabel="";iconButton(e,t){const i=document.createElement("button");return i.type="button",i.className="icon-btn",i.id=e,i.textContent=t,i}setLabels(e){if(this.previousButton&&this.nextButton)for(const[t,i,n]of[[this.previousButton,e.previous??"","Alt+↑"],[this.nextButton,e.next??"","Alt+↓"]]){const s=i===""?n:`${i} (${n})`;t.title=s,t.setAttribute("aria-label",i||s),t.setAttribute("aria-keyshortcuts",n.replace("↑","ArrowUp").replace("↓","ArrowDown"))}this.labelText.textContent=e.list,this.noneLabel=e.none??this.noneLabel,this.addLabel=e.add,this.kindSelect&&(this.addButton.textContent=`+ ${e.add}`,this.addButton.style.cssText="width: auto; min-width: 0; white-space: nowrap; padding-left: .6em; padding-right: .6em;"),this.options.optional&&this.listed(this.items,this.select.value);for(const[t,i]of[[this.removeButton,e.remove],[this.addButton,e.add],...[...this.actionButtons].map(([n,s])=>[s,e.actions?.[n]??""])])t.title=i,t.setAttribute("aria-label",i)}setKinds(e){this.kinds=e;const t=this.kindSelect;if(!t)return;const i=t.value;t.replaceChildren(...e.map(n=>{const s=new Option(n.label,n.value);return this.options.ids.kind&&(s.id=this.options.ids.kind(n.value)),s.hidden=n.hidden===!0,s})),e.some(n=>n.value===i&&!n.hidden)&&(t.value=i)}kindLabel(e){return this.kinds.find(t=>t.value===e)?.label??e}get pickedKind(){return this.kindSelect?.value}setItems(e,t){this.items=e,this.listed(e,t)}listed(e,t){this.select.replaceChildren(...this.options.optional?[new Option(this.noneLabel,"")]:[],...e.map(i=>new Option(i.label,i.id))),t!==void 0&&(this.select.value=t),this.select.selectedIndex<0&&(this.select.selectedIndex=0),this.setPresent(this.options.optional?this.select.value!=="":e.length>0)}setStepState(e,t){this.previousButton&&(this.previousButton.disabled=!e),this.nextButton&&(this.nextButton.disabled=!t)}setRemoveEnabled(e){this.removeButton.disabled=!e}get value(){return this.select.value}setAddState(e,t){this.addButton.disabled=!e;const i=t??this.addLabel;this.addButton.title=i,this.addButton.setAttribute("aria-label",i),this.addReason||(this.addReason=this.addButton.ownerDocument.createElement("span"),this.addReason.className="add-reason",this.addReason.style.cssText="font-size: .85em; opacity: .8; align-self: center;",this.addButton.after(this.addReason)),this.addReason.textContent=!e&&t?t:"",this.addReason.hidden=e||!t}rename(e,t){const i=[...this.select.options].find(n=>n.value===e);i&&(i.textContent=t)}show(e){this.select.value=e,this.options.optional&&this.setPresent(this.select.value!=="")}setPresent(e){const t=this.options.optional===!0;this.pickerRow.hidden=!e&&!t,this.removeButton.hidden=!e&&!t,this.removeButton.disabled=!e,this.select.disabled=!e&&!t;for(const i of this.actionButtons.values())i.hidden=!e&&!t,i.disabled=!e}focus(){this.select.focus()}}class Tn{static read(e,t){let i=e;for(const n of t.split(".")){if(i=Tn.bare(i),i===null||typeof i!="object")return;i=i[n]}return Tn.bare(i)}static write(e,t,i){const n=t.split("."),s=[];let r=e;for(let l=0;l<n.length-1;l++){let c=Tn.bare(r[n[l]]);if(c===null||typeof c!="object"||Array.isArray(c)){if(i===void 0)return;c={}}r[n[l]]=c,s.push({owner:r,part:n[l]}),r=c}const a=n[n.length-1];i===void 0?delete r[a]:r[a]=i;for(let l=s.length-1;l>=0;l--){const c=s[l].owner[s[l].part];if(Object.keys(c).length>0)break;delete s[l].owner[s[l].part]}}static stated(e,t){return Tn.read(e,t)!==void 0}static bare(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"value"in e&&"basis"in e?e.value:e}}class tu{static sets=new Map;static publish(e){tu.sets.set(e.kind,e)}static of(e){return tu.sets.get(e)}static kinds(){return[...tu.sets.keys()]}}class gn{static CHROME="2.6em";static UNBOUNDED=9999;static fit(e){const t=[...e.querySelectorAll('input[type="number"]')];for(const i of t)i.style.width=`calc(${gn.charsFor(i)}ch + ${gn.CHROME})`,gn.hold(i,!0),i.dataset.held!==""&&(i.dataset.held="",i.addEventListener("input",()=>gn.hold(i)),i.addEventListener("change",()=>gn.hold(i,!0)));return t.length}static hold(e,t=!1){const i=gn.heldValue(e.value,e,t);i!==e.value&&(e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})))}static heldValue(e,t,i=!1){if(e===""||!/^-?\d+(\.\d+)?$/.test(e))return e;const n=gn.wholeOnly(t.step)?0:gn.decimalsOf(t.step),s=e.indexOf("."),r=s>=0&&e.length-s-1>n?n===0?e.slice(0,s):e.slice(0,s+n+1):e,a=Number(r),l=t.min===""?void 0:Number(t.min),c=t.max===""?void 0:Number(t.max);return c!==void 0&&a>c?String(c):i&&l!==void 0&&a<l?String(l):r}static charsFor(e){const t=a=>a===""?void 0:Math.abs(Number(a)),i=Math.max(t(e.max)??gn.UNBOUNDED,t(e.min)??0),n=String(Math.floor(Number.isFinite(i)?i:gn.UNBOUNDED)).length,s=e.min!==""&&Number(e.min)<0?1:0,r=gn.wholeOnly(e.step)?0:gn.decimalsOf(e.step);return n+s+(r>0?r+1:0)}static decimalsOf(e){if(e===""||e==="any")return 2;const t=e.indexOf(".");return Math.max(2,t<0?0:e.length-t-1)}static wholeOnly(e){return e!==""&&e!=="any"&&!e.includes(".")}}class Pa{constructor(e,t,i=()=>{}){this.read=e,this.edit=t,this.context=i}static inPlace(e){return new Pa(()=>e,t=>t(e))}}class Gs{constructor(e,t,i="",n,s){this.container=e,this.idPrefix=i,this.values=n,this.enhance=s,this.said=new zn([t,"en"])}set;target;changed=()=>{};said;setLanguage(e){this.said=new zn([e,"en"]),this.set&&this.target&&this.show(this.set,this.target,this.changed)}show(e,t,i){this.set=e,this.target=t instanceof Pa?t:Pa.inPlace(t),this.changed=i,this.container.replaceChildren();const n=new Map;for(const s of e.parameters){const r=this.read(s.group)??"";let a=n.get(r);if(!a){if(a=document.createElement("fieldset"),a.className="parameter-group",r!==""){const l=document.createElement("legend");l.textContent=r,a.append(l)}n.set(r,a),this.container.append(a)}a.append(this.fieldOf(s))}gn.fit(this.container),this.sync()}clear(){this.set=void 0,this.target=void 0,this.container.replaceChildren()}field(e){return this.container.querySelector(`[data-key="${e}"]`)??void 0}sync(e=!1){const t=this.target?.read();if(!this.set||!t)return;const i=this.target.context(),n=e?null:this.container.getRootNode().activeElement;for(const s of this.set.parameters){const r=this.field(s.key);if(!r)continue;const a=r.closest("label, .parameter-row")??r;a.hidden=s.visibleWhen!==void 0&&!s.visibleWhen(t,i);const l=Tn.read(t,s.key);if(s.type==="number"){const c=r;c!==n&&(c.value=typeof l=="number"?Gs.shown(l,s):"");const h=Gs.boundsOf(s,t,i);c.min=String(h.min),c.max=String(h.max);const d=s.effective?.(t,i);c.placeholder=d!==void 0?Gs.shown(d,s):this.read(s.placeholder)??"",c.classList.toggle("parameter-derived",l===void 0)}else if(s.type==="choice"){const c=r,h=s.optionsOf?.(t,i)??s.choices;if([...c.options].filter(d=>d.value!=="").map(d=>d.value).join(`
45
45
  `)!==h.map(d=>d.value).join(`
46
46
  `)&&c.replaceChildren(...s.required?[]:[new Option("—","")],...h.map(d=>new Option(this.read(d.label)??d.value,d.value))),c!==n&&(c.value=typeof l=="string"&&h.some(d=>d.value===l)?l:s.required?c.options[0]?.value??"":""),!s.required){const d=s.effective?.(t,i),u=h.find(p=>p.value===d);c.options[0].textContent=u?this.read(u.label)??u.value:this.read(s.empty)??"—"}}else if(s.type==="boolean"){const c=r;c!==n&&(c.checked=l===!0)}else if(s.type==="colour"){const c=r;c!==n&&(c.value=Gs.swatchOf(l,s.fallback??"#808080"))}else if(s.type==="set")this.syncSet(s,r,t,i);else if(s.type==="said"){const c=r;c!==n&&(c.value=this.values?.said().read(Tn.read(t,s.key))??""),this.markMissing(s,c)}else{const c=r;c!==n&&(c.value=typeof l=="string"?l:"",c.classList.remove("invalid"),c.removeAttribute("aria-invalid"))}}for(const s of this.container.querySelectorAll("fieldset.parameter-group"))s.hidden=[...s.querySelectorAll("label, .parameter-row")].filter(r=>r.parentElement===s).every(r=>r.hidden)}fieldOf(e){const t=document.createElement("label"),i=this.read(e.hint);i&&(t.title=i);const n=document.createElement("span");n.textContent=this.read(e.label)??e.key,t.append(n," ");let s;if(e.type==="choice"){const r=document.createElement("select");this.identify(r,e),e.required||r.append(new Option("—","")),r.append(...e.choices.map(a=>new Option(this.read(a.label)??a.value,a.value))),r.addEventListener("input",()=>this.write(e,r.value===""?void 0:r.value)),t.append(r),this.enhance?.(e,r)}else if(e.type==="set"){const r=document.createElement("div");return this.identify(r,e),r.className="parameter-set",r.addEventListener("input",()=>{const a=[...r.querySelectorAll("input:checked")].map(l=>l.value);this.write(e,a.length>0?a:void 0)}),this.setRow(e,r)}else if(e.type==="boolean"){const r=document.createElement("input");r.type="checkbox",this.identify(r,e),r.addEventListener("input",()=>this.write(e,r.checked?!0:e.required?!1:void 0)),t.prepend(r),t.append(" ")}else{const r=document.createElement("input");this.identify(r,e),r.autocomplete="off",e.type==="number"?(r.type="number",r.min=String(e.min),r.max=String(e.max),r.step=String(e.step),s=e.unit,r.addEventListener("input",()=>{const a=r.value.trim();if(a==="")return e.required?void 0:this.write(e,void 0);const l=Number(a);Number.isFinite(l)&&this.write(e,l)})):e.type==="colour"?(r.type="color",r.addEventListener("input",()=>this.write(e,r.value))):e.type==="said"?(r.type="text",r.placeholder=this.read(e.placeholder)??"",r.addEventListener("input",()=>{const a=this.target?.read(),l=this.values;!a||!l||(this.write(e,l.said().write(Tn.read(a,e.key),r.value,l.writingLanguage())),this.markMissing(e,r))})):(r.type="text",r.placeholder=this.read(e.placeholder)??"",r.addEventListener("input",()=>{const a=e.required||e.validate?r.value.trim():r.value,l=this.target?.read(),c=l!==void 0&&(e.required===!0&&a===""||a!==""&&e.validate?.(a,l,this.target.context())===!1);r.classList.toggle("invalid",c),c?r.setAttribute("aria-invalid","true"):r.removeAttribute("aria-invalid"),!c&&this.write(e,a===""?void 0:a)}),r.addEventListener("change",()=>{if(!r.classList.contains("invalid"))return;r.classList.remove("invalid"),r.removeAttribute("aria-invalid");const a=this.target?.read(),l=a===void 0?void 0:Tn.read(a,e.key);r.value=typeof l=="string"?l:""})),t.append(r)}return s&&t.append(` ${s}`),t}markMissing(e,t){e.type!=="said"||!e.required||(t.classList.toggle("invalid",t.value===""),t.setAttribute("aria-invalid",String(t.value==="")))}setRow(e,t){const i=document.createElement("div");i.className="parameter-row";const n=this.read(e.hint);n&&(i.title=n);const s=document.createElement("span");return s.textContent=this.read(e.label)??e.key,i.append(s,t),i}syncSet(e,t,i,n){if(e.type!=="set")return;const s=Tn.read(i,e.key),r=new Set(Array.isArray(s)?s:[]),a=e.options(i,n);if(a.length===0){t.textContent=this.read(e.empty)??"";return}[...t.querySelectorAll("input")].map(c=>c.value).join(`
47
47
  `)===a.map(c=>c.value).join(`
@@ -54,10 +54,14 @@ rr0-date-input [hidden] { display: none !important; }
54
54
  range in the rationale. That is "derived", not "stated".`,file:`Sizes are ANGULAR, in degrees (\`angular\`: {widthDeg, heightDeg}), never metric: the format stores
55
55
  no physical size, because an observer perceives an angle and a size only follows from a distance
56
56
  nobody measured. Convert the comparisons an account gives (the full Moon and the Sun about 0.5
57
- degrees across, a thumbnail at arm's length about 1.5, a fist about 10), or measure them: a
57
+ degrees across, a thumbnail at arm's length about 1.5, a one-euro coin about 1.5 at arm's length,
58
+ a tennis ball about 6 if held out at arm's length, a fist about 10), or measure them: a
58
59
  drawing made on a photograph of the place, with a known field of view or a landmark of known
59
60
  bearing, gives degrees per pixel. Where nothing gives a size, work from what the scene implies
60
- and put the range in the rationale.`},{draft:'Directions are `aim`: `azimuthDeg` clockwise from true north (north 0, east 90, south 180,\n west 270) and `altitudeDeg` above the horizon (horizon 0, zenith 90). Derive them where the\n geography allows — an observer driving towards a named village is looking along that bearing, and a\n phenomenon "barring the road" is on it. Where nothing bears on the altitude, assume something low\n and plausible rather than leaving the phenomenon undrawable, and mark it "assumed".',file:"A shape is PLACED by `aim`, the direction of its centre in the observer's sky: `azimuthDeg`\n clockwise from true north and `altitudeDeg` above the horizon. Not the way the observer faced,\n which is the pose's heading and pitch. `bounds` (pixels) is recomputed on load from `aim` and\n `angular`; leave it out. `angle` tilts the shape, in radians, positive clockwise on screen.\n Derive directions from the geography where it allows (a map, the bearing of a road, a landmark\n the observer named); where nothing bears on the altitude, assume something low and plausible and\n mark it \"assumed\"."},{draft:`Times are the local legal time at the place. State the IANA \`timeZone\` the observer's own clock
61
+ and put the range in the rationale. Never inflate: an angle below one pixel is invisible, and
62
+ that is a fact about the account to report, not something to enlarge so that the shape shows.
63
+ If another document gives a larger figure (an interview years later), you may take it, but say
64
+ which one you took and why.`},{draft:'Directions are `aim`: `azimuthDeg` clockwise from true north (north 0, east 90, south 180,\n west 270) and `altitudeDeg` above the horizon (horizon 0, zenith 90). Derive them where the\n geography allows — an observer driving towards a named village is looking along that bearing, and a\n phenomenon "barring the road" is on it. Where nothing bears on the altitude, assume something low\n and plausible rather than leaving the phenomenon undrawable, and mark it "assumed".',file:"A shape is PLACED by `aim`, the direction of its centre in the observer's sky: `azimuthDeg`\n clockwise from true north and `altitudeDeg` above the horizon. Not the way the observer faced,\n which is the pose's heading and pitch. `bounds` (pixels) is recomputed on load from `aim` and\n `angular`; leave it out. `angle` tilts the shape, in radians, positive clockwise on screen.\n Derive directions from the geography where it allows (a map, the bearing of a road, a landmark\n the observer named); where nothing bears on the altitude, assume something low and plausible and\n mark it \"assumed\"."},{draft:`Times are the local legal time at the place. State the IANA \`timeZone\` the observer's own clock
61
65
  was on ("Europe/Paris", "America/Denver") and NEVER \`utcOffsetHours\`: the editor works the
62
66
  offset out from that zone's own historical rules at that date, out of the platform's IANA
63
67
  database (see TimeZones.offsetHoursAt), and it is right about summer time as it was then rather
@@ -70,7 +74,17 @@ rr0-date-input [hidden] { display: none !important; }
70
74
  from the number alone, and without it approximates the offset from the longitude, which knows
71
75
  nothing of legal time. A time corrected by the investigator (a clock found fast) is "derived".`},{draft:'Duration: `durationSeconds` is the one length the reconstruction is played at, a bare number. When the\n account gives a vague length ("a few minutes", "five to ten"), write what was said in `durationText`,\n an ISO 8601 duration with the doubt EDTF has (`"PT3M~"`, about three minutes) or a range\n (`"PT5M/PT10M"`), AND the length to play at in `durationSeconds` (the duration, or the middle of the\n range), marked "assumed". Or give `endTime`, whose `raw` takes the approximation suffix:\n {"raw": "1974-05-20T19:02~", "year": 1974, "month": 5, "day": 20, "hour": 19, "minute": 2}.',file:'Duration: `durationSeconds` is the one length the reconstruction is played at, a bare number. For a\n vague length ("a few minutes"), state it in `durationText` (an ISO 8601 duration with a doubt, `"PT3M~"`, or a\n range, `"PT5M/PT10M"`) and put the length chosen to play at in `durationSeconds`, with its provenance. Use\n `durationSeconds` alone for a length that was timed or bounded.'},{draft:`Give a keyframe only for a moment the account actually distinguishes — where it arrived, where it
72
76
  went, when it changed. Two to four is a normal first draft, and one is right for a phenomenon
73
- that never moved. Interpolation between them is the player's job.`,file:'`timeline.keyframes` is [{t, shapes: [{sourceId, shape}]}], t in milliseconds from the start of\n the recording. Give a keyframe only for a moment the account distinguishes (where it arrived,\n when it changed, where it went); the player interpolates between them. A keyframe need only\n restate what changes: every field a shape leaves out is held from the keyframe before. To make a\n shape vanish, keyframe it at `transparency: 1`. `milestones` ([{t, label, note}]) name the\n moments the account itself names ("A", "B"), shown on the seek bar.'},{draft:'For each shape give only `kind` ("oval" or "polygon"), `title` (what the observer called it,\n in their language), `angular` and `aim`. Never a pixel box, a transparency or a halo: those\n are how a drawing is painted, they are derived from the angle and the direction on loading, and\n values for them would be numbers no one observed and no one could check.',file:'A shape is `kind` "oval" or "polygon" (a polygon\'s `points` are pixels from the top-left of its\n box, spanning the box: they are stretched with it), `title` (what the observer called it),\n `angular` and `aim`. Add `color`, `haloScale` (a glow around it), `brightness` (0 a light\n you can look at, 1 one you cannot) and `blur` (0 hard edges, 1 none) only when the account\n describes them; left out, they assert nothing.'},{draft:"NEVER write `description`. It is the account you were just given: it is what the observer said,\n it does not change because somebody read it, and anything you would put there instead belongs in\n the numbers the reading produced. Leave the field out of your answer entirely.",file:`\`description\` is the account itself, in prose: what the observer said, in their words where the
77
+ that never moved. Interpolation between them is the player's job.`,file:`\`timeline.keyframes\` is [{t, shapes: [{sourceId, shape}]}], t in milliseconds from the start of
78
+ the recording. Give a keyframe only for a moment the account distinguishes (where it arrived,
79
+ when it changed, where it went); the player interpolates between them. A keyframe need only
80
+ restate what changes: every field a shape leaves out is held from the keyframe before. To make a
81
+ shape vanish, keyframe it at \`transparency: 1\`. There is no field for blinking: write a flash as
82
+ keyframes a few milliseconds apart, per \`sourceId\` (interpolation is per source). A rotation of more
83
+ than half a turn between two keyframes needs intermediate keyframes with unrolled angles, or the
84
+ shape turns the short way round. Motion the account calls continuous or slowing down (a landing,
85
+ a take-off) needs a path sampled about every 100 ms and eased, not six keyframes joined by
86
+ straight lines, whose speed jumps at each one. \`milestones\` ([{t, label, note}]) name the
87
+ moments the account itself names ("A", "B"), shown on the seek bar.`},{draft:'For each shape give only `kind` ("oval" or "polygon"), `title` (what the observer called it,\n in their language), `angular` and `aim`. Never a pixel box, a transparency or a halo: those\n are how a drawing is painted, they are derived from the angle and the direction on loading, and\n values for them would be numbers no one observed and no one could check.',file:'A shape is `kind` "oval" or "polygon" (a polygon\'s `points` are stretched with its box: when you leave\n `bounds` out, as you should, write them as FRACTIONS of the box from 0 to 1, e.g.\n {"x": 0.26, "y": 0.98}; values written as pixels (0-100) are multiplied by the box\'s width and\n give a giant shape), `title` (what the observer called it),\n `angular` and `aim`. Add `color`, `haloScale` (a glow around it), `brightness` (0 a light\n you can look at, 1 one you cannot) and `blur` (0 hard edges, 1 none) only when the account\n describes them; left out, they assert nothing. `brightness` above 0 adds a dazzle veil, a large\n ringed halo: leave it at 0 on anything that is not a light.'},{draft:"NEVER write `description`. It is the account you were just given: it is what the observer said,\n it does not change because somebody read it, and anything you would put there instead belongs in\n the numbers the reading produced. Leave the field out of your answer entirely.",file:`\`description\` is the account itself, in prose: what the observer said, in their words where the
74
88
  documents quote them, one string or one per language ({"fr": ..., "en": ...}). Not your
75
89
  analysis: measurements, contradictions and reasoning belong in the values, their rationales,
76
90
  and your report.`},{draft:`\`tags\` are stored in English whatever the account's language, because two recordings that share
@@ -80,7 +94,27 @@ rr0-date-input [hidden] { display: none !important; }
80
94
  a tag have to match on it. Reuse the vocabulary already in use where it fits ({tags}); pass
81
95
  classification codes and case references through unchanged ("RR3", "NL", "GEIPAN D1").
82
96
  \`paralysis\` changes the replay (the view is held still): use it only when the account says the
83
- observer could not move.`},{draft:"`decor` is the scenery around the observer, and `eastM`/`northM` are metres from where they\n stand. Something the observer is INSIDE — their own car, their kitchen — goes at 0,0 and carries\n `observerSide` (\"front-left\" for a European driver's seat), which is what puts the viewpoint\n within it. Anything they are NOT inside must be placed away from 0,0, or it is drawn on the lens.\n Give `sizeM` in metres ({widthM, lengthM, heightM}: about 1.7 x 4.2 x 1.4 for a 1970s family\n car) or leave it out for the primitive's own size. Add decor only for what the account names: an\n unmentioned streetlight is scenery nobody reported.",file:'`decor` is the scenery the account names, and `eastM`/`northM` are metres from where the\n observer stood at the start. Something the observer is INSIDE (their car) goes at 0,0 and carries\n `observerSide` ("front-left" for a European driver\'s seat); anything else must be away from\n 0,0, or it is drawn on the lens. Give `sizeM` ({widthM, lengthM, heightM}) where known. The\n relief and the roads of the map are drawn for you: add decor for what the account uses (the wood the phenomenon stood before, the car, the other people present, as kind\n "observer"). When the account says the phenomenon went behind something, that object\'s\n `occludesSourceIds` names the shape. Roads the map lacks go in `roads`.'},{draft:"`observerTrack` is where the observer stood and which way they faced, over time. One pose is\n normally enough. `headingDeg` is the direction they were LOOKING, same convention as `aim`,\n and it is what makes a shape's azimuth mean anything — an observer driving towards a named village\n faces that bearing. `elevationM` is metres above the local ground (0 for someone standing on it;\n the eye's own height is added), `pitchDeg` 0 for someone looking level, `fovDeg` about 60 for\n the naked eye.",file:'`observerTrack` ({keyframes: [{t, pose}]}) is where the observer stood and which way they looked,\n over time: `lat`, `lng`, `elevationM` (metres above the local ground, 0 for someone standing\n on it: the eye\'s own height is added), `headingDeg` and `pitchDeg` (the direction they LOOKED,\n same conventions as `aim`), `fovDeg` (the vertical field shown, about 60 for the naked eye).\n A walk is a series of poses; a head turned towards the phenomenon is two poses a fraction of a\n second apart. `instrument` is "eye" unless a camera was used.'},{draft:'`account` is about the OBSERVERS and how their account travelled, not about the phenomenon.\n An account naming who was there says it in `observerOccupation` ("boulanger"), in their own\n words and never as a level, and each other person present is a `decor` object of kind\n "observer". But `source` and `followedUp` say how the report was OBTAINED, which no account\n of a sighting can tell you: leave them out rather than guessing, unless the text itself says an\n investigator came, or that it is a press cutting.',file:'`account` is about the observer and how the account travelled: `observerAgeYears` (at the\n time), `observerOccupation` (in their words), `source` (how it reached whoever wrote the\n recording: on-site, interview, telephone, questionnaire, letter, social-media, press) and `followedUp`\n (whether they were gone back to). Where the account can be read goes in `sources`, in the\n shape of an RR0 source: [{type ("book" | "article", none for a web page or a post), title,\n authors, url, publication: {publisher, time}, index}]. Always give the documents you worked from. Each other person present is a `decor` object of kind\n "observer".'},{draft:'Silence is a statement. An observer who says the thing was silent is not an observer who said nothing\n about sound: write a `soundTrack` whose keyframe holds a sound of kind "none", and mark it\n "stated". An account that simply never mentions sound gets no soundTrack at all.',file:'Absent is not zero. An observer who says the thing was silent gets a `soundTrack` whose keyframe\n holds a sound of kind "none"; an account that never mentions sound gets no soundTrack. The same\n holds for the weather: `weatherTrack` states what the observer saw of the sky (cover, rain,\n wind); when it comes from a record (ERA5, a METAR, a station), `weatherSource` names it.'},{draft:`\`lightPollution\` is how bright the night sky of the place is, towns and all: the zenith of a
97
+ observer could not move.`},{draft:"`decor` is the scenery around the observer, and `eastM`/`northM` are metres from where they\n stand. Something the observer is INSIDE — their own car, their kitchen — goes at 0,0 and carries\n `observerSide` (\"front-left\" for a European driver's seat), which is what puts the viewpoint\n within it. Anything they are NOT inside must be placed away from 0,0, or it is drawn on the lens.\n Give `sizeM` in metres ({widthM, lengthM, heightM}: about 1.7 x 4.2 x 1.4 for a 1970s family\n car) or leave it out for the primitive's own size. Add decor only for what the account names: an\n unmentioned streetlight is scenery nobody reported.",file:`\`decor\` is the scenery the account names, and \`eastM\`/\`northM\` are metres from where the
98
+ observer stood at the start. Something the observer is INSIDE (their car) goes at 0,0 and carries
99
+ \`observerSide\` ("front-left" for a European driver's seat); anything else must be away from
100
+ 0,0, or it is drawn on the lens. Give \`sizeM\` ({widthM, lengthM, heightM}) where known. The
101
+ relief and the roads of the map are drawn for you: add decor for what the account uses (the wood the phenomenon stood before, the car, the other people present, as kind
102
+ "observer"). When the account says the phenomenon went behind something, that object's
103
+ \`occludesSourceIds\` names the shape. The converse is a trap: a decor object that stands on a
104
+ shape's line of sight WITHOUT declaring it is read as "the phenomenon passed in front of it", and the
105
+ distance is capped by its own (a car 5 m away gave "at most 0.05 m" for a 6 m object). A distance is
106
+ an inequality: in front of X is less than X's distance, behind X is at least that. A track's
107
+ \`altitudeM\` is metres above the GROUND under the object, not above the observer (the eye is
108
+ at \`elevationM\` + 1.6 m). Draw only what you can place: never a building or garage whose plan you do
109
+ not have, and no real surroundings when the place is only known to about 0.1 degree; say so
110
+ instead. Roads the map lacks go in \`roads\`. An obstacle that explains why the account describes what it does (a
111
+ tree line the phenomenon went behind) may be added from a survey or open data, with its
112
+ provenance. A decor of kind "entity" counts as seen; a companion who saw nothing is an
113
+ "observer", placed only where the account puts them: someone in another vehicle whose type and
114
+ position are unknown is left out and listed in your report, not drawn as a pedestrian in the road.
115
+ The eye is 1.6 m above the ground plus the pose's \`elevationM\`: for a high seat (a tractor cab, a
116
+ lorry), raise \`elevationM\` by the difference. A seat that is not a car's (a central seat) is
117
+ \`observerSide\` "front". Standing decor sits on the ground; only a \`track\` lifts it.`},{draft:"`observerTrack` is where the observer stood and which way they faced, over time. One pose is\n normally enough. `headingDeg` is the direction they were LOOKING, same convention as `aim`,\n and it is what makes a shape's azimuth mean anything — an observer driving towards a named village\n faces that bearing. `elevationM` is metres above the local ground (0 for someone standing on it;\n the eye's own height is added), `pitchDeg` 0 for someone looking level, `fovDeg` about 60 for\n the naked eye.",file:'`observerTrack` ({keyframes: [{t, pose}]}) is where the observer stood and which way they looked,\n over time: `lat`, `lng`, `elevationM` (metres above the local ground, 0 for someone standing\n on it: the eye\'s own height is added), `headingDeg` and `pitchDeg` (the direction they LOOKED,\n same conventions as `aim`), `fovDeg` (the vertical field shown, about 60 for the naked eye).\n A walk is a series of poses; a head turned towards the phenomenon is two poses a fraction of a\n second apart. An observer who follows a moving phenomenon looks 0.15 to 0.2 s behind it, so keep\n the gaze on the same path, sampled as densely, or it leaves the field. `instrument` is "eye" unless a camera was used.'},{draft:'`account` is about the OBSERVERS and how their account travelled, not about the phenomenon.\n An account naming who was there says it in `observerOccupation` ("boulanger"), in their own\n words and never as a level, and each other person present is a `decor` object of kind\n "observer". But `source` and `followedUp` say how the report was OBTAINED, which no account\n of a sighting can tell you: leave them out rather than guessing, unless the text itself says an\n investigator came, or that it is a press cutting.',file:'`account` is about the observer and how the account travelled: `observerAgeYears` (at the\n time), `observerOccupation` (in their words), `source` (how it reached whoever wrote the\n recording: on-site, interview, telephone, questionnaire, letter, social-media, press) and `followedUp`\n (whether they were gone back to). Where the account can be read goes in `sources`, in the\n shape of an RR0 source: [{type ("book" | "article", none for a web page or a post), title,\n authors, url, publication: {publisher, time}, index}]. Always give the documents you worked from. Each other person present is a `decor` object of kind\n "observer".'},{draft:'Silence is a statement. An observer who says the thing was silent is not an observer who said nothing\n about sound: write a `soundTrack` whose keyframe holds a sound of kind "none", and mark it\n "stated". An account that simply never mentions sound gets no soundTrack at all.',file:'Absent is not zero. An observer who says the thing was silent gets a `soundTrack` whose keyframe\n holds a sound of kind "none"; an account that never mentions sound gets no soundTrack. The same\n holds for the weather: `weatherTrack` states what the observer saw of the sky (cover, rain,\n wind); when it comes from a record (ERA5, a METAR, a station), `weatherSource` names it.'},{draft:`\`lightPollution\` is how bright the night sky of the place is, towns and all: the zenith of a
84
118
  moonless night in magnitudes per square arcsecond (22 a natural sky, about 19 a suburb, 17 a city
85
119
  centre). Write it only from a figure: a Sky Quality Meter reading the observer gives ("stated"),
86
120
  or the World Atlas's "SQM" value for the place (Falchi et al. 2016), marked "derived" with the
@@ -93,7 +127,36 @@ rr0-date-input [hidden] { display: none !important; }
93
127
  and takes stars away; never write a brighter sky than the source gives.`},{file:`The observer's own estimate in metres ("60 m long, 175 m away, 10 m up") is not an observation
94
128
  but a conclusion: it goes in \`interpretation\` (bodies in metres, see the format page), never in
95
129
  the shapes. When it contradicts the angles the observer measured, keep it anyway and say so in
96
- your report: the player's comparison is what shows the contradiction.`}];static text(e){return Hu.RULES.map(t=>t[e]).filter(t=>t!==void 0).map((t,i)=>`${i+1}. ${t.replace("{tags}",Hu.KNOWN_TAGS.join(", "))}`).join(`
130
+ your report: the player's comparison is what shows the contradiction.`},{file:`Place the observer from the account's own description (the road, the property, the bearing of a
131
+ landmark), not from the nearest village; when only a town centre is known, mark the place
132
+ "assumed", not "derived". A shape drawn from a description (a crescent "tips down") rather than measured on the observer's
133
+ sketch is "assumed", whole, in its envelope. Check coordinates before trusting them: a file placed 2.4 km from a field
134
+ that photographs showed to be flat sat on an 11 % slope; a memorial is not the place where
135
+ something happened. The \`{value, basis, rationale}\` envelope may wrap the whole \`{lat, lng}\`. When the account gives
136
+ only a distance and a direction from a known point ("2 km west of the village"), move from that
137
+ point by that bearing and distance, mark the result "assumed", and state the offset and the point it
138
+ started from in the rationale: a bare village centre would be wrong, and a shifted one is honest only
139
+ if it says it was shifted.`},{file:`Use the sky the account cites to pin and to check the time (a star at a stated azimuth and
140
+ altitude, the Moon "up" or "down", a sunset), and report the mismatches; if you have no way to
141
+ compute the sky, say the check was approximate or not made, never that it passed; do not correct the
142
+ account to fit the computed sky, and do not delete a value that contradicts it. Check that a
143
+ sentence is testimony before keeping it: "the Sun was still below the horizon" in a summary is not
144
+ something the observer said. With several observers, share one clock and give each their own offset.
145
+ Take the legal offset of THAT year, not today's (a weather service answering with \`timezone=auto\`
146
+ gives today's rules).`},{file:`Do not invent a difference between observers, and do not flatten the ones stated: use a ratio
147
+ an observer annotated on their own drawing for that observer only, and leave out what nobody
148
+ said. The light-pollution atlas dates from 2015: do not apply it to an event decades earlier; omit
149
+ the field and say so. Once written, cross-check your numbers against independent figures in the
150
+ documents (a table of distances, a runway's axis), and report the residuals.`},{file:`Words: the person is an "observer" (a human and their instruments), what they gave is an
151
+ "account", what is seen is a "phenomenon". Never "witness", "testimony", "object", "craft", "flew" or
152
+ "landed" in a title, a summary, a rationale or your report, except in the observer's own words:
153
+ naming an object already concludes there was one, and excludes a halo, a planet or a reflection.`},{file:`Before handing over, project where each shape and decor object should appear and compare with what
154
+ the player draws, before touching any value: "misplaced" and "hidden by something" look alike, and
155
+ a decor 8 m away that looked wrong was right and merely covered. Look at a close-up of the key
156
+ moment instead of concluding from numbers. A grey or black scene is more often "not loaded" or a
157
+ camera inside a wall than a data fault. Then list, in your report, the questions whose answers would
158
+ replace each "assumed" value (height at the start, timed duration, which way the head turned, standing
159
+ point, what was behind), because that list is what an investigator can act on.`}];static text(e){return Hu.RULES.map(t=>t[e]).filter(t=>t!==void 0).map((t,i)=>`${i+1}. ${t.replace("{tags}",Hu.KNOWN_TAGS.join(", "))}`).join(`
97
160
  `)}}class Gu{static of(e){const{recording:t}=Un.strip(e),{timeline:i,...n}=t,s=(i?.keyframes??[]).map(a=>Gu.keyframe(a)),r=Object.entries(n).filter(([a,l])=>a!=="version"&&l!==void 0);if(!(r.length===0&&s.every(a=>a.shapes.length===0)))return{...Object.fromEntries(r),...s.length>0?{timeline:{keyframes:s}}:{}}}static keyframe(e){return{t:e.t,shapes:e.shapes.map(t=>Gu.shape(t.sourceId,t.shape))}}static shape(e,t){const i=t??{},n=i.angular,s=i.aim;return{sourceId:e,kind:i.kind??"oval",...i.title===void 0?{}:{title:i.title},...n?.widthDeg===void 0||n.heightDeg===void 0?{}:{angular:{widthDeg:n.widthDeg,heightDeg:n.heightDeg}},...s?.azimuthDeg===void 0||s.altitudeDeg===void 0?{}:{aim:{azimuthDeg:s.azimuthDeg,altitudeDeg:s.altitudeDeg}}}}}const Qv={name:"draft_recording",description:"Record what the account states, what justifies each value, and what it leaves out.",input_schema:{type:"object",properties:{recording:{type:"object",description:"The recording, in the format given above. Partial: only the fields the account actually states."},claims:{type:"array",description:"One entry per value in `recording`. EVERY value needs one: a value with no claim is a value nobody can check.",items:{type:"object",properties:{path:{type:"string",description:'Where the value sits in `recording`, dot-joined, array indices as steps: "time.hour", "place.0.lat", "timeline.keyframes.1.shapes.0.shape.angular.widthDeg".'},basis:{type:"string",enum:["stated","derived","assumed"],description:'"stated": the observer said it. "derived": worked out from what they said plus something checkable. "assumed": chosen so the reconstruction has a value at all, on nothing they said.'},rationale:{type:"string",description:`For "stated", the account's own words, copied verbatim, never a paraphrase. For "derived", the working, with the numbers in it. For "assumed", what the guess was chosen for and how wrong it could be.`}},required:["path","basis","rationale"]}},gaps:{type:"array",description:"What nothing could settle, not even a guess worth making — one short sentence each, in the reader's language. Usually empty.",items:{type:"string"}}},required:["recording","claims","gaps"]}},VS=`You are reading an observer's account of an aerial sighting and reconstructing it in the
98
161
  recording format of UFO@home, a tool that replays what an observer reported seeing, from where they
99
162
  stood, under the real sky of that moment.
@@ -2952,7 +3015,7 @@ canvas[data-cursor="rotate"] {
2952
3015
  `;class Yl{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 Yl(t)}static TRAVEL_M=50;get travels(){return this.spanM>Yl.TRAVEL_M}get moved(){return this.spanM>Yl.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(yt(t,e.east,t,e.west).x),Math.abs(yt(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:fs(0,-s,i,n).lat,south:fs(0,s,i,n).lat,east:fs(s,0,i,n).lng,west:fs(-s,0,i,n).lng}}get box(){const 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 ws{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)>ws.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new ws(Math.max(1-(e.instrument.stabilization??0),ws.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,a,l,c,h]=ws.HZ;return{eastM:i*ws.SWAY_M*(.7*n(s,.3)+.3*n(l,1.9)),northM:i*ws.SWAY_M*(.6*n(a,2.2)+.4*n(c,.8)),upM:i*ws.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*ws.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(l,2.7)),pitchDeg:i*this.rotationPassed*ws.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*ws.DRIFT_ROLL_DEG*n(s,2.9)}}}class Yt{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=Yl.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],a=t.points[s],l=(a.t-r.t)/1e3;if(l<=0)continue;const c=yt(a.lat,a.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/l,f=Yt.stepHzFor(p);i.push({startMs:r.t,endMs:a.t,speedMPerS:p,eastUnit:u>0?h/u:0,northUnit:u>0?d/u:0,stepHz:f,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=f*l}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new Yt(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const n=Yt.of(e)?.offsetAt(t)??Yt.STILL;return i?n:Yt.add(n,ws.of(e)?.offsetAt(t))}static stepHzFor(e){return e<Yt.SLOWEST_WALK_M_PER_S||e>Yt.FASTEST_WALK_M_PER_S?0:Yt.REFERENCE_STEP_HZ*Math.pow(e/Yt.REFERENCE_SPEED_M_PER_S,Yt.CADENCE_EXPONENT)}offsetAt(e){return Yt.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/Yt.REFERENCE_SPEED_M_PER_S,n=(a,l,c,h)=>{if(a<0||a>Yt.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/Yt.JOLT_DECAY_S)*Math.sin(2*Math.PI*Yt.JOLT_HZ*d),p=h*l*i*u;return{eastM:p*t.eastUnit,northM:p*t.northUnit,upM:-Math.abs(p)*.3,rollDeg:0,pitchDeg:-h*c*i*u*this.rotationPassed,yawDeg:0}},s=t.rampsOut?n(e-t.endMs,Yt.STOP_LURCH_M,Yt.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=t.rampsIn?n(e-t.startMs,Yt.START_LURCH_M,Yt.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 Yt.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(t,e),r=Yt.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*t.speedMPerS/Yt.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:Yt.RISE_M_PER_M_PER_S*t.speedMPerS*s*Math.cos(n),rollDeg:Yt.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:Yt.HEAD_YAW_DEG*a*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,a=Math.min(e.rampsIn?s/n:1,e.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class jS{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 Oo{static sessionDeclared=!1;static unlock(e){if(Oo.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(!(Oo.sessionDeclared||typeof navigator>"u")){Oo.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const e1=.05,t1=.08,i1=2,n1=3,JS=14,QS=.02;class eE{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}}Oo.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,e1);for(const{param:s,ratio:r}of e.pitch)s.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),n,e1)}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 a=e.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[n,s,a],sources:[i,r],volumeParam:a.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 a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:t,nodes:[a],sources:[r],volumeParam:a.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*i1),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*i1),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*n1),e.sampleRate),i=t.getChannelData(0),n=Math.max(1,Math.floor(QS*e.sampleRate)),s=Math.round(n1*JS);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),l=.4+Math.random()*.6;for(let c=0;c<n&&a+c<i.length;c++)i[a+c]=Math.max(i[a+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,t1/3);const n=i+t1;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 Ze{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=Ze.outline(Ze.BOOKMARK);static MILESTONES_ON=Ze.solid(Ze.BOOKMARK);static PICTURES_OFF=Ze.outline(`${Ze.PICTURE}${Ze.PICTURE_HILLS}`);static PICTURES_ON=Ze.solid(`${Ze.PICTURE}${Ze.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=Ze.outline(`${Ze.TRACE_LINE}${Ze.TRACE_MARK}`);static TRACES_ON=Ze.solid(`${Ze.TRACE_LINE}${Ze.TRACE_MARK}`);static MAP_OFF=Ze.outline(`${Ze.PIN}${Ze.PIN_HOLE}`);static MAP_ON=Ze.solid(`${Ze.PIN}${Ze.PIN_HOLE}`);static SHARE=Ze.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=Ze.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=Ze.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=Ze.svg("M7.4 5v14l11-7z");static PAUSE=Ze.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=Ze.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=Ze.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=Ze.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=Ze.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}function Po(o){return[...o].sort((e,t)=>e.t-t.t)}function Kp(o,e){let t;for(const i of Po(o)){if(i.t>e)break;t=i}return t}const Zp=Math.PI/180,Zh=180/Math.PI;class $s{constructor(e,t,i){this.kind=e,this.canvasHeightPx=t,this.fovDeg=i;const n=i*Zp/2;this.focalPx=e==="equidistant"?t/2/n:t/2/Math.tan(n)}focalPx;static of(e,t,i){return new $s(e.projection,t,i)}degToPx(e){const t=e*Zp;return this.kind==="equidistant"?this.focalPx*t:2*this.focalPx*Math.tan(t/2)}pxToDeg(e){return this.kind==="equidistant"?e/this.focalPx*Zh:2*Math.atan(e/(2*this.focalPx))*Zh}angleDegToRadiusPx(e){const t=e*Zp;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*Zh:Math.atan(e/this.focalPx)*Zh}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(mt.angularWidthDeg(e))}}class en{static fovOf(e,t){return ot(e,t)?.fovDeg??Ut.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 a=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*a,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)<en.UNMOVED_PX&&Math.abs(s.y-t.bounds.y)<en.UNMOVED_PX)return t;const r=this.aimFrom(e,i,n,t.bounds);return r?{...t,aim:r}:t})}static UNMOVED_PX=.01;static aimOf(e,t,i){const n=$s.of(e.instrument,mt.CANVAS_HEIGHT_PX,this.fovOf(e,t));return this.aimFrom(e,n,ot(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),a=t.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}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),a=this.shortestArc(t.azimuthDeg-s.headingDeg),l=t.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,l)-i.height/2}}static frameCentre(e){return{x:Ut.frameWidthPx(e.instrument,mt.CANVAS_HEIGHT_PX)/2,y:mt.CANVAS_HEIGHT_PX/2}}static shortestArc(e){return(e%360+540)%360-180}static offAxisPx(e,t){return Math.abs(t)>=en.OFF_CANVAS_DEG?Math.sign(t)*en.OFF_CANVAS_PX:e.angleDegToRadiusPx(t)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(e,t,i){const n=Ut.frameWidthPx(t,mt.CANVAS_HEIGHT_PX)/2,s=Ut.frameWidthPx(e.instrument,mt.CANVAS_HEIGHT_PX)/2,r=mt.CANVAS_HEIGHT_PX/2;for(const a of[...e.timeline.allKeyframes]){const l=this.fovOf(e,a.t),c=i?.get(a.t)??l,h=$s.of(t,mt.CANVAS_HEIGHT_PX,c),d=$s.of(e.instrument,mt.CANVAS_HEIGHT_PX,l);e.timeline.addKeyframe(a.t,a.shapes.map(u=>{const{bounds:p}=u.shape,f=p.x+p.width/2-n,g=p.y+p.height/2-r,m=Math.hypot(f,g),v=m===0?1:d.angleDegToRadiusPx(h.radiusPxToAngleDeg(m))/m,b={...p,x:s+f*v-p.width/2,y:r+g*v-p.height/2};return{...u,shape:{...u.shape,bounds:b}}}))}this.toBounds(e)}static eachKeyframe(e,t){const{timeline:i}=e;for(const n of[...i.allKeyframes]){const s=ot(e,n.t),r=this.fovOf(e,n.t),a=$s.of(e.instrument,mt.CANVAS_HEIGHT_PX,r);i.addKeyframe(n.t,n.shapes.map(l=>({...l,shape:t(l.shape,a,s)})))}}}function tE(o){return Un.restore(Lm(o),o.provenance)}function Lm(o){return en.toAngular(o),en.toAim(o),{version:1,id:o.id,time:o.event.time,endTime:o.event.endTime,durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:o.event.place,observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:o.timeline.toJSON(),observerTrack:o.observerTrack.toJSON(),weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:o.decor,milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:o.interpretation}}function iE(o){const{recording:e,provenance:t}=Un.strip(o),i=nE(e);return i.provenance=t,i}function nE(o){const e=[],t=new _p({eventType:"sighting",time:o.time,endTime:o.endTime,durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:o.place,description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},xp.fromJSON(o.timeline,e),o.observerTrack?bh.fromJSON(o.observerTrack):new bh,o.weatherTrack?Mh.fromJSON(o.weatherTrack):new Mh,o.soundTrack?wh.fromJSON(o.soundTrack):new wh,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,o.decor??[],o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(i=>i.pose.exposureSeconds).find(i=>i!==void 0),Po(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);return t.account=o.account,t.sources=o.sources,t.sway=o.sway,t.iso=o.iso,t.lightPollution=o.lightPollution,t.observerMap=o.observerMap,t.vehicle=o.vehicle,t.interpretation=o.interpretation,t.loadIssues=e,en.toBounds(t),en.toPosition(t),t}class uc{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=uc.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=>` ${uc.text(n)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
2953
3016
  ${i.join(`
2954
3017
  `)}`)}}class Os{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,n){if(!Os.isObject(e)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Os.typeOf(e)});return}for(const[s,r]of Object.entries(e)){const a=i?`${i}.${s}`:s,l=t[s];l?this.field(r,l,a,n):n.push({kind:"unknown-key",path:a})}}field(e,t,i,n){if(Os.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):Os.isObject(e)||n.push({kind:"wrong-type",path:i,expected:"object",found:Os.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((s,r)=>{const a=Os.isStated(s)?s.value:s;this.object(a,t.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:Os.typeOf(e)});return;default:typeof e!==t.type&&n.push({kind:"wrong-type",path:i,expected:t.type,found:Os.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return Os.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 zs{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?zs.travelDegOver(e,t,i,i+n*1e3)/s/zs.PIXELS_PER_INSTANT:0,a=zs.flashesOver(e,n)*zs.INSTANTS_PER_FLASH,l=Math.ceil(Math.max(r,a));return l<2?1:Math.min(zs.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 a=zs.directionAt(r,t,i),l=zs.directionAt(r,t,n),c=Math.min(1,Math.max(-1,a.x*l.x+a.y*l.y+a.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=Xs(e,i),s=n.eastM,r=n.altitudeM-t,a=n.northM,l=Math.hypot(s,r,a);return l===0?{x:0,y:1,z:0}:{x:s/l,y:r/l,z:a/l}}}const $M={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",noSound:"No sound recorded",moments:"Moments",moreControls:"More controls",fewerControls:"Fewer controls",showObserverMap:"Show where the observer was",hideObserverMap:"Hide where the observer was",mapImageryUnavailable:"Aerial imagery unavailable",zoomMapIn:"Zoom in",zoomMapOut:"Zoom out",fitMap:"Back to the whole path",placeObserverHere:"Put the observer here",showReferences:"Show the pictures of the place",hideReferences:"Hide the pictures of the place",showTraces:"Show the investigator's lines",hideTraces:"Hide the investigator's lines",referenceOpacity:"Picture opacity",referencesMenu:"Pictures of the place",showMilestones:"Show the account's moments",hideMilestones:"Hide the account's moments",observerHere:"The observer, here",decorHere:"Scenery",recordingIssues:"{count} problem(s) in this recording: it may not play as its author meant",issueTemplates:uc.EN},sE=Object.freeze(Object.defineProperty({__proto__:null,ufoMessages_en:$M},Symbol.toStringTag,{value:"Module"})),YM=Math.PI/180,rE=180/Math.PI,aE=256,qM=19,oE=1.25;function KM(o,e){return 156543.03392*Math.cos(o*YM)/2**e}function ZM(o,e){return KM(o,e)*aE}function lE(o,e){let t=0;for(;t<qM&&ZM(o,t+1)>=e;)t++;return t}function jM(o,e){return ZM(o,e)}function cE(o,e){const t=e*oE;let i=0;for(;i<qM&&KM(o,i)>t;)i++;return i}function iu(o){const e=o*YM;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function JM(o,e,t){const i=2**t;return{x:(o+180)/360*i,y:iu(e)*i}}function QM(o,e,t){const i=iu(o.north),n=iu(o.south);return{x:(e-o.west)/(o.east-o.west),y:(iu(t)-i)/(n-i)}}function hE(o,e,t){const{x:i,y:n}=JM(o,e,t);return{x:Math.floor(i),y:Math.floor(n),z:t}}function dE(o){const e=2**o.z,t=o.x/e*360-180,i=(o.x+1)/e*360-180,n=s1(o.y,e);return{south:s1(o.y+1,e),north:n,west:t,east:i}}function s1(o,e){const t=o/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*rE}function ew(o,e,t,i){const n=hE(o,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 a=r.map(dE),l={south:Math.min(...a.map(c=>c.south)),north:Math.max(...a.map(c=>c.north)),west:Math.min(...a.map(c=>c.west)),east:Math.max(...a.map(c=>c.east))};return{tiles:r,bounds:l}}const uE="#2ec4ff";class so{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=QM(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??uE;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 a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=n.reduce((l,c)=>Math.hypot(c.x-a.x,c.y-a.y)>Math.hypot(l.x-a.x,l.y-a.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),a=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,a,l-c,l+c),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(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:so.MARKER_RADIUS_PX}),t.beginPath(),t.arc(n.x,n.y,so.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 a=yt(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=so.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?so.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 p of n.slice().reverse())this.paintOutlinedText(p,this.width-6,s),s-=11;const r=(e.south+e.north)/2,l=Math.abs(yt(r,e.east,r,e.west).x)/this.width,c=so.SCALE_STEPS_M.find(p=>p/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 Mi{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(Mi.MAX_ZOOM,Math.max(Mi.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=Mi.mercatorY01(t.north),s=Mi.mercatorY01(t.south),r=Mi.mercatorY01(i.north),a=Mi.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+a)/2-n)/(s-n)}keepInView(e,t,i){if(!this.changed)return!1;const n=this.boundsWithin(e),s=Mi.mercatorY01(n.north),r=Mi.mercatorY01(n.south),a=(t.lng-n.west)/(n.east-n.west),l=(Mi.mercatorY01(t.lat)-s)/(r-s);return a>=i&&a<=1-i&&l>=i&&l<=1-i?!1:(this.panBy(.5-a,.5-l),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=Mi.mercatorY01(e.north),n=Mi.mercatorY01(e.south),s=e.east-e.west;return{west:e.west+(this.centerX-t)*s,east:e.west+(this.centerX+t)*s,north:Mi.latitudeAt(i+(this.centerY-t)*(n-i)),south:Mi.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=yt(n,e.east,n,s).x;let a=r;for(const l of t){const{x:c,z:h}=yt(l.lat,l.lng,n,s),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:fs(0,-a,n,s).lat,south:fs(0,a,n,s).lat,east:fs(a,0,n,s).lng,west:fs(-a,0,n,s).lng}}static expand(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=Mi.mercatorY01(e.north),s=Mi.mercatorY01(e.south);return{lat:Mi.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 bs=256,r1=3,pE=32768;class tw{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(yt(i,e.east,i,e.west).x),r=Math.abs(yt(e.north,n,e.south,n).z),a=lE(i,Math.max(s,r)),{tiles:l}=ew(n,i,a,r1),c=r1*bs,h=new Float32Array(c*c),d=l[0];await Promise.all(l.map(p=>this.decodeTileInto(p,d,h,c)));const u=new Float32Array(t.width*t.height);for(let p=0;p<t.height;p++){const f=e.north+(e.south-e.north)*(p/(t.height-1));for(let g=0;g<t.width;g++){const m=e.west+(e.east-e.west)*(g/(t.width-1));u[p*t.width+g]=this.sampleAt(f,m,a,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 a=await createImageBitmap(await r.blob()),l=document.createElement("canvas");l.width=bs,l.height=bs;const c=l.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(a,0,0);const{data:h}=c.getImageData(0,0,bs,bs),d=(e.x-t.x)*bs,u=(e.y-t.y)*bs;for(let p=0;p<bs;p++)for(let f=0;f<bs;f++){const g=(p*bs+f)*4,m=h[g]*256+h[g+1]+h[g+2]/256-pE,v=d+f,b=u+p;i[b*n+v]=m}}sampleAt(e,t,i,n,s,r){const{x:a,y:l}=JM(t,e,i),c=(a-n.x)*bs,h=(l-n.y)*bs,d=Math.max(0,Math.min(r-1,Math.floor(c))),u=Math.max(0,Math.min(r-1,Math.floor(h))),p=Math.min(r-1,d+1),f=Math.min(r-1,u+1),g=c-d,m=h-u,v=s[u*r+d],b=s[u*r+p],M=s[f*r+d],y=s[f*r+p],x=v+(b-v)*g,S=M+(y-M)*g;return x+(S-x)*m}}class Rp{constructor(e,t,i,n){this.width=e,this.height=t,this.samples=i,this.values=n}at(e,t,i=0){return this.values[(t*this.width+e)*this.samples+i]}static parse(e){const t=new DataView(e);if(e.byteLength<8||t.getUint16(0)!==18761||t.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=t.getUint32(4,!0),n=t.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const b=i+2+v*12;s.set(t.getUint16(b,!0),{type:t.getUint16(b+2,!0),count:t.getUint32(b+4,!0),value:t.getUint32(b+8,!0)})}const r=(v,b)=>{const M=s.get(v);if(M===void 0){if(b===void 0)throw new Error(`TIFF without tag ${v}`);return b}return M.type===3?M.value&65535:M.value},a=v=>{const b=s.get(v);if(b===void 0)throw new Error(`TIFF without tag ${v}`);const M=b.type===3?2:4,y=[];if(b.count*M<=4){const x=new DataView(new ArrayBuffer(4));x.setUint32(0,b.value,!0);for(let S=0;S<b.count;S++)y.push(M===2?x.getUint16(S*2,!0):x.getUint32(0,!0))}else for(let x=0;x<b.count;x++)y.push(M===2?t.getUint16(b.value+x*2,!0):t.getUint32(b.value+x*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const l=r(256),c=r(257),h=r(277,1),d=a(258)[0],u=r(339,1)===3;if(!(u&&d===32||!u&&d===8))throw new Error(`Unsupported TIFF samples: ${d} bits`);const p=a(273),f=a(279),g=new Uint8Array(l*c*h*(d/8));let m=0;for(let v=0;v<p.length&&m<g.length;v++){const b=Math.min(f[v],g.length-m);g.set(new Uint8Array(e,p[v],b),m),m+=b}if(m<g.length)throw new Error("Truncated TIFF");return new Rp(l,c,h,u?new Float32Array(g.buffer):g)}}class fE{constructor(e,t,i,n,s){this.heights=e,this.plants=t,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-t/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(e,t,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const l=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);l!==void 0&&(n===void 0||l>n)&&(n=l)}return n}}class at{static METRES_PER_DEGREE=111320;static MIN_BRIDGE_M=4;static DEFAULT_DECK_M=6;static FOOTBRIDGE_DECK_M=2.5;static DECK_MARGIN_M=2.4;static ROAD_MATCH_M=12;static DEFAULT_DECK_HEIGHT_M=4;static MIN_POLE_M=6;static MAX_POLE_M=70;static MAX_SPAN_M=800;static MAX_LINES=16;static BY_VOLTAGE=[{upToKv:25,poleM:11,dropM:1.2,spreadM:.8},{upToKv:70,poleM:20,dropM:3,spreadM:3},{upToKv:100,poleM:22,dropM:3.5,spreadM:3.5},{upToKv:170,poleM:27,dropM:4.5,spreadM:4.5},{upToKv:250,poleM:32,dropM:5.5,spreadM:5.5},{upToKv:1e3,poleM:42,dropM:7,spreadM:7.5}];static toMetres(e,t){const[i,n]=e;return{east:(i-t.lng)*at.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(n-t.lat)*at.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>at.toMetres(i,t))}static bearing(e,t){return(Math.atan2(t.east-e.east,t.north-e.north)*180/Math.PI+360)%360}static distanceToSegment(e,t,i){const n=i.east-t.east,s=i.north-t.north,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*n+(e.north-t.north)*s)/r));return Math.hypot(e.east-(t.east+a*n),e.north-(t.north+a*s))}static bridges(e,t,i,n){const s=e.elevatedRoads.map(a=>({path:at.path(a,t),properties:a.properties})),r=[];for(const a of e.bridges){const l=at.path(a,t);if(l.length<2)continue;const c=l[0],h=l[l.length-1],d=Math.hypot(h.east-c.east,h.north-c.north);if(d<at.MIN_BRIDGE_M)continue;const u={east:(c.east+h.east)/2,north:(c.north+h.north)/2};Math.hypot(u.east,u.north)>i+d/2||r.push({eastM:at.tenth(u.east),northM:at.tenth(u.north),lengthM:at.tenth(d),widthM:at.roadOf(u,s).width,heightM:at.tenth(at.deckHeight(c,h,n)),headingDeg:at.tenth(at.bearing(c,h)%180),...at.roadOf(u,s).name?{name:at.roadOf(u,s).name}:{}})}return r.sort((a,l)=>Math.hypot(a.eastM,a.northM)-Math.hypot(l.eastM,l.northM)),r}static roadOf(e,t){let i;for(const a of t)for(let l=0;l+1<a.path.length;l++){const c=at.distanceToSegment(e,a.path[l],a.path[l+1]);(i===void 0||c<i.distance)&&(i={distance:c,properties:a.properties})}if(i===void 0||i.distance>at.ROAD_MATCH_M)return{width:at.DEFAULT_DECK_M};const n=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(a=>typeof a=="string"&&a.length>0),s=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(s)&&s>0?at.tenth(s+at.DECK_MARGIN_M):i.properties.nature==="Sentier"?at.FOOTBRIDGE_DECK_M:at.DEFAULT_DECK_M;return n?{width:r,name:n}:{width:r}}static deckHeight(e,t,i){if(i===void 0)return at.DEFAULT_DECK_HEIGHT_M;const n=[],s=20;for(let r=4;r<=s-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/s,e.north+(t.north-e.north)*r/s);a!==void 0&&a>=1.5&&n.push(a)}return n.length===0?at.DEFAULT_DECK_HEIGHT_M:(n.sort((r,a)=>r-a),n[Math.floor(n.length/2)])}static lines(e,t,i,n){const s=[];for(const r of e.lines){const a=String(r.properties.voltage??""),l=at.kilovolts(a);if(l===void 0)continue;const c=at.BY_VOLTAGE.find(d=>l<=d.upToKv)??at.BY_VOLTAGE[at.BY_VOLTAGE.length-1],h=at.path(r,t);for(let d=0;d+1<h.length;d++){const u=h[d],p=h[d+1],f=Math.hypot(p.east-u.east,p.north-u.north);if(f<5||f>at.MAX_SPAN_M||at.distanceToSegment({east:0,north:0},u,p)>i)continue;const g=at.poleHeight(u,p,n)??c.poleM;s.push({eastM:at.tenth((u.east+p.east)/2),northM:at.tenth((u.north+p.north)/2),lengthM:at.tenth(f),headingDeg:at.tenth(at.bearing(u,p)),heightM:at.tenth(Math.max(4,g-c.dropM)),poleHeightM:at.tenth(g),acrossM:[-c.spreadM,0,c.spreadM],voltage:a})}}return s.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),s.slice(0,at.MAX_LINES)}static kilovolts(e){const t=/([\d.,]+)\s*kV/i.exec(e);if(t===null)return;const i=Number(t[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(e,t,i){if(i===void 0)return;const n=[e,t].map(s=>i.tallestStructureNear(s.east,s.north,3)).filter(s=>s!==void 0&&s>=at.MIN_POLE_M&&s<=at.MAX_POLE_M);return n.length===0?void 0:n.reduce((s,r)=>s+r,0)/n.length}static tenth(e){return Math.round(e*10)/10}}class ci{static covers(e,t){return e>=41.2&&e<=51.3&&t>=-5.4&&t<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??ci.WMS,this.wfs=e.wfsEndpoint??ci.WFS}static radius(e){return Math.min(e,ci.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,ci.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=ci.lidarRadius(t),n=Math.ceil(2*i/ci.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(e,i,n,ci.HEIGHT_LAYER),this.raster(e,i,n,ci.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new Ns("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(d=>d===ci.NO_DATA))throw new Ns("no-coverage","No LiDAR HD survey here yet");const l=new Uint8Array(n*n),c=new Uint8Array(n*n);for(let d=0;d<n*n;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];l[d]=p>u&&p>f?1:0,c[d]=u>120&&p<90&&f<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:l,building:c,structures:new fE(a,l,c,n,h)}}async laserDate(e){return ci.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return ci.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",e))}static latest(e){return e.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(e,t,i,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(e,`BBOX(${t},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(e,t){const i=ci.radius(t),n=Math.min(ci.MAX_PHOTO_PIXELS,Math.ceil(2*i/ci.METRES_PER_PIXEL)),s=await this.raster(e,i,n,ci.PHOTO_LAYER);if(s.samples<3)throw new Ns("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(e,t,i){const n=ci.radius(t),s=n/ci.METRES_PER_DEGREE,r=n/(ci.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),l=`BBOX(geometrie,${[e.lng-r,e.lat-s,e.lng+r,e.lat+s].map(f=>f.toFixed(6)).join(",")},'EPSG:4326')`,[c,h,d,u,p]=await Promise.all([this.features("construction_lineaire",`${l} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${l} AND position_par_rapport_au_sol<>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("ligne_electrique",l,"voltage,geometrie"),i?this.features("batiment",l,"nature,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_modification,geometrie",5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",l,"toponyme,geometrie",100).catch(()=>[]):Promise.resolve([])]);return{bridges:c,elevatedRoads:h,lines:d,buildings:u,zones:p,mapDate:ci.latest(u.map(f=>f.properties.date_modification))}}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,l=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const c of l)n.push(c.map(h=>({lat:h[1],lng:h[0]})))}return n}async roads(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${t} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async raster(e,t,i,n){const s=t/ci.METRES_PER_DEGREE,r=t/(ci.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-s,e.lng-r,e.lat+s,e.lng+r].map(c=>c.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let l;try{l=await this.fetchImpl(`${this.wms}?${a}`)}catch(c){throw new Ns("unreachable",c instanceof Error?c.message:String(c))}if(!l.ok)throw new Ns("unreachable",`The survey answered ${l.status}`);try{return Rp.parse(await l.arrayBuffer())}catch(c){throw new Ns("unreachable",c instanceof Error?c.message:String(c))}}async features(e,t,i,n=200){const s=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:e.includes(":")?e:`BDTOPO_V3:${e}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(n),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(l){throw new Ns("unreachable",l instanceof Error?l.message:String(l))}if(!r.ok)throw new Ns("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class va{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(e,t){if(e.length<2||t.length<2)return!1;const i=t[0],n=t.map(a=>yt(a.lat,a.lng,i.lat,i.lng)),s=e.map(a=>yt(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const l=s[a],c=s[a+1],h=Math.hypot(c.x-l.x,c.z-l.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/va.SAMPLE_M)),u=Math.atan2(c.x-l.x,-(c.z-l.z));for(let p=0;p<=d;p++){const f=p/d,g=va.nearest(n,l.x+(c.x-l.x)*f,l.z+(c.z-l.z)*f);g.distanceM>va.NEAR_M||va.angleBetween(u,g.heading)<=va.ALIGNED_DEG&&(r+=h/d)}}return r>=va.LONG_ENOUGH_M}static nearest(e,t,i){let n={distanceM:1/0,heading:0};for(let s=0;s<e.length-1;s++){const r=e[s],a=e[s+1],l=a.x-r.x,c=a.z-r.z,h=l*l+c*c,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*l+(i-r.z)*c)/h)),u=Math.hypot(t-(r.x+l*d),i-(r.z+c*d));u<n.distanceM&&(n={distanceM:u,heading:Math.atan2(l,-c)})}return n}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class Qt{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-9e3;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Qt.WMS,this.timeoutMs=e.timeoutMs??Qt.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Qt.MAX_WINDOW_M,this.geoplatform=new ci({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const n={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!ci.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(yt(n.lat,e.east,n.lat,e.west).x),r=Math.abs(yt(e.north,n.lng,e.south,n.lng).z);t=this.finer(t,s,r);const a={x:s/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},l={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},c={south:e.south-l.y/Qt.METRES_PER_DEGREE,north:e.north+l.y/Qt.METRES_PER_DEGREE,west:e.west-l.x/(Qt.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:e.east+l.x/(Qt.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=f=>Math.min(Qt.MAX_PIXELS,Math.max(Qt.MIN_PIXELS,Math.ceil(f/Qt.METRES_PER_PIXEL))),d={width:h(s+2*l.x),height:h(r+2*l.y)},u={x:(s+2*l.x)/d.width,y:(r+2*l.y)/d.height};let p=new Error("No layer of the IGN's relief answered");for(const f of Qt.LAYERS)try{const g=await this.heights(c,d,f);f===Qt.LAYERS[0]&&await this.layBridgeDecks(g,c,d,i?.route);const m=this.sample(g,t,e,c,u,a);if(m)return{heights:m,width:t.width,height:t.height,bounds:e};p=new Error(`${f} does not cover this place`)}catch(g){p=g}throw p}finer(e,t,i){if(e.width<Qt.MESH_FROM_VERTICES||e.height<Qt.MESH_FROM_VERTICES)return e;const n=(s,r)=>{const a=Math.ceil(s/Qt.FINE_SPACING_M),l=Math.max(r-1,Math.min(Qt.MAX_SEGMENTS,a));return l%2===0?l:l+1};return{width:n(t,e.width)+1,height:n(i,e.height)+1}}async raster(e,t,i){const n=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[e.south,e.west,e.north,e.east].map(r=>r.toFixed(6)).join(","),WIDTH:String(t.width),HEIGHT:String(t.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return Rp.parse(await s.arrayBuffer())}async heights(e,t,i){const n=await this.raster(e,t,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(e,t,i,n){if(!(!n||n.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(s=>s>Qt.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(v=>va.follows(n,v));if(s.length===0)return;const r=await this.raster(t,i,Qt.CLASS_LAYER);if(r.samples<3||r.width!==e.width||r.height!==e.height)return;const a=(v,[b,M,y])=>r.values[v*r.samples]===b&&r.values[v*r.samples+1]===M&&r.values[v*r.samples+2]===y,l=e.width,c=e.height,h=new Uint8Array(l*c);let d=!1;for(let v=0;v<h.length;v++)a(v,Qt.DECK)&&(h[v]=1,d=!0);if(!d)return;const u=Qt.DECK_END_PIXELS,p=[];for(let v=0;v<h.length;v++){if(h[v]!==1)continue;const b=v%l,M=(v-b)/l;for(let y=-u;y<=u;y++)for(let x=-u;x<=u;x++){const S=b+x,A=M+y;if(S<0||A<0||S>=l||A>=c)continue;const w=A*l+S;h[w]===0&&a(w,Qt.NO_CLASS)&&p.push(w)}}for(const v of p)h[v]=1;const f=this.paint(s,t,l,c),g=this.touching(h,f,l,c);if(g.every(v=>v===0))return;const m=await this.heights(t,i,Qt.SURFACE_LAYER);if(m.width!==l||m.height!==c)return;for(let v=0;v<g.length;v++){if(g[v]===0)continue;const b=m.values[v];Number.isFinite(b)&&b>Qt.NO_DATA_BELOW&&b>e.values[v]&&(e.values[v]=b)}}catch{}}paint(e,t,i,n){const s=new Uint8Array(i*n),r=l=>(l-t.west)/(t.east-t.west)*i,a=l=>(t.north-l)/(t.north-t.south)*n;for(const l of e)for(let c=0;c<l.length-1;c++){const h=r(l[c].lng),d=a(l[c].lat),u=r(l[c+1].lng),p=a(l[c+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let g=0;g<=f;g++){const m=Math.floor(h+(u-h)*g/f),v=Math.floor(d+(p-d)*g/f);for(let b=-1;b<=1;b++)for(let M=-1;M<=1;M++){const y=m+M,x=v+b;y>=0&&x>=0&&y<i&&x<n&&(s[x*i+y]=1)}}}return s}touching(e,t,i,n){const s=new Uint8Array(e.length),r=new Uint8Array(e.length);for(let a=0;a<e.length;a++){if(e[a]===0||r[a]===1)continue;const l=[],c=[a];r[a]=1;let h=!1;for(;c.length>0;){const d=c.pop();l.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let g=-1;g<=1;g++){const m=u+g,v=p+f;if(m<0||v<0||m>=i||v>=n)continue;const b=v*i+m;e[b]===1&&r[b]===0&&(r[b]=1,c.push(b))}}if(h)for(const d of l)s[d]=1}return s}sample(e,t,i,n,s,r){const{width:a,height:l}=t,c=new Float32Array(a*l),h=new Uint8Array(a*l),d=Math.min(r.x,this.maxWindowM)/s.x,u=Math.min(r.y,this.maxWindowM)/s.y;let p=0;for(let f=0;f<l;f++){const g=i.north+(i.south-i.north)*(l===1?.5:f/(l-1)),m=(n.north-g)/(n.north-n.south)*e.height-.5;for(let v=0;v<a;v++){const M=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*e.width-.5,y=d>1||u>1?this.tent(e,M,m,Math.max(1,d),Math.max(1,u)):this.bilinear(e,M,m),x=f*a+v;y===void 0?p++:(c[x]=y,h[x]=1)}}if(!(p===a*l||p/(a*l)>Qt.MAX_HOLE_SHARE))return this.fill(c,h,a,l),c}tent(e,t,i,n,s){let r=0,a=0,l=0;const c=Math.max(0,Math.ceil(i-s)),h=Math.min(e.height-1,Math.floor(i+s)),d=Math.max(0,Math.ceil(t-n)),u=Math.min(e.width-1,Math.floor(t+n));for(let p=c;p<=h;p++){const f=1-Math.abs(p-i)/s;if(!(f<=0))for(let g=d;g<=u;g++){const m=f*(1-Math.abs(g-t)/n);if(m<=0)continue;l+=m;const v=e.at(g,p);!Number.isFinite(v)||v<Qt.NO_DATA_BELOW||(r+=m*v,a+=m)}}return l>0&&a>=l*.5?r/a:void 0}bilinear(e,t,i){const n=Math.max(0,Math.min(e.width-1,Math.floor(t))),s=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,n+1),a=Math.min(e.height-1,s+1),l=Math.max(0,Math.min(1,t-n)),c=Math.max(0,Math.min(1,i-s)),h=e.at(n,s),d=e.at(r,s),u=e.at(n,a),p=e.at(r,a);for(const m of[h,d,u,p])if(!Number.isFinite(m)||m<Qt.NO_DATA_BELOW)return;const f=h+(d-h)*l,g=u+(p-u)*l;return f+(g-f)*c}fill(e,t,i,n){let s=t.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let l=0;l<i;l++){const c=a*i+l;if(t[c])continue;let h=0,d=0;for(let u=-1;u<=1;u++)for(let p=-1;p<=1;p++){const f=a+u,g=l+p;f<0||g<0||f>=n||g>=i||!t[f*i+g]||(h+=e[f*i+g],d++)}d>0&&r.push([c,h/d])}if(r.length===0)return;for(const[a,l]of r)e[a]=l,t[a]=1;s-=r.length}}}class mE{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(e,t,i)}catch(r){n=r}throw n}}const nu=256,gE=5;async function iw(o,e,t,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(yt(n,o.east,n,o.west).x),a=Math.abs(yt(o.north,s,o.south,s).z),l=Math.max(r,a),{zoom:c,gridSize:h}=vE(n,l,Math.max(e.width,e.height)),{tiles:d,bounds:u}=ew(s,n,c,h),p=h*nu,f=document.createElement("canvas");f.width=p,f.height=p;const g=f.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=d[0];await Promise.all(d.map(async y=>{const x=t(y),S=await i(x);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${x}`);const A=await createImageBitmap(await S.blob());g.drawImage(A,(y.x-m.x)*nu,(y.y-m.y)*nu)}));const v=Math.min(Math.max(e.width,e.height),p);if(v===p)return{source:f,width:p,height:p,bounds:u};const b=document.createElement("canvas");b.width=v,b.height=v;const M=b.getContext("2d");if(!M)throw new Error("2D canvas context unavailable");return M.drawImage(f,0,0,p,p,0,0,v,v),{source:b,width:v,height:v,bounds:u}}function vE(o,e,t){let i=cE(o,e/Math.max(1,t)),n=a1(o,i,e);for(;n>gE&&i>0;)i--,n=a1(o,i,e);return{zoom:i,gridSize:n,mPerPixel:jM(o,i)/nu}}function a1(o,e,t){const i=Math.ceil(t/2/jM(o,e));return Math.max(3,2*i+1)}class nw{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 iw(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Ll{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??Ll.ENDPOINTS}static queue=Promise.resolve();static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=Ll.queue.then(e,e);return Ll.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,Ll.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class ya{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(e={}){this.client=new Ll(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${ya.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(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:ya.surfaceOf(s),widthM:ya.widthOf(s),...ya.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",n=e.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(t==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(e.lanes??"",10),l=Number.parseInt(e.maxspeed??"",10),c=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(s||r)?"dual":t?"road":void 0;return{...c?{kind:c}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||t==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(l)&&l>0?{speedKmh:l}:{}}}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:ya.WIDTH_M[e.highway]??ya.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 jp="https://ufoathome.org/roads/index.json";class Ol{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??Ol.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(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
2955
- `);let t=Ol.shared.get(e);return t||(t=this.fetchFirstAvailable(),Ol.shared.set(e,t),t.then(i=>{i.length===0&&Ol.shared.delete(e)})),this.index=t}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.122.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==jp?[t,jp]:[jp]).map(i=>i+e)}}class xa{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(e={}){this.platform=new ci(e)}static covers(e){return ci.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,n)=>xa.wayOf(i,n))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const n=String(e.properties.nature??""),s=xa.BY_NATURE[n]??xa.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),l=Number(e.properties.vitesse_moyenne_vl),c=xa.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=xa.KINDS[n],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(l)&&l>0?{speedKmh:l}:{},points:i}]}}class yE{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(xa.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}function bE(){return{elevation:sw(),imagery:rw(),roads:ME()}}function sw(){return new mE(new Qt,new tw)}function rw(){return new nw}function ME(){return new Ol({fallback:new yE(new xa,new ya)})}const wE=new Set,ql="show-observer-map",Kl="hide-milestones";class At extends HTMLElement{static get observedAttributes(){return["src",ql,Kl]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;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;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Mi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=_p.create();issues=[];issueCheck=0;sightingAudio=new eE;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>At.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=$M;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");At.setIcon(this.moreButton,e?Ze.UNFOLDED:Ze.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)<At.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>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},At.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=Mi.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>${ZS}</style>${KS}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new dc(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",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.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new so(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",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.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const 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.chromeResizeObserver?.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===ql&&this.applyObserverMapDefault(),e===Kl&&this.setMilestonesShown(!this.hasAttribute(Kl))}async loadFromSrc(e){this.sightingData=await ho.json(e)}get sightingData(){return tE(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=iE(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.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.currentSighting.observer?.title??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await _e(async()=>{const{default:r}=await import("./sightingSchema-kkSSrggd.js");return{default:r}},[],import.meta.url);n=new Os(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],uc.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(xE,{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=uc.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(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(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.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}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)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(a,l);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),At.setIcon(this.referencesButton,i?Ze.PICTURES_ON:Ze.PICTURES_OFF);const n=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),At.setIcon(this.tracesButton,this.tracesShownState?Ze.TRACES_ON:Ze.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?Po(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),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(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)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(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,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(l,c),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,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=At.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((p,f)=>{p.hover.style.width=At.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],l=a.length>0?Kp(a,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)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||n===0||s===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),l=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==l&&(this.chromeCanvas.height=l),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,l),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,l/this.canvas.height,0,0),this.chromeRenderer??=new dc(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}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=At.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>n||(!s||Math.abs(a-e)<Math.abs(s.t-e))&&(s={t:a,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?Kp(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=zs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<At.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(At.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/At.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/At.EXPOSURE_STEP_PX),s=Math.min(At.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(t.fromMs+t.ms*a/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,a]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)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=Ut.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:wE;this.canvasRenderer.setStarPoints(Ut.starPointsOf(this.sighting.instrument));const n=(ot(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 l of s)for(const[,c]of l.shapes){const h=l.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[l,c]of s[0].shapes)!this.selectionShown||!i.has(l)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?kt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds)):void 0;this.chromeDraw=l=>{a&&l.paintGroupHandles(a),this.overlayPainter?.(l)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(l=>[...l.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,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(pg(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 jS(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*At.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Ze.PLAY:Ze.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){At.icons.get(e)!==t&&(At.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-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},At.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,At.setIcon(this.playPauseButton,e?Ze.PAUSE:Ze.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(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ql),t=e===null?this.sighting.observerMap??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;At.setIcon(this.observerMapButton,e?Ze.MAP_ON:Ze.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=Yl.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=Mi.including(this.observerPath.boundsAround(At.OBSERVER_MAP_MIN_SPAN_M,At.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?Mi.expand(e,At.OBSERVER_MAP_IMAGERY_AHEAD):e,n=At.OBSERVER_MAP_IMAGERY_PX*(t?1+2*At.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=rw();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?Mi.expand(e,At.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=At.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(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=ot(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},At.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Kp(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Po(this.currentSighting.milestones):[]){const a=ot(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?$s.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Ut.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,Po(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,At.setIcon(this.milestonesButton,this.milestonesShown?Ze.MILESTONES_ON:Ze.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=ot(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Xs(i,e),{lat:s,lng:r}=fs(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=ot(this.currentSighting,this.currentTime),s=$s.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Yt.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=At.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.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){At.setIcon(this.muteButton,Ze.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}At.setIcon(this.muteButton,this.mutedState?Ze.MUTED:Ze.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;At.setIcon(this.fullscreenButton,e?Ze.EXIT_FULLSCREEN:Ze.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 zn(Is.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=yh(Is.preferencesFor(this),Sh);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await SS(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=cc(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?_m(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 jh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?l1(o1(this.realStartMs+i)):jh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?jh(this.currentSighting.timeline.duration):this.canShowClockTime?l1(o1(this.realStartMs+this.realDurationMs)):jh(this.realDurationMs)}}function o1(o){const e=new Date(o);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function l1(o){if(o.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return o.second?`${e(o.hour)}:${e(o.minute??0)}:${e(o.second)}`:`${e(o.hour)}:${e(o.minute??0)}`}function jh(o){const e=Math.round(o/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Om="rr0-ufo";function Cp(){customElements.get(Om)||customElements.define(Om,At)}const xE="recordingissues";class rh{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+rh.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-rh.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=rh.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(" · ")}}class Pl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=yt(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},a=r(t-Pl.HALF_SPAN_MS),l=r(t+Pl.HALF_SPAN_MS),c=r(t);if(!a||!l||!c)return 0;const h=Math.hypot(l.eastM-a.eastM,l.northM-a.northM),d=2*Pl.HALF_SPAN_MS/1e3;if(h/d<Pl.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-a.eastM,l.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const SE=.08,c1=.15,h1=2,EE=2e3;class AE{context;noiseBuffer;voices=new Map;level=1;master;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}}Oo.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}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,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<EE),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(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(a).connect(n);const c=()=>{const x=e.createBufferSource();return x.buffer=this.noise(e),x.loop=!0,x.loopStart=Math.random()*h1*.5,x},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();m.connect(v).connect(b).connect(n);const M=[s,r,h,p,m];for(const x of M)x.start();const y={nodes:[i,n,a,l,d,u,f,g,v,b,...M],sources:M,firing:s,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:g,windGain:b,cabin:n,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:l}){const c=e.currentTime,h=(b,M)=>b.setTargetAtTime(M,c,SE),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=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*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const g=!r||a;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?a?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*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,c1/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},c1*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*h1,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 Th{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 Th.BY_KIND[e??"generic"]??Th.BY_KIND.generic}}class To{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=To.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 a=[];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<To.STANDING_MPS){l=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;a.push({speedMps:h,rpm:f,load:m,gear:l})}return new To(a,i)}at(e){const t=(e-this.startMs)/To.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 Wu{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 p=yt(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const c=Th.of(a.kind),h=this.drive(`observer:${a.kind}`,Wu.trackKey(e),()=>To.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Th.of(c.engine.kind),d=g=>{const m=Xs(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,Wu.decorKey(c,r),()=>To.of(h,d,0,r));if(!u)continue;const p=Xs(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}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 TE="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",_E=`
3018
+ `);let t=Ol.shared.get(e);return t||(t=this.fetchFirstAvailable(),Ol.shared.set(e,t),t.then(i=>{i.length===0&&Ol.shared.delete(e)})),this.index=t}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.123.0")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==jp?[t,jp]:[jp]).map(i=>i+e)}}class xa{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(e={}){this.platform=new ci(e)}static covers(e){return ci.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,n)=>xa.wayOf(i,n))}static wayOf(e,t){if(e.geometry.type!=="LineString")return[];const i=e.geometry.coordinates.map(([u,p])=>({lat:p,lng:u}));if(i.length<2)return[];const n=String(e.properties.nature??""),s=xa.BY_NATURE[n]??xa.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),l=Number(e.properties.vitesse_moyenne_vl),c=xa.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=xa.KINDS[n],d=[e.properties.cpx_toponyme_route_nommee,e.properties.nom_voie_ban_gauche,e.properties.nom_voie_ban_droite].find(u=>typeof u=="string"&&u.length>0);return[{id:String(e.properties.cleabs??`ign-${t}`),...d?{name:d}:{},surface:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(l)&&l>0?{speedKmh:l}:{},points:i}]}}class yE{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(e){if(xa.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}function bE(){return{elevation:sw(),imagery:rw(),roads:ME()}}function sw(){return new mE(new Qt,new tw)}function rw(){return new nw}function ME(){return new Ol({fallback:new yE(new xa,new ya)})}const wE=new Set,ql="show-observer-map",Kl="hide-milestones";class At extends HTMLElement{static get observedAttributes(){return["src",ql,Kl]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;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;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new Mi;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;milestoneCaption;timeStartLabel;timeEndLabel;timePill;muteButton;volumeInput;controlsRow;momentsBox;momentsButton;momentsCurrent;momentsMenu;moreButton;controlsRight;seekSegments;seekDot;playerTitleBox;seekPreview;seekPreviewCanvas;seekPreviewTitle;seekPreviewTime;observerPath;observerMapBounds;observerMapImagery;observerMapImageryBounds;observerMapImageryViewWidth=0;observerMapImageryLoading=!1;observerMapImageryCredit;observerMapImageryFailed=!1;creditShownExternally=!1;lookYawDeg=0;lookPitchDeg=0;milestonesShown=!0;currentSighting=_p.create();issues=[];issueCheck=0;sightingAudio=new eE;soundPreview;player;loopEnabled=!1;playbackBeforeClick;highlightedSourceIds=new Set;paintsShapes=!0;steadyObserver=!1;static LIVE_BODY_MAX_RATE=2;get steadyBody(){return this.steadyObserver||this.player.playbackState!=="playing"||this.player.playbackRate>At.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;messages=$M;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");At.setIcon(this.moreButton,e?Ze.UNFOLDED:Ze.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)<At.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>=Mi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=Mi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},At.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=Mi.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>${ZS}</style>${KS}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new dc(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",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.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new so(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",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.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.loadLocaleMessages();const 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.chromeResizeObserver?.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===ql&&this.applyObserverMapDefault(),e===Kl&&this.setMilestonesShown(!this.hasAttribute(Kl))}async loadFromSrc(e){this.sightingData=await ho.json(e)}get sightingData(){return tE(this.currentSighting)}set sightingData(e){this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=iE(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.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.currentSighting.observer?.title??"";this.playerTitleBox.textContent=e,this.playerTitleBox.hidden=e===""}get recordingIssues(){return this.issues}async reportIssues(e,t){const i=++this.issueCheck;let n=[];try{const{default:s}=await _e(async()=>{const{default:r}=await import("./sightingSchema-kkSSrggd.js");return{default:r}},[],import.meta.url);n=new Os(s).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...n,...t.loadIssues],uc.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(xE,{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=uc.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(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.dispatchEvent(new CustomEvent("playrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(e){if(e!==this.clockHeld){if(this.clockHeld=e,e){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(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.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}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)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const e=this.currentSighting.references;!this.referenceOpacityTouched&&e.length>0&&(this.referenceOpacityInput.value=String(e[0].opacity));for(const t of[...this.referenceViews.keys()])e.some(i=>i.id===t)||this.referenceViews.delete(t);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(e){let t=this.referenceViews.get(e.id);return t||(t={shown:!0,opacity:e.opacity},this.referenceViews.set(e.id,t)),t}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=e=>{const t=e.composedPath();t.includes(this.referencesMenu)||t.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=e=>{e.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const e=this.referencesButton.getBoundingClientRect(),t=this.referencesMenu,i=4;t.style.bottom=`${Math.max(i,window.innerHeight-e.top+i)}px`,t.style.top="auto";const n=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),n=this.said.read(t.title)??t.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const l=document.createElement("span");l.textContent=n,l.title=n,r.append(a,l);const c=document.createElement("input");return c.type="range",c.min="0",c.max="1",c.step="0.05",c.value=String(i.opacity),c.title=this.messages.referenceOpacity,c.setAttribute("aria-label",`${this.messages.referenceOpacity}: ${n}`),c.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,c.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),c.addEventListener("input",()=>{i.opacity=Number(c.value),this.dispatchReferenceView()}),s.append(r,c),s});this.referencesMenu.setAttribute("aria-label",this.messages.referencesMenu),this.referencesMenu.replaceChildren(...e)}updateReferencesButton(){const e=this.currentSighting.references.length>0,t=this.severalReferences,i=t?this.currentSighting.references.some(s=>this.viewOfReference(s).shown):this.referencesShownState;this.referencesButton.hidden=!e,this.referenceOpacityInput.hidden=!e||!this.referencesShownState||t,this.referencesButton.setAttribute("aria-pressed",String(i)),t?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),At.setIcon(this.referencesButton,i?Ze.PICTURES_ON:Ze.PICTURES_OFF);const n=t?this.messages.referencesMenu:this.referencesShownState?this.messages.hideReferences:this.messages.showReferences;this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages.referenceOpacity,this.referenceOpacityInput.setAttribute("aria-label",this.messages.referenceOpacity)}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),At.setIcon(this.tracesButton,this.tracesShownState?Ze.TRACES_ON:Ze.TRACES_OFF);const e=this.tracesShownState?this.messages.hideTraces:this.messages.showTraces;this.tracesButton.title=e,this.tracesButton.setAttribute("aria-label",e)}dispatchReferenceView(){const e=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(t=>[t.id,{...this.viewOfReference(t)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:e}}))}refreshMilestoneMarks(){const e=this.player.seekableDuration,t=e>0?Po(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),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.refreshSeekSegments(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)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages.moments,this.showCurrentMoment(void 0)}showCurrentMoment(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,a)=>r-a):[],Math.max(e,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const l=document.createElement("i");l.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(l,c),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,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=At.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((p,f)=>{p.hover.style.width=At.fillOf(p,s),p.element.classList.toggle("hovered",s>=p.start&&(s<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],l=a.length>0?Kp(a,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)}paintChrome(e){const t=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||n===0||s===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),l=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==l&&(this.chromeCanvas.height=l),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,l),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,l/this.canvas.height,0,0),this.chromeRenderer??=new dc(t),this.chromeDirty=!0,e(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}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=At.MARK_SNAP_PX/i*t;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>n||(!s||Math.abs(a-e)<Math.abs(s.t-e))&&(s={t:a,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?Kp(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=zs.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<At.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(At.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/At.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/At.EXPOSURE_STEP_PX),s=Math.min(At.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(t.fromMs+t.ms*a/(s-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),n=this.shapesAt(e+t);let s=0;for(const[r,a]of i){const l=n.get(r);if(!l)continue;const c=l.bounds.x+l.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=l.bounds.y+l.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(c,h))}return s}shapeAt(e,t,i){if(!this.accountHidden)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=Ut.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:wE;this.canvasRenderer.setStarPoints(Ut.starPointsOf(this.sighting.instrument));const n=(ot(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 l of s)for(const[,c]of l.shapes){const h=l.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[l,c]of s[0].shapes)!this.selectionShown||!i.has(l)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?kt.groupBoundsFor([...t].filter(([l])=>i.has(l)).map(([,l])=>l.bounds)):void 0;this.chromeDraw=l=>{a&&l.paintGroupHandles(a),this.overlayPainter?.(l)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(l=>[...l.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,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(pg(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 jS(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*At.SEEK_KEY_STEP_MS)))}else e.key===" "&&(e.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const e=this.playbackFlash;e.innerHTML=this.player.playbackState==="playing"?Ze.PLAY:Ze.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){At.icons.get(e)!==t&&(At.icons.set(e,t),e.innerHTML=t)}set captionHeld(e){this.stageElement.classList.toggle("caption-held",e)}set controlsHeld(e){this.stageElement.classList.toggle("controls-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},At.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,At.setIcon(this.playPauseButton,e?Ze.PAUSE:Ze.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(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:e}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const e=this.getAttribute(ql),t=e===null?this.sighting.observerMap??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;At.setIcon(this.observerMapButton,e?Ze.MAP_ON:Ze.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=Yl.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=Mi.including(this.observerPath.boundsAround(At.OBSERVER_MAP_MIN_SPAN_M,At.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?Mi.expand(e,At.OBSERVER_MAP_IMAGERY_AHEAD):e,n=At.OBSERVER_MAP_IMAGERY_PX*(t?1+2*At.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const s=rw();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?Mi.expand(e,At.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=At.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),l=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&l&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(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=ot(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},At.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?Kp(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?Po(this.currentSighting.milestones):[]){const a=ot(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:t?.lat!==void 0&&t.lng!==void 0?{lat:t.lat,lng:t.lng}:void 0,headingDeg:t?.headingDeg===void 0?void 0:t.headingDeg+this.lookYawDeg,coneHalfAngleDeg:t?$s.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Ut.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,Po(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,At.setIcon(this.milestonesButton,this.milestonesShown?Ze.MILESTONES_ON:Ze.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=ot(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=Xs(i,e),{lat:s,lng:r}=fs(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=ot(this.currentSighting,this.currentTime),s=$s.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(t),y:s.angleDegToRadiusPx(i)}}gaitAt(e){return Yt.bodyAt(this.currentSighting,e,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(e){e!==this.mutedState&&(this.mutedState=e,!e&&this.volumeState===0&&(this.volumeState=At.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.hasSound&&(this.muted=!this.mutedState)}ambientSound;get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const e=!this.hasSound;if(this.muteButton.disabled=e,this.volumeInput.hidden=e,e){At.setIcon(this.muteButton,Ze.MUTED),this.muteButton.title=this.messages.noSound,this.muteButton.setAttribute("aria-label",this.messages.noSound),this.muteButton.setAttribute("aria-pressed","true");return}At.setIcon(this.muteButton,this.mutedState?Ze.MUTED:Ze.VOLUME);const t=this.mutedState?this.messages.unmute:this.messages.mute;this.muteButton.title=t,this.muteButton.setAttribute("aria-label",t),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;At.setIcon(this.fullscreenButton,e?Ze.EXIT_FULLSCREEN:Ze.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 zn(Is.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=yh(Is.preferencesFor(this),Sh);if(e===this.messagesLanguage||e==="en"&&this.messagesLanguage===void 0)return;this.messagesLanguage=e;const t=await SS(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=cc(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?_m(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 jh(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?l1(o1(this.realStartMs+i)):jh(i)}formatEndOfTimeline(){return this.realDurationMs===void 0?jh(this.currentSighting.timeline.duration):this.canShowClockTime?l1(o1(this.realStartMs+this.realDurationMs)):jh(this.realDurationMs)}}function o1(o){const e=new Date(o);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function l1(o){if(o.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return o.second?`${e(o.hour)}:${e(o.minute??0)}:${e(o.second)}`:`${e(o.hour)}:${e(o.minute??0)}`}function jh(o){const e=Math.round(o/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Om="rr0-ufo";function Cp(){customElements.get(Om)||customElements.define(Om,At)}const xE="recordingissues";class rh{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+rh.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-rh.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=rh.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(" · ")}}class Pl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const n=e.event.place?.[0],s=e.observerTrack;if(!n)return 0;const r=g=>{const m=s.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=yt(m.lat,m.lng,n.lat,n.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg}},a=r(t-Pl.HALF_SPAN_MS),l=r(t+Pl.HALF_SPAN_MS),c=r(t);if(!a||!l||!c)return 0;const h=Math.hypot(l.eastM-a.eastM,l.northM-a.northM),d=2*Pl.HALF_SPAN_MS/1e3;if(h/d<Pl.MIN_SPEED_MS)return 0;const u=i.heightAt(l.eastM,l.northM)-i.heightAt(a.eastM,a.northM),p=Math.atan2(u,h)*180/Math.PI;if(c.heading===void 0)return p;const f=Math.atan2(l.eastM-a.eastM,l.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const SE=.08,c1=.15,h1=2,EE=2e3;class AE{context;noiseBuffer;voices=new Map;level=1;master;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}}Oo.unlock(this.context),this.apply()}setLevel(e){this.level=e,this.master&&(this.master.gain.value=e)}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,this.master=void 0}masterOf(e){return this.master||(this.master=e.createGain(),this.master.gain.value=this.level,this.master.connect(e.destination)),this.master}apply(){const e=this.context;if(!e)return;const t=this.paused?[]:this.requested.filter(n=>n.inside||n.distanceM<EE),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(this.masterOf(e));const s=e.createOscillator();s.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),l=e.createBiquadFilter();l.type="lowpass",l.frequency.value=900,s.connect(l),r.connect(l),l.connect(a).connect(n);const c=()=>{const x=e.createBufferSource();return x.buffer=this.noise(e),x.loop=!0,x.loopStart=Math.random()*h1*.5,x},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(n);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const g=e.createGain();p.connect(f).connect(g).connect(n);const m=c(),v=e.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const b=e.createGain();m.connect(v).connect(b).connect(n);const M=[s,r,h,p,m];for(const x of M)x.start();const y={nodes:[i,n,a,l,d,u,f,g,v,b,...M],sources:M,firing:s,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:g,windGain:b,cabin:n,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:n,noise:s,inside:r,windowsOpen:a,distanceM:l}){const c=e.currentTime,h=(b,M)=>b.setTargetAtTime(M,c,SE),d=n.rpm/60,u=d*i.cylinders/2,p=Math.min(1,n.rpm/i.shiftUpRpm),f=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*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*n.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const g=!r||a;h(t.windGain.gain,f**2*(g?.5:.06));const m=r?a?3500:700:8e3/(1+l/60);h(t.cabin.frequency,m);const v=r?.5:Math.min(1,8/Math.max(l,1));h(t.output.gain,v*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,c1/3),setTimeout(()=>{for(const n of t.sources)try{n.stop()}catch{}for(const n of t.nodes)n.disconnect()},c1*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*h1,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 Th{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 Th.BY_KIND[e??"generic"]??Th.BY_KIND.generic}}class To{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=To.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 a=[];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<To.STANDING_MPS){l=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=v=>u/e.kmhPer1000Rpm[v-1]*1e3;for(;l<e.kmhPer1000Rpm.length&&p(l)>e.shiftUpRpm;)l++;for(;l>1&&p(l)<e.shiftDownRpm;)l--;const f=Math.max(p(l),e.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=d>.15?Math.min(1,g+d/2.5):d<-.3?.05:g;a.push({speedMps:h,rpm:f,load:m,gear:l})}return new To(a,i)}at(e){const t=(e-this.startMs)/To.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 Wu{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 p=yt(d,u,n.lat,n.lng);return{eastM:p.x,northM:-p.z}},r=Math.max(e.observerTrack.duration,(e.event.durationSeconds??0)*1e3),a=e.vehicle;if(a){const c=Th.of(a.kind),h=this.drive(`observer:${a.kind}`,Wu.trackKey(e),()=>To.of(c,s,0,r));h&&i.push({id:"observer",profile:c,state:h.at(t),noise:a.noise??1,inside:!0,windowsOpen:a.windowsOpen===!0,distanceM:0})}const l=s(t);for(const c of e.decor){if(!c.engine||!l)continue;const h=Th.of(c.engine.kind),d=g=>{const m=Xs(c,g);return{eastM:m.eastM,northM:m.northM}},u=this.drive(`decor:${c.id}`,Wu.decorKey(c,r),()=>To.of(h,d,0,r));if(!u)continue;const p=Xs(c,t),f=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${c.id}`,profile:h,state:u.at(t),noise:c.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:f})}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 TE="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAMAAADVRocKAAAARVBMVEX9sST/uyTfoCjNlSikfCqRcCx8Yy21hipTSi4TITEMHTEuMzBqWC3/wSRUX207SFj8/PyaoakmNUd5gYxBPy90fIfMz9RsB4kZAAACEUlEQVRo3u2XyXbDIAxFLeapjts6/f9PrQA3JymT25Cd3iY5xtYVIB6wLCQSiUQikUgk0nzBoVdFZ1xIpaTQbJnPACaNdYeskWwuAhaZoltnUemfnNkL4N49KEI8n0YAEXMvEWISAWQZPw2Xk1MIoF1dSNAzCMy6JsGyCR0wrkMwT3cBeDt+FH8aEHoA68LbM8HRHXQ3f0RE3/jXOOFX+s4djrKpIbzS7K+MmLrxlWCNR8mczjMw92Ar4dZLDXG4kzXinAECcOUPL3jMdN2294/GQGVG4EMHxORNJXoCfG6oT1trvDGM7iIA9N6aTOuuEbB9ra6FyCYr2gjge+fjA4CIi2uujYRoOBSw0A5/D0hT0X4PW0xtuotNpQPYtkt/fdtyM0LP6ZvOI2DtvoxtJWHvx38AxIkevLwXQ2TOA66DziYfLwC4r5wbIlwJo1ys8+VOBMy7/sxdjwIap49lVC3UePZp1mmyit4SuGUf11pjoTHVRVzXUaXFVt87kuEBsWZ055Q+2sXA76LbZYsvKR1ubvJqbKd5swl+GPI31p6L/sNYuDTe3jo+GBdr1J+P9PGawbRUw9VhleD/3ffT9uZ7DhtX1JNHL2CmNRXxYZhwSwBd3aJTyU85/GKOwhxBf5RnVk+75OSiuu+Ax4PQ3Jsg1hTeMUMwJgQp+PKCe2a+JuefFwQnkUgkEolEIpFerW8TL0hlNl2QVAAAAABJRU5ErkJggg==",_E=`
2956
3019
  <div class="stage" id="stage">
2957
3020
  <div class="frame" id="frame">
2958
3021
  <canvas id="scene-canvas"></canvas>
@@ -9236,7 +9299,7 @@ vLitRank = litRank;`)}`,l.fragmentShader=`uniform float uLitShare;
9236
9299
  varying float vLitRank;
9237
9300
  ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
9238
9301
  totalEmissiveRadiance *= step(vLitRank, uLitShare);`)}`},r.customProgramCacheKey=()=>"facade-lit-windows";const a=new Se(s,r);return a.castShadow=!0,a.receiveShadow=!0,t.add(a),t}static litWindowShare={value:0};static setLitWindowShare(e){Ue.litWindowShare.value=Math.max(0,Math.min(1,e))}static build(e,t){const i=Ue.hasFacade(e)?Ue.buildFacade(e):e.kind==="building"?tb(e.floors??hc,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?nb():e.kind==="shrub"?ib():e.kind==="bridge"?hC(e):e.kind==="wire"?dC(e):e.kind==="wall"?Vi.build(e):e.kind==="crop"?rb():e.kind==="terrace"?bC():e.kind==="mound"?ab():e.kind==="streetlight"?ob(t):e.kind==="vehicle"?lb(t,e.windows,e.observerSide,e.observerFacing):e.kind==="aircraft"?fb():e.kind==="entity"?ub():ig();e.color&&this.paint(i,e.color);const n=this.scaleFor(e),s=new Lt;return e.kind==="building"&&e.roof&&this.addRoof(s,e),i.name=Ue.BODY_NAME,i.scale.copy(n),s.add(i),e.headingDeg!==void 0&&(s.rotation.y=-e.headingDeg*Vf),this.addLights(s,e.lights),Ue.fitLights(s,e,e.sizeM??{}),s}static scaleFor(e){const t=e.sizeM;if(!t||Ue.hasFacade(e)||e.kind==="bridge"||e.kind==="wire"||e.kind==="terrace"||e.kind==="wall")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:Yf(t.widthM,i.widthM),t.heightM===void 0?1:Yf(e.kind==="building"?this.wallHeightOf(e,t.heightM):t.heightM,i.heightM),t.lengthM===void 0?1:Yf(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??hc)+1):0;if(e==="bridge")return li.NATURAL_SIZE;if(e==="wire")return Ro.NATURAL_SIZE;if(e==="terrace"||e==="wall")return{widthM:1,lengthM:1,heightM:1};const n=`${e}:${i}`,s=cb.get(n);if(s)return s;const r=e==="building"?tb(i-1,void 0,void 0,void 0):e==="tree"?nb():e==="shrub"?ib():e==="crop"?rb():e==="mound"?ab():e==="streetlight"?ob(!1):e==="vehicle"?lb(!1,void 0,void 0):e==="aircraft"?fb():e==="entity"?ub():ig(),a=new dn().setFromObject(r),l={widthM:a.max.x-a.min.x,heightM:a.max.y-a.min.y,lengthM:a.max.z-a.min.z};return this.dispose(r),cb.set(n,l),l}static usesModel(e){return Eh(e)!==void 0&&!(e.observerSide!==void 0&&Fa(e.kind))}static applyModel(e,t,i,n={}){const s=this.bodyOf(e),r=new Lt;r.name=Ue.BODY_NAME,i.rotation.y=-(n.headingOffsetDeg??0)*Vf,i.updateMatrixWorld(!0);const a=new dn().setFromObject(i),l={lengthM:a.max.z-a.min.z,heightM:a.max.y-a.min.y,widthM:a.max.x-a.min.x},c=t.kind==="tree"&&t.sizeM?.heightM!==void 0?{heightM:t.sizeM.heightM}:t.sizeM,h=hb(c,l)??hb(n.depictedSizeM,l)??1;i.scale.multiplyScalar(h);const d=a.getCenter(new D).multiplyScalar(h);i.position.x-=d.x,i.position.z-=d.z,i.position.y-=t.kind==="aircraft"?d.y:a.min.y*h,i.traverse(u=>{u instanceof Se&&(u.castShadow=!0,u.receiveShadow=!0)}),r.add(i),t.kind==="tree"&&r.add(Ue.trunkShadow(l.heightM*h)),s.parent?(s.parent.add(r),s.removeFromParent()):e.add(r),this.dispose(s),Ue.fitLights(e,t,{widthM:l.widthM*h,heightM:l.heightM*h,lengthM:l.lengthM*h})}static fitLights(e,t,i){const n=Ah.byId(Gr.rigOf(t)||void 0)?.referenceSizeM;if(!n||!t.lights)return;const s=(h,d)=>h===void 0||d===0?1:h/d,r=s(i.widthM,n.widthM),a=s(i.heightM,n.heightM),l=s(i.lengthM,n.lengthM),c=new Map(t.lights.map(h=>[h.id,h.offsetM]));e.traverse(h=>{const d=h.userData.lightId,u=d===void 0?void 0:c.get(d);u&&h.position.set(u.x*r,u.y*a,u.z*l)})}static trunkShadow(e){Ue.trunkProxy??={geometry:new vs(1,1.15,1,8),material:new Vn({colorWrite:!1,depthWrite:!1})};const t=new Se(Ue.trunkProxy.geometry,Ue.trunkProxy.material),i=Math.min(.3,Math.max(.12,e*.035)),n=e*.45;return t.scale.set(i,n,i),t.position.y=n/2,t.castShadow=!0,t.receiveShadow=!1,t.userData.sharedModel=!0,t.name="trunk-shadow",t}static trunkProxy;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=iC(i.color),s=Bt(e,new Li(Wf,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=Yi,r.transparent=!0,r.depthWrite=!1,r.fog=!1}}static setLights(e,t,i,n,s=0,r=1,a=Z4,l=[1,1,1]){if(!t||t.length===0)return;const c=new Map(t.map(p=>[p.id,p])),h=Math.max(1,n*a/Wf),d=Wf*h,u=r/(Math.PI*d*d);for(const p of e.children){if(!(p instanceof Se))continue;const f=p.userData.lightId;if(!f)continue;const g=c.get(f);if(!g)continue;const m=s>0?GM(g,i,i+s):FS(g,i)?1:0;p.visible=m>0;const v=p.material,b=p.userData.lightColor;if(b){const M=m*j4*(g.intensity??1)*u;v.color.setRGB(b[0]*M*l[0],b[1]*M*l[1],b[2]*M*l[2])}p.scale.setScalar(h)}}static setLit(e,t,i,n=1){const[s,r,a]=t==="streetlight"?[J4,Q4,E2]:[eC,tC,A2],l=i?s*n/(Math.PI*r*r):0,c=[a[0]*l,a[1]*l,a[2]*l];e.traverse(h=>{const d=h.userData;!(h instanceof Se)||!d.emissive||d.lightId||h.material.color.setRGB(...c)})}static dispose(e){e.traverse(t=>{if(!(t instanceof Se))return;if(t.userData.sharedModel){for(const n of t.userData.tintedMaterials??[])n.dispose();return}t.geometry.dispose();const i=t.material;for(const n of Array.isArray(i)?i:[i])n.dispose()})}}const Kf="https://ufoathome.org/models/index.json";class ph{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(e={}){this.sharing=!e.fetchImpl,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.indexUrls=e.indexUrls??SC()}async entries(e){const t=await this.load();return e?t.filter(i=>[i.kind].flat().includes(e)):t}async entry(e){return(await this.load()).find(t=>t.id===e)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const e=this.indexUrls.join(`
9239
- `);let t=ph.shared.get(e);return t||(t=this.fetchFirstAvailable(),ph.shared.set(e,t),t.then(i=>{i.length===0&&ph.shared.delete(e)})),this.loading=t}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 SC(){const o=`?v=${encodeURIComponent("0.122.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==Kf?[e,Kf]:[Kf]).map(t=>t+o)}const pu=[{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 ph}];async function Zf(o){const{GLTFLoader:e}=await _e(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-C8s-rYg8.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const k2=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class ds{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Se(new Wn(2,2),new Dt({uniforms:{uColor:{value:new ne(0,0,0)},uRadius:{value:1}},vertexShader:ds.VERTEX,fragmentShader:ds.FRAGMENT,transparent:!0,depthWrite:!1,blending:Yi,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*ds.MIN_ANGLE_RAD),r=ds.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(ds.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(ds.MAX_SHARE*ds.FILL*Math.PI))}static VERTEX=`
9302
+ `);let t=ph.shared.get(e);return t||(t=this.fetchFirstAvailable(),ph.shared.set(e,t),t.then(i=>{i.length===0&&ph.shared.delete(e)})),this.loading=t}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 SC(){const o=`?v=${encodeURIComponent("0.123.0")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==Kf?[e,Kf]:[Kf]).map(t=>t+o)}const pu=[{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 ph}];async function Zf(o){const{GLTFLoader:e}=await _e(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-C8s-rYg8.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,n)=>{t.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const k2=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class ds{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Se(new Wn(2,2),new Dt({uniforms:{uColor:{value:new ne(0,0,0)},uRadius:{value:1}},vertexShader:ds.VERTEX,fragmentShader:ds.FRAGMENT,transparent:!0,depthWrite:!1,blending:Yi,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*ds.MIN_ANGLE_RAD),r=ds.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(ds.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(ds.MAX_SHARE*ds.FILL*Math.PI))}static VERTEX=`
9240
9303
  uniform float uRadius;
9241
9304
  varying vec2 vOffset;
9242
9305
  void main() {
@@ -9867,7 +9930,7 @@ void main() {`).replace("#include <opaque_fragment>",`
9867
9930
  vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
9868
9931
  gl_FragColor = vec4(light, 1.0);
9869
9932
  }
9870
- `,transparent:!0,blending:Yi,depthWrite:!1,side:mi,fog:!1});this.object=new Se(new Li(nv.RADIUS,128,32,0,Math.PI*2,0,Tt.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<Tt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ms.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=ms.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class pp{constructor(e){this.generator=e}static SIZE=128;target=new Lh(pp.SIZE,{type:di,generateMipmaps:!1,minFilter:gt,magFilter:gt});camera=new Ug(.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 a=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=a[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 es{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){es.install(),this.generator=new A0(e),this.eye=new pp(this.generator)}static decor;refresh(e,t,i,n,s,r,a,l=[],c,h=es.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new pp(this.generator),this.probes.set(m.id,v)),d.push({probe:v,reflector:m})}const u=performance.now(),p=()=>d.filter(({probe:m})=>m.capturedVersion!==a),f=p().filter(({probe:m})=>u-m.capturedAtMs>=h);if(f.length>0){const m=f.reduce((v,b)=>b.probe.capturedAtMs<v.probe.capturedAtMs?b:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,v,[m.reflector.holder,...s]),es.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),es.decor=m.probe.filtered;for(const v of r)es.reflectOn(v,m.probe);for(const v of n)v.shiny||es.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=p();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:es.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Ph?t.sharp&&s.setSurroundings(t.sharp):s instanceof Ea&&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(es.installed)return;es.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!tt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}tt.lights_fragment_maps=tt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function _C(o,e){return JSON.stringify(o.cloudLayers)===JSON.stringify(e.cloudLayers)&&o.cloudCover===e.cloudCover&&o.cloudDarkness===e.cloudDarkness&&o.cloudBaseM===e.cloudBaseM&&o.highCloudCover===e.highCloudCover&&o.iceCrystalAlignment===e.iceCrystalAlignment&&o.rareIceCrystals===e.rareIceCrystals&&o.lowerCloudCover===e.lowerCloudCover&&o.relativeHumidity===e.relativeHumidity&&o.precipitationType===e.precipitationType&&o.precipitationIntensity===e.precipitationIntensity&&o.precipitationAmount===e.precipitationAmount&&o.windDirectionDeg===e.windDirectionDeg&&o.windSpeed===e.windSpeed&&o.storm===e.storm}const Hd=900,jf=1,gb=4,Jf=5,vb=.5,Rl=900,IC=6371e3,DC=3e4;function yb(o){const e=Math.sqrt(2*IC*Math.max(o,0));return Math.max(Rl,Math.min(e,DC))}const Qf=.5,em=850,tm=.03,RC=.015,$n=850,Xc=300,da=120,CC=700,kC=3.5,Gd=20,bb=.04,LC=.26,Mb=4,im=1.5,wb=-1,OC=.01,fu=-4,PC=2,NC=20,Vd=2600,FC=.97,UC=.38,$c=fu,BC=8,zC=2,HC=-.5,xb=1500,GC=.7,VC=.3,WC=.32,XC=.65,Sb=2.4,$C=.9,YC=400,qC=[0,45,90,135,180,225,270,315],KC=2,ZC=16,Eb=4e3,Ab=880,Wd=40,Tb=60,jC=10,JC=1,QC=150,e6=55,t6=.5,i6=17,_b=.265,Ib=[[0,0],...Array.from({length:8},(o,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*_b,Math.sin(t)*_b]})],nm=700,sm=250/ag,n6=12,Db=5,rm=6,Ka=[.92,.92,.95],am=[.15,.15,.19],om={snow:{fallSpeedMPerS:2,size:.3,color:new ne(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new ne(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Cl=0,lm=0,s6=150,cm=3e3,Yc=20,r6=15,Rb=Cl,a6=40,Cb=1,o6=9;function hm(o){return Cb+(o6-Cb)*o}const kb=new ne(.75,.82,.92),l6=10,c6=.5;function Lb(o){return or(o/l6,c6,1)}const Za=200,Ob=.18,Pb=.32,h6=.35,Nb=new ne(.85,.9,.98),Fb=5,Ub=.85,Bb=.01;function d6(o,e,t=1){return Math.round(o*(Bb+(1-Bb)*e)*t)}function u6(o,e){return JSON.stringify(o.cloudLayers)===JSON.stringify(e.cloudLayers)&&o.cloudCover===e.cloudCover&&o.cloudDarkness===e.cloudDarkness&&o.cloudBaseM===e.cloudBaseM&&o.highCloudCover===e.highCloudCover&&o.iceCrystalAlignment===e.iceCrystalAlignment&&o.lowerCloudCover===e.lowerCloudCover}const zb=230,Hb=.7,Gb=.05,p6=.6,f6=.7,m6=.15,Vb=.35,g6=3,v6=1/12,y6=.5,nr=new ne(.82,.86,1),b6=2500,M6=1.6,dm=15,w6={Venus:new ne(1,.96,.85),Mars:new ne(1,.55,.4),Jupiter:new ne(.95,.87,.72),Saturn:new ne(.92,.86,.68)};class Xe{renderer;scene=new Tr;phenomena=new Fs(this.scene);references=new Ps(this.scene,()=>this.render());camera;celestialGroup=new Lt;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()+Eb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Eb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ni;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new we;decorModelProvider=pu[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new Mt(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=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(e){return(e.sizeM?.lengthM??Xe.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Xe.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new sy(16777215,0);celestialLightTarget=new ui;skyLight=new SA(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new cu;weather=Sp;observerElevationM=0;siteElevationM=0;air=new Es;groundRadius=Rl;terrainRadius=Rl;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 we;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new sy(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new cu;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new cu;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;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Nh;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=bE()){this.renderer=new UD({canvas:e,antialias:!0}),this.resolution=new zt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=ah,this.camera=new ts(60,e.width/Math.max(e.height,1),.1,Hd*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=-da,this.celestialLight.shadow.camera.right=da,this.celestialLight.shadow.camera.top=da,this.celestialLight.shadow.camera.bottom=-da,this.celestialLight.shadow.camera.near=$n-Xc,this.celestialLight.shadow.camera.far=$n+Xc,this.celestialLight.shadow.bias=-.03/(2*Xc),this.celestialLight.shadow.normalBias=bb,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(nr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ut(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*sm,0,e.z*sm);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)*vi,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*vi;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*vi,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(yb(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Rl),this.camera.far=Math.max(Hd*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,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.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=Xe.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){if(t&&t.length>=2){const s=t[0];for(const r of t){const a=yt(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>Xe.STILL_OBSERVER_M)return 0}}let i=0;for(const s of e){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/Xe.PATCH_WHOLE_SHARE/100)*100;return n>Rl*Xe.PATCH_WHOLE_SHARE?Math.min(n,Xe.MAX_DECOR_TERRAIN_M):0}static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;placeTerrain(e,t,i,n){const s=(r,a)=>{const l=yt(a.lat,a.lng,e,t);r.position.x=l.x-i,r.position.z=l.z+n};this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin)}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:c,z:h}=yt(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(c*c+h*h)<QC*(n/Rl))return}const s=this.terrainRadius,r=this.terrainMeshOrigin;r!==void 0&&Math.hypot(yt(e,t,r.lat,r.lng).x,yt(e,t,r.lat,r.lng).z)<=s||(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const l=++this.terrainBuildToken;this.awaitArrival(C4(e,t,this.terrainProviders,n,{route:this.observerRoute}),Xe.TERRAIN_PATIENCE_MS).then(({mesh:c,attribution:h,originElevationM:d})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(d??0),this.anchorGrassTo(c,e,t);const u=this.terrainMesh,p=this.terrainMeshOrigin,f=p?yt(e,t,p.lat,p.lng):void 0;u&&f&&Math.hypot(f.x,f.z)<=s&&(c.position.y=u.position.y+this.groundYOfPatch(u,f.x,f.z)),u&&p&&f&&Math.hypot(f.x,f.z)<=s?this.crossfadeTerrain(c,u,p):this.disposeMesh(this.terrainMesh),c.renderOrder=JC,this.terrainMesh=c,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=h,this.scene.add(c),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(c=>{console.warn("Terrain build failed, keeping the flat ground fallback:",c),i?.()})}grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=yt(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const n=yt(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const n=e.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/Xe.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,origin:i,frameId:requestAnimationFrame(r)}}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>Xe.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}s&&Math.hypot(yt(e,t,s.lat,s.lng).x,yt(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,e,t,n.contemporary),this.awaitArrival(n.getRoads(S2(e,t,i)),Xe.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.setGroundSpacing(this.patchSpacingM(e)),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??=_e(async()=>{const{TraceSystem:e}=await import("./TraceSystem-CZFR0soj.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(Jf);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!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.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius),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=e6*(this.sunArriving[1]/i6);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=cn.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(_C(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!u6(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Es.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Xr.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>=y6,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;this.decorObjects=e,this.decorTerrainRadiusM=Xe.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),Ue.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,BC);for(const i of e){const n=Ue.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,n,t.indexOf(i)<zC),i.model&&i.id.startsWith(As.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),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??=_e(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-C1ugmbHe.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=Xe.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const a=Bn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=Tt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*a}}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}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}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),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(e+s*n,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*vi)/Math.cos(e.lat*vi)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,l=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*c}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p)},t,l?(d,u)=>l.relativeOfLuminance(d,u):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,l,c)=>(a*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 Zf(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(Eh(e))||!Ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=TC(i.scene);n.traverse(s=>{s instanceof Se&&(s.userData.sharedModel=!0)}),Ue.applyModelParameters(n,e.modelParameters,i.bindings),Ue.applyModel(t,e,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(e.id,i.credit)}standInScenes=new Map;async loadDecorModel(e,t,i=!1){const n=i?zu[e.kind]:Eh(e);if(!(!n||!Ue.usesModel(e)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const l=i||e.kind==="tree"?await this.standInScene(r):await Zf(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;!i&&e.kind!=="tree"&&es.reflectOn(l);const h={ref:JSON.stringify(n),scene:l,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${e.id}":`,s)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=Zf(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||es.reflectOn(i),i)),this.standInScenes.set(e,t)),t}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?yt(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(u=>u.observerSide!==void 0&&Fa(u.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,s?0:this.gaitOffset.eastM,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 a=0,l;if(s){const u=Xs(s,i),p=Ue.occupantView(s,u.headingDeg),f=-(u.headingDeg??0)*vi,g=p.x*Math.cos(f)+p.z*Math.sin(f),m=-p.x*Math.sin(f)+p.z*Math.cos(f),v=u.eastM+n.x,b=-u.northM+n.z;r.x=-(v+g),r.z=-(b+m),this.camera.position.y=this.groundYUnder(v,b)+p.eyeY,l=p.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*vi,-(p.headingDeg+this.indoorLookYawDeg)*vi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const c=this.findCabin(i,n,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(u=>[u.x,u.z,u.cos,u.sin,u.halfWidthM,u.halfLengthM,u.levelY].map(p=>p.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const u of this.decorObjects){if(u.kind==="terrace")continue;const p=this.decorGroups.get(u.id);if(!p)continue;const f=Xs(u,i),g=f.eastM+n.x+r.x,m=-f.northM+n.z+r.z,v=this.terrainMesh,b=`${v?.geometry.uuid}:${(g-(v?.position.x??0)).toFixed(3)}:${(m-(v?.position.z??0)).toFixed(3)}:${(v?.position.y??0).toFixed(3)}:${f.headingDeg}:${f.altitudeM}:${h}`;if(p.userData.footprintKey!==b){if(u.kind==="wire"){const T=Ue.wireGround(u,g,m,f.headingDeg,(I,R)=>this.groundYUnder(I,R));p.userData.footprintGroundY=T.startY,Ue.shearWire(p,Ue.sizeOf(u).lengthM,T.dropM)}else p.userData.footprintGroundY=this.groundUnderFootprint(u,g,m,f.headingDeg,f.altitudeM);p.userData.footprintKey=b}const y=f.altitudeM>Xe.AIRBORNE_M&&Math.hypot(g,m)<Xe.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:p.userData.footprintGroundY;if(p.position.set(g,y+f.altitudeM,m),u.kind==="crop"){const T=Math.hypot(g,m);p.visible=T<=s6}const x=this.decorPresence.get(u.id),S=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(p.visible=!S);const A=this.decorSunlight.get(u.id);A&&!S&&this.lightFromAbove(p,A),f.headingDeg!==void 0&&(p.rotation.y=-f.headingDeg*vi);const w=US(u,i);if(w!==void 0&&Xe.turnHead(p,f.headingDeg??0,w),u.kind==="crop"&&p.visible){const T=this.terrainMesh,I=[T?.geometry.uuid,g-(T?.position.x??0),m-(T?.position.z??0),p.position.y-(T?.position.y??0),f.headingDeg,f.altitudeM].map(R=>typeof R=="number"?R.toFixed(4):R).join(":");p.userData.cropGroundKey!==I&&(Ue.fitCropToGround(p,(R,O)=>this.groundYUnder(R,O)+f.altitudeM),p.userData.cropGroundKey=I)}if(!S){const T=p.position.distanceTo(this.camera.position);a=Math.max(a,T),T<Xe.trafficModelRangeM(u)&&this.pendingTrafficModels.delete(u.id)&&this.loadDecorModel(u,this.decorModelToken)}}if(s&&l!==void 0){const u=this.decorGroups.get(s.id);u&&(this.camera.position.y=u.position.y+l)}this.updateContrails();const d=Math.max(Hd*1.2,this.groundRadius*2.5,a*1.2);Math.abs(this.camera.far-d)>1&&(this.camera.far=d,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let n=i;for(const s of this.terraces){const r=e-s.x,a=t-s.z,l=r*s.cos-a*s.sin,c=r*s.sin+a*s.cos;if(Math.abs(l)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(l))/s.bankM)),d=h*h*(3-2*h);n=Math.max(n,d*s.levelY+(1-d)*Math.min(s.levelY,i))}}return n}placeTerraces(e,t,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xs(s,e),l=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=Ue.sizeOf(s),d=-(a.headingDeg??0)*vi,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(l-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(l,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=Ue.fitTerrace(r,s,(g,m)=>this.terrainYUnder(l+g*u+m*p,c-g*p+m*u)),r.userData.terraceKey=f),this.terraces.push({x:l,z:c,cos:u,sin:p,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):lm}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}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 lm;const r=n.getX(0),a=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=or((t-r)/(a-r)*(s-1),0,s-1),d=or((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return lm;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,g=d-p,m=(x,S)=>n.getY(x*s+S),v=m(p,u),b=m(p,u+1),M=m(p+1,u),y=m(p+1,u+1);return f+g<=1?v+(b-v)*f+(M-v)*g:y+(M-y)*(1-f)+(b-y)*(1-g)}groundUnderFootprint(e,t,i,n,s=0){return Ue.groundUnderFootprint(e,t,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;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}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=ns.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}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),i=e?ns.NONE:this.perception??ns.NONE;if(vn.uColorVision.value.set(...i.colorMatrix),vn.uContrast.value=i.contrastGain,!e){vn.uMedium.value=0;return}vn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const n=e.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0;vn.uMediumExposure.value=n!==void 0&&n>0?1/(t*n):.065*e.exposureSeconds*e.iso*this.filterTransmittance/(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 we;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&&Ue.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 a=n.kind==="streetlight"&&n.origin!==void 0&&n.lit===void 0&&!n.litKeyframes?.length&&this.lastAstronomy,l=n.kind==="vehicle"?HM(n,e):void 0,c=a?this.lastAstronomy.sun.altitudeDeg<HC:l!==void 0?Na.lamps(l):Dp(n,e);Ue.setLit(r,n.kind,c,this.relativeScale);const h=this.streetlightLights.get(n.id);h&&(h.visible=c),l!==void 0&&(this.headlightSettings.set(n.id,l),this.aimDecorBeam(n,r,l))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=_e(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-NhpS6K9T.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const n=new D(0,0,-1).transformDirection(t.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=Ue.sizeOf(e).lengthM,r=t.getWorldPosition(new D).addScaledVector(n,s/2-VC);r.y+=GC;const a=Ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,n,a*WC,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?Na.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,n=new D(Math.sin(i),0,-Math.cos(i)),s=new D(n.x*Sb,this.camera.position.y-$C,n.z*Sb);this.headlightSystem.aim("observer",t,s,n,XC,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i){const n=Ue.bodyOf(t),s=n.children.find(a=>a.userData.emissive);if(!s)return;const r=new Uw(16764006,xb*this.relativeScale,YC);r.position.copy(s.position).multiply(n.scale),r.castShadow=i,r.shadow.mapSize.set(512,512),r.shadow.bias=-.002,t.add(r),this.streetlightLights.set(e,r)}applyWindowGlow(){const e=this.lastAstronomy;Ue.setLitWindowShare(e?mn.share(e.sun.altitudeDeg,e.localHour):0)}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.applyWindowGlow(),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 a=Ws.luminanceOf(r);if(!(a>0))return[0,0,0];const l=De.relativeOfResponse(a)/a;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.sunBeamFraction=Ri.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,Mb,new ne(1,.96,.88),e.sun.magnitude),this.placeEclipse(e),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}placeEclipse(e){const t=e.eclipse;if(!t||e.sun.altitudeDeg<fu){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Mb/$n*(180/Math.PI),n=i/t.sunRadiusDeg,s=si(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=si(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(or(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),l=a>1e-9?or(t.separationDeg*n*vi/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-l)*a)/c,Math.sin(l*a)/c]:[1,0],u={x:s.x*h+r.x*d,y:s.y*h+r.y*d,z:s.z*h+r.z*d},p=t.moonRadiusDeg*n;this.eclipseDiscs={sun:new D(s.x,s.y,s.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*vi,moonRadiusRad:p*vi};const f=.01,g=(b,M)=>si(e.sun.altitudeDeg+b,e.sun.azimuthDeg+M,1),m={x:g(f,0).x-g(-f,0).x,y:g(f,0).y-g(-f,0).y,z:g(f,0).z-g(-f,0).z},v={x:g(0,f).x-g(0,-f).x,y:g(0,f).y-g(0,-f).y,z:g(0,f).z-g(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:m,right:v}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Vl(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}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??Xe.relativeSkyOf(O0(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),ke.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=xb*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?He.DEFAULT_AEROSOL_OPTICAL_DEPTH:Xr.opticalDepth(i))*He.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Tt.aureoleScale(n,Tt.airMass(e.altitudeDeg))*s,l=Tt.coronaScale(r),c=Tt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.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 nv,this.celestialGroup.add(this.lunarDiffraction.object));const d=Tt.profile(Tt.HAZE_COARSE_MODE),u=Tt.profile(Tt.CLOUD_DROPLETS),p=Ny(e.altitudeDeg),f=new Float32Array(Tt.STEPS*3);let g=0;for(let M=0;M<Tt.STEPS;M++){const y=M*3,x=[0,1,2].map(A=>c*p[A]*(a*d[y+A]+l*u[y+A])),S=Ws.shown(x,Ws.luminanceOf(x),(A,w)=>t.relativeOfLuminance(A,w));f.set(S,y),g=Math.max(g,Ws.response(S))}const{x:m,y:v,z:b}=si(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof Bo||(this.scene.fog=new Bo),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)))}umbraTint(){const e=this.siteElevationM+this.observerElevationM+1.6,[t,i,n]=this.air.transmittance(e,e,Xe.UMBRA_PATH_M),s=.2126*t+.7152*i+.0722*n;return s>0?[(.4124*t+.3576*i+.1805*n)/s,1,(.0193*t+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(e){const t=e.eclipse?.horizonShare;return t&&Math.max(...t)<.1?{share:t,tint:this.umbraTint()}:void 0}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},sunLight:Ri.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?Ri.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?ZC:KC),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 q4(em),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Da(-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 qn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Da(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new fn,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}get plumePuffCount(){return this.plumeSystem?.count??0}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(tm*this.camera.fov*Math.PI/180);let s,r=n;const a=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(As.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.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(tm*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>=$c,s=!n&&e.moon.altitudeDeg>=$c,r=n?e.sun:e.moon,a=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*vi)),c=this.siteElevationM+this.observerElevationM;let h=r,d=n||s?mb.directFraction(r.altitudeDeg,c):0;n&&d<=0&&e.moon.altitudeDeg>=$c&&(h=e.moon,d=mb.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*vi)),p=n||s?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),g=Math.max(0,1/(1+.1125*f)-p),m=[0,0,0];if(n||s){const S=Tt.illuminanceOf(r.magnitude)*i,A=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let R=0;R<3;R++)m[R]=S*A[R]*g*l,this.cloudBeam[R]=S*A[R];const{x:w,y:T,z:I}=si(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,T,I),d>0){const R=Tt.illuminanceOf(h.magnitude)*i,O=h===r?A:this.air.transmittanceFromSpace(c,h.altitudeDeg),L=h===r?p:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=R*O[P]*L*d}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),A=t.skyIrradiance,w=[0,1,2].map(I=>A[I]*S+m[I]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const T=Ke.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(T*(w[0]+a[0]*u),T*(w[1]+a[1]*u),T*(w[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:M,z:y}=si(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,M,y),this.celestialLight.shadow.normalBias=bb*or(M/LC,.1,1),this.placeShadowFrustum();const x=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/x,a[1]/x,a[2]/x),this.celestialLight.intensity=x,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=Bn.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Tt.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=Xe.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,a*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof za||r instanceof Ea)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Xe.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new 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,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,n=kC;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Gd+5,i.near=this.shadowLightDistanceM-Gd,i.far=this.shadowLightDistanceM+Gd,i.updateProjectionMatrix(),t.bias=-.004/(2*Gd),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Xe.CABIN_SKY_SHARE&&(r.envMapIntensity=Xe.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(CC,Math.max(da,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(Xc,t*(Xc/da));this.shadowLightDistanceM=Math.max($n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*da?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=da;shadowLightDistanceM=$n;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*vi,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/De.semiSaturation(De.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new rn,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=Ut.starPointsOf(e),i=Ut.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=ce.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return Da(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,i=0){const n=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const 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.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{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()+Xe.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.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())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(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()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&Fa(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xs(s,e),l=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=Ue.sizeOf(s),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(l,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new es(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof hs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,a=>this.measureSurroundings(a,n,s),e?0:es.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 hh;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>si(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const a=p=>p.map(f=>f/t),l=this.surroundings,c={up:a(r.up),down:a(r.down)},h=(p,f)=>p.some((g,m)=>Math.abs(g-f[m])>.03*Math.max(Math.abs(g),Math.abs(f[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>=$c?e.sun:e.moon.altitudeDeg>=$c?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,v6);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.aimBeams(),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,a,l)=>this.directionAtScreenPoint(r,a,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()),vn.uRodShare.value=this.scatteredSky?.rodShare??0,vn.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);vn.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,this.pointLayerHost)}pointLayerHost={points:()=>{const e=[];return this.celestialGroup.traverse(t=>{(t instanceof hs&&t.userData.pointSource||t instanceof Se&&t.userData.skyRibbon)&&e.push(t)}),e},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(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(Jf),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(e){if(!this.references.any||!this.bodySystem.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(L2),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new Vn({blending:Uh,blendSrc:th,blendDst:th,blendSrcAlpha:th,blendDstAlpha:th,toneMapped:!1});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(N2),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&&Xe.markDecorDepth(s,n.kind!=="crop")}e.layers.set(jf),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(O2),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Vn({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const n=e.getObjectByName("head");if(!n)return;const s=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(Xe.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*vi}static isSolidSurface(e){if(!(e instanceof Se))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==Yi}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Se))return;t&&Xe.isSolidSurface(i)?i.layers.enable(jf):i.layers.disable(jf)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new we),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new qD(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()+Xe.EXPOSURE_BUDGET_MS,s=Xe.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=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=a[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(vn.uRodShare.value=this.scatteredSky?.rodShare??0,vn.uHasOverlay.value=1,vn.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 Tr,t=new Ks(-1,1,1,-1,0,2),i=Wd/(Ab*Math.tan(Tb*vi/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),a=this.screenPointOf(r);if(!a)continue;const l=new Lc(s.material);l.position.set(a.ndcX,a.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 dn,i=new D,n=this.camera.getWorldDirection(new D),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<Xe.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 p of[t.min.y,t.max.y])for(const f of[t.min.z,t.max.z]){if(i.set(u,p,f).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,v),d=Math.max(d,v)}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 we),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new uh(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 we);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new tv(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new we);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new pi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new we(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 pi.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*vi);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new Dn;screenPointSize=new we;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(gb),this.camera.layers.set(gb),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 Ib)this.isSunOccluded(t[0],t[1])||e++;return e/Ib.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 a=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*a).addScaledVector(c,t*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(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 v=e.x+t.x*m-s.position.x,b=e.z+t.z*m-s.position.z;if(Math.hypot(v,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(a.count));if(l<2||l*l!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(l-1)],h=[r.position.z+a.getZ(0),r.position.z+a.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,p=i;for(const[m,v,b]of[[e.x,t.x,c],[e.z,t.z,h]]){const M=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(v)<1e-12){if(m<M||m>y)return!1;continue}const x=(M-m)/v,S=(y-m)/v;u=Math.max(u,Math.min(x,S)),p=Math.min(p,Math.max(x,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),g=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let m=0;m<=g;m++){const v=u+(p-u)*m/g,b=e.x+t.x*v,M=e.y+t.y*v,y=e.z+t.z*v;if(M<=this.groundYUnder(b,y))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=vb;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const l=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>Xe.isSolidSurface(c.object));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.raycaster.ray.origin,n=this.raycaster.ray.direction,s=OC*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new D).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,l=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=Xe.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...l],s);if(c)return this.groundHides(e,t)?void 0:c}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let n,s=1/0,r=1/0,a=!1;for(const l of t){const c=Math.acos(or(l.direction.dot(e),-1,1))-l.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=l.inFront===!0;(h!==d?h:h?u!==a?u:l.radiusRad<r:c<s)&&(n=l.key,s=c,r=l.radiusRad,a=u)}return n}pickInterpretationBodyAt(e,t){const i=this.bodySystem.group.children.filter(p=>p.visible&&p.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=RC*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],l=a.length>0?Xe.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new dn,u=new D;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new D).length()/2,g=u.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||l!==void 0&&l<m-f)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),b=Math.atan(f/m);if(b>r){const M=this.raycaster.intersectObject(p,!0)[0];if(!M||l!==void 0&&l<M.distance)continue}else if(v>r)continue;b<h&&(h=b,c=p.name.slice(5))}return c}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(tm*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const l=a.direction.dot(i);l>r&&(r=l,s={star:a.star,altitudeDeg:a.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,vb)}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 a=0;a<8;a++){const l=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&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 dn;bodyCornerScratch=new D;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}decorScreenBox(e){const t=this.decorGroups.get(e);if(!t||!t.visible)return;const i=this.bodyBoxScratch.setFromObject(t);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let l=0;l<8;l++){const c=this.bodyCornerScratch.set(l&1?i.max.x:i.min.x,l&2?i.max.y:i.min.y,l&4?i.max.z:i.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorGroundPointAt(e,t,i,n=0){const s=this.decorGroups.get(e);if(!s)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*vi/2):0}decorGrabHeightAt(e,t,i){const n=this.decorGroups.get(e);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),l=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return l?Math.min(Math.max(l.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new ba;decorHitScratch=new D;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Xe.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=Xe.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}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.plumeSystem?.dispose(),this.plumeSystem=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())Ue.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.animationFrameId=null,this.frame(t),this.animationFrameId===null&&this.needsAnimationLoop()&&(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.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(e=>e.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<Xe.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(e){const t=this.skyMesh?.geometry??new Li(Hd,32,16),i=t.attributes.position,n=t.getAttribute("color")??new bt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:l}=jD(i.getX(r),i.getY(r),i.getZ(r)),c=rR(a,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 Vn({vertexColors:!0,side:mi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Se(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=yb(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Lg(this.groundRadius,48),i=new za({color:new ne(Qf,Qf,Qf),fog:!0});Bo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Se(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);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,e.depthTest=!0,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,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.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=si(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-Ft.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*FC);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ft.iceAlphaAt(i,Vd,r,this.cloudFieldOffset)*UC),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<fu){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:a,z:l}=si(t.altitudeDeg,t.azimuthDeg,$n),c=Ny(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=Xe.unitLuminance(n);let p=this.bodyMeshes.get(e);if(e==="sun"){const f=Math.PI*(i/$n)**2,g=[0,1,2].map(v=>u[v]*d[v]/(this.sunBeamFraction*f));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(Xe.BRIGHTEST_RELATIVE,v));p instanceof Se||(this.disposeMesh(p),p=new Se(new Li(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)),p.material.color.setRGB(m[0],m[1],m[2]),p.scale.setScalar(i)}else{if(!(p instanceof hs)){this.disposeMesh(p);const m=new lt;m.setAttribute("position",new rt(new Float32Array(3),3)),m.setAttribute("color",new rt(new Float32Array(3),3)),p=new hs(m,ke.material(tc[tc.length-1].size,!1)),ke.track(p),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)}const f=p.geometry.getAttribute("color"),g=e.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*d[0]*g,u[1]*d[1]*g,u[2]*d[2]*g),f.needsUpdate=!0}if(p.position.set(r,a,l),this.setHitArea(e,r,a,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,l,d,i/$n*(180/Math.PI),Xe.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,l*f),this.lensFlare||(this.lensFlare=Y4(),this.lensFlare.uniforms.uOpacity.value=t6,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<fu){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=si(e.altitudeDeg,e.azimuthDeg,$n),a=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??_n.MEAN_RADIUS_DEG,h=$n*Math.tan(c*vi),d=Math.max(or(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/$n)**2,u=new ne(...l.map(g=>Math.min(Xe.BRIGHTEST_RELATIVE,g/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(or(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Lc?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=Xb(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Lc(new lu({map:Xb(e.phase),color:u,fog:!1,blending:Yi,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,l,c)}bentLight(e,t,i=PC){const[n,s,r]=this.arrivingIlluminance(e,t,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(e,t){return Xe.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new ne;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,ke.CONE_SOLID_ANGLE/t)}pointScratch=new we;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=Tt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=Ws.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 lu({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Lc(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const a=s*2;r.scale.set(a,a,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,a=0){if(cn.radiusDeg(cn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new cn(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.shine({x:t,y:i,z:n},s,r,a)}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=Ul(e.magnitude,t),s=zf(n);this.cometKey=i,this.setBodyMesh(i,e.position,im*(.5+.5*n),new ne(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new ls($n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Di,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Vd},0);return}const s=this.lowerCloudCover(),r=it.deckLitUntilDeg(it.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,l=this.bentLight(a,a===e?ut.SUN_MAGNITUDE:t.magnitude),c=it.strength(i,s,a.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=si(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Vd},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??gu,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Io,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(),a=this.bentLight(s,n?ut.SUN_MAGNITUDE:t.magnitude,NC),l=Sn.strength(i,r,s.altitudeDeg)*a.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}=si(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,a.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Ma,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=cs.galactic(i,n),r=Xe.directionOf(s.centre),a=Xe.directionOf(s.rotation),l=Xe.directionOf(s.pole),c=new Je().set(r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z),h=Xe.directionOf(cs.eclipticPole(i,n)),d=Xe.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:Xe.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:ce.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}=si(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=Ul(n.magnitude,t),a=zf(r);this.setBodyMesh(s,n.position,im*(.5+.5*r),new ne(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(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=Ul(n.magnitude,t),r=zf(s),a=w6[n.body]??new ne(1,1,1),l=new ne(a.r*r,a.g*r,a.b*r),c=im*(.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 Hs(n,s),a=um(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:p}=r.position(i.ra[h],i.dec[h]);if(u<wb)continue;const{x:f,y:g,z:m}=si(u,p,em);l.push({x:f,y:g,z:m,brightness:Ul(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(v=>v*Tt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of A4){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<wb)continue;const{x:p,y:f,z:g}=si(d,u,em);this.namedStars.push({star:h,direction:new D(p,f,g).normalize(),altitudeDeg:d})}this.starTiers=tc.map((h,d)=>{const u=l.filter(x=>Vg(x.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),g=new Float32Array(u.length*3),m=new Float32Array(u.length),v=new Float32Array(u.length);u.forEach((x,S)=>{p[S*3]=x.x,p[S*3+1]=x.y,p[S*3+2]=x.z,f[S]=x.brightness,g.set(x.illuminance,S*3),m[S]=x.phase,v[S]=x.speedFactor});const b=new lt;b.setAttribute("position",new rt(p,3)),b.setAttribute("seed",new rt(m.map(x=>x/(2*Math.PI)),1));const M=new rt(new Float32Array(u.length*3),3);b.setAttribute("color",M);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new hs(b,ke.material(h.size)),ke.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:M,brightness:f,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){ke.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 Ql(this.celestialGroup,nm,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 ne(Ka[0]+(am[0]-Ka[0])*t,Ka[1]+(am[1]-Ka[1])*t,Ka[2]+(am[2]-Ka[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}=D0(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=R0(nm);this.cloudMesh=new Se(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}=D0(new ne(...Ka),e,Vd,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Se(R0(nm*1.04),t),this.cirrusMesh.renderOrder=Db-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?Ql.deckOrder(!0,0,1):Db}cloudLayerOffset(){const t=((this.weather.cloudBaseM??ag)-this.observerElevationM)*sm;return Math.sign(t||1)*Math.max(Math.abs(t),n6)}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,a]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*dm*this.relativeScale/Math.PI,c=new ne(t[0]+nr.r*l,t[1]+nr.g*l,t[2]+nr.b*l);this.layeredClouds?.setLighting(n.clone(),new ne(s,r,a),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,a*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 d6(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,cm],[this.rainSplashSystem?.points,Za],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:om[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=Lb(hm(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=om[e],i=t.poolSize,n=um(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),l=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let M=0;M<i;M++){const y=n()*Math.PI*2,x=n()*t.radiusM;s[M*3]=Math.cos(y)*x,s[M*3+1]=Cl+n()*(t.topYM-Cl),s[M*3+2]=Math.sin(y)*x,r[M]=n()*Math.PI*2,a[M]=.7+n()*.6,l[M]=.6+n()*.8,c[M]=.4+n()*1.2}const g=new lt;g.setAttribute("position",new rt(s,3)),g.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 ne(...this.baseFogColor)},uTexture:{value:x6(e)},uNearFocusDistance:{value:Fb},uHazeDistance:{value:t.radiusM*Ub}},v=new Dt({uniforms:m,vertexShader:I6,fragmentShader:D6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const b=new hs(g,v);b.renderOrder=rm,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=l,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,this.precipitationBounceVelX=p,this.precipitationBounceVelZ=f}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=om[i];if(this.precipitationUniforms?.uColor.value.copy(Xe.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*vi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,M=i==="hail"&&p&&f&&g&&m&&v;for(let y=0,x=0;y<l.length;y+=3,x++){if(M&&p[x]>0){if(p[x]-=t,p[x]<=0){const w=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[y]=Math.cos(w)*T,l[y+1]=n.topYM,l[y+2]=Math.sin(w)*T,p[x]=0}else{const w=1-p[x]/g[x];l[y+1]=Cl+Math.sin(Math.PI*w)*f[x],l[y]=Xd(l[y]+(r+m[x])*t,n.radiusM),l[y+2]=Xd(l[y+2]+(a+v[x])*t,n.radiusM)}continue}let S=0,A=0;if(b){const w=p6*d[x],T=f6*u[x];S=Math.sin(e*w*Math.PI*2+c[x])*T,A=Math.sin(e*w*Math.PI*2+c[x]+Math.PI/2)*T}if(l[y]+=(r+S)*t,l[y+1]-=n.fallSpeedMPerS*h[x]*t,l[y+2]+=(a+A)*t,l[y]=Xd(l[y],n.radiusM),l[y+2]=Xd(l[y+2],n.radiusM),l[y+1]<Cl){if(M){f[x]=Vb*(.2+Math.random()*1.6),g[x]=m6*(.5+Math.random()),p[x]=g[x];const I=Math.random()*Math.PI*2,R=g6*(f[x]/Vb);m[x]=Math.cos(I)*R,v[x]=Math.sin(I)*R,l[y+1]=Cl;continue}const w=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[y]=Math.cos(w)*T,l[y+1]=n.topYM,l[y+2]=Math.sin(w)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=hm(this.weather.precipitationIntensity);this.rainSystem=V4({count:cm,radiusM:Yc,heightM:r6,bottomYM:Rb,overallSpeed:a6,color:kb.clone(),opacity:.85,visibleCount:this.precipitationCount(cm),speedStreak:Lb(e),pixelSize:zb,seed:9001,nearFocusDistanceM:Fb,hazeDistanceM:Yc*Ub,hazeColor:new ne(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=rm,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=um(4242),t=new Float32Array(Za*3),i=new Float32Array(Za),n=new Float32Array(Za),s=new Float32Array(Za);for(let h=0;h<Za;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Yc;t[h*3]=Math.cos(d)*u,t[h*3+1]=Rb,t[h*3+2]=Math.sin(d)*u,n[h]=Wb(Ob,Pb),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new lt;r.setAttribute("position",new rt(t,3));const a=new rt(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Za));const l=new Dt({uniforms:{uMaxSize:{value:h6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Nb.clone()},uTexture:{value:A6()}},vertexShader:T6,fragmentShader:_6,transparent:!0,depthWrite:!1}),c=new hs(r,l);c.renderOrder=rm,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*vi;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-hm(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(Xe.litBySky(kb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Xe.litBySky(Nb,this.baseFogColor));const n=this.weather.windDirectionDeg*vi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Yc,l=h=>(h%(a*2)+a*3)%(a*2)-a;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=Hb+(1-Hb)*(1-c),d=Gb+(1-Gb)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=zb*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,a=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())*Yc;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Wb(Ob,Pb),n[c]=0}a[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=ji.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(b6/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*dm*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+nr.r*c,this.airlight[1]+nr.g*c,this.airlight[2]+nr.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*M6;r.setRGB(1+l*nr.r,1+l*nr.g,1+l*nr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*dm*this.relativeScale,t){const{x:l,y:c,z:h}=si(25,t.azimuthDeg,$n);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new wa($n*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=qC.map(e=>{const t=Fo.point(e,this.compassPoints),i=new lu({map:R6(t),depthTest:!1,fog:!1}),n=new Lc(i),{x:s,y:r,z:a}=si(0,e,Ab);return n.position.set(s,r,a),n.scale.set(Wd,Wd,1),n.renderOrder=jC,n.layers.set(Jf),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=Tb*Math.PI/360,i=Wd*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 vi=Math.PI/180;function or(o,e,t){return Math.max(e,Math.min(t,o))}function Wb(o,e){return o+Math.random()*(e-o)}function Xd(o,e){return(o%(e*2)+e*3)%(e*2)-e}let $d,Yd;function x6(o){switch(o){case"snow":return S6();case"hail":return E6()}}function S6(){if($d)return $d;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),$d=new Qr(e),$d}function E6(){if(Yd)return Yd;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),Yd=new Qr(e),Yd}let qd;function A6(){if(qd)return qd;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),qd=new Qr(e),qd}const T6=`
9933
+ `,transparent:!0,blending:Yi,depthWrite:!1,side:mi,fog:!1});this.object=new Se(new Li(nv.RADIUS,128,32,0,Math.PI*2,0,Tt.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<Tt.STEPS;i++){for(let n=0;n<3;n++)this.texels[i*4+n]=ms.toHalfFloat(Math.min(t[i*3+n],6e4));this.texels[i*4+3]=ms.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class pp{constructor(e){this.generator=e}static SIZE=128;target=new Lh(pp.SIZE,{type:di,generateMipmaps:!1,minFilter:gt,magFilter:gt});camera=new Ug(.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 a=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=a[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 es{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){es.install(),this.generator=new A0(e),this.eye=new pp(this.generator)}static decor;refresh(e,t,i,n,s,r,a,l=[],c,h=es.REFRESH_MS){for(const m of[...this.probes.keys()])n.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const d=[{probe:this.eye}];for(const m of n){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new pp(this.generator),this.probes.set(m.id,v)),d.push({probe:v,reflector:m})}const u=performance.now(),p=()=>d.filter(({probe:m})=>m.capturedVersion!==a),f=p().filter(({probe:m})=>u-m.capturedAtMs>=h);if(f.length>0){const m=f.reduce((v,b)=>b.probe.capturedAtMs<v.probe.capturedAtMs?b:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(e,t,v,[m.reflector.holder,...s]),es.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(e,t,i,[...s,...l]),c?.(m.probe.sharp),es.decor=m.probe.filtered;for(const v of r)es.reflectOn(v,m.probe);for(const v of n)v.shiny||es.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=a}const g=p();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(u-m.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:es.decor}){e.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[])s instanceof Ph?t.sharp&&s.setSurroundings(t.sharp):s instanceof Ea&&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(es.installed)return;es.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!tt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}tt.lights_fragment_maps=tt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}function _C(o,e){return JSON.stringify(o.cloudLayers)===JSON.stringify(e.cloudLayers)&&o.cloudCover===e.cloudCover&&o.cloudDarkness===e.cloudDarkness&&o.cloudBaseM===e.cloudBaseM&&o.highCloudCover===e.highCloudCover&&o.iceCrystalAlignment===e.iceCrystalAlignment&&o.rareIceCrystals===e.rareIceCrystals&&o.lowerCloudCover===e.lowerCloudCover&&o.relativeHumidity===e.relativeHumidity&&o.precipitationType===e.precipitationType&&o.precipitationIntensity===e.precipitationIntensity&&o.precipitationAmount===e.precipitationAmount&&o.windDirectionDeg===e.windDirectionDeg&&o.windSpeed===e.windSpeed&&o.storm===e.storm}const Hd=900,jf=1,gb=4,Jf=5,vb=.5,Rl=900,IC=6371e3,DC=3e4;function yb(o){const e=Math.sqrt(2*IC*Math.max(o,0));return Math.max(Rl,Math.min(e,DC))}const Qf=.5,em=850,tm=.03,RC=.015,$n=850,Xc=300,da=120,CC=700,kC=3.5,Gd=20,bb=.04,LC=.26,Mb=4,im=1.5,wb=-1,OC=.01,fu=-4,PC=2,NC=20,Vd=2600,FC=.97,UC=.38,$c=fu,BC=8,zC=2,HC=-.5,xb=1500,GC=.7,VC=.3,WC=.32,XC=.65,Sb=2.4,$C=.9,YC=400,qC=[0,45,90,135,180,225,270,315],KC=2,ZC=16,Eb=4e3,Ab=880,Wd=40,Tb=60,jC=10,JC=1,QC=150,ek=55,tk=.5,ik=17,_b=.265,Ib=[[0,0],...Array.from({length:8},(o,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*_b,Math.sin(t)*_b]})],nm=700,sm=250/ag,nk=12,Db=5,rm=6,Ka=[.92,.92,.95],am=[.15,.15,.19],om={snow:{fallSpeedMPerS:2,size:.3,color:new ne(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new ne(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Cl=0,lm=0,sk=150,cm=3e3,Yc=20,rk=15,Rb=Cl,ak=40,Cb=1,ok=9;function hm(o){return Cb+(ok-Cb)*o}const kb=new ne(.75,.82,.92),lk=10,ck=.5;function Lb(o){return or(o/lk,ck,1)}const Za=200,Ob=.18,Pb=.32,hk=.35,Nb=new ne(.85,.9,.98),Fb=5,Ub=.85,Bb=.01;function dk(o,e,t=1){return Math.round(o*(Bb+(1-Bb)*e)*t)}function uk(o,e){return JSON.stringify(o.cloudLayers)===JSON.stringify(e.cloudLayers)&&o.cloudCover===e.cloudCover&&o.cloudDarkness===e.cloudDarkness&&o.cloudBaseM===e.cloudBaseM&&o.highCloudCover===e.highCloudCover&&o.iceCrystalAlignment===e.iceCrystalAlignment&&o.lowerCloudCover===e.lowerCloudCover}const zb=230,Hb=.7,Gb=.05,pk=.6,fk=.7,mk=.15,Vb=.35,gk=3,vk=1/12,yk=.5,nr=new ne(.82,.86,1),bk=2500,Mk=1.6,dm=15,wk={Venus:new ne(1,.96,.85),Mars:new ne(1,.55,.4),Jupiter:new ne(.95,.87,.72),Saturn:new ne(.92,.86,.68)};class Xe{renderer;scene=new Tr;phenomena=new Fs(this.scene);references=new Ps(this.scene,()=>this.render());camera;celestialGroup=new Lt;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()+Eb,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),Eb+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new ni;roadAttribution;roadWays;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new we;decorModelProvider=pu[0].create();decorModelToken=0;decorModelCredits=new Map;bodySystem=new Mt(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=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(e){return(e.sizeM?.lengthM??Xe.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*Xe.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new sy(16777215,0);celestialLightTarget=new ui;skyLight=new SA(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassHovered=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new cu;weather=Sp;observerElevationM=0;siteElevationM=0;air=new Es;groundRadius=Rl;terrainRadius=Rl;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 we;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new sy(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;lensFlareArtifactIntensity=0;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new cu;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new cu;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;plumeSystem;iceHalos;lunarDiffraction;eclipsedSun=new Nh;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=bE()){this.renderer=new UD({canvas:e,antialias:!0}),this.resolution=new zt(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=ah,this.camera=new ts(60,e.width/Math.max(e.height,1),.1,Hd*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=-da,this.celestialLight.shadow.camera.right=da,this.celestialLight.shadow.camera.top=da,this.celestialLight.shadow.camera.bottom=-da,this.celestialLight.shadow.camera.near=$n-Xc,this.celestialLight.shadow.camera.far=$n+Xc,this.celestialLight.shadow.bias=-.03/(2*Xc),this.celestialLight.shadow.normalBias=bb,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(nr),this.scene.add(this.celestialLight,this.celestialLightTarget,this.skyLight,this.lightningLight),this.scene.add(this.celestialGroup),this.scene.add(this.bodySystem.group),this.scene.add(this.roadSystem.group),this.roadSystem.onMarkings=()=>{this.compileNextFrameOffThread(),this.render()};const i=new ut(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*sm,0,e.z*sm);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)*vi,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*vi;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*vi,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(yb(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Rl),this.camera.far=Math.max(Hd*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),e.lat!==void 0&&e.lng!==void 0&&this.placeTerrain(e.lat,e.lng,0,0),this.poseElevationM=e.elevationM,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.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=Xe.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){if(t&&t.length>=2){const s=t[0];for(const r of t){const a=yt(r.lat,r.lng,s.lat,s.lng);if(Math.hypot(a.x,a.z)>Xe.STILL_OBSERVER_M)return 0}}let i=0;for(const s of e){if(s.kind==="aircraft"||s.kind==="observer"||s.track)continue;const r=Math.max(s.sizeM?.widthM??0,s.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(s.eastM,s.northM)+r)}const n=Math.ceil(i/Xe.PATCH_WHOLE_SHARE/100)*100;return n>Rl*Xe.PATCH_WHOLE_SHARE?Math.min(n,Xe.MAX_DECOR_TERRAIN_M):0}static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;placeTerrain(e,t,i,n){const s=(r,a)=>{const l=yt(a.lat,a.lng,e,t);r.position.x=l.x-i,r.position.z=l.z+n};this.terrainMesh&&this.terrainMeshOrigin&&s(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&s(this.fadingTerrain.mesh,this.fadingTerrain.origin)}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const n=Math.max(this.groundRadius,this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-n)<n*.1){const{x:c,z:h}=yt(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(c*c+h*h)<QC*(n/Rl))return}const s=this.terrainRadius,r=this.terrainMeshOrigin;r!==void 0&&Math.hypot(yt(e,t,r.lat,r.lng).x,yt(e,t,r.lat,r.lng).z)<=s||(this.roadSystem.clear(),this.roadAttribution=void 0),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=n;const l=++this.terrainBuildToken;this.awaitArrival(C4(e,t,this.terrainProviders,n,{route:this.observerRoute}),Xe.TERRAIN_PATIENCE_MS).then(({mesh:c,attribution:h,originElevationM:d})=>{if(l!==this.terrainBuildToken)return;this.setSiteElevation(d??0),this.anchorGrassTo(c,e,t);const u=this.terrainMesh,p=this.terrainMeshOrigin,f=p?yt(e,t,p.lat,p.lng):void 0;u&&f&&Math.hypot(f.x,f.z)<=s&&(c.position.y=u.position.y+this.groundYOfPatch(u,f.x,f.z)),u&&p&&f&&Math.hypot(f.x,f.z)<=s?this.crossfadeTerrain(c,u,p):this.disposeMesh(this.terrainMesh),c.renderOrder=JC,this.terrainMesh=c,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=h,this.scene.add(c),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,n),this.drapeStatedRoads(),this.drapeTraces(),this.render(),i?.()}).catch(c=>{console.warn("Terrain build failed, keeping the flat ground fallback:",c),i?.()})}grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=yt(this.grassReference.lat,this.grassReference.lng,t,i);Math.hypot(r.x,r.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:t,lng:i};const n=yt(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(n.x,n.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const n=e.material;n.opacity=0,n.polygonOffset=!0,n.polygonOffsetFactor=-1,n.polygonOffsetUnits=-4;const s=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-s)/Xe.TERRAIN_CROSSFADE_MS);if(n.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}n.polygonOffset=!1,n.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:t,origin:i,frameId:requestAnimationFrame(r)}}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>Xe.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}s&&Math.hypot(yt(e,t,s.lat,s.lng).x,yt(e,t,s.lat,s.lng).z)<=s.radiusM&&this.drapeRoads(s.ways,e,t,n.contemporary),this.awaitArrival(n.getRoads(S2(e,t,i)),Xe.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.setGroundSpacing(this.patchSpacingM(e)),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??=_e(async()=>{const{TraceSystem:e}=await import("./TraceSystem-CZFR0soj.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(Jf);this.scene.add(t.group),this.traceSystem=t})}drapeTraces(){const e=this.traceSystem,t=this.terrainMesh,i=this.terrainMeshOrigin;!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.setGroundSpacing(this.patchSpacingM(s)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(s,r,a),n,this.terrainRadius),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=ek*(this.sunArriving[1]/ik);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=cn.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(_C(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!uk(t,e),n=t.precipitationType!==e.precipitationType,s=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||n||s)&&(this.air=Es.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Xr.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>=yk,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;this.decorObjects=e,this.decorTerrainRadiusM=Xe.terrainReachFor(e,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),Ue.dispose(i);this.decorGroups.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,n)=>Math.hypot(i.eastM,i.northM)-Math.hypot(n.eastM,n.northM)).slice(0,BC);for(const i of e){const n=Ue.build(i,i.lit??!1);this.scene.add(n),this.decorGroups.set(i.id,n),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,n,t.indexOf(i)<zC),i.model&&i.id.startsWith(As.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,n)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),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??=_e(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-C1ugmbHe.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=Xe.CONTRAIL_SCATTERING,s=this.skyLight.color,r=[s.r*n*.5,s.g*n*.5,s.b*n*.5];if(t&&i){const a=Bn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const l=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=Tt.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=n*c*l[h]*a}}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}entryOfDecorModel(e){return this.decorModelProvider.entry(e).catch(()=>{})}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),n=this.bodyEastScale;return{heightAt:(s,r)=>this.groundYUnder(e+s*n,t-r)-i}}get bodyEastScale(){const e=this.decorReferencePose,t=this.decorCurrentPose;return e?.lat===void 0||t?.lat===void 0?1:Math.cos(t.lat*vi)/Math.cos(e.lat*vi)}bodyMaskedByDecor(e,t){const i=this.decorGroups.get(t);return i?this.bodySystem.maskedShare(e,i):void 0}setBodies(e,t=0,i=e.map(r=>r.id),n=[],s){const{x:r,z:a}=this.bodyOrigin,l=this.scatteredSky,c=this.bodyEastScale;Math.abs(c-1)>1e-9&&(e=e.map(d=>({...d,eastM:d.eastM*c}))),this.bodySystem.set(e,{originX:r,originZ:a,originGroundY:this.groundYUnder(r,a),eye:this.camera.position,groundYAt:(d,u)=>this.groundYUnder(d,u),wind:s,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p)},t,l?(d,u)=>l.relativeOfLuminance(d,u):void 0,i),this.bodySystem.setSmoke(n,t),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}plumeLight(){const e=this.celestialLight.color,t=this.celestialLight.intensity*.5,i=this.skyLight.color,n=this.skyLight.groundColor,s=this.skyLight.intensity,r=(a,l,c)=>(a*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 Zf(i),credit:n,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(Eh(e))||!Ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const n=TC(i.scene);n.traverse(s=>{s instanceof Se&&(s.userData.sharedModel=!0)}),Ue.applyModelParameters(n,e.modelParameters,i.bindings),Ue.applyModel(t,e,n,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.decorModelCredits.set(e.id,i.credit)}standInScenes=new Map;async loadDecorModel(e,t,i=!1){const n=i?zu[e.kind]:Eh(e);if(!(!n||!Ue.usesModel(e)))try{const s=n.url?void 0:n.id?await this.decorModelProvider.entry(n.id):void 0,r=this.modelUrl(n)??s?.url,a=n.credit??s?.credit;if(!r||!a)return;const l=i||e.kind==="tree"?await this.standInScene(r):await Zf(r);if(t!==this.decorModelToken||i&&!this.pendingTrafficModels.has(e.id))return;const c=this.decorGroups.get(e.id);if(!c)return;!i&&e.kind!=="tree"&&es.reflectOn(l);const h={ref:JSON.stringify(n),scene:l,headingOffsetDeg:n.headingOffsetDeg??s?.headingOffsetDeg,depictedSizeM:s?.sizeM,credit:a,bindings:s?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(s){console.warn(`Keeping the built-in shape for decor "${e.id}":`,s)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=Zf(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||es.reflectOn(i),i)),this.standInScenes.set(e,t)),t}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?yt(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},s=this.decorObjects.find(u=>u.observerSide!==void 0&&Fa(u.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,s?0:this.gaitOffset.eastM,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 a=0,l;if(s){const u=Xs(s,i),p=Ue.occupantView(s,u.headingDeg),f=-(u.headingDeg??0)*vi,g=p.x*Math.cos(f)+p.z*Math.sin(f),m=-p.x*Math.sin(f)+p.z*Math.cos(f),v=u.eastM+n.x,b=-u.northM+n.z;r.x=-(v+g),r.z=-(b+m),this.camera.position.y=this.groundYUnder(v,b)+p.eyeY,l=p.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*vi,-(p.headingDeg+this.indoorLookYawDeg)*vi,0,"YXZ")}this.bodyOrigin={x:n.x+r.x,z:n.z+r.z};const c=this.findCabin(i,n,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,n,r);const h=this.terraces.map(u=>[u.x,u.z,u.cos,u.sin,u.halfWidthM,u.halfLengthM,u.levelY].map(p=>p.toFixed(3)).join(",")).join(";");!s&&this.terraces.length>0&&(this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const u of this.decorObjects){if(u.kind==="terrace")continue;const p=this.decorGroups.get(u.id);if(!p)continue;const f=Xs(u,i),g=f.eastM+n.x+r.x,m=-f.northM+n.z+r.z,v=this.terrainMesh,b=`${v?.geometry.uuid}:${(g-(v?.position.x??0)).toFixed(3)}:${(m-(v?.position.z??0)).toFixed(3)}:${(v?.position.y??0).toFixed(3)}:${f.headingDeg}:${f.altitudeM}:${h}`;if(p.userData.footprintKey!==b){if(u.kind==="wire"){const T=Ue.wireGround(u,g,m,f.headingDeg,(I,R)=>this.groundYUnder(I,R));p.userData.footprintGroundY=T.startY,Ue.shearWire(p,Ue.sizeOf(u).lengthM,T.dropM)}else p.userData.footprintGroundY=this.groundUnderFootprint(u,g,m,f.headingDeg,f.altitudeM);p.userData.footprintKey=b}const y=f.altitudeM>Xe.AIRBORNE_M&&Math.hypot(g,m)<Xe.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:p.userData.footprintGroundY;if(p.position.set(g,y+f.altitudeM,m),u.kind==="crop"){const T=Math.hypot(g,m);p.visible=T<=sk}const x=this.decorPresence.get(u.id),S=x!==void 0&&(i<x.fromMs||i>x.untilMs);x&&(p.visible=!S);const A=this.decorSunlight.get(u.id);A&&!S&&this.lightFromAbove(p,A),f.headingDeg!==void 0&&(p.rotation.y=-f.headingDeg*vi);const w=US(u,i);if(w!==void 0&&Xe.turnHead(p,f.headingDeg??0,w),u.kind==="crop"&&p.visible){const T=this.terrainMesh,I=[T?.geometry.uuid,g-(T?.position.x??0),m-(T?.position.z??0),p.position.y-(T?.position.y??0),f.headingDeg,f.altitudeM].map(R=>typeof R=="number"?R.toFixed(4):R).join(":");p.userData.cropGroundKey!==I&&(Ue.fitCropToGround(p,(R,O)=>this.groundYUnder(R,O)+f.altitudeM),p.userData.cropGroundKey=I)}if(!S){const T=p.position.distanceTo(this.camera.position);a=Math.max(a,T),T<Xe.trafficModelRangeM(u)&&this.pendingTrafficModels.delete(u.id)&&this.loadDecorModel(u,this.decorModelToken)}}if(s&&l!==void 0){const u=this.decorGroups.get(s.id);u&&(this.camera.position.y=u.position.y+l)}this.updateContrails();const d=Math.max(Hd*1.2,this.groundRadius*2.5,a*1.2);Math.abs(this.camera.far-d)>1&&(this.camera.far=d,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let n=i;for(const s of this.terraces){const r=e-s.x,a=t-s.z,l=r*s.cos-a*s.sin,c=r*s.sin+a*s.cos;if(Math.abs(l)<=s.halfWidthM&&Math.abs(c)<=s.halfLengthM){const h=Math.min(1,Math.max(0,(s.halfWidthM-Math.abs(l))/s.bankM)),d=h*h*(3-2*h);n=Math.max(n,d*s.levelY+(1-d)*Math.min(s.levelY,i))}}return n}placeTerraces(e,t,i){this.terraces=[];const n=this.terrainMesh;for(const s of this.decorObjects){if(s.kind!=="terrace")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xs(s,e),l=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=Ue.sizeOf(s),d=-(a.headingDeg??0)*vi,u=Math.cos(d),p=Math.sin(d),f=`${n?.geometry.uuid}:${(l-(n?.position.x??0)).toFixed(3)}:${(c-(n?.position.z??0)).toFixed(3)}:${(n?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(l,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=Ue.fitTerrace(r,s,(g,m)=>this.terrainYUnder(l+g*u+m*p,c-g*p+m*u)),r.userData.terraceKey=f),this.terraces.push({x:l,z:c,cos:u,sin:p,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:r.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(e,t){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,e-i.position.x,t-i.position.z):lm}patchSpacingM(e){const t=e.geometry.getAttribute("position");return t&&t.count>=2?Math.abs(t.getX(1)-t.getX(0)):1/0}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 lm;const r=n.getX(0),a=n.getX(s-1),l=n.getZ(0),c=n.getZ((s-1)*s),h=or((t-r)/(a-r)*(s-1),0,s-1),d=or((i-l)/(c-l)*(s-1),0,s-1);if(!Number.isFinite(h)||!Number.isFinite(d))return lm;const u=Math.min(Math.floor(h),s-2),p=Math.min(Math.floor(d),s-2),f=h-u,g=d-p,m=(x,S)=>n.getY(x*s+S),v=m(p,u),b=m(p,u+1),M=m(p+1,u),y=m(p+1,u+1);return f+g<=1?v+(b-v)*f+(M-v)*g:y+(M-y)*(1-f)+(b-y)*(1-g)}groundUnderFootprint(e,t,i,n,s=0){return Ue.groundUnderFootprint(e,t,i,n,(r,a)=>this.groundYUnder(r,a),s)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;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}skyUnknown=!1;setSkyUnknown(e){e!==this.skyUnknown&&(this.skyUnknown=e,this.render())}perception=ns.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}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),i=e?ns.NONE:this.perception??ns.NONE;if(vn.uColorVision.value.set(...i.colorMatrix),vn.uContrast.value=i.contrastGain,!e){vn.uMedium.value=0;return}vn.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:3;const n=e.autoExposure||this.skyUnknown?this.scatteredSky?.sceneAdaptation:void 0;vn.uMediumExposure.value=n!==void 0&&n>0?1/(t*n):.065*e.exposureSeconds*e.iso*this.filterTransmittance/(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 we;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&&Ue.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 a=n.kind==="streetlight"&&n.origin!==void 0&&n.lit===void 0&&!n.litKeyframes?.length&&this.lastAstronomy,l=n.kind==="vehicle"?HM(n,e):void 0,c=a?this.lastAstronomy.sun.altitudeDeg<HC:l!==void 0?Na.lamps(l):Dp(n,e);Ue.setLit(r,n.kind,c,this.relativeScale);const h=this.streetlightLights.get(n.id);h&&(h.visible=c),l!==void 0&&(this.headlightSettings.set(n.id,l),this.aimDecorBeam(n,r,l))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=_e(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-NhpS6K9T.js");return{HeadlightSystem:e}},[],import.meta.url).then(({HeadlightSystem:e})=>{this.headlightSystem??=new e(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const e=this.headlightSystem;if(e){for(const t of this.decorObjects)t.kind==="vehicle"&&e.add(t.id);this.observerHeadlights&&e.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const e of this.decorObjects){const t=this.headlightSettings.get(e.id),i=this.decorGroups.get(e.id);t!==void 0&&i&&this.aimDecorBeam(e,i,t)}this.aimObserverBeam()}}headlightScatterPerM(){const e=this.siteElevationM+this.camera.position.y,t=200,i=this.air.transmittance(e,e,t)[1];return i>0?-Math.log(Math.min(1,i))/t:.05}aimDecorBeam(e,t,i){if(!this.headlightSystem?.has(e.id))return;t.updateMatrixWorld(!0);const n=new D(0,0,-1).transformDirection(t.matrixWorld);if(n.y=0,n.lengthSq()<1e-9)return;n.normalize();const s=Ue.sizeOf(e).lengthM,r=t.getWorldPosition(new D).addScaledVector(n,s/2-VC);r.y+=GC;const a=Ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,n,a*WC,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(e){this.observerHeadlights=e,e&&this.loadHeadlights(),this.headlightSystem&&(e?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const e=this.observerHeadlights;if(!e||!this.headlightSystem?.has("observer"))return;const t=e.setting==="auto"?this.lastAstronomy?Na.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,n=new D(Math.sin(i),0,-Math.cos(i)),s=new D(n.x*Sb,this.camera.position.y-$C,n.z*Sb);this.headlightSystem.aim("observer",t,s,n,XC,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i){const n=Ue.bodyOf(t),s=n.children.find(a=>a.userData.emissive);if(!s)return;const r=new Uw(16764006,xb*this.relativeScale,YC);r.position.copy(s.position).multiply(n.scale),r.castShadow=i,r.shadow.mapSize.set(512,512),r.shadow.bias=-.002,t.add(r),this.streetlightLights.set(e,r)}applyWindowGlow(){const e=this.lastAstronomy;Ue.setLitWindowShare(e?mn.share(e.sun.altitudeDeg,e.localHour):0)}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.applyWindowGlow(),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 a=Ws.luminanceOf(r);if(!(a>0))return[0,0,0];const l=De.relativeOfResponse(a)/a;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.sunBeamFraction=Ri.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,Mb,new ne(1,.96,.88),e.sun.magnitude),this.placeEclipse(e),this.setMoonMesh(e.moon,t),this.buildPlanets(e.planets,t),this.buildComet(e.comet,t),this.buildNovae(e.novae??[],t)}placeEclipse(e){const t=e.eclipse;if(!t||e.sun.altitudeDeg<fu){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=Mb/$n*(180/Math.PI),n=i/t.sunRadiusDeg,s=si(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=si(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(or(s.x*r.x+s.y*r.y+s.z*r.z,-1,1)),l=a>1e-9?or(t.separationDeg*n*vi/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-l)*a)/c,Math.sin(l*a)/c]:[1,0],u={x:s.x*h+r.x*d,y:s.y*h+r.y*d,z:s.z*h+r.z*d},p=t.moonRadiusDeg*n;this.eclipseDiscs={sun:new D(s.x,s.y,s.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*vi,moonRadiusRad:p*vi};const f=.01,g=(b,M)=>si(e.sun.altitudeDeg+b,e.sun.azimuthDeg+M,1),m={x:g(f,0).x-g(-f,0).x,y:g(f,0).y-g(-f,0).y,z:g(f,0).z-g(-f,0).z},v={x:g(0,f).x-g(0,-f).x,y:g(0,f).y-g(0,-f).y,z:g(0,f).z-g(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:n,up:m,right:v}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Vl(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(s,this.sunDiscRadiance)}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??Xe.relativeSkyOf(O0(e.sun.altitudeDeg),this.relativeScale),i=t,n=this.lightUnderClouds(e),s=r=>n?[0,1,2].map(a=>r[a]*n.through+n.radiance[a]*(1-n.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=s(i.airlight),this.skyMesh&&this.skyGradientMaterial&&(this.skyMesh.material=this.scatteredSky?.ready?this.scatteredSky.material:this.skyGradientMaterial),this.updateCelestialLight(e,t),this.updateCloudLighting(e.sun,this.baseFogColor),ke.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const r of this.streetlightLights.values())r.intensity=xb*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?He.DEFAULT_AEROSOL_OPTICAL_DEPTH:Xr.opticalDepth(i))*He.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=Tt.aureoleScale(n,Tt.airMass(e.altitudeDeg))*s,l=Tt.coronaScale(r),c=Tt.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.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 nv,this.celestialGroup.add(this.lunarDiffraction.object));const d=Tt.profile(Tt.HAZE_COARSE_MODE),u=Tt.profile(Tt.CLOUD_DROPLETS),p=Ny(e.altitudeDeg),f=new Float32Array(Tt.STEPS*3);let g=0;for(let M=0;M<Tt.STEPS;M++){const y=M*3,x=[0,1,2].map(A=>c*p[A]*(a*d[y+A]+l*u[y+A])),S=Ws.shown(x,Ws.luminanceOf(x),(A,w)=>t.relativeOfLuminance(A,w));f.set(S,y),g=Math.max(g,Ws.response(S))}const{x:m,y:v,z:b}=si(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(g>1/200?{x:m,y:v,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof Bo||(this.scene.fog=new Bo),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)))}umbraTint(){const e=this.siteElevationM+this.observerElevationM+1.6,[t,i,n]=this.air.transmittance(e,e,Xe.UMBRA_PATH_M),s=.2126*t+.7152*i+.0722*n;return s>0?[(.4124*t+.3576*i+.1805*n)/s,1,(.0193*t+.1192*i+.9505*n)/s]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(e){const t=e.eclipse?.horizonShare;return t&&Math.max(...t)<.1?{share:t,tint:this.umbraTint()}:void 0}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},sunLight:Ri.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?Ri.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction)}}}pumpScatteredSky(){const e=this.scatteredSky;!e||e.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(e.advance(this.skyHoldUntilMs?ZC:KC),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 q4(em),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Da(-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 qn,this.celestialGroup.add(this.reentrySystem.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):Da(-90,this.instrumentMagnitudeGain);this.reentrySystem.set(e,t,i=>this.cloudTransmission(i),(i,n)=>this.arrivingIlluminance(i,n,1)),this.render()}setLaunchPlumes(e){e.length===0&&!this.plumeSystem?.count||(this.plumeSystem||(this.plumeSystem=new fn,this.celestialGroup.add(this.plumeSystem.object)),this.plumeSystem.set(e,this.relativeScale,t=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),t=>this.cloudTransmission(t)),this.render())}get plumePuffCount(){return this.plumeSystem?.count??0}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(tm*this.camera.fov*Math.PI/180);let s,r=n;const a=new D;for(const[l,c]of this.decorGroups){if(!c.visible||!l.startsWith(As.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.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(tm*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>=$c,s=!n&&e.moon.altitudeDeg>=$c,r=n?e.sun:e.moon,a=[0,0,0],l=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*vi)),c=this.siteElevationM+this.observerElevationM;let h=r,d=n||s?mb.directFraction(r.altitudeDeg,c):0;n&&d<=0&&e.moon.altitudeDeg>=$c&&(h=e.moon,d=mb.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*vi)),p=n||s?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),g=Math.max(0,1/(1+.1125*f)-p),m=[0,0,0];if(n||s){const S=Tt.illuminanceOf(r.magnitude)*i,A=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let R=0;R<3;R++)m[R]=S*A[R]*g*l,this.cloudBeam[R]=S*A[R];const{x:w,y:T,z:I}=si(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(w,T,I),d>0){const R=Tt.illuminanceOf(h.magnitude)*i,O=h===r?A:this.air.transmittanceFromSpace(c,h.altitudeDeg),L=h===r?p:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=R*O[P]*L*d}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),A=t.skyIrradiance,w=[0,1,2].map(I=>A[I]*S+m[I]);this.skyLight.color.setRGB(w[0],w[1],w[2]);const T=Ke.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(T*(w[0]+a[0]*u),T*(w[1]+a[1]*u),T*(w[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!n&&!s||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:M,z:y}=si(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,M,y),this.celestialLight.shadow.normalBias=bb*or(M/LC,.1,1),this.placeShadowFrustum();const x=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/x,a[1]/x,a[2]/x),this.celestialLight.intensity=x,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=Bn.litFraction(t.sunElevationDeg,t.heightM);if(s>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=Tt.illuminanceOf(i.magnitude)*this.relativeScale,l=t.heightM>=Xe.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)n[c]=Math.max(0,a*r[c]*s*l-this.sceneSunBeam[c])}}e.traverse(s=>{const r=s.material;if(!(r instanceof za||r instanceof Ea)||s.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=Xe.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*n[0]*a,r.color.g*n[1]*a,r.color.b*n[2]*a)})}lightDirection=new 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,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),a=c=>{const h=r.dot(c)/i;return(h-Math.round(h))*i},l=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(n,a(n)).addScaledVector(s,a(s));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(l).addScaledVector(e,this.shadowLightDistanceM)}fitShadowToCabin(e){if(e===this.cabinShadow)return;this.cabinShadow=e;const t=this.celestialLight.shadow;if(!e){this.shadowHalfExtentM=-1;return}const i=t.camera,n=kC;i.left=-n,i.right=n,i.top=n,i.bottom=-n,this.shadowHalfExtentM=n,this.shadowLightDistanceM=Gd+5,i.near=this.shadowLightDistanceM-Gd,i.far=this.shadowLightDistanceM+Gd,i.updateProjectionMatrix(),t.bias=-.004/(2*Gd),t.mapSize.x!==2048&&(t.mapSize.set(2048,2048),t.map?.dispose(),t.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(e){for(const t of e)t.traverse(i=>{const n=i.material;for(const s of Array.isArray(n)?n:n?[n]:[]){const r=s;r.isMeshStandardMaterial&&r.envMapIntensity!==Xe.CABIN_SKY_SHARE&&(r.envMapIntensity=Xe.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(CC,Math.max(da,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(Xc,t*(Xc/da));this.shadowLightDistanceM=Math.max($n,s+10),n.near=this.shadowLightDistanceM-s,n.far=this.shadowLightDistanceM+s,n.updateProjectionMatrix(),i.bias=-.03/(2*s);const r=t>2*da?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=da;shadowLightDistanceM=$n;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*vi,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/De.semiSaturation(De.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new rn,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=Ut.starPointsOf(e),i=Ut.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=ce.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return Da(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,i=0){const n=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=n-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,n,i)}filterTransmittance=1;render(){this.restatingExposure||(this.sceneVersion++,this.frameDirty=!0,this.resolution.noteChange(performance.now()),!this.suspended&&(this.syncAnimationLoop(),!(this.animationFrameId!==null||this.framesDriven||this.flushFrameId!==null)&&(this.flushFrameId=requestAnimationFrame(()=>{this.flushFrameId=null,this.drawIfDirty()}))))}drawIfDirty(){if(!(!this.frameDirty||this.contextReleased||this.suspended)){if(this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy),this.compileBeforeNextDraw){this.compileBeforeNextDraw=!1;const 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.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.refreshReflections(),this.resolution.beginDrawing();try{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()+Xe.COMPILE_WAIT_MS;return new Promise(n=>{const s=()=>{if(this.contextReleased)return n();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.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())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(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()}cabinDecor(){return this.cabinGroups}cabinGroups=[];findCabin(e,t,i){const n=[];for(const s of this.decorObjects){if(s.kind!=="aircraft"||s.observerSide!==void 0&&Fa(s.kind))continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=Xs(s,e),l=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=Ue.sizeOf(s),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(l,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&n.push(r)}return this.cabinGroups=n,n}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new es(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(a=>a.mesh)],i=[...this.starTiers.map(a=>a.points),...[...this.bodyMeshes.values()].filter(a=>a instanceof hs),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(a=>a!==void 0),...this.cabinDecor()],n=this.relativeScale,s=this.sceneVersion,r=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values()],s,i,a=>this.measureSurroundings(a,n,s),e?0:es.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 hh;const s=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>si(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,s,r=>{const a=p=>p.map(f=>f/t),l=this.surroundings,c={up:a(r.up),down:a(r.down)},h=(p,f)=>p.some((g,m)=>Math.abs(g-f[m])>.03*Math.max(Math.abs(g),Math.abs(f[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>=$c?e.sun:e.moon.altitudeDeg>=$c?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,vk);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.aimBeams(),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,a,l)=>this.directionAtScreenPoint(r,a,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()),vn.uRodShare.value=this.scatteredSky?.rodShare??0,vn.uRelativeScale.value=this.relativeScale,this.applyMedium();const n=this.references.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);vn.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,this.pointLayerHost)}pointLayerHost={points:()=>{const e=[];return this.celestialGroup.traverse(t=>{(t instanceof hs&&t.userData.pointSource||t instanceof Se&&t.userData.skyRibbon)&&e.push(t)}),e},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(e=this.camera){this.renderReferencesPass(e),this.renderBodiesOverReferences(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(Jf),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=n}renderBodiesOverReferences(e){if(!this.references.any||!this.bodySystem.any)return;const t=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(L2),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new Vn({blending:Uh,blendSrc:th,blendDst:th,blendSrcAlpha:th,blendDstAlpha:th,toneMapped:!1});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(N2),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&&Xe.markDecorDepth(s,n.kind!=="crop")}e.layers.set(jf),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null,e.layers.set(O2),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}decorDepthMaterial=new Vn({colorWrite:!1});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const n=e.getObjectByName("head");if(!n)return;const s=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(Xe.HEAD_TURN_LIMIT_DEG,s));n.rotation.y=-r*vi}static isSolidSurface(e){if(!(e instanceof Se))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==Yi}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Se))return;t&&Xe.isSolidSurface(i)?i.layers.enable(jf):i.layers.disable(jf)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new we),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new qD(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()+Xe.EXPOSURE_BUDGET_MS,s=Xe.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=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=a[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(vn.uRodShare.value=this.scatteredSky?.rodShare??0,vn.uHasOverlay.value=1,vn.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 Tr,t=new Ks(-1,1,1,-1,0,2),i=Wd/(Ab*Math.tan(Tb*vi/2));for(const s of this.compassSprites){if(!s.visible)continue;const r=s.getWorldPosition(new D).sub(this.camera.position).normalize(),a=this.screenPointOf(r);if(!a)continue;const l=new Lc(s.material);l.position.set(a.ndcX,a.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 dn,i=new D,n=this.camera.getWorldDirection(new D),s=this.decorObjects.filter(a=>a.track?.length||a.kind==="aircraft"||a.kind==="vehicle").map(a=>this.decorGroups.get(a.id)),r=this.bodySystem.reflectors.map(a=>a.holder);for(const a of[...s,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<Xe.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 p of[t.min.y,t.max.y])for(const f of[t.min.z,t.max.z]){if(i.set(u,p,f).sub(this.camera.position).normalize(),i.dot(n)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;l=Math.min(l,m),c=Math.max(c,m),h=Math.min(h,v),d=Math.max(d,v)}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 we),i=Math.max(1,Math.round(t.x)),n=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new uh(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 we);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new tv(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new we);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new pi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){const n=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!n){e.setFromCamera(new we(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 pi.ndcFor(t,this.camera.fov,n);if(t.z>=0)return;const s=Math.tan(this.camera.fov/2*vi);return{ndcX:t.x/-t.z/(n*s),ndcY:t.y/-t.z/s}}screenPointScratch=new D;screenPointQuaternion=new Dn;screenPointSize=new we;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(gb),this.camera.layers.set(gb),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 Ib)this.isSunOccluded(t[0],t[1])||e++;return e/Ib.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 a=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*a).addScaledVector(c,t*a).normalize()}if(this.groundBlocks(this.camera.position,n,s))return!0;if(i.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const r=this.sunOcclusionRaycaster.intersectObjects(i,!0)[0];return r!==void 0&&r.distance<s}groundBlocks(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 v=e.x+t.x*m-s.position.x,b=e.z+t.z*m-s.position.z;if(Math.hypot(v,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),l=Math.round(Math.sqrt(a.count));if(l<2||l*l!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(l-1)],h=[r.position.z+a.getZ(0),r.position.z+a.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,p=i;for(const[m,v,b]of[[e.x,t.x,c],[e.z,t.z,h]]){const M=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(v)<1e-12){if(m<M||m>y)return!1;continue}const x=(M-m)/v,S=(y-m)/v;u=Math.max(u,Math.min(x,S)),p=Math.min(p,Math.max(x,S))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),g=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let m=0;m<=g;m++){const v=u+(p-u)*m/g,b=e.x+t.x*v,M=e.y+t.y*v,y=e.z+t.z*v;if(M<=this.groundYUnder(b,y))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=vb;let n,s;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const l=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>Xe.isSolidSurface(c.object));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.raycaster.ray.origin,n=this.raycaster.ray.direction,s=OC*this.camera.fov*Math.PI/180,r=[...this.hitAreas.entries()].map(([h,d])=>{const u=d.getWorldPosition(new D).sub(i);return{key:h,direction:u.clone().normalize(),radiusRad:Math.atan2(d.scale.x/2,u.length())}}),a=this.eclipseDiscs,l=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=Xe.nearestBody(n,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...l],s);if(c)return this.groundHides(e,t)?void 0:c}pickOpticsAt(e,t){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(e,t)?i:void 0}static nearestBody(e,t,i){let n,s=1/0,r=1/0,a=!1;for(const l of t){const c=Math.acos(or(l.direction.dot(e),-1,1))-l.radiusRad;if(c>i)continue;const h=c<=0,d=s<=0,u=l.inFront===!0;(h!==d?h:h?u!==a?u:l.radiusRad<r:c<s)&&(n=l.key,s=c,r=l.radiusRad,a=u)}return n}pickInterpretationBodyAt(e,t){const i=this.bodySystem.group.children.filter(p=>p.visible&&p.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray.direction,s=this.raycaster.ray.origin,r=RC*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],l=a.length>0?Xe.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new dn,u=new D;for(const p of i){if(d.setFromObject(p),d.isEmpty())continue;d.getCenter(u);const f=d.getSize(new D).length()/2,g=u.clone().sub(s),m=g.length();if(m===0||g.dot(n)<=0||l!==void 0&&l<m-f)continue;const v=Math.acos(Math.min(1,g.normalize().dot(n))),b=Math.atan(f/m);if(b>r){const M=this.raycaster.intersectObject(p,!0)[0];if(!M||l!==void 0&&l<M.distance)continue}else if(v>r)continue;b<h&&(h=b,c=p.name.slice(5))}return c}pickStarAt(e,t){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,n=Math.cos(tm*this.camera.fov*Math.PI/180);let s,r=n;for(const a of this.namedStars){const l=a.direction.dot(i);l>r&&(r=l,s={star:a.star,altitudeDeg:a.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,vb)}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 a=0;a<8;a++){const l=this.bodyCornerScratch.set(a&1?t.max.x:t.min.x,a&2?t.max.y:t.min.y,a&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 dn;bodyCornerScratch=new D;pickPlacedBodyAt(e,t){return this.aimAtScreenPoint(this.raycaster,e,t),this.bodySystem.pick(this.raycaster)}decorScreenBox(e){const t=this.decorGroups.get(e);if(!t||!t.visible)return;const i=this.bodyBoxScratch.setFromObject(t);if(i.isEmpty())return;let n=1/0,s=1/0,r=-1/0,a=-1/0;for(let l=0;l<8;l++){const c=this.bodyCornerScratch.set(l&1?i.max.x:i.min.x,l&2?i.max.y:i.min.y,l&4?i.max.z:i.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;n=Math.min(n,h.ndcX),r=Math.max(r,h.ndcX),s=Math.min(s,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:n,minY:s,maxX:r,maxY:a}}decorGroundPointAt(e,t,i,n=0){const s=this.decorGroups.get(e);if(!s)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(s.position.y+n)),this.decorHitScratch);return r?{x:r.x,z:r.z}:void 0}decorDistanceM(e){const t=this.decorGroups.get(e);return t?Math.hypot(t.position.x-this.camera.position.x,t.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(e){const t=this.decorGroups.get(e);return t?t.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*vi/2):0}decorGrabHeightAt(e,t,i){const n=this.decorGroups.get(e);if(!n)return 0;const s=this.bodyBoxScratch.setFromObject(n).max.y-n.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-n.position.x,0,this.camera.position.z-n.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,n.position),l=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return l?Math.min(Math.max(l.y-n.position.y,0),Math.max(s,0)):0}decorPlaneScratch=new ba;decorHitScratch=new D;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(s=>s&&s.transparent&&s.opacity<Xe.SEE_THROUGH_BELOW)})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],n=Xe.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!n)return;const s=this.bodySystem.pickHit(this.raycaster);if(s!==void 0&&s.distance<n.distance)return;let r=n.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}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.plumeSystem?.dispose(),this.plumeSystem=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())Ue.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.animationFrameId=null,this.frame(t),this.animationFrameId===null&&this.needsAnimationLoop()&&(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.suspended&&this.hasAnimations()}hasAnimations(){return this.starTiers.some(e=>e.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new D;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const e=this.lastAstronomy?.sun;return e!==void 0&&e.altitudeDeg<Xe.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(e){const t=this.skyMesh?.geometry??new Li(Hd,32,16),i=t.attributes.position,n=t.getAttribute("color")??new bt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:l}=jD(i.getX(r),i.getY(r),i.getZ(r)),c=rR(a,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 Vn({vertexColors:!0,side:mi,fog:!1,depthWrite:!1});this.skyGradientMaterial=s,this.skyMesh=new Se(t,s),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=yb(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Lg(this.groundRadius,48),i=new za({color:new ne(Qf,Qf,Qf),fog:!0});Bo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Se(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);const i=this.terrainMesh;let n=0;if(i){const s=i.geometry.getAttribute("position");n=1/0;for(let r=0;r<s.count;r++)Math.abs(s.getX(r)+i.position.x)>600||Math.abs(s.getZ(r)+i.position.z)>600||(n=Math.min(n,s.getY(r)+i.position.y));n=Number.isFinite(n)?Math.min(0,n)-1:0}this.groundMesh.position.y=n,this.groundMesh.renderOrder=0,e.depthTest=!0,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,a])=>`${r}=${Math.round(a.x/10)},${Math.round(a.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=si(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-Ft.alphaAt(i,Math.abs(this.cloudLayerOffset()),s,this.cloudFieldOffset)*FC);const r=t?0:this.weather.highCloudCover??0;return r>0&&(n*=1-Ft.iceAlphaAt(i,Vd,r,this.cloudFieldOffset)*UC),Math.max(0,Math.min(1,n))}setBodyMesh(e,t,i,n,s){if(t.altitudeDeg<fu){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:a,z:l}=si(t.altitudeDeg,t.azimuthDeg,$n),c=Ny(t.altitudeDeg),h=this.cloudTransmission(t),d=this.arrivingIlluminance(t,s,h),u=Xe.unitLuminance(n);let p=this.bodyMeshes.get(e);if(e==="sun"){const f=Math.PI*(i/$n)**2,g=[0,1,2].map(v=>u[v]*d[v]/(this.sunBeamFraction*f));this.sunDiscRadiance=g;const m=g.map(v=>Math.min(Xe.BRIGHTEST_RELATIVE,v));p instanceof Se||(this.disposeMesh(p),p=new Se(new Li(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)),p.material.color.setRGB(m[0],m[1],m[2]),p.scale.setScalar(i)}else{if(!(p instanceof hs)){this.disposeMesh(p);const m=new lt;m.setAttribute("position",new rt(new Float32Array(3),3)),m.setAttribute("color",new rt(new Float32Array(3),3)),p=new hs(m,ke.material(tc[tc.length-1].size,!1)),ke.track(p),this.celestialGroup.add(p),this.bodyMeshes.set(e,p)}const f=p.geometry.getAttribute("color"),g=e.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*d[0]*g,u[1]*d[1]*g,u[2]*d[2]*g),f.needsUpdate=!0}if(p.position.set(r,a,l),this.setHitArea(e,r,a,l,i),e==="sun"&&(this.sunArriving=d),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,l,d,i/$n*(180/Math.PI),Xe.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*f,a*f+this.celestialGroup.position.y,l*f),this.lensFlare||(this.lensFlare=Y4(),this.lensFlare.uniforms.uOpacity.value=tk,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<fu){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:n,y:s,z:r}=si(e.altitudeDeg,e.azimuthDeg,$n),a=this.cloudTransmission(e),l=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??_n.MEAN_RADIUS_DEG,h=$n*Math.tan(c*vi),d=Math.max(or(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/$n)**2,u=new ne(...l.map(g=>Math.min(Xe.BRIGHTEST_RELATIVE,g/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(or(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Lc?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=Xb(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Lc(new lu({map:Xb(e.phase),color:u,fog:!1,blending:Yi,depthWrite:!1})),f.userData.phaseKey=p,this.celestialGroup.add(f),this.bodyMeshes.set(i,f)),f.scale.set(h*2,h*2,1),f.position.set(n,s,r),this.setHitArea(i,n,s,r,h),this.setGlare(i,n,s,r,l,c)}bentLight(e,t,i=PC){const[n,s,r]=this.arrivingIlluminance(e,t,1),a=Math.max(s,1e-30);return{scale:s/i,tint:[n/a,1,r/a]}}static litBySky(e,t){return Xe.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new ne;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,ke.CONE_SOLID_ANGLE/t)}pointScratch=new we;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=Tt.illuminanceOf(t)*i*this.relativeScale;return[n[0]*s,n[1]*s,n[2]*s]}static unitLuminance(e){const t=Ws.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 lu({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Lc(l),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,n);const a=s*2;r.scale.set(a,a,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,a=0){if(cn.radiusDeg(cn.K*Math.max(...s))<=Math.max(r,a)){this.disposeGlare(e);return}let l=this.glareSprites.get(e);l||(l=new cn(`veil:${e}`),this.celestialGroup.add(l.mesh),this.glareSprites.set(e,l)),l.shine({x:t,y:i,z:n},s,r,a)}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=Ul(e.magnitude,t),s=zf(n);this.cometKey=i,this.setBodyMesh(i,e.position,im*(.5+.5*n),new ne(s,s,s),e.magnitude),this.cometTail||(this.cometTail=new ls($n),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,n)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new Di,this.iceHalos.setCloudOffset(this.cloudFieldOffset),this.iceHalos.onReady=()=>this.render(),this.celestialGroup.add(this.iceHalos.object)),this.iceHalos.setUrgent(!!this.skyHoldUntilMs);const i=this.highCloudCover(),n=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(n?.offset??this.cloudFieldOffset),this.layeredClouds?.hostHalo(this.iceHalos),i===void 0){this.iceHalos.update({x:0,y:1,z:0},-1,0,[1,1,1],{cover:0,layerHeight:Vd},0);return}const s=this.lowerCloudCover(),r=it.deckLitUntilDeg(it.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,l=this.bentLight(a,a===e?ut.SUN_MAGNITUDE:t.magnitude),c=it.strength(i,s,a.altitudeDeg,r)*l.scale,{x:h,y:d,z:u}=si(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,l.tint,{cover:n?.cover??i,layerHeight:n?.layerHeight??Vd},n?.iceCrystalAlignment??this.weather.iceCrystalAlignment??gu,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Io,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(),a=this.bentLight(s,n?ut.SUN_MAGNITUDE:t.magnitude,NC),l=Sn.strength(i,r,s.altitudeDeg)*a.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}=si(s.altitudeDeg,s.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},l,a.tint,n)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Ma,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:n}=e.frame,s=cs.galactic(i,n),r=Xe.directionOf(s.centre),a=Xe.directionOf(s.rotation),l=Xe.directionOf(s.pole),c=new Je().set(r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z),h=Xe.directionOf(cs.eclipticPole(i,n)),d=Xe.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:Xe.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:ce.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}=si(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=Ul(n.magnitude,t),a=zf(r);this.setBodyMesh(s,n.position,im*(.5+.5*r),new ne(a,a,a),n.magnitude)}for(const n of this.novaKeys)i.has(n)||(this.disposeMesh(this.bodyMeshes.get(n)),this.bodyMeshes.delete(n),this.disposeHitArea(n),this.disposeGlare(n));this.novaKeys=i}disposeComet(){this.cometTail?.set(void 0,void 0,0),this.cometKey&&(this.disposeMesh(this.bodyMeshes.get(this.cometKey)),this.bodyMeshes.delete(this.cometKey),this.disposeHitArea(this.cometKey),this.disposeGlare(this.cometKey),this.cometKey=void 0)}buildPlanets(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=Ul(n.magnitude,t),r=zf(s),a=wk[n.body]??new ne(1,1,1),l=new ne(a.r*r,a.g*r,a.b*r),c=im*(.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 Hs(n,s),a=um(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:p}=r.position(i.ra[h],i.dec[h]);if(u<wb)continue;const{x:f,y:g,z:m}=si(u,p,em);l.push({x:f,y:g,z:m,brightness:Ul(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(v=>v*Tt.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of A4){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<wb)continue;const{x:p,y:f,z:g}=si(d,u,em);this.namedStars.push({star:h,direction:new D(p,f,g).normalize(),altitudeDeg:d})}this.starTiers=tc.map((h,d)=>{const u=l.filter(x=>Vg(x.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),g=new Float32Array(u.length*3),m=new Float32Array(u.length),v=new Float32Array(u.length);u.forEach((x,S)=>{p[S*3]=x.x,p[S*3+1]=x.y,p[S*3+2]=x.z,f[S]=x.brightness,g.set(x.illuminance,S*3),m[S]=x.phase,v[S]=x.speedFactor});const b=new lt;b.setAttribute("position",new rt(p,3)),b.setAttribute("seed",new rt(m.map(x=>x/(2*Math.PI)),1));const M=new rt(new Float32Array(u.length*3),3);b.setAttribute("color",M);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new hs(b,ke.material(h.size)),ke.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:M,brightness:f,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(e){ke.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 Ql(this.celestialGroup,nm,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 ne(Ka[0]+(am[0]-Ka[0])*t,Ka[1]+(am[1]-Ka[1])*t,Ka[2]+(am[2]-Ka[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}=D0(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=R0(nm);this.cloudMesh=new Se(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}=D0(new ne(...Ka),e,Vd,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Se(R0(nm*1.04),t),this.cirrusMesh.renderOrder=Db-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?Ql.deckOrder(!0,0,1):Db}cloudLayerOffset(){const t=((this.weather.cloudBaseM??ag)-this.observerElevationM)*sm;return Math.sign(t||1)*Math.max(Math.abs(t),nk)}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,a]=this.cloudBeam.map(d=>d/Math.PI),l=this.lightningLevel*dm*this.relativeScale/Math.PI,c=new ne(t[0]+nr.r*l,t[1]+nr.g*l,t[2]+nr.b*l);this.layeredClouds?.setLighting(n.clone(),new ne(s,r,a),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,a*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 dk(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,cm],[this.rainSplashSystem?.points,Za],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:om[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=Lb(hm(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=om[e],i=t.poolSize,n=um(9001),s=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),l=new Float32Array(i),c=new Float32Array(i),h=new Float32Array(i),d=new Float32Array(i),u=new Float32Array(i),p=new Float32Array(i),f=new Float32Array(i);for(let M=0;M<i;M++){const y=n()*Math.PI*2,x=n()*t.radiusM;s[M*3]=Math.cos(y)*x,s[M*3+1]=Cl+n()*(t.topYM-Cl),s[M*3+2]=Math.sin(y)*x,r[M]=n()*Math.PI*2,a[M]=.7+n()*.6,l[M]=.6+n()*.8,c[M]=.4+n()*1.2}const g=new lt;g.setAttribute("position",new rt(s,3)),g.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 ne(...this.baseFogColor)},uTexture:{value:xk(e)},uNearFocusDistance:{value:Fb},uHazeDistance:{value:t.radiusM*Ub}},v=new Dt({uniforms:m,vertexShader:Ik,fragmentShader:Dk,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const b=new hs(g,v);b.renderOrder=rm,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=s,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=l,this.precipitationWobbleAmpJitter=c,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=d,this.precipitationBounceDuration=u,this.precipitationBounceVelX=p,this.precipitationBounceVelZ=f}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=om[i];if(this.precipitationUniforms?.uColor.value.copy(Xe.litBySky(n.color,this.baseFogColor)),t<=0)return;const s=this.weather.windDirectionDeg*vi,r=Math.sin(s)*this.weather.windSpeed*n.driftSensitivity,a=-Math.cos(s)*this.weather.windSpeed*n.driftSensitivity,l=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,M=i==="hail"&&p&&f&&g&&m&&v;for(let y=0,x=0;y<l.length;y+=3,x++){if(M&&p[x]>0){if(p[x]-=t,p[x]<=0){const w=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[y]=Math.cos(w)*T,l[y+1]=n.topYM,l[y+2]=Math.sin(w)*T,p[x]=0}else{const w=1-p[x]/g[x];l[y+1]=Cl+Math.sin(Math.PI*w)*f[x],l[y]=Xd(l[y]+(r+m[x])*t,n.radiusM),l[y+2]=Xd(l[y+2]+(a+v[x])*t,n.radiusM)}continue}let S=0,A=0;if(b){const w=pk*d[x],T=fk*u[x];S=Math.sin(e*w*Math.PI*2+c[x])*T,A=Math.sin(e*w*Math.PI*2+c[x]+Math.PI/2)*T}if(l[y]+=(r+S)*t,l[y+1]-=n.fallSpeedMPerS*h[x]*t,l[y+2]+=(a+A)*t,l[y]=Xd(l[y],n.radiusM),l[y+2]=Xd(l[y+2],n.radiusM),l[y+1]<Cl){if(M){f[x]=Vb*(.2+Math.random()*1.6),g[x]=mk*(.5+Math.random()),p[x]=g[x];const I=Math.random()*Math.PI*2,R=gk*(f[x]/Vb);m[x]=Math.cos(I)*R,v[x]=Math.sin(I)*R,l[y+1]=Cl;continue}const w=Math.random()*Math.PI*2,T=Math.sqrt(Math.random())*n.radiusM;l[y]=Math.cos(w)*T,l[y+1]=n.topYM,l[y+2]=Math.sin(w)*T}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=hm(this.weather.precipitationIntensity);this.rainSystem=V4({count:cm,radiusM:Yc,heightM:rk,bottomYM:Rb,overallSpeed:ak,color:kb.clone(),opacity:.85,visibleCount:this.precipitationCount(cm),speedStreak:Lb(e),pixelSize:zb,seed:9001,nearFocusDistanceM:Fb,hazeDistanceM:Yc*Ub,hazeColor:new ne(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=rm,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=um(4242),t=new Float32Array(Za*3),i=new Float32Array(Za),n=new Float32Array(Za),s=new Float32Array(Za);for(let h=0;h<Za;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Yc;t[h*3]=Math.cos(d)*u,t[h*3+1]=Rb,t[h*3+2]=Math.sin(d)*u,n[h]=Wb(Ob,Pb),i[h]=e()*n[h],s[h]=i[h]/n[h]}const r=new lt;r.setAttribute("position",new rt(t,3));const a=new rt(s,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(Za));const l=new Dt({uniforms:{uMaxSize:{value:hk},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:Nb.clone()},uTexture:{value:Ak()}},vertexShader:Tk,fragmentShader:_k,transparent:!0,depthWrite:!1}),c=new hs(r,l);c.renderOrder=rm,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:n,lifeAttribute:a}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const e=this.rainSystem;if(!e)return;const t=this.weather.windDirectionDeg*vi;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-hm(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(Xe.litBySky(kb,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(Xe.litBySky(Nb,this.baseFogColor));const n=this.weather.windDirectionDeg*vi,s=Math.sin(n)*this.weather.windSpeed,r=-Math.cos(n)*this.weather.windSpeed,a=Yc,l=h=>(h%(a*2)+a*3)%(a*2)-a;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=Hb+(1-Hb)*(1-c),d=Gb+(1-Gb)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=zb*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,a=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())*Yc;i[l]=Math.cos(h)*d,i[l+2]=Math.sin(h)*d,s[c]=Wb(Ob,Pb),n[c]=0}a[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=ji.brightnessAt(l,e);c>i&&(t=l,i=c)}const n=t?Math.min(1,Math.max(.1,(bk/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*dm*this.relativeScale/Math.PI;l.color.setRGB(this.airlight[0]+nr.r*c,this.airlight[1]+nr.g*c,this.airlight[2]+nr.b*c)}const r=this.skyMesh?.material?.color;if(r){const l=s*Mk;r.setRGB(1+l*nr.r,1+l*nr.g,1+l*nr.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=s*dm*this.relativeScale,t){const{x:l,y:c,z:h}=si(25,t.azimuthDeg,$n);this.lightningLight.position.set(l,c,h)}this.lightningBolt||(this.lightningBolt=new wa($n*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=qC.map(e=>{const t=Fo.point(e,this.compassPoints),i=new lu({map:Rk(t),depthTest:!1,fog:!1}),n=new Lc(i),{x:s,y:r,z:a}=si(0,e,Ab);return n.position.set(s,r,a),n.scale.set(Wd,Wd,1),n.renderOrder=jC,n.layers.set(Jf),n.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(n),n}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=Tb*Math.PI/360,i=Wd*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 vi=Math.PI/180;function or(o,e,t){return Math.max(e,Math.min(t,o))}function Wb(o,e){return o+Math.random()*(e-o)}function Xd(o,e){return(o%(e*2)+e*3)%(e*2)-e}let $d,Yd;function xk(o){switch(o){case"snow":return Sk();case"hail":return Ek()}}function Sk(){if($d)return $d;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),$d=new Qr(e),$d}function Ek(){if(Yd)return Yd;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),Yd=new Qr(e),Yd}let qd;function Ak(){if(qd)return qd;const o=64,e=document.createElement("canvas");e.width=o,e.height=o;const t=e.getContext("2d"),i=t.createRadialGradient(o/2,o/2,0,o/2,o/2,o/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,o,o),qd=new Qr(e),qd}const Tk=`
9871
9934
  uniform float uMaxSize;
9872
9935
  uniform float uScale;
9873
9936
  attribute float aLife;
@@ -9880,7 +9943,7 @@ void main() {
9880
9943
  vOpacity = 1.0 - aLife;
9881
9944
  gl_Position = projectionMatrix * mvPosition;
9882
9945
  }
9883
- `,_6=`
9946
+ `,_k=`
9884
9947
  uniform vec3 uColor;
9885
9948
  uniform sampler2D uTexture;
9886
9949
  varying float vOpacity;
@@ -9891,7 +9954,7 @@ void main() {
9891
9954
  if (alpha < 0.01) discard;
9892
9955
  gl_FragColor = vec4(uColor, alpha);
9893
9956
  }
9894
- `,I6=`
9957
+ `,Ik=`
9895
9958
  uniform float uSize;
9896
9959
  uniform float uScale;
9897
9960
  uniform float uNearFocusDistance;
@@ -9917,7 +9980,7 @@ void main() {
9917
9980
  gl_PointSize = max(1.0, uSize * uScale / dist + vNearBlur * 12.0);
9918
9981
  gl_Position = projectionMatrix * mvPosition;
9919
9982
  }
9920
- `,D6=`
9983
+ `,Dk=`
9921
9984
  precision mediump float;
9922
9985
  uniform sampler2D uTexture;
9923
9986
  uniform vec3 uColor;
@@ -9932,13 +9995,13 @@ void main() {
9932
9995
  float blur = max(vNearBlur, vHaze);
9933
9996
  gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
9934
9997
  }
9935
- `;function Xb(o){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,a="#010101",l="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const c=or(o.illuminatedFraction,0,1),h=o.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 Qr(t)}function R6(o){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(o,64,68),new Qr(e)}function um(o){let e=o;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 fp{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;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"),e.setAttribute("always-live",""),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${fp.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<fp.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 pm=7.5,fh=9;class lr{static cache=new Map;static load(e){let t=lr.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>lr.parse(i)),lr.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,a)=>a===0||e[a-1].magnitudeLimit<t);if(i.length<=1)return lr.load(e[0].url);const n=i.map(r=>r.url).join(`
9936
- `);let s=lr.cache.get(n);return s||(s=Promise.all(i.map(r=>lr.load(r.url))).then(r=>r.reduce((a,l)=>lr.concat(a,l))),lr.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 Xt{constructor(e){if(this.heights=e,e.length!==Xt.WIDTH*Xt.HEIGHT)throw new Error(`a lunar relief has ${Xt.WIDTH*Xt.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Xt.SAMPLES_PER_DEGREE;static HEIGHT=180*Xt.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(e,t){const i=Xt.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),a=Math.floor(s),l=n-r,c=s-a,h=(p,f)=>{const g=(p%Xt.WIDTH+Xt.WIDTH)%Xt.WIDTH,m=Math.min(Xt.HEIGHT-1,Math.max(0,f));return this.heights[m*Xt.WIDTH+g]},d=h(r,a)*(1-l)+h(r+1,a)*l,u=h(r,a+1)*(1-l)+h(r+1,a+1)*l;return(d*(1-c)+u*c)*Xt.UNIT_KM}static inBand(e,t){const i=Math.PI/180,n=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return n>=Xt.BAND_FROM_DEG&&n<=Xt.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(Xt.WIDTH*Xt.HEIGHT),r=Xt.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),l=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(s[(c+h)*Xt.WIDTH+(l+d+Xt.WIDTH)%Xt.WIDTH]=Math.round(i/Xt.UNIT_KM));return new Xt(s)}static smooth(){return new Xt(new Int8Array(Xt.WIDTH*Xt.HEIGHT))}}class Ss{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,n=Ss.SAMPLES){const{s,u:r,w:a,distanceKm:l}=Ss.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=Xt.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),g=Math.sin(p),m=f*r[0]+g*a[0],v=f*r[1]+g*a[1],b=f*r[2]+g*a[2];let M=0;for(let y=Ss.SEARCH_FROM_DEG;y<=Ss.SEARCH_TO_DEG;y+=Ss.SEARCH_STEP_DEG){const x=Math.cos(y*c),S=Math.sin(y*c),A=x*s[0]+S*m,w=x*s[1]+S*v,T=x*s[2]+S*b,I=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(w,A)/c,O=d+i.heightKm(I,R),L=Math.atan2(O*S,l-O*x);L>M&&(M=L)}h[u]=M/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/l)/c}}static frame(e,t){const i=new Kr(t.lat,t.lng,t.elevationM),n=Zr(e),s=G0(e,i,!1),r=new It(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*Ss.AU_KM,l=Ss.bodyFixed(e),c=l(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=s4(e,i),p=jg(u),f=Yr(u,new It(-r.x,-r.y,-r.z,n.t)),g=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),m=Math.atan2(-f.y,f.x),v=new It(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),b=new It(-Math.sin(m),-Math.cos(m),0,n.t);return{s:d,u:l(Yr(p,v)),w:l(Yr(p,b)),distanceKm:a}}static surfacePoint(e,t,i,n){const{s,u:r,w:a}=Ss.frame(e,t),l=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*l)*r[d]+Math.sin(i*l)*a[d]),h=[0,1,2].map(d=>Math.cos(n*l)*s[d]+Math.sin(n*l)*c[d]);return{latDeg:Math.asin(h[2])/l,lonDeg:Math.atan2(h[1],h[0])/l}}static radiusAt(e,t){const i=e.radiusDeg.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e.radiusDeg[s]*(1-r)+e.radiusDeg[(s+1)%i]*r}static uncoveredFraction(e,t,i){const n=e.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const l=a/n*2*Math.PI,c=Math.cos(l),h=Math.sin(l),d=c*i.upDeg+h*i.rightDeg,u=d*d-s+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const g=Math.max(0,d-p),m=Math.max(g,e.radiusDeg[a]);f>m&&(r+=.5*(f*f-m*m))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=M4(de.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,a=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],l=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>a(r,l(Math.PI/2-s,a(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new Kr(t.lat,t.lng,t.elevationM),n=Zr(e),s=G0(e,i,!1),r=Ss.bodyFixed(e)(new It(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class mh{static cache=new Map;static load(e){let t=mh.cache.get(e);return t||(t=mh.fetchRelief(e).catch(()=>{}),mh.cache.set(e,t)),t}static async fetchRelief(e){const t=await fetch(e);if(!t.ok)return;let i=new Uint8Array(await t.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new Xt(new Int8Array(i.buffer,i.byteOffset,i.length))}}class mp{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=mp.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=mp.MATRICES[String(e.type)];if(!t)return ns.NONE;const i=Number(e.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>ns.IDENTITY[a]+(r-ns.IDENTITY[a])*n),contrastGain:1}}}class sv{static ID="fatigue";id=sv.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return ns.NONE}}class lo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_LEVEL=.1;id=lo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary). Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:lo.MAX_LEVEL,step:.01,unit:"%"}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(lo.MAX_LEVEL,Number.isFinite(t)?t:0));if(i===0)return ns.NONE;const n=i/lo.MEASURED_LEVEL*lo.MEASURED_LOSS_DB;return{colorMatrix:ns.IDENTITY,contrastGain:10**(-n/20)}}}class zo{static ALL=[new mp,new lo,new sv];static byId(e){return zo.ALL.find(t=>t.id===e)}static perceptionOf(e){return zo.ALL.reduce((t,i)=>ns.combine(t,i.perceive(e?.[i.id]??{})),ns.NONE)}static compact(e){const t={};for(const i of zo.ALL){const n=e[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(t[i.id]=s)}return Object.keys(t).length>0?t:void 0}}class gp{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 Fo.point(e,this.names?.compassPoints)}towards(e){return Fo.towards(e,this.names)}}class rv{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>this.release())}shown=!1;get up(){return this.shown}show(e,t){const i=rv.resolve(e,t);if(!i){this.release();return}this.element.src=i,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}static resolve(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const C6={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},k6="Global Meteor Network",L6="https://globalmeteornetwork.org/data/",O6="“Thunder” by Jerimee",P6="https://creativecommons.org/licenses/by/3.0/",N6="CC BY 3.0";class Zn{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(Zn.text(n));const s=t.currentRoadAttribution;s&&i(Zn.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(Zn.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(Zn.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(Zn.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new zn(Is.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(Zn.text(u))}const a=t.satelliteState;if(a.status==="ready"&&a.credit){const h=document.createElement("li");h.appendChild(Zn.link(a.creditUrl??"",a.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(Zn.link(L6,k6),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(Zn.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(Zn.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=Zn.text(`${O6} (`);c.append(Zn.link(P6,N6),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 F6=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,U6=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,B6=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,z6=20,H6=1;class G6{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}}Oo.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(F6,this.ambientVolume).then(a=>this.applyIfCurrent(a,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/z6,1);const s=i>H6;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(U6,this.windVolume).then(a=>this.applyIfCurrent(a,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(B6,.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 zr{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(zr.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*zr.stumpffC(n),a=t-i*i*i/Math.sqrt(zr.SUN_GM_AU3_PER_DAY2)*zr.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(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(zr.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=a=>{const l=this.inverseSemiMajorAxis*a*a,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*a*a*a*zr.stumpffS(l)+c*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<zr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){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),a=Math.sin(t),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*a*l,y:s*r+n*a*l,z:a*c},{x:-n*a-s*r*l,y:-s*a+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 F2=[{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 mu{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 F2.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=jt(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),a=this.subtract(r,s),l=this.length(r),c=this.length(a),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(a,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(a,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,a){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,a),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 a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-a)}return s}static horizontalOf(e,t,i,n){const s=Yr(e4(),new It(e.x,e.y,e.z,t)),r=Yr(y2(t),s),a=G0(t,new Kr(n.lat,n.lng,n.elevationM),!0),l=new It(r.x-a.x,r.y-a.y,r.z-a.z,t),c=Wp(l);return ev(c.ra,c.dec,i,n)}static earthPositionAt(e){return Yr(QR(),Oa(de.Earth,e))}static julianDayOf(e){return 2451545+jt(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new zr(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 fm=[{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 vp{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return fm.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of fm){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Hs.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 fm.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,a]=i[s-1]??i[0],[l,c]=i[s]??i[0];if(l===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return a+h*(c-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const V6=[{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}],bc=6.5;class ac{static activeAt(e){return V6.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)),a=this.wrappedDelta(i,s),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return a<0?a<-l?0:1+a/l:a>0?a>c?0:1-a/c:1}static observedRatePerHour(e,t,i,n=bc){if(t<=0)return 0;const s=bc-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Hs.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 bi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=jt(e),n=new zp(0,kR(e).elon-90,1),s=Yr(r4(i),Qg(n,i)),r=Wp(s);return ev(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=bc){const i=bi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=bc-t;return(bi.QUIET_RATE_PER_HOUR+i)/Math.pow(bi.POPULATION_INDEX,n)}static schedule(e){const t=new Xp(e.seed^1542469173);return Uo.schedule(e).map(i=>{const n=bi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=bi.turnAround(n,t.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:bi.toHorizontal(a),bearingDeg:bi.bearingFrom(a,n)}})}static turnAround(e,t){const[i,n]=bi.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]=bi.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=bi.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=bi.normalise(bi.cross(e,t));return[i,bi.normalise(bi.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=bi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=bi.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return bi.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 $b="https://ufoathome.org/tle/index.json";class wn{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??wn.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($b)||e.push($b),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${wn.FIRST_SNAPSHOT}T00:00:00Z`)-wn.MAX_ELEMENT_AGE_DAYS*wn.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)-wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS&&e.getTime()<=Date.parse(n.to)+wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const a of Object.keys(i.kinds)){const l=await this.kindAt(a,e,i,n);s.push(...l),r.push(this.coverageOf(a,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*wn.DAY_MS,a=Math.floor(s/r),l=s-a*r<r/2?a-1:a+1,c=new Set(i.kinds[e].bins),h=[a,l].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>c.has(g));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(g=>this.binary(new URL(`${e}/${g}.bin`,n).href))]),p=new Map;for(const g of u)for(const m of wn.decode(g,i.recordBytes)){const v=p.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&p.set(m.norad,m)}const f=[];for(const g of p.values()){const m=Math.abs(g.epochMs-s)/wn.DAY_MS;if(m>wn.MAX_ELEMENT_AGE_DAYS)continue;const v=d[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||f.push({norad:g.norad,name:v.name,kind:e,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],a=t.getTime(),l=wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS,c=n?"covered":a<Date.parse(s)-l?"before":a>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 W6{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=mt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=mt.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:mt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:mt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Ho{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*Ho.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=Ho.degOver(e)/t;return i<1?1:Math.min(Ho.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class an{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 Ho.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return an.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return an.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??an.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=an.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,an.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,n=an.EYE,s=t??e.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(e,t,i){const s=(e.detailUm??an.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*an.ARCSEC_PER_RADIAN,r=1.22*an.WAVELENGTH_M/(i/1e3)*an.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/an.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=an.graspOf(e,t),n=an.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Ut.focalLengthMmFor(e,t.fieldOfViewDeg);return an.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const Yb=111320,qc=Math.PI/180,X6=1.02,$6=1;class gh{static of(e,t){const i=gh.sightings(e,t);if(i.length<2)return;const n=gh.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,l=Math.tan(r.widthDeg/2*qc)===0?0:Math.tan(s.widthDeg/2*qc)/Math.tan(r.widthDeg/2*qc);if(l<X6)return;const c=a/(l-1),h=mt.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:mt.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=ot(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=gh.closedAlongSight(i,n),[r,a,l]=s>=0?[n,i,s]:[i,n,-s];l<$6||r.widthDeg<=a.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:a,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*Yb,n=(t.lng-e.lng)*Yb*Math.cos(e.lat*qc),s=(e.sightAzimuthDeg??0)*qc;return i*Math.cos(s)+n*Math.sin(s)}}class Ln{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:Ln.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:Ln.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:Ln.atLeastNearest(e.derivedM),basis:"derived"};const t=Ln.largest(e.range?.minM,e.crossing?.behindM),i=Ln.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*Ln.MARGIN,s=i===void 0?void 0:i/Ln.MARGIN;return n!==void 0&&s!==void 0?{distanceM:Ln.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(Ln.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 mm=Math.PI/180;class qe{constructor(e,t,i){this.body=e,this.ground=t,this.eyeAt=i;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)qe.collect(this.motionKeys,s.t,s.motions),qe.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;lightKeys=new Map;static collect(e,t,i){for(const[n,s]of Object.entries(i??{})){const r=e.get(n)??[];r.push({t,value:s}),e.set(n,r)}}motionsAt(e){return qe.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?qe.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let a=r.length-1;for(;a>=0&&r[a].t>t;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const l=r[a],c=r[Math.min(a+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=qe.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=ot(e,0),s=ot(e,t),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?yt(s.lat,s.lng,n.lat,n.lng):void 0,l=a?a.x:0,c=a?-a.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+qe.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=qe.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let a=0,l=0;for(;l<qe.MAX_RANGE_M;){if(l=a+Math.max(.5,a*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(a+l)/2;r(h)<=0?l=h:a=h}return l}a=l}}static directionOf(e,t){const i=e*mm,n=t*mm;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)),a=this.body.withObserver&&n.carried&&s.carried?this.eyeAt(e):void 0,l=a?a.eastM+qe.lerp(n.carried.eastM,s.carried.eastM,r):qe.lerp(n.eastM,s.eastM,r),c=a?a.northM+qe.lerp(n.carried.northM,s.carried.northM,r):qe.lerp(n.northM,s.northM,r),h={widthM:qe.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:qe.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:qe.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},d={headingDeg:qe.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:qe.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:qe.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let u;if(a)u=a.upM+qe.lerp(n.carried.upM,s.carried.upM,r);else if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const p=qe.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);u=this.groundUnderFootprint(l,c,h,d.headingDeg)+p+h.heightM/2}else u=qe.lerp(this.centreUpOf(n),this.centreUpOf(s),r);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:l,northM:c,upM:u,sizeM:h,attitude:d,appearance:{color:qe.lerpColor(n.appearance.color,s.appearance.color,r),albedo:qe.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:qe.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r),transparency:qe.lerp(n.appearance.transparency,s.appearance.transparency,r),haloScale:qe.lerp(n.appearance.haloScale,s.appearance.haloScale,r)},flame:qe.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(p=>p.flame!==void 0&&p.flame.luminanceCdM2>0)}}static flameBetween(e,t,i){if(!e||e.luminanceCdM2<=0)return i>=1&&t&&t.luminanceCdM2>0?t:void 0;const n=e,s=t??e,r={...i<1?n:s,lengthM:qe.lerp(n.lengthM,s.lengthM,i),widthM:qe.lerp(n.widthM,s.widthM,i),luminanceCdM2:qe.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){return"upM"in e.vertical?e.vertical.upM:this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2}groundUnderFootprint(e,t,i,n){const s=n*mm,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={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+a.eastM*u,t+r.northM*d+a.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??qe.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},l={color:s.appearance?.color??n?.appearance.color??qe.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??qe.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??qe.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??qe.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??qe.DEFAULT_APPEARANCE.haloScale},c=this.positionOf(s,r,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;if(n={t:s.t,...c,sizeM:r,attitude:a,appearance:l,flame:h,present:d},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const u=qe.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:u.eastM*s.distanceM,northM:u.northM*s.distanceM,upM:u.upM*s.distanceM}}i.push(n)}return i}verticalOf(e,t){if(e.onGround)return{aboveGroundM:0};if(e.altitudeAboveGroundM!==void 0)return{aboveGroundM:e.altitudeAboveGroundM};if(e.altitudeM!==void 0)return{upM:e.altitudeM+t.heightM/2}}positionOf(e,t,i){if(e.eastM!==void 0&&e.northM!==void 0)return{eastM:e.eastM,northM:e.northM,vertical:this.verticalOf(e,t)??{aboveGroundM:0}};if(e.azimuthDeg===void 0||e.altitudeDeg===void 0)return;const n=i(e.t);if(!n)return;const s=e.distanceM??(e.onGround?qe.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=qe.directionOf(e.azimuthDeg,e.altitudeDeg),a=n.eastM+r.eastM*s,l=n.northM+r.northM*s;return{eastM:a,northM:l,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpColor(e,t,i){const n=qe.rgbOf(e),s=qe.rgbOf(t);return!n||!s?i<1?e:t:"#"+n.map((r,a)=>Math.round(qe.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!t)return;const i=t[1].length===3?t[1].replace(/./g,"$&$&"):t[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class Et{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],a=r.t-s.t,l=a>0?(t-s.t)/a:0,[c,h]=Et.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,a=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??a;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,p=Et.leadAt(s,t-u);if(!p)return;const f=Et.seenFrom(i,p);if(f.altitudeDeg<0)return;const g=Math.min(Et.FADE_MS,(d-h)/4),m=g>0?Math.min(1,(t-h)/g,(d-t)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),b=l.absoluteMagnitude+5*Math.log10(f.distanceKm/Et.STANDARD_DISTANCE_KM)+v,M=[f],y=(l.trainS??Et.DEFAULT_TRAIN_S)*1e3;for(let x=1;x<=Et.TRAIN_POINTS;x++){const S=Math.min(y*x/Et.TRAIN_POINTS,t-h),A=Et.leadAt(s,t-u-S);if(!A||(M.push(Et.seenFrom(i,A)),S>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:f,magnitude:b,color:l.color??Et.DEFAULT_COLOR,train:M})})}return n}static seenFrom(e,t){const i=Et.ecef(e),n=Et.ecef(t),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],l=e.lat*Et.DEG,c=e.lng*Et.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)*a,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*a,p=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/p)/Et.DEG,azimuthDeg:(Math.atan2(h,d)/Et.DEG+360)%360,distanceKm:p/1e3}}static ecef(e){const t=e.lat*Et.DEG,i=e.lng*Et.DEG,n=Math.sin(t),s=Et.A/Math.sqrt(1-Et.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-Et.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*Et.DEG,u=h.lng*Et.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(a);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]))/Et.DEG,Math.atan2(c[1],c[0])/Et.DEG]}}class St{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=St.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static DEFAULTS={exhaustKgPerS:273,condensedShare:.1,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.1,particleRadiusUm:.5},"methane-lox":{condensedShare:.14,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.2,particleRadiusUm:.5},hypergolic:{condensedShare:.1,particleRadiusUm:.4},solid:{condensedShare:.33,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(e){const t={},i=e.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*St.G0;i.thrustKN!==void 0&&n&&(t.exhaustKgPerS=i.thrustKN*1e3/n),n&&(t.collarExpansionKmPerS=n/1e3*St.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(t,St.PROPELLANTS[i.propellant])}return{...St.DEFAULTS,...t,...e.plume}}static PUFF_EVERY_S=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static sunDirectionAt(e){const t=new Kr(0,0,-6378137),i=yc(de.Sun,e,t,!0,!0),n=(i.ra-r2(e))*15*St.DEG,s=i.dec*St.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static viewsAt(e,t,i,n){const s=[];for(const r of e){const a=St.plumeOf(r),l=r.track[0]?.t??0,c=r.track[r.track.length-1]?.t??0,h=r.burnFromT??l,d=Math.min(r.burnUntilT??c,t);if(d<=h)continue;const u=Math.max(St.PUFF_EVERY_S*1e3,(d-h)/St.MAX_PUFFS),p=a.particleRadiusUm*1e-6,f=6/(4*917*p),g=a.exhaustKgPerS*(u/1e3)*a.condensedShare,m=[{share:1-a.collarShare,expansionKmPerS:a.expansionKmPerS,lifetimeS:a.lifetimeS},{share:a.collarShare,expansionKmPerS:a.collarExpansionKmPerS,lifetimeS:a.collarLifetimeS}];for(let v=d;v>=h;v-=u){const b=(t-v)/1e3;if(b>a.lifetimeS)break;const M=Et.leadAt({id:r.id,track:r.track,fragments:[]},v);if(!M)continue;const y=Et.seenFrom(i,M);if(y.altitudeDeg<0)continue;const x=St.sunlightAt(M,n);if(x.lit<=0)continue;const S=Et.leadAt({id:r.id,track:r.track,fragments:[]},Math.max(l,v-u)),A=S?St.distanceKm(M,S):0,w=St.scatteringPhase(i,M,n);for(const T of m){if(T.share<=0||b>T.lifetimeS)continue;const I=a.initialRadiusKm+T.expansionKmPerS*b+A/2,R=3*g*T.share*f/(2*Math.PI*(I*1e3)**2),O=Math.max(0,1-(b/T.lifetimeS)**2),L=St.SUN_ILLUMINANCE_LUX*St.ALBEDO*w*R*O*x.lit;L<=0||s.push({launchId:r.id,centre:y,radiusDeg:Math.atan2(I,y.distanceKm)/St.DEG,luminanceCdM2:L,sunTransmittance:x.transmittance,lit:x.lit,ageS:b})}}}return s}static sunlightAt(e,t){const i=St.earthCentred(e),n=i[0]*t[0]+i[1]*t[1]+i[2]*t[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*t[0],i[1]-n*t[1],i[2]-n*t[2]),r=St.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(St.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const l=Math.max(0,(s-St.EARTH_RADIUS_KM)*1e3),c=Math.exp(-l/St.SCALE_HEIGHT_M),h=Math.sqrt(2*Math.PI*St.EARTH_RADIUS_KM*1e3*St.SCALE_HEIGHT_M),d=Math.exp(-(((l/1e3-25)/15)**2)),u=[0,1,2].map(p=>Math.exp(-St.RAYLEIGH_PER_M[p]*c*h-St.OZONE_GRAZING_DEPTH[p]*d));return{lit:a,transmittance:u}}static scatteringPhase(e,t,i){const n=St.earthCentred(e),s=St.earthCentred(t),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,l=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,c=St.ANISOTROPY;return(1-c*c)/(4*Math.PI*(1+c*c-2*c*l)**1.5)}static distanceKm(e,t){const i=St.earthCentred(e),n=St.earthCentred(t);return Math.hypot(i[0]-n[0],i[1]-n[1],i[2]-n[2])}static earthCentred(e){const t=e.lat*St.DEG,i=e.lng*St.DEG,n=St.EARTH_RADIUS_KM+e.heightM/1e3;return[n*Math.cos(t)*Math.cos(i),n*Math.cos(t)*Math.sin(i),n*Math.sin(t)]}}class av{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=av.FIRST_DAY}}class Y6{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 q6="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",ng=[{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 Y6(q6,o=>av.mayCover(o),async()=>new(await _e(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-CDtWnd9O.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Pn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=Pn.positionAt(e,i);if(!n)return;const s=Et.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Pn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>Pn.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*Pn.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,a=r.t-s.t;if(a>Pn.MAX_GAP_S*1e3)return;const l=a>0?(t-s.t)/a: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:Pn.wrapLongitude(s.lng+h*l),heightM:c*Pn.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=Pn.positionAt(e,i-500),s=Pn.positionAt(e,i+500);if(!n||!s)return;const r=Pn.unit(Et.seenFrom(t,n.geo)),a=Pn.unit(Et.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[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 qb="https://ufoathome.org/fireballs/index.json";class Ts{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??Ts.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(qb)||e.push(qb),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Ts.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Ts.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=Ts.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=Et.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/Et.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:Ts.COLOR,trainS:Ts.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 Al=Math.PI/180,Kc=180/Math.PI;class Ii{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 a=Ii.projectionOf(r,i,n?.(r));if(a)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...Ii.compare(l,r.id,{aim:c.aim,angular:c.angular},a),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?Ii.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(Ii.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const a=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 a!==void 0&&!Ii.withinSize(a)&&s.push("width"),l!==void 0&&!Ii.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:a,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:Ii.outlineOf(e),s=i&&i.length>0?Ii.centreOf(i):e,r=Ii.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const a=Ii.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=Ii.cross(a,r);let c=1/0,h=-1/0,d=1/0,u=-1/0;for(const p of n){const f={eastM:p.eastM-t.eastM,northM:p.northM-t.northM,upM:p.upM-t.upM},g=Ii.dot(f,r);if(g<=0)return;const m=Math.atan2(Ii.dot(f,a),g),v=Math.atan2(Ii.dot(f,l),g);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,v),u=Math.max(u,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*Kc+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*Kc},angular:{widthDeg:(h-c)*Kc,heightDeg:(u-d)*Kc}}}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*Al,n=t.altitudeDeg*Al,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*Al);return Math.acos(Math.max(-1,Math.min(1,s)))*Kc}static withinSize(e){return e<=Ii.SIZE_TOLERANCE&&e>=1/Ii.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"&&k2.includes(r))for(let d=0;d<=Ii.RINGS;d++){const u=d/Ii.RINGS*Math.PI;for(let p=0;p<Ii.SEGMENTS;p++){const f=p/Ii.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(f),i*Math.sin(u)*Math.sin(f),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const p of[-n,n])s.push([d,u,p]);const l=e.attitude.headingDeg*Al,c=e.attitude.pitchDeg*Al,h=e.attitude.rollDeg*Al;return s.map(([d,u,p])=>{const f=d*Math.cos(h)+p*Math.sin(h),g=-d*Math.sin(h)+p*Math.cos(h),m=u*Math.cos(c)-g*Math.sin(c),v=u*Math.sin(c)+g*Math.cos(c);return{eastM:e.eastM+f*Math.cos(l)+m*Math.sin(l),northM:e.northM-f*Math.sin(l)+m*Math.cos(l),upM:e.upM+v}})}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}}Cp();const K6={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},Z6="{name} — mag {mag}, {alt}° above the horizon",j6="{name} — {size}, {distance} away",J6="{name} — satellite, mag {mag}, {height} km up",U2="satellites-change",B2="fireballs-change",Q6="aircraft-change",ek="rr0-confrontation",tk="{name} — mag {mag}, {alt}° below the horizontal",gm="Credits",Kb="comet:",Zb="nova:",jb={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},ik=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,nk=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,sk=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,rk=-18,ak={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Kd={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Wt 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",ql,Kl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;holding=!1;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 wn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Ts;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=ng[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Wt.trafficRuntimeLoading??=_e(()=>import("./trafficRuntime-XVgt3vom.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>Wt.trafficRuntime=e),Wt.trafficRuntimeLoading.catch(()=>{Wt.trafficRuntimeLoading=void 0}),Wt.trafficRuntimeLoading}traffic;lastSun;decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new G6;vehicleAudio=new AE;aircraftAudio;vehicleHearing=new Wu;decorAircraftHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}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,a=-((e.clientY-i.top)/i.height*2-1),l=this.pickAt(r,a);l?this.showHoverTooltip(e,e.altKey&&l.detail?l.detail():l.name):this.hoverTooltip.hidden=!0};pickAt(e,t){const i=this.naming,n=i.names,s=this.sceneRenderer.pickBodyAt(e,t);if(s)return{kind:"sky",id:s,name:this.bodyName(s)};const r=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,a=r?this.interpretationShown?.bodies.find(g=>g.id===r):void 0,l=a?this.said.read(a.title)||(a.model.id==="figure"?i.decorKind("entity",jb.entity):void 0):void 0;if(r!==void 0&&l)return{kind:"body",id:r,name:l};const c=this.pickDecorAt(e,t),h=c?this.ufoElement.sighting.decor.find(g=>g.id===c):void 0;if(h){const g=this.said.read(h.title)||i.decorKind(h.kind,jb[h.kind]);return{kind:"decor",id:h.id,name:g,detail:()=>this.decorTooltip(h,g)}}const d=this.trafficTooltipAt(e,t);if(d)return{kind:"traffic",name:d};const u=this.sceneRenderer.pickSatelliteAt(e,t);if(u)return{kind:"satellite",name:(n?.satelliteTooltip??J6).replace("{name}",u.name).replace("{mag}",u.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(u.heightKm).toLocaleString())};const p=this.sceneRenderer.pickOpticsAt(e,t);if(p){const g=(n?.opticsTooltips??C6)[p.id].replace("{angle}",String(Math.round(p.angleDeg??0)));return{kind:"optics",id:p.id,name:g.split(" — ")[0],detail:()=>g}}const f=this.sceneRenderer.pickStarAt(e,t);if(f){const g=f.star.mag,m=f.altitudeDeg;return{kind:"star",name:(m<0?n?.starTooltipBelow??tk:n?.starTooltip??Z6).replace("{name}",i.star(f.star)).replace("{mag}",g.toLocaleString(void 0,{maximumFractionDigits:Math.abs(g)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(m))))}}}decorTooltip(e,t){const i=c=>c.toLocaleString(void 0,{maximumFractionDigits:c<10?1:0}),n=Ue.sizeOf(e),s=this.sceneRenderer.decorDistanceM(e.id),r=s===void 0?"":s>=1e3?`${(s/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${i(s)} m`;return(this.naming.names?.decorTooltip??j6).replace("{name}",t).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(Kb)?e.slice(Kb.length):void 0,i=t?F2.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(Zb)?vp.byId(e.slice(Zb.length)):void 0;if(n)return this.naming.nova(n);const s=K6[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new gp;namesLanguage="en";async loadSceneNames(){const e=yh(Is.preferencesFor(this),Sh);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await FM(e);e===this.namesLanguage&&this.applySceneNaming(new gp(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of a){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??gm;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(),n=e.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${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(),ji.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather($h(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now()),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${IE}</style>${_E}`,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 Xe(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.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new rv(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(Om),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"&&Zn.fill(n,this)}),this.creditsButton.title=gm,this.creditsButton.setAttribute("aria-label",gm),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of Wt.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new zn(Is.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:Na.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=ot(e,t);if(!i)return 0;for(const n of[400,-400]){const s=ot(e,t+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=yt(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:e,count:t.length,route:n},n}traceLabels(e){const t=Is.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),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of Wt.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Wt.GESTURES)document.removeEventListener(e,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(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===ql||e===Kl)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[ql,Kl]){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=ot(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}=yt(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)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorGroundPointAt(e,t,i,n=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,n)}decorMetresPerNdcY(e){return this.sceneRenderer.decorMetresPerNdcY(e)}decorGrabHeightAt(e,t,i){return this.sceneRenderer.decorGrabHeightAt(e,t,i)}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=ho.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(this.ufoElement.playRequested?void 0:i.image,this.documentUrl),this.sightingData=i}loader;poster;showPoster(e,t){this.poster.show(e,t)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}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.syncAccountHidden(),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 fp(this,()=>document.createElement(yp))}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.imageSmoothingQuality="high",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){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0: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[...new Map(this.sceneRenderer.currentDecorModelCredits.map(t=>[`${t.title}|${t.author??""}|${t.license}|${t.sourceUrl??""}`,t])).values()]}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=mt.CANVAS_HEIGHT_PX,i=Ut.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:pm,url:this.getAttribute("star-catalog-src")??nk},{magnitudeLimit:fh,url:this.getAttribute("deep-star-catalog-src")??sk}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>pm?fh:pm;const n=await lr.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=fh||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=an.gainFor(e.instrument,{fNumber:ot(e,0)?.fNumber,fieldOfViewDeg:en.fovOf(e,0),exposureSeconds:e.exposure});return Da(rk,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=zs.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=Ho.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,zs.instants(this.decorWithTraffic(this.ufoElement.sighting),ot(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(t.fromMs+t.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-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:en.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Pl.at(e,t,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather($h(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.seatedDecor(this.decorWithTraffic(i),e)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Wt.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??Wt.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=ot(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=ot(i,0),r=Fi(i,0),a=ps(i.event.time??{},n?.lng??Kd.lng,i.event.utcOffsetHours),l=i.weatherSource!==void 0&&a?MS(a):void 0,c=Object.fromEntries(Ca(Fi(i,e)).map(I=>[I.id,Uu(e,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:l)]));this.sceneRenderer.setCloudOffset(Uu(e,i.weatherTrack,r,s,n,void 0,l),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:Kd),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(an.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:en.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,fi.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setPerception(zo.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(Yt.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(ot(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,e)),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 h=n?.lat??Kd.lat,d=n?.lng??Kd.lng,u=ps(i.event.time??{},d,i.event.utcOffsetHours),p={lat:h,lng:d,elevationM:n?.elevationM??0};this.pushSatellitesAt(u,e,p),this.ensureFireballs(u);const f=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(f.length===0?[]:Et.viewsAt(f,e,{lat:h,lng:d,heightM:p.elevationM}));const g=this.interpretationShown?.launches??[];if(this.sceneRenderer.setLaunchPlumes(g.length===0||!u?[]:St.viewsAt(g,e,{lat:h,lng:d,heightM:p.elevationM},St.sunDirectionAt(new Date(u.getTime()+e)))),t&&!t.sky)return;if(this.sceneRenderer.setSkyUnknown(!u),!u){this.sceneRenderer.setAstronomy(ak);return}const m=new Date(u.getTime()+e),v=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/Ho.DEG_PER_SECOND*1e3)),b=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),M=`${Math.floor(m.getTime()/v)}|${Math.round(h/b)}|${Math.round(d/b)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(M===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=M;const y=Ji("Sun",m,p),x=Ji("Moon",m,p);let S=Ri.separationOf(y,x)<1?Ri.viewAt(m,p):void 0;if(S){const I=Ri.offsetOf(y,x,S.separationDeg);if(S.obscuration>Wt.LIMB_FROM_OBSCURATION){const R=this.limbFor(m,p);R&&(S={...S,obscuration:1-Ss.uncoveredFraction(R,S.sunRadiusDeg,I),limb:R})}S={...S,horizonShare:Ri.horizonShare(S,I,y.altitudeDeg,y.azimuthDeg,_n.distanceKm(m,p))}}const A={...y,magnitude:Gf("Sun",m)-2.5*Math.log10(Ri.beamFraction(S))};this.lastSun={altitudeDeg:A.altitudeDeg,azimuthDeg:A.azimuthDeg};const w={...x,phase:oo(m),magnitude:Gf("Moon",m),radiusDeg:_n.apparentRadiusDeg(m,p)},T=w4.map(I=>({body:I,position:Ji(I,m,p),magnitude:Gf(I,m)}));this.sceneRenderer.setAstronomy({sun:A,moon:w,planets:T,comet:this.cometAt(m,p),novae:vp.appearancesAt(m,p).map(({outburst:I,position:R,magnitude:O})=>({id:I.id,position:R,magnitude:O})),stars:this.starCatalog?{catalog:this.starCatalog,date:m,observer:p}:void 0,frame:{date:m,observer:p},localHour:((m.getUTCHours()+m.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(d/15)))%24+24)%24,eclipse:S}),this.ufoElement.setSunAltitude(A.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,mh.load(ik).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(e.getTime()-i.atMs)<5e3&&i.lat===t.lat&&i.lng===t.lng&&i.elevationM===t.elevationM)return i.profile;const n=Ss.profile(e,t,this.limbRelief);return this.limbCache={profile:n,atMs:e.getTime(),lat:t.lat,lng:t.lng,elevationM:t.elevationM},n}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||!Ts.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Wt.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(l=>Ts.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(B2)),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}seatedDecor(e,t){if(!e.some(r=>r.observerKeyframes?.length))return e;const i=e.map(r=>{if(!r.observerKeyframes?.length)return"";const a=Wv(r,t);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===e&&n.seats===i)return n.seated;const s=e.map(r=>{if(!r.observerKeyframes?.length)return r;const a=Wv(r,t);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=ot(e,0),i=t?.lng===void 0?void 0:ps(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 a=Wt.aircraftProviders.get(this.aircraftSource.id);if(a||Wt.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.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=Pn.MAX_GAP_S*1e3,d=Wt.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,g)=>f.TrafficDecor.from(l.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,u)});a.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==l)return;if(f.status!=="found"){l.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await Wt.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=f.tracks,l.set=p(g),this.startAircraftSound(l,g),this.announceTraffic(),this.describeTraffic(a,l,g,p),l.set.shown>0&&this.readUpperAir(l,g,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,a]of n.presence){if(e<a.fromMs||e>a.untilMs)continue;const l=n.flights.get(r),c=l?Pn.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:Bn.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=Wt.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=Wt.trafficRuntime;if(!n)return;const s=t.descriptions?.get(As.keyOf(i)),r=ot(this.ufoElement.sighting,this.lastTimeMs),a={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA($h(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,a,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.newAircraftAudio(t),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,As.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){this.startDecorAircraftSound(e);const i=this.aircraftAudio;if(!i)return;const n=Wt.trafficRuntime;if(!n){i.setVoices([]);return}const s=ot(e,t),r=$h(e,t),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},l=this.trafficVoices(t,s,a,n),c=e.event.place?.[0],h={lat:s?.lat??c?.lat,lng:s?.lng??c?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,l.push(...this.decorAircraftHearing.voices(e,t,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,d=>this.decorModelSounds.get(d.model?.id??""))),l.sort((d,u)=>u.levelDbA-d.levelDbA),l.length=Math.min(l.length,4)),i.setVoices(l,s?.headingDeg??0)}trafficVoices(e,t,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:t?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,As.keyOf,a,s.startMs+e,i)}startDecorAircraftSound(e){const t=e.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(t.length!==0){for(const i of t){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||Wt.trafficRuntime){!this.aircraftAudio&&Wt.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Wt.trafficRuntime));return}Wt.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(e){const t=new e.AircraftAudio;return t.setLevel(this.ufoElement.level),this.interacted&&t.resume(),t.setPaused(this.ufoElement.playbackState!=="playing"),t}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(Q6)),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=>As.keyOf(c))),r=t.tracks.filter(c=>s.has(As.keyOf(c))&&c.points.length>0),a=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(As.keyOf(c),d),a.set(As.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||a.size===0)&&(t.descriptions=l,t.models=a,t.set=n(i,a),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=Wt.upperAirProviders.get(s.id);r||Wt.upperAirProviders.set(s.id,r=s.create());const a=await r.between(e.observer,i,n);this.traffic!==e||a.status!=="found"||(e.air=a.samples,e.airSource=a.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 a=n.presence.get(r.id),l=n.flights.get(r.id);if(!a||!l)continue;const c=Pn.positionAt(l,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:Bn.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ji("Sun",new Date(e.t),t);return Bn.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??Wt.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(U2)))},s=Wt.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,a]=await Promise.all([s.at(e),_e(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const 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=ot(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!t||r===void 0||a===void 0)return[];const l=ps(i.event.time??{},a,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,a,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),p=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=mu.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),a=new Map,l=new Map,c=new Set;for(const f of i.sourceIds){const g=i.getInterpolatedShapeAt(e,f);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};a.set(f,m);const v=g.aim?this.sceneRenderer.screenPointOf(Fs.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},b=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,M=b?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,f):{};c.add(f),(b||g.aim)&&c.delete(f);const y=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),x=this.sizeEstimateOf(f);x.add(y,M);const S=gh.of(t,f);l.set(f,Ln.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&y>0?mt.distanceMAt(S.widthM,y):void 0,range:x.distanceRangeAt(y),crossing:M}))}for(const[f,g]of a)for(const[m,v]of a){if(m===f||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const M=l.get(m);M&&l.set(f,{distanceM:M.distanceM*.999,basis:M.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[f,g]of a)d.push({sourceId:f,shape:g,distanceM:l.get(f).distanceM,renderOrder:h.indexOf(f),aim:g.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(ot(t,e)?.rollDeg??0)+Yt.bodyAt(t,e,this.ufoElement.steadyBody).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:Ut.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=e,this.ufoElement.playerTitle=e?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=qe.eyeOf(this.ufoElement.sighting,i,n);return s?qe.lineOfSightMeetsGround(s,e,t,n):void 0}bodyMaskedBy(e,t){return this.sceneRenderer.bodyMaskedByDecor(e,t)}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>qe.eyeOf(n,u,i),r=new qe(e,i,s).at(t),a=s(t);if(!r||!a)return;const l=r.eastM-a.eastM,c=r.northM-a.northM,h=r.upM-a.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=f=>qe.eyeOf(n,f,i),r=new qe(e,i,s),a=r.at(t)?t:e.track[0]?.t,l=a===void 0?void 0:r.at(a),c=a===void 0?void 0:s(a);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.upM-c.upM,p=Math.hypot(h,d);if(!(p===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,p)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,l=f=>qe.eyeOf(n,f,a);i&&(s=i.bodies.map(f=>new qe(f,a,l).at(e)).filter(f=>f!==void 0));const c=Fi(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(f=>f.id)??[],i?.smoke??[],d);const u=i&&this.comparing?l(e):void 0;if(u&&(r=new Ii(n.timeline).at(e,s,u,f=>f.outlineNode?this.sceneRenderer.bodyOutline?.(f.id,f.outlineNode):void 0)),this.confrontationReadings=r,!t)return;const p=JSON.stringify(r);p!==this.confrontationSignature&&(this.confrontationSignature=p,this.dispatchEvent(new CustomEvent(ek,{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&&Fi(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=Fi(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?ps(n,s?.lng??0,e.event.utcOffsetHours):void 0,a=(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=ji.schedule({durationMs:a,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?ps(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,a=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),l=bi.schedule({ratePerHour:bi.observedRatePerHour(bi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:bi.TYPICAL_VELOCITY_KM_S,seed:a}),c=ac.activeAt(n).map(d=>{const u=ac.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:ac.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=Uo.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:a+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=ot(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Ut.focalLengthMmFor(i,en.fovOf(t,e));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return $s.of(t.instrument,mt.CANVAS_HEIGHT_PX,en.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new W6,this.sizeEstimates.set(e,t)),t}}const yp="rr0-scene";function ok(){Cp(),customElements.get(yp)||customElements.define(yp,Wt)}class lk{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=MM(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class ck{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 Jb="rr0-provider-settings",hk=`
9998
+ `;function Xb(o){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,a="#010101",l="#f4f1e2";i.fillStyle=a,i.beginPath(),i.arc(s,r,n,0,Math.PI*2),i.fill();const c=or(o.illuminatedFraction,0,1),h=o.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 Qr(t)}function Rk(o){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(o,64,68),new Qr(e)}function um(o){let e=o;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 fp{constructor(e,t){this.source=e,this.create=t}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;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"),e.setAttribute("always-live",""),Object.assign(e.style,{position:"fixed",left:"-10000px",top:"0",width:`${fp.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<fp.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 pm=7.5,fh=9;class lr{static cache=new Map;static load(e){let t=lr.cache.get(e);return t||(t=fetch(e).then(i=>i.arrayBuffer()).then(i=>lr.parse(i)),lr.cache.set(e,t)),t}static upTo(e,t){const i=e.filter((r,a)=>a===0||e[a-1].magnitudeLimit<t);if(i.length<=1)return lr.load(e[0].url);const n=i.map(r=>r.url).join(`
9999
+ `);let s=lr.cache.get(n);return s||(s=Promise.all(i.map(r=>lr.load(r.url))).then(r=>r.reduce((a,l)=>lr.concat(a,l))),lr.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 Xt{constructor(e){if(this.heights=e,e.length!==Xt.WIDTH*Xt.HEIGHT)throw new Error(`a lunar relief has ${Xt.WIDTH*Xt.HEIGHT} samples, not ${e.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*Xt.SAMPLES_PER_DEGREE;static HEIGHT=180*Xt.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(e,t){const i=Xt.SAMPLES_PER_DEGREE,n=(t%360+360)%360*i-.5,s=(90-e)*i-.5,r=Math.floor(n),a=Math.floor(s),l=n-r,c=s-a,h=(p,f)=>{const g=(p%Xt.WIDTH+Xt.WIDTH)%Xt.WIDTH,m=Math.min(Xt.HEIGHT-1,Math.max(0,f));return this.heights[m*Xt.WIDTH+g]},d=h(r,a)*(1-l)+h(r+1,a)*l,u=h(r,a+1)*(1-l)+h(r+1,a+1)*l;return(d*(1-c)+u*c)*Xt.UNIT_KM}static inBand(e,t){const i=Math.PI/180,n=Math.acos(Math.cos(e*i)*Math.cos(t*i))*180/Math.PI;return n>=Xt.BAND_FROM_DEG&&n<=Xt.BAND_TO_DEG}static withBump(e,t,i,n=.4){const s=new Int8Array(Xt.WIDTH*Xt.HEIGHT),r=Xt.SAMPLES_PER_DEGREE,a=Math.ceil(n*r),l=Math.floor(t*r),c=Math.floor((90-e)*r);for(let h=-a;h<=a;h++)for(let d=-a;d<=a;d++)Math.hypot(d,h)<=a&&(s[(c+h)*Xt.WIDTH+(l+d+Xt.WIDTH)%Xt.WIDTH]=Math.round(i/Xt.UNIT_KM));return new Xt(s)}static smooth(){return new Xt(new Int8Array(Xt.WIDTH*Xt.HEIGHT))}}class Ss{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(e,t,i,n=Ss.SAMPLES){const{s,u:r,w:a,distanceKm:l}=Ss.frame(e,t),c=Math.PI/180,h=new Float32Array(n),d=Xt.REFERENCE_RADIUS_KM;for(let u=0;u<n;u++){const p=u/n*2*Math.PI,f=Math.cos(p),g=Math.sin(p),m=f*r[0]+g*a[0],v=f*r[1]+g*a[1],b=f*r[2]+g*a[2];let M=0;for(let y=Ss.SEARCH_FROM_DEG;y<=Ss.SEARCH_TO_DEG;y+=Ss.SEARCH_STEP_DEG){const x=Math.cos(y*c),S=Math.sin(y*c),A=x*s[0]+S*m,w=x*s[1]+S*v,T=x*s[2]+S*b,I=Math.asin(Math.max(-1,Math.min(1,T)))/c,R=Math.atan2(w,A)/c,O=d+i.heightKm(I,R),L=Math.atan2(O*S,l-O*x);L>M&&(M=L)}h[u]=M/c}return{radiusDeg:h,meanRadiusDeg:Math.asin(d/l)/c}}static frame(e,t){const i=new Kr(t.lat,t.lng,t.elevationM),n=Zr(e),s=G0(e,i,!1),r=new It(s.x-n.x,s.y-n.y,s.z-n.z,n.t),a=Math.hypot(r.x,r.y,r.z)*Ss.AU_KM,l=Ss.bodyFixed(e),c=l(r),h=Math.hypot(c[0],c[1],c[2]),d=[c[0]/h,c[1]/h,c[2]/h],u=s4(e,i),p=jg(u),f=Yr(u,new It(-r.x,-r.y,-r.z,n.t)),g=Math.asin(f.z/Math.hypot(f.x,f.y,f.z)),m=Math.atan2(-f.y,f.x),v=new It(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),n.t),b=new It(-Math.sin(m),-Math.cos(m),0,n.t);return{s:d,u:l(Yr(p,v)),w:l(Yr(p,b)),distanceKm:a}}static surfacePoint(e,t,i,n){const{s,u:r,w:a}=Ss.frame(e,t),l=Math.PI/180,c=[0,1,2].map(d=>Math.cos(i*l)*r[d]+Math.sin(i*l)*a[d]),h=[0,1,2].map(d=>Math.cos(n*l)*s[d]+Math.sin(n*l)*c[d]);return{latDeg:Math.asin(h[2])/l,lonDeg:Math.atan2(h[1],h[0])/l}}static radiusAt(e,t){const i=e.radiusDeg.length,n=(t/360*i%i+i)%i,s=Math.floor(n),r=n-s;return e.radiusDeg[s]*(1-r)+e.radiusDeg[(s+1)%i]*r}static uncoveredFraction(e,t,i){const n=e.radiusDeg.length,s=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let r=0;for(let a=0;a<n;a++){const l=a/n*2*Math.PI,c=Math.cos(l),h=Math.sin(l),d=c*i.upDeg+h*i.rightDeg,u=d*d-s+t*t;if(u<=0)continue;const p=Math.sqrt(u),f=d+p;if(f<=0)continue;const g=Math.max(0,d-p),m=Math.max(g,e.radiusDeg[a]);f>m&&(r+=.5*(f*f-m*m))}return Math.min(1,Math.max(0,r*(2*Math.PI/n)/(Math.PI*t*t)))}static AU_KM=1495978707e-1;static bodyFixed(e){const t=M4(de.Moon,e),i=Math.PI/180,n=t.ra*15*i,s=t.dec*i,r=t.spin*i,a=(c,[h,d,u])=>[Math.cos(c)*h+Math.sin(c)*d,-Math.sin(c)*h+Math.cos(c)*d,u],l=(c,[h,d,u])=>[h,Math.cos(c)*d+Math.sin(c)*u,-Math.sin(c)*d+Math.cos(c)*u];return c=>a(r,l(Math.PI/2-s,a(Math.PI/2+n,[c.x,c.y,c.z])))}static subObserverPoint(e,t){const i=new Kr(t.lat,t.lng,t.elevationM),n=Zr(e),s=G0(e,i,!1),r=Ss.bodyFixed(e)(new It(s.x-n.x,s.y-n.y,s.z-n.z,n.t)),a=Math.hypot(r[0],r[1],r[2]);return{latDeg:Math.asin(r[2]/a)*180/Math.PI,lonDeg:Math.atan2(r[1],r[0])*180/Math.PI}}}class mh{static cache=new Map;static load(e){let t=mh.cache.get(e);return t||(t=mh.fetchRelief(e).catch(()=>{}),mh.cache.set(e,t)),t}static async fetchRelief(e){const t=await fetch(e);if(!t.ok)return;let i=new Uint8Array(await t.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const n=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(n).arrayBuffer())}return new Xt(new Int8Array(i.buffer,i.byteOffset,i.length))}}class mp{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=mp.ID;label="Colour vision";hint="How colours look to someone whose cones differ, from Machado et al. 2009. Only recolours: it does not change brightness or what the eye can resolve.";sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",label:"Type",kind:"choice",default:"normal",choices:[{id:"normal",label:"Typical"},{id:"protan",label:"Protan (red-weak or red-blind)"},{id:"deutan",label:"Deutan (green-weak or green-blind)"},{id:"tritan",label:"Tritan (blue-weak or blue-blind)"}]},{id:"severity",label:"Severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(e){const t=mp.MATRICES[String(e.type)];if(!t)return ns.NONE;const i=Number(e.severity??100),n=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:t.map((r,a)=>ns.IDENTITY[a]+(r-ns.IDENTITY[a])*n),contrastGain:1}}}class sv{static ID="fatigue";id=sv.ID;label="Fatigue";hint="Stated only: sleep loss has not been shown to change what a healthy eye receives, so the picture is unchanged. It bears on attention and memory, not on vision.";sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",label:"Awake for",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(e){return ns.NONE}}class lo{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_LEVEL=.1;id=lo.ID;label="Alcohol";hint="Lowers contrast sensitivity by about 0.9 dB at 0.08 % blood alcohol (one controlled study, results vary). Double vision, narrowed field and other drugs are not modelled: no source quantifies them.";sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",label:"Blood alcohol",kind:"number",default:0,min:0,max:lo.MAX_LEVEL,step:.01,unit:"%"}];perceive(e){const t=Number(e.bloodAlcohol??0),i=Math.max(0,Math.min(lo.MAX_LEVEL,Number.isFinite(t)?t:0));if(i===0)return ns.NONE;const n=i/lo.MEASURED_LEVEL*lo.MEASURED_LOSS_DB;return{colorMatrix:ns.IDENTITY,contrastGain:10**(-n/20)}}}class zo{static ALL=[new mp,new lo,new sv];static byId(e){return zo.ALL.find(t=>t.id===e)}static perceptionOf(e){return zo.ALL.reduce((t,i)=>ns.combine(t,i.perceive(e?.[i.id]??{})),ns.NONE)}static compact(e){const t={};for(const i of zo.ALL){const n=e[i.id]??{},s=Object.fromEntries(i.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(s).length>0&&(t[i.id]=s)}return Object.keys(t).length>0?t:void 0}}class gp{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 Fo.point(e,this.names?.compassPoints)}towards(e){return Fo.towards(e,this.names)}}class rv{constructor(e,t){this.element=e,this.onChange=t,e.addEventListener("error",()=>this.release())}shown=!1;get up(){return this.shown}show(e,t){const i=rv.resolve(e,t);if(!i){this.release();return}this.element.src=i,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}static resolve(e,t){if(!(typeof e!="string"||e.trim()===""))try{const i=new URL(e.trim(),t??location.href);return i.protocol==="https:"||i.protocol==="http:"?i.href:void 0}catch{return}}}const Ck={halo22:"22° halo — a ring round the Sun, from light bent through hexagonal ice crystals in high cirrus; its inner edge is red, at 21.7°",halo46:"46° halo — a rarer, fainter ring: light entering a crystal by a side face and leaving by an end face",oddRadius:"{angle}° halo — an odd-radius ring, rare and faint, made by ice crystals with pyramid ends",parhelion:"Parhelion (sundog) — a bright coloured spot beside the Sun at its own height, from flat plates falling level; red toward the Sun",parhelion120:"120° parhelion — a faint white spot 120° from the Sun, from light reflected inside flat plates",upperTangentArc:"Upper tangent arc — a bright arc resting on top of the 22° halo, from columns lying level",lowerTangentArc:"Lower tangent arc — an arc touching the bottom of the 22° halo, from columns lying level",circumzenithal:"Circumzenithal arc — a vivid band of colour near the zenith, from light entering the top face of flat plates (only with the Sun under 32°)",circumhorizontal:"Circumhorizontal arc — a band of colour low in the sky, from light entering the side face of flat plates (only with the Sun over 58°)",parhelicCircle:"Parhelic circle — a white circle round the whole sky at the Sun's own height, from reflections on the vertical faces of flat plates",pillar:"Light pillar — a shaft of light standing above the Sun, from reflections off slightly tilted flat plates",subsun:"Subsun — a mirror image of the Sun below the horizon, from reflections off the flat faces of plates"},kk="Global Meteor Network",Lk="https://globalmeteornetwork.org/data/",Ok="“Thunder” by Jerimee",Pk="https://creativecommons.org/licenses/by/3.0/",Nk="CC BY 3.0";class Zn{static fill(e,t){e.innerHTML="";const i=h=>e.appendChild(h),n=t.currentTerrainAttribution;n&&i(Zn.text(n));const s=t.currentRoadAttribution;s&&i(Zn.text(s));const r=t.ufoElement.observerMapCredit;r&&!n?.includes(r)&&i(Zn.text(r));for(const h of t.decorModelCredits){const d=h.author?` — ${h.author}`:"",u=document.createElement("li");h.sourceUrl?u.append(Zn.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(Zn.link(h.creditUrl,h.credit)):d.textContent=h.credit,i(d)}if(t.ufoElement.sighting.traces.length>0){const h=new zn(Is.preferencesFor(t)),d=new Set(t.ufoElement.sighting.traces.map(u=>h.read(u.source)).filter(u=>!!u));for(const u of d)i(Zn.text(u))}const a=t.satelliteState;if(a.status==="ready"&&a.credit){const h=document.createElement("li");h.appendChild(Zn.link(a.creditUrl??"",a.credit)),i(h)}if(t.fireballState.status==="ready"&&t.fireballState.records.length>0){const h=document.createElement("li");h.append(Zn.link(Lk,kk),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(Zn.link(l.creditUrl,l.credit)),i(h),l.trailCredit){const d=document.createElement("li");d.appendChild(Zn.link(l.trailCredit.creditUrl,l.trailCredit.credit)),i(d)}}const c=Zn.text(`${Ok} (`);c.append(Zn.link(Pk,Nk),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 Fk=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,Uk=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,Bk=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,zk=20,Hk=1;class Gk{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}}Oo.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(Fk,this.ambientVolume).then(a=>this.applyIfCurrent(a,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/zk,1);const s=i>Hk;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(Uk,this.windVolume).then(a=>this.applyIfCurrent(a,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(Bk,.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 zr{constructor(e){this.elements=e;const{eccentricity:t,perihelionAu:i}=e,[n,s]=this.perifocalAxes(),r=Math.sqrt(zr.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*zr.stumpffC(n),a=t-i*i*i/Math.sqrt(zr.SUN_GM_AU3_PER_DAY2)*zr.stumpffS(n);return{x:r*this.perihelionPosition.x+a*this.perihelionVelocity.x,y:r*this.perihelionPosition.y+a*this.perihelionVelocity.y,z:r*this.perihelionPosition.z+a*this.perihelionVelocity.z}}heliocentricDistanceAt(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(zr.SUN_GM_AU3_PER_DAY2)*Math.abs(e),n=a=>{const l=this.inverseSemiMajorAxis*a*a,c=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*c)*a*a*a*zr.stumpffS(l)+c*a};let s=Math.max(1,i/this.elements.perihelionAu);for(;n(s)<i;)s*=2;let r=0;for(let a=0;a<zr.MAX_ITERATIONS&&s-r>1e-13*Math.max(1,s);a++){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),a=Math.sin(t),l=Math.cos(i),c=Math.sin(i);return[{x:n*r-s*a*l,y:s*r+n*a*l,z:a*c},{x:-n*a-s*r*l,y:-s*a+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 F2=[{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 mu{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 F2.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=jt(t),s=this.earthPositionAt(n),r=this.apparentPositionOf(e,2451545+n.tt,s),a=this.subtract(r,s),l=this.length(r),c=this.length(a),h=this.tailEndAt(e,r,s,l,n,t,i),d=this.horizontalOf(a,n,t,i);return{apparition:e,position:d,...h,heliocentricDistanceAu:l,earthDistanceAu:c,elongationDeg:this.angleBetween(a,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,a){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,a),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 a=this.length(this.subtract(s,i))/this.LIGHT_SPEED_AU_PER_DAY;s=n.positionAt(t-a)}return s}static horizontalOf(e,t,i,n){const s=Yr(e4(),new It(e.x,e.y,e.z,t)),r=Yr(y2(t),s),a=G0(t,new Kr(n.lat,n.lng,n.elevationM),!0),l=new It(r.x-a.x,r.y-a.y,r.z-a.z,t),c=Wp(l);return ev(c.ra,c.dec,i,n)}static earthPositionAt(e){return Yr(QR(),Oa(de.Earth,e))}static julianDayOf(e){return 2451545+jt(e).tt}static orbitOf(e){const t=this.orbits.get(e.id);if(t)return t;const i=new zr(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 fm=[{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 vp{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(e){const t=this.julianDayOf(e);return fm.filter(i=>this.magnitudeAt(i,t)!==void 0)}static appearancesAt(e,t){const i=this.julianDayOf(e),n=[];for(const s of fm){const r=this.magnitudeAt(s,i);r!==void 0&&n.push({outburst:s,position:Hs.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 fm.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,a]=i[s-1]??i[0],[l,c]=i[s]??i[0];if(l===r)return a;const h=Math.min(1,Math.max(0,(n-r)/(l-r)));return a+h*(c-a)}static julianDayOf(e){return e.getTime()/864e5+this.UNIX_EPOCH_JD}}const Vk=[{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}],bc=6.5;class ac{static activeAt(e){return Vk.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)),a=this.wrappedDelta(i,s),l=this.wrappedDelta(s,n),c=this.wrappedDelta(r,s);return a<0?a<-l?0:1+a/l:a>0?a>c?0:1-a/c:1}static observedRatePerHour(e,t,i,n=bc){if(t<=0)return 0;const s=bc-n;return e*Math.sin(t*Math.PI/180)/Math.pow(i,s)}static radiantPosition(e,t,i){return Hs.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 bi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(e,t){const i=jt(e),n=new zp(0,kR(e).elon-90,1),s=Yr(r4(i),Qg(n,i)),r=Wp(s);return ev(r.ra,r.dec,e,t)}static observedRatePerHour(e,t=bc){const i=bi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(e*Math.PI/180)),n=bc-t;return(bi.QUIET_RATE_PER_HOUR+i)/Math.pow(bi.POPULATION_INDEX,n)}static schedule(e){const t=new Xp(e.seed^1542469173);return Uo.schedule(e).map(i=>{const n=bi.toCartesian({altitudeDeg:Math.asin(t.next())*180/Math.PI,azimuthDeg:t.between(0,360)}),s=i.fromRadiantDeg*Math.PI/180,r=bi.turnAround(n,t.between(0,360)),a={x:n.x*Math.cos(s)+r.x*Math.sin(s),y:n.y*Math.cos(s)+r.y*Math.sin(s),z:n.z*Math.cos(s)+r.z*Math.sin(s)};return{...i,radiant:bi.toHorizontal(a),bearingDeg:bi.bearingFrom(a,n)}})}static turnAround(e,t){const[i,n]=bi.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]=bi.basisAround(e),s=e.x*t.x+e.y*t.y+e.z*t.z,r=bi.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=bi.normalise(bi.cross(e,t));return[i,bi.normalise(bi.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=bi.toCartesian(e.radiant??{altitudeDeg:90,azimuthDeg:0}),i=bi.turnAround(t,e.bearingDeg),n=e.fromRadiantDeg*Math.PI/180;return bi.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 $b="https://ufoathome.org/tle/index.json";class wn{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??wn.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($b)||e.push($b),e}static FIRST_SNAPSHOT="2021-02-22";async covers(e){const t=Date.parse(`${wn.FIRST_SNAPSHOT}T00:00:00Z`)-wn.MAX_ELEMENT_AGE_DAYS*wn.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)-wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS&&e.getTime()<=Date.parse(n.to)+wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS):!1}async at(e){const t=await this.loadIndex();if(!t)return;const{index:i,base:n}=t,s=[],r=[];for(const a of Object.keys(i.kinds)){const l=await this.kindAt(a,e,i,n);s.push(...l),r.push(this.coverageOf(a,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*wn.DAY_MS,a=Math.floor(s/r),l=s-a*r<r/2?a-1:a+1,c=new Set(i.kinds[e].bins),h=[a,l].map(g=>new Date(g*r).toISOString().slice(0,10)).filter(g=>c.has(g));if(h.length===0)return[];const[d,...u]=await Promise.all([this.json(new URL(`objects-${e}.json`,n).href),...h.map(g=>this.binary(new URL(`${e}/${g}.bin`,n).href))]),p=new Map;for(const g of u)for(const m of wn.decode(g,i.recordBytes)){const v=p.get(m.norad);(!v||Math.abs(m.epochMs-s)<Math.abs(v.epochMs-s))&&p.set(m.norad,m)}const f=[];for(const g of p.values()){const m=Math.abs(g.epochMs-s)/wn.DAY_MS;if(m>wn.MAX_ELEMENT_AGE_DAYS)continue;const v=d[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>s||f.push({norad:g.norad,name:v.name,kind:e,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return f}coverageOf(e,t,i,n){const{from:s,to:r}=i.kinds[e],a=t.getTime(),l=wn.MAX_ELEMENT_AGE_DAYS*wn.DAY_MS,c=n?"covered":a<Date.parse(s)-l?"before":a>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 Wk{lowerM;upperM;add(e,t){if(!(e<=0)){if(t.behindM!==void 0){const i=mt.sizeMAt(t.behindM,e);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(t.inFrontM!==void 0){const i=mt.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:mt.distanceMAt(this.lowerM,e),maxM:this.upperM===void 0?void 0:mt.distanceMAt(this.upperM,e)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class Ho{static DEG_PER_SECOND=360/86164.0905;static degOver(e){return Math.max(0,e)*Ho.DEG_PER_SECOND}static instants(e,t){if(!(t>0))return 1;const i=Ho.degOver(e)/t;return i<1?1:Math.min(Ho.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class an{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 Ho.DEG_PER_SECOND*3600}static graspOf(e,t={}){if(e.visualAid)return an.visualAidGrasp(e,t.focalLengthMm);const i=t.exposureSeconds??e.exposureSeconds,n=t.fNumber??e.fNumber;if(i===void 0||n===void 0||!(i>0)||!(n>0))return an.EYE;const s=t.focalLengthMm??e.frame?.focalLengthMm??an.UNKNOWN_CAMERA_FOCAL_MM,r=s/n,a=an.resolutionArcsec(e,s,r);return{apertureMm:r,exposureSeconds:Math.min(i,an.trailLimitedSeconds(a)),resolutionArcsec:a}}static visualAidGrasp(e,t){const i=e.visualAid,n=an.EYE,s=t??e.frame?.focalLengthMm,r=i.magnification??(s!==void 0&&i.eyepieceFocalMm?s/i.eyepieceFocalMm:1),a=Math.min(i.apertureMm,n.apertureMm*r);return{apertureMm:Math.max(a,n.apertureMm),exposureSeconds:n.exposureSeconds,resolutionArcsec:n.resolutionArcsec/Math.max(1,Math.min(r,i.apertureMm/n.apertureMm))}}static resolutionArcsec(e,t,i){const s=(e.detailUm??an.UNKNOWN_CAMERA_DETAIL_UM)/1e3/t*an.ARCSEC_PER_RADIAN,r=1.22*an.WAVELENGTH_M/(i/1e3)*an.ARCSEC_PER_RADIAN;return Math.max(s,r)}static trailLimitedSeconds(e){return e/an.skyDriftArcsecPerSecond}static gainOverEye(e,t={}){const i=an.graspOf(e,t),n=an.EYE,s=(i.apertureMm/n.apertureMm)**2,r=i.exposureSeconds/n.exposureSeconds,a=(n.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(s*r*a)}static gainFor(e,t){const i=t.fieldOfViewDeg===void 0?void 0:Ut.focalLengthMmFor(e,t.fieldOfViewDeg);return an.gainOverEye(e,{fNumber:t.fNumber,focalLengthMm:i,exposureSeconds:t.exposureSeconds})}}const Yb=111320,qc=Math.PI/180,Xk=1.02,$k=1;class gh{static of(e,t){const i=gh.sightings(e,t);if(i.length<2)return;const n=gh.baseline(i);if(!n)return;const{near:s,far:r,closedM:a}=n,l=Math.tan(r.widthDeg/2*qc)===0?0:Math.tan(s.widthDeg/2*qc)/Math.tan(r.widthDeg/2*qc);if(l<Xk)return;const c=a/(l-1),h=mt.sizeMAt(c,s.widthDeg),d=i.map(u=>({t:u.t,m:mt.distanceMAt(h,u.widthDeg)}));return{widthM:h,distanceM:d,nearestM:Math.min(...d.map(u=>u.m)),fromT:r.t,toT:s.t,closedM:a}}static sightings(e,t){return e.timeline.allKeyframes.flatMap(i=>{const n=i.shapes.find(a=>a.sourceId===t)?.shape,s=n?.angular?.widthDeg,r=ot(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=gh.closedAlongSight(i,n),[r,a,l]=s>=0?[n,i,s]:[i,n,-s];l<$k||r.widthDeg<=a.widthDeg||(!t||l>t.closedM)&&(t={near:r,far:a,closedM:l})}return t}static closedAlongSight(e,t){const i=(t.lat-e.lat)*Yb,n=(t.lng-e.lng)*Yb*Math.cos(e.lat*qc),s=(e.sightAzimuthDeg??0)*qc;return i*Math.cos(s)+n*Math.sin(s)}}class Ln{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(e){if(e.statedM!==void 0&&e.statedM>0)return{distanceM:Ln.atLeastNearest(e.statedM),basis:"stated"};if(e.hypothesisM!==void 0&&e.hypothesisM>0)return{distanceM:Ln.atLeastNearest(e.hypothesisM),basis:"hypothesis"};if(e.derivedM!==void 0&&e.derivedM>0)return{distanceM:Ln.atLeastNearest(e.derivedM),basis:"derived"};const t=Ln.largest(e.range?.minM,e.crossing?.behindM),i=Ln.smallest(e.range?.maxM,e.crossing?.inFrontM),n=t===void 0?void 0:t*Ln.MARGIN,s=i===void 0?void 0:i/Ln.MARGIN;return n!==void 0&&s!==void 0?{distanceM:Ln.atLeastNearest(n<=s?Math.sqrt(n*s):n),basis:"bounded"}:n!==void 0?{distanceM:Ln.atLeastNearest(n),basis:"bounded"}:s!==void 0&&s<Ln.CONVENTIONAL_M?{distanceM:Ln.atLeastNearest(s),basis:"bounded"}:{distanceM:Ln.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(e){return Math.max(Ln.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 mm=Math.PI/180;class qe{constructor(e,t,i){this.body=e,this.ground=t,this.eyeAt=i;const n=[...e.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)qe.collect(this.motionKeys,s.t,s.motions),qe.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;lightKeys=new Map;static collect(e,t,i){for(const[n,s]of Object.entries(i??{})){const r=e.get(n)??[];r.push({t,value:s}),e.set(n,r)}}motionsAt(e){return qe.channelsAt(this.motionKeys,e,0)}lightsAt(e){return this.lightKeys.size>0?qe.channelsAt(this.lightKeys,e,void 0):void 0}static channelsAt(e,t,i){const n={};for(const[s,r]of e){let a=r.length-1;for(;a>=0&&r[a].t>t;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const l=r[a],c=r[Math.min(a+1,r.length-1)],h=c===l||c.t===l.t?0:Math.min(1,(t-l.t)/(c.t-l.t));n[s]=qe.lerp(l.value,c.value,h)}return n}static eyeOf(e,t,i){const n=ot(e,0),s=ot(e,t),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?yt(s.lat,s.lng,n.lat,n.lng):void 0,l=a?a.x:0,c=a?-a.z:0;return{eastM:l,northM:c,upM:i.heightAt(l,c)+qe.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(e,t,i,n){const s=qe.directionOf(t,i),r=c=>e.upM+s.upM*c-n.heightAt(e.eastM+s.eastM*c,e.northM+s.northM*c);let a=0,l=0;for(;l<qe.MAX_RANGE_M;){if(l=a+Math.max(.5,a*.01),r(l)<=0){for(let c=0;c<30;c++){const h=(a+l)/2;r(h)<=0?l=h:a=h}return l}a=l}}static directionOf(e,t){const i=e*mm,n=t*mm;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)),a=this.body.withObserver&&n.carried&&s.carried?this.eyeAt(e):void 0,l=a?a.eastM+qe.lerp(n.carried.eastM,s.carried.eastM,r):qe.lerp(n.eastM,s.eastM,r),c=a?a.northM+qe.lerp(n.carried.northM,s.carried.northM,r):qe.lerp(n.northM,s.northM,r),h={widthM:qe.lerp(n.sizeM.widthM,s.sizeM.widthM,r),lengthM:qe.lerp(n.sizeM.lengthM,s.sizeM.lengthM,r),heightM:qe.lerp(n.sizeM.heightM,s.sizeM.heightM,r)},d={headingDeg:qe.lerpAngle(n.attitude.headingDeg,s.attitude.headingDeg,r),pitchDeg:qe.lerp(n.attitude.pitchDeg,s.attitude.pitchDeg,r),rollDeg:qe.lerp(n.attitude.rollDeg,s.attitude.rollDeg,r)};let u;if(a)u=a.upM+qe.lerp(n.carried.upM,s.carried.upM,r);else if("aboveGroundM"in n.vertical&&"aboveGroundM"in s.vertical){const p=qe.lerp(n.vertical.aboveGroundM,s.vertical.aboveGroundM,r);u=this.groundUnderFootprint(l,c,h,d.headingDeg)+p+h.heightM/2}else u=qe.lerp(this.centreUpOf(n),this.centreUpOf(s),r);return{id:this.body.id,model:this.body.model,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:l,northM:c,upM:u,sizeM:h,attitude:d,appearance:{color:qe.lerpColor(n.appearance.color,s.appearance.color,r),albedo:qe.lerp(n.appearance.albedo,s.appearance.albedo,r),luminanceCdM2:qe.lerp(n.appearance.luminanceCdM2,s.appearance.luminanceCdM2,r),transparency:qe.lerp(n.appearance.transparency,s.appearance.transparency,r),haloScale:qe.lerp(n.appearance.haloScale,s.appearance.haloScale,r)},flame:qe.flameBetween(n.flame,s.flame,r),motions:this.motionsAt(e),lights:this.lightsAt(e),throwsFlame:this.body.track.some(p=>p.flame!==void 0&&p.flame.luminanceCdM2>0)}}static flameBetween(e,t,i){if(!e||e.luminanceCdM2<=0)return i>=1&&t&&t.luminanceCdM2>0?t:void 0;const n=e,s=t??e,r={...i<1?n:s,lengthM:qe.lerp(n.lengthM,s.lengthM,i),widthM:qe.lerp(n.widthM,s.widthM,i),luminanceCdM2:qe.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(e){return"upM"in e.vertical?e.vertical.upM:this.groundUnderFootprint(e.eastM,e.northM,e.sizeM,e.attitude.headingDeg)+e.vertical.aboveGroundM+e.sizeM.heightM/2}groundUnderFootprint(e,t,i,n){const s=n*mm,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={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+a.eastM*u,t+r.northM*d+a.northM*u))}return l}place(e,t){const i=[];let n;for(const s of e){const r=s.sizeM??n?.sizeM??qe.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},l={color:s.appearance?.color??n?.appearance.color??qe.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??qe.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??qe.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??qe.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??qe.DEFAULT_APPEARANCE.haloScale},c=this.positionOf(s,r,t)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!c)continue;const h=s.flame??n?.flame,d=s.present??n?.present??!0;if(n={t:s.t,...c,sizeM:r,attitude:a,appearance:l,flame:h,present:d},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const u=qe.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:u.eastM*s.distanceM,northM:u.northM*s.distanceM,upM:u.upM*s.distanceM}}i.push(n)}return i}verticalOf(e,t){if(e.onGround)return{aboveGroundM:0};if(e.altitudeAboveGroundM!==void 0)return{aboveGroundM:e.altitudeAboveGroundM};if(e.altitudeM!==void 0)return{upM:e.altitudeM+t.heightM/2}}positionOf(e,t,i){if(e.eastM!==void 0&&e.northM!==void 0)return{eastM:e.eastM,northM:e.northM,vertical:this.verticalOf(e,t)??{aboveGroundM:0}};if(e.azimuthDeg===void 0||e.altitudeDeg===void 0)return;const n=i(e.t);if(!n)return;const s=e.distanceM??(e.onGround?qe.lineOfSightMeetsGround(n,e.azimuthDeg,e.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=qe.directionOf(e.azimuthDeg,e.altitudeDeg),a=n.eastM+r.eastM*s,l=n.northM+r.northM*s;return{eastM:a,northM:l,vertical:this.verticalOf(e,t)??{upM:n.upM+r.upM*s}}}static lerp(e,t,i){return e+(t-e)*i}static lerpColor(e,t,i){const n=qe.rgbOf(e),s=qe.rgbOf(t);return!n||!s?i<1?e:t:"#"+n.map((r,a)=>Math.round(qe.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(e){const t=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(e);if(!t)return;const i=t[1].length===3?t[1].replace(/./g,"$&$&"):t[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(e,t,i){const n=((t-e)%360+540)%360-180;return((e+n*i)%360+360)%360}}class Et{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],a=r.t-s.t,l=a>0?(t-s.t)/a:0,[c,h]=Et.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,a=s.track[s.track.length-1]?.t??0;s.fragments.forEach((l,c)=>{const h=l.fromT??r,d=l.untilT??a;if(t<h||t>d)return;const u=(l.lagS??0)*1e3,p=Et.leadAt(s,t-u);if(!p)return;const f=Et.seenFrom(i,p);if(f.altitudeDeg<0)return;const g=Math.min(Et.FADE_MS,(d-h)/4),m=g>0?Math.min(1,(t-h)/g,(d-t)/g):1,v=-2.5*Math.log10(Math.max(m,.001)),b=l.absoluteMagnitude+5*Math.log10(f.distanceKm/Et.STANDARD_DISTANCE_KM)+v,M=[f],y=(l.trainS??Et.DEFAULT_TRAIN_S)*1e3;for(let x=1;x<=Et.TRAIN_POINTS;x++){const S=Math.min(y*x/Et.TRAIN_POINTS,t-h),A=Et.leadAt(s,t-u-S);if(!A||(M.push(Et.seenFrom(i,A)),S>=t-h))break}n.push({reentryId:s.id,fragmentId:l.id??String(c),head:f,magnitude:b,color:l.color??Et.DEFAULT_COLOR,train:M})})}return n}static seenFrom(e,t){const i=Et.ecef(e),n=Et.ecef(t),s=n[0]-i[0],r=n[1]-i[1],a=n[2]-i[2],l=e.lat*Et.DEG,c=e.lng*Et.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)*a,u=Math.cos(l)*Math.cos(c)*s+Math.cos(l)*Math.sin(c)*r+Math.sin(l)*a,p=Math.hypot(h,d,u);return{altitudeDeg:Math.asin(u/p)/Et.DEG,azimuthDeg:(Math.atan2(h,d)/Et.DEG+360)%360,distanceKm:p/1e3}}static ecef(e){const t=e.lat*Et.DEG,i=e.lng*Et.DEG,n=Math.sin(t),s=Et.A/Math.sqrt(1-Et.E2*n*n);return[(s+e.heightM)*Math.cos(t)*Math.cos(i),(s+e.heightM)*Math.cos(t)*Math.sin(i),(s*(1-Et.E2)+e.heightM)*n]}static alongGreatCircle(e,t,i){const n=h=>{const d=h.lat*Et.DEG,u=h.lng*Et.DEG;return[Math.cos(d)*Math.cos(u),Math.cos(d)*Math.sin(u),Math.sin(d)]},s=n(e),r=n(t),a=Math.max(-1,Math.min(1,s[0]*r[0]+s[1]*r[1]+s[2]*r[2])),l=Math.acos(a);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]))/Et.DEG,Math.atan2(c[1],c[0])/Et.DEG]}}class St{static EARTH_RADIUS_KM=6371;static SHADOW_RADIUS_KM=St.EARTH_RADIUS_KM+15;static PENUMBRA_KM=10;static SUN_ILLUMINANCE_LUX=127e3;static RAYLEIGH_PER_M=[58e-7,135e-7,331e-7];static SCALE_HEIGHT_M=8e3;static OZONE_GRAZING_DEPTH=[2.4,1.8,.24];static ANISOTROPY=.7;static ALBEDO=.99;static DEFAULTS={exhaustKgPerS:273,condensedShare:.1,particleRadiusUm:.5,expansionKmPerS:.15,initialRadiusKm:.5,lifetimeS:420,collarShare:.85,collarExpansionKmPerS:2.5,collarLifetimeS:20};static PROPELLANTS={"rp1-lox":{condensedShare:.1,particleRadiusUm:.5},"methane-lox":{condensedShare:.14,particleRadiusUm:.5},"hydrogen-lox":{condensedShare:.2,particleRadiusUm:.5},hypergolic:{condensedShare:.1,particleRadiusUm:.4},solid:{condensedShare:.33,particleRadiusUm:.8}};static G0=9.80665;static COLLAR_SPREAD_OF_EXHAUST_VELOCITY=.735;static plumeOf(e){const t={},i=e.vehicle?.engine;if(i){const n=i.specificImpulseS===void 0?void 0:i.specificImpulseS*St.G0;i.thrustKN!==void 0&&n&&(t.exhaustKgPerS=i.thrustKN*1e3/n),n&&(t.collarExpansionKmPerS=n/1e3*St.COLLAR_SPREAD_OF_EXHAUST_VELOCITY),i.propellant&&Object.assign(t,St.PROPELLANTS[i.propellant])}return{...St.DEFAULTS,...t,...e.plume}}static PUFF_EVERY_S=.5;static MAX_PUFFS=320;static DEG=Math.PI/180;static sunDirectionAt(e){const t=new Kr(0,0,-6378137),i=yc(de.Sun,e,t,!0,!0),n=(i.ra-r2(e))*15*St.DEG,s=i.dec*St.DEG;return[Math.cos(s)*Math.cos(n),Math.cos(s)*Math.sin(n),Math.sin(s)]}static viewsAt(e,t,i,n){const s=[];for(const r of e){const a=St.plumeOf(r),l=r.track[0]?.t??0,c=r.track[r.track.length-1]?.t??0,h=r.burnFromT??l,d=Math.min(r.burnUntilT??c,t);if(d<=h)continue;const u=Math.max(St.PUFF_EVERY_S*1e3,(d-h)/St.MAX_PUFFS),p=a.particleRadiusUm*1e-6,f=6/(4*917*p),g=a.exhaustKgPerS*(u/1e3)*a.condensedShare,m=[{share:1-a.collarShare,expansionKmPerS:a.expansionKmPerS,lifetimeS:a.lifetimeS},{share:a.collarShare,expansionKmPerS:a.collarExpansionKmPerS,lifetimeS:a.collarLifetimeS}];for(let v=d;v>=h;v-=u){const b=(t-v)/1e3;if(b>a.lifetimeS)break;const M=Et.leadAt({id:r.id,track:r.track,fragments:[]},v);if(!M)continue;const y=Et.seenFrom(i,M);if(y.altitudeDeg<0)continue;const x=St.sunlightAt(M,n);if(x.lit<=0)continue;const S=Et.leadAt({id:r.id,track:r.track,fragments:[]},Math.max(l,v-u)),A=S?St.distanceKm(M,S):0,w=St.scatteringPhase(i,M,n);for(const T of m){if(T.share<=0||b>T.lifetimeS)continue;const I=a.initialRadiusKm+T.expansionKmPerS*b+A/2,R=3*g*T.share*f/(2*Math.PI*(I*1e3)**2),O=Math.max(0,1-(b/T.lifetimeS)**2),L=St.SUN_ILLUMINANCE_LUX*St.ALBEDO*w*R*O*x.lit;L<=0||s.push({launchId:r.id,centre:y,radiusDeg:Math.atan2(I,y.distanceKm)/St.DEG,luminanceCdM2:L,sunTransmittance:x.transmittance,lit:x.lit,ageS:b})}}}return s}static sunlightAt(e,t){const i=St.earthCentred(e),n=i[0]*t[0]+i[1]*t[1]+i[2]*t[2];if(n>=0)return{lit:1,transmittance:[1,1,1]};const s=Math.hypot(i[0]-n*t[0],i[1]-n*t[1],i[2]-n*t[2]),r=St.PENUMBRA_KM,a=Math.min(1,Math.max(0,(s-(St.SHADOW_RADIUS_KM-r/2))/r));if(a<=0)return{lit:0,transmittance:[0,0,0]};const l=Math.max(0,(s-St.EARTH_RADIUS_KM)*1e3),c=Math.exp(-l/St.SCALE_HEIGHT_M),h=Math.sqrt(2*Math.PI*St.EARTH_RADIUS_KM*1e3*St.SCALE_HEIGHT_M),d=Math.exp(-(((l/1e3-25)/15)**2)),u=[0,1,2].map(p=>Math.exp(-St.RAYLEIGH_PER_M[p]*c*h-St.OZONE_GRAZING_DEPTH[p]*d));return{lit:a,transmittance:u}}static scatteringPhase(e,t,i){const n=St.earthCentred(e),s=St.earthCentred(t),r=[n[0]-s[0],n[1]-s[1],n[2]-s[2]],a=Math.hypot(r[0],r[1],r[2])||1,l=-(r[0]*i[0]+r[1]*i[1]+r[2]*i[2])/a,c=St.ANISOTROPY;return(1-c*c)/(4*Math.PI*(1+c*c-2*c*l)**1.5)}static distanceKm(e,t){const i=St.earthCentred(e),n=St.earthCentred(t);return Math.hypot(i[0]-n[0],i[1]-n[1],i[2]-n[2])}static earthCentred(e){const t=e.lat*St.DEG,i=e.lng*St.DEG,n=St.EARTH_RADIUS_KM+e.heightM/1e3;return[n*Math.cos(t)*Math.cos(i),n*Math.cos(t)*Math.sin(i),n*Math.sin(t)]}}class av{static FIRST_DAY="2022-01-01";static mayCover(e){return new Date(e).toISOString().slice(0,10)>=av.FIRST_DAY}}class Yk{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 qk="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",ng=[{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 Yk(qk,o=>av.mayCover(o),async()=>new(await _e(async()=>{const{AdsbLolArchiveProvider:o}=await import("./AdsbLolArchiveProvider-CDtWnd9O.js");return{AdsbLolArchiveProvider:o}},[],import.meta.url)).AdsbLolArchiveProvider)}];class Pn{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(e,t,i){const n=Pn.positionAt(e,i);if(!n)return;const s=Et.seenFrom(t,n.geo);if(!(s.altitudeDeg<0))return{track:e,sky:s,altitudeFt:n.altitudeFt,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg,angularRateDegPerS:Pn.angularRate(e,t,i)}}static viewsAt(e,t,i){return e.flatMap(n=>Pn.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*Pn.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,a=r.t-s.t;if(a>Pn.MAX_GAP_S*1e3)return;const l=a>0?(t-s.t)/a: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:Pn.wrapLongitude(s.lng+h*l),heightM:c*Pn.FT_TO_M},altitudeFt:c,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg}}static angularRate(e,t,i){const n=Pn.positionAt(e,i-500),s=Pn.positionAt(e,i+500);if(!n||!s)return;const r=Pn.unit(Et.seenFrom(t,n.geo)),a=Pn.unit(Et.seenFrom(t,s.geo)),l=Math.min(1,Math.max(-1,r[0]*a[0]+r[1]*a[1]+r[2]*a[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 qb="https://ufoathome.org/fireballs/index.json";class Ts{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??Ts.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(qb)||e.push(qb),e}static mayCover(e){return new Date(e).toISOString().slice(0,7)>=Ts.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(e,t){if(!Ts.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=Ts.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=Et.seenFrom(t,n);if(!(s.altitudeDeg<0))return{record:e,peak:s,magnitude:e.peakMagnitude+5*Math.log10(s.distanceKm/Et.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:Ts.COLOR,trainS:Ts.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 Al=Math.PI/180,Kc=180/Math.PI;class Ii{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 a=Ii.projectionOf(r,i,n?.(r));if(a)for(const l of r.explains){const c=this.timeline.getInterpolatedShapeAt(e,l);!c||c.transparency>=1||s.push({...Ii.compare(l,r.id,{aim:c.aim,angular:c.angular},a),title:c.title})}}return s}static compare(e,t,i,n){const s=[],r=i.aim?Ii.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(Ii.DIRECTION_TOLERANCE_DEG,c)&&s.push("direction")}const a=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 a!==void 0&&!Ii.withinSize(a)&&s.push("width"),l!==void 0&&!Ii.withinSize(l)&&s.push("height"),{sourceId:e,bodyId:t,stated:i,predicted:n,separationDeg:r,widthRatio:a,heightRatio:l,disagreements:s}}static projectionOf(e,t,i){const n=i&&i.length>0?i:Ii.outlineOf(e),s=i&&i.length>0?Ii.centreOf(i):e,r=Ii.normalized({eastM:s.eastM-t.eastM,northM:s.northM-t.northM,upM:s.upM-t.upM});if(!r)return;const a=Ii.normalized({eastM:r.northM,northM:-r.eastM,upM:0})??{eastM:1,northM:0,upM:0},l=Ii.cross(a,r);let c=1/0,h=-1/0,d=1/0,u=-1/0;for(const p of n){const f={eastM:p.eastM-t.eastM,northM:p.northM-t.northM,upM:p.upM-t.upM},g=Ii.dot(f,r);if(g<=0)return;const m=Math.atan2(Ii.dot(f,a),g),v=Math.atan2(Ii.dot(f,l),g);c=Math.min(c,m),h=Math.max(h,m),d=Math.min(d,v),u=Math.max(u,v)}return{aim:{azimuthDeg:(Math.atan2(r.eastM,r.northM)*Kc+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,r.upM)))*Kc},angular:{widthDeg:(h-c)*Kc,heightDeg:(u-d)*Kc}}}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*Al,n=t.altitudeDeg*Al,s=Math.sin(i)*Math.sin(n)+Math.cos(i)*Math.cos(n)*Math.cos((e.azimuthDeg-t.azimuthDeg)*Al);return Math.acos(Math.max(-1,Math.min(1,s)))*Kc}static withinSize(e){return e<=Ii.SIZE_TOLERANCE&&e>=1/Ii.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"&&k2.includes(r))for(let d=0;d<=Ii.RINGS;d++){const u=d/Ii.RINGS*Math.PI;for(let p=0;p<Ii.SEGMENTS;p++){const f=p/Ii.SEGMENTS*2*Math.PI;s.push([t*Math.sin(u)*Math.cos(f),i*Math.sin(u)*Math.sin(f),n*Math.cos(u)])}}else for(const d of[-t,t])for(const u of[-i,i])for(const p of[-n,n])s.push([d,u,p]);const l=e.attitude.headingDeg*Al,c=e.attitude.pitchDeg*Al,h=e.attitude.rollDeg*Al;return s.map(([d,u,p])=>{const f=d*Math.cos(h)+p*Math.sin(h),g=-d*Math.sin(h)+p*Math.cos(h),m=u*Math.cos(c)-g*Math.sin(c),v=u*Math.sin(c)+g*Math.cos(c);return{eastM:e.eastM+f*Math.cos(l)+m*Math.sin(l),northM:e.northM-f*Math.sin(l)+m*Math.cos(l),upM:e.upM+v}})}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}}Cp();const Kk={sun:"Sun",moon:"Moon",Venus:"Venus",Mars:"Mars",Jupiter:"Jupiter",Saturn:"Saturn"},Zk="{name} — mag {mag}, {alt}° above the horizon",jk="{name} — {size}, {distance} away",Jk="{name} — satellite, mag {mag}, {height} km up",U2="satellites-change",B2="fireballs-change",Qk="aircraft-change",e6="rr0-confrontation",t6="{name} — mag {mag}, {alt}° below the horizontal",gm="Credits",Kb="comet:",Zb="nova:",jb={building:"Building",tree:"Tree",shrub:"Shrub",bridge:"Bridge",wire:"Overhead line",crop:"Crop row",terrace:"Terrace (restanque)",mound:"Stone heap",wall:"Dry-stone wall",streetlight:"Streetlight",vehicle:"Vehicle",observer:"Observer",aircraft:"Aircraft",entity:"Being"},i6=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,n6=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,s6=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,r6=-18,a6={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Kd={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class Wt 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",ql,Kl]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;holding=!1;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 wn;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Ts;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=ng[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return Wt.trafficRuntimeLoading??=_e(()=>import("./trafficRuntime-XVgt3vom.js"),__vite__mapDeps([2,1]),import.meta.url).then(e=>Wt.trafficRuntime=e),Wt.trafficRuntimeLoading.catch(()=>{Wt.trafficRuntimeLoading=void 0}),Wt.trafficRuntimeLoading}traffic;lastSun;decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new Gk;vehicleAudio=new AE;aircraftAudio;vehicleHearing=new Wu;decorAircraftHearing;decorModelSounds=new Map;thunderTimeoutId;handleFullscreenChange=()=>this.resizeToStage();handlePointerMove=e=>{if(this.sceneRenderer.setCompassHovered(!0),this.holding){this.hoverTooltip.hidden=!0;return}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,a=-((e.clientY-i.top)/i.height*2-1),l=this.pickAt(r,a);l?this.showHoverTooltip(e,e.altKey&&l.detail?l.detail():l.name):this.hoverTooltip.hidden=!0};pickAt(e,t){const i=this.naming,n=i.names,s=this.sceneRenderer.pickBodyAt(e,t);if(s)return{kind:"sky",id:s,name:this.bodyName(s)};const r=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(e,t):void 0,a=r?this.interpretationShown?.bodies.find(g=>g.id===r):void 0,l=a?this.said.read(a.title)||(a.model.id==="figure"?i.decorKind("entity",jb.entity):void 0):void 0;if(r!==void 0&&l)return{kind:"body",id:r,name:l};const c=this.pickDecorAt(e,t),h=c?this.ufoElement.sighting.decor.find(g=>g.id===c):void 0;if(h){const g=this.said.read(h.title)||i.decorKind(h.kind,jb[h.kind]);return{kind:"decor",id:h.id,name:g,detail:()=>this.decorTooltip(h,g)}}const d=this.trafficTooltipAt(e,t);if(d)return{kind:"traffic",name:d};const u=this.sceneRenderer.pickSatelliteAt(e,t);if(u)return{kind:"satellite",name:(n?.satelliteTooltip??Jk).replace("{name}",u.name).replace("{mag}",u.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(u.heightKm).toLocaleString())};const p=this.sceneRenderer.pickOpticsAt(e,t);if(p){const g=(n?.opticsTooltips??Ck)[p.id].replace("{angle}",String(Math.round(p.angleDeg??0)));return{kind:"optics",id:p.id,name:g.split(" — ")[0],detail:()=>g}}const f=this.sceneRenderer.pickStarAt(e,t);if(f){const g=f.star.mag,m=f.altitudeDeg;return{kind:"star",name:(m<0?n?.starTooltipBelow??t6:n?.starTooltip??Zk).replace("{name}",i.star(f.star)).replace("{mag}",g.toLocaleString(void 0,{maximumFractionDigits:Math.abs(g)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(m))))}}}decorTooltip(e,t){const i=c=>c.toLocaleString(void 0,{maximumFractionDigits:c<10?1:0}),n=Ue.sizeOf(e),s=this.sceneRenderer.decorDistanceM(e.id),r=s===void 0?"":s>=1e3?`${(s/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${i(s)} m`;return(this.naming.names?.decorTooltip??jk).replace("{name}",t).replace("{size}",`${i(n.widthM)} × ${i(n.lengthM)} × ${i(n.heightM)} m`).replace("{distance}",r)}bodyName(e){const t=e.startsWith(Kb)?e.slice(Kb.length):void 0,i=t?F2.find(r=>r.id===t):void 0;if(i)return this.naming.comet(i);const n=e.startsWith(Zb)?vp.byId(e.slice(Zb.length)):void 0;if(n)return this.naming.nova(n);const s=Kk[e];return s===void 0?e:this.naming.body(e,s)}get naming(){return this.sceneNaming}sceneNaming=new gp;namesLanguage="en";async loadSceneNames(){const e=yh(Is.preferencesFor(this),Sh);if(e===this.namesLanguage)return;this.namesLanguage=e;const t=await FM(e);e===this.namesLanguage&&this.applySceneNaming(new gp(t))}setBusy(e,t=""){this.busyElement.hidden=!e,this.busyNote.textContent=e?t:"",this.busyElement.setAttribute("aria-label",t),this.busyElement.setAttribute("aria-busy",String(e))}renderLoaderText(e,t){let i=0;const n=(s,r)=>{s.setAttribute("aria-label",r),s.replaceChildren(),r.split(" ").forEach((a,l)=>{l>0&&s.append(" ");const c=document.createElement("span");c.className="scene-loader-word",c.setAttribute("aria-hidden","true");for(const h of a){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??gm;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(),n=e.clientX-i.left+12,s=n+this.hoverTooltip.offsetWidth-i.width;this.hoverTooltip.style.left=`${s>0?Math.max(0,n-s-4):n}px`,this.hoverTooltip.style.top=`${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(),ji.thunderDelayMs(e))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather($h(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){const e=this.ufoElement.level;this.weatherAudio.setLevel(e),this.vehicleAudio.setLevel(e),this.aircraftAudio?.setLevel(e)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=e=>{this.lastTimeMs=e.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"&&this.sceneRenderer.frame(performance.now()),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const e=this.ufoElement.playbackState==="playing";this.sceneRenderer.setAnimationsRunning(e,e),this.weatherAudio.setPaused(!e),this.vehicleAudio.setPaused(!e),this.aircraftAudio?.setPaused(!e),e&&this.unlockIfAlreadyActivated(),e||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${IE}</style>${_E}`,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 Xe(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.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=t,this.poster=new rv(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=s=>{this.holding=s,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ufoElement=document.createElement(Om),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"&&Zn.fill(n,this)}),this.creditsButton.title=gm,this.creditsButton.setAttribute("aria-label",gm),this.sceneRenderer.onMapSubjectBounds=s=>this.ufoElement.setMapSubjectBounds(s),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("playrequest",()=>this.poster.release()),this.ufoElement.seekPreviewPainter=(s,r)=>this.seekPreviewOf(r).paint(s,r),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=s=>s.vehicle!==void 0||s.decor.some(r=>r.engine!==void 0)||s.weatherTrack.allKeyframes.some(r=>r.weather.precipitationType!=="none"||r.weather.windSpeed>1),this.ufoElement.addEventListener("referenceview",s=>this.applyReferenceView(s.detail)),this.ufoElement.addEventListener("traceview",s=>this.sceneRenderer.setTracesShown(s.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const s of Wt.GESTURES)this.addEventListener(s,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new zn(Is.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(e,t){const i=e.vehicle;return i?{setting:Na.at(i.headlights??"auto",i.headlightKeyframes,t)??"auto",headingDeg:this.travelHeadingAt(e,t)}:void 0}travelHeadingAt(e,t){const i=ot(e,t);if(!i)return 0;for(const n of[400,-400]){const s=ot(e,t+n);if(!s||i.lat===void 0||i.lng===void 0||s.lat===void 0||s.lng===void 0)break;const r=yt(s.lat,s.lng,i.lat,i.lng);if(Math.hypot(r.x,r.z)<.8)continue;return(Math.atan2(r.x,-r.z)*180/Math.PI+(n<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(e){const t=e.allKeyframes;if(this.routeCache?.track===e&&this.routeCache.count===t.length)return this.routeCache.route;const i=t.flatMap(s=>s.pose.lat!==void 0&&s.pose.lng!==void 0?[{lat:s.pose.lat,lng:s.pose.lng}]:[]),n=i.length>=2?i:void 0;return this.routeCache={track:e,count:t.length,route:n},n}traceLabels(e){const t=Is.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),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of Wt.GESTURES)document.addEventListener(t,this.handlePageGesture,!0);const e=this.getAttribute("src");e&&this.loadFromSrc(e)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(e=>{if(e[e.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of Wt.GESTURES)document.removeEventListener(e,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(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===ql||e===Kl)&&i!==t&&this.forwardPlayerAttributes()}forwardPlayerAttributes(){for(const e of[ql,Kl]){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=ot(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}=yt(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)}decorScreenBox(e){return this.sceneRenderer.decorScreenBox(e)}decorGroundPointAt(e,t,i,n=0){return this.sceneRenderer.decorGroundPointAt(e,t,i,n)}decorMetresPerNdcY(e){return this.sceneRenderer.decorMetresPerNdcY(e)}decorGrabHeightAt(e,t,i){return this.sceneRenderer.decorGrabHeightAt(e,t,i)}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=ho.json(e);this.holdForNewScene(t);const i=await t;this.documentUrl=new URL(e,location.href).href,this.showPoster(this.ufoElement.playRequested?void 0:i.image,this.documentUrl),this.sightingData=i}loader;poster;showPoster(e,t){this.poster.show(e,t)}applyHold(){const e=this.holding,t=this.poster.up;this.loader.hidden=!e||t,e&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=e||t,this.ufoElement.controlsHeld=e||t,this.ufoElement.holdClock(e)}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.syncAccountHidden(),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 fp(this,()=>document.createElement(yp))}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.imageSmoothingQuality="high",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){const i=e.views?.[t.id];this.sceneRenderer.setReferenceView(t.id,{opacity:i?i.shown?i.opacity:0: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[...new Map(this.sceneRenderer.currentDecorModelCredits.map(t=>[`${t.title}|${t.author??""}|${t.license}|${t.sourceUrl??""}`,t])).values()]}applyFrameFormat(){const e=this.ufoElement.sighting.instrument,t=mt.CANVAS_HEIGHT_PX,i=Ut.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:pm,url:this.getAttribute("star-catalog-src")??n6},{magnitudeLimit:fh,url:this.getAttribute("deep-star-catalog-src")??s6}],t=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=t>pm?fh:pm;const n=await lr.upTo(e,t);i===this.starCatalogRequest&&(this.starCatalog=n,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=fh||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const e=this.ufoElement.sighting,t=an.gainFor(e.instrument,{fNumber:ot(e,0)?.fNumber,fieldOfViewDeg:en.fovOf(e,0),exposureSeconds:e.exposure});return Da(r6,t)}updateAstronomy(e){this.ensureStarsDeepEnough(),this.applySceneAt(e);const t=zs.windowEndingAt(e,this.exposureSeconds()),i=t.seconds,n=this.degreesPerPixelAt(e),s=Ho.instants(i,n),r=Math.max(s,this.ufoElement.exposureTimes(e).length,zs.instants(this.decorWithTraffic(this.ufoElement.sighting),ot(this.ufoElement.sighting,e)?.elevationM??0,t.fromMs,i,n));if(r<=1){this.sceneRenderer.setExposure(1);return}this.sceneRenderer.setExposure(r,a=>this.applySceneAt(t.fromMs+t.ms*a/(r-1),{sky:Math.floor(a*s/r)!==Math.floor((a-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:en.fovOf(this.ufoElement.sighting,e)/t}roadGradeAt(e,t){return e.observerTrack.allKeyframes.length<2?0:Pl.at(e,t,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(e,t){const i=this.ufoElement.sighting;this.setWeather($h(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.seatedDecor(this.decorWithTraffic(i),e)),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??Wt.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(e)),this.sceneRenderer.setContrails(this.traffic?.contrails??Wt.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(e));const n=ot(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=ot(i,0),r=Fi(i,0),a=ps(i.event.time??{},n?.lng??Kd.lng,i.event.utcOffsetHours),l=i.weatherSource!==void 0&&a?MS(a):void 0,c=Object.fromEntries(Ca(Fi(i,e)).map(I=>[I.id,Uu(e,i.weatherTrack,r,s,n,I.id,I.instances?.length?void 0:l)]));this.sceneRenderer.setCloudOffset(Uu(e,i.weatherTrack,r,s,n,void 0,l),c),this.sceneRenderer.setObserverPose(n?{...n,pitchDeg:n.pitchDeg+this.roadGradeAt(i,e)}:Kd),this.sceneRenderer.setLensOptics(this.lensOpticsAt(e)),this.sceneRenderer.setInstrumentGain(an.gainFor(i.instrument,{fNumber:n?.fNumber,fieldOfViewDeg:en.fovOf(i,e),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,fi.byId(n?.filter).opticalDensity),this.sceneRenderer.setMedium(i.instrument.medium,i.exposure,n?.fNumber??i.instrument.fNumber,i.iso),this.sceneRenderer.setPerception(zo.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(Yt.bodyAt(i,e,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(ot(i,0),n,e),this.placeBodiesAt(e,t===void 0),this.sceneRenderer.updateDecorLitState(e,t?.stepMs??0),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,e)),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 h=n?.lat??Kd.lat,d=n?.lng??Kd.lng,u=ps(i.event.time??{},d,i.event.utcOffsetHours),p={lat:h,lng:d,elevationM:n?.elevationM??0};this.pushSatellitesAt(u,e,p),this.ensureFireballs(u);const f=[...this.interpretationShown?.reentries??[],...this.fireballs?.reentries??[]];this.sceneRenderer.setReentries(f.length===0?[]:Et.viewsAt(f,e,{lat:h,lng:d,heightM:p.elevationM}));const g=this.interpretationShown?.launches??[];if(this.sceneRenderer.setLaunchPlumes(g.length===0||!u?[]:St.viewsAt(g,e,{lat:h,lng:d,heightM:p.elevationM},St.sunDirectionAt(new Date(u.getTime()+e)))),t&&!t.sky)return;if(this.sceneRenderer.setSkyUnknown(!u),!u){this.sceneRenderer.setAstronomy(a6);return}const m=new Date(u.getTime()+e),v=Math.max(1,Math.round(.25*this.degreesPerPixelAt(e)/Ho.DEG_PER_SECOND*1e3)),b=Math.max(1e-8,this.degreesPerPixelAt(e)*.1),M=`${Math.floor(m.getTime()/v)}|${Math.round(h/b)}|${Math.round(d/b)}|${Math.round(p.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(M===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=M;const y=Ji("Sun",m,p),x=Ji("Moon",m,p);let S=Ri.separationOf(y,x)<1?Ri.viewAt(m,p):void 0;if(S){const I=Ri.offsetOf(y,x,S.separationDeg);if(S.obscuration>Wt.LIMB_FROM_OBSCURATION){const R=this.limbFor(m,p);R&&(S={...S,obscuration:1-Ss.uncoveredFraction(R,S.sunRadiusDeg,I),limb:R})}S={...S,horizonShare:Ri.horizonShare(S,I,y.altitudeDeg,y.azimuthDeg,_n.distanceKm(m,p))}}const A={...y,magnitude:Gf("Sun",m)-2.5*Math.log10(Ri.beamFraction(S))};this.lastSun={altitudeDeg:A.altitudeDeg,azimuthDeg:A.azimuthDeg};const w={...x,phase:oo(m),magnitude:Gf("Moon",m),radiusDeg:_n.apparentRadiusDeg(m,p)},T=w4.map(I=>({body:I,position:Ji(I,m,p),magnitude:Gf(I,m)}));this.sceneRenderer.setAstronomy({sun:A,moon:w,planets:T,comet:this.cometAt(m,p),novae:vp.appearancesAt(m,p).map(({outburst:I,position:R,magnitude:O})=>({id:I.id,position:R,magnitude:O})),stars:this.starCatalog?{catalog:this.starCatalog,date:m,observer:p}:void 0,frame:{date:m,observer:p},localHour:((m.getUTCHours()+m.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(d/15)))%24+24)%24,eclipse:S}),this.ufoElement.setSunAltitude(A.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(e,t){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,mh.load(i6).then(s=>{this.limbRelief=s,this.lastSkyKey="",s&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(e.getTime()-i.atMs)<5e3&&i.lat===t.lat&&i.lng===t.lng&&i.elevationM===t.elevationM)return i.profile;const n=Ss.profile(e,t,this.limbRelief);return this.limbCache={profile:n,atMs:e.getTime(),lat:t.lat,lng:t.lng,elevationM:t.elevationM},n}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||!Ts.mayCover(n+i)){this.fireballs={key:s,status:"outside",reentries:[]};return}const r={key:s,status:"loading",reentries:[]};this.fireballs=r,Wt.fireballArchive.between(n,n+i).then(a=>{r.status=a?"ready":"unavailable",r.records=a??[],r.reentries=r.records.map(l=>Ts.asReentry(l,n)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(B2)),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}seatedDecor(e,t){if(!e.some(r=>r.observerKeyframes?.length))return e;const i=e.map(r=>{if(!r.observerKeyframes?.length)return"";const a=Wv(r,t);return`${a.side??"-"}/${a.facing??"-"}`}).join("|"),n=this.seatedMemo;if(n&&n.base===e&&n.seats===i)return n.seated;const s=e.map(r=>{if(!r.observerKeyframes?.length)return r;const a=Wv(r,t);return{...r,observerSide:a.side,observerFacing:a.facing}});return this.seatedMemo={base:e,seats:i,seated:s},s}ensureTraffic(e){const t=ot(e,0),i=t?.lng===void 0?void 0:ps(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 a=Wt.aircraftProviders.get(this.aircraftSource.id);if(a||Wt.aircraftProviders.set(this.aircraftSource.id,a=this.aircraftSource.create()),a.mayCover&&!a.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=Pn.MAX_GAP_S*1e3,d=Wt.SOUND_LOOKBACK_MS,u={lat:t.lat,lng:t.lng,elevationM:t.elevationM??0},p=(f,g)=>f.TrafficDecor.from(l.tracks??[],c,s,f.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,u)});a.between(c,s-d,s+n+h).then(async f=>{if(this.traffic!==l)return;if(f.status!=="found"){l.status=f.status==="outside"?"outside":"unavailable",this.announceTraffic();return}let g;try{g=await Wt.loadTrafficRuntime()}catch{this.traffic===l&&(l.status="unavailable",this.announceTraffic());return}this.traffic===l&&(l.status="ready",l.tracks=f.tracks,l.set=p(g),this.startAircraftSound(l,g),this.announceTraffic(),this.describeTraffic(a,l,g,p),l.set.shown>0&&this.readUpperAir(l,g,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,a]of n.presence){if(e<a.fromMs||e>a.untilMs)continue;const l=n.flights.get(r),c=l?Pn.positionAt(l,i.startMs+e):void 0;c&&t.set(r,{heightM:c.geo.heightM,sunElevationDeg:Bn.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=Wt.trafficRuntime;return r?.TrafficTooltip.text(n,s.names?.trafficTooltip??r.TrafficTooltip.ENGLISH,a=>s.towards(a))}trafficInfoAt(e){const t=this.traffic,i=t?.set?.flights.get(e);if(!t||!i||t.startMs===void 0||!t.observer)return;const n=Wt.trafficRuntime;if(!n)return;const s=t.descriptions?.get(As.keyOf(i)),r=ot(this.ufoElement.sighting,this.lastTimeMs),a={lat:t.observer.lat,lng:t.observer.lng,heightM:r?.elevationM??0},l=n.AmbientNoise.dbA($h(this.ufoElement.sighting,this.lastTimeMs)),c=n.TrafficInfos.at(i,s,a,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.newAircraftAudio(t),this.sortOutAudible(e,t)}sortOutAudible(e,t){!e.set||!e.observer||(e.audible=t.TrafficSound.candidates(e.set.flights,e.descriptions??new Map,As.keyOf,{...e.observer,heightM:0},{ambientDbA:t.AmbientNoise.BASE_DB_A}))}pushAircraftSound(e,t){this.startDecorAircraftSound(e);const i=this.aircraftAudio;if(!i)return;const n=Wt.trafficRuntime;if(!n){i.setVoices([]);return}const s=ot(e,t),r=$h(e,t),a={ambientDbA:n.AmbientNoise.dbA(r),referenceAmplitude:n.AmbientNoise.referenceAmplitude(r)},l=this.trafficVoices(t,s,a,n),c=e.event.place?.[0],h={lat:s?.lat??c?.lat,lng:s?.lng??c?.lng};h.lat!==void 0&&h.lng!==void 0&&(this.decorAircraftHearing??=new n.DecorAircraftHearing,l.push(...this.decorAircraftHearing.voices(e,t,{lat:h.lat,lng:h.lng,heightM:s?.elevationM??0},a,d=>this.decorModelSounds.get(d.model?.id??""))),l.sort((d,u)=>u.levelDbA-d.levelDbA),l.length=Math.min(l.length,4)),i.setVoices(l,s?.headingDeg??0)}trafficVoices(e,t,i,n){const s=this.traffic,r=s?.set;if(!s||!r||!s.audible||s.startMs===void 0||!s.observer)return[];const a={lat:s.observer.lat,lng:s.observer.lng,heightM:t?.elevationM??0};return n.TrafficSound.voices(s.audible,r.flights,s.descriptions??new Map,As.keyOf,a,s.startMs+e,i)}startDecorAircraftSound(e){const t=e.decor.filter(i=>i.kind==="aircraft"&&i.track?.some(n=>(n.altitudeM??0)>0));if(t.length!==0){for(const i of t){const n=i.model?.id;!n||i.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.sceneRenderer.entryOfDecorModel(n).then(s=>{this.decorModelSounds.set(n,s?.parameters?.sound)}))}if(this.aircraftAudio||Wt.trafficRuntime){!this.aircraftAudio&&Wt.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(Wt.trafficRuntime));return}Wt.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(e){const t=new e.AircraftAudio;return t.setLevel(this.ufoElement.level),this.interacted&&t.resume(),t.setPaused(this.ufoElement.playbackState!=="playing"),t}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(Qk)),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=>As.keyOf(c))),r=t.tracks.filter(c=>s.has(As.keyOf(c))&&c.points.length>0),a=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(As.keyOf(c),d),a.set(As.keyOf(c),i.AircraftModels.of(d)))})),!(this.traffic!==t||a.size===0)&&(t.descriptions=l,t.models=a,t.set=n(i,a),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=Wt.upperAirProviders.get(s.id);r||Wt.upperAirProviders.set(s.id,r=s.create());const a=await r.between(e.observer,i,n);this.traffic!==e||a.status!=="found"||(e.air=a.samples,e.airSource=a.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 a=n.presence.get(r.id),l=n.flights.get(r.id);if(!a||!l)continue;const c=Pn.positionAt(l,i.startMs+Math.min(a.untilMs,Math.max(a.fromMs,e)));c&&t.set(r.id,{heightM:c.geo.heightM,sunElevationDeg:Bn.sunElevationDeg(s,i.observer,c.geo)})}return t}sunElevationAt(e,t){const i=Ji("Sun",new Date(e.t),t);return Bn.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??Wt.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(U2)))},s=Wt.tleArchive;(async()=>{if(!await s.covers(e))return n("outside");const[r,a]=await Promise.all([s.at(e),_e(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!r)return n("unavailable");this.satellites={snapshot:r,passes:new a.SatellitePasses(r.objects)},n("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>n("unavailable"))}get satelliteState(){const 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=ot(i,0),s=i.event.place?.[0],r=n?.lat??s?.lat,a=n?.lng??s?.lng;if(!t||r===void 0||a===void 0)return[];const l=ps(i.event.time??{},a,i.event.utcOffsetHours);if(!l)return[];const c=Math.min(Math.max(e,0),4*36e5),h={lat:r,lng:a,elevationM:n?.elevationM??0},d=JSON.stringify([this.satellitesFor,l.getTime(),r,a,h.elevationM,c]);if(this.satellitePassesMemo?.key===d)return this.satellitePassesMemo.passes;const u=Math.max(10,Math.ceil(c/1e3/600)),p=t.passes.passesDuring(l,new Date(l.getTime()+c),h,u);return this.satellitePassesMemo={key:d,passes:p},p}cometAt(e,t){const i=mu.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),a=new Map,l=new Map,c=new Set;for(const f of i.sourceIds){const g=i.getInterpolatedShapeAt(e,f);if(!g)continue;const m={...g,bounds:{...g.bounds,x:g.bounds.x+s.x,y:g.bounds.y+s.y}};a.set(f,m);const v=g.aim?this.sceneRenderer.screenPointOf(Fs.directionOf(g.aim,this.directionScratch)):{ndcX:(m.bounds.x+m.bounds.width/2)/n.width*2-1,ndcY:-((m.bounds.y+m.bounds.height/2)/n.height*2-1)},b=v!==void 0&&Math.abs(v.ndcX)<=1&&Math.abs(v.ndcY)<=1,M=b?this.sceneRenderer.decorDistancesAt(v.ndcX,v.ndcY,f):{};c.add(f),(b||g.aim)&&c.delete(f);const y=g.angular?.widthDeg??r.pxToDeg(g.bounds.width),x=this.sizeEstimateOf(f);x.add(y,M);const S=gh.of(t,f);l.set(f,Ln.resolve({hypothesisM:this.distanceHypotheses.get(f),derivedM:S&&y>0?mt.distanceMAt(S.widthM,y):void 0,range:x.distanceRangeAt(y),crossing:M}))}for(const[f,g]of a)for(const[m,v]of a){if(m===f||v.transparency>=1||v.bounds.width*v.bounds.height<=g.bounds.width*g.bounds.height||!(g.bounds.x>=v.bounds.x&&g.bounds.y>=v.bounds.y&&g.bounds.x+g.bounds.width<=v.bounds.x+v.bounds.width&&g.bounds.y+g.bounds.height<=v.bounds.y+v.bounds.height))continue;const M=l.get(m);M&&l.set(f,{distanceM:M.distanceM*.999,basis:M.basis});break}this.depths=l;const h=i.sourceIds,d=[];for(const[f,g]of a)d.push({sourceId:f,shape:g,distanceM:l.get(f).distanceM,renderOrder:h.indexOf(f),aim:g.aim,hidden:c.has(f)||this.interpretationShown!==void 0&&(!this.comparing||g.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const p=(ot(t,e)?.rollDeg??0)+Yt.bodyAt(t,e,this.ufoElement.steadyBody).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:Ut.starPointsOf(t.instrument),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(e){this.interpretationShown=e,this.ufoElement.playerTitle=e?.title,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(e){this.inTheRound=e}get compareAccount(){return this.comparing}set compareAccount(e){this.comparing=e,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}get confrontation(){return this.confrontationReadings}groundAlong(e,t,i){const n=this.sceneRenderer.bodyGround,s=qe.eyeOf(this.ufoElement.sighting,i,n);return s?qe.lineOfSightMeetsGround(s,e,t,n):void 0}bodyMaskedBy(e,t){return this.sceneRenderer.bodyMaskedByDecor(e,t)}bodyReading(e,t){const i=this.sceneRenderer.bodyGround,n=this.ufoElement.sighting,s=u=>qe.eyeOf(n,u,i),r=new qe(e,i,s).at(t),a=s(t);if(!r||!a)return;const l=r.eastM-a.eastM,c=r.northM-a.northM,h=r.upM-a.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=f=>qe.eyeOf(n,f,i),r=new qe(e,i,s),a=r.at(t)?t:e.track[0]?.t,l=a===void 0?void 0:r.at(a),c=a===void 0?void 0:s(a);if(!l||!c)return;const h=l.eastM-c.eastM,d=l.northM-c.northM,u=l.upM-c.upM,p=Math.hypot(h,d);if(!(p===0&&u===0))return{azimuthDeg:(Math.atan2(h,d)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(u,p)*180/Math.PI}}placeBodiesAt(e,t){const i=this.interpretationShown,n=this.ufoElement.sighting;let s=[],r=[];const a=this.sceneRenderer.bodyGround,l=f=>qe.eyeOf(n,f,a);i&&(s=i.bodies.map(f=>new qe(f,a,l).at(e)).filter(f=>f!==void 0));const c=Fi(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(f=>f.id)??[],i?.smoke??[],d);const u=i&&this.comparing?l(e):void 0;if(u&&(r=new Ii(n.timeline).at(e,s,u,f=>f.outlineNode?this.sceneRenderer.bodyOutline?.(f.id,f.outlineNode):void 0)),this.confrontationReadings=r,!t)return;const p=JSON.stringify(r);p!==this.confrontationSignature&&(this.confrontationSignature=p,this.dispatchEvent(new CustomEvent(e6,{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&&Fi(e,s.t).storm&&this.handleLightningFlash(s)}ensureLightningSchedule(e){const t=Fi(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?ps(n,s?.lng??0,e.event.utcOffsetHours):void 0,a=(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=ji.schedule({durationMs:a,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?ps(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,a=Math.round(n.getTime()/1e3)+Math.round(t.lat*1e3),l=bi.schedule({ratePerHour:bi.observedRatePerHour(bi.apexPosition(n,s).altitudeDeg),durationMs:r,velocityKmS:bi.TYPICAL_VELOCITY_KM_S,seed:a}),c=ac.activeAt(n).map(d=>{const u=ac.radiantPosition(d.shower,n,s);return{entry:d,position:u,rate:ac.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=Uo.schedule({ratePerHour:c.rate,durationMs:r,velocityKmS:c.entry.shower.velocityKmS,seed:a+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=ot(t,e),r=s?.fNumber??i.fNumber;if(!n||r===void 0)return;const a=Ut.focalLengthMmFor(i,en.fovOf(t,e));if(a!==void 0)return{focalLengthMm:a,fNumber:r,focusDistance:s?.focusDistanceM??0,frameHeightMm:n.heightMm}}projectionAt(e){const t=this.ufoElement.sighting;return $s.of(t.instrument,mt.CANVAS_HEIGHT_PX,en.fovOf(t,e))}sizeEstimateOf(e){let t=this.sizeEstimates.get(e);return t||(t=new Wk,this.sizeEstimates.set(e,t)),t}}const yp="rr0-scene";function o6(){Cp(),customElements.get(yp)||customElements.define(yp,Wt)}class l6{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=MM(this.shapePrototype,this.currentPointer.x,this.currentPointer.y);this.timeline.addKeyframe(e,[{sourceId:this.sourceId,shape:t}])}}class c6{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 Jb="rr0-provider-settings",h6=`
9937
10000
  rr0-provider-settings { display: block; }
9938
10001
  rr0-provider-settings .ps-provider { margin: .3em 0; }
9939
10002
  rr0-provider-settings .ps-heading { font-weight: 600; margin-right: .6em; }
9940
10003
  rr0-provider-settings .ps-setting { display: inline-flex; align-items: center; gap: .3em; margin-right: .8em; }
9941
- `;class dk extends HTMLElement{list=[];words={};shown={};set providers(e){this.list=e,this.render()}set labels(e){this.words=e,this.render()}get values(){return this.shown}set values(e){this.shown=structuredClone(e),this.render()}connectedCallback(){this.render()}word(e,t){return this.words[e]??t}current(e,t){return this.shown[e.id]?.[t.id]??t.default}edit(e,t,i){const n={...this.shown[e.id]??{}};i===void 0?delete n[t.id]:n[t.id]=i,this.shown={...this.shown,[e.id]:n},this.dispatchEvent(new Event("settingschange",{bubbles:!0}))}render(){if(!this.isConnected&&this.list.length===0)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=hk;const i=this.list.map(n=>{const s=e.createElement("div");s.className="ps-provider",s.dataset.provider=n.id;const r=e.createElement("span");return r.className="ps-heading",r.textContent=this.word(n.id,n.label),r.title=this.word(`${n.id}.hint`,n.hint),s.append(r,...n.settings.map(a=>this.control(n,a))),s});this.replaceChildren(t,...i),gn.fit(this)}control(e,t){const i=this.ownerDocument,n=i.createElement("label");n.className="ps-setting";const s=i.createElement("span");s.textContent=this.word(`${e.id}.${t.id}`,t.label),n.append(s);const r=`${e.id}-${t.id}`;if(t.kind==="choice"){const a=i.createElement("select");a.id=r;for(const l of t.choices??[]){const c=i.createElement("option");c.value=l.id,c.textContent=this.word(`${e.id}.${t.id}.${l.id}`,l.label),a.append(c)}a.value=String(this.current(e,t)),a.addEventListener("change",()=>this.edit(e,t,a.value)),n.append(a)}else{const a=i.createElement("input");a.id=r,a.type="number",t.min!==void 0&&(a.min=String(t.min)),t.max!==void 0&&(a.max=String(t.max)),t.step!==void 0&&(a.step=String(t.step)),a.value=String(this.current(e,t)),a.addEventListener("input",()=>{const l=a.value.trim()===""?void 0:Number(a.value);this.edit(e,t,Number.isFinite(l)?l:void 0)}),n.append(a),t.unit&&n.append(i.createTextNode(` ${t.unit}`))}return n}}function uk(){customElements.get(Jb)||customElements.define(Jb,dk)}const Qb="rr0-popover-picker",pk=`
10004
+ `;class d6 extends HTMLElement{list=[];words={};shown={};set providers(e){this.list=e,this.render()}set labels(e){this.words=e,this.render()}get values(){return this.shown}set values(e){this.shown=structuredClone(e),this.render()}connectedCallback(){this.render()}word(e,t){return this.words[e]??t}current(e,t){return this.shown[e.id]?.[t.id]??t.default}edit(e,t,i){const n={...this.shown[e.id]??{}};i===void 0?delete n[t.id]:n[t.id]=i,this.shown={...this.shown,[e.id]:n},this.dispatchEvent(new Event("settingschange",{bubbles:!0}))}render(){if(!this.isConnected&&this.list.length===0)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=h6;const i=this.list.map(n=>{const s=e.createElement("div");s.className="ps-provider",s.dataset.provider=n.id;const r=e.createElement("span");return r.className="ps-heading",r.textContent=this.word(n.id,n.label),r.title=this.word(`${n.id}.hint`,n.hint),s.append(r,...n.settings.map(a=>this.control(n,a))),s});this.replaceChildren(t,...i),gn.fit(this)}control(e,t){const i=this.ownerDocument,n=i.createElement("label");n.className="ps-setting";const s=i.createElement("span");s.textContent=this.word(`${e.id}.${t.id}`,t.label),n.append(s);const r=`${e.id}-${t.id}`;if(t.kind==="choice"){const a=i.createElement("select");a.id=r;for(const l of t.choices??[]){const c=i.createElement("option");c.value=l.id,c.textContent=this.word(`${e.id}.${t.id}.${l.id}`,l.label),a.append(c)}a.value=String(this.current(e,t)),a.addEventListener("change",()=>this.edit(e,t,a.value)),n.append(a)}else{const a=i.createElement("input");a.id=r,a.type="number",t.min!==void 0&&(a.min=String(t.min)),t.max!==void 0&&(a.max=String(t.max)),t.step!==void 0&&(a.step=String(t.step)),a.value=String(this.current(e,t)),a.addEventListener("input",()=>{const l=a.value.trim()===""?void 0:Number(a.value);this.edit(e,t,Number.isFinite(l)?l:void 0)}),n.append(a),t.unit&&n.append(i.createTextNode(` ${t.unit}`))}return n}}function u6(){customElements.get(Jb)||customElements.define(Jb,d6)}const Qb="rr0-popover-picker",p6=`
9942
10005
  rr0-popover-picker { display: inline-block; }
9943
10006
  rr0-popover-picker .pp-trigger { anchor-name: --rr0-popover-picker; font: inherit; text-align: left; max-width: 100%; cursor: pointer; }
9944
10007
  rr0-popover-picker .pp-trigger::after { content: " ▾"; opacity: .6; }
@@ -9952,7 +10015,7 @@ rr0-popover-picker .pp-choice:hover, rr0-popover-picker .pp-choice:focus-visible
9952
10015
  rr0-popover-picker .pp-choice[aria-selected="true"] { font-weight: 600; }
9953
10016
  rr0-popover-picker .pp-choice[aria-selected="true"]::before { content: "✓ "; }
9954
10017
  rr0-popover-picker .pp-choice[aria-disabled="true"] { opacity: .45; cursor: not-allowed; background: none; }
9955
- `;class bp extends HTMLElement{tree=[];current="";trigger;panel;stale=!0;build(){if(this.trigger)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=pk;const i=e.createElement("button");i.type="button",i.className="pp-trigger";const n=e.createElement("div");n.className="pp-panel",n.setAttribute("popover",""),n.setAttribute("role","listbox");const s=`${this.id||"rr0-popover-picker"}-panel`;n.id=s,i.setAttribute("popovertarget",s),i.setAttribute("aria-haspopup","listbox"),this.trigger=i,this.panel=n,n.addEventListener("beforetoggle",r=>{r.newState==="open"&&this.drawMenu()}),this.append(t,i,n),this.render()}connectedCallback(){this.build()}set choices(e){this.tree=e,this.build(),this.render()}get choices(){return this.tree}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(e){this.setAttribute("placeholder",e),this.render()}get value(){return this.current}set value(e){this.current=e,this.build(),this.render()}get selectedLabel(){return bp.find(this.tree,this.current)?.label}static find(e,t){for(const i of e)if(i.children){const n=bp.find(i.children,t);if(n)return n}else if(i.id===t)return i}pick(e){e.disabledReason!==void 0||e.id===void 0||(this.panel?.hidePopover?.(),e.id!==this.current&&(this.current=e.id,this.render(),this.dispatchEvent(new Event("change",{bubbles:!0}))))}render(){if(!this.trigger||!this.panel)return;this.trigger.textContent=this.selectedLabel??(this.current||this.placeholder),this.stale=!0;let e=!1;try{e=this.panel.matches(":popover-open")}catch{}e&&this.drawMenu()}drawMenu(){if(!this.panel||!this.stale)return;this.stale=!1;const e=this.ownerDocument,t=(i,n)=>i.flatMap(s=>{if(s.children){const l=e.createElement("div");return l.className="pp-heading",l.setAttribute("role","presentation"),l.style.setProperty("--pp-depth",String(n)),l.textContent=s.label,[l,...t(s.children,n+1)]}const r=e.createElement("button");r.type="button",r.className="pp-choice",r.dataset.id=s.id,r.setAttribute("role","option"),r.setAttribute("aria-selected",String(s.id===this.current)),r.style.setProperty("--pp-depth",String(n)),r.textContent=s.label;const a=s.disabledReason??s.hint;return a&&(r.title=a),s.disabledReason!==void 0&&r.setAttribute("aria-disabled","true"),r.addEventListener("click",()=>this.pick(s)),[r]});this.panel.replaceChildren(...t(this.tree,0))}}function fk(){customElements.get(Qb)||customElements.define(Qb,bp)}const Mp="rr0-duration-input",mk=`
10018
+ `;class bp extends HTMLElement{tree=[];current="";trigger;panel;stale=!0;build(){if(this.trigger)return;const e=this.ownerDocument,t=e.createElement("style");t.textContent=p6;const i=e.createElement("button");i.type="button",i.className="pp-trigger";const n=e.createElement("div");n.className="pp-panel",n.setAttribute("popover",""),n.setAttribute("role","listbox");const s=`${this.id||"rr0-popover-picker"}-panel`;n.id=s,i.setAttribute("popovertarget",s),i.setAttribute("aria-haspopup","listbox"),this.trigger=i,this.panel=n,n.addEventListener("beforetoggle",r=>{r.newState==="open"&&this.drawMenu()}),this.append(t,i,n),this.render()}connectedCallback(){this.build()}set choices(e){this.tree=e,this.build(),this.render()}get choices(){return this.tree}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(e){this.setAttribute("placeholder",e),this.render()}get value(){return this.current}set value(e){this.current=e,this.build(),this.render()}get selectedLabel(){return bp.find(this.tree,this.current)?.label}static find(e,t){for(const i of e)if(i.children){const n=bp.find(i.children,t);if(n)return n}else if(i.id===t)return i}pick(e){e.disabledReason!==void 0||e.id===void 0||(this.panel?.hidePopover?.(),e.id!==this.current&&(this.current=e.id,this.render(),this.dispatchEvent(new Event("change",{bubbles:!0}))))}render(){if(!this.trigger||!this.panel)return;this.trigger.textContent=this.selectedLabel??(this.current||this.placeholder),this.stale=!0;let e=!1;try{e=this.panel.matches(":popover-open")}catch{}e&&this.drawMenu()}drawMenu(){if(!this.panel||!this.stale)return;this.stale=!1;const e=this.ownerDocument,t=(i,n)=>i.flatMap(s=>{if(s.children){const l=e.createElement("div");return l.className="pp-heading",l.setAttribute("role","presentation"),l.style.setProperty("--pp-depth",String(n)),l.textContent=s.label,[l,...t(s.children,n+1)]}const r=e.createElement("button");r.type="button",r.className="pp-choice",r.dataset.id=s.id,r.setAttribute("role","option"),r.setAttribute("aria-selected",String(s.id===this.current)),r.style.setProperty("--pp-depth",String(n)),r.textContent=s.label;const a=s.disabledReason??s.hint;return a&&(r.title=a),s.disabledReason!==void 0&&r.setAttribute("aria-disabled","true"),r.addEventListener("click",()=>this.pick(s)),[r]});this.panel.replaceChildren(...t(this.tree,0))}}function f6(){customElements.get(Qb)||customElements.define(Qb,bp)}const Mp="rr0-duration-input",m6=`
9956
10019
  rr0-duration-input { position: relative; display: inline-flex; align-items: center; gap: .3em; }
9957
10020
  rr0-duration-input .duration-field { position: relative; display: inline-flex; align-items: center; gap: .25em; }
9958
10021
  rr0-duration-input .duration-field input[type="text"] { padding-right: 1.6em; }
@@ -9966,8 +10029,8 @@ rr0-duration-input .duration-mode { order: -1; font: inherit; color: inherit; ba
9966
10029
  rr0-duration-input .duration-mode:hover { text-decoration-thickness: 2px; }
9967
10030
  rr0-duration-input .duration-mode:focus-visible { outline: 2px solid #4af; outline-offset: 2px; border-radius: 2px; }
9968
10031
  rr0-duration-input [hidden] { display: none !important; }
9969
- `;class gk extends HTMLElement{wording=ka;built=!1;precise=!0;numberInput;textInput;modeButton;helpButton;popup;chosen;build(){if(this.built)return;this.built=!0;const e=this.getAttribute("name"),t=this.ownerDocument,i=t.createElement("style");i.textContent=mk;const n=t.createElement("span");n.className="duration-field",this.numberInput=t.createElement("input"),this.numberInput.type="number",this.numberInput.min="0",this.numberInput.max="86400",this.numberInput.step="0.1",this.numberInput.setAttribute("aria-required","true");const s=t.createElement("span");s.className="duration-unit",s.textContent="s",this.textInput=t.createElement("input"),this.textInput.type="text",this.textInput.hidden=!0,this.helpButton=t.createElement("button"),this.helpButton.type="button",this.helpButton.className="duration-help",this.helpButton.textContent="?",this.helpButton.hidden=!0,this.popup=t.createElement("div"),this.popup.className="duration-helppop",this.popup.hidden=!0,this.chosen=t.createElement("span"),this.chosen.className="duration-chosen",this.chosen.hidden=!0,this.modeButton=t.createElement("button"),this.modeButton.type="button",this.modeButton.className="duration-mode",e&&(this.numberInput.id=e,this.textInput.id=`${e}-text`),n.append(this.numberInput,s,this.textInput,this.helpButton,this.popup),this.append(i,n,this.modeButton,this.chosen),this.numberInput.addEventListener("input",()=>{const r=this.numberInput.value;this.tell(r===""?void 0:Number(r),void 0)}),this.textInput.addEventListener("input",()=>this.readText()),this.textInput.addEventListener("focus",()=>this.showDeduction()),this.modeButton.addEventListener("click",()=>this.setPrecise(!this.precise)),this.helpButton.addEventListener("click",()=>{this.popup.hidden=!this.popup.hidden}),this.applyWording()}connectedCallback(){this.build(),document.addEventListener("pointerdown",this.closeHelpOutside,!0),document.addEventListener("keydown",this.closeHelpOnEscape,!0)}disconnectedCallback(){document.removeEventListener("pointerdown",this.closeHelpOutside,!0),document.removeEventListener("keydown",this.closeHelpOnEscape,!0)}closeHelpOutside=e=>{this.popup&&!this.popup.hidden&&!e.composedPath().includes(this)&&(this.popup.hidden=!0)};closeHelpOnEscape=e=>{e.key==="Escape"&&this.popup&&(this.popup.hidden=!0)};get input(){return this.build(),this.numberInput}get textField(){return this.build(),this.textInput}get isPrecise(){return this.build(),this.precise}set messages(e){this.wording=e,this.built&&this.applyWording()}applyWording(){const e=this.wording;this.modeButton.title=e.durationModeTitle,this.modeButton.setAttribute("aria-label",e.durationModeTitle);const t=this.ownerDocument.createElement("p");t.textContent=e.durationHelpTitle;const i=this.ownerDocument.createElement("ul");for(const n of e.durationHelpLines.split(`
9970
- `)){const s=this.ownerDocument.createElement("li");s.textContent=n,i.append(s)}this.popup.replaceChildren(t,i),this.setPrecise(this.precise)}setPrecise(e){this.build();const t=this.precise;this.precise=e,this.numberInput.hidden=!e,this.querySelector(".duration-unit").hidden=!e,this.textInput.hidden=e,this.helpButton.hidden=e,this.modeButton.textContent=e?this.wording.durationPrecise:this.wording.durationIso,this.modeButton.setAttribute("aria-pressed",String(!e)),!e&&t&&this.textInput.value===""&&this.numberInput.value!==""&&(this.textInput.value=Nn.format(Number(this.numberInput.value))),this.showDeduction(),this.showChosen()}set(e,t){this.build(),this.numberInput.value=e===void 0?"":String(e),this.textInput.value=t??"",this.setPrecise(t===void 0)}readText(){const e=this.textInput.value.trim();if(this.showDeduction(),e===""){this.numberInput.value="",this.showChosen(),this.tell(void 0,void 0);return}const t=Nn.parse(e);t&&(this.numberInput.value=String(t.chosenSeconds),this.showChosen(),this.tell(t.chosenSeconds,Nn.isExact(e)?void 0:e))}tell(e,t){this.dispatchEvent(new CustomEvent("durationchange",{detail:{seconds:e,text:t},bubbles:!0,composed:!0}))}describe(e){const t=this.wording,i=e.minSeconds===e.maxSeconds?Nn.say(e.minSeconds):`${Nn.say(e.minSeconds)} – ${Nn.say(e.maxSeconds)}`,n=e.doubt==="~"?t.timeQualifierApproximate:e.doubt==="?"?t.timeQualifierUncertain:e.doubt==="%"?t.timeQualifierBoth:"";return n?`${i} — ${n.toLowerCase()}`:i}showDeduction(){const e=this.textInput.value.trim();if(this.precise||e===""){this.textInput.title="";return}const t=Nn.parse(e);this.textInput.title=t?`→ ${this.describe(t)}`:this.wording.durationInvalid}showChosen(){const e=this.precise?void 0:Nn.parse(this.textInput.value),t=e!==void 0&&!Nn.isExact(this.textInput.value);this.chosen.hidden=!t,this.chosen.textContent=t?this.wording.durationChosen.replace("{value}",Nn.say(e.chosenSeconds)):""}}function vk(){customElements.get(Mp)||customElements.define(Mp,gk)}class Zd{static at(e,t){if(e.year===void 0||t.year===void 0)return;let i=t.year-e.year;const n=(s,r)=>s!==void 0&&r!==void 0;return n(e.month,t.month)&&(t.month<e.month||t.month===e.month&&n(e.day,t.day)&&t.day<e.day)&&i--,i>=0?i:void 0}static birthFor(e,t){if(t.year===void 0)return;const i=t.year-e;return{year:i,raw:`${String(i).padStart(4,"0")}~`}}static isFirm(e){return!/[?~%]/.test(e.raw??"")}}class wp{static easter(e){const t=e%19,i=Math.floor(e/100),n=e%100,s=Math.floor(i/4),r=i%4,a=Math.floor((i+8)/25),l=Math.floor((i-a+1)/3),c=(19*t+i-s-l+15)%30,h=Math.floor(n/4),d=n%4,u=(32+2*r+2*h-c-d)%7,p=Math.floor((t+11*c+22*u)/451),f=Math.floor((c+u-7*p+114)/31),g=(c+u-7*p+114)%31+1;return new Date(Date.UTC(e,f-1,g,12))}static lunation(e){if(e<1583)return;const t=wp.easter(e),i=uu(0,t,40);if(!i)return;const n=uu(180,i.date,20),s=uu(0,new Date(i.date.getTime()+864e5),40);if(!(!n||!s))return{begin:i.date,full:n.date,end:s.date}}static isIn(e){const t=wp.lunation(e.getUTCFullYear());return t!==void 0&&e>=t.begin&&e<t.end}}const yk=[{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."}],bk=23493,eM=[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 Us{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 Us.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Us.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return yk.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()-bk;if(!(t<0))return eM[Math.min(t,eM.length-1)]}static visibilityAt(e,t){const i=Ji("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:Us.shadowHeightKm(i),lowOrbitLit:Us.isLitOverhead(Us.LOW_ORBIT_KM,i),classes:Us.classesAt(e),trackedObjects:Us.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Us.FIRST_ORBIT}T00:00:00Z`)}}}const tM="https://ufoathome.org/reentries/index.json";class jn{static MINUTE_SLACK_MS=60*6e4;static WINDOW_SLACK_MS=60*6e4;static VISIBLE_KM=1500;static VISIBLE_DEG=jn.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??jn.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(tM)||e.push(tM),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 a of[e-jn.DAY_MS,t+jn.DAY_MS])s.add(String(new Date(a).getUTCFullYear()));const r=(await Promise.all([...s].filter(a=>n.index.years.includes(a)).map(a=>this.yearOf(a,n.base)))).flat();return jn.match(r,e,t,i)}static DAY_MS=864e5;static match(e,t,i,n){const s=[];for(const a of e){if(a.inclinationDeg!==void 0&&Math.abs(n.lat)>a.inclinationDeg+jn.VISIBLE_DEG)continue;const l=Date.parse(a.precision==="day"?`${a.time}T00:00Z`:a.time);if(Number.isFinite(l))if(a.precision==="minute"){const c=l<t?t-l:l>i?l-i:0;if(c>jn.MINUTE_SLACK_MS)continue;let h;if(a.seenLat!==void 0&&a.seenLng!==void 0&&(h=jn.distanceKm(n.lat,n.lng,a.seenLat,a.seenLng),h>jn.VISIBLE_KM))continue;s.push({record:a,timeMs:l,offsetMinutes:Math.round(c/6e4),seenKm:h})}else{const c=a.precision==="day"?jn.DAY_MS/2:(a.uncertaintyHours??0)*36e5,h=a.precision==="day"?l+c:l,d=jn.WINDOW_SLACK_MS;if(h+c+d<t||h-c-d>i)continue;s.push({record:a,timeMs:h})}}const r={minute:0,hours:1,day:2};return s.sort((a,l)=>r[a.record.precision]-r[l.record.precision]||(a.record.uncertaintyHours??0)-(l.record.uncertaintyHours??0)||a.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 jn.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 Mk="https://ufoathome.org/light-pollution/index.json";class co{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??co.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,Mk].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+co.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 a=((t+180)%360+360)%360-180,l=Math.floor((n.north-e)/n.tileDeg),c=Math.floor((a+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,p=co.nameOf(d-n.tileDeg,u),f=await this.tile(`${s}${p}.bin`);if(!f)return{status:"failed"};const g=n.tileDeg/n.cells,m=Math.min(n.cells-1,Math.floor((d-e)/g)),v=Math.min(n.cells-1,Math.floor((a-u)/g)),b=co.mcdOf(f[m*n.cells+v],n);return b===0?{status:"natural"}:{status:"found",lightPollution:Math.round(co.magPerArcsec2Of(b)*100)/100,artificialMcdPerM2:b,lat:d-(m+.5)*g,lng:u+(v+.5)*g}}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 iM=[{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 co}];class Ct{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 wt;dust=new yi;assess(e,t,i){const n=Ji("Sun",e,t),s=Ji("Moon",e,t),r={altitudeDeg:s.altitudeDeg,phaseAngleDeg:ce.phaseAngleOf(oo(e).illuminatedFraction)},a=cs.galactic(e,t),l=Ct.unit(a.centre),c=Ct.unit(a.rotation),h=Ct.unit(a.pole),d=Ct.unit(cs.eclipticPole(e,t)),u=Ct.unit(n),p=Ct.unit(s),f=Ct.normalize(Ct.reject(u,d));let g,m,v=0;const b=(M,y)=>{const x=Ct.unit({altitudeDeg:M,azimuthDeg:y}),S=Ct.between(x,u),A=ce.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:S},{...r,separationDeg:Ct.between(x,p)},M,i);A>v&&(v=A);const w=jr.fromMagPerArcsec2(A),T=10**(-.4*ce.EXTINCTION_PER_AIR_MASS*(ce.airMass(M)-1)),I=this.galaxy.surfaceBrightnessS10(Math.atan2(Ct.dot(x,c),Ct.dot(x,l))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,Ct.dot(x,h))))*180/Math.PI)*T;g=Ct.better(g,I,w,A,M,y,S);const R=Math.max(-1,Math.min(1,Ct.dot(x,d))),O=Ct.normalize(Ct.reject(x,d)),L=this.dust.surfaceBrightnessS10(Ct.between(O,f),Math.asin(R)*180/Math.PI)*T;m=Ct.better(m,L,w,A,M,y,S)};for(let M=Ct.LOWEST_DEG;M<=90;M+=Ct.COARSE_STEP_DEG)for(let y=0;y<360;y+=Ct.COARSE_STEP_DEG)b(M,y);for(const M of[g,m]){if(!M)continue;const y=Ct.FINE_SPAN_DEG,x=Ct.FINE_STEP_DEG;for(let S=M.altitudeDeg-y;S<=M.altitudeDeg+y;S+=x)if(!(S<Ct.LOWEST_DEG||S>90))for(let A=M.azimuthDeg-y;A<=M.azimuthDeg+y;A+=x)b(S,(A+360)%360)}return{milkyWay:g&&g.contrast>=Ct.THRESHOLD_CONTRAST?g:void 0,zodiacal:m&&m.contrast>=Ct.THRESHOLD_CONTRAST?m:void 0,darkestSkyMagPerArcsec2:v}}static better(e,t,i,n,s,r,a){const l=t/i;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:r,magPerArcsec2:jr.toMagPerArcsec2(t),skyMagPerArcsec2:n,sunSeparationDeg:a}}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,Ct.dot(e,t))))*180/Math.PI}static reject(e,t){const i=Ct.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]}}class wi{static MIN_NAME_LENGTH=3;static EMAIL=/[\p{L}\d._%+-]+@[\p{L}\d-]+(?:\.[\p{L}\d-]+)+/u;static PHONE=/(?:\+\d{1,3}[ .-]?|\b0)\d(?:[ .-]?\d{2}){4}\b|\+\d[\d ().-]{8,}\d/;static ADDRESS=new RegExp("\\b\\d{1,4}\\s?(?:bis|ter)?,?\\s+(?:rue|avenue|av\\.|boulevard|bd|chemin|impasse|allée|route|place|street|st\\.|road|rd|lane|drive|via|calle|piazza)\\b","iu");static inspect(e,t){const i=new Set((t?wi.all(t):[]).map(n=>`${n.kind}:${n.found}`));return wi.all(e).filter(n=>!i.has(`${n.kind}:${n.found}`))}static initialsOf(e){return e.trim().split("-").map(t=>{const i=[...t.trim()][0];return i===void 0?"":`${i.toLocaleUpperCase()}.`}).filter(t=>t!=="").join("-")}static withInitials(e,t,i=!1){let n=e;for(const s of wi.usable(t)){const r=wi.initialsOf(s);n=n.replace(new RegExp(wi.escape(s),"giu"),i?r.replace(/[.-]/g,""):r)}return n}static namesOf(e){const t=e.observer,i=[t?.lastName,...t?.firstNames??[]];return wi.usable(i.filter(n=>typeof n=="string"))}static isInitials(e){const t=e.replace(/[^\p{L}]/gu,"");return t.length>0&&t.length<=3&&t===t.toLocaleUpperCase()}static usable(e){return e.map(t=>(t??"").trim()).filter(t=>t.length>=wi.MIN_NAME_LENGTH&&!wi.isInitials(t))}static all(e){const t=[],i=e.observer,n=wi.usable([i?.lastName]),s=wi.usable(i?.firstNames??[]);for(const a of n)t.push({kind:"lastName",found:a});for(const a of s)t.push({kind:"firstNames",found:a});const r=[...n,...s];for(const a of[e.id,i?.id])for(const l of r)a&&a.toLocaleLowerCase().includes(l.toLocaleLowerCase())&&t.push({kind:"nameInId",found:`${a}`});for(const a of wi.texts(e)){for(const d of r)new RegExp(`(?<![\\p{L}])${wi.escape(d)}(?![\\p{L}])`,"iu").test(a)&&t.push({kind:"nameInText",found:d});const l=wi.ADDRESS.exec(a)?.[0];l&&t.push({kind:"address",found:l});const c=wi.EMAIL.exec(a)?.[0];c&&t.push({kind:"email",found:c});const h=wi.PHONE.exec(a)?.[0];h&&t.push({kind:"phone",found:h})}return wi.unique(t)}static texts(e){const t=n=>typeof n=="string"?[n]:typeof n=="object"&&n!==null?Object.values(n).filter(s=>typeof s=="string"):[],i=(e.place??[]).map(n=>{const s=n;return s.name??s.value?.name});return[...t(e.description),...t(e.summary),...t(e.account?.observerOccupation),...i.flatMap(t)]}static unique(e){const t=new Set;return e.filter(i=>{const n=`${i.kind}:${i.found}`;return t.has(n)?!1:(t.add(n),!0)})}static escape(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}const wk=.5,jd=40,xk=4e5,ja=Math.PI/180,Tl=180/Math.PI;class Yn{static localDirection(e,t,i,n=new D){const s=Math.tan(t/2*ja);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*ja),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*ja,n=e.altitudeDeg*ja;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)*Tl+360)%360,altitudeDeg:Math.atan2(e.y,t)*Tl}}static rotationOf(e){const t=new ui;return t.rotation.set(e.pitchDeg*ja,-e.headingDeg*ja,-(e.rollDeg??0)*ja,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Ar().setFromQuaternion(e,"YXZ"),i=(-t.y*Tl%360+360)%360,n=-t.z*Tl;return{headingDeg:i,pitchDeg:t.x*Tl,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 a=(Math.sqrt(5)-1)/2;let l=r-a*(r-s),c=s+a*(r-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let p=0;p<60&&r-s>1e-4;p++){if(!h||!d)return;h.residualDeg<d.residualDeg?(r=c,c=l,d=h,l=r-a*(r-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+a*(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 a=this.refine(r,n,s);return{registration:{...this.anglesOf(a),fovDeg:i},residualDeg:this.residualDeg(a,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(),p=h.clone().cross(d).normalize(),f=p.clone().cross(u);return new Je().set(u.x,f.x,p.x,u.y,f.y,p.y,u.z,f.z,p.z)},a=r(e[i],e[n]),c=r(t[i],t[n]).multiply(a.transpose());return new Dn().setFromRotationMatrix(new ct().setFromMatrix3(c))}static refine(e,t,i){const n=e.clone(),s=new D;for(let r=0;r<20;r++){const a=new Je().set(0,0,0,0,0,0,0,0,0),l=a.elements,c=new D;for(let p=0;p<t.length;p++){s.copy(t[p]).applyQuaternion(n);const f=s,g=[[0,f.z,-f.y],[-f.z,0,f.x],[f.y,-f.x,0]],m=[i[p].x-f.x,i[p].y-f.y,i[p].z-f.z];for(let v=0;v<3;v++){for(let b=0;b<3;b++)for(let M=0;M<3;M++)l[b*3+v]+=g[M][v]*g[M][b];c.setComponent(v,c.getComponent(v)+g[0][v]*m[0]+g[1][v]*m[1]+g[2][v]*m[2])}}for(let p=0;p<3;p++)l[p*3+p]+=1e-9;const h=c.applyMatrix3(a.invert()),d=h.length();if(d<1e-12)break;const u=new Dn().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 a=s.angleTo(i[r])*Tl;n+=a*a}return Math.sqrt(n/t.length)}}const nM=6371e3,Zc=Math.PI/180;class Wl{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*Zc)),a=[t-r,e-s,t+r,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${Wl.API}/search?bbox=${a}&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:a,bearingDeg:l}=Wl.offset(t,i,s,n),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(p=>p.name).filter(p=>!!p),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:n,distanceM:a,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:r,srcFull:e.assets.hd?.href,credit:`${Wl.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${Wl.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,i,n){const s=(i-e)*Zc*nM,r=(n-t)*Zc*nM*Math.cos((e+i)/2*Zc);return{distanceM:Math.hypot(r,s),bearingDeg:(Math.atan2(r,s)/Zc+360)%360}}}const Jd=36e5,sM=25;class vm{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=cc(e.event)??0,r=this.sampleTimings(e,n,s);let a;try{a=await this.provider.getWeather({points:r.map(l=>this.pointAt(e,l,i))})}catch{return{status:"failed",at:n}}return a?{status:"inferred",at:n,source:a.source,keyframes:a.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()/Jd)*Jd+Jd;for(;s<=n&&i.length<sM;)i.push(new Date(s)),s+=Jd;return t>0&&i[i.length-1].getTime()!==n&&i.length<sM&&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}missingOf(e){const t=e.event.time;return{date:t?.year===void 0||t.month===void 0||t.day===void 0,place:this.originOf(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=ps(i,t.lng,e.event.utcOffsetHours);return n?{origin:t,start:n}:void 0}originOf(e){const t=ot(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=ot(e,t.t);return{lat:n?.lat??i.lat,lng:n?.lng??i.lng,time:t.time}}}const Sk=Date.UTC(1940,0,1),rM=36e5,aM=.25,Ek=.7,Ak=.45,Tk=.1,_k=2,Ik=.3,Dk=.2,Rk=8,ym=.125,Ck=.05,oM=125,lM=100,cM=2500,bm=3500,Mm=8e3,kk=95,Lk=99,Ok=[96,99],Pk=["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"],Nk=5;class z2{fetchImpl;baseUrl;forecastUrl;now;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive",this.forecastUrl=e.forecastUrl??"https://api.open-meteo.com/v1/forecast",this.now=e.now??(()=>new Date)}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(h=>h.time.getTime()),i=Math.min(...t);if(i<Sk)return;const n=new Map;for(const h of e.points){const d=this.cellKey(h);n.has(d)||n.set(d,{lat:h.lat,lng:h.lng,index:n.size})}const s=i>=this.now().getTime()-Nk*864e5,r=this.requestUrl([...n.values()],new Date(i),new Date(Math.max(...t)),s);let a=this.cache.get(r);if(!a){const h=await this.fetchImpl(r);if(!h.ok)throw new Error(`Open-Meteo HTTP ${h.status}`);const d=await h.json();if(a=Array.isArray(d)?d:[d],a.length<n.size||a.some(u=>u.error||!u.hourly))return;this.cache.set(r,a)}const l=s?{id:"open-meteo-forecast",name:"Open-Meteo (forecast model)",url:r}:{id:"era5",name:"ERA5 (Open-Meteo)",url:r},c=e.points.map(h=>this.sampleAt(a[n.get(this.cellKey(h)).index].hourly,h.time));if(!c.some(h=>h===void 0))return{samples:c,source:l}}cellKey(e){return`${Math.round(e.lat/aM)},${Math.round(e.lng/aM)}`}requestUrl(e,t,i,n){const s=new URLSearchParams({latitude:e.map(r=>r.lat).join(","),longitude:e.map(r=>r.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:Pk.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${n?this.forecastUrl:this.baseUrl}?${s}`}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(a=>Date.parse(`${a}Z`)),n=t.getTime();if(i.length===0||n<i[0]-rM||n>i[i.length-1]+rM)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,a)=>r+(a-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(oM*(e.temperatureC-e.dewPointC),lM,cM)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:bm,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Mm,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=kk&&e.weatherCode<=Lk,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(Xr.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/Rk),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":Ok.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=(Ek*e.cloudCoverLow+Ak*e.cloudCoverMid+Tk*e.cloudCoverHigh)/i,s=Math.min(1,e.precipitationMm/_k);return this.clamp(n+Ik*s+(t?Dk:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<Ck)return;const t=this.clamp(oM*(e.temperatureC-e.dewPointC),lM,cM);if(e.cloudCoverLow>=ym)return Math.round(t);if(e.cloudCoverMid>=ym)return bm;if(e.cloudCoverHigh>=ym)return Mm;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?bm:Mm}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function Fk(){return new z2}const Uk=5;class H2{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 a=await this.fetchImpl(s,{signal:i.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const l=await a.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 a=await r.json(),l=(Array.isArray(a)?a:[]).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??Uk)});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 Bk(){return new H2}const zk=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new H2}],sg=[{id:"era5",name:"Open-Meteo",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new z2}],wm=o=>o.id==="open-meteo-forecast"||sg.some(e=>e.id===o.id);class Hk{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 iw(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const xm=[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>sw()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new tw}],hM=[{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 nw},{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 Hk}];class vh{constructor(e,t){this.root=e,this.messages=t}static STYLE=`
10032
+ `;class g6 extends HTMLElement{wording=ka;built=!1;precise=!0;numberInput;textInput;modeButton;helpButton;popup;chosen;build(){if(this.built)return;this.built=!0;const e=this.getAttribute("name"),t=this.ownerDocument,i=t.createElement("style");i.textContent=m6;const n=t.createElement("span");n.className="duration-field",this.numberInput=t.createElement("input"),this.numberInput.type="number",this.numberInput.min="0",this.numberInput.max="86400",this.numberInput.step="0.1",this.numberInput.setAttribute("aria-required","true");const s=t.createElement("span");s.className="duration-unit",s.textContent="s",this.textInput=t.createElement("input"),this.textInput.type="text",this.textInput.hidden=!0,this.helpButton=t.createElement("button"),this.helpButton.type="button",this.helpButton.className="duration-help",this.helpButton.textContent="?",this.helpButton.hidden=!0,this.popup=t.createElement("div"),this.popup.className="duration-helppop",this.popup.hidden=!0,this.chosen=t.createElement("span"),this.chosen.className="duration-chosen",this.chosen.hidden=!0,this.modeButton=t.createElement("button"),this.modeButton.type="button",this.modeButton.className="duration-mode",e&&(this.numberInput.id=e,this.textInput.id=`${e}-text`),n.append(this.numberInput,s,this.textInput,this.helpButton,this.popup),this.append(i,n,this.modeButton,this.chosen),this.numberInput.addEventListener("input",()=>{const r=this.numberInput.value;this.tell(r===""?void 0:Number(r),void 0)}),this.textInput.addEventListener("input",()=>this.readText()),this.textInput.addEventListener("focus",()=>this.showDeduction()),this.modeButton.addEventListener("click",()=>this.setPrecise(!this.precise)),this.helpButton.addEventListener("click",()=>{this.popup.hidden=!this.popup.hidden}),this.applyWording()}connectedCallback(){this.build(),document.addEventListener("pointerdown",this.closeHelpOutside,!0),document.addEventListener("keydown",this.closeHelpOnEscape,!0)}disconnectedCallback(){document.removeEventListener("pointerdown",this.closeHelpOutside,!0),document.removeEventListener("keydown",this.closeHelpOnEscape,!0)}closeHelpOutside=e=>{this.popup&&!this.popup.hidden&&!e.composedPath().includes(this)&&(this.popup.hidden=!0)};closeHelpOnEscape=e=>{e.key==="Escape"&&this.popup&&(this.popup.hidden=!0)};get input(){return this.build(),this.numberInput}get textField(){return this.build(),this.textInput}get isPrecise(){return this.build(),this.precise}set messages(e){this.wording=e,this.built&&this.applyWording()}applyWording(){const e=this.wording;this.modeButton.title=e.durationModeTitle,this.modeButton.setAttribute("aria-label",e.durationModeTitle);const t=this.ownerDocument.createElement("p");t.textContent=e.durationHelpTitle;const i=this.ownerDocument.createElement("ul");for(const n of e.durationHelpLines.split(`
10033
+ `)){const s=this.ownerDocument.createElement("li");s.textContent=n,i.append(s)}this.popup.replaceChildren(t,i),this.setPrecise(this.precise)}setPrecise(e){this.build();const t=this.precise;this.precise=e,this.numberInput.hidden=!e,this.querySelector(".duration-unit").hidden=!e,this.textInput.hidden=e,this.helpButton.hidden=e,this.modeButton.textContent=e?this.wording.durationPrecise:this.wording.durationIso,this.modeButton.setAttribute("aria-pressed",String(!e)),!e&&t&&this.textInput.value===""&&this.numberInput.value!==""&&(this.textInput.value=Nn.format(Number(this.numberInput.value))),this.showDeduction(),this.showChosen()}set(e,t){this.build(),this.numberInput.value=e===void 0?"":String(e),this.textInput.value=t??"",this.setPrecise(t===void 0)}readText(){const e=this.textInput.value.trim();if(this.showDeduction(),e===""){this.numberInput.value="",this.showChosen(),this.tell(void 0,void 0);return}const t=Nn.parse(e);t&&(this.numberInput.value=String(t.chosenSeconds),this.showChosen(),this.tell(t.chosenSeconds,Nn.isExact(e)?void 0:e))}tell(e,t){this.dispatchEvent(new CustomEvent("durationchange",{detail:{seconds:e,text:t},bubbles:!0,composed:!0}))}describe(e){const t=this.wording,i=e.minSeconds===e.maxSeconds?Nn.say(e.minSeconds):`${Nn.say(e.minSeconds)} – ${Nn.say(e.maxSeconds)}`,n=e.doubt==="~"?t.timeQualifierApproximate:e.doubt==="?"?t.timeQualifierUncertain:e.doubt==="%"?t.timeQualifierBoth:"";return n?`${i} — ${n.toLowerCase()}`:i}showDeduction(){const e=this.textInput.value.trim();if(this.precise||e===""){this.textInput.title="";return}const t=Nn.parse(e);this.textInput.title=t?`→ ${this.describe(t)}`:this.wording.durationInvalid}showChosen(){const e=this.precise?void 0:Nn.parse(this.textInput.value),t=e!==void 0&&!Nn.isExact(this.textInput.value);this.chosen.hidden=!t,this.chosen.textContent=t?this.wording.durationChosen.replace("{value}",Nn.say(e.chosenSeconds)):""}}function v6(){customElements.get(Mp)||customElements.define(Mp,g6)}class Zd{static at(e,t){if(e.year===void 0||t.year===void 0)return;let i=t.year-e.year;const n=(s,r)=>s!==void 0&&r!==void 0;return n(e.month,t.month)&&(t.month<e.month||t.month===e.month&&n(e.day,t.day)&&t.day<e.day)&&i--,i>=0?i:void 0}static birthFor(e,t){if(t.year===void 0)return;const i=t.year-e;return{year:i,raw:`${String(i).padStart(4,"0")}~`}}static isFirm(e){return!/[?~%]/.test(e.raw??"")}}class wp{static easter(e){const t=e%19,i=Math.floor(e/100),n=e%100,s=Math.floor(i/4),r=i%4,a=Math.floor((i+8)/25),l=Math.floor((i-a+1)/3),c=(19*t+i-s-l+15)%30,h=Math.floor(n/4),d=n%4,u=(32+2*r+2*h-c-d)%7,p=Math.floor((t+11*c+22*u)/451),f=Math.floor((c+u-7*p+114)/31),g=(c+u-7*p+114)%31+1;return new Date(Date.UTC(e,f-1,g,12))}static lunation(e){if(e<1583)return;const t=wp.easter(e),i=uu(0,t,40);if(!i)return;const n=uu(180,i.date,20),s=uu(0,new Date(i.date.getTime()+864e5),40);if(!(!n||!s))return{begin:i.date,full:n.date,end:s.date}}static isIn(e){const t=wp.lunation(e.getUTCFullYear());return t!==void 0&&e>=t.begin&&e<t.end}}const y6=[{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."}],b6=23493,eM=[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 Us{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 Us.EARTH_RADIUS_KM*(1/Math.cos(t)-1)}static isLitOverhead(e,t){return e>Us.shadowHeightKm(t)}static classesAt(e){const t=e.getTime();return y6.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()-b6;if(!(t<0))return eM[Math.min(t,eM.length-1)]}static visibilityAt(e,t){const i=Ji("Sun",e,t).altitudeDeg;return{sunAltitudeDeg:i,shadowHeightKm:Us.shadowHeightKm(i),lowOrbitLit:Us.isLitOverhead(Us.LOW_ORBIT_KM,i),classes:Us.classesAt(e),trackedObjects:Us.trackedInOrbitAt(e),anythingInOrbit:e.getTime()>=Date.parse(`${Us.FIRST_ORBIT}T00:00:00Z`)}}}const tM="https://ufoathome.org/reentries/index.json";class jn{static MINUTE_SLACK_MS=60*6e4;static WINDOW_SLACK_MS=60*6e4;static VISIBLE_KM=1500;static VISIBLE_DEG=jn.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??jn.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(tM)||e.push(tM),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 a of[e-jn.DAY_MS,t+jn.DAY_MS])s.add(String(new Date(a).getUTCFullYear()));const r=(await Promise.all([...s].filter(a=>n.index.years.includes(a)).map(a=>this.yearOf(a,n.base)))).flat();return jn.match(r,e,t,i)}static DAY_MS=864e5;static match(e,t,i,n){const s=[];for(const a of e){if(a.inclinationDeg!==void 0&&Math.abs(n.lat)>a.inclinationDeg+jn.VISIBLE_DEG)continue;const l=Date.parse(a.precision==="day"?`${a.time}T00:00Z`:a.time);if(Number.isFinite(l))if(a.precision==="minute"){const c=l<t?t-l:l>i?l-i:0;if(c>jn.MINUTE_SLACK_MS)continue;let h;if(a.seenLat!==void 0&&a.seenLng!==void 0&&(h=jn.distanceKm(n.lat,n.lng,a.seenLat,a.seenLng),h>jn.VISIBLE_KM))continue;s.push({record:a,timeMs:l,offsetMinutes:Math.round(c/6e4),seenKm:h})}else{const c=a.precision==="day"?jn.DAY_MS/2:(a.uncertaintyHours??0)*36e5,h=a.precision==="day"?l+c:l,d=jn.WINDOW_SLACK_MS;if(h+c+d<t||h-c-d>i)continue;s.push({record:a,timeMs:h})}}const r={minute:0,hours:1,day:2};return s.sort((a,l)=>r[a.record.precision]-r[l.record.precision]||(a.record.uncertaintyHours??0)-(l.record.uncertaintyHours??0)||a.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 jn.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 M6="https://ufoathome.org/light-pollution/index.json";class co{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??co.defaultIndexUrls()}static defaultIndexUrls(){const e=typeof location>"u"?void 0:new URL("/light-pollution/index.json",location.href).href;return[...new Set([e,M6].filter(t=>t!==void 0))]}static magPerArcsec2Of(e){return-2.5*Math.log10((e+co.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 a=((t+180)%360+360)%360-180,l=Math.floor((n.north-e)/n.tileDeg),c=Math.floor((a+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,p=co.nameOf(d-n.tileDeg,u),f=await this.tile(`${s}${p}.bin`);if(!f)return{status:"failed"};const g=n.tileDeg/n.cells,m=Math.min(n.cells-1,Math.floor((d-e)/g)),v=Math.min(n.cells-1,Math.floor((a-u)/g)),b=co.mcdOf(f[m*n.cells+v],n);return b===0?{status:"natural"}:{status:"found",lightPollution:Math.round(co.magPerArcsec2Of(b)*100)/100,artificialMcdPerM2:b,lat:d-(m+.5)*g,lng:u+(v+.5)*g}}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 iM=[{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 co}];class Ct{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 wt;dust=new yi;assess(e,t,i){const n=Ji("Sun",e,t),s=Ji("Moon",e,t),r={altitudeDeg:s.altitudeDeg,phaseAngleDeg:ce.phaseAngleOf(oo(e).illuminatedFraction)},a=cs.galactic(e,t),l=Ct.unit(a.centre),c=Ct.unit(a.rotation),h=Ct.unit(a.pole),d=Ct.unit(cs.eclipticPole(e,t)),u=Ct.unit(n),p=Ct.unit(s),f=Ct.normalize(Ct.reject(u,d));let g,m,v=0;const b=(M,y)=>{const x=Ct.unit({altitudeDeg:M,azimuthDeg:y}),S=Ct.between(x,u),A=ce.magPerArcsec2({altitudeDeg:n.altitudeDeg,separationDeg:S},{...r,separationDeg:Ct.between(x,p)},M,i);A>v&&(v=A);const w=jr.fromMagPerArcsec2(A),T=10**(-.4*ce.EXTINCTION_PER_AIR_MASS*(ce.airMass(M)-1)),I=this.galaxy.surfaceBrightnessS10(Math.atan2(Ct.dot(x,c),Ct.dot(x,l))*180/Math.PI,Math.asin(Math.max(-1,Math.min(1,Ct.dot(x,h))))*180/Math.PI)*T;g=Ct.better(g,I,w,A,M,y,S);const R=Math.max(-1,Math.min(1,Ct.dot(x,d))),O=Ct.normalize(Ct.reject(x,d)),L=this.dust.surfaceBrightnessS10(Ct.between(O,f),Math.asin(R)*180/Math.PI)*T;m=Ct.better(m,L,w,A,M,y,S)};for(let M=Ct.LOWEST_DEG;M<=90;M+=Ct.COARSE_STEP_DEG)for(let y=0;y<360;y+=Ct.COARSE_STEP_DEG)b(M,y);for(const M of[g,m]){if(!M)continue;const y=Ct.FINE_SPAN_DEG,x=Ct.FINE_STEP_DEG;for(let S=M.altitudeDeg-y;S<=M.altitudeDeg+y;S+=x)if(!(S<Ct.LOWEST_DEG||S>90))for(let A=M.azimuthDeg-y;A<=M.azimuthDeg+y;A+=x)b(S,(A+360)%360)}return{milkyWay:g&&g.contrast>=Ct.THRESHOLD_CONTRAST?g:void 0,zodiacal:m&&m.contrast>=Ct.THRESHOLD_CONTRAST?m:void 0,darkestSkyMagPerArcsec2:v}}static better(e,t,i,n,s,r,a){const l=t/i;return e&&e.contrast>=l?e:{contrast:l,altitudeDeg:s,azimuthDeg:r,magPerArcsec2:jr.toMagPerArcsec2(t),skyMagPerArcsec2:n,sunSeparationDeg:a}}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,Ct.dot(e,t))))*180/Math.PI}static reject(e,t){const i=Ct.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]}}class wi{static MIN_NAME_LENGTH=3;static EMAIL=/[\p{L}\d._%+-]+@[\p{L}\d-]+(?:\.[\p{L}\d-]+)+/u;static PHONE=/(?:\+\d{1,3}[ .-]?|\b0)\d(?:[ .-]?\d{2}){4}\b|\+\d[\d ().-]{8,}\d/;static ADDRESS=new RegExp("\\b\\d{1,4}\\s?(?:bis|ter)?,?\\s+(?:rue|avenue|av\\.|boulevard|bd|chemin|impasse|allée|route|place|street|st\\.|road|rd|lane|drive|via|calle|piazza)\\b","iu");static inspect(e,t){const i=new Set((t?wi.all(t):[]).map(n=>`${n.kind}:${n.found}`));return wi.all(e).filter(n=>!i.has(`${n.kind}:${n.found}`))}static initialsOf(e){return e.trim().split("-").map(t=>{const i=[...t.trim()][0];return i===void 0?"":`${i.toLocaleUpperCase()}.`}).filter(t=>t!=="").join("-")}static withInitials(e,t,i=!1){let n=e;for(const s of wi.usable(t)){const r=wi.initialsOf(s);n=n.replace(new RegExp(wi.escape(s),"giu"),i?r.replace(/[.-]/g,""):r)}return n}static namesOf(e){const t=e.observer,i=[t?.lastName,...t?.firstNames??[]];return wi.usable(i.filter(n=>typeof n=="string"))}static isInitials(e){const t=e.replace(/[^\p{L}]/gu,"");return t.length>0&&t.length<=3&&t===t.toLocaleUpperCase()}static usable(e){return e.map(t=>(t??"").trim()).filter(t=>t.length>=wi.MIN_NAME_LENGTH&&!wi.isInitials(t))}static all(e){const t=[],i=e.observer,n=wi.usable([i?.lastName]),s=wi.usable(i?.firstNames??[]);for(const a of n)t.push({kind:"lastName",found:a});for(const a of s)t.push({kind:"firstNames",found:a});const r=[...n,...s];for(const a of[e.id,i?.id])for(const l of r)a&&a.toLocaleLowerCase().includes(l.toLocaleLowerCase())&&t.push({kind:"nameInId",found:`${a}`});for(const a of wi.texts(e)){for(const d of r)new RegExp(`(?<![\\p{L}])${wi.escape(d)}(?![\\p{L}])`,"iu").test(a)&&t.push({kind:"nameInText",found:d});const l=wi.ADDRESS.exec(a)?.[0];l&&t.push({kind:"address",found:l});const c=wi.EMAIL.exec(a)?.[0];c&&t.push({kind:"email",found:c});const h=wi.PHONE.exec(a)?.[0];h&&t.push({kind:"phone",found:h})}return wi.unique(t)}static texts(e){const t=n=>typeof n=="string"?[n]:typeof n=="object"&&n!==null?Object.values(n).filter(s=>typeof s=="string"):[],i=(e.place??[]).map(n=>{const s=n;return s.name??s.value?.name});return[...t(e.description),...t(e.summary),...t(e.account?.observerOccupation),...i.flatMap(t)]}static unique(e){const t=new Set;return e.filter(i=>{const n=`${i.kind}:${i.found}`;return t.has(n)?!1:(t.add(n),!0)})}static escape(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}}const w6=.5,jd=40,x6=4e5,ja=Math.PI/180,Tl=180/Math.PI;class Yn{static localDirection(e,t,i,n=new D){const s=Math.tan(t/2*ja);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*ja),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*ja,n=e.altitudeDeg*ja;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)*Tl+360)%360,altitudeDeg:Math.atan2(e.y,t)*Tl}}static rotationOf(e){const t=new ui;return t.rotation.set(e.pitchDeg*ja,-e.headingDeg*ja,-(e.rollDeg??0)*ja,"YXZ"),t.quaternion.clone()}static anglesOf(e){const t=new Ar().setFromQuaternion(e,"YXZ"),i=(-t.y*Tl%360+360)%360,n=-t.z*Tl;return{headingDeg:i,pitchDeg:t.x*Tl,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 a=(Math.sqrt(5)-1)/2;let l=r-a*(r-s),c=s+a*(r-s),h=this.solveAtField(e,t,l),d=this.solveAtField(e,t,c);for(let p=0;p<60&&r-s>1e-4;p++){if(!h||!d)return;h.residualDeg<d.residualDeg?(r=c,c=l,d=h,l=r-a*(r-s),h=this.solveAtField(e,t,l)):(s=l,l=c,h=d,c=s+a*(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 a=this.refine(r,n,s);return{registration:{...this.anglesOf(a),fovDeg:i},residualDeg:this.residualDeg(a,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(),p=h.clone().cross(d).normalize(),f=p.clone().cross(u);return new Je().set(u.x,f.x,p.x,u.y,f.y,p.y,u.z,f.z,p.z)},a=r(e[i],e[n]),c=r(t[i],t[n]).multiply(a.transpose());return new Dn().setFromRotationMatrix(new ct().setFromMatrix3(c))}static refine(e,t,i){const n=e.clone(),s=new D;for(let r=0;r<20;r++){const a=new Je().set(0,0,0,0,0,0,0,0,0),l=a.elements,c=new D;for(let p=0;p<t.length;p++){s.copy(t[p]).applyQuaternion(n);const f=s,g=[[0,f.z,-f.y],[-f.z,0,f.x],[f.y,-f.x,0]],m=[i[p].x-f.x,i[p].y-f.y,i[p].z-f.z];for(let v=0;v<3;v++){for(let b=0;b<3;b++)for(let M=0;M<3;M++)l[b*3+v]+=g[M][v]*g[M][b];c.setComponent(v,c.getComponent(v)+g[0][v]*m[0]+g[1][v]*m[1]+g[2][v]*m[2])}}for(let p=0;p<3;p++)l[p*3+p]+=1e-9;const h=c.applyMatrix3(a.invert()),d=h.length();if(d<1e-12)break;const u=new Dn().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 a=s.angleTo(i[r])*Tl;n+=a*a}return Math.sqrt(n/t.length)}}const nM=6371e3,Zc=Math.PI/180;class Wl{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*Zc)),a=[t-r,e-s,t+r,e+s].map(h=>h.toFixed(6)).join(",");return((await this.fetchJson(`${Wl.API}/search?bbox=${a}&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:a,bearingDeg:l}=Wl.offset(t,i,s,n),c=e.properties,h=c["pers:interior_orientation"]?.field_of_view,d=(c.providers??[]).map(p=>p.name).filter(p=>!!p),u=c.license??"CC-BY-SA-4.0";return{id:e.id,lat:s,lng:n,distanceM:a,bearingDeg:l,azimuthDeg:c["view:azimuth"],panorama:h!==void 0&&h>=360,takenAt:c.datetime??"",src:r,srcFull:e.assets.hd?.href,credit:`${Wl.CREDIT}${d.length?` — ${d.join(", ")}`:""} (${u})`,creditUrl:`${Wl.API.replace(/\/api$/,"")}/#focus=pic&pic=${e.id}`}}static offset(e,t,i,n){const s=(i-e)*Zc*nM,r=(n-t)*Zc*nM*Math.cos((e+i)/2*Zc);return{distanceM:Math.hypot(r,s),bearingDeg:(Math.atan2(r,s)/Zc+360)%360}}}const Jd=36e5,sM=25;class vm{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=cc(e.event)??0,r=this.sampleTimings(e,n,s);let a;try{a=await this.provider.getWeather({points:r.map(l=>this.pointAt(e,l,i))})}catch{return{status:"failed",at:n}}return a?{status:"inferred",at:n,source:a.source,keyframes:a.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()/Jd)*Jd+Jd;for(;s<=n&&i.length<sM;)i.push(new Date(s)),s+=Jd;return t>0&&i[i.length-1].getTime()!==n&&i.length<sM&&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}missingOf(e){const t=e.event.time;return{date:t?.year===void 0||t.month===void 0||t.day===void 0,place:this.originOf(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=ps(i,t.lng,e.event.utcOffsetHours);return n?{origin:t,start:n}:void 0}originOf(e){const t=ot(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=ot(e,t.t);return{lat:n?.lat??i.lat,lng:n?.lng??i.lng,time:t.time}}}const S6=Date.UTC(1940,0,1),rM=36e5,aM=.25,E6=.7,A6=.45,T6=.1,_6=2,I6=.3,D6=.2,R6=8,ym=.125,C6=.05,oM=125,lM=100,cM=2500,bm=3500,Mm=8e3,k6=95,L6=99,O6=[96,99],P6=["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"],N6=5;class z2{fetchImpl;baseUrl;forecastUrl;now;cache=new Map;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.baseUrl=e.baseUrl??"https://archive-api.open-meteo.com/v1/archive",this.forecastUrl=e.forecastUrl??"https://api.open-meteo.com/v1/forecast",this.now=e.now??(()=>new Date)}async getWeather(e){if(e.points.length===0)return;const t=e.points.map(h=>h.time.getTime()),i=Math.min(...t);if(i<S6)return;const n=new Map;for(const h of e.points){const d=this.cellKey(h);n.has(d)||n.set(d,{lat:h.lat,lng:h.lng,index:n.size})}const s=i>=this.now().getTime()-N6*864e5,r=this.requestUrl([...n.values()],new Date(i),new Date(Math.max(...t)),s);let a=this.cache.get(r);if(!a){const h=await this.fetchImpl(r);if(!h.ok)throw new Error(`Open-Meteo HTTP ${h.status}`);const d=await h.json();if(a=Array.isArray(d)?d:[d],a.length<n.size||a.some(u=>u.error||!u.hourly))return;this.cache.set(r,a)}const l=s?{id:"open-meteo-forecast",name:"Open-Meteo (forecast model)",url:r}:{id:"era5",name:"ERA5 (Open-Meteo)",url:r},c=e.points.map(h=>this.sampleAt(a[n.get(this.cellKey(h)).index].hourly,h.time));if(!c.some(h=>h===void 0))return{samples:c,source:l}}cellKey(e){return`${Math.round(e.lat/aM)},${Math.round(e.lng/aM)}`}requestUrl(e,t,i,n){const s=new URLSearchParams({latitude:e.map(r=>r.lat).join(","),longitude:e.map(r=>r.lng).join(","),start_date:this.isoDate(t),end_date:this.isoDate(i),hourly:P6.join(","),wind_speed_unit:"ms",timezone:"UTC"});return`${n?this.forecastUrl:this.baseUrl}?${s}`}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(a=>Date.parse(`${a}Z`)),n=t.getTime();if(i.length===0||n<i[0]-rM||n>i[i.length-1]+rM)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,a)=>r+(a-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(oM*(e.temperatureC-e.dewPointC),lM,cM)),thicknessM:650,coverage:this.clamp(e.cloudCoverLow,0,1),sizeM:1400,density:1},{id:"record-mid",type:"unknown",baseM:bm,thicknessM:800,coverage:this.clamp(e.cloudCoverMid,0,1),sizeM:2500,density:1},{id:"record-high",type:"cirrus",baseM:Mm,thicknessM:400,coverage:this.clamp(e.cloudCoverHigh,0,1),sizeM:2200,density:.35}]}toWeather(e){const t=e.weatherCode>=k6&&e.weatherCode<=L6,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(Xr.relativeHumidity(e.temperatureC,e.dewPointC)*100)/100,precipitationType:i,precipitationIntensity:i==="none"?0:this.clamp(Math.sqrt(e.precipitationMm/R6),0,1),windDirectionDeg:(e.windFromDeg+180)%360,windSpeed:e.windSpeedMs,storm:t}}precipitationTypeFrom(e){return e.snowfallCm>0?"snow":O6.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=(E6*e.cloudCoverLow+A6*e.cloudCoverMid+T6*e.cloudCoverHigh)/i,s=Math.min(1,e.precipitationMm/_6);return this.clamp(n+I6*s+(t?D6:0),0,1)}cloudBaseFrom(e){if(e.cloudCover<C6)return;const t=this.clamp(oM*(e.temperatureC-e.dewPointC),lM,cM);if(e.cloudCoverLow>=ym)return Math.round(t);if(e.cloudCoverMid>=ym)return bm;if(e.cloudCoverHigh>=ym)return Mm;const i=Math.max(e.cloudCoverLow,e.cloudCoverMid,e.cloudCoverHigh);if(!(i<=0))return i===e.cloudCoverLow?Math.round(t):i===e.cloudCoverMid?bm:Mm}clamp(e,t,i){return Math.max(t,Math.min(i,e))}}function F6(){return new z2}const U6=5;class H2{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 a=await this.fetchImpl(s,{signal:i.signal});if(!a.ok)throw new Error(`Nominatim HTTP ${a.status}`);const l=await a.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 a=await r.json(),l=(Array.isArray(a)?a:[]).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??U6)});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 B6(){return new H2}const z6=[{id:"nominatim",name:"Nominatim",credit:"© OpenStreetMap",creditUrl:"https://osm.org/copyright",create:()=>new H2}],sg=[{id:"era5",name:"Open-Meteo",credit:"© Copernicus/ECMWF",creditUrl:"https://open-meteo.com/en/docs/historical-weather-api",create:()=>new z2}],wm=o=>o.id==="open-meteo-forecast"||sg.some(e=>e.id===o.id);class H6{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 iw(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const xm=[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>sw()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new tw}],hM=[{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 nw},{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 H6}];class vh{constructor(e,t){this.root=e,this.messages=t}static STYLE=`
9971
10034
  .model-picker-button { display: inline-flex; align-items: center; gap: .5em; cursor: pointer; max-width: 100%; }
9972
10035
  .model-picker-button img { width: 2em; height: 1.5em; object-fit: contain; }
9973
10036
  .model-picker-button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -9996,7 +10059,7 @@ rr0-duration-input [hidden] { display: none !important; }
9996
10059
  .model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
9997
10060
  .model-picker .model-name { font-weight: 600; }
9998
10061
  .model-picker .model-credit { font-size: .8em; color: #666; }
9999
- `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await _e(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-B2MXsKrk.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const n=document.createElement("button");n.type="button",n.className="model-picker-button",e.after(n),e.hidden=!0;let s=0,r;const a=()=>{const c=++s,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(g=>g.value).join()]);if(u===r){--s;return}r=u,n.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,n.title=this.messages().choose,n.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(g=>vh.pictureOf(g)).then(g=>{if(!g||c!==s)return;const m=new Image;m.src=g,m.alt="",n.prepend(m)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const l=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};n.addEventListener("click",()=>void this.open(e,t,l)),a()}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=vh.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const a=document.createElement("h2");a.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(a,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),_e(async()=>{const{ModelViewer:S}=await import("./ModelViewer-BltV6g37.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const b=new Map,M=S=>{const A=document.createElement("button");A.type="button",A.className="model-card",A.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const w=document.createElement("div");w.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,A.append(w,T),S.title){const P=document.createElement("span");P.className="model-credit",P.textContent=S.title,A.append(P)}g(S.value).then(P=>vh.pictureOf(P)).then(P=>{if(!P)return;const k=new Image;k.src=P,k.alt="",w.append(k)});let I,R=!1;const O=()=>{R&&!(I&&!I.active)||(R=!0,Promise.all([g(S.value),_e(()=>import("./ModelViewer-BltV6g37.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([P,{ModelViewer:k}])=>{!P||!R||(I=k.show(w,P))}).catch(()=>{}))},L=()=>{R=!1,I?.stop(),I=void 0};return b.set(A,O),A.addEventListener("pointerenter",O),A.addEventListener("focus",O),A.addEventListener("pointerleave",()=>{document.activeElement!==A&&L()}),A.addEventListener("blur",L),A.addEventListener("click",P=>{if(I?.consumeDrag()){P.preventDefault();return}m(S.value)}),A},y=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),y().append(M(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const A=document.createElement("h3");A.textContent=S.label,h.append(A);const w=y();for(const T of Array.from(S.children))w.append(M(T));v=void 0}else S instanceof HTMLOptionElement&&(v??y()).append(M(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const x=r.querySelector('.model-card[aria-pressed="true"]');(x??l).focus(),x&&b.get(x)?.()}addAddressForm(e,t,i,n,s,r,a){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(M,y,x="")=>{const S=document.createElement("label"),A=document.createElement("span");A.textContent=M;const w=document.createElement("input");return w.type=y,w.placeholder=x,S.append(A,w),c.append(S),w},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const b=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const M of[d,u,p,f,g])M.addEventListener("input",b);l.addEventListener("click",()=>{const M=c.hidden;if(c.hidden=!M,l.setAttribute("aria-expanded",String(M)),!M)return;const y=s.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",g.value=y?.source??"",b(),d.focus()}),c.addEventListener("submit",M=>{M.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),a())}),b()}}class ov{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=ov.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 Gk{formatters=new Map;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=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const n=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",s=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(s)return s[1]?(s[1]==="-"?-1:1)*(Number(s[2])+Number(s[3])/60):0}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(n=>this.offsetHoursAt(n,i)===e)}}function Nr(o,e){return o.find(t=>t.id===e)??o[0]}class Vk{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 Wk=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new Vk}],dM=new Set;Cp();ok();const _l={width:48,height:28},Xk=2500,uM=40,$k=10,pM=600,fM=900,Il=2e-4,Yk=900,qk=-1.46,Kk=3,Sm=.2,Zk=.5,jk=3,Jk=.01,Qk=1.6,Em=2e3,eL=250,mM=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),ua=4,jc="ufo-1",gM=["oval","polygon"],tL={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function iL(o){return o.kind==="oval"?"oval":"polygon"}const nL=-6,sL=21;class Nt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=Wk[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new Gk;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;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=Bk();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;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;launchEditor;launchEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new vm(Fk());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;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;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelLaunchesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;addDecorObserverButton;surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=pu[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=ka;currentAppearance={...tL};currentSourceId=jc;selectedSourceIds=new Set([jc]);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 Wl;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.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(mM.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;mM.has(e.key)?this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel())};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${qS}</style>${YS}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const n of this.shadow.querySelectorAll(Nu))n.build();for(const n of this.shadow.querySelectorAll(Mp))n.build();this.sceneElement=document.createElement(yp),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",n=>{this.ufoElement.sighting.observerMap=n.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",n=>{const{lat:s,lng:r}=n.detail;this.latInput.value=String(Number(s.toFixed(6))),this.lngInput.value=String(Number(r.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 rh(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const n of[this.timeStartLabel,this.timeEndLabel])n.addEventListener("click",()=>this.switchTimeDisplay()),n.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Mp),this.durationInput=this.durationElement.input,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.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.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),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.rareIceCrystalsInput,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.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),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.refreshFilterOptions(),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.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),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.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",n=>{n.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),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.labelRareIce=this.shadow.getElementById("label-rare-ice"),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.labelLaunchesSubgroup=this.shadow.getElementById("label-launches-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.decorList=new Im({header:this.shadow.getElementById("decor-list-header"),footer:this.shadow.getElementById("decor-list-footer"),ids:{list:"decor",label:"label-decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:n=>`option-decor-${n}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:n=>this.selectDecor(n),onAdd:n=>this.addDecor(n),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",actions:{"look-at-decor":"Look at it"}}),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new ga(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:n=>this.setPlantedDecor(n),kindName:n=>this.decorList.kindLabel(n),cite:n=>this.citeSource(n),busy:(n,s)=>this.sceneElement.setBusy(n,s),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(n=>({lat:n.pose.lat,lng:n.pose.lng})).filter(n=>typeof n.lat=="number"&&typeof n.lng=="number")},ka,async(n,s)=>this.surroundingsProvider?this.surroundingsProvider.covers(n,s)?this.surroundingsProvider:void 0:(await _e(async()=>{const{SurroundingsSources:r}=await import("./surroundingsSources-CvhFXPJx.js");return{SurroundingsSources:r}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,n,s),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryChoice!==Nt.NO_SCENERY),this.scenerySource.addEventListener("change",()=>{if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryChoice!==Nt.NO_SCENERY),this.sceneryChoice===Nt.NO_SCENERY){this.surroundings.withdraw();return}const n=this.plantingCentre();n&&this.surroundings.survey(n.lat,n.lng)}),this.sceneryRadius.addEventListener("input",()=>{const n=Number(this.sceneryRadius.value);if(!Number.isFinite(n)||n<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const s=this.plantingCentre();this.surroundings.radiusChanged(n,s?.lat,s?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),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.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.modelPicker=new vh(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new Gs(this.decorParametersHost,"en","decorParam.");const t={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new Gs(this.decorBaseHost,"en","decorBase.",t,(n,s)=>this.enhanceDecorModelChoice(n,s)),this.decorStateForm=new Gs(this.decorStateHost,"en","decorState.",t),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",n=>{this.focus({preventScroll:!0}),this.onPointerDown(n)}),this.ufoElement.canvasElement.addEventListener("pointermove",n=>this.onPointerMove(n)),this.ufoElement.canvasElement.addEventListener("contextmenu",n=>this.onContextMenu(n)),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 n=this.ufoElement.sighting;n.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),n.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),n.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.durationElement.addEventListener("durationchange",n=>{const{seconds:s,text:r}=n.detail;this.ufoElement.sighting.event.durationText=r,this.ufoElement.durationSeconds=s,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((s??0)*1e3),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.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const n of this.referenceFields)n.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",n=>this.onReferenceWheel(n),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",n=>this.onBodyWheel(n),{passive:!1}),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 n of[this.milestoneLabelInput,this.milestoneNoteInput])n.addEventListener("input",()=>this.updateMilestone());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(B2,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(U2,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const n of gM)this.presetButtons[n].addEventListener("click",()=>this.setAppearance({presetId:n}));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 n of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])n.addEventListener("input",()=>this.updateObserver());for(const n of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])n.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",n=>{n.key==="Enter"&&(n.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.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const n=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const s=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(r=>[r.t,en.fovOf(this.ufoElement.sighting,r.t)]));this.retuneFieldOfView(n),this.retuneExposure(n),en.reproject(this.ufoElement.sighting,n,s),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const i=n=>this.shadow.querySelector(`${Nu}[name="${n}"]`);this.startDate=i("obs-time"),this.endDate=i("obs-end-time"),this.birthDate=i("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=zo.ALL,this.perceptionSettings.labels=this.messages.observerPerception,this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata()),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.birthDate.messages=this.messages;for(const n of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(n,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",n=>{const{time:s}=n.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=s}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",n=>{this.birth=n.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",n=>{const{time:s}=n.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=s})});for(const n of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])n.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const n of this.weatherFields){if(n===this.iceCrystalAlignmentInput||n===this.rareIceCrystalsInput){n.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}n.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const n of this.soundFields)n.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(n=>this.shadow.getElementById(n.getAttribute("aria-controls")));for(const n of this.groupTabs)n.addEventListener("click",()=>this.toggleGroup(n,!this.isGroupOpen(n)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const n of this.subgroupTabs)n.addEventListener("click",()=>this.openSubgroup(n));gn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new $l(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",n=>this.onParamSummaryClick(n)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(n=>n.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),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=kS(this.shadow.getElementById("cloud-editor"),this.sceneElement,(n=!0)=>{n&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(n,s)=>{this.headingInput.value=String(this.rounded(n)),this.pitchInput.value=String(this.rounded(s)),this.updateObserver()},yh(Is.preferencesFor(this),Sh)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),Is.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}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.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??jc,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.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField();const t=this.plantingCentre();this.surroundings.placeLoaded(t?.lat,t?.lng),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=JSON.stringify(this.sightingData),this.touched=!1,this.savedFileText=this.fileText(),this.fileEditor?.markSaved())}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=wi.inspect(this.sightingData,this.loadedJson());if(e.length===0){this.downloadJson();return}this.askAboutIdentity(e)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(s=>{const r=document.createElement("li");return r.textContent=t[s.kind].replaceAll("{value}",s.found),r}));const n=e.some(s=>["lastName","firstNames","nameInId","nameInText"].includes(s.kind));this.shadow.getElementById("identity-ask-initials").hidden=!n,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=wi.namesOf(this.sightingData);this.observerLastNameInput.value=wi.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>wi.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=wi.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=wi.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=wi.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}downloadJson(){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),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(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);if(Ci.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.resetHistory(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await ho.json(e);if(Ci.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.resetHistory(),this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Ja))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";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=Kh[0].create();get narrativeSourceId(){return Nr(Kh,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:Nt.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof os&&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,a=cr.stated(r);if(a.length>0){const l=this.ufoElement.sighting.provenance,c=Lm(this.ufoElement.sighting);this.sightingData=cr.apply(c,Vu.loadable(r),a),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.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:Nt.valueAt(Lm(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[rL[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 a=document.createElement(t==="stated"?"q":"span");a.textContent=n.rationale,s.append(r,a),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=Nr(Kh,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(),a=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",a!==void 0),s.title=a?this.said.read(a)??"":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 a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),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 os))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(Nt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Nt.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"?Nt.NARRATIVE_KEY_STORAGE:e==="workspace"?Nt.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",zk,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",sg,e=>{this.weatherInference=new vm(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",iM,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",Kh,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,xm,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,hM,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,ng,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,pu,()=>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 a=()=>{const l=Nr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return a(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),a(),i(Nr(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:Nr(xm,this.chosenSourceId.get("elevation")).create(),imagery:Nr(hM,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(Nr(ng,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=Nr(pu,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),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)<Il&&Math.abs(t-this.namedCoordinates.lng)<Il||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),fM))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0||this.timeZoneIsStated())return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Il&&Math.abs(t-i.lng)<Il||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),fM))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t);this.placeZone=i??void 0,!(!i||this.timeZoneIsStated())&&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,a=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,this.surroundings.placeChanged(e,t);const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Ut.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=fi.byId(c.getLatestPoseAt(h-1)?.filter),b=m===fi.NONE.id||m===""?v===fi.NONE?void 0:fi.NONE.id:m,M=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=M===u.exposureSeconds?void 0:M;const y=this.numberOrUndefined(this.focusDistanceInput.value),x=Math.abs(f-Ut.fieldOfViewDeg(u))>.01||g!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&a===0&&!x?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:y,filter:b}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!Zd.isFirm(t))return;const n=Zd.at(t,i);n!==void 0&&(this.observerAgeInput.value=String(n),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&Zd.at(i,e)===t)return;const n=Zd.birthFor(t,e);n&&(this.birthDate.setPrecise(!1),this.birth=n,this.birthDate.time=n,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&cc({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}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.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.preferredZoneFor(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference());if(t.length===0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const n=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return n&&t.includes(n)?n:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}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),observerBirth:this.birth,observerPerception:zo.compact(this.perceptionSettings.values),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??{},a=t===""?r:{...r,url:t},l=Object.keys(a).length>0?[a,...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={...Fi(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={...Fi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.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>xk?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(),a={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)||jd))},l=s.registration,c=a.headingDeg!==l.headingDeg||a.pitchDeg!==l.pitchDeg||a.rollDeg!==l.rollDeg||a.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:a,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=ot(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=ot(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=ot(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:wk,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:jd},from:this.observerPositionNow(),...i};n.references=[...n.references,a],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&&Yn.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(Yn.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 a=this.canvasPointOfDirection(Yn.worldDirection(s.scene));if(a&&Math.hypot(a.x-e.x,a.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(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:Yn.aimOf(r)};const l=Yn.picturePointOf(r,n.registration,s);return l?{...a,picture:l}:a})),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)||jd,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 a=Yn.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:Yn.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=Yn.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 Yn.worldDirectionOf(e.picture,t.registration,i).angleTo(Yn.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 a=document.createElement("option");a.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(a)}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(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(a=>a.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const a=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+a}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(a=>this.canvasPointOfDirection(Yn.worldDirectionOf(a,n,i))),r=this.currentLandmarks().map((a,l)=>({picture:this.canvasPointOfDirection(Yn.worldDirectionOf(a.picture,n,i)),scene:this.canvasPointOfDirection(Yn.worldDirection(a.scene)),label:this.landmarkLabel(a,l),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(Yn.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(a=>a!==void 0)?s:void 0,r.filter(a=>a.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 a=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:a,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=ot(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,a]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(a,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:jd}})}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 _e(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.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),a=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,...a],this.currentTraceId=a[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(a.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 fx){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(),Xk)}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=pg(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 vm(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!wm(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),pM))}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(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!wm(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&wm(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}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=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}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&&ps(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.pendingWeatherEdit=void 0,this.closeFileAsk(),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=iM[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(),pM)}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 a=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.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(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=cc(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}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=hS(this.ufoElement.sighting.event);this.durationElement.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"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(ln.opensPrecise(e.time)),this.endDate.setPrecise(ln.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}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)>Kk;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),Yk))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Il&&Math.abs(e.lng-i)<Il}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=Nr(xm,this.chosenSourceId.get("elevation")),s=await new ov(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(ot(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.birthDate.setPrecise(ln.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,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=Fi(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??gu)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??wM)),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=yv(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(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await _e(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-C0NC8jbz.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const n=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(n!==void 0){this.fileFocus="shape",this.selectUnit(n.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(n=>n.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,n]of t.entries()){const s=n.shapes.findIndex(r=>r.sourceId===e);if(s>=0)return["timeline","keyframes",i,"shapes",s]}}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i)||JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,s=!t&&this.fileTextApplied!==void 0&&JSON.stringify(i.weatherTrack)!==JSON.stringify(Nt.weatherOf(this.fileTextApplied)),r={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,s&&!this.restoringWeather&&this.weatherFromRecords){const a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):sg.some(l=>l.id===a.id)&&this.askAboutWeather(r,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch{this.showFileNote(this.messages.importErrorMalformed),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}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)),a=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)a.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration)}seekTo(e){this.goToMark(e*1e3)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}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-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-launches")?.hidden===!1?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"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:e==="decor"?this.paintDecorOverlay: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 i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.syncLaunchesTab(),this.shadow.getElementById("account-view-row").hidden=this.isReading}syncLaunchesTab(){const e=this.subgroupTabs.find(t=>t.getAttribute("aria-controls")==="shape-launches");e&&(e.hidden=!1,this.launchEditor&&this.shadow.getElementById("shape-launches")?.hidden===!1&&this.launchEditor.refresh())}chooseAccountView(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}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()),e.getAttribute("aria-controls")==="shape-launches"&&this.loadLaunchEditor().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,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Nt.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 a=document.createElement("span");a.className="param-nest-label",a.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Nt.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(a),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),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),XM.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return e==="phenomenon"?this.panelIndex("shape"):Nt.SUMMARY_GROUPS.indexOf(e)}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 XS(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(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=Nt.QUESTION_FIELDS[s];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const l=this.shadow.getElementById(a);l&&!l.hidden&&l.value===""&&t.add(a)}}for(const[s,r]of Object.entries(Nt.QUESTION_FIELDS))for(const a of Nt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(a);if(!l)continue;const c=t.has(a)&&!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(Nt.QUESTION_FIELDS))for(const a of r.fields){const l=this.shadow.getElementById(a);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),a=i.get(r)??0,l=r===n,c=Nt.badgeOn(s);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!l),s.title=a===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a))}}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;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();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("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const a=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorList.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.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),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()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.querySelector("#shape-shapes .toolbar");if(t)for(const i of Array.from(t.children))i.id!=="add-shape"&&(i.hidden=e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();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:iL(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,mt.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,mt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(mt.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(mt.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),a=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-a)/2,width:r,height:a},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}))}refreshFilterOptions(){const e={[fi.NONE.id]:this.messages.filterNone,[fi.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[fi.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=s=>e[s.id]??s.name,i=[...this.filterSelect.options].map(s=>s.textContent);if(i.length!==fi.ALL.length||fi.ALL.some((s,r)=>i[r]!==t(s))){const s=this.filterSelect.value||fi.NONE.id;this.filterSelect.replaceChildren();for(const r of fi.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=s}const n=this.ufoElement?.sighting?.instrument;for(const s of this.filterSelect.options){const r=!n||fi.usableWith(fi.byId(s.value),n);s.disabled=!r,s.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,n={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},s=r=>{const a=this.naming.instrument(r),l=Ut.unavailability(r,t);if(!l)return{id:r.id,label:a};const c=(l.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(l.from)).replace("{to}",String(l.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=Ut.CATEGORIES.map(r=>({label:n[r],children:Jc.filter(a=>a.category===r).map(s)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Nt.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=ot(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Ut.fieldOfViewDeg(t),r=n?Ut.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),gn.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 a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),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?"":Nt.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),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=fi.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Ut.fieldOfViewDeg(e),n=Ut.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>Jk||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 ot(e,this.ufoElement.currentTime)?.fovDeg??Ut.fieldOfViewDeg(e.instrument)}currentProjection(){return $s.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=mt.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=ot(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?Ut.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,a=n?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Cm*e/l*i.heightMm,h=r*r/(a*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),a=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))+a+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=(g,m)=>Number(g.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)??$k,a=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=a!==void 0&&a<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(mt.sizeMAt(c,h),2),lengthM:n(mt.sizeMAt(c,h),2),heightM:n(mt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=_e(async()=>{const{BodyEditor:e}=await import("./BodyEditor-ChwDW_Ws.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),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,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().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,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=_e(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-BCbplrLt.js");return{LaunchEditor:e}},__vite__mapDeps([10,11]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.launchEditor)),this.launchEditorLoading}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:mt.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=$s.of(i.instrument,mt.CANVAS_HEIGHT_PX,en.fovOf(i,e)),s=this.ufoElement.seekableDuration;s>i.timeline.duration&&i.timeline.setSpan(s),i.timeline.addKeyframe(e,t.map(r=>{const a=en.aimOf(i,e,r.shape.bounds),l=n.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:l}:{...h,angular:l}}}))}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.ufoElement.sighting.timeline.sourceIds.length>0&&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(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??jc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}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.decorList.kindLabel(e.kind)} ${n}`}addDecor(e=this.decorList.pickedKind??"building"){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:hc}:{},windows:BM(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}readSceneryChoice(){try{return localStorage.getItem(Nt.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(Nt.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(Nt.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(Nt.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const{SURROUNDINGS_SOURCES:e,SurroundingsSources:t}=await _e(async()=>{const{SURROUNDINGS_SOURCES:s,SurroundingsSources:r}=await import("./surroundingsSources-CvhFXPJx.js");return{SURROUNDINGS_SOURCES:s,SurroundingsSources:r}},[],import.meta.url);if(!this.isConnected)return;const i=document.createElement("option");i.value=Nt.NO_SCENERY,i.id="option-scenery-none",i.textContent=this.messages.surveySourceNone;const n=e.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=s.name,r.title=s.credit,r});this.scenerySource.replaceChildren(i,...n),this.scenerySource.value=this.sceneryChoice===Nt.NO_SCENERY?Nt.NO_SCENERY:t.byId(this.sceneryChoice)?.id??t.DEFAULT_ID}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?Bu.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*Em,t=Math.round(e/eL*1e3);return{lights:Ah.byId("airliner")?.create(),track:[{t:0,eastM:-Em,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Em,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Eh(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(n=>{this.drawnEntryAsked!==i||!n||(this.drawnEntry=n,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?zu[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(n=>{const s=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);n.model={url:i.url,credit:s!==void 0&&r!==void 0?{title:s,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,n]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),s=this.ufoElement.sighting.decor.find(l=>l.id===e.id);if(!s||s.model?.id!==t||!n?.sizeM)return;const r=s.sizeM!==void 0&&i?.sizeM!==void 0&&s.sizeM.widthM===i.sizeM.widthM&&s.sizeM.lengthM===i.sizeM.lengthM&&s.sizeM.heightM===i.sizeM.heightM;if(s.sizeM&&!r)return;const a={...s.sizeM,...Object.fromEntries(Object.entries(n.sizeM).filter(([,l])=>l!==void 0).map(([l,c])=>[l,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=Po([...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&&(t.milestones=t.milestones.filter(n=>n.t!==i.t),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=Po(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)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning()}syncDecorFields(){this.syncDecorVisibility()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1;return}if(this.decorBaseShown){this.decorBaseForm.sync(),this.decorStateForm.sync();return}this.decorBaseShown=!0;const t=()=>new Pa(()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return i?Gr.viewOf(i,this.ufoElement.currentTime):void 0},(i,n)=>this.commitDecorBase(i,n.key),()=>this.decorBaseContext());this.decorBaseForm.show(On.BASE,t(),()=>{}),this.decorStateForm.show(On.STATE,t(),()=>{})}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Lo.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:Ue.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Lo.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:On.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:zu[e.kind]?.id}}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!i||(t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,s=Gr.viewOf(i,n);e(s);const r=this.ufoElement.sighting;r.decor=r.decor.map(l=>l.id===i.id?Gr.apply(l,s,t,n):l),t==="model.id"&&this.adoptCatalogueSize(i,s.model?.id);const a=r.decor.find(l=>l.id===i.id);t==="title"&&this.decorList.rename(a.id,this.decorLabel(a)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?$t.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const n=e.id,s=new Pa(()=>this.ufoElement.sighting.decor.find(r=>r.id===n),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(l=>{if(l.id!==n)return l;const c=structuredClone(l);return r(c),c})});this.decorParameterForm.show(t,s,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}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 jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new gp;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new zn(["en"]);tagNames=new km({});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?ps(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,Fi(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},a=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(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}",a.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return an.gainFor(e.instrument,{fNumber:ot(e,0)?.fNumber,fieldOfViewDeg:en.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ji("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=Da(i,n,s),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<qk)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",a(Math.abs(n))).replace("{eye}",a(Da(i,0,s)));return r<=fh?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(fh))}showerClause(e,t){const i=bi.observedRatePerHour(bi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=ac.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 a=ac.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:ac.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.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=mu.brightestAt(e,t);if(!i||i.magnitude>bc){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=vp.brightestAt(e,t);if(!i||i.magnitude>bc){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=Ri.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ji("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ji("Moon",e,t);if(i.altitudeDeg<=0||oo(e).illuminatedFraction<.97)return;const n=[],s=_n.distanceKm(e,t),r=_n.relativeToMean(_n.radiusAtKm(s)),a=s<=_n.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=_n.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&n.push(a.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(_n.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),wp.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}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=Us.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=Da(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),a=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}",a);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}",a):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,Nt.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=Us.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const l=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(a.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 a=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}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=Ji("Sun",i.peak.date,t);return n<=Da(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:a,launch:l}=r.peak.object;a!=="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,a)=>a[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=ot(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=ps(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=>Ts.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Ts.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(a=>this.fireballTimelineMs(a,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=Fi(this.ufoElement.sighting,0),n=Ji("Sun",e,t),s=Ji("Moon",e,t),r=it.deckLitUntilDeg(it.DECK_HEIGHT_M),a=n.altitudeDeg>-r,l=a?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(it.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(it.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??gu;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=Fi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ji("Sun",e,t),s=Ji("Moon",e,t),r=n.altitudeDeg>0,a=r?n:s;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(Sn.strength(i.precipitationIntensity,l,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Sn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(Sn.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(oo(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ji("Sun",e,t);if(i.altitudeDeg>nL)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 p=n.zodiacal.sunSeparationDeg<=Ct.CONE_SEPARATION_DEG;s.push((p?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),a=Ji("Moon",e,t),l=n.darkestSkyMagPerArcsec2<sL,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-a.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(oo(e).illuminatedFraction),a.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&a.altitudeDeg>0&&!d){const p=Math.round(oo(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.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=Ji("Sun",e,t),n=Ji("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(oo(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new Ct;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<mu.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=mu.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=vp.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}=Xs(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(n-Qk,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}updatePresetButtons(){for(const e of gM)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return yv(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-_l.width/2,y:e.height/2-_l.height/2,width:_l.width,height:_l.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 lk(this.ufoElement.sighting.timeline,new ck(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=Is.preferencesFor(this);this.preferences=t;const i=yh(t,Sh),n=this.narrativeProvider.localize?.(i),[s,r,a]=i==="en"?[ka,{},void 0]:await Promise.all([NM(i),AS(i),FM(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new gp(a),this.said=new zn(t),this.tagNames=new km(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new $l(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),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===jc&&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.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,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.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,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.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,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.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,actions:{"look-at-decor":e.lookAtDecor}}),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.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const t=this.shadow.getElementById("option-scenery-none");t&&(t.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),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.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),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.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new $l(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),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.labelRareIce.textContent=e.rareIceCrystals,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.labelFilter.textContent=e.filter,this.refreshFilterOptions(),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;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const n=this.decorMoveAxis(e);if(i==="decor"&&n&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,n))return;const s=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",l=i==="shape";if(l)if(this.selectedSourceIds.size>1){const d=new qp(this.selectedMembers()),u=kt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=s.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?kt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&kt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,dM);if(!c){const d=n==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!l)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:s.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}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.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}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,a)=>s.indexOf(r)-s.indexOf(a)).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,a=s?.kind==="polygon"&&kt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,dM);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.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(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),a=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||a,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:a?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?kt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=WM;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="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const n=document.createElement("span");n.className="submenu-empty",n.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(n)}for(const n of t){const s=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(n)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,n,r.checked)),s.appendChild(r),s.appendChild(document.createTextNode(this.shapeLabel(n))),this.contextMasksSubmenu.appendChild(s)}for(const n of i){const s=this.sceneElement.bodyMaskedBy(n.id,e.id);if(s===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(n.title)??n.id,l=this.messages;r.textContent=`${a} — ${s>=.995?l.masksBodyFully:s>.005?l.masksBodyPartly.replace("{share}",String(Math.round(s*100))):l.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}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(a=>a!==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=kt.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=kt.hitTestVertex(i,e);if(n===void 0)return;const s=kt.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;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(uM,(e.maxX-e.minX)/2*t.width),n=Math.max(uM,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=kt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:a}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="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));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Sm};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:Zk};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=Ue.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Gr.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}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)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const n=this.pickDecorAt(e);if(n===i.id)return!0;const s=this.decorCanvasBounds();return s!==void 0&&t.x>=s.x&&t.x<=s.x+s.width&&t.y>=s.y&&t.y<=s.y+s.height?n===void 0||this.ufoElement.sighting.decor.find(a=>a.id===n)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const n=this.editableDecor();if(!n)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(!this.grabsDecor(e,t,n))return!1;const s=this.ndcOf(e),r=Gr.viewOf(n,this.ufoElement.currentTime),a=s?this.sceneElement.decorGrabHeightAt?.(n.id,s.x,s.y)??0:0,l=s&&this.sceneElement.decorGroundPointAt(n.id,s.x,s.y,a);return!s||!l?!1:(this.dragState={kind:"decor-move",id:n.id,startGround:l,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:s.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(n.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const n=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!n&&t.axis!=="up"||this.commitDecorBase(s=>{n&&(t.axis==="ground"||t.axis==="east")&&(s.eastM=this.roundedMeters(t.startEastM+n.x-t.startGround.x)),n&&(t.axis==="ground"||t.axis==="north")&&(s.northM=this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),t.axis==="up"&&(s.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const n=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:n?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:n?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:n},n||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Fa(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Fa(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==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(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,a=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+a}}}));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,a=kt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}else{const{kind:n,sourceId:s,original:r,handle:a}=this.dragState,l=n==="resize"?kt.resizeShape(r,a,t):kt.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)<jk)return;this.cameraDragState.moved=!0}const a=n+(t.x-i.x)*Sm,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Sm));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(a,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),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(Ta,i.width-ua);break;case"ArrowRight":i.width+=ua;break;case"ArrowUp":i.height=Math.max(Ta,i.height-ua);break;case"ArrowDown":i.height+=ua;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=ua;break;case"ArrowRight":i.x+=ua;break;case"ArrowUp":i.y-=ua;break;case"ArrowDown":i.y+=ua;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 qp(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&&kt.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}if(i==="decor"&&r&&this.decorMoveAxis(e)){const l=this.decorCanvasBounds(),c=l&&kt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const l=kt.hitTestHandle({bounds:new qp(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"&&kt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&kt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${kt.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(MM(this.buildPrototype({x:0,y:0,width:_l.width,height:_l.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 rL={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},vM="rr0-sighting-editor",yM="rr0-ufo-recorder";class aL extends Nt{}function G2(){kM(),fk(),uk(),vk(),Cp(),customElements.get(vM)||customElements.define(vM,Nt),customElements.get(yM)||customElements.define(yM,aL)}const rg={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load JSON file",importUrl:"Or load from URL",importButton:"Load",fileNotACase:"That file is not a case (it has no events).",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},oL=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:rg},Symbol.toStringTag,{value:"Module"})),bM="rr0-case-editor",lL=`
10062
+ `;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await _e(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-B2MXsKrk.js");return{ModelThumbnails:i}},__vite__mapDeps([3,4]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const n=document.createElement("button");n.type="button",n.className="model-picker-button",e.after(n),e.hidden=!0;let s=0,r;const a=()=>{const c=++s,h=e.selectedOptions[0],d=e.value===""?i?.current():void 0,u=JSON.stringify([e.value,h?.textContent,d?.url,d?.title,this.messages().choose,[...e.options].map(g=>g.value).join()]);if(u===r){--s;return}r=u,n.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,n.title=this.messages().choose,n.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(g=>vh.pictureOf(g)).then(g=>{if(!g||c!==s)return;const m=new Image;m.src=g,m.alt="",n.prepend(m)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const l=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};n.addEventListener("click",()=>void this.open(e,t,l)),a()}ensureStyle(){const e=this.root instanceof ShadowRoot?this.root:this.root.getRootNode(),t=e instanceof ShadowRoot?e:document.head;if(t.querySelector("style[data-model-picker]"))return;const i=document.createElement("style");i.dataset.modelPicker="",i.textContent=vh.STYLE,t.append(i)}open(e,t,i){const n=this.messages(),s=document.createElement("div");s.className="model-picker-backdrop";const r=document.createElement("div");r.className="model-picker",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");const a=document.createElement("h2");a.textContent=n.title;const l=document.createElement("button");l.type="button",l.className="model-picker-close",l.setAttribute("aria-label",n.close),l.title=n.close,l.textContent="✕";const c=document.createElement("header");c.append(a,l);const h=document.createElement("div");h.className="model-picker-body",r.append(c,h),s.append(r);const d=()=>{s.remove(),document.removeEventListener("keydown",u,!0),_e(async()=>{const{ModelViewer:S}=await import("./ModelViewer-BltV6g37.js");return{ModelViewer:S}},__vite__mapDeps([5,4]),import.meta.url).then(({ModelViewer:S})=>S.end())},u=S=>{S.key==="Escape"&&(S.stopPropagation(),d())},p=i?.current(),f="\0address",g=S=>S===f&&p?Promise.resolve({url:p.url}):t(S),m=S=>{d(),!(S===f||S===e.value)&&(e.value=S,e.dispatchEvent(new Event("change",{bubbles:!0})))};let v;const b=new Map,M=S=>{const A=document.createElement("button");A.type="button",A.className="model-card",A.setAttribute("aria-pressed",String(S.value===f||S.value===e.value&&!p));const w=document.createElement("div");w.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=S.textContent,A.append(w,T),S.title){const P=document.createElement("span");P.className="model-credit",P.textContent=S.title,A.append(P)}g(S.value).then(P=>vh.pictureOf(P)).then(P=>{if(!P)return;const k=new Image;k.src=P,k.alt="",w.append(k)});let I,R=!1;const O=()=>{R&&!(I&&!I.active)||(R=!0,Promise.all([g(S.value),_e(()=>import("./ModelViewer-BltV6g37.js"),__vite__mapDeps([5,4]),import.meta.url)]).then(([P,{ModelViewer:k}])=>{!P||!R||(I=k.show(w,P))}).catch(()=>{}))},L=()=>{R=!1,I?.stop(),I=void 0};return b.set(A,O),A.addEventListener("pointerenter",O),A.addEventListener("focus",O),A.addEventListener("pointerleave",()=>{document.activeElement!==A&&L()}),A.addEventListener("blur",L),A.addEventListener("click",P=>{if(I?.consumeDrag()){P.preventDefault();return}m(S.value)}),A},y=()=>(v=document.createElement("div"),v.className="model-picker-grid",h.append(v),v);if(p){const S=new Option(p.title||p.url,f);S.title=[p.author,p.license].filter(Boolean).join(" — "),y().append(M(S))}for(const S of Array.from(e.children))if(S instanceof HTMLOptGroupElement){const A=document.createElement("h3");A.textContent=S.label,h.append(A);const w=y();for(const T of Array.from(S.children))w.append(M(T));v=void 0}else S instanceof HTMLOptionElement&&(v??y()).append(M(S));i&&this.addAddressForm(c,l,r,h,i,n,d),l.addEventListener("click",d),s.addEventListener("click",S=>{S.target===s&&d()}),document.addEventListener("keydown",u,!0),this.root.append(s);const x=r.querySelector('.model-card[aria-pressed="true"]');(x??l).focus(),x&&b.get(x)?.()}addAddressForm(e,t,i,n,s,r,a){const l=document.createElement("button");l.type="button",l.className="model-picker-add",l.textContent="+",l.title=r.address,l.setAttribute("aria-label",r.address),l.setAttribute("aria-expanded","false"),e.insertBefore(l,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(M,y,x="")=>{const S=document.createElement("label"),A=document.createElement("span");A.textContent=M;const w=document.createElement("input");return w.type=y,w.placeholder=x,S.append(A,w),c.append(S),w},d=h(r.addressUrl,"url","https://…/model.glb"),u=h(r.addressName,"text"),p=h(r.addressAuthor,"text"),f=h(r.addressLicense,"text","CC0 1.0"),g=h(r.addressSource,"url","https://…"),m=document.createElement("p");m.textContent=r.addressIncomplete;const v=document.createElement("button");v.type="submit",v.className="model-picker-use",v.textContent=r.addressUse,c.append(m,v),i.insertBefore(c,n);const b=()=>{v.disabled=d.value.trim()==="",m.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const M of[d,u,p,f,g])M.addEventListener("input",b);l.addEventListener("click",()=>{const M=c.hidden;if(c.hidden=!M,l.setAttribute("aria-expanded",String(M)),!M)return;const y=s.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",g.value=y?.source??"",b(),d.focus()}),c.addEventListener("submit",M=>{M.preventDefault(),d.value.trim()!==""&&(s.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:g.value.trim()}),a())}),b()}}class ov{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=ov.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 G6{formatters=new Map;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=this.formatters.get(e);if(i===void 0){try{i=new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"longOffset"})}catch{i=null}this.formatters.set(e,i)}if(i===null)return;const n=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",s=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(n);if(s)return s[1]?(s[1]==="-"?-1:1)*(Number(s[2])+Number(s[3])/60):0}zonesAt(e,t){const i=t?.year!==void 0?t:{year:new Date().getFullYear(),month:1,day:1,hour:12};return this.available().filter(n=>this.offsetHoursAt(n,i)===e)}}function Nr(o,e){return o.find(t=>t.id===e)??o[0]}class V6{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 W6=[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new V6}],dM=new Set;Cp();o6();const _l={width:48,height:28},X6=2500,uM=40,$6=10,pM=600,fM=900,Il=2e-4,Y6=900,q6=-1.46,K6=3,Sm=.2,Z6=.5,j6=3,J6=.01,Q6=1.6,Em=2e3,eL=250,mM=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),ua=4,jc="ufo-1",gM=["oval","polygon"],tL={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function iL(o){return o.kind==="oval"?"oval":"polygon"}const nL=-6,sL=21;class Nt extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;presetButtons;presetsGroup;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;utcOffsetInput;timeZoneSelect;timeZoneProvider=W6[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new G6;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;accountViewSelect;durationElement;exportButton;importFileInput;importUrlInput;importUrlButton;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;narrativeRememberInput;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=B6();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;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;launchEditor;launchEditorLoading;fileEditor;fileEditorLoading;fileEditorHost;fileNote;fileAsk;identityAsk;fileSyncTimer;fileApplyTimer;historySnapshot;historyTimer;historyAnswering=!1;undoButton;redoButton;labelFileGroup;cloudCoverInput;cloudDarknessInput;cloudBaseInput;precipitationTypeSelect;precipitationIntensityInput;windDirectionInput;windSpeedInput;stormInput;weatherInferredInput;weatherSourceText;skyCandidatesOutput;showMeteorButton;showCometButton;showNovaButton;showSatelliteButton;showFireballButton;weatherSourceLink;weatherFields;weatherInference=new vm(F6());weatherLookupTimer;weatherLookupToken=0;weatherLookupPending=!1;weatherLookupResult;weatherTrackSpan;soundKindSelect;soundVolumeInput;soundPitchInput;soundPitchValue;soundSrcInput;soundFields;soundKindOptions=new Map;soundPreviewTimer;instrumentSelect;filterSelect;labelFilter;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;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;labelImportFile;labelImportUrl;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;labelNarrativeRemember;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;skyDetailsButton;clampedLines;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelLaunchesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;addDecorObserverButton;surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=pu[0].create();milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=ka;currentAppearance={...tL};currentSourceId=jc;selectedSourceIds=new Set([jc]);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 Wl;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.armingLandmark||this.pendingLandmark)&&this.disarmLandmark(),this.contextMenu.hidden||this.hideContextMenu(),this.decorContextMenu.hidden||this.hideDecorContextMenu()),(e.ctrlKey||e.metaKey)&&!e.altKey&&["z","y"].includes(e.key.toLowerCase())){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;e.preventDefault(),e.key.toLowerCase()==="y"||e.shiftKey?this.redo():this.undo();return}if(mM.has(e.key)||e.key==="Delete"||e.key==="Backspace"){const t=e.composedPath()[0];if(t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLElement&&(t.isContentEditable||t.closest(".cm-editor")))return;mM.has(e.key)?this.moveOrResizeSelectedShapes(e):this.canvasMode()==="decor"?this.deleteDecor():this.deleteShape()}};handleDragPointerMove=e=>this.onDragPointerMove(e);handleDragPointerUp=()=>{const e=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedDecorId:void 0,t=this.cameraDragState&&!this.cameraDragState.moved?this.cameraDragState.pressedBodyId:void 0;this.endDrag(),t!==void 0&&this.showBody(t),e!==void 0&&(this.selectDecor(e),this.revealDecorPanel())};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${qS}</style>${YS}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const n of this.shadow.querySelectorAll(Nu))n.build();for(const n of this.shadow.querySelectorAll(Mp))n.build();this.sceneElement=document.createElement(yp),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",n=>{this.ufoElement.sighting.observerMap=n.detail.open,this.dispatchEvent(new CustomEvent("sightingchange"))}),this.sceneElement.accountInTheRound=!1,this.ufoElement=this.sceneElement.ufoElement,this.ufoElement.steadyObserver=!0,this.ufoElement.observerPlacing=!0,this.ufoElement.addEventListener("observerplace",n=>{const{lat:s,lng:r}=n.detail;this.latInput.value=String(Number(s.toFixed(6))),this.lngInput.value=String(Number(r.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 rh(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const n of[this.timeStartLabel,this.timeEndLabel])n.addEventListener("click",()=>this.switchTimeDisplay()),n.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.durationElement=this.shadow.querySelector(Mp),this.durationInput=this.durationElement.input,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.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.rareIceCrystalsInput=this.shadow.getElementById("rareIceCrystals"),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.rareIceCrystalsInput,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.filterSelect=this.shadow.getElementById("filter"),this.labelFilter=this.shadow.getElementById("label-filter"),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.refreshFilterOptions(),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.labelObserverBirth=this.shadow.getElementById("label-observer-birth"),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.labelFileGroup=this.shadow.getElementById("label-file-group"),this.fileEditorHost=this.shadow.getElementById("file-editor"),this.fileNote=this.shadow.getElementById("file-note"),this.fileAsk=this.shadow.getElementById("file-ask"),this.identityAsk=this.shadow.getElementById("identity-ask"),this.shadow.getElementById("identity-ask-keep").addEventListener("click",()=>{this.closeIdentityAsk(),this.downloadJson()}),this.shadow.getElementById("identity-ask-back").addEventListener("click",()=>this.closeIdentityAsk()),this.shadow.getElementById("identity-ask-initials").addEventListener("click",()=>{this.closeIdentityAsk(),this.writeNamesAsInitials()}),this.fileAsk.addEventListener("cancel",n=>{n.preventDefault(),this.keepReadingWeather()}),this.shadow.getElementById("file-ask-stop").addEventListener("click",()=>this.stopReadingWeather()),this.shadow.getElementById("file-ask-keep").addEventListener("click",()=>this.keepReadingWeather()),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.labelRareIce=this.shadow.getElementById("label-rare-ice"),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.labelLaunchesSubgroup=this.shadow.getElementById("label-launches-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.decorList=new Im({header:this.shadow.getElementById("decor-list-header"),footer:this.shadow.getElementById("decor-list-footer"),ids:{list:"decor",label:"label-decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:n=>`option-decor-${n}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:n=>this.selectDecor(n),onAdd:n=>this.addDecor(n),onRemove:()=>this.deleteDecor()}),this.decorList.setKinds([{value:"building",label:"Building"},{value:"tree",label:"Tree"},{value:"shrub",label:"Shrub"},{value:"bridge",label:"Bridge"},{value:"wire",label:"Overhead line"},{value:"crop",label:"Crop row"},{value:"terrace",label:"Terrace (restanque)"},{value:"mound",label:"Stone heap"},{value:"wall",label:"Dry-stone wall"},{value:"streetlight",label:"Streetlight"},{value:"vehicle",label:"Vehicle"},{value:"aircraft",label:"Aircraft"},{value:"entity",label:"Being"},{value:"observer",label:"Other observer",hidden:!0}]),this.decorList.setLabels({list:"Environment",remove:"Delete decor",add:"Add",actions:{"look-at-decor":"Look at it"}}),this.addDecorObserverButton=this.shadow.getElementById("add-decor-observer"),this.sceneryStatus=this.shadow.getElementById("scenery-status"),this.sceneryWarning=this.shadow.getElementById("scenery-warning"),this.scenerySource=this.shadow.getElementById("scenery-source"),this.labelScenerySource=this.shadow.getElementById("label-scenery-source"),this.sceneryRadius=this.shadow.getElementById("scenery-radius"),this.labelSceneryRadius=this.shadow.getElementById("label-scenery-radius"),this.sceneryRadius.value=this.readSceneryRadius(),this.surroundings=new ga(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:n=>this.setPlantedDecor(n),kindName:n=>this.decorList.kindLabel(n),cite:n=>this.citeSource(n),busy:(n,s)=>this.sceneElement.setBusy(n,s),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(n=>({lat:n.pose.lat,lng:n.pose.lng})).filter(n=>typeof n.lat=="number"&&typeof n.lng=="number")},ka,async(n,s)=>this.surroundingsProvider?this.surroundingsProvider.covers(n,s)?this.surroundingsProvider:void 0:(await _e(async()=>{const{SurroundingsSources:r}=await import("./surroundingsSources-CvhFXPJx.js");return{SurroundingsSources:r}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,n,s),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryChoice!==Nt.NO_SCENERY),this.scenerySource.addEventListener("change",()=>{if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryChoice!==Nt.NO_SCENERY),this.sceneryChoice===Nt.NO_SCENERY){this.surroundings.withdraw();return}const n=this.plantingCentre();n&&this.surroundings.survey(n.lat,n.lng)}),this.sceneryRadius.addEventListener("input",()=>{const n=Number(this.sceneryRadius.value);if(!Number.isFinite(n)||n<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const s=this.plantingCentre();this.surroundings.radiusChanged(n,s?.lat,s?.lng)}),this.fillScenerySources(),this.undoButton=this.shadow.getElementById("undo"),this.redoButton=this.shadow.getElementById("redo"),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.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.modelPicker=new vh(this.shadow,()=>({title:this.messages.modelPickerTitle,close:this.messages.modelPickerClose,choose:this.messages.modelPickerChoose,address:this.messages.decorModelAdvanced,addressUrl:this.messages.decorModelUrl,addressName:this.messages.decorModelTitle,addressAuthor:this.messages.decorModelAuthor,addressLicense:this.messages.decorModelLicense,addressSource:this.messages.decorModelSource,addressUse:this.messages.modelPickerUse,addressIncomplete:this.messages.modelPickerIncomplete})),this.decorParametersHost=this.shadow.getElementById("decor-parameters"),this.decorParameterForm=new Gs(this.decorParametersHost,"en","decorParam.");const t={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new Gs(this.decorBaseHost,"en","decorBase.",t,(n,s)=>this.enhanceDecorModelChoice(n,s)),this.decorStateForm=new Gs(this.decorStateHost,"en","decorState.",t),this.labelDecorGroup=this.shadow.getElementById("label-decor-group"),this.labelMilestones=this.shadow.getElementById("label-milestones"),this.labelMilestoneLabel=this.shadow.getElementById("label-milestone-label"),this.labelMilestoneNote=this.shadow.getElementById("label-milestone-note"),this.ufoElement.canvasElement.addEventListener("pointerdown",n=>{this.focus({preventScroll:!0}),this.onPointerDown(n)}),this.ufoElement.canvasElement.addEventListener("pointermove",n=>this.onPointerMove(n)),this.ufoElement.canvasElement.addEventListener("contextmenu",n=>this.onContextMenu(n)),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 n=this.ufoElement.sighting;n.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),n.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),n.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.durationElement.addEventListener("durationchange",n=>{const{seconds:s,text:r}=n.detail;this.ufoElement.sighting.event.durationText=r,this.ufoElement.durationSeconds=s,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((s??0)*1e3),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.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.referenceSelect.addEventListener("change",()=>this.selectReference(this.referenceSelect.value)),this.deleteReferenceButton.addEventListener("click",()=>this.deleteReference());for(const n of this.referenceFields)n.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",n=>this.onReferenceWheel(n),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",n=>this.onBodyWheel(n),{passive:!1}),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 n of[this.milestoneLabelInput,this.milestoneNoteInput])n.addEventListener("input",()=>this.updateMilestone());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(B2,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(U2,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown);for(const n of gM)this.presetButtons[n].addEventListener("click",()=>this.setAppearance({presetId:n}));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 n of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])n.addEventListener("input",()=>this.updateObserver());for(const n of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])n.addEventListener("input",()=>this.updateObserver());this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",n=>{n.key==="Enter"&&(n.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.filterSelect.addEventListener("change",()=>this.updateObserver()),this.instrumentSelect.addEventListener("change",()=>{const n=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const s=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(r=>[r.t,en.fovOf(this.ufoElement.sighting,r.t)]));this.retuneFieldOfView(n),this.retuneExposure(n),en.reproject(this.ufoElement.sighting,n,s),this.sceneElement.applyFrameFormat(),this.refreshFilterOptions(),this.syncOpticsFromInstrument(),this.ufoElement.refresh(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.accountViewSelect.addEventListener("change",()=>this.chooseAccountView(this.accountViewSelect.value==="bodies")),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const i=n=>this.shadow.querySelector(`${Nu}[name="${n}"]`);this.startDate=i("obs-time"),this.endDate=i("obs-end-time"),this.birthDate=i("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=zo.ALL,this.perceptionSettings.labels=this.messages.observerPerception,this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata()),this.startDate.messages=this.messages,this.endDate.messages=this.messages,this.birthDate.messages=this.messages;for(const n of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(n,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",n=>{const{time:s}=n.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=s}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",n=>{this.birth=n.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",n=>{const{time:s}=n.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=s})});for(const n of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])n.addEventListener("input",()=>this.updateObserverMetadata());this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const n of this.weatherFields){if(n===this.iceCrystalAlignmentInput||n===this.rareIceCrystalsInput){n.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}n.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const n of this.soundFields)n.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(n=>this.shadow.getElementById(n.getAttribute("aria-controls")));for(const n of this.groupTabs)n.addEventListener("click",()=>this.toggleGroup(n,!this.isGroupOpen(n)));this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const n of this.subgroupTabs)n.addEventListener("click",()=>this.openSubgroup(n));gn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummaryBuilder=new $l(this.messages,this.naming,this.said,this.tagNames,{messages:this.messages,locale:this.language}),this.paramSummary.addEventListener("click",n=>this.onParamSummaryClick(n)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(n=>n.id==="group-shape")],!0),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),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=kS(this.shadow.getElementById("cloud-editor"),this.sceneElement,(n=!0)=>{n&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(n,s)=>{this.headingInput.value=String(this.rounded(n)),this.pitchInput.value=String(this.rounded(s)),this.updateObserver()},yh(Is.preferencesFor(this),Sh)),this.currentMilestoneT=this.ufoElement.sighting.milestones[0]?.t,this.refreshMilestoneList(),this.onSelectionOrTimeChanged(),this.syncDurationField(),this.syncPlaybackControls(),this.refreshSourceRows(),this.refreshTimeZoneOptions(),this.syncWeatherSourceState(),this.isConnected&&this.loadLocaleMessages()}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),Is.preferencesFor(this).join()!==this.preferences.join()&&this.loadLocaleMessages(),this.shadow.addEventListener("pointerdown",this.armHistory,!0),this.shadow.addEventListener("keydown",this.armHistory,!0);for(const t of["input","change","click","keyup","pointerup"])this.shadow.addEventListener(t,this.scheduleHistoryRecord,!0);this.shadow.addEventListener("input",this.touch,!0),this.shadow.addEventListener("change",this.touch,!0),this.shadow.addEventListener("keydown",this.touchByKey,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.importFromUrl(e)}attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),this.shadow.removeEventListener("pointerdown",this.armHistory,!0),this.shadow.removeEventListener("keydown",this.armHistory,!0);for(const e of["input","change","click","keyup","pointerup"])this.shadow.removeEventListener(e,this.scheduleHistoryRecord,!0);clearTimeout(this.historyTimer),this.shadow.removeEventListener("input",this.touch,!0),this.shadow.removeEventListener("change",this.touch,!0),this.shadow.removeEventListener("keydown",this.touchByKey,!0),this.cloudEditor.stopManipulation(),document.removeEventListener("click",this.handleOutsideContextMenuClick),this.endDrag(),queueMicrotask(()=>{this.isConnected||this.releaseFileEditor()})}releaseFileEditor(){this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileEditorLoading=void 0}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.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncBodiesShown(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??jc,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.offsetIsAuthors=!1,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField();const t=this.plantingCentre();this.surroundings.placeLoaded(t?.lat,t?.lng),this.syncWeatherOwnership(),this.markClean()}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&JSON.stringify(this.sightingData)!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=JSON.stringify(this.sightingData),this.touched=!1,this.savedFileText=this.fileText(),this.fileEditor?.markSaved())}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.historySnapshot!==void 0&&(clearTimeout(this.historyTimer),this.historyTimer=setTimeout(()=>this.recordHistory(),350))};recordHistory(){this.historyTimer=void 0;const e=this.fileEditor;if(e===void 0||this.historySnapshot===void 0)return;const t=this.fileText();t!==this.historySnapshot&&(this.historySnapshot=t,this.historyAnswering=!1,e.replaceText(t,this.fileSyncActive()),this.fileTextApplied=e.text,this.syncHistoryButtons())}undo(){this.stepHistory(e=>e.undo(this.fileSyncActive()))}redo(){this.stepHistory(e=>e.redo(this.fileSyncActive()))}stepHistory(e){this.historyTimer!==void 0&&(clearTimeout(this.historyTimer),this.recordHistory());const t=this.fileEditor;t===void 0||this.isRecording||this.ufoElement.playbackState==="playing"||e(t)&&(clearTimeout(this.fileApplyTimer),this.applyFileText(t.text,!0),this.historyAnswering=!0,this.syncHistoryButtons())}syncHistoryButtons(){this.undoButton.disabled=!(this.fileEditor?.canUndo??!1),this.redoButton.disabled=!(this.fileEditor?.canRedo??!1)}resetHistory(){clearTimeout(this.historyTimer),this.historyTimer=void 0,this.historySnapshot=void 0,this.historyAnswering=!1,this.fileEditor?.destroy(),this.fileEditor=void 0,this.fileTextApplied=void 0,this.fileEditorLoading=void 0,this.syncHistoryButtons(),this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>{})}touchByKey=e=>{(e.key==="Delete"||e.key==="Backspace")&&(this.touched=!0)};warnBeforeLeaving=e=>{!this.guardsLeaving||!this.dirty||(e.preventDefault(),e.returnValue="")};holdLoad(e){return!this.dispatchEvent(new CustomEvent("beforeload",{detail:{proceed:e,dirty:this.dirty},cancelable:!0,bubbles:!0,composed:!0}))}exportJson(){const e=wi.inspect(this.sightingData,this.loadedJson());if(e.length===0){this.downloadJson();return}this.askAboutIdentity(e)}loadedJson(){try{return this.baseline?JSON.parse(this.baseline):void 0}catch{return}}askAboutIdentity(e){const t={lastName:this.messages.identityLastName,firstNames:this.messages.identityFirstNames,nameInId:this.messages.identityNameInId,nameInText:this.messages.identityNameInText,address:this.messages.identityAddress,email:this.messages.identityEmail,phone:this.messages.identityPhone};this.shadow.getElementById("identity-ask-text").textContent=this.messages.identityAsk,this.shadow.getElementById("identity-ask-found").replaceChildren(...e.map(s=>{const r=document.createElement("li");return r.textContent=t[s.kind].replaceAll("{value}",s.found),r}));const n=e.some(s=>["lastName","firstNames","nameInId","nameInText"].includes(s.kind));this.shadow.getElementById("identity-ask-initials").hidden=!n,typeof this.identityAsk.showModal=="function"?this.identityAsk.showModal():this.identityAsk.setAttribute("open","")}closeIdentityAsk(){typeof this.identityAsk.close=="function"?this.identityAsk.close():this.identityAsk.removeAttribute("open")}writeNamesAsInitials(){const e=wi.namesOf(this.sightingData);this.observerLastNameInput.value=wi.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>wi.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=wi.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=wi.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=wi.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}downloadJson(){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),this.markClean()}async importFromFile(){const e=this.importFileInput.files?.[0];if(e){if(this.holdLoad(()=>void this.loadFile(e))){this.importFileInput.value="";return}await this.loadFile(e)}}async loadFile(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);if(Ci.isCase(i)){if(this.offerCase(i,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=i,this.resetHistory(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importUrlInput.value=""}catch{window.alert(this.messages.importError)}finally{this.importFileInput.value=""}}offerCase(e,t){return!this.dispatchEvent(new CustomEvent("caseloaded",{detail:{json:e,url:t},bubbles:!0,composed:!0,cancelable:!0}))}bodyShapeIds(){return this.accountShapeIds?[...this.accountShapeIds]:this.ufoElement.sighting.timeline.sourceIds}set documentUrl(e){this.sceneElement.documentUrl=e}async importFromUrl(e=this.importUrlInput.value.trim()){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){try{const t=await ho.json(e);if(Ci.isCase(t)){const n=new URL(e,location.href).href;if(this.offerCase(t,n)){this.importUrlInput.value=n;return}throw new Error("A case has no recording to edit here")}const i=t;this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.resetHistory(),this.importUrlInput.value=new URL(e,location.href).href,this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){window.alert(this.importErrorFor(t))}}importErrorFor(e){if(!(e instanceof Ja))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";static SCENERY_STORAGE="rr0-sighting-editor.surroundings";static SCENERY_RADIUS_STORAGE="rr0-sighting-editor.surroundings-radius";static NO_SCENERY="none";narrativeProvider=Kh[0].create();get narrativeSourceId(){return Nr(Kh,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:Nt.LANGUAGE_NAMES[this.showerLanguage()],settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const n=i instanceof os&&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,a=cr.stated(r);if(a.length>0){const l=this.ufoElement.sighting.provenance,c=Lm(this.ufoElement.sighting);this.sightingData=cr.apply(c,Vu.loadable(r),a),this.ufoElement.sighting.provenance=l,this.recordNarrativeProvenance(e,a),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset()}this.narrativeStatus.textContent=a.length>0?this.messages.narrativeApplied.replace("{count}",String(a.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:Nt.valueAt(Lm(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[rL[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 a=document.createElement(t==="stated"?"q":"span");a.textContent=n.rationale,s.append(r,a),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=Nr(Kh,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(),a=r===""?void 0:n.suspect(r);s.classList.toggle("invalid",a!==void 0),s.title=a?this.said.read(a)??"":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 a=e[i.id]??this.storedNarrativeSetting(i.id);return a!==void 0&&(r.value=a),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 os))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(Nt.NARRATIVE_KEY_STORAGE),localStorage.removeItem(Nt.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"?Nt.NARRATIVE_KEY_STORAGE:e==="workspace"?Nt.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",z6,e=>{this.placeProvider=e.create()})),this.weatherSourceRow.replaceChildren(this.sourcePicker("weather",sg,e=>{this.weatherInference=new vm(e.create()),this.scheduleWeatherLookup()})),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),this.sourcePicker("light-pollution",iM,e=>{this.lightPollutionProvider=e.create(),this.scheduleLightPollutionLookup()})),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",Kh,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,xm,()=>this.applyTerrainSources()),this.labelledPicker("imagery",this.messages.sourceImagery,hM,()=>this.applyTerrainSources()),this.labelledPicker("aircraft",this.messages.sourceAircraft,ng,()=>this.applyAircraftSource()),this.labelledPicker("decor-model",this.messages.decorModel,pu,()=>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 a=()=>{const l=Nr(t,s.value);s.title=l.credit,r.href=l.creditUrl,r.textContent=l.credit};return a(),s.addEventListener("change",()=>{this.chosenSourceId.set(e,s.value),a(),i(Nr(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:Nr(xm,this.chosenSourceId.get("elevation")).create(),imagery:Nr(hM,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(){this.sceneElement.setAircraftSource(Nr(ng,this.chosenSourceId.get("aircraft"))),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=Nr(pu,this.chosenSourceId.get("decor-model")).create(),this.sceneElement.setDecorModelProvider(this.decorModelProvider),this.decorModelEntries=void 0,this.refreshDecorModelOptions(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId)),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)<Il&&Math.abs(t-this.namedCoordinates.lng)<Il||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),fM))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(){const e=this.numberOrUndefined(this.latInput.value),t=this.numberOrUndefined(this.lngInput.value);if(e===void 0||t===void 0||this.timeZoneIsStated())return;const i=this.timeZoneLookedUpAt;i&&Math.abs(e-i.lat)<Il&&Math.abs(t-i.lng)<Il||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(e,t),fM))}async lookUpTimeZone(e,t){this.timeZoneLookedUpAt={lat:e,lng:t};const i=await this.timeZoneProvider.zoneAt(e,t);this.placeZone=i??void 0,!(!i||this.timeZoneIsStated())&&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,a=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,this.surroundings.placeChanged(e,t);const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Ut.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),g=this.numberOrUndefined(this.fNumberInput.value),m=this.filterSelect.value,v=fi.byId(c.getLatestPoseAt(h-1)?.filter),b=m===fi.NONE.id||m===""?v===fi.NONE?void 0:fi.NONE.id:m,M=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=M===u.exposureSeconds?void 0:M;const y=this.numberOrUndefined(this.focusDistanceInput.value),x=Math.abs(f-Ut.fieldOfViewDeg(u))>.01||g!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&n===0&&s===0&&a===0&&!x?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:n,rollDeg:s===0?void 0:s,fovDeg:f,fNumber:g,focusDistanceM:y,filter:b}),this.ufoElement.refresh(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup(),this.schedulePlaceReverse(),this.scheduleTimeZoneLookup(),this.scheduleGroundElevation(),this.updateUtcOffsetValidity()}syncAgeFromBirth(e){const t=this.birth,i=this.ufoElement.sighting.event.time;if(!t||!i||e&&!Zd.isFirm(t))return;const n=Zd.at(t,i);n!==void 0&&(this.observerAgeInput.value=String(n),this.updateObserverMetadata())}syncBirthFromAge(){const e=this.ufoElement.sighting.event.time,t=this.numberOrUndefined(this.observerAgeInput.value);if(!e||t===void 0)return;const i=this.birth;if(i&&Zd.at(i,e)===t)return;const n=Zd.birthFor(t,e);n&&(this.birthDate.setPrecise(!1),this.birth=n,this.birthDate.time=n,this.updateObserverMetadata())}editDate(e){e(),this.dropDurationOutrankedByDates(),this.ufoElement.sighting.event.timeZone&&this.applyTimeZoneOffset(),this.ufoElement.refresh(),this.refreshSceneryWarning(),this.syncDurationField(),this.scheduleWeatherLookup(),this.scheduleLightPollutionLookup()}dropDurationOutrankedByDates(){const e=this.ufoElement.sighting.event;e.durationSeconds!==void 0&&cc({...e,durationSeconds:void 0})!==void 0&&(this.ufoElement.sighting.event.durationText=void 0,this.ufoElement.durationSeconds=void 0)}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.zoneShown()}zoneShown(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone:e.utcOffsetHours===void 0?"":this.preferredZoneFor(e.utcOffsetHours)??""}updateTimeZone(){const e=this.ufoElement.sighting.event,t=this.stringOrUndefined(this.timeZoneSelect.value);if(e.timeZone=t,this.offsetIsAuthors=!1,t===void 0){e.utcOffsetHours=void 0,this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup();return}this.applyTimeZoneOffset()}applyTimeZoneOffset(){const e=this.ufoElement.sighting.event;if(this.offsetIsAuthors&&e.utcOffsetHours!==void 0){const t=this.preferredZoneFor(e.utcOffsetHours);e.timeZone=t,this.timeZoneSelect.value=t??""}else{const t=e.timeZone?this.timeZones.offsetHoursAt(e.timeZone,this.timeZoneReference()):void 0;t!==void 0&&(e.utcOffsetHours=t)}this.syncUtcOffsetField(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}timeZoneReference(){const e=this.ufoElement.sighting.event.time;return e?.year!==void 0?e:{year:new Date().getFullYear(),month:1,day:1,hour:12}}preferredZoneFor(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference());if(t.length===0)return;const i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const n=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return n&&t.includes(n)?n:t[0]}updateUtcOffset(){const e=this.ufoElement.sighting.event,t=this.numberOrUndefined(this.utcOffsetInput.value);if(t===void 0)e.utcOffsetHours=void 0,e.timeZone=void 0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value="";else{const i=this.preferredZoneFor(t);if(i===void 0){this.utcOffsetInput.classList.add("invalid"),this.utcOffsetInput.title=this.messages.utcOffsetNoZone;return}e.utcOffsetHours=t,e.timeZone=i,this.offsetIsAuthors=!0,this.autoFilledTimeZone=void 0,this.timeZoneSelect.value=i}this.updateUtcOffsetValidity(),this.ufoElement.refresh(),this.scheduleWeatherLookup()}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),observerBirth:this.birth,observerPerception:zo.compact(this.perceptionSettings.values),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??{},a=t===""?r:{...r,url:t},l=Object.keys(a).length>0?[a,...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={...Fi(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={...Fi(this.ufoElement.sighting,this.ufoElement.currentTime),iceCrystalAlignment:Number(this.iceCrystalAlignmentInput.value),rareIceCrystals:Number(this.rareIceCrystalsInput.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>x6?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(),a={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)||jd))},l=s.registration,c=a.headingDeg!==l.headingDeg||a.pitchDeg!==l.pitchDeg||a.rollDeg!==l.rollDeg||a.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:a,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=ot(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=ot(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=ot(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${n.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:w6,registration:{headingDeg:s?.headingDeg??0,pitchDeg:s?.pitchDeg??0,fovDeg:jd},from:this.observerPositionNow(),...i};n.references=[...n.references,a],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&&Yn.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(Yn.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 a=this.canvasPointOfDirection(Yn.worldDirection(s.scene));if(a&&Math.hypot(a.x-e.x,a.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(a=>{if(a.id!==e)return a;if(t==="scene")return{...a,scene:Yn.aimOf(r)};const l=Yn.picturePointOf(r,n.registration,s);return l?{...a,picture:l}:a})),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)||jd,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 a=Yn.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const n=this.currentLandmarks(),s=this.nextLandmarkId(n);this.writeLandmarks([...n,{id:s,picture:this.pendingLandmark,scene:Yn.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=Yn.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 Yn.worldDirectionOf(e.picture,t.registration,i).angleTo(Yn.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 a=document.createElement("option");a.value=r.id;const l=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,s)+l,this.referenceLandmarksSelect.appendChild(a)}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(a=>a.id===e?{...a,label:this.said.write(a.label,this.referenceLandmarkLabelInput.value,this.writingLanguage)}:a));const t=this.referenceLandmarksSelect.options[this.referenceLandmarksSelect.selectedIndex],i=this.currentLandmarks(),n=i.findIndex(a=>a.id===e),s=this.currentReference(),r=s?this.sceneElement.referenceAspect(s.id):void 0;if(t&&n>=0){const a=s&&r!==void 0?` · ${this.landmarkResidualDeg(i[n],s,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[n],n)+a}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(a=>this.canvasPointOfDirection(Yn.worldDirectionOf(a,n,i))),r=this.currentLandmarks().map((a,l)=>({picture:this.canvasPointOfDirection(Yn.worldDirectionOf(a.picture,n,i)),scene:this.canvasPointOfDirection(Yn.worldDirection(a.scene)),label:this.landmarkLabel(a,l),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(Yn.worldDirectionOf(this.pendingLandmark,n,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(s.every(a=>a!==void 0)?s:void 0,r.filter(a=>a.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 a=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:a,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=ot(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,a]of this.streetPictures.entries()){const l=document.createElement("option");l.value=String(r),l.textContent=this.streetPictureLabel(a,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:jd}})}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 _e(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url),h=await new Promise((d,u)=>{const p=new FileReader;p.onload=()=>d(p.result),p.onerror=()=>u(p.error),p.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),a=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,...a],this.currentTraceId=a[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(a.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 fx){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(),X6)}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=pg(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 vm(e),this.scheduleWeatherLookup()}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())}scheduleWeatherLookup(e=!1){if(!this.weatherFromRecords||this.pendingWeatherEdit!==void 0)return;const t=this.ufoElement.sighting.weatherSource;!e&&t!==void 0&&!wm(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),pM))}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(){const e=this.ufoElement.sighting.weatherSource;if(!this.weatherFromRecords||e===void 0||!wm(e))return;const t=this.ufoElement.seekableDuration;this.weatherTrackSpan===void 0||t===this.weatherTrackSpan||(this.weatherTrackSpan=t,this.scheduleWeatherLookup())}syncWeatherSourceState(){const e=this.ufoElement.sighting.weatherSource,t=this.weatherFromRecords;for(const a of this.weatherFields)a.disabled=t&&e!==void 0&&a!==this.iceCrystalAlignmentInput&&a!==this.rareIceCrystalsInput||this.ufoElement.playbackState==="playing",this.ufoElement.playbackState==="playing"?a.title=this.messages.weatherWhilePlaying:a.title===this.messages.weatherWhilePlaying&&(a.title="");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&wm(e)){this.cancelWeatherLookup(),this.weatherLookupResult=void 0,this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState();return}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=i?t?this.weatherStatusMessage():"":this.weatherUnavailableMessage();this.weatherSourceText.textContent=r===""?"":`${r} `,this.weatherSourceRow.hidden=r===""||!i}startDateHalfEntered(){return this.shadow.getElementById("obs-time-native")?.validity.badInput===!0}weatherUnavailableMessage(){const e=this.weatherInference.missingOf(this.ufoElement.sighting);return this.startDateHalfEntered()&&(e.date=!0),e.date&&e.place?this.messages.weatherNeedsDateAndPlace:e.date?this.messages.weatherNeedsDate:this.messages.weatherNeedsPlace}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&&ps(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.pendingWeatherEdit=void 0,this.closeFileAsk(),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=iM[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(),pM)}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 a=await n.lookUp(t.lat,t.lng);i!==this.lightPollutionToken||!this.lightPollutionFromRecord()||(this.lightPollutionLookup=a,a.status==="found"?(e.lightPollution=a.lightPollution,e.provenance.set("lightPollution",{basis:"derived",rationale:`${n.citation}, at ${a.lat.toFixed(4)}, ${a.lng.toFixed(4)}: ${Math.round(a.artificialMcdPerM2*1e3)} µcd/m² artificial over the natural 171`,of:a.lightPollution}),this.lightPollutionInput.value=String(a.lightPollution),this.ufoElement.refresh()):a.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(){const e=this.shadow.activeElement;if(e!==this.durationInput&&e!==this.durationElement.textField){const t=this.ufoElement.sighting.event,i=cc(t);this.durationElement.set(i!==void 0?i/1e3:void 0,t.durationText)}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=hS(this.ufoElement.sighting.event);this.durationElement.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"))}chooseTimeInputMode(){const e=this.ufoElement.sighting.event;this.startDate.setPrecise(ln.opensPrecise(e.time)),this.endDate.setPrecise(ln.opensPrecise(e.endTime))}syncObservationTimeFields(){this.startDate.time=this.ufoElement.sighting.event.time}syncObservationEndTimeFields(){this.endDate.time=this.ufoElement.sighting.event.endTime}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)>K6;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),Y6))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Il&&Math.abs(e.lng-i)<Il}async applyGroundElevation(e,t){const i=++this.groundElevationToken,n=Nr(xm,this.chosenSourceId.get("elevation")),s=await new ov(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(ot(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.birthDate.setPrecise(ln.opensPreciseDate(e.account?.observerBirth)),this.perceptionSettings.values=e.account?.observerPerception??{},this.birth=e.account?.observerBirth,this.birthDate.time=this.birth,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=Fi(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??gu)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??wM)),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=yv(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(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>this.syncFileEditor(!1),()=>this.showFileNote(this.messages.importError))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await _e(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-C0NC8jbz.js");return{SightingFileEditor:t}},__vite__mapDeps([6,7]),import.meta.url);return this.historySnapshot??=this.fileText(),this.fileTextApplied=this.historySnapshot,this.fileEditor=new e(this.fileEditorHost,this.historySnapshot,t=>this.onFileTextEdited(t),this.messages.fileEditorLabel,{baseline:this.touched?this.savedFileText:this.fileText(),phrases:this.messages.fileSearchPhrases,caretMoved:t=>this.onFileCaret(t)}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}fileSyncActive(){return this.fileEditor!==void 0&&this.isGroupIdOpen("group-file")}fileFocus;caretTimer;followingCaret=!1;onFileCaret(e){clearTimeout(this.caretTimer),this.caretTimer=setTimeout(()=>this.focusFromFile(e),120)}focusFromFile(e){if(!this.fileSyncActive())return;const t=this.ufoElement.sighting;this.followingCaret=!0;try{const i=e[0]==="decor"&&typeof e[1]=="number"?t.decor[e[1]]:void 0;if(i!==void 0){this.fileFocus="decor",this.selectDecor(i.id);return}const n=e[0]==="timeline"&&e[1]==="keyframes"&&typeof e[2]=="number"&&e[3]==="shapes"&&typeof e[4]=="number"?t.timeline.allKeyframes[e[2]]?.shapes[e[4]]:void 0;if(n!==void 0){this.fileFocus="shape",this.selectUnit(n.sourceId),this.syncCanvasMode(),this.ufoElement.refresh();return}this.fileFocus=void 0,this.syncCanvasMode(),this.ufoElement.refresh()}finally{this.followingCaret=!1}}showInFile(e){this.followingCaret||e===void 0||!this.fileSyncActive()||this.fileEditor.reveal(e)}bodyPath(e){try{const i=(JSON.parse(this.fileEditor.text).interpretation?.bodies??[]).findIndex(n=>n.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,n]of t.entries()){const s=n.shapes.findIndex(r=>r.sourceId===e);if(s>=0)return["timeline","keyframes",i,"shapes",s]}}showFileNote(e){this.fileNote.textContent=e??"",this.fileNote.hidden=e===void 0}fileText(){return JSON.stringify(this.sightingData,null,2)}scheduleFileSync(){this.fileEditor===void 0||this.fileSyncTimer!==void 0||!this.isGroupIdOpen("group-file")||(this.fileSyncTimer=setTimeout(()=>{this.fileSyncTimer=void 0,this.syncFileEditor()},250))}syncFileEditor(e=!0){const t=this.fileEditor;if(!(t===void 0||!this.isGroupIdOpen("group-file")||t.focused)&&!this.historyAnswering){try{JSON.parse(t.text)}catch{return}t.replaceText(this.fileText(),e),this.fileTextApplied=t.text}}onFileTextEdited(e){this.syncHistoryButtons(),clearTimeout(this.fileApplyTimer),this.fileApplyTimer=setTimeout(()=>this.applyFileText(e),500)}applyFileText(e,t=!1){this.fileApplyTimer=void 0;let i;try{i=JSON.parse(e)}catch{return}if(typeof i!="object"||i===null||Array.isArray(i)||JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,s=!t&&this.fileTextApplied!==void 0&&JSON.stringify(i.weatherTrack)!==JSON.stringify(Nt.weatherOf(this.fileTextApplied)),r={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,s&&!this.restoringWeather&&this.weatherFromRecords){const a=this.ufoElement.sighting.weatherSource;a===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):sg.some(l=>l.id===a.id)&&this.askAboutWeather(r,a.name??a.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch{this.showFileNote(this.messages.importErrorMalformed),this.fileTextApplied=e}finally{this.applyingFileText=!1}}fileTextApplied;static weatherOf(e){try{return JSON.parse(e).weatherTrack}catch{return}}pendingWeatherEdit;restoringWeather=!1;askAboutWeather(e,t){this.cancelWeatherLookup(),this.pendingWeatherEdit=e,this.shadow.getElementById("file-ask-text").textContent=this.messages.weatherEditedAsk.replaceAll("{source}",t),this.shadow.getElementById("file-ask-stop").textContent=this.messages.weatherEditedStop,this.shadow.getElementById("file-ask-keep").textContent=this.messages.weatherEditedKeep,typeof this.fileAsk.showModal=="function"?this.fileAsk.showModal():this.fileAsk.setAttribute("open","")}closeFileAsk(){typeof this.fileAsk.close=="function"?this.fileAsk.close():this.fileAsk.removeAttribute("open")}stopReadingWeather(){this.pendingWeatherEdit=void 0,this.closeFileAsk(),this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState(),this.ufoElement.refresh(),this.syncFileEditor(!1)}keepReadingWeather(){const e=this.pendingWeatherEdit;if(this.pendingWeatherEdit=void 0,this.closeFileAsk(),e!==void 0){this.restoringWeather=!0;try{this.applyFileText(JSON.stringify({...this.sightingData,weatherTrack:e.track,weatherSource:e.source}))}finally{this.restoringWeather=!1}this.syncFileEditor(!1)}}applyingFileText=!1;leaveFileEditor(){const e=this.fileEditor;e!==void 0&&(this.fileApplyTimer!==void 0&&(clearTimeout(this.fileApplyTimer),this.applyFileText(e.text)),setTimeout(()=>this.syncFileEditor(!1),0))}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)),a=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)a.push({t:l.t,kind:"milestone",label:this.said.read(l.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration)}seekTo(e){this.goToMark(e*1e3)}showRender(){this.sceneElement.scrollIntoView?.({block:"center",behavior:"smooth"})}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-file")?this.fileFocus==="decor"&&this.editableDecor()!==void 0?"decor":this.fileFocus==="shape"&&this.selectedSourceIds.size>0?"shape":"scene":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-bodies")?.hidden===!1?"body":this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-launches")?.hidden===!1?"scene":this.isGroupIdOpen("group-shape")?"shape":this.isGroupIdOpen("group-decor")&&this.editableDecor()!==void 0?"decor":"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:e==="decor"?this.paintDecorOverlay: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 i=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading?this.ufoElement.sighting.interpretation:void 0;this.sceneElement.compareAccount=i!==void 0,this.sceneElement.interpretation!==i&&(this.sceneElement.interpretation=i),this.accountViewSelect.value=i!==void 0?"bodies":"shapes",this.syncLaunchesTab(),this.shadow.getElementById("account-view-row").hidden=this.isReading}syncLaunchesTab(){const e=this.subgroupTabs.find(t=>t.getAttribute("aria-controls")==="shape-launches");e&&(e.hidden=!1,this.launchEditor&&this.shadow.getElementById("shape-launches")?.hidden===!1&&this.launchEditor.refresh())}chooseAccountView(e){const t=this.groupTabs.find(n=>n.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(n=>n.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}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()),e.getAttribute("aria-controls")==="shape-launches"&&this.loadLaunchEditor().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,phenomena:!0,groundElevationM:this.groundElevationM??0,roadGradeDeg:this.sceneElement.roadGradeDeg}).map(n=>({...n,panel:this.summaryPanelIndex(n.group)})),i=t.map(n=>`${n.field}=${n.label}=${n.value}${n.unit}${n.full??""}${n.fromSource?"*":""}`).join("|");i!==this.paramSummarySignature&&(this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.runAssessments())}paramChips=[];renderParamSummary(){const e=Nt.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 a=document.createElement("span");a.className="param-nest-label",a.textContent=n.group==="assessment"?this.messages.assessmentGroup:n.group==="summary"?this.messages.summaryGroup:Nt.tabLabel(this.groupTabs[this.summaryPanelIndex(n.group)]),r.append(a),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),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),XM.sync(this.paramSummary,this.openDescription,this.messages.summaryDescription,this.messages.closeDescription,()=>{this.openDescription=void 0,this.syncDescription()})}static NESTED_GROUPS=["summary","observation","observer","location","temporal","weather","sound","decor","phenomenon","assessment"];summaryPanelIndex(e){return e==="phenomenon"?this.panelIndex("shape"):Nt.SUMMARY_GROUPS.indexOf(e)}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 XS(this.messages).read(this.ufoElement.sighting);e!==this.assessmentToken||!this.isConnected||(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=Nt.QUESTION_FIELDS[s];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const l=this.shadow.getElementById(a);l&&!l.hidden&&l.value===""&&t.add(a)}}for(const[s,r]of Object.entries(Nt.QUESTION_FIELDS))for(const a of Nt.QUESTION_FIELDS[s].fields){const l=this.shadow.getElementById(a);if(!l)continue;const c=t.has(a)&&!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(Nt.QUESTION_FIELDS))for(const a of r.fields){const l=this.shadow.getElementById(a);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),a=i.get(r)??0,l=r===n,c=Nt.badgeOn(s);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!l),s.title=a===0?"":l?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a))}}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;if(t.dataset.field==="description"){this.openDescription=this.paramChips.find(a=>a.field==="description")?.full,this.syncDescription();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("shape:")){this.selectedSourceIds=new Set([s.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(s.startsWith("body:")){const a=this.subgroupTabs.find(l=>l.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(l=>l.show(s.slice(5)));return}if(s.startsWith("decor:")){this.currentDecorId=s.slice(6),this.refreshDecorList(),this.decorList.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.syncDecorBaseFromTimeline(),this.syncIndoorLookReset(),this.updateAppearanceFieldsDisabledState(),this.updateShapeTitleValidity(),this.refreshRealSize(),this.refreshBlurDistanceBound(),this.refreshSkyCandidates(),this.refreshInstrumentOptions(),this.refreshFilterOptions(),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()}updateShapeToolbarVisibility(){const e=this.ufoElement.sighting.timeline.sourceIds.length===0,t=this.shadow.querySelector("#shape-shapes .toolbar");if(t)for(const i of Array.from(t.children))i.id!=="add-shape"&&(i.hidden=e)}updateAppearanceFieldsDisabledState(){this.updateShapeToolbarVisibility();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:iL(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,mt.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,mt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(mt.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(mt.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),a=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-a)/2,width:r,height:a},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}))}refreshFilterOptions(){const e={[fi.NONE.id]:this.messages.filterNone,[fi.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[fi.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=s=>e[s.id]??s.name,i=[...this.filterSelect.options].map(s=>s.textContent);if(i.length!==fi.ALL.length||fi.ALL.some((s,r)=>i[r]!==t(s))){const s=this.filterSelect.value||fi.NONE.id;this.filterSelect.replaceChildren();for(const r of fi.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=s}const n=this.ufoElement?.sighting?.instrument;for(const s of this.filterSelect.options){const r=!n||fi.usableWith(fi.byId(s.value),n);s.disabled=!r,s.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,n={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},s=r=>{const a=this.naming.instrument(r),l=Ut.unavailability(r,t);if(!l)return{id:r.id,label:a};const c=(l.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(l.from)).replace("{to}",String(l.to));return r.id===i.id?{id:r.id,label:this.messages.instrumentOutOfPeriod.replace("{name}",a),hint:c}:{id:r.id,label:a,disabledReason:c}};this.instrumentSelect.choices=Ut.CATEGORIES.map(r=>({label:n[r],children:Jc.filter(a=>a.category===r).map(s)})).filter(r=>r.children.length>0),this.instrumentSelect.value=this.instrumentSelect.value||i.id}static exposureText(e){return e>=1?String(Math.round(e*100)/100):`1/${Math.round(1/e)}`}statedExposureSeconds(e){const t=Nt.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=ot(e,this.ufoElement.currentTime),n=t.frame,s=i?.fovDeg??Ut.fieldOfViewDeg(t),r=n?Ut.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),gn.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 a=i?.fNumber??t.fNumber;this.fNumberInput!==this.shadow.activeElement&&(this.fNumberInput.value=a===void 0?"":String(a)),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?"":Nt.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),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=fi.byId(i?.filter).id)}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Ut.fieldOfViewDeg(e),n=Ut.fieldOfViewDeg(t.instrument);for(const s of[...t.observerTrack.allKeyframes])Math.abs(s.pose.fovDeg-i)>J6||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 ot(e,this.ufoElement.currentTime)?.fovDeg??Ut.fieldOfViewDeg(e.instrument)}currentProjection(){return $s.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=mt.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=ot(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?Ut.focalLengthMmFor(t,n.fovDeg):void 0)??i.focalLengthMm,a=n?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const l=this.ufoElement.canvasElement.height;if(l<=0)return;const c=2*Cm*e/l*i.heightMm,h=r*r/(a*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),a=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))+a+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=(g,m)=>Number(g.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)??$6,a=this.sceneElement.groundAlong(s.azimuthDeg,s.altitudeDeg,t),l=a!==void 0&&a<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(mt.sizeMAt(c,h),2),lengthM:n(mt.sizeMAt(c,h),2),heightM:n(mt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:n(s.azimuthDeg,2),altitudeDeg:n(s.altitudeDeg,2)},f={t,...p,distanceM:c,...l?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=_e(async()=>{const{BodyEditor:e}=await import("./BodyEditor-ChwDW_Ws.js");return{BodyEditor:e}},__vite__mapDeps([8,9]),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,modelPicker:()=>this.modelPicker,shapes:()=>this.bodyShapeIds().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,seekTo:t=>{this.ufoElement.currentTime=t},readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,n)=>this.sceneElement.groundAlong(t,i,n)},this.language),this.bodyEditor)),this.bodyEditorLoading}loadLaunchEditor(){return this.launchEditorLoading??=_e(async()=>{const{LaunchEditor:e}=await import("./LaunchEditor-BCbplrLt.js");return{LaunchEditor:e}},__vite__mapDeps([10,11]),import.meta.url).then(({LaunchEditor:e})=>(this.launchEditor=new e(this.shadow.getElementById("launch-editor"),{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language),this.launchEditor)),this.launchEditorLoading}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:mt.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=$s.of(i.instrument,mt.CANVAS_HEIGHT_PX,en.fovOf(i,e)),s=this.ufoElement.seekableDuration;s>i.timeline.duration&&i.timeline.setSpan(s),i.timeline.addKeyframe(e,t.map(r=>{const a=en.aimOf(i,e,r.shape.bounds),l=n.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:l}:{...h,angular:l}}}))}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.ufoElement.sighting.timeline.sourceIds.length>0&&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(i=>this.selectedSourceIds.has(i));t.length!==0&&this.removeShapes(t)}removeShapes(e){const t=this.ufoElement.sighting.timeline;for(const i of e)t.removeSource(i);this.currentSourceId=t.sourceIds[0]??jc,this.selectedSourceIds=new Set([this.currentSourceId]),this.refreshSourceList(),this.ufoElement.refresh()}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.decorList.kindLabel(e.kind)} ${n}`}addDecor(e=this.decorList.pickedKind??"building"){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:hc}:{},windows:BM(e)};t.decor=[...t.decor,n],this.currentDecorId=n.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(n.id,e)}readSceneryChoice(){try{return localStorage.getItem(Nt.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(Nt.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(Nt.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(Nt.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const{SURROUNDINGS_SOURCES:e,SurroundingsSources:t}=await _e(async()=>{const{SURROUNDINGS_SOURCES:s,SurroundingsSources:r}=await import("./surroundingsSources-CvhFXPJx.js");return{SURROUNDINGS_SOURCES:s,SurroundingsSources:r}},[],import.meta.url);if(!this.isConnected)return;const i=document.createElement("option");i.value=Nt.NO_SCENERY,i.id="option-scenery-none",i.textContent=this.messages.surveySourceNone;const n=e.map(s=>{const r=document.createElement("option");return r.value=s.id,r.textContent=s.name,r.title=s.credit,r});this.scenerySource.replaceChildren(i,...n),this.scenerySource.value=this.sceneryChoice===Nt.NO_SCENERY?Nt.NO_SCENERY:t.byId(this.sceneryChoice)?.id??t.DEFAULT_ID}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],n=t?.lat??i?.lat,s=t?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}setPlantedDecor(e){this.ufoElement.sighting.decor=e,e.some(t=>t.id===this.currentDecorId)||(this.currentDecorId=e[0]?.id),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleHistoryRecord()}refreshSceneryWarning(){const e=this.ufoElement?.sighting,t=e?Bu.anachronism(e.decor,e.event.time):void 0;this.sceneryWarning.hidden=t===void 0,this.sceneryWarning.textContent=t?this.messages.surveyWarning.replace("{survey}",t.survey).replace("{observation}",t.observation):""}citeSource(e){const t=this.ufoElement.sighting;(t.sources??[]).some(i=>i.url===e.url)||(t.sources=[...t.sources??[],e])}async adoptDefaultModel(e,t){const i=(await this.decorModelProvider.entries(t).catch(()=>[]))[0];if(!i)return;const n=this.ufoElement.sighting.decor.find(s=>s.id===e);!n||n.model||n.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(s=>s.id===e?{...s,model:{id:i.id},sizeM:i.sizeM}:s),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh())}defaultAircraft(){const e=2*Em,t=Math.round(e/eL*1e3);return{lights:Ah.byId("airliner")?.create(),track:[{t:0,eastM:-Em,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:Em,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(n=>n.kind===e).length;return`${this.decorList.kindLabel(e)} ${t+1}`}deleteDecor(){const t=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);t!==void 0&&this.removeDecor(t.id)}removeDecor(e){const t=this.ufoElement.sighting;t.decor=t.decor.filter(i=>i.id!==e),this.currentDecorId===e&&(this.currentDecorId=t.decor[0]?.id),this.refreshDecorList(),this.ufoElement.refresh()}selectDecor(e){this.currentDecorId=e,this.isGroupIdOpen("group-file")&&(this.fileFocus="decor"),this.decorList.show(e),this.syncDecorFields(),this.syncCanvasMode(),this.canvasMode()==="decor"&&this.ufoElement.refresh();const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===e);t>=0&&this.showInFile(["decor",t])}updateDecor(e={}){if(this.currentDecorId===void 0)return;const t=this.ufoElement.sighting;t.decor=t.decor.map(i=>i.id!==this.currentDecorId?i:{...i,...e}),this.syncDecorVisibility(),this.ufoElement.refresh()}decorModelEntries;refreshDecorModelOptions(e){if(!e||this.decorModelEntries?.kind===e.kind)return;const t=e.kind;this.decorModelProvider.entries(t).catch(()=>[]).then(i=>{this.decorModelEntries={kind:t,entries:i},this.isConnected&&this.decorBaseForm.sync()})}drawnEntry;drawnEntryAsked;publishedParametersOf(e){const t=Eh(e);if(!(!t?.id||t.url!==void 0)){if(this.drawnEntry?.id===t.id)return this.drawnEntry.parameters;if(this.drawnEntryAsked!==t.id){this.drawnEntryAsked=t.id;const i=t.id;this.decorModelProvider.entry(i).catch(()=>{}).then(n=>{this.drawnEntryAsked!==i||!n||(this.drawnEntry=n,this.isConnected&&this.syncDecorVisibility())})}}}modelPicker;enhanceDecorModelChoice(e,t){e.key==="model.id"&&(t.addEventListener("change",()=>t.dispatchEvent(new Event("input",{bubbles:!0}))),this.modelPicker.enhance(t,async i=>{const n=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),s=i!==""?i:n?zu[n.kind]?.id:void 0;return s!==void 0?this.decorModelProvider.entry(s).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):n===void 0?void 0:{decorKind:n.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId)?.model;return i?.url===void 0?void 0:{url:i.url,title:i.credit?.title??"",author:i.credit?.author??"",license:i.credit?.license??"",source:i.credit?.sourceUrl??""}},apply:i=>this.commitDecorBase(n=>{const s=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);n.model={url:i.url,credit:s!==void 0&&r!==void 0?{title:s,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,n]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),s=this.ufoElement.sighting.decor.find(l=>l.id===e.id);if(!s||s.model?.id!==t||!n?.sizeM)return;const r=s.sizeM!==void 0&&i?.sizeM!==void 0&&s.sizeM.widthM===i.sizeM.widthM&&s.sizeM.lengthM===i.sizeM.lengthM&&s.sizeM.heightM===i.sizeM.heightM;if(s.sizeM&&!r)return;const a={...s.sizeM,...Object.fromEntries(Object.entries(n.sizeM).filter(([,l])=>l!==void 0).map(([l,c])=>[l,this.roundedMeters(c)]))};this.updateDecor({sizeM:a})}roundedMeters(e){return Math.round(e*100)/100}addMilestone(){const e=Math.round(this.ufoElement.currentTime),t=this.ufoElement.sighting;t.milestones.find(n=>n.t===e)||(t.milestones=Po([...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&&(t.milestones=t.milestones.filter(n=>n.t!==i.t),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=Po(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)??""}refreshDecorList(){this.decorList.setItems(this.ufoElement.sighting.decor.map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning()}syncDecorFields(){this.syncDecorVisibility()}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}showDecorBase(e){if(this.decorBaseHost.hidden=e===void 0,this.decorStateHost.hidden=e===void 0,!e){this.decorBaseForm.clear(),this.decorStateForm.clear(),this.decorBaseShown=!1;return}if(this.decorBaseShown){this.decorBaseForm.sync(),this.decorStateForm.sync();return}this.decorBaseShown=!0;const t=()=>new Pa(()=>{const i=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return i?Gr.viewOf(i,this.ufoElement.currentTime):void 0},(i,n)=>this.commitDecorBase(i,n.key),()=>this.decorBaseContext());this.decorBaseForm.show(On.BASE,t(),()=>{}),this.decorStateForm.show(On.STATE,t(),()=>{})}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Lo.of(e,this.publishedParametersOf(e));return{kind:e.kind,natural:Ue.naturalSize(e.kind,e.floors),traits:{color:t.color,lit:t.lit,headlights:t.headlights,lights:t.lights,observerSide:t.observerSide},lightRigs:Lo.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:On.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:zu[e.kind]?.id}}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(l=>l.id===this.currentDecorId);if(!i||(t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,s=Gr.viewOf(i,n);e(s);const r=this.ufoElement.sighting;r.decor=r.decor.map(l=>l.id===i.id?Gr.apply(l,s,t,n):l),t==="model.id"&&this.adoptCatalogueSize(i,s.model?.id);const a=r.decor.find(l=>l.id===i.id);t==="title"&&this.decorList.rename(a.id,this.decorLabel(a)),this.syncDecorVisibility(),this.ufoElement.refresh(),t==="lightRig"&&this.dispatchEvent(new CustomEvent("sightingchange"))}syncDecorBaseFromTimeline(){this.ufoElement.playbackState==="playing"||!this.decorBaseShown||(this.decorBaseForm.sync(),this.decorStateForm.sync())}showDecorParameters(e){const t=e?$t.of(e,this.publishedParametersOf(e)):void 0;if(!e||!t){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const i=`${e.id}|${t.kind}|${t.parameters.map(r=>r.key).join(",")}`;if(i===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=i;const n=e.id,s=new Pa(()=>this.ufoElement.sighting.decor.find(r=>r.id===n),r=>{const a=this.ufoElement.sighting;a.decor=a.decor.map(l=>{if(l.id!==n)return l;const c=structuredClone(l);return r(c),c})});this.decorParameterForm.show(t,s,()=>{this.syncDecorVisibility(),this.ufoElement.refresh()})}syncDecorParameterVisibility(){this.showDecorParameters(this.ufoElement.sighting.decor.find(e=>e.id===this.currentDecorId))}syncDecorVisibility(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);this.refreshDecorModelOptions(e),this.showDecorBase(e),this.syncDecorParameterVisibility()}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 jn;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new gp;static LANGUAGE_NAMES={en:"English",fr:"French",es:"Spanish",it:"Italian"};said=new zn(["en"]);tagNames=new km({});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?ps(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,Fi(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},a=[this.starsClause(n,r),this.showerClause(n,r),this.cometClause(n,r),this.novaClause(n,r),this.eclipseClause(n,r),this.moonClause(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}",a.join(" · "))}instrumentGain(){const e=this.ufoElement.sighting;return an.gainFor(e.instrument,{fNumber:ot(e,0)?.fNumber,fieldOfViewDeg:en.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Ji("Sun",e,t).altitudeDeg,n=this.instrumentGain(),s=this.skyLossAt(e,t),r=Da(i,n,s),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<q6)return this.messages.skyStarsNone;const l=this.ufoElement.sighting.instrument,c=Math.abs(n)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(n>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(l)).replace("{gain}",a(Math.abs(n))).replace("{eye}",a(Da(i,0,s)));return r<=fh?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(fh))}showerClause(e,t){const i=bi.observedRatePerHour(bi.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),n=ac.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 a=ac.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:ac.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.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=mu.brightestAt(e,t);if(!i||i.magnitude>bc){this.showCometButton.hidden=!0;return}return this.showCometButton.hidden=i.position.altitudeDeg<=0,this.cometText(i)}novaClause(e,t){const i=vp.brightestAt(e,t);if(!i||i.magnitude>bc){this.showNovaButton.hidden=!0;return}return this.showNovaButton.hidden=i.position.altitudeDeg<=0,this.novaText(i)}eclipseClause(e,t){const i=Ri.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const n=Ji("Sun",i.peak,t),s=r=>r.replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return s(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return s(this.messages.skyEclipsePartial).replace("{percent}",String(Math.round(i.obscuration*100))).replace("{time}",this.observerClock(i.peak).replace(/:\d\d$/,""))}moonClause(e,t){const i=Ji("Moon",e,t);if(i.altitudeDeg<=0||oo(e).illuminatedFraction<.97)return;const n=[],s=_n.distanceKm(e,t),r=_n.relativeToMean(_n.radiusAtKm(s)),a=s<=_n.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:s>=_n.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&n.push(a.replace("{distance}",(Math.round(s/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(_n.radiusAtKm(s)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),wp.isIn(e)&&n.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),n.length>0?n.join(" · "):void 0}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=Us.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=Da(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=s),a=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}",a);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}",a):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,Nt.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=Us.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const l=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&l.push(this.messages.skyReentriesMore.replace("{count}",String(a.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 a=n.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}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=Ji("Sun",i.peak.date,t);return n<=Da(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:a,launch:l}=r.peak.object;a!=="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,a)=>a[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=ot(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=ps(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=>Ts.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=Ts.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=this.strikingFireballs(n,this.observerAtStart()).filter(a=>this.fireballTimelineMs(a,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=Fi(this.ufoElement.sighting,0),n=Ji("Sun",e,t),s=Ji("Moon",e,t),r=it.deckLitUntilDeg(it.DECK_HEIGHT_M),a=n.altitudeDeg>-r,l=a?n:s;if(l.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(it.strength(c,i.lowerCloudCover??i.cloudCover,l.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(it.formsAt(l.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??gu;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=Fi(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const n=Ji("Sun",e,t),s=Ji("Moon",e,t),r=n.altitudeDeg>0,a=r?n:s;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const l=i.lowerCloudCover??i.cloudCover;if(Sn.strength(i.precipitationIntensity,l,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Sn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(Sn.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(oo(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Ji("Sun",e,t);if(i.altitudeDeg>nL)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 p=n.zodiacal.sunSeparationDeg<=Ct.CONE_SEPARATION_DEG;s.push((p?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),a=Ji("Moon",e,t),l=n.darkestSkyMagPerArcsec2<sL,c=this.ufoElement.sighting.lightPollution,h=ce.scatteringAt(90-a.altitudeDeg)*ce.moonOutput(ce.phaseAngleOf(oo(e).illuminatedFraction),a.altitudeDeg)*ce.scatteredFraction(90),d=ce.artificialZenithNanolamberts(c)>h;if(l&&a.altitudeDeg>0&&!d){const p=Math.round(oo(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=ce.artificialZenithNanolamberts(c)>ce.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=Ji("Sun",e,t),n=Ji("Moon",e,t);return ce.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:ce.phaseAngleOf(oo(e).illuminatedFraction),altitudeDeg:n.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new Ct;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<mu.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=mu.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=ps(i,t.lng,e.event.utcOffsetHours);if(!n)return;const s=vp.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}=Xs(e,this.ufoElement.currentTime),s=Math.hypot(t,i);if(s===0&&n===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(n-Q6,s)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}updatePresetButtons(){for(const e of gM)this.presetButtons[e]?.setAttribute("aria-pressed",String(e===this.currentAppearance.presetId))}get samplingRate(){return Number(this.samplingRateInput.value)}buildPrototype(e=this.defaultBounds()){return yv(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-_l.width/2,y:e.height/2-_l.height/2,width:_l.width,height:_l.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 l6(this.ufoElement.sighting.timeline,new c6(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=Is.preferencesFor(this);this.preferences=t;const i=yh(t,Sh),n=this.narrativeProvider.localize?.(i),[s,r,a]=i==="en"?[ka,{},void 0]:await Promise.all([NM(i),AS(i),FM(i)]);if(await n,e!==this.localeToken)return;const l=i!==this.language;this.language=i,this.naming=new gp(a),this.said=new zn(t),this.tagNames=new km(r),s!==this.messages?this.applyMessages(s):(this.paramSummaryBuilder=new $l(s,this.naming,this.said,this.tagNames,{messages:s,locale:this.language}),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===jc&&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.shadow.getElementById("label-account-view").textContent=e.accountView,this.accountViewSelect.options[0].textContent=e.accountView2d,this.accountViewSelect.options[1].textContent=e.accountView3d,this.accountViewSelect.title=e.accountViewHint,this.durationInput.placeholder=e.durationPlaceholder,this.durationElement.messages=e,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.shadow.getElementById("observer-identity-hint").textContent=e.identityHint,this.shadow.getElementById("identity-ask-initials").textContent=e.identityInitials,this.shadow.getElementById("identity-ask-keep").textContent=e.identityKeep,this.shadow.getElementById("identity-ask-back").textContent=e.identityBack,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.labelObserverBirth.textContent=e.observerBirth,this.perceptionSettings.labels=e.observerPerception,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.startDate.hint=e.observationTimeHint,this.obsEndTimeInput.placeholder=e.edtfPlaceholder,this.endDate.hint=e.observationEndTimeHint,this.presetsGroup.setAttribute("aria-label",e.presetsGroupLabel),this.labelDecorGroup.textContent=e.decor,this.decorList.setKinds([{value:"building",label:e.decorBuilding},{value:"tree",label:e.decorTree},{value:"shrub",label:e.decorShrub},{value:"bridge",label:e.decorBridge},{value:"wire",label:e.decorWire},{value:"crop",label:e.decorCrop},{value:"terrace",label:e.decorTerrace},{value:"mound",label:e.decorMound},{value:"wall",label:e.decorWall},{value:"streetlight",label:e.decorStreetlight},{value:"vehicle",label:e.decorVehicle},{value:"aircraft",label:e.decorAircraft},{value:"entity",label:e.decorEntity},{value:"observer",label:e.decorObserver,hidden:!0}]),this.decorList.setLabels({list:e.decor,remove:e.deleteDecor,add:e.addDecor,actions:{"look-at-decor":e.lookAtDecor}}),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.undoButton.title=e.undo,this.undoButton.setAttribute("aria-label",e.undo),this.redoButton.title=e.redo,this.redoButton.setAttribute("aria-label",e.redo),this.contextViewAccountButton.textContent=e.viewAccount,this.labelContextMasks.textContent=`${e.masks} ▸`,this.addDecorObserverButton.textContent=e.addObserver,this.surroundings.setMessages(e),this.labelScenerySource.textContent=e.surveySource,this.labelSceneryRadius.textContent=e.surveyRadius,this.sceneryRadius.title=e.surveyRadiusTitle,this.scenerySource.title=e.surveySourceTitle;const t=this.shadow.getElementById("option-scenery-none");t&&(t.textContent=e.surveySourceNone),this.sceneryStatus.setAttribute("aria-label",e.surveyLabel),this.refreshSceneryWarning(),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.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),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.labelLaunchesSubgroup.textContent=e.launchesSubgroup,this.bodyEditor?.setLanguage(this.language),this.labelTemporalGroup.textContent=e.temporalGroup,this.labelFileGroup.textContent=e.fileGroup,this.labelLocationGroup.textContent=e.locationGroup,this.labelObservationGroup.textContent=e.observationGroup,this.labelObserverGroup.textContent=e.observerGroup,this.labelWeatherGroup.textContent=e.weather,this.startDate.messages=e,this.endDate.messages=e,this.birthDate.messages=e,this.paramSummaryBuilder=new $l(e,this.naming,this.said,this.tagNames,{messages:e,locale:this.language}),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.labelRareIce.textContent=e.rareIceCrystals,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.labelFilter.textContent=e.filter,this.refreshFilterOptions(),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;if(!this.beginBodyHandleDrag(t)&&!this.beginBodyDrag(e)){const d=this.decorMoveAxis(e)==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;this.beginCameraDrag(t,u?.kind==="decor"?u.id:void 0,u?.kind==="body"?u.id:void 0)}return}const n=this.decorMoveAxis(e);if(i==="decor"&&n&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,n))return;const s=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",l=i==="shape";if(l)if(this.selectedSourceIds.size>1){const d=new qp(this.selectedMembers()),u=kt.hitTestHandle({bounds:d.bounds(),angle:0},t);if(u==="rotate"){if(a)return;this.dragState={kind:"group-rotate",group:d,startPointer:t},this.startDragListening();return}if(u){if(a)return;this.dragState={kind:"group-resize",group:d,handle:u},this.startDragListening();return}}else{const d=s.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?kt.hitTestVertex(d,t):void 0;if(d?.kind==="polygon"&&u!==void 0){if(a)return;this.dragState={kind:"vertex",sourceId:this.currentSourceId,original:d,vertexIndex:u},this.startDragListening();return}const p=d&&kt.hitTestHandle(d,t);if(d&&p){if(a)return;this.beginDrag(p==="rotate"?"rotate":"resize",this.currentSourceId,d,t,p);return}}const c=this.ufoElement.shapeAt(t.x,t.y,dM);if(!c){const d=n==="ground"?this.ndcOf(e):void 0,u=d?this.sceneElement.pickAt(d.x,d.y):void 0;if(u?.kind==="body"&&u.id!==void 0){a?this.showBody(u.id):this.beginCameraDrag(t,void 0,u.id);return}const p=u?.kind==="decor"?u.id:void 0;if(p!==void 0){a?(this.selectDecor(p),this.revealDecorPanel()):this.beginCameraDrag(t,p);return}a||this.beginCameraDrag(t);return}if(this.revealShapePanel(),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!l)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:s.getInterpolatedShapeAt(r,d)??c.shape}));this.dragState={kind:"move",sources:h,startPointer:t},this.startDragListening()}showBody(e){if(this.fileSyncActive()){this.showInFile(this.bodyPath(e));return}this.revealShapePanel();const t=this.subgroupTabs.find(i=>i.getAttribute("aria-controls")==="shape-bodies");t&&this.openSubgroup(t),this.loadBodyEditor().then(i=>i.show(e))}revealDecorPanel(){if(this.fileSyncActive()){this.fileFocus="decor",this.syncCanvasMode();return}const e=this.groupTabs.find(t=>t.getAttribute("aria-controls")==="group-decor");e&&this.toggleGroup(e,!0)}revealShapePanel(){if(this.fileSyncActive()){this.fileFocus="shape",this.syncCanvasMode();return}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.isGroupIdOpen("group-file")&&(this.fileFocus="shape"),this.refreshSourceList(),this.onSelectionOrTimeChanged(),this.showInFile(this.shapePath(e)))}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,a)=>s.indexOf(r)-s.indexOf(a)).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,a=s?.kind==="polygon"&&kt.hitTestVertex(s,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,dM);if(a){this.selectedSourceIds.has(a.sourceId)||this.selectUnit(a.sourceId),this.currentSourceId=a.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(p=>this.selectedSourceIds.has(p)),s=i.length<=n.length,r=n.length>0&&i.slice(i.length-n.length).every(p=>this.selectedSourceIds.has(p)),a=n.length>0&&i.slice(0,n.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=s||r,this.contextSendToBackButton.disabled=s||a,this.contextBringToFrontButton.title=s?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=s?this.messages.onlyOneShape:a?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?kt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=WM;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="";const t=[...this.ufoElement.sighting.timeline.sourceIds],i=this.ufoElement.sighting.interpretation?.bodies??[];if(t.length===0&&i.length===0){const n=document.createElement("span");n.className="submenu-empty",n.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(n)}for(const n of t){const s=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(n)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,n,r.checked)),s.appendChild(r),s.appendChild(document.createTextNode(this.shapeLabel(n))),this.contextMasksSubmenu.appendChild(s)}for(const n of i){const s=this.sceneElement.bodyMaskedBy(n.id,e.id);if(s===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(n.title)??n.id,l=this.messages;r.textContent=`${a} — ${s>=.995?l.masksBodyFully:s>.005?l.masksBodyPartly.replace("{share}",String(Math.round(s*100))):l.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}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(a=>a!==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=kt.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=kt.hitTestVertex(i,e);if(n===void 0)return;const s=kt.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;return this.canvasBoundsOf(e===void 0?void 0:this.sceneElement.bodyScreenBox(e))}canvasBoundsOf(e){if(!e)return;const t=this.ufoElement.canvasElement,i=Math.max(uM,(e.maxX-e.minX)/2*t.width),n=Math.max(uM,(e.maxY-e.minY)/2*t.height),s=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:s-i/2,y:r-n/2,width:i,height:n}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),n=e.reading();if(!i||!n)return!1;const s=kt.hitTestHandle({bounds:i,angle:0},t);if(!s)return!1;if(s==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...n.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:s,centre:r,startPointer:t,startSizeM:{...n.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(s,0)),this.startDragListening(),!0}beginBodyHandleDrag(e){return this.beginFrameDrag(this.bodyFrame,e)}onFrameDragPointerMove(e){const t=this.dragState,i=this.canvasPointFromEvent(e);if(!i||!t)return;if(t.kind==="frame-rotate"){const u=(i.x-t.startPointer.x)*t.target.rotateDegPerPx,p=(t.startPointer.y-i.y)*t.target.rotateDegPerPx,f=t.startAttitude;t.target.turnTo(e.shiftKey?{headingDeg:f.headingDeg,pitchDeg:f.pitchDeg+p,rollDeg:f.rollDeg+u}:{headingDeg:f.headingDeg+u,pitchDeg:f.pitchDeg,rollDeg:f.rollDeg});return}if(t.kind!=="frame-resize")return;const{centre:n,startPointer:s,startSizeM:r,handle:a}=t,l=(u,p)=>Math.max(.05,Math.abs(u)/Math.max(1,Math.abs(p))),c=a==="e"||a==="w",h=a==="n"||a==="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));t.target.resize({widthM:h?r.widthM:r.widthM*d,lengthM:h?r.lengthM:r.lengthM*d,heightM:c?r.heightM:r.heightM*d})}bodyFrame={bounds:()=>this.bodyCanvasBounds(),reading:()=>this.bodyEditor?.readingNow(),resize:e=>this.bodyEditor?.resize(e),turnTo:e=>this.bodyEditor?.turnTo(e),rotateDegPerPx:Sm};decorFrame={bounds:()=>this.decorCanvasBounds(),reading:()=>this.decorReading(),resize:e=>this.commitDecorBase(t=>{Object.assign(t,{sizeM:{widthM:this.roundedMeters(e.widthM),lengthM:this.roundedMeters(e.lengthM),heightM:this.roundedMeters(e.heightM)}})},"sizeM.widthM"),turnTo:e=>this.commitDecorBase(t=>{t.headingDeg=this.rounded((e.headingDeg%360+360)%360)},"headingDeg"),rotateDegPerPx:Z6};decorReading(){const e=this.editableDecor();if(e===void 0)return;const t=Ue.naturalSize(e.kind,e.floors);return{sizeM:{widthM:e.sizeM?.widthM??t.widthM??1,lengthM:e.sizeM?.lengthM??t.lengthM??1,heightM:e.sizeM?.heightM??t.heightM??1},attitude:{headingDeg:Gr.viewOf(e,this.ufoElement.currentTime).headingDeg,pitchDeg:0,rollDeg:0}}}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)))}editableDecor(){const e=this.ufoElement.sighting.decor.find(t=>t.id===this.currentDecorId);return e&&e.observerSide===void 0?e:void 0}decorCanvasBounds(){const e=this.editableDecor();return e?this.canvasBoundsOf(this.sceneElement.decorScreenBox(e.id)):void 0}paintDecorOverlay=e=>{const t=this.decorCanvasBounds();t&&e.paintGroupHandles(t)};decorMoveAxis(e){if(!(e.metaKey||[e.shiftKey,e.altKey,e.ctrlKey].filter(Boolean).length>1))return e.shiftKey?"east":e.altKey?"north":e.ctrlKey?"up":"ground"}grabsDecor(e,t,i){const n=this.pickDecorAt(e);if(n===i.id)return!0;const s=this.decorCanvasBounds();return s!==void 0&&t.x>=s.x&&t.x<=s.x+s.width&&t.y>=s.y&&t.y<=s.y+s.height?n===void 0||this.ufoElement.sighting.decor.find(a=>a.id===n)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const n=this.editableDecor();if(!n)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(!this.grabsDecor(e,t,n))return!1;const s=this.ndcOf(e),r=Gr.viewOf(n,this.ufoElement.currentTime),a=s?this.sceneElement.decorGrabHeightAt?.(n.id,s.x,s.y)??0:0,l=s&&this.sceneElement.decorGroundPointAt(n.id,s.x,s.y,a);return!s||!l?!1:(this.dragState={kind:"decor-move",id:n.id,startGround:l,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:s.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(n.id)??0,startEastM:r.eastM,startNorthM:r.northM},this.setCanvasCursor("move"),this.startDragListening(),!0)}onDecorMovePointerMove(e){const t=this.dragState;if(t?.kind!=="decor-move")return;const i=this.ndcOf(e);if(!i)return;const n=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!n&&t.axis!=="up"||this.commitDecorBase(s=>{n&&(t.axis==="ground"||t.axis==="east")&&(s.eastM=this.roundedMeters(t.startEastM+n.x-t.startGround.x)),n&&(t.axis==="ground"||t.axis==="north")&&(s.northM=this.roundedMeters(t.startNorthM-(n.z-t.startGround.z))),t.axis==="up"&&(s.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const n=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:n?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:n?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:n},n||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&Fa(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&Fa(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==="frame-resize"||this.dragState?.kind==="frame-rotate"){this.onFrameDragPointerMove(e);return}if(this.dragState?.kind==="decor-move"){this.onDecorMovePointerMove(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,a=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+a}}}));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,a=kt.moveVertex(s,r,t);this.commitShapes(i,[{sourceId:n,shape:a}])}else{const{kind:n,sourceId:s,original:r,handle:a}=this.dragState,l=n==="resize"?kt.resizeShape(r,a,t):kt.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)<j6)return;this.cameraDragState.moved=!0}const a=n+(t.x-i.x)*Sm,l=Math.max(-90,Math.min(90,s-(t.y-i.y)*Sm));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=l,this.sceneElement.setIndoorLook(a,l),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),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(Ta,i.width-ua);break;case"ArrowRight":i.width+=ua;break;case"ArrowUp":i.height=Math.max(Ta,i.height-ua);break;case"ArrowDown":i.height+=ua;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=ua;break;case"ArrowRight":i.x+=ua;break;case"ArrowUp":i.y-=ua;break;case"ArrowDown":i.y+=ua;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 qp(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&&kt.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}if(i==="decor"&&r&&this.decorMoveAxis(e)){const l=this.decorCanvasBounds(),c=l&&kt.hitTestHandle({bounds:l,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const l=kt.hitTestHandle({bounds:new qp(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"&&kt.hitTestVertex(l,t)!==void 0)return"vertex";const c=l&&kt.hitTestHandle(l,t);if(l&&c)return this.cursorForHandle(c,l.angle)}return n.hitTest(s,t.x,t.y)?r&&a?"move":"select":this.pickDecorAt(e)!==void 0?r?"pan":"select":r?"pan":void 0}cursorForHandle(e,t){return e==="rotate"?"rotate":`resize-${kt.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(MM(this.buildPrototype({x:0,y:0,width:_l.width,height:_l.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 rL={stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},vM="rr0-sighting-editor",yM="rr0-ufo-recorder";class aL extends Nt{}function G2(){kM(),f6(),u6(),v6(),Cp(),customElements.get(vM)||customElements.define(vM,Nt),customElements.get(yM)||customElements.define(yM,aL)}const rg={event:"Event",accountOf:"Observation of",passagesHeading:"Reported in",interviewOf:"Interview of",untitledInterview:"Interview {n}",deleteInterviewQuestion:"Delete this interview from the case? Nothing is written until the case is saved.",untitledReading:"Reading {n}",untitledObservation:"Observation {n}",deleteRecording:"Delete this recording from the case",deleteReadingQuestion:"Delete this reading? Nothing is written until the case is saved.",deleteObservationQuestion:"Delete this observation from the case? Nothing is written until the case is saved.",deleteRefused:"This observation is interpreted by {n} reading(s): delete them first.",titleField:"Title of the interpretation",authorField:"Author",addTitle:"Add an event",kindField:"Type",kindObservation:"Observation",kindInterview:"Interview",witnessField:"Witness",mediumField:"Medium",interviewerField:"Interviewer",plainTitleField:"Title",sourceField:"Source",sourceBlank:"A blank recording",sourceFile:"A JSON file",sourceUrl:"An address",observerField:"Observer",fileField:"File",urlField:"Address",loadFailed:"That recording could not be read.",isACase:"That is a case, not a recording.",ok:"OK",cancel:"Cancel",caseHeading:"Case",caseId:"ID",recordingId:"ID",idTaken:"Another recording of the case has this ID.",idInvalid:"An ID is made of letters, digits, hyphens and underscores, and starts with a letter or a digit.",idNeeded:"A reading names this recording by its ID: it cannot be left empty.",idDuplicated:"Two events of the case have the ID “{id}”: a reading that names it is ambiguous.",readingUnresolved:"A reading names “{id}”, which no event of the case has as its ID, nor any recording it lists.",caseTitle:"Title",caseTime:"When",eventsTab:"Events",fileTab:"File",importFile:"Load JSON file",importUrl:"Or load from URL",importButton:"Load",fileNotACase:"That file is not a case (it has no events).",fileInvalid:"This text is not valid JSON yet, or not a case: the case keeps what it last understood.",fileLoading:"Loading the editor…",add:"Add",addHint:"Add an event",interpretationOf:"Interpretation of",interpretationOfNone:"—",exportButton:"Save",exportTitle:"Save the case",exportAlso:"Also save the observations",addToCase:"Add to a case",unsavedChanges:"Changes not saved",discardQuestion:"Some changes are not saved yet. Load anyway and lose them?",discardTitle:"Unsaved changes",discardOk:"Load anyway",leaveQuestion:"Some changes are not saved yet. Leave anyway and lose them?",leaveOk:"Leave anyway"},oL=Object.freeze(Object.defineProperty({__proto__:null,caseEditorMessages_en:rg},Symbol.toStringTag,{value:"Module"})),bM="rr0-case-editor",lL=`
10000
10063
  <style>
10001
10064
  :host { display: block; }
10002
10065
  /* The colours of the file's text editor (see SightingFileEditor): a key, a string, a number or a word, and a mistake. Dark mode redefines them. */
@@ -10091,7 +10154,7 @@ rr0-duration-input [hidden] { display: none !important; }
10091
10154
  <div id="passages" class="passages" hidden><ul id="passages-list"></ul></div>
10092
10155
  </section>
10093
10156
  <section id="interview-section" class="recording" hidden>
10094
- <rr0-interview id="interview"></rr0-interview>
10157
+ <rr0-interview-editor id="interview"></rr0-interview-editor>
10095
10158
  </section>
10096
10159
  </section>
10097
10160
  <section class="group-panel" id="group-case-file" aria-labelledby="label-case-file-group" hidden>
@@ -10136,4 +10199,4 @@ rr0-duration-input [hidden] { display: none !important; }
10136
10199
  </form>
10137
10200
  </dialog>
10138
10201
  `;class Xl extends HTMLElement{shadow=this.attachShadow({mode:"open"});editor;session;current;currentInterview;interviewElement;interviewReady;group="events";fileEditor;fileEditorLoading;fileApplied="";editorMessages=ka;messages=rg;said=new zn(["en"]);localeToken=0;language="en";dialogMode="add";pendingLoad;dirtyTimer;caseDate;dateModeFor;constructor(){super(),G2(),kM(),this.shadow.innerHTML=lL,customElements.upgrade(this.shadow),this.shadow.getElementById("case-date").build(),this.editor=this.shadow.getElementById("editor"),this.interviewElement=this.shadow.getElementById("interview"),this.interviewElement.addEventListener(vS,t=>this.interviewChanged(t.detail)),this.interviewElement.addEventListener(yS,t=>void this.followToObservation(t.detail)),this.editor.addEventListener("caseloaded",t=>{t.preventDefault();const{json:i,url:n}=t.detail;this.openCase(i,n??location.href)}),this.editor.addEventListener("recordingloaded",()=>this.closeCase()),this.editor.guardsLeaving=!1,this.editor.addEventListener("beforeload",t=>{this.dirty&&(t.preventDefault(),this.pendingLoad=t.detail.proceed,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion))});for(const t of["input","change","datechange","click","pointerup","keyup"])this.shadow.addEventListener(t,()=>this.scheduleDirtyCheck(),!0);for(const[t,i]of[["case-id","id"],["case-title","title"]])this.input(t).addEventListener("input",()=>this.writeCaseField(i,this.input(t).value));this.caseDate=this.byId("case-date"),this.caseDate.addEventListener("datechange",t=>{const{time:i}=t.detail;this.writeCaseField("time",i?Xl.rr0TimeOf(Ao(i)):"")}),this.byId("track").addEventListener("change",()=>{const t=this.session?this.items(this.session)[Number(this.byId("track").value)]:void 0;t&&(t.interview?this.showInterview(t.interview):this.showTrack(t.track))});const e=this.input("recording-id");e.addEventListener("input",()=>this.writeRecordingId()),e.addEventListener("blur",()=>{this.showRecordingIdError(void 0),this.refreshRow()});for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.addEventListener("click",()=>this.openGroup(t.getAttribute("aria-controls")==="group-case-file"?"file":"events"));this.byId("import-file").addEventListener("change",()=>void this.importFromFile()),this.byId("import-url-button").addEventListener("click",()=>void this.importFromUrl()),this.byId("add").addEventListener("click",()=>this.askAdd()),this.byId("make-case").addEventListener("click",()=>this.makeCase()),this.byId("delete").addEventListener("click",()=>this.askDelete()),this.byId("export").addEventListener("click",()=>this.askExport()),this.byId("source").addEventListener("change",()=>this.syncSourceFields()),this.byId("kind").addEventListener("change",()=>this.syncSourceFields()),this.byId("of").addEventListener("change",()=>this.syncSourceFields()),this.byId("cancel").addEventListener("click",()=>this.closeDialog()),this.byId("dialog").addEventListener("close",()=>{this.pendingLoad=void 0}),this.byId("form").addEventListener("submit",t=>{t.preventDefault(),this.submitDialog()})}static get observedAttributes(){return["src"]}attributeChangedCallback(e,t,i){e==="src"&&i&&this.editor.setAttribute("src",i)}warnBeforeLeaving=e=>{this.leaving||!this.dirty||(e.preventDefault(),e.returnValue="")};disconnectedCallback(){document.removeEventListener("click",this.askBeforeFollowing,!0),window.removeEventListener("beforeunload",this.warnBeforeLeaving),window.clearTimeout(this.dirtyTimer)}get dirty(){return this.session?(this.commit(),this.session.dirty):this.editor.dirty}scheduleDirtyCheck(){window.clearTimeout(this.dirtyTimer),this.dirtyTimer=window.setTimeout(()=>this.refreshDirty(),600)}refreshDirty(){const e=this.session;e&&this.commit(),this.byId("dirty").hidden=!(e&&e.dirty);const t=e?this.current!==void 0&&e.changed(this.current):this.editor.dirty;this.byId("recording-dirty").hidden=!t}leaving=!1;askBeforeFollowing=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;const t=e.composedPath().find(n=>n instanceof HTMLAnchorElement);if(!t||!t.href||t.target&&t.target!=="_self"||t.hasAttribute("download"))return;const i=new URL(t.href,location.href);i.href===location.href||i.origin===location.origin&&i.pathname===location.pathname&&i.search===location.search&&i.hash!==""||this.dirty&&(e.preventDefault(),e.stopPropagation(),this.pendingLoad=()=>{this.leaving=!0,location.assign(i.href)},this.openDialog("discard",this.messages.discardTitle,this.messages.leaveQuestion,this.messages.leaveOk))};connectedCallback(){document.addEventListener("click",this.askBeforeFollowing,!0),window.addEventListener("beforeunload",this.warnBeforeLeaving);const e=this.getAttribute("src");e&&this.editor.getAttribute("src")!==e&&this.editor.setAttribute("src",e),this.loadLocale()}get sightingData(){return this.editor.sightingData}set sightingData(e){this.closeCase(),this.editor.sightingData=e}get sightingEditor(){return this.editor}get caseSession(){return this.session}byId(e){return this.shadow.getElementById(e)}async loadLocale(){const e=++this.localeToken,t=Is.preferencesFor(this),i=yh(t,Sh),[n,s]=i==="en"?[rg,ka]:await Promise.all([RS(i),NM(i)]);e===this.localeToken&&(this.said=new zn(t),this.language=i,this.messages=n,this.caseDate.messages=s,this.editorMessages=s,this.applyMessages(),this.refreshRow())}applyMessages(){const e=this.messages,t=(s,r)=>{this.byId(s).textContent=r};t("case-heading",e.caseHeading),t("label-case-id",e.caseId),t("label-case-title",e.caseTitle),t("label-case-time",e.caseTime),t("label-events-group",e.eventsTab),t("label-case-file-group",e.fileTab),t("label-import-file",e.importFile),t("label-import-url",e.importUrl),t("import-url-button",e.importButton),this.byId("track").setAttribute("aria-label",e.event),t("label-kind",e.kindField),t("label-witness",e.witnessField),t("label-medium",e.mediumField),t("label-recording-id",e.recordingId),t("make-case",e.addToCase);for(const s of["dirty","recording-dirty"])this.byId(s).title=e.unsavedChanges,this.byId(s).setAttribute("aria-label",e.unsavedChanges);t("add","+"),t("export",e.exportButton),t("label-export-recordings",e.exportAlso),t("label-title",e.titleField),t("label-author",e.authorField),t("label-date",e.caseTime),t("label-of",e.interpretationOf),t("label-source",e.sourceField),t("label-observer",e.observerField),t("label-file",e.fileField),t("label-url",e.urlField),t("ok",e.ok),t("cancel",e.cancel);const i=this.byId("source");[e.sourceBlank,e.sourceFile,e.sourceUrl].forEach((s,r)=>{i.options[r].textContent=s});const n=this.byId("kind");[e.kindObservation,e.kindInterview].forEach((s,r)=>{n.options[r].textContent=s}),this.byId("add").title=e.addHint,this.byId("add").setAttribute("aria-label",e.addHint),this.byId("delete").title=e.deleteRecording,this.byId("delete").setAttribute("aria-label",e.deleteRecording)}openGroup(e){this.group=e;for(const t of this.shadow.querySelectorAll("#case-tabs .group-tab"))t.setAttribute("aria-expanded",String(t.getAttribute("aria-controls")===(e==="file"?"group-case-file":"group-events")));e==="file"?this.loadFileEditor().then(()=>this.syncFileEditor(),()=>this.showFileNote(this.messages.loadFailed)):this.leaveFile(),this.refreshRow()}applySections(){const e=this.session,t=e===void 0||this.group==="events";this.byId("events-row").hidden=e===void 0,this.byId("group-events").hidden=!t,this.byId("group-case-file").hidden=e===void 0||this.group!=="file",this.byId("recording").hidden=this.currentInterview!==void 0,this.byId("interview-section").hidden=this.currentInterview===void 0}showFileNote(e){const t=this.byId("case-file-note");t.textContent=e??"",t.hidden=e===void 0}fileText(){return this.session?JSON.stringify(this.session.json,null,2)+`
10139
- `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([_e(()=>import("./SightingFileEditor-C0NC8jbz.js"),__vite__mapDeps([6,7]),import.meta.url),_e(()=>import("./caseSchema-BDFgjA8v.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,n=>this.onFileEdited(n),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid);return}if(!Ci.isCase(i)){this.showFileNote(this.messages.fileInvalid);return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(){const e=this.input("import-file"),t=e.files?.[0];if(t){try{const i=JSON.parse(await t.text());this.guarded(()=>void this.importCase(i,new URL("case.json",location.href).href))}catch{this.showFileNote(this.messages.loadFailed)}e.value=""}}async importFromUrl(){const e=this.input("import-url").value.trim();if(e!=="")try{const t=new URL(e,location.href).href,i=await ho.json(t);this.guarded(()=>void this.importCase(i,t))}catch{this.showFileNote(this.messages.loadFailed)}}async importCase(e,t){if(!Ci.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t)}catch{this.showFileNote(this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t){const i=new xh(e,t);if(i.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=i,this.current=void 0;const n=this.getAttribute("track"),s=n?new URL(n,t).href:void 0,r=i.tracks.find(a=>a.url===s)??i.tracks.find(a=>a.kind==="observer")??i.tracks[0];await this.showTrack(r)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=await ho.json(e.url),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.byId("passages").hidden=!0;try{const i=!e.recording;await this.loadTrack(e);const n=t.accountOf(e);n&&await this.loadTrack(n),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&n?.recording?Xl.shapesOf(n.recording):void 0,this.editor.sightingData=structuredClone(e.recording),i&&t.keep(e,this.editor.sightingData,!0),n&&n.loaded===void 0&&t.keep(n,n.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e)}}passagesToken=0;async transcriptOf(e){const t=this.session;if(t)try{const i=t.transcriptText(e);if(i!==void 0)return JSON.parse(i);if(e.url)return await ho.json(new URL(e.url,t.url??location.href).href)}catch{}}async showPassages(e){const t=this.session,i=this.byId("passages"),n=++this.passagesToken;if(i.hidden=!0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await _e(async()=>{const{InterviewFile:c}=await import("./interviewJson-78rX1Ar1.js");return{InterviewFile:c}},[],import.meta.url);if(n!==this.passagesToken)return;const r=e.event.id??t.proposedId(e),a=[];for(const c of t.interviews){const h=await this.transcriptOf(c);if(!h||!Array.isArray(h.segments))continue;const d={...h,interviewOf:h.interviewOf??c.interviewOf};for(const u of s.passagesAbout(d,r))a.push({interview:c,json:h,passage:u})}if(n!==this.passagesToken||this.current!==e||a.length===0)return;this.byId("passages-list").replaceChildren(...a.sort((c,h)=>c.passage.at-h.passage.at).map(({interview:c,json:h,passage:d})=>{const u=document.createElement("li"),p=document.createElement("button");p.type="button",p.className="at",p.textContent=`▶ ${s.clock(d.at,!0)}`,p.addEventListener("click",()=>this.editor.seekTo(d.at));const f=document.createElement("button");f.type="button",f.className="excerpt";const m=this.items(t).findIndex(M=>M.interview===c),v=`${this.messages.passagesHeading} ${this.optionLabel({interview:c},m)}`,b=d.text===void 0?"":d.range?d.text.slice(d.range[0],d.range[1]):d.text;return f.textContent=b===""?v:`${s.speakerName(h,d.speaker)} : « ${b.length>120?`${b.slice(0,117)}…`:b} »`,f.title=v,f.addEventListener("click",()=>{this.showInterview(c).then(()=>this.interviewElement.revealSegment(d.index))}),u.append(p,f),u})),i.hidden=!1}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");i&&(await this.showTrack(i),this.editor.seekTo(e.at),this.editor.showRender())}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const n of i.shapes??[])t.add(n.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),a=r.length>0?r.map(l=>this.labelOf(l,i.tracks.indexOf(l))).join(", "):this.said.read(e.interview.title);return a?`${this.messages.interviewOf} ${a}`:this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1))}const n=e.track,s=this.labelOf(n,t);return n.kind==="observer"?`${this.messages.accountOf} ${s}`:s}async showInterview(e){const t=this.session;t&&(this.commit(),this.current=void 0,this.passagesToken++,this.byId("passages").hidden=!0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i))})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e))}ensureInterview(){return this.interviewReady??=_e(async()=>{const{register:e}=await import("./InterviewElement-wiGHrsHB.js");return{register:e}},__vite__mapDeps([12,13,14,15]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,n=this.currentInterview;if(!(!i||!n)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(n,e.text);for(const s of[n.interviewOf].flat()){const r=i.tracks.find(a=>a.kind==="observer"&&(a.event.id??i.proposedId(a))===s);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const n=this.session.tracks.filter(s=>s.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(n||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time?Xl.rr0TimeOf(Ao(e.time)):void 0,i=this.said.read(e.observer?.title),n=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=xh.around(e,t,i,n,location.href),this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:eu(Xl.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const n=this.input("case-time");n.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&ln.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("recording").classList.toggle("in-case",e!==void 0),this.byId("interview-section").classList.toggle("in-case",e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[r,a]of[["case-id","id"],["case-title","title"]]){const l=this.input(r);l!==t&&(l.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),n=this.items(e);i.replaceChildren(...n.map((r,a)=>new Option(this.optionLabel(r,a),String(a))));const s=this.currentInterview?n.findIndex(r=>r.interview===this.currentInterview):this.current?n.findIndex(r=>r.track===this.current):0;i.value=String(Math.max(0,s)),this.byId("delete").hidden=this.currentInterview===void 0&&e.tracks.length<=1,this.refreshRecordingId(e),this.refreshDirty()}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const l=this.input("recording-id");this.shadow.activeElement!==l&&(l.value=t.event.id??""),l.placeholder=e.proposedId(t)}const{duplicateIds:n,unresolved:s}=e.problems(),r=[...n.map(l=>this.messages.idDuplicated.replace("{id}",l)),...s.map(({reference:l})=>this.messages.readingUnresolved.replace("{id}",l))],a=this.byId("case-problems");a.hidden=r.length===0,a.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,n){this.dialogMode=e,this.byId("dialog-title").textContent=t;const s=this.byId("dialog-message");s.textContent=i??"",s.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=n??(e==="discard"?this.messages.discardOk:this.messages.ok),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}closeDialog(){this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle);const t=this.byId("of");t.replaceChildren(new Option(this.messages.interpretationOfNone,""),...e.tracks.filter(n=>n.kind==="observer").map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),t.value="",this.byId("kind").value="observation";const i=e.tracks.filter(n=>n.kind==="observer");this.byId("witness").replaceChildren(...i.map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const n of["observer","title","author","file","url"])this.input(n).value="";this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await _e(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value==="interview",t=this.byId("source").value,i=!e&&this.byId("of").value!=="";this.byId("row-source").hidden=e,this.byId("row-of").hidden=e,this.byId("row-witness").hidden=!e,this.byId("row-medium").hidden=!e,e&&this.fillMedia(),this.byId("row-file").hidden=e||t!=="file",this.byId("row-url").hidden=e||t!=="url",this.byId("row-observer").hidden=e||i,this.byId("row-title").hidden=!(e||i),this.byId("row-author").hidden=!(e||i),this.byId("label-title").textContent=e?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=e?this.messages.interviewerField:this.messages.authorField}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const u=e.tracks[Number(this.byId("witness").value)],p=this.input("title").value.trim(),f=this.input("author").value.trim(),g=e.addInterview(u,this.input("date").value||this.today(),p!==""?p:void 0,f!==""?f.split(",").map(m=>({people:m.trim()})).filter(m=>m.people!==""):void 0,this.byId("medium").value);return await this.showInterview(g),!0}const t=this.byId("of").value,i=t===""?void 0:e.tracks[Number(t)],n=this.byId("source").value;if(i&&n==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const u=this.input("title").value.trim(),p=this.input("author").value.trim(),f=e.addReading(i,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?[{title:p}]:void 0);return this.showTrack(f),!0}const s=this.input("observer").value.trim(),r=this.input("date").value.trim();let a;try{if(n==="blank"){const u=(s||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";a={version:1,id:`${r?`${r}-`:""}${u}`,...s?{observer:{title:s}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const u=n==="file"?await this.readFile():await ho.json(this.input("url").value.trim());if(Ci.isCase(u))return this.showError(this.messages.isACase),!1;a=u,s&&!a.observer?.title&&(a={...a,observer:{...a.observer,title:s}})}}catch{return this.showError(this.messages.loadFailed),!1}const l=(i?this.input("title").value:s).trim(),c=l!==""?l:this.said.read(a.observer?.title),h=this.input("author").value.trim(),d=e.addObservation(a,r!==""?r:void 0,c,i?{account:i,by:h!==""?[{title:h}]:void 0}:void 0);return this.showTrack(d),!0}async readFile(){const e=this.input("file").files?.[0];if(!e)throw new Error("No file");const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsText(e)});return JSON.parse(t)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(a=>a.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const n=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,n&&this.showTrack(n))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const a of t.tracks)await this.loadTrack(a)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:n,strToU8:s}=await _e(async()=>{const{zipSync:a,strToU8:l}=await import("./browser-_Ncw3Jhn.js");return{zipSync:a,strToU8:l}},[],import.meta.url),r={};for(const a of i)r[a.path]=s(a.content);return this.download(new Blob([n(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.click(),URL.revokeObjectURL(i)}}function cL(){G2(),customElements.get(bM)||customElements.define(bM,Xl)}cL();export{IL as $,Oo as A,k2 as B,sy as C,kl as D,Im as E,ts as F,Lt as G,Is as H,vS as I,D as J,Lm as K,St as L,Se as M,gh as N,Ll as O,Gs as P,ps as Q,Et as R,zn as S,As as T,Sh as U,Ls as V,UD as W,Ji as X,TL as Y,bt as Z,_e as _,ho as a,TC as a$,ep as a0,wL as a1,Dt as a2,dr as a3,rA as a4,we as a5,ye as a6,xt as a7,DL as a8,ct as a9,yL as aA,Dn as aB,z1 as aC,ui as aD,SL as aE,_L as aF,Tw as aG,Mr as aH,Jh as aI,ef as aJ,ZE as aK,gt as aL,ei as aM,Wo as aN,Vm as aO,ki as aP,Dr as aQ,iA as aR,Zt as aS,vL as aT,bL as aU,Dw as aV,ML as aW,Ks as aX,Iw as aY,J1 as aZ,Z3 as a_,gL as aa,ne as ab,uE as ac,lt as ad,x0 as ae,hs as af,lu as ag,Qr as ah,Lc as ai,yt as aj,rt as ak,Vn as al,Hn as am,EL as an,Na as ao,Yi as ap,pL as aq,mL as ar,fL as as,Hh as at,AL as au,xL as av,lA as aw,Zu as ax,hn as ay,Uw as az,NM as b,Yu as b0,M0 as b1,un as b2,Nw as b3,Pg as b4,Ng as b5,_t as b6,Ua as b7,zh as b8,yS as c,Ns as d,ci as e,at as f,uL as g,Pa as h,tu as i,hL as j,Dm as k,dL as l,Pn as m,fs as n,q6 as o,av as p,Zf as q,Xs as r,yh as s,Ue as t,Mt as u,Ea as v,dn as w,Jr as x,Tr as y,SA as z};
10202
+ `:""}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const[{SightingFileEditor:e},{default:t}]=await Promise.all([_e(()=>import("./SightingFileEditor-C0NC8jbz.js"),__vite__mapDeps([6,7]),import.meta.url),_e(()=>import("./caseSchema-BDFgjA8v.js"),[],import.meta.url)]),i=this.fileText();return this.fileApplied=i,this.fileEditor=new e(this.byId("case-file-editor"),i,n=>this.onFileEdited(n),this.editorMessages.fileEditorLabel,{baseline:i,phrases:this.editorMessages.fileSearchPhrases,schema:t}),this.fileEditor}catch(e){throw this.fileEditorLoading=void 0,e}finally{this.showFileNote(void 0)}})(),this.fileEditorLoading}syncFileEditor(){if(!this.fileEditor||!this.session)return;this.commit();const e=this.fileText();this.fileApplied=e,this.fileEditor.replaceText(e,!1),this.showFileNote(void 0)}onFileEdited(e){const t=this.session;if(!t)return;if(e===this.fileApplied){this.showFileNote(void 0);return}let i;try{i=JSON.parse(e)}catch{this.showFileNote(this.messages.fileInvalid);return}if(!Ci.isCase(i)){this.showFileNote(this.messages.fileInvalid);return}this.fileApplied=e,this.showFileNote(void 0),JSON.stringify(i)!==JSON.stringify(t.json)&&(t.replaceJson(i),this.current&&!t.tracks.includes(this.current)&&(this.current=void 0),this.currentInterview&&!t.interviews.includes(this.currentInterview)&&(this.currentInterview=void 0),this.refreshRow(),this.scheduleDirtyCheck())}leaveFile(){const e=this.session;if(e)if(this.current===void 0&&this.currentInterview===void 0){const t=e.tracks.find(i=>i.kind==="observer")??e.tracks[0];t&&this.showTrack(t)}else this.currentInterview&&(this.interviewElement.event=this.currentInterview)}guarded(e){if(!this.dirty){e();return}this.pendingLoad=e,this.openDialog("discard",this.messages.discardTitle,this.messages.discardQuestion)}async importFromFile(){const e=this.input("import-file"),t=e.files?.[0];if(t){try{const i=JSON.parse(await t.text());this.guarded(()=>void this.importCase(i,new URL("case.json",location.href).href))}catch{this.showFileNote(this.messages.loadFailed)}e.value=""}}async importFromUrl(){const e=this.input("import-url").value.trim();if(e!=="")try{const t=new URL(e,location.href).href,i=await ho.json(t);this.guarded(()=>void this.importCase(i,t))}catch{this.showFileNote(this.messages.loadFailed)}}async importCase(e,t){if(!Ci.isCase(e)){this.showFileNote(this.messages.fileNotACase);return}try{await this.openCase(e,t)}catch{this.showFileNote(this.messages.fileNotACase);return}this.syncFileEditor(),this.showFileNote(void 0)}async openCase(e,t){const i=new xh(e,t);if(i.tracks.length===0)throw new Error("A case with no recording has nothing to edit");this.session=i,this.current=void 0;const n=this.getAttribute("track"),s=n?new URL(n,t).href:void 0,r=i.tracks.find(a=>a.url===s)??i.tracks.find(a=>a.kind==="observer")??i.tracks[0];await this.showTrack(r)}closeCase(){this.session&&(this.session=void 0,this.current=void 0,this.currentInterview=void 0,this.editor.reading=!1,this.editor.accountShapeIds=void 0,this.refreshRow())}commit(){this.session&&this.current&&this.editor.edited&&this.session.keep(this.current,this.editor.sightingData)}async loadTrack(e){e.recording||(e.recording=await ho.json(e.url),e.loaded=JSON.stringify(e.recording))}async showTrack(e){const t=this.session;if(t){this.commit(),this.currentInterview=void 0,this.byId("passages").hidden=!0;try{const i=!e.recording;await this.loadTrack(e);const n=t.accountOf(e);n&&await this.loadTrack(n),this.current=e,this.editor.documentUrl=e.base?e.base.url:e.url,this.editor.reading=e.kind==="reading",this.editor.accountShapeIds=e.kind==="reading"&&n?.recording?Xl.shapesOf(n.recording):void 0,this.editor.sightingData=structuredClone(e.recording),i&&t.keep(e,this.editor.sightingData,!0),n&&n.loaded===void 0&&t.keep(n,n.recording,!0)}catch{this.showError(this.messages.loadFailed)}this.refreshRow(),this.showPassages(e)}}passagesToken=0;async transcriptOf(e){const t=this.session;if(t)try{const i=t.transcriptText(e);if(i!==void 0)return JSON.parse(i);if(e.url)return await ho.json(new URL(e.url,t.url??location.href).href)}catch{}}async showPassages(e){const t=this.session,i=this.byId("passages"),n=++this.passagesToken;if(i.hidden=!0,!t||e.kind!=="observer"||t.interviews.length===0)return;const{InterviewFile:s}=await _e(async()=>{const{InterviewFile:c}=await import("./interviewJson-CfwBPiuG.js");return{InterviewFile:c}},[],import.meta.url);if(n!==this.passagesToken)return;const r=e.event.id??t.proposedId(e),a=[];for(const c of t.interviews){const h=await this.transcriptOf(c);if(!h||!Array.isArray(h.segments))continue;const d={...h,interviewOf:h.interviewOf??c.interviewOf};for(const u of s.passagesAbout(d,r))a.push({interview:c,json:h,passage:u})}if(n!==this.passagesToken||this.current!==e||a.length===0)return;this.byId("passages-list").replaceChildren(...a.sort((c,h)=>c.passage.at-h.passage.at).map(({interview:c,json:h,passage:d})=>{const u=document.createElement("li"),p=document.createElement("button");p.type="button",p.className="at",p.textContent=`▶ ${s.clock(d.at,!0)}`,p.addEventListener("click",()=>this.editor.seekTo(d.at));const f=document.createElement("button");f.type="button",f.className="excerpt";const m=this.items(t).findIndex(M=>M.interview===c),v=`${this.messages.passagesHeading} ${this.optionLabel({interview:c},m)}`,b=d.text===void 0?"":d.range?d.text.slice(d.range[0],d.range[1]):d.text;return f.textContent=b===""?v:`${s.speakerName(h,d.speaker)} : « ${b.length>120?`${b.slice(0,117)}…`:b} »`,f.title=v,f.addEventListener("click",()=>{this.showInterview(c).then(()=>this.interviewElement.revealSegment(d.index))}),u.append(p,f),u})),i.hidden=!1}async followToObservation(e){const t=this.session;if(!t)return;const i=t.tracks.find(n=>n.kind==="observer"&&(n.event.id??t.proposedId(n))===e.sighting)??t.tracks.find(n=>n.kind==="observer");i&&(await this.showTrack(i),this.editor.seekTo(e.at),this.editor.showRender())}static shapesOf(e){const t=new Set;for(const i of e.timeline?.keyframes??[])for(const n of i.shapes??[])t.add(n.sourceId);return[...t]}items(e){return[...e.tracks.map(t=>({track:t})),...e.interviews.map(t=>({interview:t}))]}optionLabel(e,t){const i=this.session;if(e.interview){const r=i.intervieweesOf(e.interview),a=r.length>0?r.map(l=>this.labelOf(l,i.tracks.indexOf(l))).join(", "):this.said.read(e.interview.title);return a?`${this.messages.interviewOf} ${a}`:this.messages.untitledInterview.replace("{n}",String(i.interviews.indexOf(e.interview)+1))}const n=e.track,s=this.labelOf(n,t);return n.kind==="observer"?`${this.messages.accountOf} ${s}`:s}async showInterview(e){const t=this.session;t&&(this.commit(),this.current=void 0,this.passagesToken++,this.byId("passages").hidden=!0,this.currentInterview=e,this.refreshRow(),await this.ensureInterview(),this.currentInterview===e&&(this.interviewElement.witnesses=t.tracks.filter(i=>i.kind==="observer").map(i=>({id:i.event.id??t.proposedId(i),label:this.labelOf(i,t.tracks.indexOf(i))})),this.interviewElement.documentUrl=t.url,this.interviewElement.transcriptText=t.transcriptText(e),this.interviewElement.event=e))}ensureInterview(){return this.interviewReady??=_e(async()=>{const{register:e}=await import("./InterviewEditorElement-CT26rBmp.js");return{register:e}},__vite__mapDeps([12,13,14,15]),import.meta.url).then(({register:e})=>{e(),customElements.upgrade(this.shadow)},e=>{throw this.interviewReady=void 0,e}),this.interviewReady}interviewChanged(e){const{field:t}=e,i=this.session,n=this.currentInterview;if(!(!i||!n)){t==="transcript"&&e.text!==void 0&&i.keepTranscript(n,e.text);for(const s of[n.interviewOf].flat()){const r=i.tracks.find(a=>a.kind==="observer"&&(a.event.id??i.proposedId(a))===s);r&&i.ensureId(r)}i.touch(),this.refreshRow(),this.scheduleDirtyCheck()}}labelOf(e,t){const i=this.said.read(e.event.title)??this.said.read(e.recording?.interpretation?.title);if(i)return i;if(e.kind==="observer")return this.said.read(e.recording?.observer?.title)??e.event.url??"";const n=this.session.tracks.filter(s=>s.kind==="reading").indexOf(e)+1;return this.messages.untitledReading.replace("{n}",String(n||t+1))}makeCase(){if(this.session)return;const e=this.editor.sightingData,t=e.time?Xl.rr0TimeOf(Ao(e.time)):void 0,i=this.said.read(e.observer?.title),n=this.getAttribute("src")?new URL(this.getAttribute("src"),location.href).href:void 0;this.session=xh.around(e,t,i,n,location.href),this.current=this.session.tracks[0],this.session.keep(this.current,e),this.dateModeFor=void 0,this.refreshRow()}writeCaseField(e,t){const i=this.session?.json;i&&(t.trim()===""?delete i[e]:i[e]=t,this.session?.touch(),this.scheduleDirtyCheck())}static rr0TimeOf(e){return e.replace(/^(\d{4}-\d\d-\d\d)T/,"$1 ")}static edtfOf(e){return e.replace(/^(\d{4}-\d\d-\d\d) (?=\d)/,"$1T")}showCaseTime(e){const t=String(e.json.time??""),i=t===""?void 0:eu(Xl.edtfOf(t));if(this.caseDate.time=i,t!==""&&!i){const n=this.input("case-time");n.value=t}this.dateModeFor!==e&&(this.caseDate.setPrecise(!(t!==""&&!i)&&ln.opensPrecise(i)),this.dateModeFor=e)}refreshRow(){const e=this.session;if(this.applySections(),this.byId("case-panel").hidden=e===void 0,this.byId("make-case-row").hidden=e!==void 0,this.byId("case").classList.toggle("in-case",e!==void 0),this.byId("recording").classList.toggle("in-case",e!==void 0),this.byId("interview-section").classList.toggle("in-case",e!==void 0),!e){this.refreshDirty();return}const t=this.shadow.activeElement;for(const[r,a]of[["case-id","id"],["case-title","title"]]){const l=this.input(r);l!==t&&(l.value=String(e.json[a]??""))}t?.closest?.("rr0-date-input")||this.showCaseTime(e);const i=this.byId("track"),n=this.items(e);i.replaceChildren(...n.map((r,a)=>new Option(this.optionLabel(r,a),String(a))));const s=this.currentInterview?n.findIndex(r=>r.interview===this.currentInterview):this.current?n.findIndex(r=>r.track===this.current):0;i.value=String(Math.max(0,s)),this.byId("delete").hidden=this.currentInterview===void 0&&e.tracks.length<=1,this.refreshRecordingId(e),this.refreshDirty()}refreshRecordingId(e){const t=this.current,i=t!==void 0&&t.kind==="observer";if(this.byId("row-recording-id").hidden=!i,i){const l=this.input("recording-id");this.shadow.activeElement!==l&&(l.value=t.event.id??""),l.placeholder=e.proposedId(t)}const{duplicateIds:n,unresolved:s}=e.problems(),r=[...n.map(l=>this.messages.idDuplicated.replace("{id}",l)),...s.map(({reference:l})=>this.messages.readingUnresolved.replace("{id}",l))],a=this.byId("case-problems");a.hidden=r.length===0,a.textContent=r.join(" ")}showRecordingIdError(e){const t=this.byId("recording-id-error");t.textContent=e??"",t.hidden=e===void 0}writeRecordingId(){const e=this.session,t=this.current;if(!e||!t)return;const i=e.setId(t,this.input("recording-id").value.trim());this.showRecordingIdError(i==="ok"?void 0:{empty:this.messages.idNeeded,invalid:this.messages.idInvalid,taken:this.messages.idTaken}[i]),this.scheduleDirtyCheck()}get dialog(){return this.byId("dialog")}openDialog(e,t,i,n){this.dialogMode=e,this.byId("dialog-title").textContent=t;const s=this.byId("dialog-message");s.textContent=i??"",s.hidden=i===void 0,this.showError(void 0),this.byId("fields-add").hidden=e!=="add",this.byId("fields-export").hidden=e!=="export",this.byId("ok").hidden=!1,this.byId("ok").textContent=n??(e==="discard"?this.messages.discardOk:this.messages.ok),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open","")}closeDialog(){this.pendingLoad=void 0,typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}showError(e){const t=this.byId("dialog-error");t.textContent=e??"",t.hidden=e===void 0}input(e){return this.byId(e)}today(){return new Date().toISOString().slice(0,10)}askAdd(){const e=this.session;if(!e)return;this.openDialog("add",this.messages.addTitle);const t=this.byId("of");t.replaceChildren(new Option(this.messages.interpretationOfNone,""),...e.tracks.filter(n=>n.kind==="observer").map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),t.value="",this.byId("kind").value="observation";const i=e.tracks.filter(n=>n.kind==="observer");this.byId("witness").replaceChildren(...i.map(n=>new Option(this.labelOf(n,e.tracks.indexOf(n)),String(e.tracks.indexOf(n))))),this.byId("medium").replaceChildren(),this.byId("source").value="blank";for(const n of["observer","title","author","file","url"])this.input(n).value="";this.input("date").value="",this.syncSourceFields()}async fillMedia(){const{InterviewMedia:e}=await _e(async()=>{const{InterviewMedia:i}=await import("./InterviewMedia-CvAxC62V.js");return{InterviewMedia:i}},[],import.meta.url),t=this.byId("medium");t.options.length>0||t.replaceChildren(...e.ALL.map(i=>new Option(e.label(i,this.language),i)))}syncSourceFields(){const e=this.byId("kind").value==="interview",t=this.byId("source").value,i=!e&&this.byId("of").value!=="";this.byId("row-source").hidden=e,this.byId("row-of").hidden=e,this.byId("row-witness").hidden=!e,this.byId("row-medium").hidden=!e,e&&this.fillMedia(),this.byId("row-file").hidden=e||t!=="file",this.byId("row-url").hidden=e||t!=="url",this.byId("row-observer").hidden=e||i,this.byId("row-title").hidden=!(e||i),this.byId("row-author").hidden=!(e||i),this.byId("label-title").textContent=e?this.messages.plainTitleField:this.messages.titleField,this.byId("label-author").textContent=e?this.messages.interviewerField:this.messages.authorField}askExport(){this.session&&(this.openDialog("export",this.messages.exportTitle),this.input("export-recordings").checked=!0)}askDelete(){const e=this.session;if(e&&this.currentInterview){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteInterviewQuestion);return}const t=this.current;if(!(!e||!t)){if(t.kind==="observer"){const i=e.readingsOf(t).length;if(i>0){this.openDialog("delete",this.messages.deleteRecording,this.messages.deleteRefused.replace("{n}",String(i))),this.byId("ok").hidden=!0;return}}this.openDialog("delete",this.messages.deleteRecording,t.kind==="reading"?this.messages.deleteReadingQuestion:this.messages.deleteObservationQuestion)}}async submitDialog(){switch(this.dialogMode){case"delete":this.closeDialog(),this.deleteCurrent();return;case"discard":{const e=this.pendingLoad;this.closeDialog(),e?.();return}case"export":await this.exportCase(this.input("export-recordings").checked)?this.closeDialog():this.showError(this.messages.loadFailed);return;case"add":await this.addRecording()&&this.closeDialog()}}async addRecording(){const e=this.session;if(!e)return!1;if(this.commit(),this.byId("kind").value==="interview"){const u=e.tracks[Number(this.byId("witness").value)],p=this.input("title").value.trim(),f=this.input("author").value.trim(),g=e.addInterview(u,this.input("date").value||this.today(),p!==""?p:void 0,f!==""?f.split(",").map(m=>({people:m.trim()})).filter(m=>m.people!==""):void 0,this.byId("medium").value);return await this.showInterview(g),!0}const t=this.byId("of").value,i=t===""?void 0:e.tracks[Number(t)],n=this.byId("source").value;if(i&&n==="blank"){if(i.kind!=="observer"||!i.recording)return!1;const u=this.input("title").value.trim(),p=this.input("author").value.trim(),f=e.addReading(i,this.input("date").value||this.today(),u!==""?u:void 0,p!==""?[{title:p}]:void 0);return this.showTrack(f),!0}const s=this.input("observer").value.trim(),r=this.input("date").value.trim();let a;try{if(n==="blank"){const u=(s||"observation").replace(/[^A-Za-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation";a={version:1,id:`${r?`${r}-`:""}${u}`,...s?{observer:{title:s}}:{},...r?{time:r}:{},timeline:{keyframes:[],order:[],groups:[]}}}else{const u=n==="file"?await this.readFile():await ho.json(this.input("url").value.trim());if(Ci.isCase(u))return this.showError(this.messages.isACase),!1;a=u,s&&!a.observer?.title&&(a={...a,observer:{...a.observer,title:s}})}}catch{return this.showError(this.messages.loadFailed),!1}const l=(i?this.input("title").value:s).trim(),c=l!==""?l:this.said.read(a.observer?.title),h=this.input("author").value.trim(),d=e.addObservation(a,r!==""?r:void 0,c,i?{account:i,by:h!==""?[{title:h}]:void 0}:void 0);return this.showTrack(d),!0}async readFile(){const e=this.input("file").files?.[0];if(!e)throw new Error("No file");const t=await new Promise((i,n)=>{const s=new FileReader;s.onload=()=>i(s.result),s.onerror=()=>n(s.error),s.readAsText(e)});return JSON.parse(t)}deleteCurrent(){const e=this.session,t=this.currentInterview;if(e&&t){if(!e.deleteInterview(t))return;this.currentInterview=void 0;const r=e.tracks.find(a=>a.kind==="observer")??e.tracks[0];r&&this.showTrack(r);return}const i=this.current;if(!e||!i)return;const n=i.kind==="reading"?e.accountOf(i)??e.tracks.find(r=>r.kind==="observer"):e.tracks.find(r=>r!==i);(i.kind==="reading"?e.deleteReading(i):e.deleteObservation(i).deleted)&&(this.current=void 0,n&&this.showTrack(n))}async exportCase(e=!0){const t=this.session;if(!t)return!0;if(this.commit(),e)try{for(const a of t.tracks)await this.loadTrack(a)}catch{return!1}const i=t.files(e,!0);if(t.markExported(e),this.fileEditor?.markSaved(),this.refreshDirty(),i.length===1)return this.download(new Blob([i[0].content],{type:"application/json"}),i[0].path),!0;const{zipSync:n,strToU8:s}=await _e(async()=>{const{zipSync:a,strToU8:l}=await import("./browser-_Ncw3Jhn.js");return{zipSync:a,strToU8:l}},[],import.meta.url),r={};for(const a of i)r[a.path]=s(a.content);return this.download(new Blob([n(r)],{type:"application/zip"}),`${t.json.id??"case"}.zip`),!0}download(e,t){const i=URL.createObjectURL(e),n=document.createElement("a");n.href=i,n.download=t,n.click(),URL.revokeObjectURL(i)}}function cL(){G2(),customElements.get(bM)||customElements.define(bM,Xl)}cL();export{IL as $,Oo as A,k2 as B,sy as C,kl as D,Im as E,ts as F,Lt as G,Is as H,yS as I,D as J,Lm as K,St as L,Se as M,gh as N,Ll as O,Gs as P,ps as Q,Et as R,zn as S,As as T,Sh as U,Ls as V,UD as W,Ji as X,TL as Y,bt as Z,_e as _,ho as a,TC as a$,ep as a0,wL as a1,Dt as a2,dr as a3,rA as a4,we as a5,ye as a6,xt as a7,DL as a8,ct as a9,yL as aA,Dn as aB,z1 as aC,ui as aD,SL as aE,_L as aF,Tw as aG,Mr as aH,Jh as aI,ef as aJ,ZE as aK,gt as aL,ei as aM,Wo as aN,Vm as aO,ki as aP,Dr as aQ,iA as aR,Zt as aS,vL as aT,bL as aU,Dw as aV,ML as aW,Ks as aX,Iw as aY,J1 as aZ,Z3 as a_,gL as aa,ne as ab,uE as ac,lt as ad,x0 as ae,hs as af,lu as ag,Qr as ah,Lc as ai,yt as aj,rt as ak,Vn as al,Hn as am,EL as an,Na as ao,Yi as ap,pL as aq,mL as ar,fL as as,Hh as at,AL as au,xL as av,lA as aw,Zu as ax,hn as ay,Uw as az,vS as b,Yu as b0,M0 as b1,un as b2,Nw as b3,Pg as b4,Ng as b5,_t as b6,Ua as b7,zh as b8,NM as c,Ns as d,ci as e,at as f,uL as g,Pa as h,tu as i,hL as j,Dm as k,dL as l,Pn as m,fs as n,qk as o,av as p,Zf as q,Xs as r,yh as s,Ue as t,Mt as u,Ea as v,dn as w,Jr as x,Tr as y,SA as z};