@rr0/ufoathome 0.170.0 → 0.170.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -335,8 +335,8 @@ ${e} :is(select:not([multiple]):not([size]), .rr0-select) {
|
|
|
335
335
|
<button id="copy" class="share-copy" type="button"></button>
|
|
336
336
|
</div>
|
|
337
337
|
</dialog>
|
|
338
|
-
`;class Ed extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Ed.TAG)||customElements.define(Ed.TAG,Ed)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=w5;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await u5.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?Va.pinnedLink(e.link(),"0.170.
|
|
339
|
-
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.170.0")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Q(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}Fe.register(rn,()=>new Rc);Fe.register(Vd,()=>new Md);Fe.register(wa,()=>new Qy);Fe.register(Wd,()=>new xd);Fe.register(Ip,()=>new ew);Fe.register($d,()=>new Cp);Fe.register(Gd,()=>new Rp);Fe.register(Kd,()=>new Lp);Fe.register(Jl,()=>new Xd);Fe.register(Hd,()=>new kp);Fe.register(vr,()=>new is);Fe.register(Fl,()=>new Np);Fe.register(Fs,()=>new Cc);Fe.register(Ul,()=>new Fp);Fe.register(_p,()=>new tw);Fe.register(Bl,()=>new Up);Fe.register(Nl,()=>new Pp);Fe.register(zl,()=>new Bp);Fe.register(Jc,()=>new zp);Fe.register(Pl,()=>new Op);Fe.register(Qn,()=>new ri);Fe.register(Fo,()=>new Vp);Fe.register(Ns,()=>new rt);Fe.register(Uo,()=>new Wp);Fe.register(Dp,()=>new Ig);Fe.register(Bo,()=>new Kp);Fe.register(No,()=>new Gp);Fe.register(zo,()=>new $p);Fe.register(w0,()=>new J_);Fe.register(Po,()=>new Hp);class bn{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[bn.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>bn.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(bn.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(c=>c===i))!==null&&s!==void 0?s:Object.keys(a).find(c=>bn.base(c)===bn.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}bn.any=new bn([]);var gx;(function(l){l.abductee="abductee",l.actor="actor",l.artist="artist",l.anthropologist="anthropologist",l.archeologist="archeologist",l.astronaut="astronaut",l.astronomer="astronomer",l.astrologist="astrologist",l.astrophysicist="astrophysicist",l.banker="banker",l.barman="barman",l.biologist="biologist",l.biochemist="biochemist",l.biophysicist="biophysicist",l.bishop="bishop",l.businessman="businessman",l.botanist="botanist",l.cameraman="cameraman",l.chemist="chemist",l.contactee="contactee",l.cryptozoologist="cryptozoologist",l.dentist="dentist",l.director="director",l.diplomat="diplomat",l.diver="diver",l.electronics="electronics",l.engineer="engineer",l.ethnologist="ethnologist",l.exobiologist="exobiologist",l.farmer="farmer",l.firefighter="firefighter",l.flightAttendant="flightAttendant",l.geologist="geologist",l.geophysicist="geophysicist",l.geographer="geographer",l.historian="historian",l.houseWife="houseWife",l.hypnotherapist="hypnotherapist",l.illusionist="illusionist",l.journalist="journalist",l.judge="judge",l.lawyer="lawyer",l.leader="leader",l.librarian="librarian",l.logger="logger",l.mathematician="mathematician",l.mechanic="mechanic",l.meteorologist="meteorologist",l.military="military",l.musician="musician",l.neurologist="neurologist",l.neuroscientist="neuroscientist",l.neuropsychiatrist="neuropsychiatrist",l.nurse="nurse",l.oceanographer="oceanographer",l.painter="painter",l.parapsychologist="parapsychologist",l.philosopher="philosopher",l.photographer="photographer",l.physician="physician",l.physicist="physicist",l.pilot="pilot",l.politician="politician",l.policeman="policeman",l.priest="priest",l.producer="producer",l.prospector="prospector",l.psychologist="psychologist",l.psychiatrist="psychiatrist",l.radioastronomer="radioastronomer",l.radioamateur="radioamateur",l.salesman="salesman",l.sailor="sailor",l.sociologist="sociologist",l.softwareEngineer="softwareEngineer",l.stuntman="stuntman",l.taxiDriver="taxiDriver",l.teacher="teacher",l.telegrapher="telegrapher",l.truckDriver="truckDriver",l.ufologist="ufologist",l.ufoWitness="ufoWitness",l.ufoWitness2="ufoWitness2",l.worker="worker",l.writer="writer"})(gx||(gx={}));var vx;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(vx||(vx={}));class M5 extends Error{constructor(e,t){super(e),this.cause=t}}class rw extends M5{constructor(e=rw.defaultMessage,t){super(e,t)}}rw.defaultMessage="Assertion failed";var bx;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(bx||(bx={}));var yx;(function(l){l.at="at",l.au="au",l.ar="ar",l.be="be",l.br="br",l.ca="ca",l.ch="ch",l.cn="cn",l.cl="cl",l.co="co",l.cy="cy",l.de="de",l.dk="dk",l.do="do",l.dz="dz",l.gr="gr",l.ec="ec",l.eg="eg",l.es="es",l.fi="fi",l.fr="fr",l.ga="ga",l.ge="ge",l.hu="hu",l.in="in",l.ie="ie",l.ir="ir",l.il="il",l.it="it",l.jp="jp",l.kr="kr",l.ma="ma",l.mx="mx",l.my="my",l.mz="mz",l.nl="nl",l.no="no",l.nz="nz",l.pa="pa",l.pe="pe",l.ph="ph",l.pl="pl",l.pt="pt",l.ro="ro",l.ru="ru",l.sc="sc",l.tr="tr",l.ua="ua",l.uk="uk",l.us="us",l.sa="sa",l.se="se",l.su="su",l.tn="tn",l.tw="tw",l.ve="ve",l.za="za"})(yx||(yx={}));function jd(l,e){for(const t of l){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class yr{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 s=t.getRootNode();t=s instanceof ShadowRoot?s.host:void 0}}}class Xp{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Vi.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,s,n){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:Vi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new Xp(a,new URL("case.json",n).href),c=o.tracks[0];return c.recording=e,c.base={url:s},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Vi.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 s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:Vi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...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){t=Oi.toCurrent(t),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(n=>n.eventType===Vi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Vi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,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,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.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,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Vi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!Xp.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(c=>s(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&s(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Vi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)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(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let c=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${n.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:m,description:v,sources:g,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),E={version:4,id:`${n.id??r}-interpretation-${c}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},S={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],S],this.caseChanged=!0;const A={event:S,url:new URL(S.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(A),A}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(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.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:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(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(s=>s!==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(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
338
|
+
`;class Ed extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(Ed.TAG)||customElements.define(Ed.TAG,Ed)}subject;messages;languageToken=0;shadow;dialog;linkField;copyButton;linkBox;embedBox;linkOption;embedOption;pin;embedMarkup;noteElement;codeEditor;codeLoading;constructor(){super(),this.shadow=this.attachShadow({mode:"open"}),this.shadow.innerHTML=w5;const e=t=>this.shadow.getElementById(t);this.dialog=e("dialog"),this.linkField=e("link"),this.copyButton=e("copy"),this.linkBox=e("link-box"),this.embedBox=e("embed-box"),this.linkOption=e("link-option"),this.embedOption=e("embed-option"),this.pin=e("pin"),this.embedMarkup=e("embed-markup"),this.noteElement=e("note"),e("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",t=>{t.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.pin.addEventListener("change",()=>this.refresh()),this.copyButton.addEventListener("click",()=>void(this.embedBox.hidden?this.copy(this.linkField.value,this.linkField):this.copy(this.codeEditor?.text??this.embedMarkup.value,this.embedMarkup))),this.applyMessages()}async useLanguage(e){const t=++this.languageToken,i=await u5.load(e);if(t===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(e){this.noteElement.textContent=e??"",this.noteElement.hidden=e===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const e=this.subject;if(!e)return;const t=this.pin.checked;this.linkField.value=t?Va.pinnedLink(e.link(),"0.170.1"):e.link(),this.fitLink();const s=`<script type="module" src="${t?Va.pinned(e.module,"0.170.1"):Va.current(e.module,import.meta.url,Yd.home())}"><\/script>
|
|
339
|
+
${e.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const e=this.messages;if(!e)return;const t=(i,s)=>{this.shadow.getElementById(i).textContent=s};t("title",e.share),t("link-label",e.link),t("embed-label",e.embed),t("copy",e.copy),t("pin-label",e.pin.replace("{version}","0.170.1")),this.pin.parentElement.title=e.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",e.close),this.linkField.setAttribute("aria-label",e.link)}show(e){this.linkBox.hidden=e!=="link",this.embedBox.hidden=e!=="embed",this.linkOption.setAttribute("aria-pressed",String(e==="link")),this.embedOption.setAttribute("aria-pressed",String(e==="embed")),e==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Q(async()=>{const{ShareCodeEditor:e}=await import("./ShareCodeEditor-CF7IVeXv.js");return{ShareCodeEditor:e}},__vite__mapDeps([2,3]),import.meta.url).then(({ShareCodeEditor:e})=>{this.codeEditor=new e(this.shadow.getElementById("embed-code"),this.embedMarkup.value,t=>{this.embedMarkup.value=t},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(e,t){try{await navigator.clipboard.writeText(e),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{t.select()}}}Fe.register(rn,()=>new Rc);Fe.register(Vd,()=>new Md);Fe.register(wa,()=>new Qy);Fe.register(Wd,()=>new xd);Fe.register(Ip,()=>new ew);Fe.register($d,()=>new Cp);Fe.register(Gd,()=>new Rp);Fe.register(Kd,()=>new Lp);Fe.register(Jl,()=>new Xd);Fe.register(Hd,()=>new kp);Fe.register(vr,()=>new is);Fe.register(Fl,()=>new Np);Fe.register(Fs,()=>new Cc);Fe.register(Ul,()=>new Fp);Fe.register(_p,()=>new tw);Fe.register(Bl,()=>new Up);Fe.register(Nl,()=>new Pp);Fe.register(zl,()=>new Bp);Fe.register(Jc,()=>new zp);Fe.register(Pl,()=>new Op);Fe.register(Qn,()=>new ri);Fe.register(Fo,()=>new Vp);Fe.register(Ns,()=>new rt);Fe.register(Uo,()=>new Wp);Fe.register(Dp,()=>new Ig);Fe.register(Bo,()=>new Kp);Fe.register(No,()=>new Gp);Fe.register(zo,()=>new $p);Fe.register(w0,()=>new J_);Fe.register(Po,()=>new Hp);class bn{constructor(e){this.preferences=e}read(e){var t,i;if(e===void 0)return;if(typeof e=="string")return e===""?void 0:e;for(const n of this.preferences){const r=(t=e[n])!==null&&t!==void 0?t:e[bn.base(n)];if(r)return r}const s=new Set(this.preferences.map(n=>bn.base(n)));for(const[n,r]of Object.entries(e))if(r&&s.has(bn.base(n)))return r;return(i=Object.values(e).find(n=>n))!==null&&i!==void 0?i:void 0}write(e,t,i){var s,n;const r=t?.trim()?t.trim():void 0;if(e===void 0||typeof e=="string")return r;const a={...e},o=(n=(s=Object.keys(a).find(c=>c===i))!==null&&s!==void 0?s:Object.keys(a).find(c=>bn.base(c)===bn.base(i)))!==null&&n!==void 0?n:i;return r===void 0?delete a[o]:a[o]=r,Object.keys(a).length===0?void 0:a}static base(e){return e.toLowerCase().split("-")[0]}}bn.any=new bn([]);var gx;(function(l){l.abductee="abductee",l.actor="actor",l.artist="artist",l.anthropologist="anthropologist",l.archeologist="archeologist",l.astronaut="astronaut",l.astronomer="astronomer",l.astrologist="astrologist",l.astrophysicist="astrophysicist",l.banker="banker",l.barman="barman",l.biologist="biologist",l.biochemist="biochemist",l.biophysicist="biophysicist",l.bishop="bishop",l.businessman="businessman",l.botanist="botanist",l.cameraman="cameraman",l.chemist="chemist",l.contactee="contactee",l.cryptozoologist="cryptozoologist",l.dentist="dentist",l.director="director",l.diplomat="diplomat",l.diver="diver",l.electronics="electronics",l.engineer="engineer",l.ethnologist="ethnologist",l.exobiologist="exobiologist",l.farmer="farmer",l.firefighter="firefighter",l.flightAttendant="flightAttendant",l.geologist="geologist",l.geophysicist="geophysicist",l.geographer="geographer",l.historian="historian",l.houseWife="houseWife",l.hypnotherapist="hypnotherapist",l.illusionist="illusionist",l.journalist="journalist",l.judge="judge",l.lawyer="lawyer",l.leader="leader",l.librarian="librarian",l.logger="logger",l.mathematician="mathematician",l.mechanic="mechanic",l.meteorologist="meteorologist",l.military="military",l.musician="musician",l.neurologist="neurologist",l.neuroscientist="neuroscientist",l.neuropsychiatrist="neuropsychiatrist",l.nurse="nurse",l.oceanographer="oceanographer",l.painter="painter",l.parapsychologist="parapsychologist",l.philosopher="philosopher",l.photographer="photographer",l.physician="physician",l.physicist="physicist",l.pilot="pilot",l.politician="politician",l.policeman="policeman",l.priest="priest",l.producer="producer",l.prospector="prospector",l.psychologist="psychologist",l.psychiatrist="psychiatrist",l.radioastronomer="radioastronomer",l.radioamateur="radioamateur",l.salesman="salesman",l.sailor="sailor",l.sociologist="sociologist",l.softwareEngineer="softwareEngineer",l.stuntman="stuntman",l.taxiDriver="taxiDriver",l.teacher="teacher",l.telegrapher="telegrapher",l.truckDriver="truckDriver",l.ufologist="ufologist",l.ufoWitness="ufoWitness",l.ufoWitness2="ufoWitness2",l.worker="worker",l.writer="writer"})(gx||(gx={}));var vx;(function(l){l.neutral="neutral",l.male="male",l.female="female"})(vx||(vx={}));class M5 extends Error{constructor(e,t){super(e),this.cause=t}}class rw extends M5{constructor(e=rw.defaultMessage,t){super(e,t)}}rw.defaultMessage="Assertion failed";var bx;(function(l){l.country="country",l.region="region",l.department="department",l.city="city",l.company="company"})(bx||(bx={}));var yx;(function(l){l.at="at",l.au="au",l.ar="ar",l.be="be",l.br="br",l.ca="ca",l.ch="ch",l.cn="cn",l.cl="cl",l.co="co",l.cy="cy",l.de="de",l.dk="dk",l.do="do",l.dz="dz",l.gr="gr",l.ec="ec",l.eg="eg",l.es="es",l.fi="fi",l.fr="fr",l.ga="ga",l.ge="ge",l.hu="hu",l.in="in",l.ie="ie",l.ir="ir",l.il="il",l.it="it",l.jp="jp",l.kr="kr",l.ma="ma",l.mx="mx",l.my="my",l.mz="mz",l.nl="nl",l.no="no",l.nz="nz",l.pa="pa",l.pe="pe",l.ph="ph",l.pl="pl",l.pt="pt",l.ro="ro",l.ru="ru",l.sc="sc",l.tr="tr",l.ua="ua",l.uk="uk",l.us="us",l.sa="sa",l.se="se",l.su="su",l.tn="tn",l.tw="tw",l.ve="ve",l.za="za"})(yx||(yx={}));function jd(l,e){for(const t of l){const i=t.toLowerCase().split("-")[0];if(e.includes(i))return i}return"en"}class yr{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 s=t.getRootNode();t=s instanceof ShadowRoot?s.host:void 0}}}class Xp{constructor(e,t){this.json=e,this.url=t,this.tracks=(e.events??[]).filter(i=>i.eventType===Vi.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,s,n){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:Vi.SIGHTING_EVENT,...t!==void 0?{time:t}:{},...i!==void 0?{title:i}:{},url:`observer-${r}.json`}]},o=new Xp(a,new URL("case.json",n).href),c=o.tracks[0];return c.recording=e,c.base={url:s},c.event.id=o.proposedId(c),o.caseChanged=!0,o}accountOf(e){if(e.kind!=="reading")return;const t=[e.event.interpretationOf].flat(),i=this.tracks.filter(s=>s.kind==="observer");return i.find(s=>s.event.id!==void 0&&t.includes(s.event.id))??i.find(s=>s.recording?.id!==void 0&&t.includes(s.recording.id))}get interviews(){return(this.json.events??[]).filter(e=>e.eventType===Vi.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 s=t.find(n=>n.event.id===i)??t.find(n=>n.recording?.id===i);return s?[s]:[]})}addInterview(e,t,i,s,n){const r=this.eventIds(),a=e?e.event.id??this.proposedId(e):"case";let o=1;for(;r.has(`interview-${a}-${o}`);)o++;const c={type:"event",eventType:Vi.INTERVIEW_EVENT,id:`interview-${a}-${o}`,...e?{interviewOf:this.ensureId(e)}:{},time:t,...n!==void 0?{medium:n}:{},...s!==void 0&&s.length>0?{by:s}:{},...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){t=Oi.toCurrent(t),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(n=>n.eventType===Vi.SIGHTING_EVENT&&typeof n.url=="string"&&n.url!=="").map(n=>{const r=new URL(n.url,this.url).href,a=n.interpretationOf===void 0?"observer":"reading",o=this.tracks.find(c=>c.url===r);return o?(o.event=n,o.kind=a,o):{event:n,url:r,kind:a}});this.tracks.splice(0,this.tracks.length,...i);const s=new Map;for(const[n,r]of this.transcripts){const a=(e.events??[]).find(o=>o.eventType===Vi.INTERVIEW_EVENT&&(n.id!==void 0&&o.id===n.id||n.url!==void 0&&o.url===n.url));a&&s.set(a,r)}this.transcripts.clear();for(const[n,r]of s)this.transcripts.set(n,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,s=t(e.recording?.observer?.lastName)||t(e.recording?.observer?.id)||t(i),n=this.eventIds(e);if(s!==""){let a=s;for(let o=2;n.has(a);o++)a=`${s}-${o}`;return a}let r=1;for(;n.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,s=a=>a===i||a===e.recording?.id,n=(this.json.events??[]).filter(a=>a.eventType===Vi.SIGHTING_EVENT&&a.interpretationOf!==void 0&&[a.interpretationOf].flat().some(o=>o!==void 0&&s(o))),r=this.interviews.filter(a=>[a.interviewOf].flat().some(o=>o!==void 0&&s(o)));if(t==="")return i===void 0?"ok":n.length>0||r.length>0?"empty":(delete e.event.id,this.caseChanged=!0,"ok");if(!Xp.ID_PATTERN.test(t))return"invalid";if(this.eventIds(e).has(t))return"taken";if(t===i)return"ok";for(const a of n){const o=[a.interpretationOf].flat().map(c=>s(c)?t:c);a.interpretationOf=Array.isArray(a.interpretationOf)?o:o[0]}for(const a of r){const o=[a.interviewOf].flat().map(c=>c!==void 0&&s(c)?t:c);a.interviewOf=Array.isArray(a.interviewOf)?o:o[0]}return e.event.id=t,this.caseChanged=!0,"ok"}problems(){return Vi.problems(this.json,this.tracks.map(e=>e.recording?.id).filter(e=>e!==void 0))}addReading(e,t,i,s){const n=e.recording;if(!n)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(T=>T.event.url)),o=new Set(this.tracks.map(T=>T.recording?.id));let c=this.tracks.filter(T=>T.kind==="reading").length+1;for(;a.has(`interpretation-${r}-${c}.json`)||o.has(`${n.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:m,description:v,sources:g,tags:b,timeline:w,milestones:y,interpretation:M,...x}=structuredClone(n),E={version:4,id:`${n.id??r}-interpretation-${c}`,...x,tags:["interpretation"],timeline:{keyframes:[],order:[],groups:[]},interpretation:{...i!==void 0?{title:i}:{},bodies:[]}},S={type:"event",eventType:"sighting",interpretationOf:this.ensureId(e),time:t,...s!==void 0&&s.length>0?{by:s}:{},...i!==void 0?{title:i}:{},url:d+h};this.json.events=[...this.json.events??[],S],this.caseChanged=!0;const A={event:S,url:new URL(S.url,this.url).href,kind:"reading",recording:E};return this.tracks.push(A),A}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(s=>s!==void 0&&t.includes(s)))}addObservation(e,t,i,s){const n=new Set(this.tracks.map(m=>m.event.url)),r=new Set(this.tracks.map(m=>m.recording?.id)),a=(e.id??"observation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"observation",o=s?"interpretation":"observer";let c=`${o}-${a}.json`,h=e.id??a;for(let m=2;n.has(c)||r.has(h);m++)c=`${o}-${a}-${m}.json`,h=`${e.id??a}-${m}`;const d={...e,id:h},u=this.tracks[0]?.event.url?.includes("/")?this.tracks[0].event.url.replace(/[^/]*$/,""):"",p={type:"event",eventType:"sighting",...s?{interpretationOf:this.ensureId(s.account)}:{},...t!==void 0?{time:t}:{},...s?.by&&s.by.length>0?{by:s.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:s?"reading":"observer",recording:d};return this.tracks.push(f),s||(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(s=>s!==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(/[^/]*$/,""),s=o=>o.startsWith(i)?o.slice(i.length):o,n=this.tracks.filter(o=>e&&o.recording!==void 0&&(t||this.changed(o))).map(o=>({path:s(o.url),content:JSON.stringify(o.recording,null,2)+`
|
|
340
340
|
`})),r=decodeURIComponent(this.url.replace(/[?#].*$/,"").replace(/^.*\//,""))||"case.json",a=[...this.transcripts].filter(([o,c])=>e&&o.url!==void 0&&(t||this.transcriptChanged(c))).map(([o,c])=>({path:s(new URL(o.url,this.url).href),content:c.text}));return[{path:r,content:JSON.stringify(this.json,null,2)+`
|
|
341
341
|
`},...n,...a]}}class Yp{constructor(e,t,i,s){this.button=e,this.onPick=i,this.idOf=s;const n=this.panel=e.ownerDocument.createElement("div");n.id=t,n.className="add-menu",n.setAttribute("popover",""),n.setAttribute("role","menu");const r=`--add-menu-${t}`;e.style.setProperty("anchor-name",r),n.style.setProperty("position-anchor",r),e.setAttribute("popovertarget",t),e.setAttribute("aria-haspopup","menu"),e.after(n)}static CSS=`
|
|
342
342
|
.add-menu { padding: .3em 0; border: 1px solid color-mix(in srgb, CanvasText 30%, transparent); border-radius: 4px; background: Canvas; color: CanvasText;
|
|
@@ -651,7 +651,7 @@ ${Pn.css("rr0-hint .hint-pop")}
|
|
|
651
651
|
.event-row-step { font-size: 13px; white-space: nowrap; }
|
|
652
652
|
.event-direction-point { font-size: 13px; color: var(--ink-dim); }
|
|
653
653
|
.event-direction-look { font-size: 13px; }
|
|
654
|
-
`;static ADDABLE={observer:["look","walk","follow"],phenomenon:["stand","blink","turn","roll","vibrate","spiral","vanish"],bodies:["motion","spin","rise","turn","ride","light","blink","vanish"]};static CHOICES={sizeBy:{values:["","altitude"],absent:"",with:["sizeDeg"]},side:{values:["left","right"],with:[]},seenFrom:{values:["","craft"],absent:"",with:["side","byDeg"]}};static AMONG={target:["shape","group","body","decor"],in:["body","decor"],vehicle:["decor"]};words;get messages(){return this.words}note;reset;fields;timeline;timelineHost;empty;addButton;addMenu;deleteButton;picked;localize(e){this.words=e,this.localizeList(),this.render()}localizeList(){const e=this.messages;this.timeline.setMessages({addKeyframeHere:e.add,keyframeHere:e.add,zoomHint:e.zoomHint}),this.addButton.innerHTML=`${we.PLUS} ${e.add}`,this.addMenu.setKinds(to.ADDABLE[this.actor].map(t=>({value:t,label:e.kinds[t]??t}))),this.empty.textContent=e.none,this.deleteButton.title=e.remove,this.deleteButton.setAttribute("aria-label",e.remove)}choose(e){this.picked=e;const t=this.host.sighting().events?.[e];t&&this.host.seek(t.t),this.render(),this.host.picked?.()}syncTimeline(e){const t=this.messages,i=h=>t.kinds[h.eventType]??h.eventType,s=e.map(({event:h,index:d})=>({id:String(d),t:h.t,until:Math.max(h.t,h.until??h.t),label:i(h)})),n=s.flatMap(h=>[h.t,h.until]),r=this.host.duration?.()??Math.max(1,...n),a=Math.min(...n),o=Math.max(...n),c=Math.max(500,(o-a)/10);this.timeline.show([{id:this.actor,label:this.titleText(),color:to.COLOR,times:[],spans:s,selected:this.picked===void 0?void 0:String(this.picked),select:h=>this.choose(Number(h)),open:()=>{},add:()=>this.addButton.click()}],r,this.host.now(),{from:a-c,to:o+c})}setTime(e){this.timeline.setTime(e)}static COLOR="#4f8fd6";shownTheirs;sync(){this.theirs()!==this.shownTheirs&&this.render()}theirs(){const e=this.host.sighting();return this.actor==="observer"?ht.observerTrackIsExpanded(e):this.actor==="phenomenon"?ht.timelineIsExpanded(e):ht.bodiesAreExpanded(e)}who(){const e=this.host.sighting();if(this.actor==="observer")return Vt.observerId(e);if(this.actor==="bodies")return this.host.currentBody?.();const t=this.host.currentShapes?.();if(t!==void 0)return t;const i=(e.events??[]).find(n=>n.eventType==="stand"&&Vt.isPhenomenon(e,n));if(i?.who!==void 0)return i.who;const s=Vt.shapeIds(e);return s.length>0?e.timeline.topOf(s[0]):void 0}events(){const e=this.host.sighting(),t=this.actor==="bodies"?this.host.currentBody?.():void 0,i=s=>this.actor==="observer"?Vt.isObserver(e,s):this.actor==="phenomenon"?Vt.isPhenomenon(e,s):t!==void 0&&(s.who===t||Vt.partOf(s.who)?.element===t);return(e.events??[]).map((s,n)=>({event:s,index:n})).filter(({event:s})=>i(s))}get pickedIndex(){return this.picked}pick(e){this.picked=e,this.render(),this.root.scrollIntoView?.({block:"start"})}titleText(){return this.actor==="observer"?this.messages.title:this.actor==="phenomenon"?this.messages.phenomenonTitle:this.messages.bodyTitle.replace("{body}",this.host.bodyLabel?.(this.who()??"")??this.who()??"")}render(){if(!this.words)return;this.shownTheirs=this.theirs(),this.root.querySelector(".events-title").textContent=this.titleText(),this.root.hidden=this.actor==="bodies"&&this.who()===void 0;const e=this.events();e.some(({index:n})=>n===this.picked)||(this.picked=e[0]?.index);const t=this.shownTheirs;this.note.hidden=e.length===0,this.note.textContent=this.actor==="observer"?t?this.messages.derivedNote:this.messages.overriddenNote:this.actor==="phenomenon"?t?this.messages.derivedShapesNote:this.messages.overriddenShapesNote:t?this.messages.derivedBodiesNote:this.messages.overriddenBodiesNote,this.reset.hidden=e.length===0||t,this.reset.textContent=this.messages.resetToEvents,this.empty.hidden=e.length>0,this.timelineHost.hidden=e.length===0,this.syncTimeline(e);const i=this.picked===void 0?void 0:this.host.sighting().events?.[this.picked],s=i?this.details(i,this.picked):[];s[0]?.append(this.deleteButton),this.fields.replaceChildren(...s)}add(e){const t=this.host.sighting(),i=this.who();if(i===void 0)return;const s=Math.round(this.host.now()),n=t.observerTrack.getInterpolatedPoseAt(s)??t.observerTrack.getLatestPoseAt(s),r=n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:t.event.place?.[0]&&{lat:t.event.place[0].lat,lng:t.event.place[0].lng},a=t.interpretation?.bodies.find(d=>d.id!==i)?.id??"",o={look:{params:{headingDeg:Math.round(n?.headingDeg??0),pitchDeg:Math.round(n?.pitchDeg??0)}},walk:{until:s+1e4,params:{from:{...r},to:{...r}}},follow:{until:s+5e3,params:{target:a}},stand:{params:{place:{...r},metres:[{t:s,widthM:1,heightM:1}]}},blink:{until:s+5e3,params:{onS:.5,offS:.5,off:{transparency:1}}},vanish:{},motion:{until:s+2e3,params:{motion:"",to:1}},spin:{until:s+5e3,params:{motion:"",turnsPerS:.5}},rise:{until:s+3e3,params:{distanceM:1,angleDeg:0,headingDeg:0,stops:!0}},ride:{params:{in:a,aboveM:0}},turn:{until:s+1e3,params:{headingDeg:0}}};this.actor==="phenomenon"&&Object.assign(o,{turn:{until:s+1e3,params:{byDeg:15,side:"left"}},roll:{until:s+500,params:{toDeg:20}},vibrate:{until:s+1e3,params:{hz:10,amplitudeShare:.1,riseS:.3}},spiral:{until:s+1e3,params:{turns:1,radiusDeg:2,shrink:.5,clockwise:!0,rollDeg:360}}}),this.actor==="bodies"&&Object.assign(o,{blink:{until:s+5e3,params:{onS:.5,offS:.5,cdM2:500}},light:{params:{cdM2:500}}});const c=o[e]??{},h={type:"event",eventType:e,who:i,t:s,...c.until===void 0?{}:{until:c.until},...c.params?{params:c.params}:{}};this.host.editing(),t.events=[...t.events??[],h],this.picked=t.events.length-1,ht.refresh(t),this.host.changed()}remove(){const e=this.host.sighting(),t=this.picked;if(t===void 0||!e.events?.[t])return;this.host.editing();const i=e.provenance,s=[];for(const n of i.paths()){const r=/^events\.(\d+)(\..*)?$/.exec(n);if(!r)continue;const a=Number(r[1]);a>t&&s.push([`events.${a-1}${r[2]??""}`,i.at(n)]),a>=t&&i.clear(n)}for(const[n,r]of s)i.set(n,r);e.events=e.events.filter((n,r)=>r!==t),this.picked=void 0,ht.refresh(e),this.host.changed()}details(e,t){const i=document.createElement("div");i.className="event-head",i.append(this.messages.from,this.seconds(e.t,r=>{e.t=r},`events.${t}.t`)),e.until!==void 0&&i.append(this.messages.to,this.seconds(e.until,r=>{e.until=r},`events.${t}.until`));const s=document.createElement("div");if(s.className="event-params",this.actor==="phenomenon"){const r=document.createElement("span");r.textContent=this.messages.who,s.append(r,this.subject(e))}if(this.actor==="bodies"){const r=document.createElement("span");r.textContent=this.messages.part,s.append(r,this.part(e))}const n=Object.entries(e.params??{});for(const[r,a]of Object.entries(to.CHOICES))a.absent!==void 0&&a.with.every(o=>e.params?.[o]!==void 0)&&e.params?.[r]===void 0&&n.push([r,a.absent]);for(const[r,a]of n){const o=document.createElement("span");o.className="event-param-label";const c=document.createElement("span");c.className="event-param-name",c.textContent=this.messages.params[r]??r;const h=this.messages.paramHints[r];h&&c.append(Jn.of(h)),o.append(c,this.basis(`events.${t}.params.${r}`));const d=document.createElement("span");d.className="event-param",d.append(this.value(e,r,a,`events.${t}.params.${r}`)),s.append(o,d)}return[i,s]}subject(e){const t=this.host.sighting(),i=document.createElement("select");i.className="event-who";const s=[...t.timeline.allGroups.map(n=>n.id),...Vt.shapeIds(t)];e.who!==void 0&&!s.includes(e.who)&&s.unshift(e.who);for(const n of s){const r=document.createElement("option");r.value=n,r.textContent=this.host.shapesLabel?.(n)??n,i.append(r)}return i.value=e.who??"",i.addEventListener("change",()=>{this.host.editing(),e.who=i.value,ht.refresh(t),this.host.changed()}),i}part(e){const t=this.host.sighting(),i=Vt.partOf(e.who),s=i?.element??e.who??"",n=document.createElement("input");return n.type="text",n.className="event-part",n.value=i?.part??"",n.placeholder=this.messages.wholeBody,n.title=this.messages.partHint,n.addEventListener("change",()=>{const r=n.value.trim().replaceAll("/","");this.host.editing(),e.who=r?`${s}/${r}`:s,ht.refresh(t),this.host.changed()}),n}value(e,t,i,s){const n=e.params,r=to.CHOICES[t];if(r&&typeof i=="string")return this.choice(t,i,r,o=>{o===r.absent?delete n[t]:n[t]=o},s);const a=to.AMONG[t];if(a&&typeof i=="string")return this.actorChoice(i,a,o=>{n[t]=o},s);if(typeof i=="string")return this.text(i,o=>{n[t]=o},s);if(typeof i=="boolean")return this.check(i,o=>{n[t]=o},s);if(typeof i=="number"){if(t==="glancesUntil")return this.seconds(i,h=>{n[t]=h},s);const o=t.endsWith("S")&&!t.endsWith("PerS"),c=t.endsWith("Deg")?"°":o?"s":t.endsWith("M")?"m":t==="cdM2"?"cd/m²":t==="hz"?"Hz":"";return this.number(i,h=>{n[t]=h},s,c,t==="pitchShare"||o||t.endsWith("PerS")?.05:t.endsWith("M")?.01:1)}if(Array.isArray(i)&&i.length>0&&i.every(o=>typeof o=="object"&&o!==null&&typeof o.t=="number"))return this.rows(i,s);if(Array.isArray(i)&&i.every(o=>typeof o=="object"&&o!==null&&typeof o.sourceId=="string"))return document.createTextNode(this.messages.parts.replace("{n}",String(i.length)));if(Array.isArray(i)&&i.every(o=>typeof o=="string"))return document.createTextNode(i.join(", "));if(Array.isArray(i))return document.createTextNode(this.messages.points.replace("{n}",String(i.length)));if(typeof i=="object"&&i!==null){const o=i;if(typeof o.lat=="number"&&typeof o.lng=="number"){const c=document.createElement("span");return typeof o.t=="number"&&c.append(this.seconds(o.t,h=>{o.t=h},s,`${this.messages.at} `)," "),c.append(this.position(i,s)),c}return typeof o.x=="number"?document.createTextNode(`${o.x}, ${o.y}, ${o.z} m`):typeof o.azimuthDeg=="number"&&typeof o.altitudeDeg=="number"?this.direction(o,s):document.createTextNode(Object.entries(o).map(([c,h])=>`${c} ${h??"∅"}`).join(", "))}return document.createTextNode(String(i))}choice(e,t,i,s,n){const r=document.createElement("select");for(const a of i.values){const o=document.createElement("option");o.value=a,o.textContent=this.messages.choices[`${e}.${a}`]??a,r.append(o)}return i.values.includes(t)||r.prepend(new Option(t,t)),r.value=t,r.addEventListener("change",()=>this.edited(()=>s(r.value),n)),r}actorChoice(e,t,i,s){const n=document.createElement("select"),r=[...Vt.ids(this.host.sighting())].filter(([,a])=>a.some(o=>t.includes(o))).map(([a])=>a);r.includes(e)||r.unshift(e);for(const a of r){const o=Vt.kindOf(this.host.sighting(),a),c=o==="body"?this.host.bodyLabel?.(a):o==="shape"||o==="group"?this.host.shapesLabel?.(a):void 0;n.append(new Option(c??a,a))}return n.value=e,n.addEventListener("change",()=>this.edited(()=>i(n.value),s)),n}direction(e,t){const i=document.createElement("span");i.className="event-direction",i.append(`${this.messages.params.azimuthDeg??"azimuthDeg"} `,this.number(e.azimuthDeg,n=>{e.azimuthDeg=(n%360+360)%360},t,"°",.1));const s=this.host.compassPoint?.(e.azimuthDeg);if(s){const n=document.createElement("span");n.className="event-direction-point",n.textContent=s,i.append(" ",n)}if(i.append(` ${this.messages.params.altitudeDeg??"altitudeDeg"} `,this.number(e.altitudeDeg,n=>{e.altitudeDeg=Math.max(-90,Math.min(90,n))},t,"°",.1)),e.altitudeDeg===90&&i.append(` (${this.messages.zenith})`),this.host.lookedAt){const n=document.createElement("button");n.type="button",n.className="event-direction-look",n.textContent=this.messages.lookedAt,n.title=this.messages.lookedAtHint,n.addEventListener("click",()=>{const r=this.host.lookedAt?.();r&&this.edited(()=>{e.azimuthDeg=Math.round((r.azimuthDeg%360+360)%360*10)/10,e.altitudeDeg=Math.round(r.altitudeDeg*10)/10},t)}),i.append(" ",n)}return i}rows(e,t){const i=Object.keys(e[0]).filter(o=>o!=="t"&&typeof e[0][o]=="number"),s={kmh:"km/h",degPerS:"°/s",widthM:"m",heightM:"m",altitudeM:"m"},n=document.createElement("span");n.className="event-rows",n.style.setProperty("--columns",String(3+i.length)),e.forEach((o,c)=>{n.append(this.seconds(o.t,d=>{o.t=d,e.sort((u,p)=>u.t-p.t)},t,`${this.messages.at} `));for(const d of i)n.append(this.number(o[d],u=>{o[d]=u},t,s[d]??"",d==="divisor"?.05:1));if(c===0)n.append(document.createElement("span"));else{const d=document.createElement("label");d.className="event-row-step",d.title=this.messages.atOnceHint;const u=this.check(o.step===!0,p=>{p?o.step=!0:delete o.step},t);u.title=this.messages.atOnceHint,d.append(u,` ${this.messages.atOnce}`),n.append(d)}const h=document.createElement("button");h.type="button",h.className="icon-btn event-row-remove",h.innerHTML=we.TRASH,h.title=h.ariaLabel=this.messages.removeRow,h.disabled=e.length<2,h.addEventListener("click",()=>this.edited(()=>{e.splice(c,1)},t)),n.append(h)});const r=document.createElement("button");r.type="button",r.className="icon-btn event-row-add",r.innerHTML=we.PLUS,r.title=r.ariaLabel=this.messages.addRow,r.addEventListener("click",()=>this.edited(()=>{const o=e[e.length-1],c={...o,t:o.t+1e3};delete c.step,e.push(c)},t));const a=document.createElement("span");return a.className="event-table",a.append(n,r),a}position(e,t){const i=this.host.positionFrame?.(),s=this.host.positionMessages?.();if(!i||!s){const a=document.createElement("span");return a.append(this.number(e.lat,o=>{e.lat=o},t,"°",1e-6)," ",this.number(e.lng,o=>{e.lng=o},t,"°",1e-6)),a}ow();const n=document.createElement("rr0-input-position");n.setAttribute("native","geo"),n.setAttribute("name",t.replace(/\./g,"-")),n.build(),n.messages=s,n.basisShown=!1,n.frame=i,n.value={lat:e.lat,lng:e.lng},n.said=e.said;let r;return n.addEventListener("positionchange",a=>{r=a.detail}),n.addEventListener("focusout",a=>{if(!r||n.contains(a.relatedTarget))return;const{value:o,said:c}=r;r=void 0,"lat"in o&&this.edited(()=>{e.lat=Math.round(o.lat*1e7)/1e7,e.lng=Math.round(o.lng*1e7)/1e7,c?e.said=c:delete e.said},t)}),n}text(e,t,i){const s=document.createElement("input");return s.type="text",s.value=e,s.addEventListener("change",()=>this.edited(()=>t(s.value.trim()),i)),s}check(e,t,i){const s=document.createElement("input");return s.type="checkbox",s.checked=e,s.addEventListener("change",()=>this.edited(()=>t(s.checked),i)),s}edited(e,t){this.host.editing(),e(),this.host.sighting().provenance.clear(t),ht.refresh(this.host.sighting()),this.host.changed()}seconds(e,t,i,s=""){const n=this.number(e/1e3,a=>t(Math.round(a*1e3)),i,"s",.1);if(!s)return n;const r=document.createElement("span");return r.append(s,n),r}number(e,t,i,s,n){const r=document.createElement("label"),a=document.createElement("input");return a.type="number",a.step=String(n),a.value=String(n<.001?e:Math.round(e*1e3)/1e3),a.addEventListener("change",()=>{const o=Number(a.value);a.value===""||!Number.isFinite(o)||this.edited(()=>t(o),i)}),r.append(a),s&&r.append(` ${s}`),r}basis(e){aw();const t=document.createElement(Zr.TAG);return t.anchorKey=e,t.messages={title:this.messages.basisTitle,basis:this.messages.basis,basisField:this.messages.basisField,howField:this.messages.howField,rationaleField:this.messages.rationaleField},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",i=>{const s=i.detail.entry;this.host.editing(),s?this.host.sighting().provenance.set(e,s):this.host.sighting().provenance.clear(e),this.host.changed()}),t}}class Rt{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(e){const t=Math.sqrt(2*Rt.EARTH_RADIUS_M*Math.max(e,0));return Math.max(Rt.GROUND_RADIUS_M,Math.min(t,Rt.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(e,t){if(t<Rt.AIRBORNE_FROM_M)return e;const i=Math.min(Rt.SHARP_GROUND_MAX_M,Math.max(Rt.SHARP_GROUND_MIN_M,t*Rt.SHARP_GROUND_HEIGHTS));return Math.min(e,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(e,t,i){if(e<Rt.AIRBORNE_FROM_M||t>-3)return;const s=e/Math.tan(-t*Math.PI/180);if(!(s<=i*Rt.LOOK_WITHIN_SHARE||s>Rt.MAX_GROUND_VISIBILITY_M))return{distanceM:s,radiusM:Math.max(Rt.SHARP_GROUND_MIN_M,s*Rt.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(e){return Rt.REBUILD_DISTANCE_M*(e/Rt.GROUND_RADIUS_M)}static decorReachFor(e,t){if(t&&t.length>=2){const n=t[0];for(const r of t){const a=ot(r.lat,r.lng,n.lat,n.lng);if(Math.hypot(a.x,a.z)>Rt.STILL_OBSERVER_M)return 0}}let i=0;for(const n of e){if(n.kind==="aircraft"||n.kind==="observer"||n.track)continue;const r=Math.max(n.sizeM?.widthM??0,n.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(n.eastM,n.northM)+r)}const s=Math.ceil(i/Rt.PATCH_WHOLE_SHARE/100)*100;return s>Rt.GROUND_RADIUS_M*Rt.PATCH_WHOLE_SHARE?Math.min(s,Rt.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=Rt.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(e,t,i){return e>=Rt.FAR_RING_RADIUS_M?!1:t>=Rt.OVERLOOK_M||i>e}static beamReachFor(e,t){let i=0;for(const s of e)for(const n of[...s.path,...(s.moves??[]).flatMap(r=>r.path)]){const r=ot(n.lat,n.lng,t.lat,t.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}const JD=ls.catalog({en:()=>Q(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(l=>l.beamKindMessages_en),fr:()=>Q(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(l=>l.beamKindMessages_fr),es:()=>Q(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(l=>l.beamKindMessages_es),it:()=>Q(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(l=>l.beamKindMessages_it)}),Ux={key:"beams",messages:JD,pickKind:"beam",simulation:()=>Q(async()=>{const{BeamSystem:l}=await import("./BeamSystem-Dd5G0PNW.js");return{BeamSystem:l}},__vite__mapDeps([4,5]),import.meta.url).then(({BeamSystem:l})=>()=>new l),editor:()=>Q(async()=>{const{BeamEditor:l}=await import("./BeamEditor-DQp2vKdn.js");return{BeamEditor:l}},__vite__mapDeps([6,5,1]),import.meta.url).then(({BeamEditor:l})=>(e,t,i)=>new l(e,t,i)),reachM:(l,e)=>Rt.beamReachFor(l,e),describe:(l,e,{texts:t,name:i,distance:s})=>({name:i,detail:t.detail.replace("{name}",i).replace("{wavelength}",String(l.wavelengthNm)).replace("{power}",l.powerW.toLocaleString()).replace("{distance}",s(e.distanceM??0))})},QD=ls.catalog({en:()=>Q(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(l=>l.launchKindMessages_en),fr:()=>Q(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(l=>l.launchKindMessages_fr),es:()=>Q(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(l=>l.launchKindMessages_es),it:()=>Q(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(l=>l.launchKindMessages_it)}),Bx={key:"launches",messages:QD,pickKind:"plume",simulation:()=>Q(async()=>{const{LaunchSimulation:l}=await import("./LaunchSimulation-Bl72jnqq.js");return{LaunchSimulation:l}},__vite__mapDeps([7,8]),import.meta.url).then(({LaunchSimulation:l})=>()=>new l),editor:()=>Q(async()=>{const{LaunchEditor:l}=await import("./LaunchEditor-hAMtWhby.js");return{LaunchEditor:l}},__vite__mapDeps([9,1,8]),import.meta.url).then(({LaunchEditor:l})=>(e,t,i)=>new l(e,t,i)),describe:(l,e,{said:t,texts:i,distance:s})=>{const n=e.detail,r=t.read(l.title)||l.vehicle?.mission||i.name,a=n.release===void 0||n.release==="burn"?void 0:l.jets?.find((c,h)=>`jet:${c.id??h}`===n.release),o=n.release===void 0||n.release==="burn"?i.ascent:a?.kind==="vent"?i.vent:i.burn;return{name:r,detail:i.detail.replace("{name}",r).replace("{part}",o).replace("{distance}",s(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},ek=ls.catalog({en:()=>Q(()=>import("./ReentryKindMessages_en-Cbgk3paQ.js"),[],import.meta.url).then(l=>l.reentryKindMessages_en),fr:()=>Q(()=>import("./ReentryKindMessages_fr-D9r9x2bK.js"),[],import.meta.url).then(l=>l.reentryKindMessages_fr),es:()=>Q(()=>import("./ReentryKindMessages_es-DwgJQanC.js"),[],import.meta.url).then(l=>l.reentryKindMessages_es),it:()=>Q(()=>import("./ReentryKindMessages_it-DQ-J5YpD.js"),[],import.meta.url).then(l=>l.reentryKindMessages_it)}),zx={key:"reentries",messages:ek,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>Q(async()=>{const{ReentrySimulation:l}=await import("./ReentrySimulation-DS7Q5nso.js");return{ReentrySimulation:l}},[],import.meta.url).then(({ReentrySimulation:l})=>()=>new l),editor:()=>Q(async()=>{const{ReentryEditor:l}=await import("./ReentryEditor-Bt90y2I7.js");return{ReentryEditor:l}},__vite__mapDeps([10,1]),import.meta.url).then(({ReentryEditor:l})=>(e,t,i)=>new l(e,t,i)),describe:(l,e,{said:t,texts:i})=>{const s=e.detail,n=(l.title?t.read(l.title):"")||l.object?.name||i.name,r=s.view.head,a=6371,o=Math.sqrt(a**2+r.distanceKm**2+2*a*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-a;return{name:(s.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",n).replace("{mag}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(o).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},Qp=Ye.point("skyEvents").provide(Ye.BUILT_IN,[{id:Bx.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Bx},{id:Ux.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Ux},{id:zx.key,name:"Fireballs",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>zx}]);class Or{static built=new WeakMap;static of(e){let t=Or.built.get(e);return t||(t=e.create(),Or.built.set(e,t)),t}static eventsOf(e,t){const i=e?.[t.key];return Array.isArray(i)?i:[]}}const tk=ls.catalog({en:()=>Q(()=>import("./DecorParameterTexts_en-C5dEeI_C.js"),[],import.meta.url).then(l=>l.decorParameterTexts_en),fr:()=>Q(()=>import("./DecorParameterTexts_fr-CThgxosI.js"),[],import.meta.url).then(l=>l.decorParameterTexts_fr),es:()=>Q(()=>import("./DecorParameterTexts_es-BysMOaxT.js"),[],import.meta.url).then(l=>l.decorParameterTexts_es),it:()=>Q(()=>import("./DecorParameterTexts_it-D0ZsTK16.js"),[],import.meta.url).then(l=>l.decorParameterTexts_it)});class ca extends Error{constructor(e,t){super(t),this.reason=e,this.name="SurroundingsUnavailableError"}}class bi{static MAX_STOPS=12;static METRES_PER_DEGREE=111320;static SAME_TREE_M=1.5;static SAME_BUILDING_M=2.5;static SAME_STRUCTURE_M=5;static stops(e,t){if(e.length===0)return[];const i=e[0],s=Math.cos(i.lat*Math.PI/180),n=e.slice(1).map((f,m)=>Math.hypot((f.lat-e[m].lat)*bi.METRES_PER_DEGREE,(f.lng-e[m].lng)*bi.METRES_PER_DEGREE*s)),r=n.reduce((f,m)=>f+m,0),a=Math.max(t,r/(bi.MAX_STOPS-1)),o=[i];let c=0,h=a;e.slice(1).forEach((f,m)=>{c+=n[m],c>=h&&(o.push(f),h=c+a)});const d=e[e.length-1],u=o[o.length-1];return Math.hypot((d.lat-u.lat)*bi.METRES_PER_DEGREE,(d.lng-u.lng)*bi.METRES_PER_DEGREE*s)>t/2&&o.length<bi.MAX_STOPS&&o.push(d),o}static async fetch(e,t,i,s={}){if(t.length===0)throw new ca("no-coverage","No place to ask about");const n=t[0],r=Math.cos(n.lat*Math.PI/180),a=new Array(t.length).fill(void 0),o=[],c=Math.max(1,s.concurrency??3);let h=0;const d=async()=>{for(;h<t.length;){const m=h++;try{a[m]=await e.getSurroundings(t[m],i)}catch(v){o.push(v)}}};await Promise.all(Array.from({length:Math.min(c,t.length)},d));const u={trees:[],buildings:[],bridges:[],lines:[]};let p=!1;const f={};if(a.forEach((m,v)=>{if(!m)return;p=!0;const g=(t[v].lng-n.lng)*bi.METRES_PER_DEGREE*r,b=(t[v].lat-n.lat)*bi.METRES_PER_DEGREE,w=M=>M.map(x=>({...x,eastM:Math.round((x.eastM+g)*10)/10,northM:Math.round((x.northM+b)*10)/10})),y=w(m.trees).sort((M,x)=>Math.hypot(M.eastM-g,M.northM-b)-Math.hypot(x.eastM-g,x.northM-b)).slice(0,s.treesPerStop??m.trees.length);bi.add(u.trees,y,(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_TREE_M),bi.add(u.buildings,w(m.buildings),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_BUILDING_M&&Math.abs(M.widthM-x.widthM)<1.5&&Math.abs(M.lengthM-x.lengthM)<1.5),bi.add(u.bridges,w(m.bridges),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_STRUCTURE_M),bi.add(u.lines,w(m.lines),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_STRUCTURE_M&&Math.abs(M.lengthM-x.lengthM)<5),bi.addFurniture(u,m,w),m.incomplete&&(u.incomplete=!0);for(const M of["laser","photo","map","lamps"]){const x=m.dates?.[M];x&&(!f[M]||x>f[M])&&(f[M]=x)}}),!p)throw o.find(m=>!(m instanceof ca&&m.reason==="no-coverage"))??o[0];return Object.keys(f).length>0&&(u.dates=f),u}static later(e,t,i){if(!e.later||t.length===0)return;const s=t[0],n=Math.cos(s.lat*Math.PI/180),r=t.map(a=>e.later(a,i)??Promise.reject(new Error("Nothing comes late")));return Promise.allSettled(r).then(a=>{if(!a.some(c=>c.status==="fulfilled"))throw a[0].reason;const o={};return a.forEach((c,h)=>{if(c.status!=="fulfilled")return;const d=(t[h].lng-s.lng)*bi.METRES_PER_DEGREE*n,u=(t[h].lat-s.lat)*bi.METRES_PER_DEGREE,p=m=>m.map(v=>({...v,eastM:Math.round((v.eastM+d)*10)/10,northM:Math.round((v.northM+u)*10)/10}));bi.addFurniture(o,c.value,p);const f=c.value.dates?.lamps;f&&(!o.dates?.lamps||f>o.dates.lamps)&&(o.dates={lamps:f})}),o})}static addFurniture(e,t,i){t.lamps&&bi.add(e.lamps??=[],i(t.lamps),(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1);const s=(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1&&Math.abs((n.headingDeg-r.headingDeg+540)%360-180)<10;t.signals&&bi.add(e.signals??=[],i(t.signals),s),t.crossings&&bi.add(e.crossings??=[],i(t.crossings),s),t.signs&&bi.add(e.signs??=[],i(t.signs),s),t.credits&&bi.add(e.credits??=[],t.credits,(n,r)=>n.url===r.url)}static add(e,t,i){for(const s of t)e.some(n=>i(n,s))||e.push(s)}}const Hx="#ff2200",Gx="#00ff44",hc="#ffffff",Of="#ffa500",mh="#ff0000",ik="#2244ff",xb=[{id:"airliner",name:"Airliner",kinds:["aircraft"],referenceSizeM:{widthM:34,heightM:12,lengthM:36},create:()=>[{id:"nav-port",offsetM:{x:-17,y:0,z:0},color:Hx,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Gx,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:hc,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:hc,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:hc,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01,phase:.08}}]},{id:"helicopter",name:"Helicopter",kinds:["aircraft"],referenceSizeM:{widthM:10,heightM:4,lengthM:14},create:()=>[{id:"nav-port",offsetM:{x:-5,y:0,z:0},color:Hx,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Gx,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:hc,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:hc,intensity:15,pattern:{kind:"flash",perMinute:75,dutyCycle:.015}}]},{id:"car-headlights",name:"Car, headlights on",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"head-left",offsetM:{x:-.7,y:.6,z:2},color:hc,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:hc,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:mh,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:mh,pattern:{kind:"steady"}}]},{id:"car-hazards",name:"Car, hazard flashers",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"hazard-front-left",offsetM:{x:-.8,y:.6,z:2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}}]},{id:"emergency-beacons",name:"Emergency vehicle beacons",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"beacon-blue",offsetM:{x:-.4,y:1.6,z:0},color:ik,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:mh,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>gt.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>gt.pedestrianLights(0)},{id:"streetlamp",name:"Streetlamp",kinds:["streetlight"],referenceSizeM:{widthM:1,heightM:5,lengthM:1},create:()=>[{id:"lamp",offsetM:{x:0,y:5,z:0},color:"#ffd9a0",intensity:2,pattern:{kind:"steady"}}]}];class Zd{static forKind(e){return xb.filter(t=>t.kinds.includes(e))}static byId(e){return xb.find(t=>t.id===e)}}class gt{static CYCLE_S=90;static GREEN_S=41;static AMBER_S=3;static PEDESTRIAN_DELAY_S=2;static PEDESTRIAN_GREEN_S=30;static VEHICLE_INTENSITY=3;static PEDESTRIAN_INTENSITY=1.5;static LENS_RADIUS_M=.1;static BEAM_DEG=30;static VEHICLE_HEAD_Y_M=2.9;static PEDESTRIAN_HEAD_Y_M=2.6;static LENS_SPACING_M=.3;static LENS_FRONT_M=.13;static RED="#ff1e00";static AMBER="#ffa200";static GREEN="#00ff8c";static phaseOf(e){const t=(e%180+180)%180;return t>=45&&t<135?1:0}static vehicleLights(e){const t=e*gt.CYCLE_S/2,i=gt.VEHICLE_HEAD_Y_M,s=gt.LENS_SPACING_M;return[gt.lamp("red",gt.RED,i+s,t+gt.GREEN_S+gt.AMBER_S,gt.CYCLE_S-gt.GREEN_S-gt.AMBER_S,gt.VEHICLE_INTENSITY),gt.lamp("amber",gt.AMBER,i,t+gt.GREEN_S,gt.AMBER_S,gt.VEHICLE_INTENSITY),gt.lamp("green",gt.GREEN,i-s,t,gt.GREEN_S,gt.VEHICLE_INTENSITY)]}static pedestrianLights(e){const t=e*gt.CYCLE_S/2+gt.GREEN_S+gt.AMBER_S+gt.PEDESTRIAN_DELAY_S,i=gt.PEDESTRIAN_HEAD_Y_M,s=gt.LENS_SPACING_M/2;return[gt.lamp("ped-red",gt.RED,i+s,t+gt.PEDESTRIAN_GREEN_S,gt.CYCLE_S-gt.PEDESTRIAN_GREEN_S,gt.PEDESTRIAN_INTENSITY),gt.lamp("ped-green",gt.GREEN,i-s,t,gt.PEDESTRIAN_GREEN_S,gt.PEDESTRIAN_INTENSITY)]}static isPedestrian(e){return e?.some(t=>t.id==="ped-green")??!1}static figureOf(e){return e.id==="ped-red"?"standing":e.id==="ped-green"?"walking":void 0}static lamp(e,t,i,s,n,r){const a=gt.CYCLE_S,o=Math.round(((1-s/a)%1+1)%1*1e6)/1e6;return{id:e,color:t,intensity:r,radiusM:gt.LENS_RADIUS_M,beamDeg:gt.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/a,dutyCycle:Math.round(n/a*1e6)/1e6,...o?{phase:o}:{}}}}}class Dd{static FLOOR_HEIGHT_M=3;static CROSSING_LENGTH_M=2.5;static of(e,t,i){const{kept:s}=i,n=g=>s.some(b=>b.kind===g),r={tree:n("tree"),building:n("building"),bridge:n("bridge"),wire:n("wire"),streetlight:n("streetlight"),trafficlight:n("trafficlight"),crossing:n("crossing"),roadsign:n("roadsign")},a=[...s,...i.others??[]],o=new Set(a.map(g=>g.id));let c=0;const h=()=>{let g;do g=`${e}-${++c}`;while(o.has(g));return o.add(g),g},d={tree:a.filter(g=>g.kind==="tree").length,building:a.filter(g=>g.kind==="building").length,bridge:a.filter(g=>g.kind==="bridge").length,wire:a.filter(g=>g.kind==="wire").length,streetlight:a.filter(g=>g.kind==="streetlight").length,trafficlight:a.filter(g=>g.kind==="trafficlight").length,crossing:a.filter(g=>g.kind==="crossing").length,roadsign:a.filter(g=>g.kind==="roadsign").length},u=new Set(a.map(g=>typeof g.title=="string"?g.title:"")),p=(g,b)=>{const w=b??`${i.kindName(g)} ${++d[g]}`;let y=w;for(let M=2;u.has(y);M++)y=`${w} (${M})`;return u.add(y),y},f=t.dates??{},m=(...g)=>{const b=g.filter(w=>w!==void 0).sort().at(-1);return b?{surveyedOn:b}:{}},v=[];if(!r.tree)for(const g of t.trees)v.push({id:h(),kind:"tree",title:p("tree",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.widthM,heightM:g.heightM},origin:e,...m(f.laser)});if(!r.building)for(const g of t.buildings)v.push({id:h(),kind:"building",title:p("building",g.name),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.lengthM,heightM:g.heightM},...g.style==="church"||g.style==="monument"?{}:{floors:g.floors??Math.max(1,Math.round((g.heightM-(g.roof?.riseM??0))/(g.facade?.storeyM??Dd.FLOOR_HEIGHT_M)))},...g.roof?{roof:g.roof}:{},...g.facade?{facade:g.facade}:{},origin:e,...m(f.map,f.laser,g.roof?.color?f.photo:void 0)});if(!r.bridge)for(const g of t.bridges)v.push({id:h(),kind:"bridge",title:p("bridge",g.name?`${i.kindName("bridge")} (${g.name})`:void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,widthM:g.widthM,heightM:g.heightM},origin:e,...m(f.map,f.laser)});if(!r.wire)for(const g of t.lines)v.push({id:h(),kind:"wire",title:p("wire",`${i.kindName("wire")} (${g.voltage})`),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,heightM:g.heightM},wire:{strands:g.acrossM.map(b=>({heightM:g.heightM,acrossM:b})),poles:"both",poleHeightM:g.poleHeightM},origin:e,...m(f.map,f.laser)});if(!r.streetlight)for(const g of t.lamps??[]){const b={...g.colorTemperatureK?{colorTemperatureK:g.colorTemperatureK}:{},...g.lumens?{lumens:g.lumens}:{},...g.mount==="wall"?{mount:"wall"}:{},...g.supposed?{supposed:!0}:{}};v.push({id:h(),kind:"streetlight",title:p("streetlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,...g.heightM?{sizeM:{heightM:g.heightM}}:{},...Object.keys(b).length>0?{lamp:b}:{},origin:e,...m(f.lamps)})}if(!r.trafficlight)for(const g of t.signals??[])v.push({id:h(),kind:"trafficlight",title:p("trafficlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lights:g.for==="pedestrians"?gt.pedestrianLights(g.phase):gt.vehicleLights(g.phase),origin:e,...m(f.lamps)});if(!r.crossing)for(const g of t.crossings??[])v.push({id:h(),kind:"crossing",title:p("crossing",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sizeM:{widthM:g.widthM,lengthM:Dd.CROSSING_LENGTH_M},origin:e,...m(f.lamps)});if(!r.roadsign)for(const g of t.signs??[])v.push({id:h(),kind:"roadsign",title:p("roadsign",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sign:{face:g.face,...g.code?{code:g.code}:{},...g.value?{value:g.value}:{}},origin:e,...m(f.lamps)});return{planted:v,handPlaced:Object.values(r).some(Boolean)}}}class dn{constructor(e,t,i,s,n={}){this.status=e,this.host=t,this.loadProvider=s,this.messages=i,this.debounceMs=n.debounceMs??dn.DEFAULT_DEBOUNCE_MS,this.radiusM=n.radiusM??dn.DEFAULT_RADIUS_M}static SAME_PLACE_M=25;static METRES_PER_DEGREE=111320;static DEFAULT_RADIUS_M=100;static DEFAULT_DEBOUNCE_MS=800;static TREES_PER_STOP=80;static WALK_LEAD_S=4;static WALK_LEAD_SHARE=.6;static SAME_BUILDING_M=3;static SAME_OBJECT_M=1.5;messages;debounceMs;radiusM;enabled=!0;surveyedFor;timer;token=0;surveyed="";furnitureSaid="";furnitureCredits=[];asked=[];lastStep;walkSpeedMps=0;setMessages(e){this.messages=e}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.cancel())}withdraw(){this.cancel(),this.withdrawPlanted(),this.say("")}placeLoaded(e,t){this.cancel(),this.surveyedFor=e!==void 0&&t!==void 0?{lat:e,lng:t}:void 0,this.say("")}radiusChanged(e,t,i){e!==this.radiusM&&(this.radiusM=e,!(!this.enabled||t===void 0||i===void 0)&&(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(t,i),this.debounceMs)))}placeChanged(e,t){!this.enabled||e===void 0||t===void 0||this.surveyedFor&&this.isSamePlace(this.surveyedFor,e,t)||(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(e,t),this.debounceMs))}walked(e,t,i,s=Date.now()){if(clearTimeout(this.timer),this.timer=void 0,this.surveyedFor={lat:e,lng:t},this.lastStep){const o=(s-this.lastStep.atMs)/1e3,c=this.metresBetween(this.lastStep,e,t);this.walkSpeedMps=o>0&&o<2?.5*this.walkSpeedMps+.5*c/o:0}if(this.lastStep={lat:e,lng:t,atMs:s},!this.enabled)return;const n=Math.min(this.radiusM,Math.max(this.radiusM*dn.WALK_LEAD_SHARE,this.walkSpeedMps*dn.WALK_LEAD_S)),r=i*Math.PI/180,a={lat:e+Math.cos(r)*n/dn.METRES_PER_DEGREE,lng:t+Math.sin(r)*n/(dn.METRES_PER_DEGREE*Math.cos(e*Math.PI/180))};this.asked.some(o=>this.metresBetween(o,a.lat,a.lng)<this.radiusM/2)||(this.asked.push(a),this.plantAhead(a))}async plantAhead(e){const t=this.token;try{const i=await this.loadProvider(e.lat,e.lng);if(!i||t!==this.token)return;const s=await i.getSurroundings(e,this.radiusM);if(t!==this.token)return;this.addAhead(i,this.fromCentre(s,e)),(s.incomplete?i.later?.(e,this.radiusM):void 0)?.then(r=>{t===this.token&&this.addAhead(i,this.fromCentre({trees:[],buildings:[],bridges:[],lines:[],...r},e))},()=>{})}catch{this.asked=this.asked.filter(i=>i!==e)}}addAhead(e,t){const i=this.host.decor(),s=i.filter(o=>o.origin===void 0),n=i.filter(o=>o.origin!==void 0),{planted:r}=Dd.of(e.id,t,{kept:s,others:n,kindName:o=>this.host.kindName(o)}),a=r.filter(o=>!n.some(c=>dn.same(c,o)));a.length>0&&this.host.setDecor([...i,...a])}static same(e,t){if(e.kind!==t.kind)return!1;const i=Math.hypot(e.eastM-t.eastM,e.northM-t.northM);if(e.kind!=="building")return i<dn.SAME_OBJECT_M;const s=n=>[n.sizeM?.widthM??0,n.sizeM?.lengthM??0];return i<dn.SAME_BUILDING_M&&s(e).every((n,r)=>Math.abs(n-s(t)[r])<1.5)}fromCentre(e,t){const i=this.host.centre?.();if(!i)return e;const s=(t.lng-i.lng)*dn.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180),n=(t.lat-i.lat)*dn.METRES_PER_DEGREE;if(Math.hypot(s,n)<.01)return e;const r=a=>a?.map(o=>({...o,eastM:Math.round((o.eastM+s)*100)/100,northM:Math.round((o.northM+n)*100)/100}));return{...e,...e.trees?{trees:r(e.trees)}:{},...e.buildings?{buildings:r(e.buildings)}:{},...e.bridges?{bridges:r(e.bridges)}:{},...e.lines?{lines:r(e.lines)}:{},...e.lamps?{lamps:r(e.lamps)}:{},...e.signals?{signals:r(e.signals)}:{},...e.crossings?{crossings:r(e.crossings)}:{},...e.signs?{signs:r(e.signs)}:{}}}metresBetween(e,t,i){const s=(e.lat-t)*dn.METRES_PER_DEGREE,n=(e.lng-i)*dn.METRES_PER_DEGREE*Math.cos(t*Math.PI/180);return Math.hypot(s,n)}async survey(e,t){const i=++this.token;this.surveyedFor={lat:e,lng:t},this.asked=[{lat:e,lng:t}],this.lastStep=void 0,this.host.busy(!0,this.messages.surveyBusy);try{const s=await this.loadProvider(e,t);if(i!==this.token)return;if(s===void 0){this.withdrawPlanted(),this.say("");return}this.say(this.messages.surveyBusy);const n=bi.stops([{lat:e,lng:t},...this.host.track?.()??[]],this.radiusM),r=n.length>1?await bi.fetch(s,n,this.radiusM,{treesPerStop:dn.TREES_PER_STOP}):await s.getSurroundings({lat:e,lng:t},this.radiusM);if(i!==this.token)return;this.plant(s,this.fromCentre(r,{lat:e,lng:t})),r.incomplete&&this.awaitLate(s,n,i)}catch(s){if(i!==this.token)return;s instanceof ca&&s.reason==="no-coverage"?(this.withdrawPlanted(),this.say("")):this.say(this.messages.surveyUnreachable)}finally{i===this.token&&this.host.busy(!1,"")}}cancel(){clearTimeout(this.timer),this.timer=void 0,this.token++,this.host.busy(!1,"")}withoutPlanted(){return this.host.decor().filter(e=>e.origin===void 0)}withdrawPlanted(){this.host.decor().some(e=>e.origin!==void 0)&&this.host.setDecor(this.withoutPlanted())}plant(e,t){const i=this.withoutPlanted(),{planted:s,handPlaced:n}=Dd.of(e.id,t,{kept:i,kindName:c=>this.host.kindName(c)}),r=c=>s.filter(h=>h.kind===c).length;if((s.length>0||this.host.decor().length!==i.length)&&this.host.setDecor([...i,...s]),s.length===0){this.furnitureSaid="",this.surveyed=n?this.messages.surveyKept:this.messages.surveyNone.replace("{radius}",String(this.radiusM)),this.say(this.surveyed,t.incomplete?this.messages.surveyFurniturePending:"");return}this.host.cite({title:`${e.name}, survey of the surroundings`,url:e.creditUrl,publication:{publisher:e.name}});const a=this.messages.surveyDone.replace("{trees}",String(r("tree"))).replace("{buildings}",String(r("building"))).replace("{bridges}",String(r("bridge"))).replace("{lines}",String(r("wire"))).replace("{source}",e.name),o=this.datesText(t.dates);this.surveyed=[a,o,n?this.messages.surveyKept:""].filter(c=>c!=="").join(" "),this.citeCredits(t),this.furnitureCredits=t.credits??[],this.furnitureSaid=this.furnitureText(s,t),this.say(this.surveyed,[this.furnitureSaid,t.incomplete?this.messages.surveyFurniturePending:""].filter(c=>c!=="").join(" "))}citeCredits(e){for(const t of e.credits??[])this.host.cite({title:t.licence?`${t.name} (${t.licence})`:t.name,url:t.url,publication:{publisher:t.name}})}awaitLate(e,t,i){const s=t.length>1?bi.later(e,t,this.radiusM):e.later?.(t[0],this.radiusM);if(!s){this.say(this.surveyed,"");return}this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurniturePending].filter(n=>n!=="").join(" ")),s.then(n=>{i===this.token&&this.plantLate(e,this.fromCentre(n,t[0]))},()=>{i===this.token&&this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurnitureUnavailable].filter(n=>n!=="").join(" "),{label:this.messages.surveyFurnitureRetry,run:()=>this.awaitLate(e,t,i)})})}plantLate(e,t){const i=this.host.decor(),{planted:s}=Dd.of(e.id,{trees:[],buildings:[],bridges:[],lines:[],...t},{kept:i,kindName:r=>this.host.kindName(r)});s.length>0&&this.host.setDecor([...i,...s]),this.citeCredits(t);const n=i.filter(r=>r.origin===e.id).concat(s);this.furnitureSaid=this.furnitureText(n,{credits:[...this.furnitureCredits,...t.credits??[]]}),this.say(this.surveyed,this.furnitureSaid)}furnitureText(e,t){const i=a=>e.filter(o=>o.kind===a).length;if(!e.some(a=>a.kind==="streetlight"||a.kind==="trafficlight"||a.kind==="crossing"||a.kind==="roadsign"))return"";const s=a=>a.of==="lamps"?i("streetlight")>0:a.of==="signals"?i("trafficlight")>0:!0,r=[...new Set((t.credits??[]).filter(s).map(a=>a.name))].join(" + ")||"OpenStreetMap";return this.messages.surveyFurnitureDone.replace("{source}",r).replace("{lamps}",String(i("streetlight"))).replace("{signals}",String(i("trafficlight"))).replace("{crossings}",String(i("crossing"))).replace("{signs}",String(i("roadsign")))}datesText(e){if(!e)return"";const t=[["laser",this.messages.surveyLaserLabel],["photo",this.messages.surveyPhotoLabel],["map",this.messages.surveyMapLabel],["lamps",this.messages.surveyLampsLabel]].filter(([i])=>e[i]!==void 0).map(([i,s])=>`${s} ${e[i]}`);return t.length>0?this.messages.surveyDated.replace("{dates}",t.join(", ")):""}isSamePlace(e,t,i){return this.metresBetween(e,t,i)<dn.SAME_PLACE_M}say(e,t="",i){if(this.status.textContent=[e,t].filter(n=>n!=="").join(" "),!i)return;const s=this.status.ownerDocument.createElement("button");s.type="button",s.className="scenery-retry",s.textContent=i.label,s.addEventListener("click",i.run),this.status.append(" ",s)}}class Ht{static INFO="message-info";static WARNING="message-warning";static ERROR="message-error";static CSS=Ht.rules();static rules(e=[],t=[],i=[]){const s=(n,r)=>[`.${n}`,...r].join(", ");return`
|
|
654
|
+
`;static ADDABLE={observer:["look","walk","follow"],phenomenon:["stand","blink","turn","roll","vibrate","spiral","vanish"],bodies:["motion","spin","rise","turn","ride","light","blink","vanish"]};static CHOICES={sizeBy:{values:["","altitude"],absent:"",with:["sizeDeg"]},side:{values:["left","right"],with:[]},seenFrom:{values:["","craft"],absent:"",with:["side","byDeg"]}};static AMONG={target:["shape","group","body","decor"],in:["body","decor"],vehicle:["decor"]};words;get messages(){return this.words}note;reset;fields;timeline;timelineHost;empty;addButton;addMenu;deleteButton;picked;localize(e){this.words=e,this.localizeList(),this.render()}localizeList(){const e=this.messages;this.timeline.setMessages({addKeyframeHere:e.add,keyframeHere:e.add,zoomHint:e.zoomHint}),this.addButton.innerHTML=`${we.PLUS} ${e.add}`,this.addMenu.setKinds(to.ADDABLE[this.actor].map(t=>({value:t,label:e.kinds[t]??t}))),this.empty.textContent=e.none,this.deleteButton.title=e.remove,this.deleteButton.setAttribute("aria-label",e.remove)}choose(e){this.picked=e;const t=this.host.sighting().events?.[e];t&&this.host.seek(t.t),this.render(),this.host.picked?.()}syncTimeline(e){const t=this.messages,i=h=>t.kinds[h.eventType]??h.eventType,s=e.map(({event:h,index:d})=>({id:String(d),t:h.t,until:Math.max(h.t,h.until??h.t),label:i(h)})),n=s.flatMap(h=>[h.t,h.until]),r=this.host.duration?.()??Math.max(1,...n),a=Math.min(...n),o=Math.max(...n),c=Math.max(500,(o-a)/10);this.timeline.show([{id:this.actor,label:this.titleText(),color:to.COLOR,times:[],spans:s,selected:this.picked===void 0?void 0:String(this.picked),select:h=>this.choose(Number(h)),open:()=>{},add:()=>this.addButton.click()}],r,this.host.now(),{from:a-c,to:o+c})}setTime(e){this.timeline.setTime(e)}static COLOR="#4f8fd6";shownTheirs;sync(){this.theirs()!==this.shownTheirs&&this.render()}theirs(){const e=this.host.sighting();return this.actor==="observer"?ht.observerTrackIsExpanded(e):this.actor==="phenomenon"?ht.timelineIsExpanded(e):ht.bodiesAreExpanded(e)}who(){const e=this.host.sighting();if(this.actor==="observer")return Vt.observerId(e);if(this.actor==="bodies")return this.host.currentBody?.();const t=this.host.currentShapes?.();if(t!==void 0)return t;const i=(e.events??[]).find(n=>n.eventType==="stand"&&Vt.isPhenomenon(e,n));if(i?.who!==void 0)return i.who;const s=Vt.shapeIds(e);return s.length>0?e.timeline.topOf(s[0]):void 0}events(){const e=this.host.sighting(),t=this.actor==="bodies"?this.host.currentBody?.():void 0,i=s=>this.actor==="observer"?Vt.isObserver(e,s):this.actor==="phenomenon"?Vt.isPhenomenon(e,s):t!==void 0&&(s.who===t||Vt.partOf(s.who)?.element===t);return(e.events??[]).map((s,n)=>({event:s,index:n})).filter(({event:s})=>i(s))}get pickedIndex(){return this.picked}pick(e){this.picked=e,this.render(),this.root.scrollIntoView?.({block:"start"})}titleText(){return this.actor==="observer"?this.messages.title:this.actor==="phenomenon"?this.messages.phenomenonTitle:this.messages.bodyTitle.replace("{body}",this.host.bodyLabel?.(this.who()??"")??this.who()??"")}render(){if(!this.words)return;this.shownTheirs=this.theirs(),this.root.querySelector(".events-title").textContent=this.titleText(),this.root.hidden=this.actor==="bodies"&&this.who()===void 0;const e=this.events();e.some(({index:n})=>n===this.picked)||(this.picked=e[0]?.index);const t=this.shownTheirs;this.note.hidden=e.length===0,this.note.textContent=this.actor==="observer"?t?this.messages.derivedNote:this.messages.overriddenNote:this.actor==="phenomenon"?t?this.messages.derivedShapesNote:this.messages.overriddenShapesNote:t?this.messages.derivedBodiesNote:this.messages.overriddenBodiesNote,this.reset.hidden=e.length===0||t,this.reset.textContent=this.messages.resetToEvents,this.empty.hidden=e.length>0,this.timelineHost.hidden=e.length===0,this.syncTimeline(e);const i=this.picked===void 0?void 0:this.host.sighting().events?.[this.picked],s=i?this.details(i,this.picked):[];s[0]?.append(this.deleteButton),this.fields.replaceChildren(...s)}add(e){const t=this.host.sighting(),i=this.who();if(i===void 0)return;const s=Math.round(this.host.now()),n=t.observerTrack.getInterpolatedPoseAt(s)??t.observerTrack.getLatestPoseAt(s),r=n?.lat!==void 0&&n.lng!==void 0?{lat:n.lat,lng:n.lng}:t.event.place?.[0]&&{lat:t.event.place[0].lat,lng:t.event.place[0].lng},a=t.interpretation?.bodies.find(d=>d.id!==i)?.id??"",o={look:{params:{headingDeg:Math.round(n?.headingDeg??0),pitchDeg:Math.round(n?.pitchDeg??0)}},walk:{until:s+1e4,params:{from:{...r},to:{...r}}},follow:{until:s+5e3,params:{target:a}},stand:{params:{place:{...r},metres:[{t:s,widthM:1,heightM:1}]}},blink:{until:s+5e3,params:{onS:.5,offS:.5,off:{transparency:1}}},vanish:{},motion:{until:s+2e3,params:{motion:"",to:1}},spin:{until:s+5e3,params:{motion:"",turnsPerS:.5}},rise:{until:s+3e3,params:{distanceM:1,angleDeg:0,headingDeg:0,stops:!0}},ride:{params:{in:a,aboveM:0}},turn:{until:s+1e3,params:{headingDeg:0}}};this.actor==="phenomenon"&&Object.assign(o,{turn:{until:s+1e3,params:{byDeg:15,side:"left"}},roll:{until:s+500,params:{toDeg:20}},vibrate:{until:s+1e3,params:{hz:10,amplitudeShare:.1,riseS:.3}},spiral:{until:s+1e3,params:{turns:1,radiusDeg:2,shrink:.5,clockwise:!0,rollDeg:360}}}),this.actor==="bodies"&&Object.assign(o,{blink:{until:s+5e3,params:{onS:.5,offS:.5,cdM2:500}},light:{params:{cdM2:500}}});const c=o[e]??{},h={type:"event",eventType:e,who:i,t:s,...c.until===void 0?{}:{until:c.until},...c.params?{params:c.params}:{}};this.host.editing(),t.events=[...t.events??[],h],this.picked=t.events.length-1,ht.refresh(t),this.host.changed()}remove(){const e=this.host.sighting(),t=this.picked;if(t===void 0||!e.events?.[t])return;this.host.editing();const i=e.provenance,s=[];for(const n of i.paths()){const r=/^events\.(\d+)(\..*)?$/.exec(n);if(!r)continue;const a=Number(r[1]);a>t&&s.push([`events.${a-1}${r[2]??""}`,i.at(n)]),a>=t&&i.clear(n)}for(const[n,r]of s)i.set(n,r);e.events=e.events.filter((n,r)=>r!==t),this.picked=void 0,ht.refresh(e),this.host.changed()}details(e,t){const i=document.createElement("div");i.className="event-head",i.append(this.messages.from,this.seconds(e.t,r=>{e.t=r},`events.${t}.t`)),e.until!==void 0&&i.append(this.messages.to,this.seconds(e.until,r=>{e.until=r},`events.${t}.until`));const s=document.createElement("div");if(s.className="event-params",this.actor==="phenomenon"){const r=document.createElement("span");r.textContent=this.messages.who,s.append(r,this.subject(e))}if(this.actor==="bodies"){const r=document.createElement("span");r.textContent=this.messages.part,s.append(r,this.part(e))}const n=Object.entries(e.params??{});for(const[r,a]of Object.entries(to.CHOICES))a.absent!==void 0&&a.with.every(o=>e.params?.[o]!==void 0)&&e.params?.[r]===void 0&&n.push([r,a.absent]);for(const[r,a]of n){const o=document.createElement("span");o.className="event-param-label";const c=document.createElement("span");c.className="event-param-name",c.textContent=this.messages.params[r]??r;const h=this.messages.paramHints[r];h&&c.append(Jn.of(h)),o.append(c,this.basis(`events.${t}.params.${r}`));const d=document.createElement("span");d.className="event-param",d.append(this.value(e,r,a,`events.${t}.params.${r}`)),s.append(o,d)}return[i,s]}subject(e){const t=this.host.sighting(),i=document.createElement("select");i.className="event-who";const s=[...t.timeline.allGroups.map(n=>n.id),...Vt.shapeIds(t)];e.who!==void 0&&!s.includes(e.who)&&s.unshift(e.who);for(const n of s){const r=document.createElement("option");r.value=n,r.textContent=this.host.shapesLabel?.(n)??n,i.append(r)}return i.value=e.who??"",i.addEventListener("change",()=>{this.host.editing(),e.who=i.value,ht.refresh(t),this.host.changed()}),i}part(e){const t=this.host.sighting(),i=Vt.partOf(e.who),s=i?.element??e.who??"",n=document.createElement("input");return n.type="text",n.className="event-part",n.value=i?.part??"",n.placeholder=this.messages.wholeBody,n.title=this.messages.partHint,n.addEventListener("change",()=>{const r=n.value.trim().replaceAll("/","");this.host.editing(),e.who=r?`${s}/${r}`:s,ht.refresh(t),this.host.changed()}),n}value(e,t,i,s){const n=e.params,r=to.CHOICES[t];if(r&&typeof i=="string")return this.choice(t,i,r,o=>{o===r.absent?delete n[t]:n[t]=o},s);const a=to.AMONG[t];if(a&&typeof i=="string")return this.actorChoice(i,a,o=>{n[t]=o},s);if(typeof i=="string")return this.text(i,o=>{n[t]=o},s);if(typeof i=="boolean")return this.check(i,o=>{n[t]=o},s);if(typeof i=="number"){if(t==="glancesUntil")return this.seconds(i,h=>{n[t]=h},s);const o=t.endsWith("S")&&!t.endsWith("PerS"),c=t.endsWith("Deg")?"°":o?"s":t.endsWith("M")?"m":t==="cdM2"?"cd/m²":t==="hz"?"Hz":"";return this.number(i,h=>{n[t]=h},s,c,t==="pitchShare"||o||t.endsWith("PerS")?.05:t.endsWith("M")?.01:1)}if(Array.isArray(i)&&i.length>0&&i.every(o=>typeof o=="object"&&o!==null&&typeof o.t=="number"))return this.rows(i,s);if(Array.isArray(i)&&i.every(o=>typeof o=="object"&&o!==null&&typeof o.sourceId=="string"))return document.createTextNode(this.messages.parts.replace("{n}",String(i.length)));if(Array.isArray(i)&&i.every(o=>typeof o=="string"))return document.createTextNode(i.join(", "));if(Array.isArray(i))return document.createTextNode(this.messages.points.replace("{n}",String(i.length)));if(typeof i=="object"&&i!==null){const o=i;if(typeof o.lat=="number"&&typeof o.lng=="number"){const c=document.createElement("span");return typeof o.t=="number"&&c.append(this.seconds(o.t,h=>{o.t=h},s,`${this.messages.at} `)," "),c.append(this.position(i,s)),c}return typeof o.x=="number"?document.createTextNode(`${o.x}, ${o.y}, ${o.z} m`):typeof o.azimuthDeg=="number"&&typeof o.altitudeDeg=="number"?this.direction(o,s):document.createTextNode(Object.entries(o).map(([c,h])=>`${c} ${h??"∅"}`).join(", "))}return document.createTextNode(String(i))}choice(e,t,i,s,n){const r=document.createElement("select");for(const a of i.values){const o=document.createElement("option");o.value=a,o.textContent=this.messages.choices[`${e}.${a}`]??a,r.append(o)}return i.values.includes(t)||r.prepend(new Option(t,t)),r.value=t,r.addEventListener("change",()=>this.edited(()=>s(r.value),n)),r}actorChoice(e,t,i,s){const n=document.createElement("select"),r=[...Vt.ids(this.host.sighting())].filter(([,a])=>a.some(o=>t.includes(o))).map(([a])=>a);r.includes(e)||r.unshift(e);for(const a of r){const o=Vt.kindOf(this.host.sighting(),a),c=o==="body"?this.host.bodyLabel?.(a):o==="shape"||o==="group"?this.host.shapesLabel?.(a):void 0;n.append(new Option(c??a,a))}return n.value=e,n.addEventListener("change",()=>this.edited(()=>i(n.value),s)),n}direction(e,t){const i=document.createElement("span");i.className="event-direction",i.append(`${this.messages.params.azimuthDeg??"azimuthDeg"} `,this.number(e.azimuthDeg,n=>{e.azimuthDeg=(n%360+360)%360},t,"°",.1));const s=this.host.compassPoint?.(e.azimuthDeg);if(s){const n=document.createElement("span");n.className="event-direction-point",n.textContent=s,i.append(" ",n)}if(i.append(` ${this.messages.params.altitudeDeg??"altitudeDeg"} `,this.number(e.altitudeDeg,n=>{e.altitudeDeg=Math.max(-90,Math.min(90,n))},t,"°",.1)),e.altitudeDeg===90&&i.append(` (${this.messages.zenith})`),this.host.lookedAt){const n=document.createElement("button");n.type="button",n.className="event-direction-look",n.textContent=this.messages.lookedAt,n.title=this.messages.lookedAtHint,n.addEventListener("click",()=>{const r=this.host.lookedAt?.();r&&this.edited(()=>{e.azimuthDeg=Math.round((r.azimuthDeg%360+360)%360*10)/10,e.altitudeDeg=Math.round(r.altitudeDeg*10)/10},t)}),i.append(" ",n)}return i}rows(e,t){const i=Object.keys(e[0]).filter(o=>o!=="t"&&typeof e[0][o]=="number"),s={kmh:"km/h",degPerS:"°/s",widthM:"m",heightM:"m",altitudeM:"m"},n=document.createElement("span");n.className="event-rows",n.style.setProperty("--columns",String(3+i.length)),e.forEach((o,c)=>{n.append(this.seconds(o.t,d=>{o.t=d,e.sort((u,p)=>u.t-p.t)},t,`${this.messages.at} `));for(const d of i)n.append(this.number(o[d],u=>{o[d]=u},t,s[d]??"",d==="divisor"?.05:1));if(c===0)n.append(document.createElement("span"));else{const d=document.createElement("label");d.className="event-row-step",d.title=this.messages.atOnceHint;const u=this.check(o.step===!0,p=>{p?o.step=!0:delete o.step},t);u.title=this.messages.atOnceHint,d.append(u,` ${this.messages.atOnce}`),n.append(d)}const h=document.createElement("button");h.type="button",h.className="icon-btn event-row-remove",h.innerHTML=we.TRASH,h.title=h.ariaLabel=this.messages.removeRow,h.disabled=e.length<2,h.addEventListener("click",()=>this.edited(()=>{e.splice(c,1)},t)),n.append(h)});const r=document.createElement("button");r.type="button",r.className="icon-btn event-row-add",r.innerHTML=we.PLUS,r.title=r.ariaLabel=this.messages.addRow,r.addEventListener("click",()=>this.edited(()=>{const o=e[e.length-1],c={...o,t:o.t+1e3};delete c.step,e.push(c)},t));const a=document.createElement("span");return a.className="event-table",a.append(n,r),a}position(e,t){const i=this.host.positionFrame?.(),s=this.host.positionMessages?.();if(!i||!s){const a=document.createElement("span");return a.append(this.number(e.lat,o=>{e.lat=o},t,"°",1e-6)," ",this.number(e.lng,o=>{e.lng=o},t,"°",1e-6)),a}ow();const n=document.createElement("rr0-input-position");n.setAttribute("native","geo"),n.setAttribute("name",t.replace(/\./g,"-")),n.build(),n.messages=s,n.basisShown=!1,n.frame=i,n.value={lat:e.lat,lng:e.lng},n.said=e.said;let r;return n.addEventListener("positionchange",a=>{r=a.detail}),n.addEventListener("focusout",a=>{if(!r||n.contains(a.relatedTarget))return;const{value:o,said:c}=r;r=void 0,"lat"in o&&this.edited(()=>{e.lat=Math.round(o.lat*1e7)/1e7,e.lng=Math.round(o.lng*1e7)/1e7,c?e.said=c:delete e.said},t)}),n}text(e,t,i){const s=document.createElement("input");return s.type="text",s.value=e,s.addEventListener("change",()=>this.edited(()=>t(s.value.trim()),i)),s}check(e,t,i){const s=document.createElement("input");return s.type="checkbox",s.checked=e,s.addEventListener("change",()=>this.edited(()=>t(s.checked),i)),s}edited(e,t){this.host.editing(),e(),this.host.sighting().provenance.clear(t),ht.refresh(this.host.sighting()),this.host.changed()}seconds(e,t,i,s=""){const n=this.number(e/1e3,a=>t(Math.round(a*1e3)),i,"s",.1);if(!s)return n;const r=document.createElement("span");return r.append(s,n),r}number(e,t,i,s,n){const r=document.createElement("label"),a=document.createElement("input");return a.type="number",a.step=String(n),a.value=String(n<.001?e:Math.round(e*1e3)/1e3),a.addEventListener("change",()=>{const o=Number(a.value);a.value===""||!Number.isFinite(o)||this.edited(()=>t(o),i)}),r.append(a),s&&r.append(` ${s}`),r}basis(e){aw();const t=document.createElement(Zr.TAG);return t.anchorKey=e,t.messages={title:this.messages.basisTitle,basis:this.messages.basis,basisField:this.messages.basisField,howField:this.messages.howField,rationaleField:this.messages.rationaleField},t.entry=this.host.sighting().provenance.at(e),t.addEventListener("basischange",i=>{const s=i.detail.entry;this.host.editing(),s?this.host.sighting().provenance.set(e,s):this.host.sighting().provenance.clear(e),this.host.changed()}),t}}class _t{static GROUND_RADIUS_M=900;static EARTH_RADIUS_M=6371e3;static MAX_GROUND_VISIBILITY_M=3e4;static REBUILD_DISTANCE_M=150;static ROADS_MAX_RADIUS_M=5e3;static STILL_OBSERVER_M=60;static PATCH_WHOLE_SHARE=700/900;static MAX_DECOR_TERRAIN_M=3e3;static groundRadiusFor(e){const t=Math.sqrt(2*_t.EARTH_RADIUS_M*Math.max(e,0));return Math.max(_t.GROUND_RADIUS_M,Math.min(t,_t.MAX_GROUND_VISIBILITY_M))}static AIRBORNE_FROM_M=300;static SHARP_GROUND_HEIGHTS=4;static SHARP_GROUND_MIN_M=6e3;static SHARP_GROUND_MAX_M=12e3;static patchRadiusFor(e,t){if(t<_t.AIRBORNE_FROM_M)return e;const i=Math.min(_t.SHARP_GROUND_MAX_M,Math.max(_t.SHARP_GROUND_MIN_M,t*_t.SHARP_GROUND_HEIGHTS));return Math.min(e,i)}static LOOK_PATCH_SHARE=.4;static LOOK_WITHIN_SHARE=.6;static LOOK_DOWN_FROM_DEG=3;static lookPatchFor(e,t,i){if(e<_t.AIRBORNE_FROM_M||t>-3)return;const s=e/Math.tan(-t*Math.PI/180);if(!(s<=i*_t.LOOK_WITHIN_SHARE||s>_t.MAX_GROUND_VISIBILITY_M))return{distanceM:s,radiusM:Math.max(_t.SHARP_GROUND_MIN_M,s*_t.LOOK_PATCH_SHARE)}}static rebuildDistanceFor(e){return _t.REBUILD_DISTANCE_M*(e/_t.GROUND_RADIUS_M)}static decorReachFor(e,t){if(t&&t.length>=2){const n=t[0];for(const r of t){const a=ot(r.lat,r.lng,n.lat,n.lng);if(Math.hypot(a.x,a.z)>_t.STILL_OBSERVER_M)return 0}}let i=0;for(const n of e){if(n.kind==="aircraft"||n.kind==="observer"||n.track)continue;const r=Math.max(n.sizeM?.widthM??0,n.sizeM?.lengthM??0)/2;i=Math.max(i,Math.hypot(n.eastM,n.northM)+r)}const s=Math.ceil(i/_t.PATCH_WHOLE_SHARE/100)*100;return s>_t.GROUND_RADIUS_M*_t.PATCH_WHOLE_SHARE?Math.min(s,_t.MAX_DECOR_TERRAIN_M):0}static FAR_RING_RADIUS_M=_t.MAX_GROUND_VISIBILITY_M;static OVERLOOK_M=20;static needsFarRing(e,t,i){return e>=_t.FAR_RING_RADIUS_M?!1:t>=_t.OVERLOOK_M||i>e}static beamReachFor(e,t){let i=0;for(const s of e)for(const n of[...s.path,...(s.moves??[]).flatMap(r=>r.path)]){const r=ot(n.lat,n.lng,t.lat,t.lng);i=Math.max(i,Math.hypot(r.x,r.z))}return i}}const JD=ls.catalog({en:()=>Q(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(l=>l.beamKindMessages_en),fr:()=>Q(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(l=>l.beamKindMessages_fr),es:()=>Q(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(l=>l.beamKindMessages_es),it:()=>Q(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(l=>l.beamKindMessages_it)}),Ux={key:"beams",messages:JD,pickKind:"beam",simulation:()=>Q(async()=>{const{BeamSystem:l}=await import("./BeamSystem-Dd5G0PNW.js");return{BeamSystem:l}},__vite__mapDeps([4,5]),import.meta.url).then(({BeamSystem:l})=>()=>new l),editor:()=>Q(async()=>{const{BeamEditor:l}=await import("./BeamEditor-DQp2vKdn.js");return{BeamEditor:l}},__vite__mapDeps([6,5,1]),import.meta.url).then(({BeamEditor:l})=>(e,t,i)=>new l(e,t,i)),reachM:(l,e)=>_t.beamReachFor(l,e),describe:(l,e,{texts:t,name:i,distance:s})=>({name:i,detail:t.detail.replace("{name}",i).replace("{wavelength}",String(l.wavelengthNm)).replace("{power}",l.powerW.toLocaleString()).replace("{distance}",s(e.distanceM??0))})},QD=ls.catalog({en:()=>Q(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(l=>l.launchKindMessages_en),fr:()=>Q(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(l=>l.launchKindMessages_fr),es:()=>Q(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(l=>l.launchKindMessages_es),it:()=>Q(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(l=>l.launchKindMessages_it)}),Bx={key:"launches",messages:QD,pickKind:"plume",simulation:()=>Q(async()=>{const{LaunchSimulation:l}=await import("./LaunchSimulation-Bl72jnqq.js");return{LaunchSimulation:l}},__vite__mapDeps([7,8]),import.meta.url).then(({LaunchSimulation:l})=>()=>new l),editor:()=>Q(async()=>{const{LaunchEditor:l}=await import("./LaunchEditor-hAMtWhby.js");return{LaunchEditor:l}},__vite__mapDeps([9,1,8]),import.meta.url).then(({LaunchEditor:l})=>(e,t,i)=>new l(e,t,i)),describe:(l,e,{said:t,texts:i,distance:s})=>{const n=e.detail,r=t.read(l.title)||l.vehicle?.mission||i.name,a=n.release===void 0||n.release==="burn"?void 0:l.jets?.find((c,h)=>`jet:${c.id??h}`===n.release),o=n.release===void 0||n.release==="burn"?i.ascent:a?.kind==="vent"?i.vent:i.burn;return{name:r,detail:i.detail.replace("{name}",r).replace("{part}",o).replace("{distance}",s(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},ek=ls.catalog({en:()=>Q(()=>import("./ReentryKindMessages_en-Cbgk3paQ.js"),[],import.meta.url).then(l=>l.reentryKindMessages_en),fr:()=>Q(()=>import("./ReentryKindMessages_fr-D9r9x2bK.js"),[],import.meta.url).then(l=>l.reentryKindMessages_fr),es:()=>Q(()=>import("./ReentryKindMessages_es-DwgJQanC.js"),[],import.meta.url).then(l=>l.reentryKindMessages_es),it:()=>Q(()=>import("./ReentryKindMessages_it-DQ-J5YpD.js"),[],import.meta.url).then(l=>l.reentryKindMessages_it)}),zx={key:"reentries",messages:ek,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>Q(async()=>{const{ReentrySimulation:l}=await import("./ReentrySimulation-DS7Q5nso.js");return{ReentrySimulation:l}},[],import.meta.url).then(({ReentrySimulation:l})=>()=>new l),editor:()=>Q(async()=>{const{ReentryEditor:l}=await import("./ReentryEditor-Bt90y2I7.js");return{ReentryEditor:l}},__vite__mapDeps([10,1]),import.meta.url).then(({ReentryEditor:l})=>(e,t,i)=>new l(e,t,i)),describe:(l,e,{said:t,texts:i})=>{const s=e.detail,n=(l.title?t.read(l.title):"")||l.object?.name||i.name,r=s.view.head,a=6371,o=Math.sqrt(a**2+r.distanceKm**2+2*a*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-a;return{name:(s.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",n).replace("{mag}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(o).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},Qp=Ye.point("skyEvents").provide(Ye.BUILT_IN,[{id:Bx.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Bx},{id:Ux.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Ux},{id:zx.key,name:"Fireballs",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>zx}]);class Or{static built=new WeakMap;static of(e){let t=Or.built.get(e);return t||(t=e.create(),Or.built.set(e,t)),t}static eventsOf(e,t){const i=e?.[t.key];return Array.isArray(i)?i:[]}}const tk=ls.catalog({en:()=>Q(()=>import("./DecorParameterTexts_en-C5dEeI_C.js"),[],import.meta.url).then(l=>l.decorParameterTexts_en),fr:()=>Q(()=>import("./DecorParameterTexts_fr-CThgxosI.js"),[],import.meta.url).then(l=>l.decorParameterTexts_fr),es:()=>Q(()=>import("./DecorParameterTexts_es-BysMOaxT.js"),[],import.meta.url).then(l=>l.decorParameterTexts_es),it:()=>Q(()=>import("./DecorParameterTexts_it-D0ZsTK16.js"),[],import.meta.url).then(l=>l.decorParameterTexts_it)});class ca extends Error{constructor(e,t){super(t),this.reason=e,this.name="SurroundingsUnavailableError"}}class bi{static MAX_STOPS=12;static METRES_PER_DEGREE=111320;static SAME_TREE_M=1.5;static SAME_BUILDING_M=2.5;static SAME_STRUCTURE_M=5;static stops(e,t){if(e.length===0)return[];const i=e[0],s=Math.cos(i.lat*Math.PI/180),n=e.slice(1).map((f,m)=>Math.hypot((f.lat-e[m].lat)*bi.METRES_PER_DEGREE,(f.lng-e[m].lng)*bi.METRES_PER_DEGREE*s)),r=n.reduce((f,m)=>f+m,0),a=Math.max(t,r/(bi.MAX_STOPS-1)),o=[i];let c=0,h=a;e.slice(1).forEach((f,m)=>{c+=n[m],c>=h&&(o.push(f),h=c+a)});const d=e[e.length-1],u=o[o.length-1];return Math.hypot((d.lat-u.lat)*bi.METRES_PER_DEGREE,(d.lng-u.lng)*bi.METRES_PER_DEGREE*s)>t/2&&o.length<bi.MAX_STOPS&&o.push(d),o}static async fetch(e,t,i,s={}){if(t.length===0)throw new ca("no-coverage","No place to ask about");const n=t[0],r=Math.cos(n.lat*Math.PI/180),a=new Array(t.length).fill(void 0),o=[],c=Math.max(1,s.concurrency??3);let h=0;const d=async()=>{for(;h<t.length;){const m=h++;try{a[m]=await e.getSurroundings(t[m],i)}catch(v){o.push(v)}}};await Promise.all(Array.from({length:Math.min(c,t.length)},d));const u={trees:[],buildings:[],bridges:[],lines:[]};let p=!1;const f={};if(a.forEach((m,v)=>{if(!m)return;p=!0;const g=(t[v].lng-n.lng)*bi.METRES_PER_DEGREE*r,b=(t[v].lat-n.lat)*bi.METRES_PER_DEGREE,w=M=>M.map(x=>({...x,eastM:Math.round((x.eastM+g)*10)/10,northM:Math.round((x.northM+b)*10)/10})),y=w(m.trees).sort((M,x)=>Math.hypot(M.eastM-g,M.northM-b)-Math.hypot(x.eastM-g,x.northM-b)).slice(0,s.treesPerStop??m.trees.length);bi.add(u.trees,y,(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_TREE_M),bi.add(u.buildings,w(m.buildings),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_BUILDING_M&&Math.abs(M.widthM-x.widthM)<1.5&&Math.abs(M.lengthM-x.lengthM)<1.5),bi.add(u.bridges,w(m.bridges),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_STRUCTURE_M),bi.add(u.lines,w(m.lines),(M,x)=>Math.hypot(M.eastM-x.eastM,M.northM-x.northM)<bi.SAME_STRUCTURE_M&&Math.abs(M.lengthM-x.lengthM)<5),bi.addFurniture(u,m,w),m.incomplete&&(u.incomplete=!0);for(const M of["laser","photo","map","lamps"]){const x=m.dates?.[M];x&&(!f[M]||x>f[M])&&(f[M]=x)}}),!p)throw o.find(m=>!(m instanceof ca&&m.reason==="no-coverage"))??o[0];return Object.keys(f).length>0&&(u.dates=f),u}static later(e,t,i){if(!e.later||t.length===0)return;const s=t[0],n=Math.cos(s.lat*Math.PI/180),r=t.map(a=>e.later(a,i)??Promise.reject(new Error("Nothing comes late")));return Promise.allSettled(r).then(a=>{if(!a.some(c=>c.status==="fulfilled"))throw a[0].reason;const o={};return a.forEach((c,h)=>{if(c.status!=="fulfilled")return;const d=(t[h].lng-s.lng)*bi.METRES_PER_DEGREE*n,u=(t[h].lat-s.lat)*bi.METRES_PER_DEGREE,p=m=>m.map(v=>({...v,eastM:Math.round((v.eastM+d)*10)/10,northM:Math.round((v.northM+u)*10)/10}));bi.addFurniture(o,c.value,p);const f=c.value.dates?.lamps;f&&(!o.dates?.lamps||f>o.dates.lamps)&&(o.dates={lamps:f})}),o})}static addFurniture(e,t,i){t.lamps&&bi.add(e.lamps??=[],i(t.lamps),(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1);const s=(n,r)=>Math.hypot(n.eastM-r.eastM,n.northM-r.northM)<1&&Math.abs((n.headingDeg-r.headingDeg+540)%360-180)<10;t.signals&&bi.add(e.signals??=[],i(t.signals),s),t.crossings&&bi.add(e.crossings??=[],i(t.crossings),s),t.signs&&bi.add(e.signs??=[],i(t.signs),s),t.credits&&bi.add(e.credits??=[],t.credits,(n,r)=>n.url===r.url)}static add(e,t,i){for(const s of t)e.some(n=>i(n,s))||e.push(s)}}const Hx="#ff2200",Gx="#00ff44",hc="#ffffff",Of="#ffa500",mh="#ff0000",ik="#2244ff",xb=[{id:"airliner",name:"Airliner",kinds:["aircraft"],referenceSizeM:{widthM:34,heightM:12,lengthM:36},create:()=>[{id:"nav-port",offsetM:{x:-17,y:0,z:0},color:Hx,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Gx,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:hc,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:hc,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:hc,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01,phase:.08}}]},{id:"helicopter",name:"Helicopter",kinds:["aircraft"],referenceSizeM:{widthM:10,heightM:4,lengthM:14},create:()=>[{id:"nav-port",offsetM:{x:-5,y:0,z:0},color:Hx,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Gx,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:hc,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:mh,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:hc,intensity:15,pattern:{kind:"flash",perMinute:75,dutyCycle:.015}}]},{id:"car-headlights",name:"Car, headlights on",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"head-left",offsetM:{x:-.7,y:.6,z:2},color:hc,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:hc,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:mh,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:mh,pattern:{kind:"steady"}}]},{id:"car-hazards",name:"Car, hazard flashers",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"hazard-front-left",offsetM:{x:-.8,y:.6,z:2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:Of,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}}]},{id:"emergency-beacons",name:"Emergency vehicle beacons",kinds:["vehicle"],referenceSizeM:{widthM:1.8,heightM:1.5,lengthM:4.5},create:()=>[{id:"beacon-blue",offsetM:{x:-.4,y:1.6,z:0},color:ik,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:mh,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>gt.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>gt.pedestrianLights(0)},{id:"streetlamp",name:"Streetlamp",kinds:["streetlight"],referenceSizeM:{widthM:1,heightM:5,lengthM:1},create:()=>[{id:"lamp",offsetM:{x:0,y:5,z:0},color:"#ffd9a0",intensity:2,pattern:{kind:"steady"}}]}];class Zd{static forKind(e){return xb.filter(t=>t.kinds.includes(e))}static byId(e){return xb.find(t=>t.id===e)}}class gt{static CYCLE_S=90;static GREEN_S=41;static AMBER_S=3;static PEDESTRIAN_DELAY_S=2;static PEDESTRIAN_GREEN_S=30;static VEHICLE_INTENSITY=3;static PEDESTRIAN_INTENSITY=1.5;static LENS_RADIUS_M=.1;static BEAM_DEG=30;static VEHICLE_HEAD_Y_M=2.9;static PEDESTRIAN_HEAD_Y_M=2.6;static LENS_SPACING_M=.3;static LENS_FRONT_M=.13;static RED="#ff1e00";static AMBER="#ffa200";static GREEN="#00ff8c";static phaseOf(e){const t=(e%180+180)%180;return t>=45&&t<135?1:0}static vehicleLights(e){const t=e*gt.CYCLE_S/2,i=gt.VEHICLE_HEAD_Y_M,s=gt.LENS_SPACING_M;return[gt.lamp("red",gt.RED,i+s,t+gt.GREEN_S+gt.AMBER_S,gt.CYCLE_S-gt.GREEN_S-gt.AMBER_S,gt.VEHICLE_INTENSITY),gt.lamp("amber",gt.AMBER,i,t+gt.GREEN_S,gt.AMBER_S,gt.VEHICLE_INTENSITY),gt.lamp("green",gt.GREEN,i-s,t,gt.GREEN_S,gt.VEHICLE_INTENSITY)]}static pedestrianLights(e){const t=e*gt.CYCLE_S/2+gt.GREEN_S+gt.AMBER_S+gt.PEDESTRIAN_DELAY_S,i=gt.PEDESTRIAN_HEAD_Y_M,s=gt.LENS_SPACING_M/2;return[gt.lamp("ped-red",gt.RED,i+s,t+gt.PEDESTRIAN_GREEN_S,gt.CYCLE_S-gt.PEDESTRIAN_GREEN_S,gt.PEDESTRIAN_INTENSITY),gt.lamp("ped-green",gt.GREEN,i-s,t,gt.PEDESTRIAN_GREEN_S,gt.PEDESTRIAN_INTENSITY)]}static isPedestrian(e){return e?.some(t=>t.id==="ped-green")??!1}static figureOf(e){return e.id==="ped-red"?"standing":e.id==="ped-green"?"walking":void 0}static lamp(e,t,i,s,n,r){const a=gt.CYCLE_S,o=Math.round(((1-s/a)%1+1)%1*1e6)/1e6;return{id:e,color:t,intensity:r,radiusM:gt.LENS_RADIUS_M,beamDeg:gt.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/a,dutyCycle:Math.round(n/a*1e6)/1e6,...o?{phase:o}:{}}}}}class Dd{static FLOOR_HEIGHT_M=3;static CROSSING_LENGTH_M=2.5;static of(e,t,i){const{kept:s}=i,n=g=>s.some(b=>b.kind===g),r={tree:n("tree"),building:n("building"),bridge:n("bridge"),wire:n("wire"),streetlight:n("streetlight"),trafficlight:n("trafficlight"),crossing:n("crossing"),roadsign:n("roadsign")},a=[...s,...i.others??[]],o=new Set(a.map(g=>g.id));let c=0;const h=()=>{let g;do g=`${e}-${++c}`;while(o.has(g));return o.add(g),g},d={tree:a.filter(g=>g.kind==="tree").length,building:a.filter(g=>g.kind==="building").length,bridge:a.filter(g=>g.kind==="bridge").length,wire:a.filter(g=>g.kind==="wire").length,streetlight:a.filter(g=>g.kind==="streetlight").length,trafficlight:a.filter(g=>g.kind==="trafficlight").length,crossing:a.filter(g=>g.kind==="crossing").length,roadsign:a.filter(g=>g.kind==="roadsign").length},u=new Set(a.map(g=>typeof g.title=="string"?g.title:"")),p=(g,b)=>{const w=b??`${i.kindName(g)} ${++d[g]}`;let y=w;for(let M=2;u.has(y);M++)y=`${w} (${M})`;return u.add(y),y},f=t.dates??{},m=(...g)=>{const b=g.filter(w=>w!==void 0).sort().at(-1);return b?{surveyedOn:b}:{}},v=[];if(!r.tree)for(const g of t.trees)v.push({id:h(),kind:"tree",title:p("tree",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.widthM,heightM:g.heightM},origin:e,...m(f.laser)});if(!r.building)for(const g of t.buildings)v.push({id:h(),kind:"building",title:p("building",g.name),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{widthM:g.widthM,lengthM:g.lengthM,heightM:g.heightM},...g.style==="church"||g.style==="monument"?{}:{floors:g.floors??Math.max(1,Math.round((g.heightM-(g.roof?.riseM??0))/(g.facade?.storeyM??Dd.FLOOR_HEIGHT_M)))},...g.roof?{roof:g.roof}:{},...g.facade?{facade:g.facade}:{},origin:e,...m(f.map,f.laser,g.roof?.color?f.photo:void 0)});if(!r.bridge)for(const g of t.bridges)v.push({id:h(),kind:"bridge",title:p("bridge",g.name?`${i.kindName("bridge")} (${g.name})`:void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,widthM:g.widthM,heightM:g.heightM},origin:e,...m(f.map,f.laser)});if(!r.wire)for(const g of t.lines)v.push({id:h(),kind:"wire",title:p("wire",`${i.kindName("wire")} (${g.voltage})`),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lit:!1,sizeM:{lengthM:g.lengthM,heightM:g.heightM},wire:{strands:g.acrossM.map(b=>({heightM:g.heightM,acrossM:b})),poles:"both",poleHeightM:g.poleHeightM},origin:e,...m(f.map,f.laser)});if(!r.streetlight)for(const g of t.lamps??[]){const b={...g.colorTemperatureK?{colorTemperatureK:g.colorTemperatureK}:{},...g.lumens?{lumens:g.lumens}:{},...g.mount==="wall"?{mount:"wall"}:{},...g.supposed?{supposed:!0}:{}};v.push({id:h(),kind:"streetlight",title:p("streetlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:0,...g.heightM?{sizeM:{heightM:g.heightM}}:{},...Object.keys(b).length>0?{lamp:b}:{},origin:e,...m(f.lamps)})}if(!r.trafficlight)for(const g of t.signals??[])v.push({id:h(),kind:"trafficlight",title:p("trafficlight",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,lights:g.for==="pedestrians"?gt.pedestrianLights(g.phase):gt.vehicleLights(g.phase),origin:e,...m(f.lamps)});if(!r.crossing)for(const g of t.crossings??[])v.push({id:h(),kind:"crossing",title:p("crossing",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sizeM:{widthM:g.widthM,lengthM:Dd.CROSSING_LENGTH_M},origin:e,...m(f.lamps)});if(!r.roadsign)for(const g of t.signs??[])v.push({id:h(),kind:"roadsign",title:p("roadsign",void 0),eastM:g.eastM,northM:g.northM,headingDeg:g.headingDeg,sign:{face:g.face,...g.code?{code:g.code}:{},...g.value?{value:g.value}:{}},origin:e,...m(f.lamps)});return{planted:v,handPlaced:Object.values(r).some(Boolean)}}}class dn{constructor(e,t,i,s,n={}){this.status=e,this.host=t,this.loadProvider=s,this.messages=i,this.debounceMs=n.debounceMs??dn.DEFAULT_DEBOUNCE_MS,this.radiusM=n.radiusM??dn.DEFAULT_RADIUS_M}static SAME_PLACE_M=25;static METRES_PER_DEGREE=111320;static DEFAULT_RADIUS_M=100;static DEFAULT_DEBOUNCE_MS=800;static TREES_PER_STOP=80;static WALK_LEAD_S=4;static WALK_LEAD_SHARE=.6;static SAME_BUILDING_M=3;static SAME_OBJECT_M=1.5;messages;debounceMs;radiusM;enabled=!0;surveyedFor;timer;token=0;surveyed="";furnitureSaid="";furnitureCredits=[];asked=[];lastStep;walkSpeedMps=0;setMessages(e){this.messages=e}setEnabled(e){e!==this.enabled&&(this.enabled=e,e||this.cancel())}withdraw(){this.cancel(),this.withdrawPlanted(),this.say("")}placeLoaded(e,t){this.cancel(),this.surveyedFor=e!==void 0&&t!==void 0?{lat:e,lng:t}:void 0,this.say("")}radiusChanged(e,t,i){e!==this.radiusM&&(this.radiusM=e,!(!this.enabled||t===void 0||i===void 0)&&(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(t,i),this.debounceMs)))}placeChanged(e,t){!this.enabled||e===void 0||t===void 0||this.surveyedFor&&this.isSamePlace(this.surveyedFor,e,t)||(clearTimeout(this.timer),this.timer=setTimeout(()=>void this.survey(e,t),this.debounceMs))}walked(e,t,i,s=Date.now()){if(clearTimeout(this.timer),this.timer=void 0,this.surveyedFor={lat:e,lng:t},this.lastStep){const o=(s-this.lastStep.atMs)/1e3,c=this.metresBetween(this.lastStep,e,t);this.walkSpeedMps=o>0&&o<2?.5*this.walkSpeedMps+.5*c/o:0}if(this.lastStep={lat:e,lng:t,atMs:s},!this.enabled)return;const n=Math.min(this.radiusM,Math.max(this.radiusM*dn.WALK_LEAD_SHARE,this.walkSpeedMps*dn.WALK_LEAD_S)),r=i*Math.PI/180,a={lat:e+Math.cos(r)*n/dn.METRES_PER_DEGREE,lng:t+Math.sin(r)*n/(dn.METRES_PER_DEGREE*Math.cos(e*Math.PI/180))};this.asked.some(o=>this.metresBetween(o,a.lat,a.lng)<this.radiusM/2)||(this.asked.push(a),this.plantAhead(a))}async plantAhead(e){const t=this.token;try{const i=await this.loadProvider(e.lat,e.lng);if(!i||t!==this.token)return;const s=await i.getSurroundings(e,this.radiusM);if(t!==this.token)return;this.addAhead(i,this.fromCentre(s,e)),(s.incomplete?i.later?.(e,this.radiusM):void 0)?.then(r=>{t===this.token&&this.addAhead(i,this.fromCentre({trees:[],buildings:[],bridges:[],lines:[],...r},e))},()=>{})}catch{this.asked=this.asked.filter(i=>i!==e)}}addAhead(e,t){const i=this.host.decor(),s=i.filter(o=>o.origin===void 0),n=i.filter(o=>o.origin!==void 0),{planted:r}=Dd.of(e.id,t,{kept:s,others:n,kindName:o=>this.host.kindName(o)}),a=r.filter(o=>!n.some(c=>dn.same(c,o)));a.length>0&&this.host.setDecor([...i,...a])}static same(e,t){if(e.kind!==t.kind)return!1;const i=Math.hypot(e.eastM-t.eastM,e.northM-t.northM);if(e.kind!=="building")return i<dn.SAME_OBJECT_M;const s=n=>[n.sizeM?.widthM??0,n.sizeM?.lengthM??0];return i<dn.SAME_BUILDING_M&&s(e).every((n,r)=>Math.abs(n-s(t)[r])<1.5)}fromCentre(e,t){const i=this.host.centre?.();if(!i)return e;const s=(t.lng-i.lng)*dn.METRES_PER_DEGREE*Math.cos(i.lat*Math.PI/180),n=(t.lat-i.lat)*dn.METRES_PER_DEGREE;if(Math.hypot(s,n)<.01)return e;const r=a=>a?.map(o=>({...o,eastM:Math.round((o.eastM+s)*100)/100,northM:Math.round((o.northM+n)*100)/100}));return{...e,...e.trees?{trees:r(e.trees)}:{},...e.buildings?{buildings:r(e.buildings)}:{},...e.bridges?{bridges:r(e.bridges)}:{},...e.lines?{lines:r(e.lines)}:{},...e.lamps?{lamps:r(e.lamps)}:{},...e.signals?{signals:r(e.signals)}:{},...e.crossings?{crossings:r(e.crossings)}:{},...e.signs?{signs:r(e.signs)}:{}}}metresBetween(e,t,i){const s=(e.lat-t)*dn.METRES_PER_DEGREE,n=(e.lng-i)*dn.METRES_PER_DEGREE*Math.cos(t*Math.PI/180);return Math.hypot(s,n)}async survey(e,t){const i=++this.token;this.surveyedFor={lat:e,lng:t},this.asked=[{lat:e,lng:t}],this.lastStep=void 0,this.host.busy(!0,this.messages.surveyBusy);try{const s=await this.loadProvider(e,t);if(i!==this.token)return;if(s===void 0){this.withdrawPlanted(),this.say("");return}this.say(this.messages.surveyBusy);const n=bi.stops([{lat:e,lng:t},...this.host.track?.()??[]],this.radiusM),r=n.length>1?await bi.fetch(s,n,this.radiusM,{treesPerStop:dn.TREES_PER_STOP}):await s.getSurroundings({lat:e,lng:t},this.radiusM);if(i!==this.token)return;this.plant(s,this.fromCentre(r,{lat:e,lng:t})),r.incomplete&&this.awaitLate(s,n,i)}catch(s){if(i!==this.token)return;s instanceof ca&&s.reason==="no-coverage"?(this.withdrawPlanted(),this.say("")):this.say(this.messages.surveyUnreachable)}finally{i===this.token&&this.host.busy(!1,"")}}cancel(){clearTimeout(this.timer),this.timer=void 0,this.token++,this.host.busy(!1,"")}withoutPlanted(){return this.host.decor().filter(e=>e.origin===void 0)}withdrawPlanted(){this.host.decor().some(e=>e.origin!==void 0)&&this.host.setDecor(this.withoutPlanted())}plant(e,t){const i=this.withoutPlanted(),{planted:s,handPlaced:n}=Dd.of(e.id,t,{kept:i,kindName:c=>this.host.kindName(c)}),r=c=>s.filter(h=>h.kind===c).length;if((s.length>0||this.host.decor().length!==i.length)&&this.host.setDecor([...i,...s]),s.length===0){this.furnitureSaid="",this.surveyed=n?this.messages.surveyKept:this.messages.surveyNone.replace("{radius}",String(this.radiusM)),this.say(this.surveyed,t.incomplete?this.messages.surveyFurniturePending:"");return}this.host.cite({title:`${e.name}, survey of the surroundings`,url:e.creditUrl,publication:{publisher:e.name}});const a=this.messages.surveyDone.replace("{trees}",String(r("tree"))).replace("{buildings}",String(r("building"))).replace("{bridges}",String(r("bridge"))).replace("{lines}",String(r("wire"))).replace("{source}",e.name),o=this.datesText(t.dates);this.surveyed=[a,o,n?this.messages.surveyKept:""].filter(c=>c!=="").join(" "),this.citeCredits(t),this.furnitureCredits=t.credits??[],this.furnitureSaid=this.furnitureText(s,t),this.say(this.surveyed,[this.furnitureSaid,t.incomplete?this.messages.surveyFurniturePending:""].filter(c=>c!=="").join(" "))}citeCredits(e){for(const t of e.credits??[])this.host.cite({title:t.licence?`${t.name} (${t.licence})`:t.name,url:t.url,publication:{publisher:t.name}})}awaitLate(e,t,i){const s=t.length>1?bi.later(e,t,this.radiusM):e.later?.(t[0],this.radiusM);if(!s){this.say(this.surveyed,"");return}this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurniturePending].filter(n=>n!=="").join(" ")),s.then(n=>{i===this.token&&this.plantLate(e,this.fromCentre(n,t[0]))},()=>{i===this.token&&this.say(this.surveyed,[this.furnitureSaid,this.messages.surveyFurnitureUnavailable].filter(n=>n!=="").join(" "),{label:this.messages.surveyFurnitureRetry,run:()=>this.awaitLate(e,t,i)})})}plantLate(e,t){const i=this.host.decor(),{planted:s}=Dd.of(e.id,{trees:[],buildings:[],bridges:[],lines:[],...t},{kept:i,kindName:r=>this.host.kindName(r)});s.length>0&&this.host.setDecor([...i,...s]),this.citeCredits(t);const n=i.filter(r=>r.origin===e.id).concat(s);this.furnitureSaid=this.furnitureText(n,{credits:[...this.furnitureCredits,...t.credits??[]]}),this.say(this.surveyed,this.furnitureSaid)}furnitureText(e,t){const i=a=>e.filter(o=>o.kind===a).length;if(!e.some(a=>a.kind==="streetlight"||a.kind==="trafficlight"||a.kind==="crossing"||a.kind==="roadsign"))return"";const s=a=>a.of==="lamps"?i("streetlight")>0:a.of==="signals"?i("trafficlight")>0:!0,r=[...new Set((t.credits??[]).filter(s).map(a=>a.name))].join(" + ")||"OpenStreetMap";return this.messages.surveyFurnitureDone.replace("{source}",r).replace("{lamps}",String(i("streetlight"))).replace("{signals}",String(i("trafficlight"))).replace("{crossings}",String(i("crossing"))).replace("{signs}",String(i("roadsign")))}datesText(e){if(!e)return"";const t=[["laser",this.messages.surveyLaserLabel],["photo",this.messages.surveyPhotoLabel],["map",this.messages.surveyMapLabel],["lamps",this.messages.surveyLampsLabel]].filter(([i])=>e[i]!==void 0).map(([i,s])=>`${s} ${e[i]}`);return t.length>0?this.messages.surveyDated.replace("{dates}",t.join(", ")):""}isSamePlace(e,t,i){return this.metresBetween(e,t,i)<dn.SAME_PLACE_M}say(e,t="",i){if(this.status.textContent=[e,t].filter(n=>n!=="").join(" "),!i)return;const s=this.status.ownerDocument.createElement("button");s.type="button",s.className="scenery-retry",s.textContent=i.label,s.addEventListener("click",i.run),this.status.append(" ",s)}}class Ht{static INFO="message-info";static WARNING="message-warning";static ERROR="message-error";static CSS=Ht.rules();static rules(e=[],t=[],i=[]){const s=(n,r)=>[`.${n}`,...r].join(", ");return`
|
|
655
655
|
/* A component's messages: information muted, warnings orange, errors red, all three at one smaller size (see MessageStyle). */
|
|
656
656
|
:is(${s(Ht.INFO,e)}, ${s(Ht.WARNING,t)}, ${s(Ht.ERROR,i)}) { font-size: var(--rr0-message-font-size, 0.78em); line-height: var(--rr0-message-line-height, 1.3); font-weight: normal; opacity: 1; }
|
|
657
657
|
:is(${s(Ht.INFO,e)}) { color: color-mix(in srgb, CanvasText 62%, transparent); }
|
|
@@ -4399,9 +4399,9 @@ canvas[data-cursor="rotate"] {
|
|
|
4399
4399
|
`;class Vc{constructor(e){this.points=e}static STATIONARY_M=5;static of(e){const t=[];for(const i of e.observerTrack.allKeyframes){const{lat:s,lng:n,headingDeg:r}=i.pose;s===void 0||n===void 0||t.push({t:i.t,lat:s,lng:n,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 Vc(t)}static TRAVEL_M=50;get travels(){return this.spanM>Vc.TRAVEL_M}get moved(){return this.spanM>Vc.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(ot(t,e.east,t,e.west).x),Math.abs(ot(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:s}=this.center,n=Math.max(this.spanM*(1+t),e)/2;return{north:tr(0,-n,i,s).lat,south:tr(0,n,i,s).lat,east:tr(n,0,i,s).lng,west:tr(-n,0,i,s).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 Vr{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){if(e.instrument.mounted)return;const t=e.event.tags?.includes("paralysis")||(e.exposure??0)>Vr.HAND_HELD_S,i=e.sway??(t?0:1);if(i>0)return new Vr(Math.max(1-(e.instrument.stabilization??0),Vr.GAZE_DRIFT_SHARE),i)}offsetAt(e){const t=e/1e3,i=this.scale,s=(d,u)=>Math.sin(2*Math.PI*d*t+u),[n,r,a,o,c,h]=Vr.HZ;return{eastM:i*Vr.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*Vr.SWAY_M*(.6*s(a,2.2)+.4*s(c,.8)),upM:i*Vr.BREATH_M*s(r,0),yawDeg:i*this.rotationPassed*Vr.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*Vr.DRIFT_PITCH_DEG*(.5*s(r,1.6)+.5*s(a,.4)),rollDeg:i*this.rotationPassed*Vr.DRIFT_ROLL_DEG*s(n,2.9)}}}class wi{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=Vc.of(e);if(!t||t.points.length<2)return;const i=[];let s=0;for(let n=1;n<t.points.length;n++){const r=t.points[n-1],a=t.points[n],o=(a.t-r.t)/1e3;if(o<=0)continue;const c=ot(a.lat,a.lng,r.lat,r.lng),h=c.x,d=-c.z,u=Math.hypot(h,d),p=u/o,f=wi.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:s,rampsIn:!0,rampsOut:!0}),s+=f*o}for(let n=0;n<i.length;n++){const r=i[n-1],a=i[n+1];i[n].rampsIn=r===void 0||r.stepHz===0,i[n].rampsOut=a===void 0||a.stepHz===0}if(i.some(n=>n.stepHz>0))return new wi(i,1-(e.instrument.stabilization??0))}static bodyAt(e,t,i=!1){const s=wi.of(e)?.offsetAt(t)??wi.STILL;return i?s:wi.add(s,Vr.of(e)?.offsetAt(t))}static stepHzFor(e){return e<wi.SLOWEST_WALK_M_PER_S||e>wi.FASTEST_WALK_M_PER_S?0:wi.REFERENCE_STEP_HZ*Math.pow(e/wi.REFERENCE_SPEED_M_PER_S,wi.CADENCE_EXPONENT)}offsetAt(e){return wi.add(this.cycleAt(e),this.joltAt(e))}joltAt(e){for(const t of this.stretches){if(t.stepHz===0)continue;const i=t.speedMPerS/wi.REFERENCE_SPEED_M_PER_S,s=(a,o,c,h)=>{if(a<0||a>wi.JOLT_LASTS_MS)return;const d=a/1e3,u=Math.exp(-d/wi.JOLT_DECAY_S)*Math.sin(2*Math.PI*wi.JOLT_HZ*d),p=h*o*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}},n=t.rampsOut?s(e-t.endMs,wi.STOP_LURCH_M,wi.STOP_PITCH_DEG,1):void 0;if(n)return n;const r=t.rampsIn?s(e-t.startMs,wi.START_LURCH_M,wi.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(o=>e>=o.startMs&&e<=o.endMs);if(!t||t.stepHz===0)return wi.STILL;const i=t.stepsBefore+t.stepHz*(e-t.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(t,e),r=wi.SWAY_M*n*Math.cos(s/2),a=n*this.rotationPassed*t.speedMPerS/wi.REFERENCE_SPEED_M_PER_S;return{eastM:r*t.northUnit,northM:-r*t.eastUnit,upM:wi.RISE_M_PER_M_PER_S*t.speedMPerS*n*Math.cos(s),rollDeg:wi.HEAD_ROLL_DEG*a*Math.cos(s/2),pitchDeg:-1.25*a*Math.cos(s),yawDeg:wi.HEAD_YAW_DEG*a*Math.cos(s/2)}}amplitudeAt(e,t){const i=1e3/e.stepHz,s=Math.min(i,(e.endMs-e.startMs)/2);if(s<=0)return 1;const n=t-e.startMs,r=e.endMs-t,a=Math.min(e.rampsIn?n/s:1,e.rampsOut?r/s:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class xk{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 s=this.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}this.onFrame(e,t)}}class Wc{static sessionDeclared=!1;static unlock(e){if(Wc.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(!(Wc.sessionDeclared||typeof navigator>"u")){Wc.sessionDeclared=!0;try{const e=navigator.audioSession;e&&(e.type="playback")}catch{}}}}const Jx=.05,Qx=.08,eS=2,tS=3,Sk=14,Ek=.02;class Ak{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}}Wc.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 s=i.currentTime;e.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,t.volume))*e.gainScale,s,Jx);for(const{param:n,ratio:r}of e.pitch)n.setTargetAtTime(Math.min(t.pitchHz*r,i.sampleRate/2-1),s,Jx)}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 s=e.createOscillator();s.type="sawtooth";const n=e.createBiquadFilter();n.type="lowpass",n.Q.value=1;const r=e.createGain();return r.gain.value=0,i.connect(n),s.connect(n),n.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(e,t){const i=e.createOscillator();i.type="sine";const s=e.createOscillator();s.type="sine",s.frequency.value=5;const n=e.createGain(),r=e.createGain();return r.gain.value=0,s.connect(n).connect(i.frequency),i.connect(r).connect(this.output(e)),i.start(),s.start(),{key:t,nodes:[n,r],sources:[i,s],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(e,t){const i=e.createBufferSource();i.buffer=this.brownNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const n=e.createGain();return n.gain.value=0,i.connect(s).connect(n).connect(this.output(e)),i.start(),{key:t,nodes:[s,n],sources:[i],volumeParam:n.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(e,t){const i=e.createBufferSource();i.buffer=this.whiteNoise(e),i.loop=!0;const s=e.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const n=e.createGain();n.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(n.gain),i.connect(s).connect(n).connect(this.output(e)),i.start(),r.start(),{key:t,nodes:[s,n,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(e,t,i){const s=this.context;if(!s)return;let n;try{n=await this.getBuffer(e)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);return}if(i!==this.voiceToken||!this.context)return;const r=s.createBufferSource();r.buffer=n,r.loop=!0;const a=s.createGain();a.gain.value=0,r.connect(a).connect(this.output(s)),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(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${e}`);return s.arrayBuffer()}).then(s=>t.decodeAudioData(s)),this.buffers.set(e,i)),i}whiteNoise(e){if(!this.noiseBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*eS),e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;this.noiseBuffer=t}return this.noiseBuffer}brownNoise(e){const t=e.createBuffer(1,Math.floor(e.sampleRate*eS),e.sampleRate),i=t.getChannelData(0);let s=0,n=0;for(let r=0;r<i.length;r++)s=(s+.02*(Math.random()*2-1))/1.02,i[r]=s,n=Math.max(n,Math.abs(s));if(n>0)for(let r=0;r<i.length;r++)i[r]/=n;return t}crackleEnvelope(e){if(!this.crackleBuffer){const t=e.createBuffer(1,Math.floor(e.sampleRate*tS),e.sampleRate),i=t.getChannelData(0),s=Math.max(1,Math.floor(Ek*e.sampleRate)),n=Math.round(tS*Sk);for(let r=0;r<n;r++){const a=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let c=0;c<s&&a+c<i.length;c++)i[a+c]=Math.max(i[a+c],o*(1-c/s))}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,Qx/3);const s=i+Qx;for(const n of e.sources){n.onended=()=>{n.disconnect();for(const r of e.nodes)r.disconnect()};try{n.stop(s)}catch{n.disconnect();for(const r of e.nodes)r.disconnect()}}}}class za{static KINDS=["beams","launches","reentries"];static statedKinds(e){return Object.keys(e??{}).filter(t=>Array.isArray(e[t])&&e[t].length>0)}static isEmpty(e){return za.statedKinds(e).length===0}static written(e){const t=za.statedKinds(e);if(t.length===0)return;const i={};for(const s of t)i[s]=e[s];return i}static read(e,t){const i=t,s={};for(const r of za.statedKinds(e))s[r]=e[r];for(const r of za.KINDS){const a=[...e?.[r]??[],...i?.[r]??[]];a.length>0&&(s[r]=a)}let n=t;if(i&&za.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:o,...c}=i;n=za.isReading(c)?c:void 0}return{skyEvents:za.written(s),interpretation:n}}static isReading(e){return(e.bodies?.length??0)>0||e.title!==void 0||(e.smoke?.length??0)>0}}function $c(l){return[...l].sort((e,t)=>e.t-t.t)}function fv(l,e){let t;for(const i of $c(l)){if(i.t>e)break;t=i}return t}class _n{static restatedDecor(e){const t=_n.originOf(e);return e.decor.map(i=>{let s=i;if(i.saidPosition){const n=_n.restated(i.saidPosition,i,_n.frameAt(e,0,t,i.id));JSON.stringify(n)!==JSON.stringify(i.saidPosition)&&(s={...i,saidPosition:n},n||delete s.saidPosition)}if(i.track?.some(n=>n.saidPosition)){const n=i.track.map(r=>{if(!r.saidPosition)return r;const a=_n.restated(r.saidPosition,r,_n.frameAt(e,r.t,t,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const o={...r,saidPosition:a};return a||delete o.saidPosition,o});s={...s,track:n}}return s})}static restatedObserverTrack(e){const t=e.observerTrack.toJSON(),i=_n.originOf(e);return!i||!t.keyframes.some(s=>s.pose.saidPosition)?t:{...t,keyframes:t.keyframes.map(s=>{const{pose:n}=s;if(!n.saidPosition||n.lat===void 0||n.lng===void 0)return s;const r=ni.toLocal({lat:n.lat,lng:n.lng},i),a=_n.restated(n.saidPosition,r,_n.frameAt(e,s.t,i));if(JSON.stringify(a)===JSON.stringify(n.saidPosition))return s;const o={...n,saidPosition:a};return a||delete o.saidPosition,{...s,pose:o}})}}static restatedInterpretation(e){const t=e.interpretation;if(!t?.bodies.some(s=>s.track.some(n=>n.saidPosition)))return t;const i=_n.originOf(e);return{...t,bodies:t.bodies.map(s=>s.track.some(n=>n.saidPosition)?{...s,track:s.track.map(n=>{if(!n.saidPosition)return n;const r=n.eastM!==void 0&&n.northM!==void 0?_n.restated(n.saidPosition,{eastM:n.eastM,northM:n.northM},_n.frameAt(e,n.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(n.saidPosition))return n;const a={...n,saidPosition:r};return r||delete a.saidPosition,a})}:s)}}static originOf(e){const t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}:void 0}static frameAt(e,t,i,s){const n=[{label:"",eastM:0,northM:0},...e.decor.filter(r=>r.id!==s).map(r=>{const{eastM:a,northM:o}=Pr(r,t);return{id:r.id,label:r.id,eastM:a,northM:o}})];return{origin:i,references:n}}static restated(e,t,i){return ni.restated(e,{eastM:t.eastM,northM:t.northM},i)}}function P0(l){return Yn.restore(Tb(l),l.provenance)}function Tb(l,e=!1){return Ti.toAngular(l),Ti.toAim(l),{version:4,id:l.id,time:N0.write(l.event.time),endTime:N0.write(l.event.endTime),durationSeconds:l.event.durationSeconds,durationText:l.event.durationText,utcOffsetHours:l.event.utcOffsetHours,timeZone:l.event.timeZone,place:RT.write(l.event.place),observer:l.observer,account:l.account,sources:l.sources?.length?l.sources:void 0,sway:l.sway,vehicle:l.vehicle,description:l.event.description,image:l.event.image,summary:l.event.summary,summaryTime:l.event.summaryTime,tags:l.event.tags,timeline:!e&&ht.timelineIsExpanded(l)?ht.timelineWithoutShapes(l):l.timeline.toJSON(),observerTrack:!e&&ht.observerTrackIsExpanded(l)?void 0:_n.restatedObserverTrack(l),events:l.events?.length?l.events:void 0,weatherTrack:l.weatherTrack.toJSON(),soundTrack:l.soundTrack.toJSON(),weather:l.weather,decor:_n.restatedDecor(l).map(t=>{if(!e&&t.lights&&(t={...t,lights:ht.writtenLights(l,t.id,t.lights)}),e||!ht.decorTrackIsExpanded(l,t.id,t.track))return t;const{track:i,...s}=t;return s}),milestones:l.milestones.length>0?l.milestones:void 0,references:l.references.length>0?l.references:void 0,roads:l.roads.length>0?l.roads:void 0,traces:l.traces.length>0?l.traces:void 0,weatherSource:l.weatherSource,instrument:l.instrumentId,exposureSeconds:l.exposureSeconds,iso:l.iso,film:l.film,metering:l.metering,sampleMs:l.sampleMs,lens:l.lens,lightPollution:l.lightPollution,observerMap:l.observerMap,interpretation:e?_n.restatedInterpretation(l):ht.writtenInterpretation(l,_n.restatedInterpretation(l)),variants:l.variants.length>0?l.variants:void 0,skyEvents:za.written(l.skyEvents),snapshots:l.snapshots,modules:l.modules?.length?l.modules:void 0}}function Mw(l){Ol.check(l,"sighting");const e=Oi.toCurrent(l),{recording:t,provenance:i}=Yn.strip(e),s=Tk(t);return s.provenance=i,s}function Tk(l){const e=[],t=new _g({eventType:"sighting",time:N0.read(l.time),endTime:N0.read(l.endTime),durationSeconds:l.durationSeconds,durationText:l.durationText,utcOffsetHours:l.utcOffsetHours,timeZone:l.timeZone,place:RT.read(l.place),description:l.description,image:l.image,summary:l.summary,summaryTime:l.summaryTime,tags:l.tags},vf.fromJSON(l.timeline,e,!1),l.observerTrack?Ep.fromJSON(l.observerTrack):new Ep,l.weatherTrack?Ap.fromJSON(l.weatherTrack):new Ap,l.soundTrack?Tp.fromJSON(l.soundTrack):new Tp,l.observer&&{id:l.observer.id,title:l.observer.title,lastName:l.observer.lastName,firstNames:l.observer.firstNames},l.id,l.weather,(l.decor??[]).map(s=>{if(!s.facade?.plain)return s;const{plain:n,...r}=s.facade;return{...s,facade:{...r,openings:"plain"}}}),l.weatherSource,l.instrument,l.exposureSeconds??l.observerTrack?.keyframes.map(s=>s.pose.exposureSeconds).find(s=>s!==void 0),$c(l.milestones??[]),l.references??[],l.roads??[],l.traces??[]);t.account=l.account,t.sources=l.sources,t.sway=l.sway,t.iso=l.iso,t.film=l.film,t.metering=l.metering,t.sampleMs=l.sampleMs,t.lens=l.lens,t.lightPollution=l.lightPollution,t.observerMap=l.observerMap,t.vehicle=l.vehicle,t.events=l.events?.map(s=>s.who===void 0?{...s,who:Oi.observerIdOf(l)}:s);const i=za.read(l.skyEvents,l.interpretation);return t.interpretation=i.interpretation,t.variants=Array.isArray(l.variants)?l.variants:[],t.skyEvents=i.skyEvents,t.snapshots=l.snapshots,t.modules=Array.isArray(l.modules)?l.modules.filter(s=>typeof s=="string"):void 0,t.loadIssues=e,ht.expand(t),t.timeline.pruneGroups(),Ti.toBounds(t),Ti.toPosition(t),ht.settle(t),t}class N0{static read(e){return e===void 0||e.trim()===""?void 0:Qu(e)}static write(e){if(e===void 0)return;const t=Hl(e);return t===""?void 0:t}}class RT{static read(e){if(e?.locations?.length)return e.locations.map(({lat:t,lng:i})=>({lat:t,lng:i,...e.name===void 0?{}:{name:e.name}}))}static write(e){if(!e?.length)return;const t=e.find(i=>i.name)?.name;return{...t===void 0?{}:{name:t},locations:e.map(({lat:i,lng:s})=>({lat:i,lng:s}))}}}class tf{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=tf.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(s=>` ${tf.text(s)}`);console.warn(`UFO@home: ${e.length} problem(s) in ${t??"this recording"}:
|
|
4400
4400
|
${i.join(`
|
|
4401
4401
|
`)}`)}}class oa{constructor(e){this.format=e}issues(e){const t=[];return this.object(e,this.format,"",t),t}object(e,t,i,s){if(!oa.isObject(e)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:oa.typeOf(e)});return}for(const[n,r]of Object.entries(e)){const a=i?`${i}.${n}`:n,o=t[n];o?this.field(r,o,a,s):s.push({kind:"unknown-key",path:a})}}field(e,t,i,s){if(oa.isStated(e)){this.field(e.value,t,i,s);return}if(!(t.loose||e===void 0||e===null))switch(t.type){case"enum":(typeof e!="string"||!t.values?.includes(e))&&s.push({kind:"not-in-list",path:i,expected:(t.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(e)});return;case"object":t.fields?this.object(e,t.fields,i,s):oa.isObject(e)||s.push({kind:"wrong-type",path:i,expected:"object",found:oa.typeOf(e)});return;case"array":Array.isArray(e)?t.fields&&e.forEach((n,r)=>{const a=oa.isStated(n)?n.value:n;this.object(a,t.fields,`${i}.${r}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:oa.typeOf(e)});return;default:typeof e!==t.type&&s.push({kind:"wrong-type",path:i,expected:t.type,found:oa.typeOf(e)})}}static isObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}static isStated(e){return oa.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 pa{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,s=Math.max(0,e-i*1e3),n=Math.max(0,e-s);return{fromMs:s,toMs:e,ms:n,seconds:n/1e3}}static instants(e,t,i,s,n){if(!(s>0))return 1;const r=n>0?pa.travelDegOver(e,t,i,i+s*1e3)/n/pa.PIXELS_PER_INSTANT:0,a=pa.flashesOver(e,s)*pa.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(r,a));return o<2?1:Math.min(pa.MAX_INSTANTS,o)}static travelDegOver(e,t,i,s){let n=0;for(const r of e){if(!r.track||r.track.length<2)continue;const a=pa.directionAt(r,t,i),o=pa.directionAt(r,t,s),c=Math.min(1,Math.max(-1,a.x*o.x+a.y*o.y+a.z*o.z));n=Math.max(n,Math.acos(c)*180/Math.PI)}return n}static flashesOver(e,t){let i=0;for(const s of e)for(const n of s.lights??[])n.pattern.kind==="flash"&&(i=Math.max(i,n.pattern.perMinute));return i/60*t}static directionAt(e,t,i){const s=Pr(e,i),n=s.eastM,r=s.altitudeM-t,a=s.northM,o=Math.hypot(n,r,a);return o===0?{x:0,y:1,z:0}:{x:n/o,y:r/o,z:a/o}}}const CT=Math.PI/180,Ik=180/Math.PI,_k=256,LT=19,Dk=1.25;function OT(l,e){return 156543.03392*Math.cos(l*CT)/2**e}function PT(l,e){return OT(l,e)*_k}function kk(l,e){let t=0;for(;t<LT&&PT(l,t+1)>=e;)t++;return t}function NT(l,e){return PT(l,e)}function Rk(l,e){const t=e*Dk;let i=0;for(;i<LT&&OT(l,i)>t;)i++;return i}function n0(l){const e=l*CT;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}function FT(l,e,t){const i=2**t;return{x:(l+180)/360*i,y:n0(e)*i}}function UT(l,e,t){const i=n0(l.north),s=n0(l.south);return{x:(e-l.west)/(l.east-l.west),y:(n0(t)-i)/(s-i)}}function Ck(l,e,t){const{x:i,y:s}=FT(l,e,t);return{x:Math.floor(i),y:Math.floor(s),z:t}}function Lk(l){const e=2**l.z,t=l.x/e*360-180,i=(l.x+1)/e*360-180,s=iS(l.y,e);return{south:iS(l.y+1,e),north:s,west:t,east:i}}function iS(l,e){const t=l/e;return Math.atan(Math.sinh(Math.PI*(1-2*t)))*Ik}function BT(l,e,t,i){const s=Ck(l,e,t),n=Math.floor(i/2),r=[];for(let c=-n;c<=n;c++)for(let h=-n;h<=n;h++)r.push({x:s.x+h,y:s.y+c,z:t});const a=r.map(Lk),o={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:o}}const Ok="#2ec4ff";class Tc{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,s=1/0;for(const n of this.targets){const r=Math.hypot(n.x-e,n.y-t);r>n.radius||r>s||(i=n,s=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 s=UT(e,i,t);return{x:s.x*this.width,y:s.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 s=this.toCanvas(e.bounds,i.bounds.north,i.bounds.west),n=this.toCanvas(e.bounds,i.bounds.south,i.bounds.east);t.drawImage(i.source,s.x,s.y,n.x-s.x,n.y-s.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 s=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:s.x,y:s.y,radius:7}),t.beginPath(),t.rect(s.x-3.5,s.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 n=(i.headingDeg-90)*Math.PI/180;t.beginPath(),t.moveTo(s.x,s.y),t.lineTo(s.x+Math.cos(n)*10,s.y+Math.sin(n)*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(s=>this.toCanvas(e.bounds,s.lat,s.lng));t.beginPath(),t.moveTo(i[0].x,i[0].y);for(const s of i.slice(1))t.lineTo(s.x,s.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 s=i.points.map(r=>this.toCanvas(e.bounds,r.lat,r.lng));if(s.length===0)continue;const n=i.color??Ok;if(i.kind==="point")t.beginPath(),t.moveTo(s[0].x,s[0].y-6),t.lineTo(s[0].x+6,s[0].y),t.lineTo(s[0].x,s[0].y+6),t.lineTo(s[0].x-6,s[0].y),t.closePath(),t.fillStyle=n,t.fill(),t.lineWidth=1.5,t.strokeStyle="rgba(0, 0, 0, 0.8)",t.stroke();else{t.beginPath(),t.moveTo(s[0].x,s[0].y);for(const r of s.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=n,t.lineWidth=2.5,t.stroke(),t.setLineDash([])}if(i.label){t.font="11px sans-serif",t.textAlign="left",t.textBaseline="middle";let r=s[0];if(i.kind==="line"&&e.position){const a=this.toCanvas(e.bounds,e.position.lat,e.position.lng);r=s.reduce((o,c)=>Math.hypot(c.x-a.x,c.y-a.y)>Math.hypot(o.x-a.x,o.y-a.y)?c:o)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(e,t){const{headingDeg:i,coneHalfAngleDeg:s}=e;if(i===void 0||s===void 0)return;const{ctx:n}=this,r=this.toCanvas(e.bounds,t.lat,t.lng),a=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,c=s*Math.PI/180;n.save(),n.beginPath(),n.moveTo(r.x,r.y),n.arc(r.x,r.y,a,o-c,o+c),n.closePath();const h=n.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)"),n.fillStyle=h,n.fill(),n.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((s,n)=>Number(s.current)-Number(n.current))){const s=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:s.x,y:s.y,radius:Tc.MARKER_RADIUS_PX}),t.beginPath(),t.arc(s.x,s.y,Tc.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,s.x,s.y)}}paintObserver(e,t){const{ctx:i}=this,s=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:s.x,y:s.y,radius:8});const n=e.markers.some(r=>{if(!r.current)return!1;const a=ot(r.lat,r.lng,t.lat,t.lng);return Math.hypot(a.x,a.z)<=Tc.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?Tc.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),n||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=n?3:2.5,i.strokeStyle=n?"#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 s=t?this.wrap(t,this.width-20):[];let n=this.height-4;i.textAlign="right";for(const p of s.slice().reverse())this.paintOutlinedText(p,this.width-6,n),n-=11;const r=(e.south+e.north)/2,o=Math.abs(ot(r,e.east,r,e.west).x)/this.width,c=Tc.SCALE_STEPS_M.find(p=>p/o<=this.width/3);if(c===void 0)return;const h=c/o,d=8,u=n-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:s}=this;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.75)",s.strokeText(e,t,i),s.fillStyle="#fff",s.fillText(e,t,i)}wrap(e,t){const i=[];let s="";for(const n of e.split(" ")){const r=s?`${s} ${n}`:n;s&&this.ctx.measureText(r).width>t?(i.push(s),s=n):s=r}return s&&i.push(s),i}}class ui{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(e,t){return ui.including(e.boundsAround(ui.MIN_SPAN_M,ui.MARGIN),t)}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 s=Math.min(ui.MAX_ZOOM,Math.max(ui.MIN_ZOOM,this.zoom*i)),n=this.centerX+(e-.5)/this.zoom,r=this.centerY+(t-.5)/this.zoom;this.centerX=n-(e-.5)/s,this.centerY=r-(t-.5)/s,this.zoom=s}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),s=ui.mercatorY01(t.north),n=ui.mercatorY01(t.south),r=ui.mercatorY01(i.north),a=ui.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-s)/(n-s)}keepInView(e,t,i){if(!this.changed)return!1;const s=this.boundsWithin(e),n=ui.mercatorY01(s.north),r=ui.mercatorY01(s.south),a=(t.lng-s.west)/(s.east-s.west),o=(ui.mercatorY01(t.lat)-n)/(r-n);return a>=i&&a<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-a,.5-o),!0)}boundsWithin(e){if(!this.changed)return e;const t=.5/this.zoom,i=ui.mercatorY01(e.north),s=ui.mercatorY01(e.south),n=e.east-e.west;return{west:e.west+(this.centerX-t)*n,east:e.west+(this.centerX+t)*n,north:ui.latitudeAt(i+(this.centerY-t)*(s-i)),south:ui.latitudeAt(i+(this.centerY+t)*(s-i))}}static including(e,t,i=3){const s=(e.north+e.south)/2,n=(e.east+e.west)/2,r=ot(s,e.east,s,n).x;let a=r;for(const o of t){const{x:c,z:h}=ot(o.lat,o.lng,s,n),d=Math.max(Math.abs(c),Math.abs(h));d<=r*i&&(a=Math.max(a,d*1.15))}return a<=r?e:{north:tr(0,-a,s,n).lat,south:tr(0,a,s,n).lat,east:tr(a,0,s,n).lng,west:tr(-a,0,s,n).lng}}static expand(e,t){const i=e.east-e.west,s=e.north-e.south;return{west:e.west-i*t,east:e.east+i*t,south:e.south-s*t,north:e.north+s*t}}static pointAt(e,t,i){const s=ui.mercatorY01(e.north),n=ui.mercatorY01(e.south);return{lat:ui.latitudeAt(s+i*(n-s)),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 zr=256,sS=3,Pk=32768;class zT{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,s=(e.west+e.east)/2,n=Math.abs(ot(i,e.east,i,e.west).x),r=Math.abs(ot(e.north,s,e.south,s).z),a=kk(i,Math.max(n,r)),{tiles:o}=BT(s,i,a,sS),c=sS*zr,h=new Float32Array(c*c),d=o[0];await Promise.all(o.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 m=0;m<t.width;m++){const v=e.west+(e.east-e.west)*(m/(t.width-1));u[p*t.width+m]=this.sampleAt(f,v,a,d,h,c)}}return{heights:u,width:t.width,height:t.height,bounds:e}}async decodeTileInto(e,t,i,s){const n=this.tileUrlTemplate.replace("{z}",String(e.z)).replace("{x}",String(e.x)).replace("{y}",String(e.y)),r=await this.fetchImpl(n);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${n}`);const a=await createImageBitmap(await r.blob()),o=document.createElement("canvas");o.width=zr,o.height=zr;const c=o.getContext("2d");if(!c)throw new Error("2D canvas context unavailable");c.drawImage(a,0,0);const{data:h}=c.getImageData(0,0,zr,zr),d=(e.x-t.x)*zr,u=(e.y-t.y)*zr;for(let p=0;p<zr;p++)for(let f=0;f<zr;f++){const m=(p*zr+f)*4,v=h[m]*256+h[m+1]+h[m+2]/256-Pk,g=d+f,b=u+p;i[b*s+g]=v}}sampleAt(e,t,i,s,n,r){const{x:a,y:o}=FT(t,e,i),c=(a-s.x)*zr,h=(o-s.y)*zr,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),m=c-d,v=h-u,g=n[u*r+d],b=n[u*r+p],w=n[f*r+d],y=n[f*r+p],M=g+(b-g)*m,x=w+(y-w)*m;return M+(x-M)*v}}class Fg{constructor(e,t,i,s){this.width=e,this.height=t,this.samples=i,this.values=s}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),s=t.getUint16(i,!0),n=new Map;for(let g=0;g<s;g++){const b=i+2+g*12;n.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=(g,b)=>{const w=n.get(g);if(w===void 0){if(b===void 0)throw new Error(`TIFF without tag ${g}`);return b}return w.type===3?w.value&65535:w.value},a=g=>{const b=n.get(g);if(b===void 0)throw new Error(`TIFF without tag ${g}`);const w=b.type===3?2:4,y=[];if(b.count*w<=4){const M=new DataView(new ArrayBuffer(4));M.setUint32(0,b.value,!0);for(let x=0;x<b.count;x++)y.push(w===2?M.getUint16(x*2,!0):M.getUint32(0,!0))}else for(let M=0;M<b.count;M++)y.push(w===2?t.getUint16(b.value+M*2,!0):t.getUint32(b.value+M*4,!0));return y};if(r(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const o=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),m=new Uint8Array(o*c*h*(d/8));let v=0;for(let g=0;g<p.length&&v<m.length;g++){const b=Math.min(f[g],m.length-v);m.set(new Uint8Array(e,p[g],b),v),v+=b}if(v<m.length)throw new Error("Truncated TIFF");return new Fg(o,c,h,u?new Float32Array(m.buffer):m)}}class Nk{constructor(e,t,i,s,n){this.heights=e,this.plants=t,this.buildings=i,this.size=s,this.metresPerPixel=n}structureAt(e,t){const i=Math.floor(e/this.metresPerPixel+this.size/2),s=Math.floor(this.size/2-t/this.metresPerPixel);if(i<0||s<0||i>=this.size||s>=this.size)return;const n=s*this.size+i;if(!(this.plants[n]||this.buildings[n]))return this.heights[n]}tallestStructureNear(e,t,i){let s;const n=Math.ceil(i/this.metresPerPixel);for(let r=-n;r<=n;r++)for(let a=-n;a<=n;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const o=this.structureAt(e+a*this.metresPerPixel,t+r*this.metresPerPixel);o!==void 0&&(s===void 0||o>s)&&(s=o)}return s}}class Re{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 JOIN_M=1;static JOIN_DEG=25;static RAIL_MATCH_M=6;static ROAD_MATCH_M=12;static DECK_SEEN_M=1.5;static DECK_STEP_M=.5;static DECK_GAP_M=2;static DECK_REACH_M=20;static DECK_MEETS_M=.3;static DECK_BEARING_M=4;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,s]=e;return{east:(i-t.lng)*Re.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180),north:(s-t.lat)*Re.METRES_PER_DEGREE}}static path(e,t){return e.geometry.type!=="LineString"?[]:e.geometry.coordinates.map(i=>Re.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 s=i.east-t.east,n=i.north-t.north,r=s*s+n*n,a=r===0?0:Math.max(0,Math.min(1,((e.east-t.east)*s+(e.north-t.north)*n)/r));return Math.hypot(e.east-(t.east+a*s),e.north-(t.north+a*n))}static bridges(e,t,i,s){const n=e.elevatedRoads.map(o=>({path:Re.path(o,t),properties:o.properties})),r=(e.elevatedRailways??[]).map(o=>Re.path(o,t)),a=[];for(const o of Re.joined(e.bridges.map(c=>Re.path(c,t)))){const c=o[0],h=o[o.length-1],d=Math.hypot(h.east-c.east,h.north-c.north);if(d<Re.MIN_BRIDGE_M)continue;const u={east:(c.east+h.east)/2,north:(c.north+h.north)/2};if(Math.hypot(u.east,u.north)>i+d/2||Re.carriesRailway(c,h,r))continue;const[p,f]=Re.deckReach(c,h,s);a.push({eastM:Re.tenth((p.east+f.east)/2),northM:Re.tenth((p.north+f.north)/2),lengthM:Re.tenth(Math.hypot(f.east-p.east,f.north-p.north)),widthM:Re.roadOf(u,n).width,heightM:Re.tenth(Re.deckHeight(c,h,s)),headingDeg:Re.tenth(Re.bearing(c,h)%180),...Re.roadOf(u,n).name?{name:Re.roadOf(u,n).name}:{}})}return a.sort((o,c)=>Math.hypot(o.eastM,o.northM)-Math.hypot(c.eastM,c.northM)),a}static carriesRailway(e,t,i){const s={east:(e.east+t.east)/2,north:(e.north+t.north)/2},n=Re.bearing(e,t)%180;for(const r of i)for(let a=0;a+1<r.length;a++){if(Re.distanceToSegment(s,r[a],r[a+1])>Re.RAIL_MATCH_M)continue;const o=Math.abs(Re.bearing(r[a],r[a+1])%180-n);if(Math.min(o,180-o)<=Re.JOIN_DEG)return!0}return!1}static joined(e){const t=e.filter(i=>i.length>=2);for(let i=0;i<t.length;i++)for(let s=i+1;s<t.length;s++){const n=Re.join(t[i],t[s]);n!==void 0&&(t[i]=n,t.splice(s,1),s=i)}return t}static join(e,t){for(const i of[e,[...e].reverse()])for(const s of[t,[...t].reverse()]){const n=i[i.length-1],r=s[0];if(Math.hypot(n.east-r.east,n.north-r.north)>Re.JOIN_M)continue;const a=Math.abs(Re.bearing(i[0],n)-Re.bearing(r,s[s.length-1]));if(Math.min(a,360-a)<=Re.JOIN_DEG)return[...i,...s.slice(1)]}}static roadOf(e,t){let i;for(const a of t)for(let o=0;o+1<a.path.length;o++){const c=Re.distanceToSegment(e,a.path[o],a.path[o+1]);(i===void 0||c<i.distance)&&(i={distance:c,properties:a.properties})}if(i===void 0||i.distance>Re.ROAD_MATCH_M)return{width:Re.DEFAULT_DECK_M};const s=[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),n=Number(i.properties.largeur_de_chaussee),r=Number.isFinite(n)&&n>0?Re.tenth(n+Re.DECK_MARGIN_M):i.properties.nature==="Sentier"?Re.FOOTBRIDGE_DECK_M:Re.DEFAULT_DECK_M;return s?{width:r,name:s}:{width:r}}static deckReach(e,t,i){const s=Math.hypot(t.east-e.east,t.north-e.north);if(i===void 0||s===0)return[e,t];const n={east:(e.east+t.east)/2,north:(e.north+t.north)/2},r={east:(t.east-e.east)/s,north:(t.north-e.north)/s},a=u=>(i.structureAt(n.east+r.east*u,n.north+r.north*u)??0)>=Re.DECK_SEEN_M,o=u=>i.structureAt(n.east+r.east*u,n.north+r.north*u)??0,c=u=>{let p;for(let m=0;m<=s/2+Re.DECK_REACH_M;m+=Re.DECK_STEP_M)if(a(u*m))p=m;else if(p!==void 0&&m-p>Re.DECK_GAP_M)break;if(p===void 0)return s/2;let f=p;for(;f-p<Re.DECK_REACH_M&&o(u*(f+Re.DECK_STEP_M))>=Re.DECK_MEETS_M;)f+=Re.DECK_STEP_M;return Math.max(s/2,f+Re.DECK_BEARING_M)},h=c(-1),d=c(1);return[{east:n.east-r.east*h,north:n.north-r.north*h},{east:n.east+r.east*d,north:n.north+r.north*d}]}static deckHeight(e,t,i){if(i===void 0)return Re.DEFAULT_DECK_HEIGHT_M;const s=[],n=20;for(let r=4;r<=n-4;r++){const a=i.structureAt(e.east+(t.east-e.east)*r/n,e.north+(t.north-e.north)*r/n);a!==void 0&&a>=1.5&&s.push(a)}return s.length===0?Re.DEFAULT_DECK_HEIGHT_M:(s.sort((r,a)=>r-a),s[Math.floor(s.length/2)])}static lines(e,t,i,s){const n=[];for(const r of e.lines){const a=String(r.properties.voltage??""),o=Re.kilovolts(a);if(o===void 0)continue;const c=Re.BY_VOLTAGE.find(d=>o<=d.upToKv)??Re.BY_VOLTAGE[Re.BY_VOLTAGE.length-1],h=Re.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>Re.MAX_SPAN_M||Re.distanceToSegment({east:0,north:0},u,p)>i)continue;const m=Re.poleHeight(u,p,s)??c.poleM;n.push({eastM:Re.tenth((u.east+p.east)/2),northM:Re.tenth((u.north+p.north)/2),lengthM:Re.tenth(f),headingDeg:Re.tenth(Re.bearing(u,p)),heightM:Re.tenth(Math.max(4,m-c.dropM)),poleHeightM:Re.tenth(m),acrossM:[-c.spreadM,0,c.spreadM],voltage:a})}}return n.sort((r,a)=>Math.hypot(r.eastM,r.northM)-Math.hypot(a.eastM,a.northM)),n.slice(0,Re.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 s=[e,t].map(n=>i.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=Re.MIN_POLE_M&&n<=Re.MAX_POLE_M);return s.length===0?void 0:s.reduce((n,r)=>n+r,0)/s.length}static tenth(e){return Math.round(e*10)/10}}class Wt{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??Wt.WMS,this.wfs=e.wfsEndpoint??Wt.WFS}static radius(e){return Math.min(e,Wt.MAX_RADIUS_M)}static lidarRadius(e){return Math.min(e,Wt.MAX_LIDAR_RADIUS_M)}async lidar(e,t){const i=Wt.lidarRadius(t),s=Math.ceil(2*i/Wt.METRES_PER_PIXEL),[n,r]=await Promise.all([this.raster(e,i,s,Wt.HEIGHT_LAYER),this.raster(e,i,s,Wt.CLASS_LAYER)]);if(n.samples!==1||r.samples<3)throw new ca("unreachable","The survey answered in a layout this does not read");const a=n.values;if(a.every(d=>d===Wt.NO_DATA))throw new ca("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(s*s),c=new Uint8Array(s*s);for(let d=0;d<s*s;d++){const u=r.values[d*r.samples],p=r.values[d*r.samples+1],f=r.values[d*r.samples+2];o[d]=p>u&&p>f?1:0,c[d]=u>120&&p<90&&f<90?1:0}const h=2*i/s;return{size:s,metresPerPixel:h,heights:a,vegetation:o,building:c,structures:new Nk(a,o,c,s,h)}}async laserDate(e){return Wt.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",e))}async photoDate(e){return Wt.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,s){const r=[s.lng-1e-4,s.lat-1e-4,s.lng+1e-4,s.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=Wt.radius(t),s=Math.min(Wt.MAX_PHOTO_PIXELS,Math.ceil(2*i/Wt.METRES_PER_PIXEL)),n=await this.raster(e,i,s,Wt.PHOTO_LAYER);if(n.samples<3)throw new ca("unreachable","The photograph came in a layout this does not read");return{size:s,metresPerPixel:2*i/s,samples:n.samples,values:n.values}}async vectors(e,t,i){const s=Wt.radius(t),n=s/Wt.METRES_PER_DEGREE,r=s/(Wt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),o=`BBOX(geometrie,${[e.lng-r,e.lat-n,e.lng+r,e.lat+n].map(g=>g.toFixed(6)).join(",")},'EPSG:4326')`,[c,h,d,u,p,f]=await Promise.all([this.features("construction_lineaire",`${o} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${o} AND position_par_rapport_au_sol>'0'`,"nature,largeur_de_chaussee,position_par_rapport_au_sol,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie"),this.features("troncon_de_voie_ferree",`${o} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",o,"voltage,geometrie"),i?this.features("batiment",o,Wt.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(f,p,[e.lng-r,e.lat-n,e.lng+r,e.lat+n]):[],v=[...p,...m];return{bridges:c,elevatedRoads:h,elevatedRailways:d,lines:u,buildings:v,zones:f,mapDate:Wt.latest(v.map(g=>g.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(e,t,i){const[s,n,r,a]=i,o=Wt.MAX_WHOLE_M/Wt.METRES_PER_DEGREE;let c;for(const d of e){if(d.properties.categorie!=="Religieux")continue;const[u,p,f,m]=Wt.extent(d);if(u>=s&&p>=n&&f<=r&&m<=a)continue;const v=[Math.max(u,s-o),Math.max(p,n-o),Math.min(f,r+o),Math.min(m,a+o)];c=c?[Math.min(c[0],v[0]),Math.min(c[1],v[1]),Math.max(c[2],v[2]),Math.max(c[3],v[3])]:v}if(!c)return[];const h=new Set(t.map(d=>d.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${c.map(u=>u.toFixed(6)).join(",")},'EPSG:4326')`,Wt.BUILDING_PROPERTIES,1e3)).filter(u=>!h.has(u.properties.cleabs))}catch{return[]}}static extent(e){let t=1/0,i=1/0,s=-1/0,n=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(t=Math.min(t,a[0]),s=Math.max(s,a[0]),i=Math.min(i,a[1]),n=Math.max(n,a[1])):Array.isArray(a)&&a.forEach(r)};return r(e.geometry.coordinates),[t,i,s,n]}async elevatedRoadLines(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${t} AND position_par_rapport_au_sol>'0'`,"geometrie",300),s=[];for(const n of i){const{type:r,coordinates:a}=n.geometry,o=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const c of o)s.push(c.map(h=>({lat:h[1],lng:h[0]})))}return s}async waterSurfaces(e){const t=`BBOX(geometrie,${[e.west,e.south,e.east,e.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${t} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}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 railways(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_voie_ferree",`${t} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(e,t,i,s){const n=t/Wt.METRES_PER_DEGREE,r=t/(Wt.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[e.lat-n,e.lng-r,e.lat+n,e.lng+r].map(c=>c.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${a}`)}catch(c){throw new ca("unreachable",c instanceof Error?c.message:String(c))}if(!o.ok)throw new ca("unreachable",`The survey answered ${o.status}`);try{return Fg.parse(await o.arrayBuffer())}catch(c){throw new ca("unreachable",c instanceof Error?c.message:String(c))}}async features(e,t,i,s=200){const n=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(s),CQL_FILTER:t,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${n}`)}catch(o){throw new ca("unreachable",o instanceof Error?o.message:String(o))}if(!r.ok)throw new ca("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class Sl{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],s=t.map(a=>ot(a.lat,a.lng,i.lat,i.lng)),n=e.map(a=>ot(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<n.length-1;a++){const o=n[a],c=n[a+1],h=Math.hypot(c.x-o.x,c.z-o.z);if(h<1e-6)continue;const d=Math.max(1,Math.ceil(h/Sl.SAMPLE_M)),u=Math.atan2(c.x-o.x,-(c.z-o.z));for(let p=0;p<=d;p++){const f=p/d,m=Sl.nearest(s,o.x+(c.x-o.x)*f,o.z+(c.z-o.z)*f);m.distanceM>Sl.NEAR_M||Sl.angleBetween(u,m.heading)<=Sl.ALIGNED_DEG&&(r+=h/d)}}return r>=Sl.LONG_ENOUGH_M}static nearest(e,t,i){let s={distanceM:1/0,heading:0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,c=a.z-r.z,h=o*o+c*c,d=h<1e-9?0:Math.max(0,Math.min(1,((t-r.x)*o+(i-r.z)*c)/h)),u=Math.hypot(t-(r.x+o*d),i-(r.z+c*d));u<s.distanceM&&(s={distanceM:u,heading:Math.atan2(o,-c)})}return s}static angleBetween(e,t){const i=Math.abs((e-t)*180/Math.PI%180);return Math.min(i,180-i)}}class Bt{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.wms=e.wmsEndpoint??Bt.WMS,this.timeoutMs=e.timeoutMs??Bt.DEFAULT_TIMEOUT_MS,this.maxWindowM=e.maxWindowM??Bt.MAX_WINDOW_M,this.geoplatform=new Wt({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:e.wfsEndpoint})}async getElevationGrid(e,t,i){const s={lat:(e.south+e.north)/2,lng:(e.west+e.east)/2};if(!Wt.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(ot(s.lat,e.east,s.lat,e.west).x),r=Math.abs(ot(e.north,s.lng,e.south,s.lng).z);t=this.finer(t,n,r);const a={x:n/Math.max(1,t.width-1),y:r/Math.max(1,t.height-1)},o={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},c={south:e.south-o.y/Bt.METRES_PER_DEGREE,north:e.north+o.y/Bt.METRES_PER_DEGREE,west:e.west-o.x/(Bt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:e.east+o.x/(Bt.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=m=>Math.min(Bt.MAX_PIXELS,Math.max(Bt.MIN_PIXELS,Math.ceil(m/Bt.METRES_PER_PIXEL))),d={width:h(n+2*o.x),height:h(r+2*o.y)},u={x:(n+2*o.x)/d.width,y:(r+2*o.y)/d.height};let p=new Error("No layer of the IGN's relief answered");const f=Math.max(u.x,u.y)>Bt.COARSE_METRES_PER_PIXEL;for(const m of f?[...Bt.LAYERS].reverse():Bt.LAYERS)try{const v=await this.heights(c,d,m);m===Bt.LAYERS[0]&&await this.layBridgeDecks(v,c,d,i?.route);const g=this.sample(v,t,e,c,u,a);if(g)return{heights:g,width:t.width,height:t.height,bounds:e};p=new Error(`${m} does not cover this place`)}catch(v){p=v}throw p}finer(e,t,i){if(e.width<Bt.MESH_FROM_VERTICES||e.height<Bt.MESH_FROM_VERTICES)return e;const s=(n,r)=>{const a=Math.ceil(n/Bt.FINE_SPACING_M),o=Math.max(r-1,Math.min(Bt.MAX_SEGMENTS,a));return o%2===0?o:o+1};return{width:s(t,e.width)+1,height:s(i,e.height)+1}}async raster(e,t,i){const s=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"}),n=await this.fetchImpl(`${this.wms}?${s}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok)throw new Error(`The IGN's relief answered ${n.status}`);return Fg.parse(await n.arrayBuffer())}async heights(e,t,i){const s=await this.raster(e,t,i);if(s.samples!==1||!(s.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return s}async layBridgeDecks(e,t,i,s){if(!(!s||s.length<2)&&!(!(e.values instanceof Float32Array)||!e.values.some(n=>n>Bt.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:t.west,south:t.south,east:t.east,north:t.north})).filter(a=>Sl.follows(s,a));if(n.length===0)return;const r=Float32Array.from(e.values);await this.layClassifiedDecks(e,t,i,n),this.layRouteDecks(e,r,t,n)}catch{}}async layClassifiedDecks(e,t,i,s){try{const n=await this.raster(t,i,Bt.CLASS_LAYER);if(n.samples<3||n.width!==e.width||n.height!==e.height)return;const r=(v,[g,b,w])=>n.values[v*n.samples]===g&&n.values[v*n.samples+1]===b&&n.values[v*n.samples+2]===w,a=e.width,o=e.height,c=new Uint8Array(a*o);let h=!1;for(let v=0;v<c.length;v++)r(v,Bt.DECK)&&(c[v]=1,h=!0);if(!h)return;const d=Bt.DECK_END_PIXELS,u=[];for(let v=0;v<c.length;v++){if(c[v]!==1)continue;const g=v%a,b=(v-g)/a;for(let w=-d;w<=d;w++)for(let y=-d;y<=d;y++){const M=g+y,x=b+w;if(M<0||x<0||M>=a||x>=o)continue;const E=x*a+M;c[E]===0&&r(E,Bt.NO_CLASS)&&u.push(E)}}for(const v of u)c[v]=1;const p=this.paint(s,t,a,o),f=this.touching(c,p,a,o);if(f.every(v=>v===0))return;const m=await this.heights(t,i,Bt.SURFACE_LAYER);if(m.width!==a||m.height!==o)return;for(let v=0;v<f.length;v++){if(f[v]===0)continue;const g=m.values[v];Number.isFinite(g)&&g>Bt.NO_DATA_BELOW&&g>e.values[v]&&(e.values[v]=g)}}catch{}}layRouteDecks(e,t,i,s){const{width:n,height:r}=e,a=(i.north+i.south)/2,o=(i.east-i.west)*Bt.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),c=(i.north-i.south)*Bt.METRES_PER_DEGREE,h=o/n,d=c/r,u=g=>({x:(g.lng-i.west)/(i.east-i.west)*o,y:(i.north-g.lat)/(i.north-i.south)*c}),p=(g,b)=>{const w=Math.floor(g/h),y=Math.floor(b/d);if(w<0||y<0||w>=n||y>=r)return;const M=t[y*n+w];return Number.isFinite(M)&&M>Bt.NO_DATA_BELOW?M:void 0},f=Bt.DECK_HALF_WIDTH_M,m=Bt.DECK_APPROACH_M,v=(g,b)=>{const w=Math.hypot(g.x-b.x,g.y-b.y)||1,y={x:(g.x-b.x)/w,y:(g.y-b.y)/w},M=[0,m/2,m].map(x=>p(g.x+y.x*x,g.y+y.y*x)).filter(x=>x!==void 0);return M.length>0?Math.max(...M):void 0};for(const g of Bt.chains(s.map(b=>b.map(u)))){const b=[0];for(let _=1;_<g.length;_++)b.push(b[_-1]+Math.hypot(g[_].x-g[_-1].x,g[_].y-g[_-1].y));const w=b[b.length-1];if(w<1||w>Bt.DECK_STRAIGHT_MAX_M)continue;const y=v(g[0],g[1]),M=v(g[g.length-1],g[g.length-2]);if(y===void 0||M===void 0)continue;const x=f+m,E=Math.max(0,Math.floor((Math.min(...g.map(_=>_.x))-x)/h)),S=Math.min(n-1,Math.ceil((Math.max(...g.map(_=>_.x))+x)/h)),A=Math.max(0,Math.floor((Math.min(...g.map(_=>_.y))-x)/d)),T=Math.min(r-1,Math.ceil((Math.max(...g.map(_=>_.y))+x)/d));for(let _=A;_<=T;_++)for(let k=E;k<=S;k++){const L=Bt.nearestAlong(g,b,{x:(k+.5)*h,y:(_+.5)*d});if(L.distance>f||L.s<-m||L.s>w+m)continue;const P=y+(M-y)*Math.min(1,Math.max(0,L.s/w)),C=_*n+k;t[C]>=P||(e.values[C]=P)}}}static chains(e){const t=e.filter(n=>n.length>=2).map(n=>[...n]),i=[],s=(n,r)=>Math.hypot(n.x-r.x,n.y-r.y)<=1;for(;t.length>0;){let n=t.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<t.length;a++){const o=t[a],c=n[0],h=n[n.length-1];if(s(h,o[0]))n=[...n,...o.slice(1)];else if(s(h,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else if(s(c,o[o.length-1]))n=[...o.slice(0,-1),...n];else if(s(c,o[0]))n=[...[...o].reverse().slice(0,-1),...n];else continue;t.splice(a,1),r=!0;break}}i.push(n)}return i}static nearestAlong(e,t,i){let s={s:0,distance:1/0};for(let n=0;n<e.length-1;n++){const r=e[n],a=e[n+1],o=a.x-r.x,c=a.y-r.y,h=o*o+c*c;if(h<1e-9)continue;let d=((i.x-r.x)*o+(i.y-r.y)*c)/h;n>0&&(d=Math.max(0,d)),n<e.length-2&&(d=Math.min(1,d));const u=Math.hypot(i.x-(r.x+o*d),i.y-(r.y+c*d));u<s.distance&&(s={s:t[n]+d*Math.sqrt(h),distance:u})}return s}paint(e,t,i,s){const n=new Uint8Array(i*s),r=o=>(o-t.west)/(t.east-t.west)*i,a=o=>(t.north-o)/(t.north-t.south)*s;for(const o of e)for(let c=0;c<o.length-1;c++){const h=r(o[c].lng),d=a(o[c].lat),u=r(o[c+1].lng),p=a(o[c+1].lat),f=Math.max(1,Math.ceil(Math.hypot(u-h,p-d)*2));for(let m=0;m<=f;m++){const v=Math.floor(h+(u-h)*m/f),g=Math.floor(d+(p-d)*m/f);for(let b=-1;b<=1;b++)for(let w=-1;w<=1;w++){const y=v+w,M=g+b;y>=0&&M>=0&&y<i&&M<s&&(n[M*i+y]=1)}}}return n}touching(e,t,i,s){const n=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 o=[],c=[a];r[a]=1;let h=!1;for(;c.length>0;){const d=c.pop();o.push(d),t[d]===1&&(h=!0);const u=d%i,p=(d-u)/i;for(let f=-1;f<=1;f++)for(let m=-1;m<=1;m++){const v=u+m,g=p+f;if(v<0||g<0||v>=i||g>=s)continue;const b=g*i+v;e[b]===1&&r[b]===0&&(r[b]=1,c.push(b))}}if(h)for(const d of o)n[d]=1}return n}sample(e,t,i,s,n,r){const{width:a,height:o}=t,c=new Float32Array(a*o),h=new Uint8Array(a*o),d=Math.min(r.x,this.maxWindowM)/n.x,u=Math.min(r.y,this.maxWindowM)/n.y;let p=0;for(let f=0;f<o;f++){const m=i.north+(i.south-i.north)*(o===1?.5:f/(o-1)),v=(s.north-m)/(s.north-s.south)*e.height-.5;for(let g=0;g<a;g++){const w=(i.west+(i.east-i.west)*(a===1?.5:g/(a-1))-s.west)/(s.east-s.west)*e.width-.5,y=d>1||u>1?this.tent(e,w,v,Math.max(1,d),Math.max(1,u)):this.bilinear(e,w,v),M=f*a+g;y===void 0?p++:(c[M]=y,h[M]=1)}}if(!(p===a*o||p/(a*o)>Bt.MAX_HOLE_SHARE))return this.fill(c,h,a,o),c}tent(e,t,i,s,n){let r=0,a=0,o=0;const c=Math.max(0,Math.ceil(i-n)),h=Math.min(e.height-1,Math.floor(i+n)),d=Math.max(0,Math.ceil(t-s)),u=Math.min(e.width-1,Math.floor(t+s));for(let p=c;p<=h;p++){const f=1-Math.abs(p-i)/n;if(!(f<=0))for(let m=d;m<=u;m++){const v=f*(1-Math.abs(m-t)/s);if(v<=0)continue;o+=v;const g=e.at(m,p);!Number.isFinite(g)||g<Bt.NO_DATA_BELOW||(r+=v*g,a+=v)}}return o>0&&a>=o*.5?r/a:void 0}bilinear(e,t,i){const s=Math.max(0,Math.min(e.width-1,Math.floor(t))),n=Math.max(0,Math.min(e.height-1,Math.floor(i))),r=Math.min(e.width-1,s+1),a=Math.min(e.height-1,n+1),o=Math.max(0,Math.min(1,t-s)),c=Math.max(0,Math.min(1,i-n)),h=e.at(s,n),d=e.at(r,n),u=e.at(s,a),p=e.at(r,a);for(const v of[h,d,u,p])if(!Number.isFinite(v)||v<Bt.NO_DATA_BELOW)return;const f=h+(d-h)*o,m=u+(p-u)*o;return f+(m-f)*c}fill(e,t,i,s){let n=t.reduce((r,a)=>r+(a?0:1),0);for(;n>0;){const r=[];for(let a=0;a<s;a++)for(let o=0;o<i;o++){const c=a*i+o;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,m=o+p;f<0||m<0||f>=s||m>=i||!t[f*i+m]||(h+=e[f*i+m],d++)}d>0&&r.push([c,h/d])}if(r.length===0)return;for(const[a,o]of r)e[a]=o,t[a]=1;n-=r.length}}}class Fk{providers;constructor(...e){this.providers=e}async getElevationGrid(e,t,i){let s=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(e,t,i)}catch(r){s=r}throw s}}const r0=256,Uk=5;async function HT(l,e,t,i){const s=(l.south+l.north)/2,n=(l.west+l.east)/2,r=Math.abs(ot(s,l.east,s,l.west).x),a=Math.abs(ot(l.north,n,l.south,n).z),o=Math.max(r,a),{zoom:c,gridSize:h}=Bk(s,o,Math.max(e.width,e.height)),{tiles:d,bounds:u}=BT(n,s,c,h),p=h*r0,f=document.createElement("canvas");f.width=p,f.height=p;const m=f.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const v=d[0];await Promise.all(d.map(async y=>{const M=t(y),x=await i(M);if(!x.ok)throw new Error(`Imagery tile fetch failed (${x.status}): ${M}`);const E=await createImageBitmap(await x.blob());m.drawImage(E,(y.x-v.x)*r0,(y.y-v.y)*r0)}));const g=Math.min(Math.max(e.width,e.height),p);if(g===p)return{source:f,width:p,height:p,bounds:u};const b=document.createElement("canvas");b.width=g,b.height=g;const w=b.getContext("2d");if(!w)throw new Error("2D canvas context unavailable");return w.drawImage(f,0,0,p,p,0,0,g,g),{source:b,width:g,height:g,bounds:u}}function Bk(l,e,t){let i=Rk(l,e/Math.max(1,t)),s=nS(l,i,e);for(;s>Uk&&i>0;)i--,s=nS(l,i,e);return{zoom:i,gridSize:s,mPerPixel:NT(l,i)/r0}}function nS(l,e,t){const i=Math.ceil(t/2/NT(l,e));return Math.max(3,2*i+1)}class GT{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 HT(e,t,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class mr{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(e,t=mr.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(e);if(!i)return[...t];const[s,n,r,a]=i.slice(1).map(Number),o=(s+r)/2,c=(n+a)/2,h=mr.FRANCE;return o>=h.south&&o<=h.north&&c>=h.west&&c<=h.east?[mr.FRANCE_ENDPOINT,...t.filter(u=>u!==mr.FRANCE_ENDPOINT)]:[...t]}fetchImpl;endpoints;constructor(e={}){this.fetchImpl=e.fetchImpl??fetch.bind(globalThis),this.endpoints=e.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(e){return this.queued(()=>this.ask(e))}queued(e){const t=mr.queue.then(e,e);return mr.queue=t.catch(()=>{}),t}async ask(e){let t;for(const i of this.endpoints??mr.endpointsFor(e))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(mr.HANG_MS)});if(n.ok)return await n.json();if(t=new Error(`${new URL(i).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){t=new Error(`${new URL(i).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,mr.RETRY_MS))}throw t??new Error("No Overpass instance answered")}}class El{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 mr(e)}async getRoads(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];way["highway"~"^(${El.DRIVABLE.join("|")})$"](${t});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(e){const t=[];for(const i of e.elements??[]){const s=i.geometry,n=i.tags;!n||!s||s.length<2||t.push({id:`osm-${i.id??t.length}`,name:n.name,surface:El.surfaceOf(n),widthM:El.widthOf(n),...El.paintOf(n),points:s.map(r=>({lat:r.lat,lng:r.lon}))})}return t}static paintOf(e){const t=e.highway??"",i=e.junction==="roundabout"||e.junction==="circular",s=e.oneway,n=s==="yes"||s==="1"||s==="true"||s===void 0&&(t==="motorway"||i),r=s==="-1"||s==="reverse",a=Number.parseInt(e.lanes??"",10),o=Number.parseInt(e.maxspeed??"",10),c=i?"roundabout":t==="motorway"?"motorway":t.endsWith("_link")?"slip":(t==="trunk"||t==="primary")&&(n||r)?"dual":t?"road":void 0;return{...c?{kind:c}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...s!==void 0||t==="motorway"||i?{direction:r?"backward":n?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}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:El.WIDTH_M[e.highway]??El.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 mv="https://ufoathome.org/roads/index.json";class rd{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??rd.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:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.ways)?(this.attributionRead=n.attribution,this.contemporaryRead=n.contemporary,n.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(`
|
|
4402
|
-
`);let t=rd.shared.get(e);return t||(t=this.fetchFirstAvailable(),rd.shared.set(e,t),t.then(i=>{i.length===0&&rd.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.
|
|
4403
|
-
`);let t=ad.shared.get(e);return t||(t=this.fetchFirstAvailable(),ad.shared.set(e,t),t.then(i=>{i.length===0&&ad.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.0")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==gv?[t,gv]:[gv]).map(i=>i+e)}}class lr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=lr.key(e);let i=lr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),lr.asked.set(t,i),i.catch(()=>lr.asked.delete(t))),structuredClone(await i)}static forget(){lr.asked.clear()}static key(e){return`v${lr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await lr.openCache(),s=lr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<lr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&lr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-lr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(lr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class kl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Wt(e)}static covers(e){return Wt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>kl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=kl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=kl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=kl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>kl.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class pn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new mr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=pn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>ot(g.lat,g.lng,s.lat,s.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=n.filter(g=>g.service===!!r.service);for(const g of pn.samples(a)){d++;const b=pn.waysAt(u,g);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=g=>[...g.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,b)=>b[1]-g[1]||g[0].localeCompare(b[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=pn.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=pn.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=pn.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>ot(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=pn.SAMPLE_M/2;a<s;a+=pn.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(pn.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],c=n.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=pn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class od{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new mr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${od.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=pn.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=pn.voltageOf(r),c=od.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=od.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:od.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class Gk{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!kl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Os{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Os.key(e);let i=Os.asked.get(t)??Os.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Os.asked.set(t,i),s.catch(()=>Os.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Os.asked.clear(),Os.failedAt=-1/0}static key(e){return`v${Os.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Os.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Os.openCache(),s=Os.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<Os.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Os.failedAt<Os.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Os.failedAt=this.now(),n)return n;throw a}return i&&Os.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Os.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Os.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const vv="https://ufoathome.org/railways/index.json";class ld{contemporary=!0;attributionRead;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??ld.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4404
|
-
`);let t=ld.shared.get(e);return t||(t=this.fetchFirstAvailable(),ld.shared.set(e,t),t.then(i=>{i.length===0&&ld.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.0")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==vv?[t,vv]:[vv]).map(i=>i+e)}}function VT(){return{elevation:WT(),imagery:$T(),roads:KT(),water:XT(),railways:YT()}}function WT(){return new Fk(new Bt,new zT)}function $T(){return new GT}function KT(){return new rd({fallback:new zk(new Dl,new El)})}function XT(){return new ad({fallback:new lr(new Hk(new sf,new Ic))})}function YT(){return new ld({fallback:new Os(new Gk(new kl,new od))})}const Vk=new Set,Rd="show-observer-map",Cd="hide-milestones",Pc="minified";class jt extends HTMLElement{static get observedAttributes(){return["src",Rd,Cd,Pc]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new ui;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=_g.create();issues=[];issueCheck=0;sightingAudio=new Ak;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>jt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;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,s=!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 n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");jt.setIcon(this.moreButton,e?st.UNFOLDED:st.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),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.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)<jt.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>=ui.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=ui.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},jt.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 s=ui.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Mk}</style>${wk}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Qd(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Tc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=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){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Rd&&this.applyObserverMapDefault(),e===Cd&&this.setMilestonesShown(!this.hasAttribute(Cd)),e===Pc){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Pc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(qT)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await Ma.recording(e)}get sightingData(){return P0(this.currentSighting)}set sightingData(e){const t=Oi.toCurrent(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Mw(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(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 s=[];try{const{default:n}=await Q(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);s=new oa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],tf.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(Wk,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;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 s=document.createElement("li");return s.textContent=tf.text(i,this.messages.issueTemplates),s}))}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.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}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 playbackRate(){return this.player.playbackRate}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(s=>this.highlightedSourceIds.has(s))||(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)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;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 s of t)this.controlsRight.insertBefore(s,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 s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);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??""}: ${s}`),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()}),n.append(r,c),n});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(n=>this.viewOfReference(n).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"),jt.setIcon(this.referencesButton,i?st.PICTURES_ON:st.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),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)),jt.setIcon(this.tracesButton,this.tracesShownState?st.TRACES_ON:st.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?$c(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),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 s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),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 s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}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 s=[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 n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=jt.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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=jt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?fv(a,n):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}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 s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Qd(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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*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 s=jt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}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 s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?fv(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 s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=pa.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<jt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(jt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/jt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/jt.EXPOSURE_STEP_PX),n=Math.min(jt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}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=Qt.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:Vk;this.canvasRenderer.setStarPoints(Qt.starPointsOf(this.sighting.instrument,tt(this.sighting,e)?.fNumber));const s=(tt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?Jt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(sw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&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 xk(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*jt.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"?st.PLAY:st.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){jt.icons.get(e)!==t&&(jt.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},jt.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,this.updateStartState(),jt.setIcon(this.playPauseButton,e?st.PAUSE:st.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(Rd),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;jt.setIcon(this.observerMapButton,e?st.MAP_ON:st.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[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=Vc.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(s=>s.points):[],i=ui.fitted(this.observerPath,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.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?ui.expand(e,jt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=ui.IMAGERY_PX*(t?1+2*jt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:$T();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).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,s=this.observerMapView.changed?ui.expand(e,jt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;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},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=jt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[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,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=tt(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},jt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?fv(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?$c(this.currentSighting.milestones):[]){const a=tt(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}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?br.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Qt.aspectOf(i)):void 0,markers:s,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,$c(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??"",jt.setIcon(this.milestonesButton,this.milestonesShown?st.MILESTONES_ON:st.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=tt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Pr(i,e),{lat:n,lng:r}=tr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.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 s=tt(this.currentSighting,this.currentTime),n=br.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return wi.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=jt.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;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),jt.setIcon(this.miniMuteButton,this.mutedState?st.MUTED:st.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){jt.setIcon(this.muteButton,st.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}jt.setIcon(this.muteButton,this.mutedState?st.MUTED:st.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;jt.setIcon(this.fullscreenButton,e?st.EXIT_FULLSCREEN:st.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 bn(yr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=jd(yr.preferencesFor(this),qd);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await c5.load(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.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),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=Qc(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?sb(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.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return ol(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?aS(rS(this.realStartMs+i)):ol(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?ol(e):ol(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return ol(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return ol(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?ol(this.currentSighting.timeline.duration):this.canShowClockTime?aS(rS(this.realStartMs+this.realDurationMs)):ol(this.realDurationMs)}}function rS(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function aS(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function ol(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Ib="rr0-ufo";function Ug(){customElements.get(Ib)||customElements.define(Ib,jt)}const Wk="recordingissues",qT="minifiedreset";class ep{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((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.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+ep.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ep.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ep.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}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 cd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const v=n.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=ot(v.lat,v.lng,s.lat,s.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-cd.HALF_SPAN_MS),o=r(t+cd.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*cd.HALF_SPAN_MS/1e3;if(h/d<cd.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.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(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const $k=.08,oS=.15,lS=2,Kk=2e3;class Xk{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}}Wc.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(s=>s.inside||s.distanceM<Kk),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*lS*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const v=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const b=e.createGain();v.connect(g).connect(b).connect(s);const w=[n,r,h,p,v];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,g,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,c,$k),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.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*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*n)}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,oS/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},oS*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*lS,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class nf{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 nf.BY_KIND[e??"generic"]??nf.BY_KIND.generic}}class Nc{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=Nc.SAMPLE_MS,r=[];for(let c=i;c<=s+n/2;c+=n){const h=t(c-n/2),d=t(c+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=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*n/1e3);if(h<Nc.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new Nc(a,i)}at(e){const t=(e-this.startMs)/Nc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class F0{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??s?.lat,u=h?.lng??s?.lng;if(d===void 0||u===void 0||!s)return;const p=ot(d,u,s.lat,s.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=nf.of(a.kind),h=this.drive(`observer:${a.kind}`,F0.trackKey(e),()=>Nc.of(c,n,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 o=n(t);for(const c of e.decor){if(!c.engine||!o)continue;const h=nf.of(c.engine.kind),d=m=>{const v=Pr(c,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${c.id}`,F0.decorKey(c,r),()=>Nc.of(h,d,0,r));if(!u)continue;const p=Pr(c,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.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 s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}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 Yk="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==",qk=`
|
|
4402
|
+
`);let t=rd.shared.get(e);return t||(t=this.fetchFirstAvailable(),rd.shared.set(e,t),t.then(i=>{i.length===0&&rd.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.1")}`,t=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(t&&t!==mv?[t,mv]:[mv]).map(i=>i+e)}}class Dl{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 Wt(e)}static covers(e){return Wt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRoads(e){return(await this.platform.roads(e)).flatMap((i,s)=>Dl.wayOf(i,s))}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 s=String(e.properties.nature??""),n=Dl.BY_NATURE[s]??Dl.DEFAULT,r=Number(e.properties.largeur_de_chaussee),a=Number(e.properties.nombre_de_voies),o=Number(e.properties.vitesse_moyenne_vl),c=Dl.DIRECTIONS[String(e.properties.sens_de_circulation??"")],h=Dl.KINDS[s],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:n.surface,widthM:Number.isFinite(r)&&r>0?r:n.widthM,...e.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...c?{direction:c}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class zk{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(Dl.covers(e))try{const t=await this.regional.getRoads(e);if(t.length>0)return t}catch{}return this.worldwide.getRoads(e)}}class sf{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(e={}){this.platform=new Wt(e)}static covers(e){return Wt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getWater(e){return(await this.platform.waterSurfaces(e)).flatMap((i,s)=>sf.surfacesOf(i,s))}static surfacesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="Polygon"?[s]:i==="MultiPolygon"?s:[],r=String(e.properties.cleabs??`ign-water-${t}`);return n.flatMap((a,o)=>{const c=a.map(h=>sf.open(h.map(d=>({lat:d[1],lng:d[0]})))).filter(h=>h.length>=3);return c.length>0?[{id:n.length>1?`${r}-${o}`:r,rings:c}]:[]})}static open(e){const t=e[0],i=e[e.length-1];return e.length>1&&t.lat===i.lat&&t.lng===i.lng?e.slice(0,-1):e}}class Ic{attribution="Water © OpenStreetMap contributors";client;constructor(e={}){this.client=new mr(e)}async getWater(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${t});way["waterway"="riverbank"](${t});)->.w;(relation["natural"="water"](${t});relation["waterway"="riverbank"](${t});)->.r;.w out geom;.r out body;way(r.r)(${t});out geom;`;return Ic.surfacesFrom(await this.client.query(i))}static surfacesFrom(e){const t=e.elements??[],i=new Map;for(const r of t)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const s=[],n=new Set;for(const r of t){if(r.type!=="relation")continue;const a=c=>(r.members??[]).filter(h=>h.type==="way"&&h.role===c&&h.ref!==void 0&&i.has(h.ref)).map(h=>(n.add(h.ref),i.get(h.ref))),o=Ic.rings(a("inner"));for(const[c,h]of Ic.rings(a("outer")).entries()){const d=o.filter(u=>Ic.contains(h,u[0]));s.push({id:`osm-r${r.id}-${c}`,rings:[h,...d]})}}for(const r of t)if(!(r.type!=="way"||!r.tags||r.id===void 0||n.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of Ic.rings([i.get(r.id)??[]]))s.push({id:`osm-w${r.id}`,rings:[a]});return s}static rings(e){const t=(n,r)=>n.lat===r.lat&&n.lng===r.lng,i=e.filter(n=>n.length>=2).map(n=>[...n]),s=[];for(;i.length>0;){let n=i.pop(),r=!0;for(;!t(n[0],n[n.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const o=i[a],c=n[n.length-1];if(t(c,o[0]))n=[...n,...o.slice(1)];else if(t(c,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}n.length>=4&&t(n[0],n[n.length-1])&&s.push(n.slice(0,-1))}return s}static contains(e,t){let i=!1;for(let s=0,n=e.length-1;s<e.length;n=s++){const r=e[s],a=e[n];r.lat>t.lat!=a.lat>t.lat&&t.lng<(a.lng-r.lng)*(t.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class Hk{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(e){if(sf.covers(e))try{const t=await this.regional.getWater(e);if(t.length>0)return t}catch{}return this.worldwide.getWater(e)}}const gv="https://ufoathome.org/water/index.json";class ad{attributionRead;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??ad.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getWater(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.surfaces)?(this.attributionRead=n.attribution,n.surfaces):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4403
|
+
`);let t=ad.shared.get(e);return t||(t=this.fetchFirstAvailable(),ad.shared.set(e,t),t.then(i=>{i.length===0&&ad.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.1")}`,t=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(t&&t!==gv?[t,gv]:[gv]).map(i=>i+e)}}class lr{constructor(e){this.water=e}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(e){const t=lr.key(e);let i=lr.asked.get(t);return i===void 0&&(i=this.recalled(t,e),lr.asked.set(t,i),i.catch(()=>lr.asked.delete(t))),structuredClone(await i)}static forget(){lr.asked.clear()}static key(e){return`v${lr.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}async recalled(e,t){const i=await lr.openCache(),s=lr.request(e);if(i)try{const r=await i.match(s);if(r){const{savedAt:a,surfaces:o}=await r.json();if(Date.now()-a<lr.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(t);return i&&lr.store(i,s,n),n}static async store(e,t,i){try{const s={savedAt:Date.now(),surfaces:i};await e.put(t,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await e.keys();for(const r of n.slice(0,Math.max(0,n.length-lr.MAX_STORED)))await e.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(lr.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__water__/${encodeURIComponent(e)}`)}}class kl{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(e={}){this.platform=new Wt(e)}static covers(e){return Wt.covers((e.south+e.north)/2,(e.west+e.east)/2)}async getRailways(e){return(await this.platform.railways(e)).flatMap((i,s)=>kl.linesOf(i,s))}static linesOf(e,t){const{type:i,coordinates:s}=e.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],r=kl.BY_NATURE[String(e.properties.nature??"")];if(!r)return[];const a=String(e.properties.cleabs??`ign-rail-${t}`),o=Number(e.properties.nombre_de_voies),c=Number(e.properties.position_par_rapport_au_sol),h=e.properties.cpx_toponyme,d=kl.GAUGE_MM[String(e.properties.largeur??"")]??1435,u=kl.electrificationOf(r.kind,d,e.properties.electrifie);return n.flatMap((p,f)=>{const m=p.map(v=>({lat:v[1],lng:v[0],...v.length>2&&Number.isFinite(v[2])&&v[2]>kl.NO_ALTITUDE?{altitudeM:v[2]}:{}}));return m.length<2?[]:[{id:n.length>1?`${a}-${f}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:d,tracks:Number.isInteger(o)&&o>0?o:1,...u?{electrification:u}:{},level:Number.isFinite(c)?c:0,points:m}]})}static electrificationOf(e,t,i){if(i===!1)return"none";if(i===!0){if(e==="subway")return"third_rail";if(!(e==="funicular"||t<1435))return"overhead"}}}class pn{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(e={}){this.client=new mr(e)}async named(e,t){if(e.length===0)return[...e];const i=`${t.south},${t.west},${t.north},${t.east}`,s=`[out:json][timeout:120];way["railway"~"^(${pn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return pn.apply(e,await this.client.query(s),t)}static apply(e,t,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=pn.ways(t,s);return n.length===0?[...e]:e.map(r=>{const a=r.points.map(g=>ot(g.lat,g.lng,s.lat,s.lng)),o=new Map,c=new Map,h=new Map;let d=0;const u=n.filter(g=>g.service===!!r.service);for(const g of pn.samples(a)){d++;const b=pn.waysAt(u,g);if(b.length===0)continue;const[w]=b;w.name&&o.set(w.name,(o.get(w.name)??0)+1),w.voltageV&&c.set(w.voltageV,(c.get(w.voltageV)??0)+1);for(const y of new Set(b.flatMap(M=>M.services)))h.set(y,(h.get(y)??0)+1)}const p=g=>[...g.entries()].sort((b,w)=>w[1]-b[1])[0]?.[0],f=r.name??p(o),m=r.voltageV??(r.electrification==="none"?void 0:p(c)),v=[...h.entries()].filter(([,g])=>g*4>=d).sort((g,b)=>b[1]-g[1]||g[0].localeCompare(b[0])).map(([g])=>g);return{...r,...f?{name:f}:{},...m?{voltageV:m}:{},...v.length>0?{services:v}:{}}})}static serviceOf(e){const t=e.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return t||[e.network,e.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(e){const t=new Map;for(const i of e.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=pn.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const r=t.get(n.ref)??new Set;r.add(s),t.set(n.ref,r)}}return t}static voltageOf(e){const t=Number.parseInt((e.voltage??"").split(";")[0],10);return Number.isFinite(t)&&t>0?t:void 0}static ways(e,t){const i=pn.servicesByWay(e),s=[];for(const n of e.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const r=n.tags??{},a=pn.voltageOf(r);s.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>ot(o.lat,o.lon,t.lat,t.lng))})}return s}static samples(e){const t=[];for(let i=0;i<e.length-1;i++){const s=Math.hypot(e[i+1].x-e[i].x,e[i+1].z-e[i].z);if(s<1e-6)continue;const n=(e[i+1].x-e[i].x)/s,r=(e[i+1].z-e[i].z)/s;for(let a=pn.SAMPLE_M/2;a<s;a+=pn.SAMPLE_M)t.push({x:e[i].x+n*a,z:e[i].z+r*a,dx:n,dz:r})}return t}static waysAt(e,t){const i=Math.cos(pn.ALIGNED_DEG*Math.PI/180),s=[];for(const n of e){let r;for(let a=0;a<n.path.length-1;a++){const o=n.path[a],c=n.path[a+1],h=c.x-o.x,d=c.z-o.z,u=Math.hypot(h,d);if(u<1e-6||Math.abs((h*t.dx+d*t.dz)/u)<i)continue;const p=Math.max(0,Math.min(1,((t.x-o.x)*h+(t.z-o.z)*d)/(u*u))),f=Math.hypot(t.x-(o.x+h*p),t.z-(o.z+d*p));f<=pn.NEAR_M&&(r===void 0||f<r)&&(r=f)}r!==void 0&&s.push({way:n,distance:r})}return s.sort((n,r)=>n.distance-r.distance).map(({way:n})=>n)}}class od{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(e={}){this.client=new mr(e)}async getRailways(e){const t=`${e.south},${e.west},${e.north},${e.east}`,i=`[out:json][timeout:25];way["railway"~"^(${od.KINDS.join("|")})$"](${t})->.w;.w out tags geom;rel(bw.w)["route"~"^(${pn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(e){const t=[],i=pn.servicesByWay(e);for(const s of e.elements??[]){const n=s.geometry,r=s.tags;if(s.type==="relation"||!r||!n||n.length<2)continue;const a=[...i.get(s.id??-1)??[]].sort(),o=pn.voltageOf(r),c=od.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),d=Number.parseInt(r.tracks??"",10),u=od.electrificationOf(r.electrified),p=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;t.push({id:`osm-rail-${s.id??t.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...o?{voltageV:o}:{},kind:c,...r.service||r.usage==="industrial"?{service:!0}:{},...p?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(d)&&d>0?d:1,...u?{electrification:u}:{},level:od.levelOf(r),points:n.map(f=>({lat:f.lat,lng:f.lon}))})}return t}static kindOf(e){switch(e.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(e){if(e!==void 0){if(e==="no")return"none";if(e==="contact_line"||e==="yes")return"overhead";if(e==="rail"||e==="4th_rail"||e==="ground-level_power_supply")return"third_rail"}}static levelOf(e){const t=Number.parseInt(e.layer??"",10);return e.tunnel&&e.tunnel!=="no"?Number.isFinite(t)&&t<0?t:-1:e.covered==="yes"&&e.location==="underground"?-1:e.bridge&&e.bridge!=="no"?Number.isFinite(t)&&t>0?t:1:0}}class Gk{constructor(e,t){this.regional=e,this.worldwide=t}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(e){if(!kl.covers(e))return this.worldwide.getRailways(e);let t;try{if(t=await this.regional.getRailways(e),t.length>0)return t}catch{}try{return await this.worldwide.getRailways(e)}catch(i){if(t)return t;throw i}}}class Os{constructor(e,t=Date.now){this.railways=e,this.now=t}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(e){const t=Os.key(e);let i=Os.asked.get(t)??Os.containing(e);if(i===void 0){const s=this.recalled(t,e);i={bounds:e,answer:s},Os.asked.set(t,i),s.catch(()=>Os.asked.delete(t))}return structuredClone(await i.answer)}static forget(){Os.asked.clear(),Os.failedAt=-1/0}static key(e){return`v${Os.FORMAT}/${[e.north,e.south,e.east,e.west].map(t=>t.toFixed(5)).join("/")}`}static containing(e){for(const t of Os.asked.values()){const i=t.bounds;if(i.north>=e.north&&i.south<=e.south&&i.east>=e.east&&i.west<=e.west)return t}}async recalled(e,t){const i=await Os.openCache(),s=Os.request(e);let n;if(i)try{const a=await i.match(s);if(a){const{savedAt:o,lines:c}=await a.json();if(Array.isArray(c)){if(this.now()-o<Os.MAX_AGE_MS)return c;n=c}}}catch{}if(this.now()-Os.failedAt<Os.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(t)}catch(a){if(Os.failedAt=this.now(),n)return n;throw a}return i&&Os.store(i,s,{savedAt:this.now(),lines:r}),r}static async store(e,t,i){try{await e.delete(t),await e.put(t,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await e.keys();for(const n of s.slice(0,Math.max(0,s.length-Os.MAX_STORED)))await e.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(Os.CACHE_NAME)}catch{return}}static request(e){const t=typeof location>"u"?"http://localhost":location.origin;return new Request(`${t}/__railways__/${encodeURIComponent(e)}`)}}const vv="https://ufoathome.org/railways/index.json";class ld{contemporary=!0;attributionRead;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??ld.defaultIndexUrls(),this.fallback=e.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(e){const t=await this.held(e);if(t)return t;if(!this.fallback)return[];const i=await this.fallback.getRailways(e);return this.attributionRead=this.fallback.attribution,i}async held(e){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=e.north&&s.south<=e.south&&s.east>=e.east&&s.west<=e.west);if(i)try{const s=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!s.ok)return;const n=await s.json();return Array.isArray(n?.lines)?(this.attributionRead=n.attribution,n.lines):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const e=this.indexUrls.join(`
|
|
4404
|
+
`);let t=ld.shared.get(e);return t||(t=this.fetchFirstAvailable(),ld.shared.set(e,t),t.then(i=>{i.length===0&&ld.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(s=>({entry:s,indexUrl:e}))}catch{}return[]}static defaultIndexUrls(){const e=`?v=${encodeURIComponent("0.170.1")}`,t=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(t&&t!==vv?[t,vv]:[vv]).map(i=>i+e)}}function VT(){return{elevation:WT(),imagery:$T(),roads:KT(),water:XT(),railways:YT()}}function WT(){return new Fk(new Bt,new zT)}function $T(){return new GT}function KT(){return new rd({fallback:new zk(new Dl,new El)})}function XT(){return new ad({fallback:new lr(new Hk(new sf,new Ic))})}function YT(){return new ld({fallback:new Os(new Gk(new kl,new od))})}const Vk=new Set,Rd="show-observer-map",Cd="hide-milestones",Pc="minified";class jt extends HTMLElement{static get observedAttributes(){return["src",Rd,Cd,Pc]}shadow;stageElement;canvas;canvasRenderer;chromeCanvas;chromeRenderer;chromeResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>{this.chromeDirty&&this.refresh()});chromeDirty=!1;tooltip;toolbar;issuesBox;issuesButton;issuesPanel;playPauseButton;fullscreenButton;cornerButtons;observerMapButton;referencesButton;tracesButton;tracesShownState=!0;referenceOpacityInput;referencesShownState=!0;accountHidden=!1;referenceViews=new Map;referencesMenu;referenceOpacityTouched=!1;milestonesButton;observerMapPanel;observerMapCanvas;observerMapRenderer;mapZoomInButton;mapZoomOutButton;mapFitButton;observerMapView=new ui;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=_g.create();issues=[];issueCheck=0;sightingAudio=new Ak;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>jt.LIVE_BODY_MAX_RATE}selectionShown=!0;overlayPainter;enableClickToPlay=!0;fullscreenTarget;ready=Promise.resolve();messages;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,s=!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 n of["nomoments","compact","tiny"]){if(!i())break;e.classList.add(n)}t&&e.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(e){this.controlsRow.classList.toggle("more-open",!e),this.updateMoreButton()}updateMoreButton(){const e=this.controlsRow.classList.contains("more-open");jt.setIcon(this.moreButton,e?st.UNFOLDED:st.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),s=this.said.read(i?.shape.title);if(!s){this.tooltip.hidden=!0;return}this.tooltip.textContent=s,this.tooltip.hidden=!1;const n=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${e.clientX-n.left+12}px`,this.tooltip.style.top=`${e.clientY-n.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)<jt.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>=ui.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=ui.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},jt.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 s=ui.pointAt(t,(e.clientX-i.left)/i.width,(e.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:s,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${Mk}</style>${wk}`,this.shadow.appendChild(e.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Qd(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new Tc(this.observerMapCanvas.getContext("2d")),this.mapZoomInButton=this.shadow.getElementById("map-zoom-in"),this.mapZoomOutButton=this.shadow.getElementById("map-zoom-out"),this.mapFitButton=this.shadow.getElementById("map-fit"),this.seekInput=this.shadow.getElementById("seek"),this.playbackFlash=this.shadow.getElementById("playback-flash"),this.milestoneMarks=this.shadow.getElementById("milestone-marks"),this.milestoneCaption=this.shadow.getElementById("milestone-caption"),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end"),this.timePill=this.shadow.getElementById("time"),this.muteButton=this.shadow.getElementById("mute"),this.controlsRight=this.shadow.getElementById("controls-right"),this.seekSegments=this.shadow.getElementById("seek-segments"),this.seekDot=this.shadow.getElementById("seek-dot"),this.playerTitleBox=this.shadow.getElementById("player-title"),this.seekPreview=this.shadow.getElementById("seek-preview"),this.seekPreviewCanvas=this.shadow.getElementById("seek-preview-canvas"),this.seekPreviewTitle=this.shadow.getElementById("seek-preview-title"),this.seekPreviewTime=this.shadow.getElementById("seek-preview-time"),this.timePill.addEventListener("click",()=>this.toggleTimeDisplay()),this.timePill.addEventListener("keydown",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const t=this.shadow.getElementById("mini-bar"),i=t.querySelector(".mini-track"),s=a=>{const o=i.getBoundingClientRect(),c=this.player.seekableDuration;if(o.width<=0||c<=0)return;const h=Math.min(Math.max((a.clientX-o.left)/o.width,0),1)*c;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;t.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),t.setPointerCapture(a.pointerId),t.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(a))}),t.addEventListener("pointermove",a=>{t.hasPointerCapture(a.pointerId)&&s(a)});const r=a=>{t.classList.contains("scrubbing")&&(t.classList.remove("scrubbing"),t.hasPointerCapture(a.pointerId)&&t.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};t.addEventListener("pointerup",r),t.addEventListener("pointercancel",r),t.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=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){if(e==="src"&&i&&i!==t&&this.isConnected&&this.loadFromSrc(i),e===Rd&&this.applyObserverMapDefault(),e===Cd&&this.setMilestonesShown(!this.hasAttribute(Cd)),e===Pc){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&t===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Pc)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=e=>{!this.minified||e.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(qT)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const e=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",e),e&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(e){this.sightingData=await Ma.recording(e)}get sightingData(){return P0(this.currentSighting)}set sightingData(e){const t=Oi.toCurrent(e);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=Mw(t),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(t,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(e){this.titleOverride=e,this.syncPlayerTitle()}titleOverride;syncPlayerTitle(){const e=this.said.read(this.titleOverride)??this.said.read(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 s=[];try{const{default:n}=await Q(async()=>{const{default:r}=await import("./sightingSchema-B1hstz7u.js");return{default:r}},[],import.meta.url);s=new oa(n).issues(e)}catch{}i===this.issueCheck&&(this.issues=[...s,...t.loadIssues],tf.warn(this.issues,t.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(Wk,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;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 s=document.createElement("li");return s.textContent=tf.text(i,this.messages.issueTemplates),s}))}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.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}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 playbackRate(){return this.player.playbackRate}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(s=>this.highlightedSourceIds.has(s))||(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)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;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 s of t)this.controlsRight.insertBefore(s,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 s=t.getBoundingClientRect().width;t.style.left=`${Math.max(i,Math.min(e.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const e=this.currentSighting.references.map(t=>{const i=this.viewOfReference(t),s=this.said.read(t.title)??t.id,n=document.createElement("div");n.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,r.append(a,o);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??""}: ${s}`),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()}),n.append(r,c),n});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(n=>this.viewOfReference(n).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"),jt.setIcon(this.referencesButton,i?st.PICTURES_ON:st.PICTURES_OFF);const s=t?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=s,this.referencesButton.setAttribute("aria-label",s),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)),jt.setIcon(this.tracesButton,this.tracesShownState?st.TRACES_ON:st.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?$c(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...t.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/e,0),1)*100}%`;const n=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${n} — ${r}`:n;return s.title=a,s.setAttribute("aria-label",a),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),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 s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return n.textContent=a?`${r} — ${a}`:r,n.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),s.appendChild(n),s})),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 s of this.momentsMenu.querySelectorAll("button")){const n=e!==void 0&&Number(s.dataset.t)===e.t;s.getAttribute("aria-current")==="true"!==n&&s.setAttribute("aria-current",String(n))}}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 s=[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 n=[];for(let r=0;r<s.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(s[r+1]-s[r],1));const o=document.createElement("i");o.className="seek-hover";const c=document.createElement("i");c.className="seek-played",a.append(o,c),n.push(a),this.seekSegmentList.push({start:s[r],end:s[r+1],element:a,played:c,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(e,t){const i=e.end-e.start,s=i>0?(t-e.start)/i:t>=e.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(e){const t=this.player.seekableDuration,i=`${t>0?Math.min(Math.max(e/t,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(e)}miniDot;miniScrubTime;paintSeekProgress(e){for(const i of this.seekSegmentList)i.played.style.width=jt.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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1),n=s*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((p,f)=>{p.hover.style.width=jt.fillOf(p,n),p.element.classList.toggle("hovered",n>=p.start&&(n<p.end||f===r))});const a=this.milestonesShown?this.sighting.milestones:[],o=a.length>0?fv(a,n):void 0,c=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,d=h?`${c} — ${h}`:c;this.seekPreviewTitle.textContent=d,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const u=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*t.width-u/2,0),Math.max(t.width-u,0))}px`,this.paintSeekPreview(n)}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 s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!t||typeof t.setTransform!="function"||s===0||n===0){e(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(s*r)),o=Math.max(1,Math.round(n*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,a,o),this.chromeDirty=!1,i&&(t.setTransform(a/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Qd(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 s=Math.min(Math.max((e.clientX-t.left)/t.width,0),1);this.player.seek(this.snapSeekToMark(s*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 s=jt.MARK_SNAP_PX/i*t;let n;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-e)>s||(!n||Math.abs(a-e)<Math.abs(n.t-e))&&(n={t:a,name:r.title})}return n}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 s=(e.clientX-t.left)/t.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(e){const t=this.milestonesShown&&this.sighting.milestones.length>0?fv(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 s=this.said.read(t.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(e){const t=this.exposureTimes(e),i=1/t.length;return t.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(e=this.currentTime){const t=pa.windowEndingAt(e,this.currentSighting.exposure??0);if(t.ms<jt.SHORTEST_VISIBLE_EXPOSURE_MS)return[e];const i=Math.min(jt.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(t.ms/jt.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(t.fromMs,t.ms)/jt.EXPOSURE_STEP_PX),n=Math.min(jt.MAX_TRAVEL_STEPS,Math.max(i,s)),r=[];for(let a=0;a<n;a++)r.push(t.fromMs+t.ms*a/(n-1));return r}travelPxOver(e,t){const i=this.shapesAt(e),s=this.shapesAt(e+t);let n=0;for(const[r,a]of i){const o=s.get(r);if(!o)continue;const c=o.bounds.x+o.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(a.bounds.y+a.bounds.height/2);n=Math.max(n,Math.hypot(c,h))}return n}shapeAt(e,t,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,e,t,i);if(n)return n}}shapesAt(e){const t=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(e,i);s&&t.set(i,s)}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=Qt.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:Vk;this.canvasRenderer.setStarPoints(Qt.starPointsOf(this.sighting.instrument,tt(this.sighting,e)?.fNumber));const s=(tt(this.sighting,e)?.rollDeg??0)+this.gaitAt(e).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(e),r=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,c]of o.shapes){const h=o.share,d=h===1?c:{...c,transparency:1-(1-c.transparency)*h};this.canvasRenderer.paintShape(this.shifted(d,r))}for(const[o,c]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...c,selected:!0}):this.canvasRenderer.paintMemberOutline(c):this.canvasRenderer.paintSelectionOnly(this.shifted(c,r)));const a=this.selectionShown&&i.size>1?Jt.groupBoundsFor([...t].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{a&&o.paintGroupHandles(a),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(c=>c.transparency<1).map(c=>this.shifted(c,r).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(e),this.paintSeekProgress(e),this.minified&&this.paintMiniProgress(e),this.timeStartLabel.textContent=this.formatPosition(e),this.showMilestoneAt(e),this.paintObserverMap(e),this.playbackState==="playing"?(this.soundPreview=void 0,this.sightingAudio.setSound(sw(this.currentSighting,e))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&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 xk(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*jt.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"?st.PLAY:st.PAUSE,e.classList.remove("flashing"),e.offsetWidth,e.classList.add("flashing")}static icons=new WeakMap;static setIcon(e,t){jt.icons.get(e)!==t&&(jt.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},jt.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,this.updateStartState(),jt.setIcon(this.playPauseButton,e?st.PAUSE:st.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(Rd),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;jt.setIcon(this.observerMapButton,e?st.MAP_ON:st.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[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const e=this.observerPath!==void 0;if(this.observerPath=Vc.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(s=>s.points):[],i=ui.fitted(this.observerPath,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.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(e)))return;const t=this.observerMapView.changed,i=t?ui.expand(e,jt.OBSERVER_MAP_IMAGERY_AHEAD):e,s=ui.IMAGERY_PX*(t?1+2*jt.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=e.east-e.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,r=n?void 0:$T();try{const a=r?await r.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??n).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,s=this.observerMapView.changed?ui.expand(e,jt.OBSERVER_MAP_IMAGERY_LOOKAHEAD):e,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,r=e.east-e.west>this.observerMapImageryViewWidth/2;return!n||!r}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(e){e!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=e,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;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},s=[this.canvas.width-e.width,this.canvas.width],n=[0,e.width],r=jt.OBSERVER_MAP_CLEARANCE_PX,a=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(o||!i(s[0],s[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(s[0],s[1],0)&&!i(n[0],n[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,s=this.canvas.height/t.height;this.observerMapBoxPx={width:e.width*i,top:(e.top-t.top)*s,bottom:(e.bottom-t.top)*s}}paintObserverMap(e){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const t=tt(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},jt.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?fv(this.currentSighting.milestones,e):void 0;for(const r of this.milestonesShown?$c(this.currentSighting.milestones):[]){const a=tt(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||s.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===n})}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?br.of(i,this.canvas.height,t.fovDeg).halfWidthAngleDeg(Qt.aspectOf(i)):void 0,markers:s,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,$c(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??"",jt.setIcon(this.milestonesButton,this.milestonesShown?st.MILESTONES_ON:st.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=tt(this.currentSighting,0);return t?.lat===void 0||t.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=Pr(i,e),{lat:n,lng:r}=tr(s.eastM,-s.northM,t.lat,t.lng);return{lat:n,lng:r,headingDeg:s.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 s=tt(this.currentSighting,this.currentTime),n=br.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(t),y:n.angleDegToRadiusPx(i)}}gaitAt(e){return wi.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=jt.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;this.miniMuteButton.hidden=e,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),jt.setIcon(this.miniMuteButton,this.mutedState?st.MUTED:st.VOLUME);const t=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=t,this.miniMuteButton.setAttribute("aria-label",t),this.muteButton.disabled=e,this.volumeInput.hidden=e,e){jt.setIcon(this.muteButton,st.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}jt.setIcon(this.muteButton,this.mutedState?st.MUTED:st.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const e=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;jt.setIcon(this.fullscreenButton,e?st.EXIT_FULLSCREEN:st.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 bn(yr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const e=jd(yr.preferencesFor(this),qd);if(e===this.messagesLanguage)return;this.messagesLanguage=e;const t=await c5.load(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.volumeInput.title=e.volume,this.volumeInput.setAttribute("aria-label",e.volume),this.updateMoreButton(),this.updateStartState(),this.referencesMenu.hidden||this.renderReferencesMenu(),this.refreshMilestoneMarks(),this.paintObserverMap(this.currentTime),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=Qc(e);this.realDurationMs=t!==void 0&&t>0?t:void 0,this.realStartMs=e.time?sb(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.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(e){if(this.realDurationMs===void 0)return ol(e);const t=this.currentSighting.timeline.duration,i=t>0&&e<=t?e/t*this.realDurationMs:e;return this.canShowClockTime?aS(rS(this.realStartMs+i)):ol(i)}formatElapsedAt(e){const t=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?ol(e):ol(t>0&&e<=t?e/t*this.realDurationMs:e)}formatRemaining(e){const t=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return ol(Math.max(0,t-e));const i=t>0&&e<=t?e/t*this.realDurationMs:e;return ol(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?ol(this.currentSighting.timeline.duration):this.canShowClockTime?aS(rS(this.realStartMs+this.realDurationMs)):ol(this.realDurationMs)}}function rS(l){const e=new Date(l);return{hour:e.getUTCHours(),minute:e.getUTCMinutes(),second:e.getUTCSeconds()}}function aS(l){if(l.hour===void 0)return"0:00";const e=t=>String(t).padStart(2,"0");return l.second?`${e(l.hour)}:${e(l.minute??0)}:${e(l.second)}`:`${e(l.hour)}:${e(l.minute??0)}`}function ol(l){const e=Math.round(l/1e3),t=Math.floor(e/60),i=e%60;return`${t}:${String(i).padStart(2,"0")}`}const Ib="rr0-ufo";function Ug(){customElements.get(Ib)||customElements.define(Ib,jt)}const Wk="recordingissues",qT="minifiedreset";class ep{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((n,r)=>n.t-r.t):[],s=`${t}|${i.map(n=>`${n.kind}:${n.t}:${n.label}`).join("|")}`;s!==this.drawn&&(this.drawn=s,this.marks=i,this.duration=t,this.layer.replaceChildren(...i.map(n=>{const r=document.createElement("span");return r.className=`timeline-mark ${n.kind}`,r.style.left=`${Math.min(Math.max(n.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+ep.SAME_INSTANT)?.t}previous(e){return[...this.marks].reverse().find(t=>t.t<e-ep.SAME_INSTANT)?.t}static SAME_INSTANT=.5;markNear(e){const t=this.seekInput.getBoundingClientRect().width;if(this.duration<=0||t<=0)return;const i=ep.SNAP_PX/t*this.duration;let s;for(const n of this.marks)Math.abs(n.t-e)>i||(!s||Math.abs(n.t-e)<Math.abs(s.t-e)||n.t===s.t&&n.kind==="milestone")&&(s=n);return s}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 cd{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(e,t,i){const s=e.event.place?.[0],n=e.observerTrack;if(!s)return 0;const r=m=>{const v=n.getInterpolatedPoseAt(Math.max(0,m));if(!v||v.lat===void 0||v.lng===void 0)return;const g=ot(v.lat,v.lng,s.lat,s.lng);return{eastM:g.x,northM:-g.z,heading:v.headingDeg}},a=r(t-cd.HALF_SPAN_MS),o=r(t+cd.HALF_SPAN_MS),c=r(t);if(!a||!o||!c)return 0;const h=Math.hypot(o.eastM-a.eastM,o.northM-a.northM),d=2*cd.HALF_SPAN_MS/1e3;if(h/d<cd.MIN_SPEED_MS)return 0;const u=i.heightAt(o.eastM,o.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(o.eastM-a.eastM,o.northM-a.northM)*180/Math.PI;return p*Math.max(0,Math.cos((c.heading-f)*Math.PI/180))}}const $k=.08,oS=.15,lS=2,Kk=2e3;class Xk{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}}Wc.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(s=>s.inside||s.distanceM<Kk),i=new Set(t.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of t){const n=this.voices.get(s.id)??this.build(e,s.id);this.retarget(e,n,s)}}build(e,t){const i=e.createGain();i.gain.value=0;const s=e.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(e));const n=e.createOscillator();n.type="sawtooth";const r=e.createOscillator();r.type="sine";const a=e.createGain(),o=e.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),r.connect(o),o.connect(a).connect(s);const c=()=>{const M=e.createBufferSource();return M.buffer=this.noise(e),M.loop=!0,M.loopStart=Math.random()*lS*.5,M},h=c(),d=e.createBiquadFilter();d.type="bandpass",d.Q.value=4;const u=e.createGain();h.connect(d).connect(u).connect(s);const p=c(),f=e.createBiquadFilter();f.type="lowpass",f.frequency.value=600;const m=e.createGain();p.connect(f).connect(m).connect(s);const v=c(),g=e.createBiquadFilter();g.type="bandpass",g.frequency.value=1400,g.Q.value=.7;const b=e.createGain();v.connect(g).connect(b).connect(s);const w=[n,r,h,p,v];for(const M of w)M.start();const y={nodes:[i,s,a,o,d,u,f,m,g,b,...w],sources:w,firing:n,crank:r,knock:d,engineGain:a,knockGain:u,roadGain:m,windGain:b,cabin:s,output:i};return this.voices.set(t,y),y}retarget(e,t,{profile:i,state:s,noise:n,inside:r,windowsOpen:a,distanceM:o}){const c=e.currentTime,h=(b,w)=>b.setTargetAtTime(w,c,$k),d=s.rpm/60,u=d*i.cylinders/2,p=Math.min(1,s.rpm/i.shiftUpRpm),f=Math.min(1.5,s.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*s.load)*(.5+.5*p)*.3),h(t.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(t.roadGain.gain,i.roadGain*f**1.5*.8);const m=!r||a;h(t.windGain.gain,f**2*(m?.5:.06));const v=r?a?3500:700:8e3/(1+o/60);h(t.cabin.frequency,v);const g=r?.5:Math.min(1,8/Math.max(o,1));h(t.output.gain,g*n)}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,oS/3),setTimeout(()=>{for(const s of t.sources)try{s.stop()}catch{}for(const s of t.nodes)s.disconnect()},oS*1e3*3))}noise(e){if(this.noiseBuffer)return this.noiseBuffer;const t=e.createBuffer(1,e.sampleRate*lS,e.sampleRate),i=t.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=t,t}}class nf{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 nf.BY_KIND[e??"generic"]??nf.BY_KIND.generic}}class Nc{constructor(e,t){this.samples=e,this.startMs=t}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(e,t,i,s){const n=Nc.SAMPLE_MS,r=[];for(let c=i;c<=s+n/2;c+=n){const h=t(c-n/2),d=t(c+n/2);if(!h||!d)return;r.push(Math.hypot(d.eastM-h.eastM,d.northM-h.northM)/(n/1e3))}const a=[];let o=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*n/1e3);if(h<Nc.STANDING_MPS){o=1,a.push({speedMps:h,rpm:e.idleRpm,load:.1,gear:0});continue}const u=h*3.6,p=g=>u/e.kmhPer1000Rpm[g-1]*1e3;for(;o<e.kmhPer1000Rpm.length&&p(o)>e.shiftUpRpm;)o++;for(;o>1&&p(o)<e.shiftDownRpm;)o--;const f=Math.max(p(o),e.idleRpm*(1+.3*Math.min(1,h/3))),m=.15+.5*Math.min(1,(h/35)**2),v=d>.15?Math.min(1,m+d/2.5):d<-.3?.05:m;a.push({speedMps:h,rpm:f,load:v,gear:o})}return new Nc(a,i)}at(e){const t=(e-this.startMs)/Nc.SAMPLE_MS,i=Math.min(Math.max(Math.floor(t),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],r=Math.min(Math.max(t-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*r,rpm:s.rpm+(n.rpm-s.rpm)*r,load:s.load+(n.load-s.load)*r,gear:r<.5?s.gear:n.gear}}}class F0{drives=new Map;at(e,t){const i=[],s=e.event.place?.[0],n=c=>{const h=e.observerTrack.getInterpolatedPoseAt(c),d=h?.lat??s?.lat,u=h?.lng??s?.lng;if(d===void 0||u===void 0||!s)return;const p=ot(d,u,s.lat,s.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=nf.of(a.kind),h=this.drive(`observer:${a.kind}`,F0.trackKey(e),()=>Nc.of(c,n,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 o=n(t);for(const c of e.decor){if(!c.engine||!o)continue;const h=nf.of(c.engine.kind),d=m=>{const v=Pr(c,m);return{eastM:v.eastM,northM:v.northM}},u=this.drive(`decor:${c.id}`,F0.decorKey(c,r),()=>Nc.of(h,d,0,r));if(!u)continue;const p=Pr(c,t),f=Math.hypot(p.eastM-o.eastM,p.northM-o.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 s=this.drives.get(e);if(s&&s.key===t)return s.drive;const n=i();return this.drives.set(e,{key:t,drive:n}),n}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 Yk="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==",qk=`
|
|
4405
4405
|
<div class="stage" id="stage">
|
|
4406
4406
|
<div class="frame" id="frame">
|
|
4407
4407
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -8876,7 +8876,7 @@ Material Type: `+_.type+`
|
|
|
8876
8876
|
|
|
8877
8877
|
Program Info Log: `+C+`
|
|
8878
8878
|
`+W+`
|
|
8879
|
-
`+J)}else C!==""?We("WebGLProgram: Program Info Log:",C):(N===""||F==="")&&(j=!1);j&&(_.diagnostics={runnable:H,programLog:C,vertexShader:{log:N,prefix:v},fragmentShader:{log:F,prefix:g}})}s.deleteShader(M),s.deleteShader(x),S=new u0(s,m),A=$6(s,m)}let S;this.getUniforms=function(){return S===void 0&&E(this),S};let A;this.getAttributes=function(){return A===void 0&&E(this),A};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=s.getProgramParameter(m,P6)),T},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=N6++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=M,this.fragmentShader=x,this}let oN=0;class lN{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const s=this._getShaderCacheForMaterial(e);return s.has(t)===!1&&(s.add(t),t.usedTimes++),s.has(i)===!1&&(s.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new cN(e),t.set(e,i)),i}}class cN{constructor(e){this.id=oN++,this.code=e,this.usedTimes=0}}function hN(l){return l===rh||l===B0||l===z0}function dN(l,e,t,i,s,n){const r=new Ow,a=new lN,o=new Set,c=[],h=new Map,d=i.logarithmicDepthBuffer;let u=i.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(S){return o.add(S),S===0?"uv":`uv${S}`}function m(S,A,T,_,k,L){const P=_.fog,C=k.geometry,N=S.isMeshStandardMaterial||S.isMeshLambertMaterial||S.isMeshPhongMaterial?_.environment:null,F=S.isMeshStandardMaterial||S.isMeshLambertMaterial&&!S.envMap||S.isMeshPhongMaterial&&!S.envMap,H=e.get(S.envMap||N,F),j=H&&H.mapping===Bg?H.image.height:null,W=p[S.type];S.precision!==null&&(u=i.getMaxPrecision(S.precision),u!==S.precision&&We("WebGLProgram.getParameters:",S.precision,"not supported, using",u,"instead."));const J=C.morphAttributes.position||C.morphAttributes.normal||C.morphAttributes.color,re=J!==void 0?J.length:0;let Le=0;C.morphAttributes.position!==void 0&&(Le=1),C.morphAttributes.normal!==void 0&&(Le=2),C.morphAttributes.color!==void 0&&(Le=3);let He,De,Z,ce;if(W){const ze=Wa[W];He=ze.vertexShader,De=ze.fragmentShader}else{He=S.vertexShader,De=S.fragmentShader;const ze=a.getVertexShaderStage(S),ps=a.getFragmentShaderStage(S);a.update(S,ze,ps),Z=ze.id,ce=ps.id}const le=l.getRenderTarget(),$=l.state.buffers.depth.getReversed(),Ue=k.isInstancedMesh===!0,je=k.isBatchedMesh===!0,Be=!!S.map,Oe=!!S.matcap,nt=!!H,lt=!!S.aoMap,ct=!!S.lightMap,fi=!!S.bumpMap&&S.wireframe===!1,mi=!!S.normalMap,ds=!!S.displacementMap,ts=!!S.emissiveMap,us=!!S.metalnessMap,Cs=!!S.roughnessMap,z=S.anisotropy>0,ar=S.clearcoat>0,gi=S.dispersion>0,O=S.iridescence>0,I=S.sheen>0,V=S.transmission>0,Y=z&&!!S.anisotropyMap,ee=ar&&!!S.clearcoatMap,de=ar&&!!S.clearcoatNormalMap,me=ar&&!!S.clearcoatRoughnessMap,te=O&&!!S.iridescenceMap,ne=O&&!!S.iridescenceThicknessMap,ve=I&&!!S.sheenColorMap,Ze=I&&!!S.sheenRoughnessMap,Ee=!!S.specularMap,be=!!S.specularColorMap,it=!!S.specularIntensityMap,dt=V&&!!S.transmissionMap,_t=V&&!!S.thicknessMap,B=!!S.gradientMap,fe=!!S.alphaMap,se=S.alphaTest>0,ye=!!S.alphaHash,_e=!!S.extensions;let ae=oo;S.toneMapped&&(le===null||le.isXRRenderTarget===!0)&&(ae=l.toneMapping);const Xe={shaderID:W,shaderType:S.type,shaderName:S.name,vertexShader:He,fragmentShader:De,defines:S.defines,customVertexShaderID:Z,customFragmentShaderID:ce,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:u,batching:je,batchingColor:je&&k._colorsTexture!==null,instancing:Ue,instancingColor:Ue&&k.instanceColor!==null,instancingMorph:Ue&&k.morphTexture!==null,outputColorSpace:le===null?l.outputColorSpace:le.isXRRenderTarget===!0?le.texture.colorSpace:Kt.workingColorSpace,alphaToCoverage:!!S.alphaToCoverage,map:Be,matcap:Oe,envMap:nt,envMapMode:nt&&H.mapping,envMapCubeUVHeight:j,aoMap:lt,lightMap:ct,bumpMap:fi,normalMap:mi,displacementMap:ds,emissiveMap:ts,normalMapObjectSpace:mi&&S.normalMapType===SR,normalMapTangentSpace:mi&&S.normalMapType===V0,packedNormalMap:mi&&S.normalMapType===V0&&hN(S.normalMap.format),metalnessMap:us,roughnessMap:Cs,anisotropy:z,anisotropyMap:Y,clearcoat:ar,clearcoatMap:ee,clearcoatNormalMap:de,clearcoatRoughnessMap:me,dispersion:gi,iridescence:O,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:I,sheenColorMap:ve,sheenRoughnessMap:Ze,specularMap:Ee,specularColorMap:be,specularIntensityMap:it,transmission:V,transmissionMap:dt,thicknessMap:_t,gradientMap:B,opaque:S.transparent===!1&&S.blending===Zl&&S.alphaToCoverage===!1,alphaMap:fe,alphaTest:se,alphaHash:ye,combine:S.combine,mapUv:Be&&f(S.map.channel),aoMapUv:lt&&f(S.aoMap.channel),lightMapUv:ct&&f(S.lightMap.channel),bumpMapUv:fi&&f(S.bumpMap.channel),normalMapUv:mi&&f(S.normalMap.channel),displacementMapUv:ds&&f(S.displacementMap.channel),emissiveMapUv:ts&&f(S.emissiveMap.channel),metalnessMapUv:us&&f(S.metalnessMap.channel),roughnessMapUv:Cs&&f(S.roughnessMap.channel),anisotropyMapUv:Y&&f(S.anisotropyMap.channel),clearcoatMapUv:ee&&f(S.clearcoatMap.channel),clearcoatNormalMapUv:de&&f(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:me&&f(S.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&f(S.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&f(S.iridescenceThicknessMap.channel),sheenColorMapUv:ve&&f(S.sheenColorMap.channel),sheenRoughnessMapUv:Ze&&f(S.sheenRoughnessMap.channel),specularMapUv:Ee&&f(S.specularMap.channel),specularColorMapUv:be&&f(S.specularColorMap.channel),specularIntensityMapUv:it&&f(S.specularIntensityMap.channel),transmissionMapUv:dt&&f(S.transmissionMap.channel),thicknessMapUv:_t&&f(S.thicknessMap.channel),alphaMapUv:fe&&f(S.alphaMap.channel),vertexTangents:!!C.attributes.tangent&&(mi||z),vertexNormals:!!C.attributes.normal,vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!C.attributes.color&&C.attributes.color.itemSize===4,pointsUvs:k.isPoints===!0&&!!C.attributes.uv&&(Be||fe),fog:!!P,useFog:S.fog===!0,fogExp2:!!P&&P.isFogExp2,flatShading:S.wireframe===!1&&(S.flatShading===!0||C.attributes.normal===void 0&&mi===!1&&(S.isMeshLambertMaterial||S.isMeshPhongMaterial||S.isMeshStandardMaterial||S.isMeshPhysicalMaterial)),sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:$,skinning:k.isSkinnedMesh===!0,hasPositionAttribute:C.attributes.position!==void 0,morphTargets:C.morphAttributes.position!==void 0,morphNormals:C.morphAttributes.normal!==void 0,morphColors:C.morphAttributes.color!==void 0,morphTargetsCount:re,morphTextureStride:Le,numDirLights:A.directional.length,numPointLights:A.point.length,numSpotLights:A.spot.length,numSpotLightMaps:A.spotLightMap.length,numRectAreaLights:A.rectArea.length,numHemiLights:A.hemi.length,numDirLightShadows:A.directionalShadowMap.length,numPointLightShadows:A.pointShadowMap.length,numSpotLightShadows:A.spotShadowMap.length,numSpotLightShadowsWithMaps:A.numSpotLightShadowsWithMaps,numLightProbes:A.numLightProbes,numLightProbeGrids:L.length,numClippingPlanes:n.numPlanes,numClipIntersection:n.numIntersection,dithering:S.dithering,shadowMapEnabled:l.shadowMap.enabled&&T.length>0,shadowMapType:l.shadowMap.type,toneMapping:ae,decodeVideoTexture:Be&&S.map.isVideoTexture===!0&&Kt.getTransfer(S.map.colorSpace)===Si,decodeVideoTextureEmissive:ts&&S.emissiveMap.isVideoTexture===!0&&Kt.getTransfer(S.emissiveMap.colorSpace)===Si,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===$s,flipSided:S.side===Ji,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:_e&&S.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(_e&&S.extensions.multiDraw===!0||je)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return Xe.vertexUv1s=o.has(1),Xe.vertexUv2s=o.has(2),Xe.vertexUv3s=o.has(3),o.clear(),Xe}function v(S){const A=[];if(S.shaderID?A.push(S.shaderID):(A.push(S.customVertexShaderID),A.push(S.customFragmentShaderID)),S.defines!==void 0)for(const T in S.defines)A.push(T),A.push(S.defines[T]);return S.isRawShaderMaterial===!1&&(g(A,S),b(A,S),A.push(l.outputColorSpace)),A.push(S.customProgramCacheKey),A.join()}function g(S,A){S.push(A.precision),S.push(A.outputColorSpace),S.push(A.envMapMode),S.push(A.envMapCubeUVHeight),S.push(A.mapUv),S.push(A.alphaMapUv),S.push(A.lightMapUv),S.push(A.aoMapUv),S.push(A.bumpMapUv),S.push(A.normalMapUv),S.push(A.displacementMapUv),S.push(A.emissiveMapUv),S.push(A.metalnessMapUv),S.push(A.roughnessMapUv),S.push(A.anisotropyMapUv),S.push(A.clearcoatMapUv),S.push(A.clearcoatNormalMapUv),S.push(A.clearcoatRoughnessMapUv),S.push(A.iridescenceMapUv),S.push(A.iridescenceThicknessMapUv),S.push(A.sheenColorMapUv),S.push(A.sheenRoughnessMapUv),S.push(A.specularMapUv),S.push(A.specularColorMapUv),S.push(A.specularIntensityMapUv),S.push(A.transmissionMapUv),S.push(A.thicknessMapUv),S.push(A.combine),S.push(A.fogExp2),S.push(A.sizeAttenuation),S.push(A.morphTargetsCount),S.push(A.morphAttributeCount),S.push(A.numDirLights),S.push(A.numPointLights),S.push(A.numSpotLights),S.push(A.numSpotLightMaps),S.push(A.numHemiLights),S.push(A.numRectAreaLights),S.push(A.numDirLightShadows),S.push(A.numPointLightShadows),S.push(A.numSpotLightShadows),S.push(A.numSpotLightShadowsWithMaps),S.push(A.numLightProbes),S.push(A.shadowMapType),S.push(A.toneMapping),S.push(A.numClippingPlanes),S.push(A.numClipIntersection),S.push(A.depthPacking)}function b(S,A){r.disableAll(),A.instancing&&r.enable(0),A.instancingColor&&r.enable(1),A.instancingMorph&&r.enable(2),A.matcap&&r.enable(3),A.envMap&&r.enable(4),A.normalMapObjectSpace&&r.enable(5),A.normalMapTangentSpace&&r.enable(6),A.clearcoat&&r.enable(7),A.iridescence&&r.enable(8),A.alphaTest&&r.enable(9),A.vertexColors&&r.enable(10),A.vertexAlphas&&r.enable(11),A.vertexUv1s&&r.enable(12),A.vertexUv2s&&r.enable(13),A.vertexUv3s&&r.enable(14),A.vertexTangents&&r.enable(15),A.anisotropy&&r.enable(16),A.alphaHash&&r.enable(17),A.batching&&r.enable(18),A.dispersion&&r.enable(19),A.batchingColor&&r.enable(20),A.gradientMap&&r.enable(21),A.packedNormalMap&&r.enable(22),A.vertexNormals&&r.enable(23),S.push(r.mask),r.disableAll(),A.fog&&r.enable(0),A.useFog&&r.enable(1),A.flatShading&&r.enable(2),A.logarithmicDepthBuffer&&r.enable(3),A.reversedDepthBuffer&&r.enable(4),A.skinning&&r.enable(5),A.morphTargets&&r.enable(6),A.morphNormals&&r.enable(7),A.morphColors&&r.enable(8),A.premultipliedAlpha&&r.enable(9),A.shadowMapEnabled&&r.enable(10),A.doubleSided&&r.enable(11),A.flipSided&&r.enable(12),A.useDepthPacking&&r.enable(13),A.dithering&&r.enable(14),A.transmission&&r.enable(15),A.sheen&&r.enable(16),A.opaque&&r.enable(17),A.pointsUvs&&r.enable(18),A.decodeVideoTexture&&r.enable(19),A.decodeVideoTextureEmissive&&r.enable(20),A.alphaToCoverage&&r.enable(21),A.numLightProbeGrids>0&&r.enable(22),A.hasPositionAttribute&&r.enable(23),S.push(r.mask)}function w(S){const A=p[S.type];let T;if(A){const _=Wa[A];T=rC.clone(_.uniforms)}else T=S.uniforms;return T}function y(S,A){let T=h.get(A);return T!==void 0?++T.usedTimes:(T=new aN(l,A,S,s),c.push(T),h.set(A,T)),T}function M(S){if(--S.usedTimes===0){const A=c.indexOf(S);c[A]=c[c.length-1],c.pop(),h.delete(S.cacheKey),S.destroy()}}function x(S){a.remove(S)}function E(){a.dispose()}return{getParameters:m,getProgramCacheKey:v,getUniforms:w,acquireProgram:y,releaseProgram:M,releaseShaderCache:x,programs:c,dispose:E}}function uN(){let l=new WeakMap;function e(r){return l.has(r)}function t(r){let a=l.get(r);return a===void 0&&(a={},l.set(r,a)),a}function i(r){l.delete(r)}function s(r,a,o){l.get(r)[a]=o}function n(){l=new WeakMap}return{has:e,get:t,remove:i,update:s,dispose:n}}function pN(l,e){return l.groupOrder!==e.groupOrder?l.groupOrder-e.groupOrder:l.renderOrder!==e.renderOrder?l.renderOrder-e.renderOrder:l.material.id!==e.material.id?l.material.id-e.material.id:l.materialVariant!==e.materialVariant?l.materialVariant-e.materialVariant:l.z!==e.z?l.z-e.z:l.id-e.id}function CE(l,e){return l.groupOrder!==e.groupOrder?l.groupOrder-e.groupOrder:l.renderOrder!==e.renderOrder?l.renderOrder-e.renderOrder:l.z!==e.z?e.z-l.z:l.id-e.id}function LE(){const l=[];let e=0;const t=[],i=[],s=[];function n(){e=0,t.length=0,i.length=0,s.length=0}function r(u){let p=0;return u.isInstancedMesh&&(p+=2),u.isSkinnedMesh&&(p+=1),p}function a(u,p,f,m,v,g){let b=l[e];return b===void 0?(b={id:u.id,object:u,geometry:p,material:f,materialVariant:r(u),groupOrder:m,renderOrder:u.renderOrder,z:v,group:g},l[e]=b):(b.id=u.id,b.object=u,b.geometry=p,b.material=f,b.materialVariant=r(u),b.groupOrder=m,b.renderOrder=u.renderOrder,b.z=v,b.group=g),e++,b}function o(u,p,f,m,v,g){const b=a(u,p,f,m,v,g);f.transmission>0?i.push(b):f.transparent===!0?s.push(b):t.push(b)}function c(u,p,f,m,v,g){const b=a(u,p,f,m,v,g);f.transmission>0?i.unshift(b):f.transparent===!0?s.unshift(b):t.unshift(b)}function h(u,p,f){t.length>1&&t.sort(u||pN),i.length>1&&i.sort(p||CE),s.length>1&&s.sort(p||CE),f&&(t.reverse(),i.reverse(),s.reverse())}function d(){for(let u=e,p=l.length;u<p;u++){const f=l[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:s,init:n,push:o,unshift:c,finish:d,sort:h}}function fN(){let l=new WeakMap;function e(i,s){const n=l.get(i);let r;return n===void 0?(r=new LE,l.set(i,[r])):s>=n.length?(r=new LE,n.push(r)):r=n[s],r}function t(){l=new WeakMap}return{get:e,dispose:t}}function mN(){const l={};return{get:function(e){if(l[e.id]!==void 0)return l[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new D,color:new oe};break;case"SpotLight":t={position:new D,direction:new D,color:new oe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new D,color:new oe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new D,skyColor:new oe,groundColor:new oe};break;case"RectAreaLight":t={color:new oe,position:new D,halfWidth:new D,halfHeight:new D};break}return l[e.id]=t,t}}}function gN(){const l={};return{get:function(e){if(l[e.id]!==void 0)return l[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie,shadowCameraNear:1,shadowCameraFar:1e3};break}return l[e.id]=t,t}}}let vN=0;function bN(l,e){return(e.castShadow?2:0)-(l.castShadow?2:0)+(e.map?1:0)-(l.map?1:0)}function yN(l){const e=new mN,t=gN(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new D);const s=new D,n=new qe,r=new qe;function a(c){let h=0,d=0,u=0;for(let A=0;A<9;A++)i.probe[A].set(0,0,0);let p=0,f=0,m=0,v=0,g=0,b=0,w=0,y=0,M=0,x=0,E=0;c.sort(bN);for(let A=0,T=c.length;A<T;A++){const _=c[A],k=_.color,L=_.intensity,P=_.distance;let C=null;if(_.shadow&&_.shadow.map&&(_.shadow.map.texture.format===rh?C=_.shadow.map.texture:C=_.shadow.map.depthTexture||_.shadow.map.texture),_.isAmbientLight)h+=k.r*L,d+=k.g*L,u+=k.b*L;else if(_.isLightProbe){for(let N=0;N<9;N++)i.probe[N].addScaledVector(_.sh.coefficients[N],L);E++}else if(_.isDirectionalLight){const N=e.get(_);if(N.color.copy(_.color).multiplyScalar(_.intensity),_.castShadow){const F=_.shadow,H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,i.directionalShadow[p]=H,i.directionalShadowMap[p]=C,i.directionalShadowMatrix[p]=_.shadow.matrix,b++}i.directional[p]=N,p++}else if(_.isSpotLight){const N=e.get(_);N.position.setFromMatrixPosition(_.matrixWorld),N.color.copy(k).multiplyScalar(L),N.distance=P,N.coneCos=Math.cos(_.angle),N.penumbraCos=Math.cos(_.angle*(1-_.penumbra)),N.decay=_.decay,i.spot[m]=N;const F=_.shadow;if(_.map&&(i.spotLightMap[M]=_.map,M++,F.updateMatrices(_),_.castShadow&&x++),i.spotLightMatrix[m]=F.matrix,_.castShadow){const H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,i.spotShadow[m]=H,i.spotShadowMap[m]=C,y++}m++}else if(_.isRectAreaLight){const N=e.get(_);N.color.copy(k).multiplyScalar(L),N.halfWidth.set(_.width*.5,0,0),N.halfHeight.set(0,_.height*.5,0),i.rectArea[v]=N,v++}else if(_.isPointLight){const N=e.get(_);if(N.color.copy(_.color).multiplyScalar(_.intensity),N.distance=_.distance,N.decay=_.decay,_.castShadow){const F=_.shadow,H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,H.shadowCameraNear=F.camera.near,H.shadowCameraFar=F.camera.far,i.pointShadow[f]=H,i.pointShadowMap[f]=C,i.pointShadowMatrix[f]=_.shadow.matrix,w++}i.point[f]=N,f++}else if(_.isHemisphereLight){const N=e.get(_);N.skyColor.copy(_.color).multiplyScalar(L),N.groundColor.copy(_.groundColor).multiplyScalar(L),i.hemi[g]=N,g++}}v>0&&(l.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Ae.LTC_FLOAT_1,i.rectAreaLTC2=Ae.LTC_FLOAT_2):(i.rectAreaLTC1=Ae.LTC_HALF_1,i.rectAreaLTC2=Ae.LTC_HALF_2)),i.ambient[0]=h,i.ambient[1]=d,i.ambient[2]=u;const S=i.hash;(S.directionalLength!==p||S.pointLength!==f||S.spotLength!==m||S.rectAreaLength!==v||S.hemiLength!==g||S.numDirectionalShadows!==b||S.numPointShadows!==w||S.numSpotShadows!==y||S.numSpotMaps!==M||S.numLightProbes!==E)&&(i.directional.length=p,i.spot.length=m,i.rectArea.length=v,i.point.length=f,i.hemi.length=g,i.directionalShadow.length=b,i.directionalShadowMap.length=b,i.pointShadow.length=w,i.pointShadowMap.length=w,i.spotShadow.length=y,i.spotShadowMap.length=y,i.directionalShadowMatrix.length=b,i.pointShadowMatrix.length=w,i.spotLightMatrix.length=y+M-x,i.spotLightMap.length=M,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=E,S.directionalLength=p,S.pointLength=f,S.spotLength=m,S.rectAreaLength=v,S.hemiLength=g,S.numDirectionalShadows=b,S.numPointShadows=w,S.numSpotShadows=y,S.numSpotMaps=M,S.numLightProbes=E,i.version=vN++)}function o(c,h){let d=0,u=0,p=0,f=0,m=0;const v=h.matrixWorldInverse;for(let g=0,b=c.length;g<b;g++){const w=c[g];if(w.isDirectionalLight){const y=i.directional[d];y.direction.setFromMatrixPosition(w.matrixWorld),s.setFromMatrixPosition(w.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(v),d++}else if(w.isSpotLight){const y=i.spot[p];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),y.direction.setFromMatrixPosition(w.matrixWorld),s.setFromMatrixPosition(w.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(v),p++}else if(w.isRectAreaLight){const y=i.rectArea[f];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),r.identity(),n.copy(w.matrixWorld),n.premultiply(v),r.extractRotation(n),y.halfWidth.set(w.width*.5,0,0),y.halfHeight.set(0,w.height*.5,0),y.halfWidth.applyMatrix4(r),y.halfHeight.applyMatrix4(r),f++}else if(w.isPointLight){const y=i.point[u];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),u++}else if(w.isHemisphereLight){const y=i.hemi[m];y.direction.setFromMatrixPosition(w.matrixWorld),y.direction.transformDirection(v),m++}}}return{setup:a,setupView:o,state:i}}function OE(l){const e=new yN(l),t=[],i=[],s=[];function n(u){d.camera=u,t.length=0,i.length=0,s.length=0}function r(u){t.push(u)}function a(u){i.push(u)}function o(u){s.push(u)}function c(){e.setup(t)}function h(u){e.setupView(t,u)}const d={lightsArray:t,shadowsArray:i,lightProbeGridArray:s,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:n,state:d,setupLights:c,setupLightsView:h,pushLight:r,pushShadow:a,pushLightProbeGrid:o}}function wN(l){let e=new WeakMap;function t(s,n=0){const r=e.get(s);let a;return r===void 0?(a=new OE(l),e.set(s,[a])):n>=r.length?(a=new OE(l),r.push(a)):a=r[n],a}function i(){e=new WeakMap}return{get:t,dispose:i}}const MN=`void main() {
|
|
8879
|
+
`+J)}else C!==""?We("WebGLProgram: Program Info Log:",C):(N===""||F==="")&&(j=!1);j&&(_.diagnostics={runnable:H,programLog:C,vertexShader:{log:N,prefix:v},fragmentShader:{log:F,prefix:g}})}s.deleteShader(M),s.deleteShader(x),S=new u0(s,m),A=$6(s,m)}let S;this.getUniforms=function(){return S===void 0&&E(this),S};let A;this.getAttributes=function(){return A===void 0&&E(this),A};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=s.getProgramParameter(m,P6)),T},this.destroy=function(){i.releaseStatesOfProgram(this),s.deleteProgram(m),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=N6++,this.cacheKey=e,this.usedTimes=1,this.program=m,this.vertexShader=M,this.fragmentShader=x,this}let oN=0;class lN{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const s=this._getShaderCacheForMaterial(e);return s.has(t)===!1&&(s.add(t),t.usedTimes++),s.has(i)===!1&&(s.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new cN(e),t.set(e,i)),i}}class cN{constructor(e){this.id=oN++,this.code=e,this.usedTimes=0}}function hN(l){return l===rh||l===B0||l===z0}function dN(l,e,t,i,s,n){const r=new Ow,a=new lN,o=new Set,c=[],h=new Map,d=i.logarithmicDepthBuffer;let u=i.precision;const p={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function f(S){return o.add(S),S===0?"uv":`uv${S}`}function m(S,A,T,_,k,L){const P=_.fog,C=k.geometry,N=S.isMeshStandardMaterial||S.isMeshLambertMaterial||S.isMeshPhongMaterial?_.environment:null,F=S.isMeshStandardMaterial||S.isMeshLambertMaterial&&!S.envMap||S.isMeshPhongMaterial&&!S.envMap,H=e.get(S.envMap||N,F),j=H&&H.mapping===Bg?H.image.height:null,W=p[S.type];S.precision!==null&&(u=i.getMaxPrecision(S.precision),u!==S.precision&&We("WebGLProgram.getParameters:",S.precision,"not supported, using",u,"instead."));const J=C.morphAttributes.position||C.morphAttributes.normal||C.morphAttributes.color,re=J!==void 0?J.length:0;let Le=0;C.morphAttributes.position!==void 0&&(Le=1),C.morphAttributes.normal!==void 0&&(Le=2),C.morphAttributes.color!==void 0&&(Le=3);let He,De,Z,ce;if(W){const ze=Wa[W];He=ze.vertexShader,De=ze.fragmentShader}else{He=S.vertexShader,De=S.fragmentShader;const ze=a.getVertexShaderStage(S),ps=a.getFragmentShaderStage(S);a.update(S,ze,ps),Z=ze.id,ce=ps.id}const le=l.getRenderTarget(),$=l.state.buffers.depth.getReversed(),Ue=k.isInstancedMesh===!0,je=k.isBatchedMesh===!0,Be=!!S.map,Oe=!!S.matcap,nt=!!H,lt=!!S.aoMap,ct=!!S.lightMap,fi=!!S.bumpMap&&S.wireframe===!1,mi=!!S.normalMap,ds=!!S.displacementMap,ts=!!S.emissiveMap,us=!!S.metalnessMap,Cs=!!S.roughnessMap,z=S.anisotropy>0,ar=S.clearcoat>0,gi=S.dispersion>0,O=S.iridescence>0,I=S.sheen>0,V=S.transmission>0,Y=z&&!!S.anisotropyMap,ee=ar&&!!S.clearcoatMap,de=ar&&!!S.clearcoatNormalMap,me=ar&&!!S.clearcoatRoughnessMap,te=O&&!!S.iridescenceMap,ne=O&&!!S.iridescenceThicknessMap,ve=I&&!!S.sheenColorMap,Ze=I&&!!S.sheenRoughnessMap,Ee=!!S.specularMap,be=!!S.specularColorMap,it=!!S.specularIntensityMap,dt=V&&!!S.transmissionMap,Dt=V&&!!S.thicknessMap,B=!!S.gradientMap,fe=!!S.alphaMap,se=S.alphaTest>0,ye=!!S.alphaHash,_e=!!S.extensions;let ae=oo;S.toneMapped&&(le===null||le.isXRRenderTarget===!0)&&(ae=l.toneMapping);const Xe={shaderID:W,shaderType:S.type,shaderName:S.name,vertexShader:He,fragmentShader:De,defines:S.defines,customVertexShaderID:Z,customFragmentShaderID:ce,isRawShaderMaterial:S.isRawShaderMaterial===!0,glslVersion:S.glslVersion,precision:u,batching:je,batchingColor:je&&k._colorsTexture!==null,instancing:Ue,instancingColor:Ue&&k.instanceColor!==null,instancingMorph:Ue&&k.morphTexture!==null,outputColorSpace:le===null?l.outputColorSpace:le.isXRRenderTarget===!0?le.texture.colorSpace:Kt.workingColorSpace,alphaToCoverage:!!S.alphaToCoverage,map:Be,matcap:Oe,envMap:nt,envMapMode:nt&&H.mapping,envMapCubeUVHeight:j,aoMap:lt,lightMap:ct,bumpMap:fi,normalMap:mi,displacementMap:ds,emissiveMap:ts,normalMapObjectSpace:mi&&S.normalMapType===SR,normalMapTangentSpace:mi&&S.normalMapType===V0,packedNormalMap:mi&&S.normalMapType===V0&&hN(S.normalMap.format),metalnessMap:us,roughnessMap:Cs,anisotropy:z,anisotropyMap:Y,clearcoat:ar,clearcoatMap:ee,clearcoatNormalMap:de,clearcoatRoughnessMap:me,dispersion:gi,iridescence:O,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:I,sheenColorMap:ve,sheenRoughnessMap:Ze,specularMap:Ee,specularColorMap:be,specularIntensityMap:it,transmission:V,transmissionMap:dt,thicknessMap:Dt,gradientMap:B,opaque:S.transparent===!1&&S.blending===Zl&&S.alphaToCoverage===!1,alphaMap:fe,alphaTest:se,alphaHash:ye,combine:S.combine,mapUv:Be&&f(S.map.channel),aoMapUv:lt&&f(S.aoMap.channel),lightMapUv:ct&&f(S.lightMap.channel),bumpMapUv:fi&&f(S.bumpMap.channel),normalMapUv:mi&&f(S.normalMap.channel),displacementMapUv:ds&&f(S.displacementMap.channel),emissiveMapUv:ts&&f(S.emissiveMap.channel),metalnessMapUv:us&&f(S.metalnessMap.channel),roughnessMapUv:Cs&&f(S.roughnessMap.channel),anisotropyMapUv:Y&&f(S.anisotropyMap.channel),clearcoatMapUv:ee&&f(S.clearcoatMap.channel),clearcoatNormalMapUv:de&&f(S.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:me&&f(S.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&f(S.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&f(S.iridescenceThicknessMap.channel),sheenColorMapUv:ve&&f(S.sheenColorMap.channel),sheenRoughnessMapUv:Ze&&f(S.sheenRoughnessMap.channel),specularMapUv:Ee&&f(S.specularMap.channel),specularColorMapUv:be&&f(S.specularColorMap.channel),specularIntensityMapUv:it&&f(S.specularIntensityMap.channel),transmissionMapUv:dt&&f(S.transmissionMap.channel),thicknessMapUv:Dt&&f(S.thicknessMap.channel),alphaMapUv:fe&&f(S.alphaMap.channel),vertexTangents:!!C.attributes.tangent&&(mi||z),vertexNormals:!!C.attributes.normal,vertexColors:S.vertexColors,vertexAlphas:S.vertexColors===!0&&!!C.attributes.color&&C.attributes.color.itemSize===4,pointsUvs:k.isPoints===!0&&!!C.attributes.uv&&(Be||fe),fog:!!P,useFog:S.fog===!0,fogExp2:!!P&&P.isFogExp2,flatShading:S.wireframe===!1&&(S.flatShading===!0||C.attributes.normal===void 0&&mi===!1&&(S.isMeshLambertMaterial||S.isMeshPhongMaterial||S.isMeshStandardMaterial||S.isMeshPhysicalMaterial)),sizeAttenuation:S.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:$,skinning:k.isSkinnedMesh===!0,hasPositionAttribute:C.attributes.position!==void 0,morphTargets:C.morphAttributes.position!==void 0,morphNormals:C.morphAttributes.normal!==void 0,morphColors:C.morphAttributes.color!==void 0,morphTargetsCount:re,morphTextureStride:Le,numDirLights:A.directional.length,numPointLights:A.point.length,numSpotLights:A.spot.length,numSpotLightMaps:A.spotLightMap.length,numRectAreaLights:A.rectArea.length,numHemiLights:A.hemi.length,numDirLightShadows:A.directionalShadowMap.length,numPointLightShadows:A.pointShadowMap.length,numSpotLightShadows:A.spotShadowMap.length,numSpotLightShadowsWithMaps:A.numSpotLightShadowsWithMaps,numLightProbes:A.numLightProbes,numLightProbeGrids:L.length,numClippingPlanes:n.numPlanes,numClipIntersection:n.numIntersection,dithering:S.dithering,shadowMapEnabled:l.shadowMap.enabled&&T.length>0,shadowMapType:l.shadowMap.type,toneMapping:ae,decodeVideoTexture:Be&&S.map.isVideoTexture===!0&&Kt.getTransfer(S.map.colorSpace)===Si,decodeVideoTextureEmissive:ts&&S.emissiveMap.isVideoTexture===!0&&Kt.getTransfer(S.emissiveMap.colorSpace)===Si,premultipliedAlpha:S.premultipliedAlpha,doubleSided:S.side===$s,flipSided:S.side===Ji,useDepthPacking:S.depthPacking>=0,depthPacking:S.depthPacking||0,index0AttributeName:S.index0AttributeName,extensionClipCullDistance:_e&&S.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(_e&&S.extensions.multiDraw===!0||je)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:S.customProgramCacheKey()};return Xe.vertexUv1s=o.has(1),Xe.vertexUv2s=o.has(2),Xe.vertexUv3s=o.has(3),o.clear(),Xe}function v(S){const A=[];if(S.shaderID?A.push(S.shaderID):(A.push(S.customVertexShaderID),A.push(S.customFragmentShaderID)),S.defines!==void 0)for(const T in S.defines)A.push(T),A.push(S.defines[T]);return S.isRawShaderMaterial===!1&&(g(A,S),b(A,S),A.push(l.outputColorSpace)),A.push(S.customProgramCacheKey),A.join()}function g(S,A){S.push(A.precision),S.push(A.outputColorSpace),S.push(A.envMapMode),S.push(A.envMapCubeUVHeight),S.push(A.mapUv),S.push(A.alphaMapUv),S.push(A.lightMapUv),S.push(A.aoMapUv),S.push(A.bumpMapUv),S.push(A.normalMapUv),S.push(A.displacementMapUv),S.push(A.emissiveMapUv),S.push(A.metalnessMapUv),S.push(A.roughnessMapUv),S.push(A.anisotropyMapUv),S.push(A.clearcoatMapUv),S.push(A.clearcoatNormalMapUv),S.push(A.clearcoatRoughnessMapUv),S.push(A.iridescenceMapUv),S.push(A.iridescenceThicknessMapUv),S.push(A.sheenColorMapUv),S.push(A.sheenRoughnessMapUv),S.push(A.specularMapUv),S.push(A.specularColorMapUv),S.push(A.specularIntensityMapUv),S.push(A.transmissionMapUv),S.push(A.thicknessMapUv),S.push(A.combine),S.push(A.fogExp2),S.push(A.sizeAttenuation),S.push(A.morphTargetsCount),S.push(A.morphAttributeCount),S.push(A.numDirLights),S.push(A.numPointLights),S.push(A.numSpotLights),S.push(A.numSpotLightMaps),S.push(A.numHemiLights),S.push(A.numRectAreaLights),S.push(A.numDirLightShadows),S.push(A.numPointLightShadows),S.push(A.numSpotLightShadows),S.push(A.numSpotLightShadowsWithMaps),S.push(A.numLightProbes),S.push(A.shadowMapType),S.push(A.toneMapping),S.push(A.numClippingPlanes),S.push(A.numClipIntersection),S.push(A.depthPacking)}function b(S,A){r.disableAll(),A.instancing&&r.enable(0),A.instancingColor&&r.enable(1),A.instancingMorph&&r.enable(2),A.matcap&&r.enable(3),A.envMap&&r.enable(4),A.normalMapObjectSpace&&r.enable(5),A.normalMapTangentSpace&&r.enable(6),A.clearcoat&&r.enable(7),A.iridescence&&r.enable(8),A.alphaTest&&r.enable(9),A.vertexColors&&r.enable(10),A.vertexAlphas&&r.enable(11),A.vertexUv1s&&r.enable(12),A.vertexUv2s&&r.enable(13),A.vertexUv3s&&r.enable(14),A.vertexTangents&&r.enable(15),A.anisotropy&&r.enable(16),A.alphaHash&&r.enable(17),A.batching&&r.enable(18),A.dispersion&&r.enable(19),A.batchingColor&&r.enable(20),A.gradientMap&&r.enable(21),A.packedNormalMap&&r.enable(22),A.vertexNormals&&r.enable(23),S.push(r.mask),r.disableAll(),A.fog&&r.enable(0),A.useFog&&r.enable(1),A.flatShading&&r.enable(2),A.logarithmicDepthBuffer&&r.enable(3),A.reversedDepthBuffer&&r.enable(4),A.skinning&&r.enable(5),A.morphTargets&&r.enable(6),A.morphNormals&&r.enable(7),A.morphColors&&r.enable(8),A.premultipliedAlpha&&r.enable(9),A.shadowMapEnabled&&r.enable(10),A.doubleSided&&r.enable(11),A.flipSided&&r.enable(12),A.useDepthPacking&&r.enable(13),A.dithering&&r.enable(14),A.transmission&&r.enable(15),A.sheen&&r.enable(16),A.opaque&&r.enable(17),A.pointsUvs&&r.enable(18),A.decodeVideoTexture&&r.enable(19),A.decodeVideoTextureEmissive&&r.enable(20),A.alphaToCoverage&&r.enable(21),A.numLightProbeGrids>0&&r.enable(22),A.hasPositionAttribute&&r.enable(23),S.push(r.mask)}function w(S){const A=p[S.type];let T;if(A){const _=Wa[A];T=rC.clone(_.uniforms)}else T=S.uniforms;return T}function y(S,A){let T=h.get(A);return T!==void 0?++T.usedTimes:(T=new aN(l,A,S,s),c.push(T),h.set(A,T)),T}function M(S){if(--S.usedTimes===0){const A=c.indexOf(S);c[A]=c[c.length-1],c.pop(),h.delete(S.cacheKey),S.destroy()}}function x(S){a.remove(S)}function E(){a.dispose()}return{getParameters:m,getProgramCacheKey:v,getUniforms:w,acquireProgram:y,releaseProgram:M,releaseShaderCache:x,programs:c,dispose:E}}function uN(){let l=new WeakMap;function e(r){return l.has(r)}function t(r){let a=l.get(r);return a===void 0&&(a={},l.set(r,a)),a}function i(r){l.delete(r)}function s(r,a,o){l.get(r)[a]=o}function n(){l=new WeakMap}return{has:e,get:t,remove:i,update:s,dispose:n}}function pN(l,e){return l.groupOrder!==e.groupOrder?l.groupOrder-e.groupOrder:l.renderOrder!==e.renderOrder?l.renderOrder-e.renderOrder:l.material.id!==e.material.id?l.material.id-e.material.id:l.materialVariant!==e.materialVariant?l.materialVariant-e.materialVariant:l.z!==e.z?l.z-e.z:l.id-e.id}function CE(l,e){return l.groupOrder!==e.groupOrder?l.groupOrder-e.groupOrder:l.renderOrder!==e.renderOrder?l.renderOrder-e.renderOrder:l.z!==e.z?e.z-l.z:l.id-e.id}function LE(){const l=[];let e=0;const t=[],i=[],s=[];function n(){e=0,t.length=0,i.length=0,s.length=0}function r(u){let p=0;return u.isInstancedMesh&&(p+=2),u.isSkinnedMesh&&(p+=1),p}function a(u,p,f,m,v,g){let b=l[e];return b===void 0?(b={id:u.id,object:u,geometry:p,material:f,materialVariant:r(u),groupOrder:m,renderOrder:u.renderOrder,z:v,group:g},l[e]=b):(b.id=u.id,b.object=u,b.geometry=p,b.material=f,b.materialVariant=r(u),b.groupOrder=m,b.renderOrder=u.renderOrder,b.z=v,b.group=g),e++,b}function o(u,p,f,m,v,g){const b=a(u,p,f,m,v,g);f.transmission>0?i.push(b):f.transparent===!0?s.push(b):t.push(b)}function c(u,p,f,m,v,g){const b=a(u,p,f,m,v,g);f.transmission>0?i.unshift(b):f.transparent===!0?s.unshift(b):t.unshift(b)}function h(u,p,f){t.length>1&&t.sort(u||pN),i.length>1&&i.sort(p||CE),s.length>1&&s.sort(p||CE),f&&(t.reverse(),i.reverse(),s.reverse())}function d(){for(let u=e,p=l.length;u<p;u++){const f=l[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:s,init:n,push:o,unshift:c,finish:d,sort:h}}function fN(){let l=new WeakMap;function e(i,s){const n=l.get(i);let r;return n===void 0?(r=new LE,l.set(i,[r])):s>=n.length?(r=new LE,n.push(r)):r=n[s],r}function t(){l=new WeakMap}return{get:e,dispose:t}}function mN(){const l={};return{get:function(e){if(l[e.id]!==void 0)return l[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new D,color:new oe};break;case"SpotLight":t={position:new D,direction:new D,color:new oe,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new D,color:new oe,distance:0,decay:0};break;case"HemisphereLight":t={direction:new D,skyColor:new oe,groundColor:new oe};break;case"RectAreaLight":t={color:new oe,position:new D,halfWidth:new D,halfHeight:new D};break}return l[e.id]=t,t}}}function gN(){const l={};return{get:function(e){if(l[e.id]!==void 0)return l[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ie,shadowCameraNear:1,shadowCameraFar:1e3};break}return l[e.id]=t,t}}}let vN=0;function bN(l,e){return(e.castShadow?2:0)-(l.castShadow?2:0)+(e.map?1:0)-(l.map?1:0)}function yN(l){const e=new mN,t=gN(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new D);const s=new D,n=new qe,r=new qe;function a(c){let h=0,d=0,u=0;for(let A=0;A<9;A++)i.probe[A].set(0,0,0);let p=0,f=0,m=0,v=0,g=0,b=0,w=0,y=0,M=0,x=0,E=0;c.sort(bN);for(let A=0,T=c.length;A<T;A++){const _=c[A],k=_.color,L=_.intensity,P=_.distance;let C=null;if(_.shadow&&_.shadow.map&&(_.shadow.map.texture.format===rh?C=_.shadow.map.texture:C=_.shadow.map.depthTexture||_.shadow.map.texture),_.isAmbientLight)h+=k.r*L,d+=k.g*L,u+=k.b*L;else if(_.isLightProbe){for(let N=0;N<9;N++)i.probe[N].addScaledVector(_.sh.coefficients[N],L);E++}else if(_.isDirectionalLight){const N=e.get(_);if(N.color.copy(_.color).multiplyScalar(_.intensity),_.castShadow){const F=_.shadow,H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,i.directionalShadow[p]=H,i.directionalShadowMap[p]=C,i.directionalShadowMatrix[p]=_.shadow.matrix,b++}i.directional[p]=N,p++}else if(_.isSpotLight){const N=e.get(_);N.position.setFromMatrixPosition(_.matrixWorld),N.color.copy(k).multiplyScalar(L),N.distance=P,N.coneCos=Math.cos(_.angle),N.penumbraCos=Math.cos(_.angle*(1-_.penumbra)),N.decay=_.decay,i.spot[m]=N;const F=_.shadow;if(_.map&&(i.spotLightMap[M]=_.map,M++,F.updateMatrices(_),_.castShadow&&x++),i.spotLightMatrix[m]=F.matrix,_.castShadow){const H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,i.spotShadow[m]=H,i.spotShadowMap[m]=C,y++}m++}else if(_.isRectAreaLight){const N=e.get(_);N.color.copy(k).multiplyScalar(L),N.halfWidth.set(_.width*.5,0,0),N.halfHeight.set(0,_.height*.5,0),i.rectArea[v]=N,v++}else if(_.isPointLight){const N=e.get(_);if(N.color.copy(_.color).multiplyScalar(_.intensity),N.distance=_.distance,N.decay=_.decay,_.castShadow){const F=_.shadow,H=t.get(_);H.shadowIntensity=F.intensity,H.shadowBias=F.bias,H.shadowNormalBias=F.normalBias,H.shadowRadius=F.radius,H.shadowMapSize=F.mapSize,H.shadowCameraNear=F.camera.near,H.shadowCameraFar=F.camera.far,i.pointShadow[f]=H,i.pointShadowMap[f]=C,i.pointShadowMatrix[f]=_.shadow.matrix,w++}i.point[f]=N,f++}else if(_.isHemisphereLight){const N=e.get(_);N.skyColor.copy(_.color).multiplyScalar(L),N.groundColor.copy(_.groundColor).multiplyScalar(L),i.hemi[g]=N,g++}}v>0&&(l.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Ae.LTC_FLOAT_1,i.rectAreaLTC2=Ae.LTC_FLOAT_2):(i.rectAreaLTC1=Ae.LTC_HALF_1,i.rectAreaLTC2=Ae.LTC_HALF_2)),i.ambient[0]=h,i.ambient[1]=d,i.ambient[2]=u;const S=i.hash;(S.directionalLength!==p||S.pointLength!==f||S.spotLength!==m||S.rectAreaLength!==v||S.hemiLength!==g||S.numDirectionalShadows!==b||S.numPointShadows!==w||S.numSpotShadows!==y||S.numSpotMaps!==M||S.numLightProbes!==E)&&(i.directional.length=p,i.spot.length=m,i.rectArea.length=v,i.point.length=f,i.hemi.length=g,i.directionalShadow.length=b,i.directionalShadowMap.length=b,i.pointShadow.length=w,i.pointShadowMap.length=w,i.spotShadow.length=y,i.spotShadowMap.length=y,i.directionalShadowMatrix.length=b,i.pointShadowMatrix.length=w,i.spotLightMatrix.length=y+M-x,i.spotLightMap.length=M,i.numSpotLightShadowsWithMaps=x,i.numLightProbes=E,S.directionalLength=p,S.pointLength=f,S.spotLength=m,S.rectAreaLength=v,S.hemiLength=g,S.numDirectionalShadows=b,S.numPointShadows=w,S.numSpotShadows=y,S.numSpotMaps=M,S.numLightProbes=E,i.version=vN++)}function o(c,h){let d=0,u=0,p=0,f=0,m=0;const v=h.matrixWorldInverse;for(let g=0,b=c.length;g<b;g++){const w=c[g];if(w.isDirectionalLight){const y=i.directional[d];y.direction.setFromMatrixPosition(w.matrixWorld),s.setFromMatrixPosition(w.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(v),d++}else if(w.isSpotLight){const y=i.spot[p];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),y.direction.setFromMatrixPosition(w.matrixWorld),s.setFromMatrixPosition(w.target.matrixWorld),y.direction.sub(s),y.direction.transformDirection(v),p++}else if(w.isRectAreaLight){const y=i.rectArea[f];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),r.identity(),n.copy(w.matrixWorld),n.premultiply(v),r.extractRotation(n),y.halfWidth.set(w.width*.5,0,0),y.halfHeight.set(0,w.height*.5,0),y.halfWidth.applyMatrix4(r),y.halfHeight.applyMatrix4(r),f++}else if(w.isPointLight){const y=i.point[u];y.position.setFromMatrixPosition(w.matrixWorld),y.position.applyMatrix4(v),u++}else if(w.isHemisphereLight){const y=i.hemi[m];y.direction.setFromMatrixPosition(w.matrixWorld),y.direction.transformDirection(v),m++}}}return{setup:a,setupView:o,state:i}}function OE(l){const e=new yN(l),t=[],i=[],s=[];function n(u){d.camera=u,t.length=0,i.length=0,s.length=0}function r(u){t.push(u)}function a(u){i.push(u)}function o(u){s.push(u)}function c(){e.setup(t)}function h(u){e.setupView(t,u)}const d={lightsArray:t,shadowsArray:i,lightProbeGridArray:s,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:n,state:d,setupLights:c,setupLightsView:h,pushLight:r,pushShadow:a,pushLightProbeGrid:o}}function wN(l){let e=new WeakMap;function t(s,n=0){const r=e.get(s);let a;return r===void 0?(a=new OE(l),e.set(s,[a])):n>=r.length?(a=new OE(l),r.push(a)):a=r[n],a}function i(){e=new WeakMap}return{get:t,dispose:i}}const MN=`void main() {
|
|
8880
8880
|
gl_Position = vec4( position, 1.0 );
|
|
8881
8881
|
}`,xN=`uniform sampler2D shadow_pass;
|
|
8882
8882
|
uniform vec2 resolution;
|
|
@@ -8903,7 +8903,7 @@ void main() {
|
|
|
8903
8903
|
squared_mean = squared_mean / samples;
|
|
8904
8904
|
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
|
8905
8905
|
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
|
8906
|
-
}`,SN=[new D(1,0,0),new D(-1,0,0),new D(0,1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1)],EN=[new D(0,-1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1),new D(0,-1,0),new D(0,-1,0)],PE=new qe,Du=new D,r1=new D;function AN(l,e,t){let i=new zg;const s=new ie,n=new ie,r=new Lt,a=new cC,o=new hC,c={},h=t.maxTextureSize,d={[ho]:Ji,[Ji]:ho,[$s]:$s},u=new Nt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ie},radius:{value:4}},vertexShader:MN,fragmentShader:xN}),p=u.clone();p.defines.HORIZONTAL_PASS=1;const f=new Tt;f.setAttribute("position",new Et(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Me(f,u),v=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=tp;let g=this.type;this.render=function(x,E,S){if(v.enabled===!1||v.autoUpdate===!1&&v.needsUpdate===!1||x.length===0)return;this.type===Qk&&(We("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=tp);const A=l.getRenderTarget(),T=l.getActiveCubeFace(),_=l.getActiveMipmapLevel(),k=l.state;k.setBlending(wr),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);const L=g!==this.type;L&&E.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(C=>C.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,C=x.length;P<C;P++){const N=x[P],F=N.shadow;if(F===void 0){We("WebGLShadowMap:",N,"has no shadow.");continue}if(F.autoUpdate===!1&&F.needsUpdate===!1)continue;s.copy(F.mapSize);const H=F.getFrameExtents();s.multiply(H),n.copy(F.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(n.x=Math.floor(h/H.x),s.x=n.x*H.x,F.mapSize.x=n.x),s.y>h&&(n.y=Math.floor(h/H.y),s.y=n.y*H.y,F.mapSize.y=n.y));const j=l.state.buffers.depth.getReversed();if(F.camera._reversedDepth=j,F.map===null||L===!0){if(F.map!==null&&(F.map.depthTexture!==null&&(F.map.depthTexture.dispose(),F.map.depthTexture=null),F.map.dispose()),this.type===ju){if(N.isPointLight){We("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}F.map=new oi(s.x,s.y,{format:rh,type:ti,minFilter:St,magFilter:St,generateMipmaps:!1}),F.map.texture.name=N.name+".shadowMap",F.map.depthTexture=new nc(s.x,s.y,yn),F.map.depthTexture.name=N.name+".shadowMapDepth",F.map.depthTexture.format=Zo,F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=pi,F.map.depthTexture.magFilter=pi}else N.isPointLight?(F.map=new pf(s.x),F.map.depthTexture=new A4(s.x,Qr)):(F.map=new oi(s.x,s.y),F.map.depthTexture=new nc(s.x,s.y,Qr)),F.map.depthTexture.name=N.name+".shadowMap",F.map.depthTexture.format=Zo,this.type===tp?(F.map.depthTexture.compareFunction=j?Rw:kw,F.map.depthTexture.minFilter=St,F.map.depthTexture.magFilter=St):(F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=pi,F.map.depthTexture.magFilter=pi);F.camera.updateProjectionMatrix()}const W=F.map.isWebGLCubeRenderTarget?6:1;for(let J=0;J<W;J++){if(F.map.isWebGLCubeRenderTarget)l.setRenderTarget(F.map,J),l.clear();else{J===0&&(l.setRenderTarget(F.map),l.clear());const re=F.getViewport(J);r.set(n.x*re.x,n.y*re.y,n.x*re.z,n.y*re.w),k.viewport(r)}if(N.isPointLight){const re=F.camera,Le=F.matrix,He=N.distance||re.far;He!==re.far&&(re.far=He,re.updateProjectionMatrix()),Du.setFromMatrixPosition(N.matrixWorld),re.position.copy(Du),r1.copy(re.position),r1.add(SN[J]),re.up.copy(EN[J]),re.lookAt(r1),re.updateMatrixWorld(),Le.makeTranslation(-Du.x,-Du.y,-Du.z),PE.multiplyMatrices(re.projectionMatrix,re.matrixWorldInverse),F._frustum.setFromProjectionMatrix(PE,re.coordinateSystem,re.reversedDepth)}else F.updateMatrices(N);i=F.getFrustum(),y(E,S,F.camera,N,this.type)}F.isPointLightShadow!==!0&&this.type===ju&&b(F,S),F.needsUpdate=!1}g=this.type,v.needsUpdate=!1,l.setRenderTarget(A,T,_)};function b(x,E){const S=e.update(m);u.defines.VSM_SAMPLES!==x.blurSamples&&(u.defines.VSM_SAMPLES=x.blurSamples,p.defines.VSM_SAMPLES=x.blurSamples,u.needsUpdate=!0,p.needsUpdate=!0),x.mapPass===null&&(x.mapPass=new oi(s.x,s.y,{format:rh,type:ti})),u.uniforms.shadow_pass.value=x.map.depthTexture,u.uniforms.resolution.value=x.mapSize,u.uniforms.radius.value=x.radius,l.setRenderTarget(x.mapPass),l.clear(),l.renderBufferDirect(E,null,S,u,m,null),p.uniforms.shadow_pass.value=x.mapPass.texture,p.uniforms.resolution.value=x.mapSize,p.uniforms.radius.value=x.radius,l.setRenderTarget(x.map),l.clear(),l.renderBufferDirect(E,null,S,p,m,null)}function w(x,E,S,A){let T=null;const _=S.isPointLight===!0?x.customDistanceMaterial:x.customDepthMaterial;if(_!==void 0)T=_;else if(T=S.isPointLight===!0?o:a,l.localClippingEnabled&&E.clipShadows===!0&&Array.isArray(E.clippingPlanes)&&E.clippingPlanes.length!==0||E.displacementMap&&E.displacementScale!==0||E.alphaMap&&E.alphaTest>0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const k=T.uuid,L=E.uuid;let P=c[k];P===void 0&&(P={},c[k]=P);let C=P[L];C===void 0&&(C=T.clone(),P[L]=C,E.addEventListener("dispose",M)),T=C}if(T.visible=E.visible,T.wireframe=E.wireframe,A===ju?T.side=E.shadowSide!==null?E.shadowSide:E.side:T.side=E.shadowSide!==null?E.shadowSide:d[E.side],T.alphaMap=E.alphaMap,T.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,T.map=E.map,T.clipShadows=E.clipShadows,T.clippingPlanes=E.clippingPlanes,T.clipIntersection=E.clipIntersection,T.displacementMap=E.displacementMap,T.displacementScale=E.displacementScale,T.displacementBias=E.displacementBias,T.wireframeLinewidth=E.wireframeLinewidth,T.linewidth=E.linewidth,S.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const k=l.properties.get(T);k.light=S}return T}function y(x,E,S,A,T){if(x.visible===!1)return;if(x.layers.test(E.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&T===ju)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,x.matrixWorld);const L=e.update(x),P=x.material;if(Array.isArray(P)){const C=L.groups;for(let N=0,F=C.length;N<F;N++){const H=C[N],j=P[H.materialIndex];if(j&&j.visible){const W=w(x,j,A,T);x.onBeforeShadow(l,x,E,S,L,W,H),l.renderBufferDirect(S,null,L,W,x,H),x.onAfterShadow(l,x,E,S,L,W,H)}}}else if(P.visible){const C=w(x,P,A,T);x.onBeforeShadow(l,x,E,S,L,C,null),l.renderBufferDirect(S,null,L,C,x,null),x.onAfterShadow(l,x,E,S,L,C,null)}}const k=x.children;for(let L=0,P=k.length;L<P;L++)y(k[L],E,S,A,T)}function M(x){x.target.removeEventListener("dispose",M);for(const S in c){const A=c[S],T=x.target.uuid;T in A&&(A[T].dispose(),delete A[T])}}}function TN(l,e){function t(){let B=!1;const fe=new Lt;let se=null;const ye=new Lt(0,0,0,0);return{setMask:function(_e){se!==_e&&!B&&(l.colorMask(_e,_e,_e,_e),se=_e)},setLocked:function(_e){B=_e},setClear:function(_e,ae,Xe,ze,ps){ps===!0&&(_e*=ze,ae*=ze,Xe*=ze),fe.set(_e,ae,Xe,ze),ye.equals(fe)===!1&&(l.clearColor(_e,ae,Xe,ze),ye.copy(fe))},reset:function(){B=!1,se=null,ye.set(-1,0,0,0)}}}function i(){let B=!1,fe=!1,se=null,ye=null,_e=null;return{setReversed:function(ae){if(fe!==ae){const Xe=e.get("EXT_clip_control");ae?Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.ZERO_TO_ONE_EXT):Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.NEGATIVE_ONE_TO_ONE_EXT),fe=ae;const ze=_e;_e=null,this.setClear(ze)}},getReversed:function(){return fe},setTest:function(ae){ae?le(l.DEPTH_TEST):$(l.DEPTH_TEST)},setMask:function(ae){se!==ae&&!B&&(l.depthMask(ae),se=ae)},setFunc:function(ae){if(fe&&(ae=OR[ae]),ye!==ae){switch(ae){case _b:l.depthFunc(l.NEVER);break;case Db:l.depthFunc(l.ALWAYS);break;case kb:l.depthFunc(l.LESS);break;case eu:l.depthFunc(l.LEQUAL);break;case Rb:l.depthFunc(l.EQUAL);break;case Cb:l.depthFunc(l.GEQUAL);break;case Lb:l.depthFunc(l.GREATER);break;case Ob:l.depthFunc(l.NOTEQUAL);break;default:l.depthFunc(l.LEQUAL)}ye=ae}},setLocked:function(ae){B=ae},setClear:function(ae){_e!==ae&&(_e=ae,fe&&(ae=1-ae),l.clearDepth(ae))},reset:function(){B=!1,se=null,ye=null,_e=null,fe=!1}}}function s(){let B=!1,fe=null,se=null,ye=null,_e=null,ae=null,Xe=null,ze=null,ps=null;return{setTest:function(Pi){B||(Pi?le(l.STENCIL_TEST):$(l.STENCIL_TEST))},setMask:function(Pi){fe!==Pi&&!B&&(l.stencilMask(Pi),fe=Pi)},setFunc:function(Pi,Aa,Ta){(se!==Pi||ye!==Aa||_e!==Ta)&&(l.stencilFunc(Pi,Aa,Ta),se=Pi,ye=Aa,_e=Ta)},setOp:function(Pi,Aa,Ta){(ae!==Pi||Xe!==Aa||ze!==Ta)&&(l.stencilOp(Pi,Aa,Ta),ae=Pi,Xe=Aa,ze=Ta)},setLocked:function(Pi){B=Pi},setClear:function(Pi){ps!==Pi&&(l.clearStencil(Pi),ps=Pi)},reset:function(){B=!1,fe=null,se=null,ye=null,_e=null,ae=null,Xe=null,ze=null,ps=null}}}const n=new t,r=new i,a=new s,o=new WeakMap,c=new WeakMap;let h={},d={},u={},p=new WeakMap,f=[],m=null,v=!1,g=null,b=null,w=null,y=null,M=null,x=null,E=null,S=new oe(0,0,0),A=0,T=!1,_=null,k=null,L=null,P=null,C=null;const N=l.getParameter(l.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let F=!1,H=0;const j=l.getParameter(l.VERSION);j.indexOf("WebGL")!==-1?(H=parseFloat(/^WebGL (\d)/.exec(j)[1]),F=H>=1):j.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(j)[1]),F=H>=2);let W=null,J={};const re=l.getParameter(l.SCISSOR_BOX),Le=l.getParameter(l.VIEWPORT),He=new Lt().fromArray(re),De=new Lt().fromArray(Le);function Z(B,fe,se,ye){const _e=new Uint8Array(4),ae=l.createTexture();l.bindTexture(B,ae),l.texParameteri(B,l.TEXTURE_MIN_FILTER,l.NEAREST),l.texParameteri(B,l.TEXTURE_MAG_FILTER,l.NEAREST);for(let Xe=0;Xe<se;Xe++)B===l.TEXTURE_3D||B===l.TEXTURE_2D_ARRAY?l.texImage3D(fe,0,l.RGBA,1,1,ye,0,l.RGBA,l.UNSIGNED_BYTE,_e):l.texImage2D(fe+Xe,0,l.RGBA,1,1,0,l.RGBA,l.UNSIGNED_BYTE,_e);return ae}const ce={};ce[l.TEXTURE_2D]=Z(l.TEXTURE_2D,l.TEXTURE_2D,1),ce[l.TEXTURE_CUBE_MAP]=Z(l.TEXTURE_CUBE_MAP,l.TEXTURE_CUBE_MAP_POSITIVE_X,6),ce[l.TEXTURE_2D_ARRAY]=Z(l.TEXTURE_2D_ARRAY,l.TEXTURE_2D_ARRAY,1,1),ce[l.TEXTURE_3D]=Z(l.TEXTURE_3D,l.TEXTURE_3D,1,1),n.setClear(0,0,0,1),r.setClear(1),a.setClear(0),le(l.DEPTH_TEST),r.setFunc(eu),fi(!1),mi(cS),le(l.CULL_FACE),lt(wr);function le(B){h[B]!==!0&&(l.enable(B),h[B]=!0)}function $(B){h[B]!==!1&&(l.disable(B),h[B]=!1)}function Ue(B,fe){return u[B]!==fe?(l.bindFramebuffer(B,fe),u[B]=fe,B===l.DRAW_FRAMEBUFFER&&(u[l.FRAMEBUFFER]=fe),B===l.FRAMEBUFFER&&(u[l.DRAW_FRAMEBUFFER]=fe),!0):!1}function je(B,fe){let se=f,ye=!1;if(B){se=p.get(fe),se===void 0&&(se=[],p.set(fe,se));const _e=B.textures;if(se.length!==_e.length||se[0]!==l.COLOR_ATTACHMENT0){for(let ae=0,Xe=_e.length;ae<Xe;ae++)se[ae]=l.COLOR_ATTACHMENT0+ae;se.length=_e.length,ye=!0}}else se[0]!==l.BACK&&(se[0]=l.BACK,ye=!0);ye&&l.drawBuffers(se)}function Be(B){return m!==B?(l.useProgram(B),m=B,!0):!1}const Oe={[Lo]:l.FUNC_ADD,[eR]:l.FUNC_SUBTRACT,[tR]:l.FUNC_REVERSE_SUBTRACT};Oe[iR]=l.MIN,Oe[sR]=l.MAX;const nt={[io]:l.ZERO,[sh]:l.ONE,[nR]:l.SRC_COLOR,[U0]:l.SRC_ALPHA,[hR]:l.SRC_ALPHA_SATURATE,[lR]:l.DST_COLOR,[aR]:l.DST_ALPHA,[rR]:l.ONE_MINUS_SRC_COLOR,[rf]:l.ONE_MINUS_SRC_ALPHA,[cR]:l.ONE_MINUS_DST_COLOR,[oR]:l.ONE_MINUS_DST_ALPHA,[dR]:l.CONSTANT_COLOR,[uR]:l.ONE_MINUS_CONSTANT_COLOR,[pR]:l.CONSTANT_ALPHA,[fR]:l.ONE_MINUS_CONSTANT_ALPHA};function lt(B,fe,se,ye,_e,ae,Xe,ze,ps,Pi){if(B===wr){v===!0&&($(l.BLEND),v=!1);return}if(v===!1&&(le(l.BLEND),v=!0),B!==ih){if(B!==g||Pi!==T){if((b!==Lo||M!==Lo)&&(l.blendEquation(l.FUNC_ADD),b=Lo,M=Lo),Pi)switch(B){case Zl:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case qs:l.blendFunc(l.ONE,l.ONE);break;case hS:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case dS:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:ft("WebGLState: Invalid blending: ",B);break}else switch(B){case Zl:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case qs:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case hS:ft("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case dS:ft("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ft("WebGLState: Invalid blending: ",B);break}w=null,y=null,x=null,E=null,S.set(0,0,0),A=0,g=B,T=Pi}return}_e=_e||fe,ae=ae||se,Xe=Xe||ye,(fe!==b||_e!==M)&&(l.blendEquationSeparate(Oe[fe],Oe[_e]),b=fe,M=_e),(se!==w||ye!==y||ae!==x||Xe!==E)&&(l.blendFuncSeparate(nt[se],nt[ye],nt[ae],nt[Xe]),w=se,y=ye,x=ae,E=Xe),(ze.equals(S)===!1||ps!==A)&&(l.blendColor(ze.r,ze.g,ze.b,ps),S.copy(ze),A=ps),g=B,T=!1}function ct(B,fe){B.side===$s?$(l.CULL_FACE):le(l.CULL_FACE);let se=B.side===Ji;fe&&(se=!se),fi(se),B.blending===Zl&&B.transparent===!1?lt(wr):lt(B.blending,B.blendEquation,B.blendSrc,B.blendDst,B.blendEquationAlpha,B.blendSrcAlpha,B.blendDstAlpha,B.blendColor,B.blendAlpha,B.premultipliedAlpha),r.setFunc(B.depthFunc),r.setTest(B.depthTest),r.setMask(B.depthWrite),n.setMask(B.colorWrite);const ye=B.stencilWrite;a.setTest(ye),ye&&(a.setMask(B.stencilWriteMask),a.setFunc(B.stencilFunc,B.stencilRef,B.stencilFuncMask),a.setOp(B.stencilFail,B.stencilZFail,B.stencilZPass)),ts(B.polygonOffset,B.polygonOffsetFactor,B.polygonOffsetUnits),B.alphaToCoverage===!0?le(l.SAMPLE_ALPHA_TO_COVERAGE):$(l.SAMPLE_ALPHA_TO_COVERAGE)}function fi(B){_!==B&&(B?l.frontFace(l.CW):l.frontFace(l.CCW),_=B)}function mi(B){B!==Zk?(le(l.CULL_FACE),B!==k&&(B===cS?l.cullFace(l.BACK):B===Jk?l.cullFace(l.FRONT):l.cullFace(l.FRONT_AND_BACK))):$(l.CULL_FACE),k=B}function ds(B){B!==L&&(F&&l.lineWidth(B),L=B)}function ts(B,fe,se){B?(le(l.POLYGON_OFFSET_FILL),(P!==fe||C!==se)&&(P=fe,C=se,r.getReversed()&&(fe=-fe),l.polygonOffset(fe,se))):$(l.POLYGON_OFFSET_FILL)}function us(B){B?le(l.SCISSOR_TEST):$(l.SCISSOR_TEST)}function Cs(B){B===void 0&&(B=l.TEXTURE0+N-1),W!==B&&(l.activeTexture(B),W=B)}function z(B,fe,se){se===void 0&&(W===null?se=l.TEXTURE0+N-1:se=W);let ye=J[se];ye===void 0&&(ye={type:void 0,texture:void 0},J[se]=ye),(ye.type!==B||ye.texture!==fe)&&(W!==se&&(l.activeTexture(se),W=se),l.bindTexture(B,fe||ce[B]),ye.type=B,ye.texture=fe)}function ar(){const B=J[W];B!==void 0&&B.type!==void 0&&(l.bindTexture(B.type,null),B.type=void 0,B.texture=void 0)}function gi(){try{l.compressedTexImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function O(){try{l.compressedTexImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function I(){try{l.texSubImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function V(){try{l.texSubImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function Y(){try{l.compressedTexSubImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function ee(){try{l.compressedTexSubImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function de(){try{l.texStorage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function me(){try{l.texStorage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function te(){try{l.texImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function ne(){try{l.texImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function ve(B){return d[B]!==void 0?d[B]:l.getParameter(B)}function Ze(B,fe){d[B]!==fe&&(l.pixelStorei(B,fe),d[B]=fe)}function Ee(B){He.equals(B)===!1&&(l.scissor(B.x,B.y,B.z,B.w),He.copy(B))}function be(B){De.equals(B)===!1&&(l.viewport(B.x,B.y,B.z,B.w),De.copy(B))}function it(B,fe){let se=c.get(fe);se===void 0&&(se=new WeakMap,c.set(fe,se));let ye=se.get(B);ye===void 0&&(ye=l.getUniformBlockIndex(fe,B.name),se.set(B,ye))}function dt(B,fe){const ye=c.get(fe).get(B);o.get(fe)!==ye&&(l.uniformBlockBinding(fe,ye,B.__bindingPointIndex),o.set(fe,ye))}function _t(){l.disable(l.BLEND),l.disable(l.CULL_FACE),l.disable(l.DEPTH_TEST),l.disable(l.POLYGON_OFFSET_FILL),l.disable(l.SCISSOR_TEST),l.disable(l.STENCIL_TEST),l.disable(l.SAMPLE_ALPHA_TO_COVERAGE),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ZERO),l.blendFuncSeparate(l.ONE,l.ZERO,l.ONE,l.ZERO),l.blendColor(0,0,0,0),l.colorMask(!0,!0,!0,!0),l.clearColor(0,0,0,0),l.depthMask(!0),l.depthFunc(l.LESS),r.setReversed(!1),l.clearDepth(1),l.stencilMask(4294967295),l.stencilFunc(l.ALWAYS,0,4294967295),l.stencilOp(l.KEEP,l.KEEP,l.KEEP),l.clearStencil(0),l.cullFace(l.BACK),l.frontFace(l.CCW),l.polygonOffset(0,0),l.activeTexture(l.TEXTURE0),l.bindFramebuffer(l.FRAMEBUFFER,null),l.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),l.bindFramebuffer(l.READ_FRAMEBUFFER,null),l.useProgram(null),l.lineWidth(1),l.scissor(0,0,l.canvas.width,l.canvas.height),l.viewport(0,0,l.canvas.width,l.canvas.height),l.pixelStorei(l.PACK_ALIGNMENT,4),l.pixelStorei(l.UNPACK_ALIGNMENT,4),l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,!1),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,l.BROWSER_DEFAULT_WEBGL),l.pixelStorei(l.PACK_ROW_LENGTH,0),l.pixelStorei(l.PACK_SKIP_PIXELS,0),l.pixelStorei(l.PACK_SKIP_ROWS,0),l.pixelStorei(l.UNPACK_ROW_LENGTH,0),l.pixelStorei(l.UNPACK_IMAGE_HEIGHT,0),l.pixelStorei(l.UNPACK_SKIP_PIXELS,0),l.pixelStorei(l.UNPACK_SKIP_ROWS,0),l.pixelStorei(l.UNPACK_SKIP_IMAGES,0),h={},d={},W=null,J={},u={},p=new WeakMap,f=[],m=null,v=!1,g=null,b=null,w=null,y=null,M=null,x=null,E=null,S=new oe(0,0,0),A=0,T=!1,_=null,k=null,L=null,P=null,C=null,He.set(0,0,l.canvas.width,l.canvas.height),De.set(0,0,l.canvas.width,l.canvas.height),n.reset(),r.reset(),a.reset()}return{buffers:{color:n,depth:r,stencil:a},enable:le,disable:$,bindFramebuffer:Ue,drawBuffers:je,useProgram:Be,setBlending:lt,setMaterial:ct,setFlipSided:fi,setCullFace:mi,setLineWidth:ds,setPolygonOffset:ts,setScissorTest:us,activeTexture:Cs,bindTexture:z,unbindTexture:ar,compressedTexImage2D:gi,compressedTexImage3D:O,texImage2D:te,texImage3D:ne,pixelStorei:Ze,getParameter:ve,updateUBOMapping:it,uniformBlockBinding:dt,texStorage2D:de,texStorage3D:me,texSubImage2D:I,texSubImage3D:V,compressedTexSubImage2D:Y,compressedTexSubImage3D:ee,scissor:Ee,viewport:be,reset:_t}}function IN(l,e,t,i,s,n,r){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,o=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ie,h=new WeakMap,d=new Set;let u;const p=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(O,I){return f?new OffscreenCanvas(O,I):cf("canvas")}function v(O,I,V){let Y=1;const ee=gi(O);if((ee.width>V||ee.height>V)&&(Y=V/Math.max(ee.width,ee.height)),Y<1)if(typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&O instanceof ImageBitmap||typeof VideoFrame<"u"&&O instanceof VideoFrame){const de=Math.floor(Y*ee.width),me=Math.floor(Y*ee.height);u===void 0&&(u=m(de,me));const te=I?m(de,me):u;return te.width=de,te.height=me,te.getContext("2d").drawImage(O,0,0,de,me),We("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+de+"x"+me+")."),te}else return"data"in O&&We("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),O;return O}function g(O){return O.generateMipmaps}function b(O){l.generateMipmap(O)}function w(O){return O.isWebGLCubeRenderTarget?l.TEXTURE_CUBE_MAP:O.isWebGL3DRenderTarget?l.TEXTURE_3D:O.isWebGLArrayRenderTarget||O.isCompressedArrayTexture?l.TEXTURE_2D_ARRAY:l.TEXTURE_2D}function y(O,I,V,Y,ee,de=!1){if(O!==null){if(l[O]!==void 0)return l[O];We("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+O+"'")}let me;Y&&(me=e.get("EXT_texture_norm16"),me||We("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let te=I;if(I===l.RED&&(V===l.FLOAT&&(te=l.R32F),V===l.HALF_FLOAT&&(te=l.R16F),V===l.UNSIGNED_BYTE&&(te=l.R8),V===l.UNSIGNED_SHORT&&me&&(te=me.R16_EXT),V===l.SHORT&&me&&(te=me.R16_SNORM_EXT)),I===l.RED_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.R8UI),V===l.UNSIGNED_SHORT&&(te=l.R16UI),V===l.UNSIGNED_INT&&(te=l.R32UI),V===l.BYTE&&(te=l.R8I),V===l.SHORT&&(te=l.R16I),V===l.INT&&(te=l.R32I)),I===l.RG&&(V===l.FLOAT&&(te=l.RG32F),V===l.HALF_FLOAT&&(te=l.RG16F),V===l.UNSIGNED_BYTE&&(te=l.RG8),V===l.UNSIGNED_SHORT&&me&&(te=me.RG16_EXT),V===l.SHORT&&me&&(te=me.RG16_SNORM_EXT)),I===l.RG_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RG8UI),V===l.UNSIGNED_SHORT&&(te=l.RG16UI),V===l.UNSIGNED_INT&&(te=l.RG32UI),V===l.BYTE&&(te=l.RG8I),V===l.SHORT&&(te=l.RG16I),V===l.INT&&(te=l.RG32I)),I===l.RGB_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RGB8UI),V===l.UNSIGNED_SHORT&&(te=l.RGB16UI),V===l.UNSIGNED_INT&&(te=l.RGB32UI),V===l.BYTE&&(te=l.RGB8I),V===l.SHORT&&(te=l.RGB16I),V===l.INT&&(te=l.RGB32I)),I===l.RGBA_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RGBA8UI),V===l.UNSIGNED_SHORT&&(te=l.RGBA16UI),V===l.UNSIGNED_INT&&(te=l.RGBA32UI),V===l.BYTE&&(te=l.RGBA8I),V===l.SHORT&&(te=l.RGBA16I),V===l.INT&&(te=l.RGBA32I)),I===l.RGB&&(V===l.UNSIGNED_SHORT&&me&&(te=me.RGB16_EXT),V===l.SHORT&&me&&(te=me.RGB16_SNORM_EXT),V===l.UNSIGNED_INT_5_9_9_9_REV&&(te=l.RGB9_E5),V===l.UNSIGNED_INT_10F_11F_11F_REV&&(te=l.R11F_G11F_B10F)),I===l.RGBA){const ne=de?$0:Kt.getTransfer(ee);V===l.FLOAT&&(te=l.RGBA32F),V===l.HALF_FLOAT&&(te=l.RGBA16F),V===l.UNSIGNED_BYTE&&(te=ne===Si?l.SRGB8_ALPHA8:l.RGBA8),V===l.UNSIGNED_SHORT&&me&&(te=me.RGBA16_EXT),V===l.SHORT&&me&&(te=me.RGBA16_SNORM_EXT),V===l.UNSIGNED_SHORT_4_4_4_4&&(te=l.RGBA4),V===l.UNSIGNED_SHORT_5_5_5_1&&(te=l.RGB5_A1)}return(te===l.R16F||te===l.R32F||te===l.RG16F||te===l.RG32F||te===l.RGBA16F||te===l.RGBA32F)&&e.get("EXT_color_buffer_float"),te}function M(O,I){let V;return O?I===null||I===Qr||I===of?V=l.DEPTH24_STENCIL8:I===yn?V=l.DEPTH32F_STENCIL8:I===af&&(V=l.DEPTH24_STENCIL8,We("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):I===null||I===Qr||I===of?V=l.DEPTH_COMPONENT24:I===yn?V=l.DEPTH_COMPONENT32F:I===af&&(V=l.DEPTH_COMPONENT16),V}function x(O,I){return g(O)===!0||O.isFramebufferTexture&&O.minFilter!==pi&&O.minFilter!==St?Math.log2(Math.max(I.width,I.height))+1:O.mipmaps!==void 0&&O.mipmaps.length>0?O.mipmaps.length:O.isCompressedTexture&&Array.isArray(O.image)?I.mipmaps.length:1}function E(O){const I=O.target;I.removeEventListener("dispose",E),A(I),I.isVideoTexture&&h.delete(I),I.isHTMLTexture&&d.delete(I)}function S(O){const I=O.target;I.removeEventListener("dispose",S),_(I)}function A(O){const I=i.get(O);if(I.__webglInit===void 0)return;const V=O.source,Y=p.get(V);if(Y){const ee=Y[I.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&T(O),Object.keys(Y).length===0&&p.delete(V)}i.remove(O)}function T(O){const I=i.get(O);l.deleteTexture(I.__webglTexture);const V=O.source,Y=p.get(V);delete Y[I.__cacheKey],r.memory.textures--}function _(O){const I=i.get(O);if(O.depthTexture&&(O.depthTexture.dispose(),i.remove(O.depthTexture)),O.isWebGLCubeRenderTarget)for(let Y=0;Y<6;Y++){if(Array.isArray(I.__webglFramebuffer[Y]))for(let ee=0;ee<I.__webglFramebuffer[Y].length;ee++)l.deleteFramebuffer(I.__webglFramebuffer[Y][ee]);else l.deleteFramebuffer(I.__webglFramebuffer[Y]);I.__webglDepthbuffer&&l.deleteRenderbuffer(I.__webglDepthbuffer[Y])}else{if(Array.isArray(I.__webglFramebuffer))for(let Y=0;Y<I.__webglFramebuffer.length;Y++)l.deleteFramebuffer(I.__webglFramebuffer[Y]);else l.deleteFramebuffer(I.__webglFramebuffer);if(I.__webglDepthbuffer&&l.deleteRenderbuffer(I.__webglDepthbuffer),I.__webglMultisampledFramebuffer&&l.deleteFramebuffer(I.__webglMultisampledFramebuffer),I.__webglColorRenderbuffer)for(let Y=0;Y<I.__webglColorRenderbuffer.length;Y++)I.__webglColorRenderbuffer[Y]&&l.deleteRenderbuffer(I.__webglColorRenderbuffer[Y]);I.__webglDepthRenderbuffer&&l.deleteRenderbuffer(I.__webglDepthRenderbuffer)}const V=O.textures;for(let Y=0,ee=V.length;Y<ee;Y++){const de=i.get(V[Y]);de.__webglTexture&&(l.deleteTexture(de.__webglTexture),r.memory.textures--),i.remove(V[Y])}i.remove(O)}let k=0;function L(){k=0}function P(){return k}function C(O){k=O}function N(){const O=k;return O>=s.maxTextures&&We("WebGLTextures: Trying to use "+O+" texture units while this GPU supports only "+s.maxTextures),k+=1,O}function F(O){const I=[];return I.push(O.wrapS),I.push(O.wrapT),I.push(O.wrapR||0),I.push(O.magFilter),I.push(O.minFilter),I.push(O.anisotropy),I.push(O.internalFormat),I.push(O.format),I.push(O.type),I.push(O.generateMipmaps),I.push(O.premultiplyAlpha),I.push(O.flipY),I.push(O.unpackAlignment),I.push(O.colorSpace),I.join()}function H(O,I){const V=i.get(O);if(O.isVideoTexture&&z(O),O.isRenderTargetTexture===!1&&O.isExternalTexture!==!0&&O.version>0&&V.__version!==O.version){const Y=O.image;if(Y===null)We("WebGLRenderer: Texture marked for update but no image data found.");else if(Y.complete===!1)We("WebGLRenderer: Texture marked for update but image is incomplete");else{$(V,O,I);return}}else O.isExternalTexture&&(V.__webglTexture=O.sourceTexture?O.sourceTexture:null);t.bindTexture(l.TEXTURE_2D,V.__webglTexture,l.TEXTURE0+I)}function j(O,I){const V=i.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&V.__version!==O.version){$(V,O,I);return}else O.isExternalTexture&&(V.__webglTexture=O.sourceTexture?O.sourceTexture:null);t.bindTexture(l.TEXTURE_2D_ARRAY,V.__webglTexture,l.TEXTURE0+I)}function W(O,I){const V=i.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&V.__version!==O.version){$(V,O,I);return}t.bindTexture(l.TEXTURE_3D,V.__webglTexture,l.TEXTURE0+I)}function J(O,I){const V=i.get(O);if(O.isCubeDepthTexture!==!0&&O.version>0&&V.__version!==O.version){Ue(V,O,I);return}t.bindTexture(l.TEXTURE_CUBE_MAP,V.__webglTexture,l.TEXTURE0+I)}const re={[sc]:l.REPEAT,[Ms]:l.CLAMP_TO_EDGE,[Pb]:l.MIRRORED_REPEAT},Le={[pi]:l.NEAREST,[bR]:l.NEAREST_MIPMAP_NEAREST,[Ff]:l.NEAREST_MIPMAP_LINEAR,[St]:l.LINEAR,[wv]:l.LINEAR_MIPMAP_NEAREST,[Nr]:l.LINEAR_MIPMAP_LINEAR},He={[ER]:l.NEVER,[DR]:l.ALWAYS,[AR]:l.LESS,[kw]:l.LEQUAL,[TR]:l.EQUAL,[Rw]:l.GEQUAL,[IR]:l.GREATER,[_R]:l.NOTEQUAL};function De(O,I){if(I.type===yn&&e.has("OES_texture_float_linear")===!1&&(I.magFilter===St||I.magFilter===wv||I.magFilter===Ff||I.magFilter===Nr||I.minFilter===St||I.minFilter===wv||I.minFilter===Ff||I.minFilter===Nr)&&We("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),l.texParameteri(O,l.TEXTURE_WRAP_S,re[I.wrapS]),l.texParameteri(O,l.TEXTURE_WRAP_T,re[I.wrapT]),(O===l.TEXTURE_3D||O===l.TEXTURE_2D_ARRAY)&&l.texParameteri(O,l.TEXTURE_WRAP_R,re[I.wrapR]),l.texParameteri(O,l.TEXTURE_MAG_FILTER,Le[I.magFilter]),l.texParameteri(O,l.TEXTURE_MIN_FILTER,Le[I.minFilter]),I.compareFunction&&(l.texParameteri(O,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE),l.texParameteri(O,l.TEXTURE_COMPARE_FUNC,He[I.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(I.magFilter===pi||I.minFilter!==Ff&&I.minFilter!==Nr||I.type===yn&&e.has("OES_texture_float_linear")===!1)return;if(I.anisotropy>1||i.get(I).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");l.texParameterf(O,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(I.anisotropy,s.getMaxAnisotropy())),i.get(I).__currentAnisotropy=I.anisotropy}}}function Z(O,I){let V=!1;O.__webglInit===void 0&&(O.__webglInit=!0,I.addEventListener("dispose",E));const Y=I.source;let ee=p.get(Y);ee===void 0&&(ee={},p.set(Y,ee));const de=F(I);if(de!==O.__cacheKey){ee[de]===void 0&&(ee[de]={texture:l.createTexture(),usedTimes:0},r.memory.textures++,V=!0),ee[de].usedTimes++;const me=ee[O.__cacheKey];me!==void 0&&(ee[O.__cacheKey].usedTimes--,me.usedTimes===0&&T(I)),O.__cacheKey=de,O.__webglTexture=ee[de].texture}return V}function ce(O,I,V){return Math.floor(Math.floor(O/V)/I)}function le(O,I,V,Y){const de=O.updateRanges;if(de.length===0)t.texSubImage2D(l.TEXTURE_2D,0,0,0,I.width,I.height,V,Y,I.data);else{de.sort((Ze,Ee)=>Ze.start-Ee.start);let me=0;for(let Ze=1;Ze<de.length;Ze++){const Ee=de[me],be=de[Ze],it=Ee.start+Ee.count,dt=ce(be.start,I.width,4),_t=ce(Ee.start,I.width,4);be.start<=it+1&&dt===_t&&ce(be.start+be.count-1,I.width,4)===dt?Ee.count=Math.max(Ee.count,be.start+be.count-Ee.start):(++me,de[me]=be)}de.length=me+1;const te=t.getParameter(l.UNPACK_ROW_LENGTH),ne=t.getParameter(l.UNPACK_SKIP_PIXELS),ve=t.getParameter(l.UNPACK_SKIP_ROWS);t.pixelStorei(l.UNPACK_ROW_LENGTH,I.width);for(let Ze=0,Ee=de.length;Ze<Ee;Ze++){const be=de[Ze],it=Math.floor(be.start/4),dt=Math.ceil(be.count/4),_t=it%I.width,B=Math.floor(it/I.width),fe=dt,se=1;t.pixelStorei(l.UNPACK_SKIP_PIXELS,_t),t.pixelStorei(l.UNPACK_SKIP_ROWS,B),t.texSubImage2D(l.TEXTURE_2D,0,_t,B,fe,se,V,Y,I.data)}O.clearUpdateRanges(),t.pixelStorei(l.UNPACK_ROW_LENGTH,te),t.pixelStorei(l.UNPACK_SKIP_PIXELS,ne),t.pixelStorei(l.UNPACK_SKIP_ROWS,ve)}}function $(O,I,V){let Y=l.TEXTURE_2D;(I.isDataArrayTexture||I.isCompressedArrayTexture)&&(Y=l.TEXTURE_2D_ARRAY),I.isData3DTexture&&(Y=l.TEXTURE_3D);const ee=Z(O,I),de=I.source;t.bindTexture(Y,O.__webglTexture,l.TEXTURE0+V);const me=i.get(de);if(de.version!==me.__version||ee===!0){if(t.activeTexture(l.TEXTURE0+V),(typeof ImageBitmap<"u"&&I.image instanceof ImageBitmap)===!1){const se=Kt.getPrimaries(Kt.workingColorSpace),ye=I.colorSpace===Rl?null:Kt.getPrimaries(I.colorSpace),_e=I.colorSpace===Rl||se===ye?l.NONE:l.BROWSER_DEFAULT_WEBGL;t.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,I.flipY),t.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,I.premultiplyAlpha),t.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,_e)}t.pixelStorei(l.UNPACK_ALIGNMENT,I.unpackAlignment);let ne=v(I.image,!1,s.maxTextureSize);ne=ar(I,ne);const ve=n.convert(I.format,I.colorSpace),Ze=n.convert(I.type);let Ee=y(I.internalFormat,ve,Ze,I.normalized,I.colorSpace,I.isVideoTexture);De(Y,I);let be;const it=I.mipmaps,dt=I.isVideoTexture!==!0,_t=me.__version===void 0||ee===!0,B=de.dataReady,fe=x(I,ne);if(I.isDepthTexture)Ee=M(I.format===Fc,I.type),_t&&(dt?t.texStorage2D(l.TEXTURE_2D,1,Ee,ne.width,ne.height):t.texImage2D(l.TEXTURE_2D,0,Ee,ne.width,ne.height,0,ve,Ze,null));else if(I.isDataTexture)if(it.length>0){dt&&_t&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,it[0].width,it[0].height);for(let se=0,ye=it.length;se<ye;se++)be=it[se],dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,Ze,be.data):t.texImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,ve,Ze,be.data);I.generateMipmaps=!1}else dt?(_t&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,ne.width,ne.height),B&&le(I,ne,ve,Ze)):t.texImage2D(l.TEXTURE_2D,0,Ee,ne.width,ne.height,0,ve,Ze,ne.data);else if(I.isCompressedTexture)if(I.isCompressedArrayTexture){dt&&_t&&t.texStorage3D(l.TEXTURE_2D_ARRAY,fe,Ee,it[0].width,it[0].height,ne.depth);for(let se=0,ye=it.length;se<ye;se++)if(be=it[se],I.format!==xs)if(ve!==null)if(dt){if(B)if(I.layerUpdates.size>0){const _e=pE(be.width,be.height,I.format,I.type);for(const ae of I.layerUpdates){const Xe=be.data.subarray(ae*_e/be.data.BYTES_PER_ELEMENT,(ae+1)*_e/be.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,ae,be.width,be.height,1,ve,Xe)}I.clearLayerUpdates()}else t.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,0,be.width,be.height,ne.depth,ve,be.data)}else t.compressedTexImage3D(l.TEXTURE_2D_ARRAY,se,Ee,be.width,be.height,ne.depth,0,be.data,0,0);else We("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else dt?B&&t.texSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,0,be.width,be.height,ne.depth,ve,Ze,be.data):t.texImage3D(l.TEXTURE_2D_ARRAY,se,Ee,be.width,be.height,ne.depth,0,ve,Ze,be.data)}else{dt&&_t&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,it[0].width,it[0].height);for(let se=0,ye=it.length;se<ye;se++)be=it[se],I.format!==xs?ve!==null?dt?B&&t.compressedTexSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,be.data):t.compressedTexImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,be.data):We("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,Ze,be.data):t.texImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,ve,Ze,be.data)}else if(I.isDataArrayTexture)if(dt){if(_t&&t.texStorage3D(l.TEXTURE_2D_ARRAY,fe,Ee,ne.width,ne.height,ne.depth),B)if(I.layerUpdates.size>0){const se=pE(ne.width,ne.height,I.format,I.type);for(const ye of I.layerUpdates){const _e=ne.data.subarray(ye*se/ne.data.BYTES_PER_ELEMENT,(ye+1)*se/ne.data.BYTES_PER_ELEMENT);t.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,ye,ne.width,ne.height,1,ve,Ze,_e)}I.clearLayerUpdates()}else t.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,0,ne.width,ne.height,ne.depth,ve,Ze,ne.data)}else t.texImage3D(l.TEXTURE_2D_ARRAY,0,Ee,ne.width,ne.height,ne.depth,0,ve,Ze,ne.data);else if(I.isData3DTexture)dt?(_t&&t.texStorage3D(l.TEXTURE_3D,fe,Ee,ne.width,ne.height,ne.depth),B&&t.texSubImage3D(l.TEXTURE_3D,0,0,0,0,ne.width,ne.height,ne.depth,ve,Ze,ne.data)):t.texImage3D(l.TEXTURE_3D,0,Ee,ne.width,ne.height,ne.depth,0,ve,Ze,ne.data);else if(I.isFramebufferTexture){if(_t)if(dt)t.texStorage2D(l.TEXTURE_2D,fe,Ee,ne.width,ne.height);else{let se=ne.width,ye=ne.height;for(let _e=0;_e<fe;_e++)t.texImage2D(l.TEXTURE_2D,_e,Ee,se,ye,0,ve,Ze,null),se>>=1,ye>>=1}}else if(I.isHTMLTexture){if("texElementImage2D"in l){const se=l.canvas;if(se.hasAttribute("layoutsubtree")||se.setAttribute("layoutsubtree","true"),ne.parentNode!==se){se.appendChild(ne),d.add(I),se.onpaint=ye=>{const _e=ye.changedElements;for(const ae of d)_e.includes(ae.image)&&(ae.needsUpdate=!0)},se.requestPaint();return}if(l.texElementImage2D.length===3)l.texElementImage2D(l.TEXTURE_2D,l.RGBA8,ne);else{const _e=l.RGBA,ae=l.RGBA,Xe=l.UNSIGNED_BYTE;l.texElementImage2D(l.TEXTURE_2D,0,_e,ae,Xe,ne)}l.texParameteri(l.TEXTURE_2D,l.TEXTURE_MIN_FILTER,l.LINEAR),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE)}}else if(it.length>0){if(dt&&_t){const se=gi(it[0]);t.texStorage2D(l.TEXTURE_2D,fe,Ee,se.width,se.height)}for(let se=0,ye=it.length;se<ye;se++)be=it[se],dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,ve,Ze,be):t.texImage2D(l.TEXTURE_2D,se,Ee,ve,Ze,be);I.generateMipmaps=!1}else if(dt){if(_t){const se=gi(ne);t.texStorage2D(l.TEXTURE_2D,fe,Ee,se.width,se.height)}B&&t.texSubImage2D(l.TEXTURE_2D,0,0,0,ve,Ze,ne)}else t.texImage2D(l.TEXTURE_2D,0,Ee,ve,Ze,ne);g(I)&&b(Y),me.__version=de.version,I.onUpdate&&I.onUpdate(I)}O.__version=I.version}function Ue(O,I,V){if(I.image.length!==6)return;const Y=Z(O,I),ee=I.source;t.bindTexture(l.TEXTURE_CUBE_MAP,O.__webglTexture,l.TEXTURE0+V);const de=i.get(ee);if(ee.version!==de.__version||Y===!0){t.activeTexture(l.TEXTURE0+V);const me=Kt.getPrimaries(Kt.workingColorSpace),te=I.colorSpace===Rl?null:Kt.getPrimaries(I.colorSpace),ne=I.colorSpace===Rl||me===te?l.NONE:l.BROWSER_DEFAULT_WEBGL;t.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,I.flipY),t.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,I.premultiplyAlpha),t.pixelStorei(l.UNPACK_ALIGNMENT,I.unpackAlignment),t.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,ne);const ve=I.isCompressedTexture||I.image[0].isCompressedTexture,Ze=I.image[0]&&I.image[0].isDataTexture,Ee=[];for(let ae=0;ae<6;ae++)!ve&&!Ze?Ee[ae]=v(I.image[ae],!0,s.maxCubemapSize):Ee[ae]=Ze?I.image[ae].image:I.image[ae],Ee[ae]=ar(I,Ee[ae]);const be=Ee[0],it=n.convert(I.format,I.colorSpace),dt=n.convert(I.type),_t=y(I.internalFormat,it,dt,I.normalized,I.colorSpace),B=I.isVideoTexture!==!0,fe=de.__version===void 0||Y===!0,se=ee.dataReady;let ye=x(I,be);De(l.TEXTURE_CUBE_MAP,I);let _e;if(ve){B&&fe&&t.texStorage2D(l.TEXTURE_CUBE_MAP,ye,_t,be.width,be.height);for(let ae=0;ae<6;ae++){_e=Ee[ae].mipmaps;for(let Xe=0;Xe<_e.length;Xe++){const ze=_e[Xe];I.format!==xs?it!==null?B?se&&t.compressedTexSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,0,0,ze.width,ze.height,it,ze.data):t.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,_t,ze.width,ze.height,0,ze.data):We("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,0,0,ze.width,ze.height,it,dt,ze.data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,_t,ze.width,ze.height,0,it,dt,ze.data)}}}else{if(_e=I.mipmaps,B&&fe){_e.length>0&&ye++;const ae=gi(Ee[0]);t.texStorage2D(l.TEXTURE_CUBE_MAP,ye,_t,ae.width,ae.height)}for(let ae=0;ae<6;ae++)if(Ze){B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,0,0,Ee[ae].width,Ee[ae].height,it,dt,Ee[ae].data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,_t,Ee[ae].width,Ee[ae].height,0,it,dt,Ee[ae].data);for(let Xe=0;Xe<_e.length;Xe++){const ps=_e[Xe].image[ae].image;B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,0,0,ps.width,ps.height,it,dt,ps.data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,_t,ps.width,ps.height,0,it,dt,ps.data)}}else{B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,0,0,it,dt,Ee[ae]):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,_t,it,dt,Ee[ae]);for(let Xe=0;Xe<_e.length;Xe++){const ze=_e[Xe];B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,0,0,it,dt,ze.image[ae]):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,_t,it,dt,ze.image[ae])}}}g(I)&&b(l.TEXTURE_CUBE_MAP),de.__version=ee.version,I.onUpdate&&I.onUpdate(I)}O.__version=I.version}function je(O,I,V,Y,ee,de){const me=n.convert(V.format,V.colorSpace),te=n.convert(V.type),ne=y(V.internalFormat,me,te,V.normalized,V.colorSpace),ve=i.get(I),Ze=i.get(V);if(Ze.__renderTarget=I,!ve.__hasExternalTextures){const Ee=Math.max(1,I.width>>de),be=Math.max(1,I.height>>de);ee===l.TEXTURE_3D||ee===l.TEXTURE_2D_ARRAY?t.texImage3D(ee,de,ne,Ee,be,I.depth,0,me,te,null):t.texImage2D(ee,de,ne,Ee,be,0,me,te,null)}t.bindFramebuffer(l.FRAMEBUFFER,O),Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,Y,ee,Ze.__webglTexture,0,us(I)):(ee===l.TEXTURE_2D||ee>=l.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=l.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&l.framebufferTexture2D(l.FRAMEBUFFER,Y,ee,Ze.__webglTexture,de),t.bindFramebuffer(l.FRAMEBUFFER,null)}function Be(O,I,V){if(l.bindRenderbuffer(l.RENDERBUFFER,O),I.depthBuffer){const Y=I.depthTexture,ee=Y&&Y.isDepthTexture?Y.type:null,de=M(I.stencilBuffer,ee),me=I.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;Cs(I)?a.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,us(I),de,I.width,I.height):V?l.renderbufferStorageMultisample(l.RENDERBUFFER,us(I),de,I.width,I.height):l.renderbufferStorage(l.RENDERBUFFER,de,I.width,I.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,me,l.RENDERBUFFER,O)}else{const Y=I.textures;for(let ee=0;ee<Y.length;ee++){const de=Y[ee],me=n.convert(de.format,de.colorSpace),te=n.convert(de.type),ne=y(de.internalFormat,me,te,de.normalized,de.colorSpace);Cs(I)?a.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,us(I),ne,I.width,I.height):V?l.renderbufferStorageMultisample(l.RENDERBUFFER,us(I),ne,I.width,I.height):l.renderbufferStorage(l.RENDERBUFFER,ne,I.width,I.height)}}l.bindRenderbuffer(l.RENDERBUFFER,null)}function Oe(O,I,V){const Y=I.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(l.FRAMEBUFFER,O),!(I.depthTexture&&I.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const ee=i.get(I.depthTexture);if(ee.__renderTarget=I,(!ee.__webglTexture||I.depthTexture.image.width!==I.width||I.depthTexture.image.height!==I.height)&&(I.depthTexture.image.width=I.width,I.depthTexture.image.height=I.height,I.depthTexture.needsUpdate=!0),Y){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,I.depthTexture.addEventListener("dispose",E)),ee.__webglTexture===void 0){ee.__webglTexture=l.createTexture(),t.bindTexture(l.TEXTURE_CUBE_MAP,ee.__webglTexture),De(l.TEXTURE_CUBE_MAP,I.depthTexture);const ve=n.convert(I.depthTexture.format),Ze=n.convert(I.depthTexture.type);let Ee;I.depthTexture.format===Zo?Ee=l.DEPTH_COMPONENT24:I.depthTexture.format===Fc&&(Ee=l.DEPTH24_STENCIL8);for(let be=0;be<6;be++)l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+be,0,Ee,I.width,I.height,0,ve,Ze,null)}}else H(I.depthTexture,0);const de=ee.__webglTexture,me=us(I),te=Y?l.TEXTURE_CUBE_MAP_POSITIVE_X+V:l.TEXTURE_2D,ne=I.depthTexture.format===Fc?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;if(I.depthTexture.format===Zo)Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,ne,te,de,0,me):l.framebufferTexture2D(l.FRAMEBUFFER,ne,te,de,0);else if(I.depthTexture.format===Fc)Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,ne,te,de,0,me):l.framebufferTexture2D(l.FRAMEBUFFER,ne,te,de,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function nt(O){const I=i.get(O),V=O.isWebGLCubeRenderTarget===!0;if(I.__boundDepthTexture!==O.depthTexture){const Y=O.depthTexture;if(I.__depthDisposeCallback&&I.__depthDisposeCallback(),Y){const ee=()=>{delete I.__boundDepthTexture,delete I.__depthDisposeCallback,Y.removeEventListener("dispose",ee)};Y.addEventListener("dispose",ee),I.__depthDisposeCallback=ee}I.__boundDepthTexture=Y}if(O.depthTexture&&!I.__autoAllocateDepthBuffer)if(V)for(let Y=0;Y<6;Y++)Oe(I.__webglFramebuffer[Y],O,Y);else{const Y=O.texture.mipmaps;Y&&Y.length>0?Oe(I.__webglFramebuffer[0],O,0):Oe(I.__webglFramebuffer,O,0)}else if(V){I.__webglDepthbuffer=[];for(let Y=0;Y<6;Y++)if(t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer[Y]),I.__webglDepthbuffer[Y]===void 0)I.__webglDepthbuffer[Y]=l.createRenderbuffer(),Be(I.__webglDepthbuffer[Y],O,!1);else{const ee=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,de=I.__webglDepthbuffer[Y];l.bindRenderbuffer(l.RENDERBUFFER,de),l.framebufferRenderbuffer(l.FRAMEBUFFER,ee,l.RENDERBUFFER,de)}}else{const Y=O.texture.mipmaps;if(Y&&Y.length>0?t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer[0]):t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer),I.__webglDepthbuffer===void 0)I.__webglDepthbuffer=l.createRenderbuffer(),Be(I.__webglDepthbuffer,O,!1);else{const ee=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,de=I.__webglDepthbuffer;l.bindRenderbuffer(l.RENDERBUFFER,de),l.framebufferRenderbuffer(l.FRAMEBUFFER,ee,l.RENDERBUFFER,de)}}t.bindFramebuffer(l.FRAMEBUFFER,null)}function lt(O,I,V){const Y=i.get(O);I!==void 0&&je(Y.__webglFramebuffer,O,O.texture,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,0),V!==void 0&&nt(O)}function ct(O){const I=O.texture,V=i.get(O),Y=i.get(I);O.addEventListener("dispose",S);const ee=O.textures,de=O.isWebGLCubeRenderTarget===!0,me=ee.length>1;if(me||(Y.__webglTexture===void 0&&(Y.__webglTexture=l.createTexture()),Y.__version=I.version,r.memory.textures++),de){V.__webglFramebuffer=[];for(let te=0;te<6;te++)if(I.mipmaps&&I.mipmaps.length>0){V.__webglFramebuffer[te]=[];for(let ne=0;ne<I.mipmaps.length;ne++)V.__webglFramebuffer[te][ne]=l.createFramebuffer()}else V.__webglFramebuffer[te]=l.createFramebuffer()}else{if(I.mipmaps&&I.mipmaps.length>0){V.__webglFramebuffer=[];for(let te=0;te<I.mipmaps.length;te++)V.__webglFramebuffer[te]=l.createFramebuffer()}else V.__webglFramebuffer=l.createFramebuffer();if(me)for(let te=0,ne=ee.length;te<ne;te++){const ve=i.get(ee[te]);ve.__webglTexture===void 0&&(ve.__webglTexture=l.createTexture(),r.memory.textures++)}if(O.samples>0&&Cs(O)===!1){V.__webglMultisampledFramebuffer=l.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(l.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let te=0;te<ee.length;te++){const ne=ee[te];V.__webglColorRenderbuffer[te]=l.createRenderbuffer(),l.bindRenderbuffer(l.RENDERBUFFER,V.__webglColorRenderbuffer[te]);const ve=n.convert(ne.format,ne.colorSpace),Ze=n.convert(ne.type),Ee=y(ne.internalFormat,ve,Ze,ne.normalized,ne.colorSpace,O.isXRRenderTarget===!0),be=us(O);l.renderbufferStorageMultisample(l.RENDERBUFFER,be,Ee,O.width,O.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+te,l.RENDERBUFFER,V.__webglColorRenderbuffer[te])}l.bindRenderbuffer(l.RENDERBUFFER,null),O.depthBuffer&&(V.__webglDepthRenderbuffer=l.createRenderbuffer(),Be(V.__webglDepthRenderbuffer,O,!0)),t.bindFramebuffer(l.FRAMEBUFFER,null)}}if(de){t.bindTexture(l.TEXTURE_CUBE_MAP,Y.__webglTexture),De(l.TEXTURE_CUBE_MAP,I);for(let te=0;te<6;te++)if(I.mipmaps&&I.mipmaps.length>0)for(let ne=0;ne<I.mipmaps.length;ne++)je(V.__webglFramebuffer[te][ne],O,I,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+te,ne);else je(V.__webglFramebuffer[te],O,I,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+te,0);g(I)&&b(l.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(me){for(let te=0,ne=ee.length;te<ne;te++){const ve=ee[te],Ze=i.get(ve);let Ee=l.TEXTURE_2D;(O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(Ee=O.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),t.bindTexture(Ee,Ze.__webglTexture),De(Ee,ve),je(V.__webglFramebuffer,O,ve,l.COLOR_ATTACHMENT0+te,Ee,0),g(ve)&&b(Ee)}t.unbindTexture()}else{let te=l.TEXTURE_2D;if((O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(te=O.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),t.bindTexture(te,Y.__webglTexture),De(te,I),I.mipmaps&&I.mipmaps.length>0)for(let ne=0;ne<I.mipmaps.length;ne++)je(V.__webglFramebuffer[ne],O,I,l.COLOR_ATTACHMENT0,te,ne);else je(V.__webglFramebuffer,O,I,l.COLOR_ATTACHMENT0,te,0);g(I)&&b(te),t.unbindTexture()}O.depthBuffer&&nt(O)}function fi(O){const I=O.textures;for(let V=0,Y=I.length;V<Y;V++){const ee=I[V];if(g(ee)){const de=w(O),me=i.get(ee).__webglTexture;t.bindTexture(de,me),b(de),t.unbindTexture()}}}const mi=[],ds=[];function ts(O){if(O.samples>0){if(Cs(O)===!1){const I=O.textures,V=O.width,Y=O.height;let ee=l.COLOR_BUFFER_BIT;const de=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,me=i.get(O),te=I.length>1;if(te)for(let ve=0;ve<I.length;ve++)t.bindFramebuffer(l.FRAMEBUFFER,me.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.RENDERBUFFER,null),t.bindFramebuffer(l.FRAMEBUFFER,me.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.TEXTURE_2D,null,0);t.bindFramebuffer(l.READ_FRAMEBUFFER,me.__webglMultisampledFramebuffer);const ne=O.texture.mipmaps;ne&&ne.length>0?t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglFramebuffer[0]):t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglFramebuffer);for(let ve=0;ve<I.length;ve++){if(O.resolveDepthBuffer&&(O.depthBuffer&&(ee|=l.DEPTH_BUFFER_BIT),O.stencilBuffer&&O.resolveStencilBuffer&&(ee|=l.STENCIL_BUFFER_BIT)),te){l.framebufferRenderbuffer(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.RENDERBUFFER,me.__webglColorRenderbuffer[ve]);const Ze=i.get(I[ve]).__webglTexture;l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,Ze,0)}l.blitFramebuffer(0,0,V,Y,0,0,V,Y,ee,l.NEAREST),o===!0&&(mi.length=0,ds.length=0,mi.push(l.COLOR_ATTACHMENT0+ve),O.depthBuffer&&O.resolveDepthBuffer===!1&&(mi.push(de),ds.push(de),l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,ds)),l.invalidateFramebuffer(l.READ_FRAMEBUFFER,mi))}if(t.bindFramebuffer(l.READ_FRAMEBUFFER,null),t.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),te)for(let ve=0;ve<I.length;ve++){t.bindFramebuffer(l.FRAMEBUFFER,me.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.RENDERBUFFER,me.__webglColorRenderbuffer[ve]);const Ze=i.get(I[ve]).__webglTexture;t.bindFramebuffer(l.FRAMEBUFFER,me.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.TEXTURE_2D,Ze,0)}t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglMultisampledFramebuffer)}else if(O.depthBuffer&&O.resolveDepthBuffer===!1&&o){const I=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,[I])}}}function us(O){return Math.min(s.maxSamples,O.samples)}function Cs(O){const I=i.get(O);return O.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&I.__useRenderToTexture!==!1}function z(O){const I=r.render.frame;h.get(O)!==I&&(h.set(O,I),O.update())}function ar(O,I){const V=O.colorSpace,Y=O.format,ee=O.type;return O.isCompressedTexture===!0||O.isVideoTexture===!0||V!==W0&&V!==Rl&&(Kt.getTransfer(V)===Si?(Y!==xs||ee!==On)&&We("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ft("WebGLTextures: Unsupported texture color space:",V)),I}function gi(O){return typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement?(c.width=O.naturalWidth||O.width,c.height=O.naturalHeight||O.height):typeof VideoFrame<"u"&&O instanceof VideoFrame?(c.width=O.displayWidth,c.height=O.displayHeight):(c.width=O.width,c.height=O.height),c}this.allocateTextureUnit=N,this.resetTextureUnits=L,this.getTextureUnits=P,this.setTextureUnits=C,this.setTexture2D=H,this.setTexture2DArray=j,this.setTexture3D=W,this.setTextureCube=J,this.rebindTextures=lt,this.setupRenderTarget=ct,this.updateRenderTargetMipmap=fi,this.updateMultisampleRenderTarget=ts,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=je,this.useMultisampledRTT=Cs,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function _N(l,e){function t(i,s=Rl){let n;const r=Kt.getTransfer(s);if(i===On)return l.UNSIGNED_BYTE;if(i===Ew)return l.UNSIGNED_SHORT_4_4_4_4;if(i===Aw)return l.UNSIGNED_SHORT_5_5_5_1;if(i===a3)return l.UNSIGNED_INT_5_9_9_9_REV;if(i===o3)return l.UNSIGNED_INT_10F_11F_11F_REV;if(i===n3)return l.BYTE;if(i===r3)return l.SHORT;if(i===af)return l.UNSIGNED_SHORT;if(i===Sw)return l.INT;if(i===Qr)return l.UNSIGNED_INT;if(i===yn)return l.FLOAT;if(i===ti)return l.HALF_FLOAT;if(i===l3)return l.ALPHA;if(i===c3)return l.RGB;if(i===xs)return l.RGBA;if(i===Zo)return l.DEPTH_COMPONENT;if(i===Fc)return l.DEPTH_STENCIL;if(i===iu)return l.RED;if(i===Tw)return l.RED_INTEGER;if(i===rh)return l.RG;if(i===Iw)return l.RG_INTEGER;if(i===_w)return l.RGBA_INTEGER;if(i===a0||i===o0||i===l0||i===c0)if(r===Si)if(n=e.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(i===a0)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===o0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===l0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===c0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=e.get("WEBGL_compressed_texture_s3tc"),n!==null){if(i===a0)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===o0)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===l0)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===c0)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Nb||i===Fb||i===Ub||i===Bb)if(n=e.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(i===Nb)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Fb)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Ub)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Bb)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===zb||i===Hb||i===Gb||i===Vb||i===Wb||i===B0||i===$b)if(n=e.get("WEBGL_compressed_texture_etc"),n!==null){if(i===zb||i===Hb)return r===Si?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(i===Gb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC;if(i===Vb)return n.COMPRESSED_R11_EAC;if(i===Wb)return n.COMPRESSED_SIGNED_R11_EAC;if(i===B0)return n.COMPRESSED_RG11_EAC;if(i===$b)return n.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Kb||i===Xb||i===Yb||i===qb||i===jb||i===Zb||i===Jb||i===Qb||i===ey||i===ty||i===iy||i===sy||i===ny||i===ry)if(n=e.get("WEBGL_compressed_texture_astc"),n!==null){if(i===Kb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Xb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Yb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===qb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===jb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Zb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Jb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Qb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===ey)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===ty)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===iy)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===sy)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===ny)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===ry)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===ay||i===oy||i===ly)if(n=e.get("EXT_texture_compression_bptc"),n!==null){if(i===ay)return r===Si?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===oy)return n.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ly)return n.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===cy||i===hy||i===z0||i===dy)if(n=e.get("EXT_texture_compression_rgtc"),n!==null){if(i===cy)return n.COMPRESSED_RED_RGTC1_EXT;if(i===hy)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===z0)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===dy)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===of?l.UNSIGNED_INT_24_8:l[i]!==void 0?l[i]:null}return{convert:t}}const DN=`
|
|
8906
|
+
}`,SN=[new D(1,0,0),new D(-1,0,0),new D(0,1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1)],EN=[new D(0,-1,0),new D(0,-1,0),new D(0,0,1),new D(0,0,-1),new D(0,-1,0),new D(0,-1,0)],PE=new qe,Du=new D,r1=new D;function AN(l,e,t){let i=new zg;const s=new ie,n=new ie,r=new Lt,a=new cC,o=new hC,c={},h=t.maxTextureSize,d={[ho]:Ji,[Ji]:ho,[$s]:$s},u=new Nt({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ie},radius:{value:4}},vertexShader:MN,fragmentShader:xN}),p=u.clone();p.defines.HORIZONTAL_PASS=1;const f=new Tt;f.setAttribute("position",new Et(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Me(f,u),v=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=tp;let g=this.type;this.render=function(x,E,S){if(v.enabled===!1||v.autoUpdate===!1&&v.needsUpdate===!1||x.length===0)return;this.type===Qk&&(We("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=tp);const A=l.getRenderTarget(),T=l.getActiveCubeFace(),_=l.getActiveMipmapLevel(),k=l.state;k.setBlending(wr),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);const L=g!==this.type;L&&E.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(C=>C.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,C=x.length;P<C;P++){const N=x[P],F=N.shadow;if(F===void 0){We("WebGLShadowMap:",N,"has no shadow.");continue}if(F.autoUpdate===!1&&F.needsUpdate===!1)continue;s.copy(F.mapSize);const H=F.getFrameExtents();s.multiply(H),n.copy(F.mapSize),(s.x>h||s.y>h)&&(s.x>h&&(n.x=Math.floor(h/H.x),s.x=n.x*H.x,F.mapSize.x=n.x),s.y>h&&(n.y=Math.floor(h/H.y),s.y=n.y*H.y,F.mapSize.y=n.y));const j=l.state.buffers.depth.getReversed();if(F.camera._reversedDepth=j,F.map===null||L===!0){if(F.map!==null&&(F.map.depthTexture!==null&&(F.map.depthTexture.dispose(),F.map.depthTexture=null),F.map.dispose()),this.type===ju){if(N.isPointLight){We("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}F.map=new oi(s.x,s.y,{format:rh,type:ti,minFilter:St,magFilter:St,generateMipmaps:!1}),F.map.texture.name=N.name+".shadowMap",F.map.depthTexture=new nc(s.x,s.y,yn),F.map.depthTexture.name=N.name+".shadowMapDepth",F.map.depthTexture.format=Zo,F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=pi,F.map.depthTexture.magFilter=pi}else N.isPointLight?(F.map=new pf(s.x),F.map.depthTexture=new A4(s.x,Qr)):(F.map=new oi(s.x,s.y),F.map.depthTexture=new nc(s.x,s.y,Qr)),F.map.depthTexture.name=N.name+".shadowMap",F.map.depthTexture.format=Zo,this.type===tp?(F.map.depthTexture.compareFunction=j?Rw:kw,F.map.depthTexture.minFilter=St,F.map.depthTexture.magFilter=St):(F.map.depthTexture.compareFunction=null,F.map.depthTexture.minFilter=pi,F.map.depthTexture.magFilter=pi);F.camera.updateProjectionMatrix()}const W=F.map.isWebGLCubeRenderTarget?6:1;for(let J=0;J<W;J++){if(F.map.isWebGLCubeRenderTarget)l.setRenderTarget(F.map,J),l.clear();else{J===0&&(l.setRenderTarget(F.map),l.clear());const re=F.getViewport(J);r.set(n.x*re.x,n.y*re.y,n.x*re.z,n.y*re.w),k.viewport(r)}if(N.isPointLight){const re=F.camera,Le=F.matrix,He=N.distance||re.far;He!==re.far&&(re.far=He,re.updateProjectionMatrix()),Du.setFromMatrixPosition(N.matrixWorld),re.position.copy(Du),r1.copy(re.position),r1.add(SN[J]),re.up.copy(EN[J]),re.lookAt(r1),re.updateMatrixWorld(),Le.makeTranslation(-Du.x,-Du.y,-Du.z),PE.multiplyMatrices(re.projectionMatrix,re.matrixWorldInverse),F._frustum.setFromProjectionMatrix(PE,re.coordinateSystem,re.reversedDepth)}else F.updateMatrices(N);i=F.getFrustum(),y(E,S,F.camera,N,this.type)}F.isPointLightShadow!==!0&&this.type===ju&&b(F,S),F.needsUpdate=!1}g=this.type,v.needsUpdate=!1,l.setRenderTarget(A,T,_)};function b(x,E){const S=e.update(m);u.defines.VSM_SAMPLES!==x.blurSamples&&(u.defines.VSM_SAMPLES=x.blurSamples,p.defines.VSM_SAMPLES=x.blurSamples,u.needsUpdate=!0,p.needsUpdate=!0),x.mapPass===null&&(x.mapPass=new oi(s.x,s.y,{format:rh,type:ti})),u.uniforms.shadow_pass.value=x.map.depthTexture,u.uniforms.resolution.value=x.mapSize,u.uniforms.radius.value=x.radius,l.setRenderTarget(x.mapPass),l.clear(),l.renderBufferDirect(E,null,S,u,m,null),p.uniforms.shadow_pass.value=x.mapPass.texture,p.uniforms.resolution.value=x.mapSize,p.uniforms.radius.value=x.radius,l.setRenderTarget(x.map),l.clear(),l.renderBufferDirect(E,null,S,p,m,null)}function w(x,E,S,A){let T=null;const _=S.isPointLight===!0?x.customDistanceMaterial:x.customDepthMaterial;if(_!==void 0)T=_;else if(T=S.isPointLight===!0?o:a,l.localClippingEnabled&&E.clipShadows===!0&&Array.isArray(E.clippingPlanes)&&E.clippingPlanes.length!==0||E.displacementMap&&E.displacementScale!==0||E.alphaMap&&E.alphaTest>0||E.map&&E.alphaTest>0||E.alphaToCoverage===!0){const k=T.uuid,L=E.uuid;let P=c[k];P===void 0&&(P={},c[k]=P);let C=P[L];C===void 0&&(C=T.clone(),P[L]=C,E.addEventListener("dispose",M)),T=C}if(T.visible=E.visible,T.wireframe=E.wireframe,A===ju?T.side=E.shadowSide!==null?E.shadowSide:E.side:T.side=E.shadowSide!==null?E.shadowSide:d[E.side],T.alphaMap=E.alphaMap,T.alphaTest=E.alphaToCoverage===!0?.5:E.alphaTest,T.map=E.map,T.clipShadows=E.clipShadows,T.clippingPlanes=E.clippingPlanes,T.clipIntersection=E.clipIntersection,T.displacementMap=E.displacementMap,T.displacementScale=E.displacementScale,T.displacementBias=E.displacementBias,T.wireframeLinewidth=E.wireframeLinewidth,T.linewidth=E.linewidth,S.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const k=l.properties.get(T);k.light=S}return T}function y(x,E,S,A,T){if(x.visible===!1)return;if(x.layers.test(E.layers)&&(x.isMesh||x.isLine||x.isPoints)&&(x.castShadow||x.receiveShadow&&T===ju)&&(!x.frustumCulled||i.intersectsObject(x))){x.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,x.matrixWorld);const L=e.update(x),P=x.material;if(Array.isArray(P)){const C=L.groups;for(let N=0,F=C.length;N<F;N++){const H=C[N],j=P[H.materialIndex];if(j&&j.visible){const W=w(x,j,A,T);x.onBeforeShadow(l,x,E,S,L,W,H),l.renderBufferDirect(S,null,L,W,x,H),x.onAfterShadow(l,x,E,S,L,W,H)}}}else if(P.visible){const C=w(x,P,A,T);x.onBeforeShadow(l,x,E,S,L,C,null),l.renderBufferDirect(S,null,L,C,x,null),x.onAfterShadow(l,x,E,S,L,C,null)}}const k=x.children;for(let L=0,P=k.length;L<P;L++)y(k[L],E,S,A,T)}function M(x){x.target.removeEventListener("dispose",M);for(const S in c){const A=c[S],T=x.target.uuid;T in A&&(A[T].dispose(),delete A[T])}}}function TN(l,e){function t(){let B=!1;const fe=new Lt;let se=null;const ye=new Lt(0,0,0,0);return{setMask:function(_e){se!==_e&&!B&&(l.colorMask(_e,_e,_e,_e),se=_e)},setLocked:function(_e){B=_e},setClear:function(_e,ae,Xe,ze,ps){ps===!0&&(_e*=ze,ae*=ze,Xe*=ze),fe.set(_e,ae,Xe,ze),ye.equals(fe)===!1&&(l.clearColor(_e,ae,Xe,ze),ye.copy(fe))},reset:function(){B=!1,se=null,ye.set(-1,0,0,0)}}}function i(){let B=!1,fe=!1,se=null,ye=null,_e=null;return{setReversed:function(ae){if(fe!==ae){const Xe=e.get("EXT_clip_control");ae?Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.ZERO_TO_ONE_EXT):Xe.clipControlEXT(Xe.LOWER_LEFT_EXT,Xe.NEGATIVE_ONE_TO_ONE_EXT),fe=ae;const ze=_e;_e=null,this.setClear(ze)}},getReversed:function(){return fe},setTest:function(ae){ae?le(l.DEPTH_TEST):$(l.DEPTH_TEST)},setMask:function(ae){se!==ae&&!B&&(l.depthMask(ae),se=ae)},setFunc:function(ae){if(fe&&(ae=OR[ae]),ye!==ae){switch(ae){case _b:l.depthFunc(l.NEVER);break;case Db:l.depthFunc(l.ALWAYS);break;case kb:l.depthFunc(l.LESS);break;case eu:l.depthFunc(l.LEQUAL);break;case Rb:l.depthFunc(l.EQUAL);break;case Cb:l.depthFunc(l.GEQUAL);break;case Lb:l.depthFunc(l.GREATER);break;case Ob:l.depthFunc(l.NOTEQUAL);break;default:l.depthFunc(l.LEQUAL)}ye=ae}},setLocked:function(ae){B=ae},setClear:function(ae){_e!==ae&&(_e=ae,fe&&(ae=1-ae),l.clearDepth(ae))},reset:function(){B=!1,se=null,ye=null,_e=null,fe=!1}}}function s(){let B=!1,fe=null,se=null,ye=null,_e=null,ae=null,Xe=null,ze=null,ps=null;return{setTest:function(Pi){B||(Pi?le(l.STENCIL_TEST):$(l.STENCIL_TEST))},setMask:function(Pi){fe!==Pi&&!B&&(l.stencilMask(Pi),fe=Pi)},setFunc:function(Pi,Aa,Ta){(se!==Pi||ye!==Aa||_e!==Ta)&&(l.stencilFunc(Pi,Aa,Ta),se=Pi,ye=Aa,_e=Ta)},setOp:function(Pi,Aa,Ta){(ae!==Pi||Xe!==Aa||ze!==Ta)&&(l.stencilOp(Pi,Aa,Ta),ae=Pi,Xe=Aa,ze=Ta)},setLocked:function(Pi){B=Pi},setClear:function(Pi){ps!==Pi&&(l.clearStencil(Pi),ps=Pi)},reset:function(){B=!1,fe=null,se=null,ye=null,_e=null,ae=null,Xe=null,ze=null,ps=null}}}const n=new t,r=new i,a=new s,o=new WeakMap,c=new WeakMap;let h={},d={},u={},p=new WeakMap,f=[],m=null,v=!1,g=null,b=null,w=null,y=null,M=null,x=null,E=null,S=new oe(0,0,0),A=0,T=!1,_=null,k=null,L=null,P=null,C=null;const N=l.getParameter(l.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let F=!1,H=0;const j=l.getParameter(l.VERSION);j.indexOf("WebGL")!==-1?(H=parseFloat(/^WebGL (\d)/.exec(j)[1]),F=H>=1):j.indexOf("OpenGL ES")!==-1&&(H=parseFloat(/^OpenGL ES (\d)/.exec(j)[1]),F=H>=2);let W=null,J={};const re=l.getParameter(l.SCISSOR_BOX),Le=l.getParameter(l.VIEWPORT),He=new Lt().fromArray(re),De=new Lt().fromArray(Le);function Z(B,fe,se,ye){const _e=new Uint8Array(4),ae=l.createTexture();l.bindTexture(B,ae),l.texParameteri(B,l.TEXTURE_MIN_FILTER,l.NEAREST),l.texParameteri(B,l.TEXTURE_MAG_FILTER,l.NEAREST);for(let Xe=0;Xe<se;Xe++)B===l.TEXTURE_3D||B===l.TEXTURE_2D_ARRAY?l.texImage3D(fe,0,l.RGBA,1,1,ye,0,l.RGBA,l.UNSIGNED_BYTE,_e):l.texImage2D(fe+Xe,0,l.RGBA,1,1,0,l.RGBA,l.UNSIGNED_BYTE,_e);return ae}const ce={};ce[l.TEXTURE_2D]=Z(l.TEXTURE_2D,l.TEXTURE_2D,1),ce[l.TEXTURE_CUBE_MAP]=Z(l.TEXTURE_CUBE_MAP,l.TEXTURE_CUBE_MAP_POSITIVE_X,6),ce[l.TEXTURE_2D_ARRAY]=Z(l.TEXTURE_2D_ARRAY,l.TEXTURE_2D_ARRAY,1,1),ce[l.TEXTURE_3D]=Z(l.TEXTURE_3D,l.TEXTURE_3D,1,1),n.setClear(0,0,0,1),r.setClear(1),a.setClear(0),le(l.DEPTH_TEST),r.setFunc(eu),fi(!1),mi(cS),le(l.CULL_FACE),lt(wr);function le(B){h[B]!==!0&&(l.enable(B),h[B]=!0)}function $(B){h[B]!==!1&&(l.disable(B),h[B]=!1)}function Ue(B,fe){return u[B]!==fe?(l.bindFramebuffer(B,fe),u[B]=fe,B===l.DRAW_FRAMEBUFFER&&(u[l.FRAMEBUFFER]=fe),B===l.FRAMEBUFFER&&(u[l.DRAW_FRAMEBUFFER]=fe),!0):!1}function je(B,fe){let se=f,ye=!1;if(B){se=p.get(fe),se===void 0&&(se=[],p.set(fe,se));const _e=B.textures;if(se.length!==_e.length||se[0]!==l.COLOR_ATTACHMENT0){for(let ae=0,Xe=_e.length;ae<Xe;ae++)se[ae]=l.COLOR_ATTACHMENT0+ae;se.length=_e.length,ye=!0}}else se[0]!==l.BACK&&(se[0]=l.BACK,ye=!0);ye&&l.drawBuffers(se)}function Be(B){return m!==B?(l.useProgram(B),m=B,!0):!1}const Oe={[Lo]:l.FUNC_ADD,[eR]:l.FUNC_SUBTRACT,[tR]:l.FUNC_REVERSE_SUBTRACT};Oe[iR]=l.MIN,Oe[sR]=l.MAX;const nt={[io]:l.ZERO,[sh]:l.ONE,[nR]:l.SRC_COLOR,[U0]:l.SRC_ALPHA,[hR]:l.SRC_ALPHA_SATURATE,[lR]:l.DST_COLOR,[aR]:l.DST_ALPHA,[rR]:l.ONE_MINUS_SRC_COLOR,[rf]:l.ONE_MINUS_SRC_ALPHA,[cR]:l.ONE_MINUS_DST_COLOR,[oR]:l.ONE_MINUS_DST_ALPHA,[dR]:l.CONSTANT_COLOR,[uR]:l.ONE_MINUS_CONSTANT_COLOR,[pR]:l.CONSTANT_ALPHA,[fR]:l.ONE_MINUS_CONSTANT_ALPHA};function lt(B,fe,se,ye,_e,ae,Xe,ze,ps,Pi){if(B===wr){v===!0&&($(l.BLEND),v=!1);return}if(v===!1&&(le(l.BLEND),v=!0),B!==ih){if(B!==g||Pi!==T){if((b!==Lo||M!==Lo)&&(l.blendEquation(l.FUNC_ADD),b=Lo,M=Lo),Pi)switch(B){case Zl:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case qs:l.blendFunc(l.ONE,l.ONE);break;case hS:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case dS:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:ft("WebGLState: Invalid blending: ",B);break}else switch(B){case Zl:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case qs:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case hS:ft("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case dS:ft("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ft("WebGLState: Invalid blending: ",B);break}w=null,y=null,x=null,E=null,S.set(0,0,0),A=0,g=B,T=Pi}return}_e=_e||fe,ae=ae||se,Xe=Xe||ye,(fe!==b||_e!==M)&&(l.blendEquationSeparate(Oe[fe],Oe[_e]),b=fe,M=_e),(se!==w||ye!==y||ae!==x||Xe!==E)&&(l.blendFuncSeparate(nt[se],nt[ye],nt[ae],nt[Xe]),w=se,y=ye,x=ae,E=Xe),(ze.equals(S)===!1||ps!==A)&&(l.blendColor(ze.r,ze.g,ze.b,ps),S.copy(ze),A=ps),g=B,T=!1}function ct(B,fe){B.side===$s?$(l.CULL_FACE):le(l.CULL_FACE);let se=B.side===Ji;fe&&(se=!se),fi(se),B.blending===Zl&&B.transparent===!1?lt(wr):lt(B.blending,B.blendEquation,B.blendSrc,B.blendDst,B.blendEquationAlpha,B.blendSrcAlpha,B.blendDstAlpha,B.blendColor,B.blendAlpha,B.premultipliedAlpha),r.setFunc(B.depthFunc),r.setTest(B.depthTest),r.setMask(B.depthWrite),n.setMask(B.colorWrite);const ye=B.stencilWrite;a.setTest(ye),ye&&(a.setMask(B.stencilWriteMask),a.setFunc(B.stencilFunc,B.stencilRef,B.stencilFuncMask),a.setOp(B.stencilFail,B.stencilZFail,B.stencilZPass)),ts(B.polygonOffset,B.polygonOffsetFactor,B.polygonOffsetUnits),B.alphaToCoverage===!0?le(l.SAMPLE_ALPHA_TO_COVERAGE):$(l.SAMPLE_ALPHA_TO_COVERAGE)}function fi(B){_!==B&&(B?l.frontFace(l.CW):l.frontFace(l.CCW),_=B)}function mi(B){B!==Zk?(le(l.CULL_FACE),B!==k&&(B===cS?l.cullFace(l.BACK):B===Jk?l.cullFace(l.FRONT):l.cullFace(l.FRONT_AND_BACK))):$(l.CULL_FACE),k=B}function ds(B){B!==L&&(F&&l.lineWidth(B),L=B)}function ts(B,fe,se){B?(le(l.POLYGON_OFFSET_FILL),(P!==fe||C!==se)&&(P=fe,C=se,r.getReversed()&&(fe=-fe),l.polygonOffset(fe,se))):$(l.POLYGON_OFFSET_FILL)}function us(B){B?le(l.SCISSOR_TEST):$(l.SCISSOR_TEST)}function Cs(B){B===void 0&&(B=l.TEXTURE0+N-1),W!==B&&(l.activeTexture(B),W=B)}function z(B,fe,se){se===void 0&&(W===null?se=l.TEXTURE0+N-1:se=W);let ye=J[se];ye===void 0&&(ye={type:void 0,texture:void 0},J[se]=ye),(ye.type!==B||ye.texture!==fe)&&(W!==se&&(l.activeTexture(se),W=se),l.bindTexture(B,fe||ce[B]),ye.type=B,ye.texture=fe)}function ar(){const B=J[W];B!==void 0&&B.type!==void 0&&(l.bindTexture(B.type,null),B.type=void 0,B.texture=void 0)}function gi(){try{l.compressedTexImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function O(){try{l.compressedTexImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function I(){try{l.texSubImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function V(){try{l.texSubImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function Y(){try{l.compressedTexSubImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function ee(){try{l.compressedTexSubImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function de(){try{l.texStorage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function me(){try{l.texStorage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function te(){try{l.texImage2D(...arguments)}catch(B){ft("WebGLState:",B)}}function ne(){try{l.texImage3D(...arguments)}catch(B){ft("WebGLState:",B)}}function ve(B){return d[B]!==void 0?d[B]:l.getParameter(B)}function Ze(B,fe){d[B]!==fe&&(l.pixelStorei(B,fe),d[B]=fe)}function Ee(B){He.equals(B)===!1&&(l.scissor(B.x,B.y,B.z,B.w),He.copy(B))}function be(B){De.equals(B)===!1&&(l.viewport(B.x,B.y,B.z,B.w),De.copy(B))}function it(B,fe){let se=c.get(fe);se===void 0&&(se=new WeakMap,c.set(fe,se));let ye=se.get(B);ye===void 0&&(ye=l.getUniformBlockIndex(fe,B.name),se.set(B,ye))}function dt(B,fe){const ye=c.get(fe).get(B);o.get(fe)!==ye&&(l.uniformBlockBinding(fe,ye,B.__bindingPointIndex),o.set(fe,ye))}function Dt(){l.disable(l.BLEND),l.disable(l.CULL_FACE),l.disable(l.DEPTH_TEST),l.disable(l.POLYGON_OFFSET_FILL),l.disable(l.SCISSOR_TEST),l.disable(l.STENCIL_TEST),l.disable(l.SAMPLE_ALPHA_TO_COVERAGE),l.blendEquation(l.FUNC_ADD),l.blendFunc(l.ONE,l.ZERO),l.blendFuncSeparate(l.ONE,l.ZERO,l.ONE,l.ZERO),l.blendColor(0,0,0,0),l.colorMask(!0,!0,!0,!0),l.clearColor(0,0,0,0),l.depthMask(!0),l.depthFunc(l.LESS),r.setReversed(!1),l.clearDepth(1),l.stencilMask(4294967295),l.stencilFunc(l.ALWAYS,0,4294967295),l.stencilOp(l.KEEP,l.KEEP,l.KEEP),l.clearStencil(0),l.cullFace(l.BACK),l.frontFace(l.CCW),l.polygonOffset(0,0),l.activeTexture(l.TEXTURE0),l.bindFramebuffer(l.FRAMEBUFFER,null),l.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),l.bindFramebuffer(l.READ_FRAMEBUFFER,null),l.useProgram(null),l.lineWidth(1),l.scissor(0,0,l.canvas.width,l.canvas.height),l.viewport(0,0,l.canvas.width,l.canvas.height),l.pixelStorei(l.PACK_ALIGNMENT,4),l.pixelStorei(l.UNPACK_ALIGNMENT,4),l.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,!1),l.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),l.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,l.BROWSER_DEFAULT_WEBGL),l.pixelStorei(l.PACK_ROW_LENGTH,0),l.pixelStorei(l.PACK_SKIP_PIXELS,0),l.pixelStorei(l.PACK_SKIP_ROWS,0),l.pixelStorei(l.UNPACK_ROW_LENGTH,0),l.pixelStorei(l.UNPACK_IMAGE_HEIGHT,0),l.pixelStorei(l.UNPACK_SKIP_PIXELS,0),l.pixelStorei(l.UNPACK_SKIP_ROWS,0),l.pixelStorei(l.UNPACK_SKIP_IMAGES,0),h={},d={},W=null,J={},u={},p=new WeakMap,f=[],m=null,v=!1,g=null,b=null,w=null,y=null,M=null,x=null,E=null,S=new oe(0,0,0),A=0,T=!1,_=null,k=null,L=null,P=null,C=null,He.set(0,0,l.canvas.width,l.canvas.height),De.set(0,0,l.canvas.width,l.canvas.height),n.reset(),r.reset(),a.reset()}return{buffers:{color:n,depth:r,stencil:a},enable:le,disable:$,bindFramebuffer:Ue,drawBuffers:je,useProgram:Be,setBlending:lt,setMaterial:ct,setFlipSided:fi,setCullFace:mi,setLineWidth:ds,setPolygonOffset:ts,setScissorTest:us,activeTexture:Cs,bindTexture:z,unbindTexture:ar,compressedTexImage2D:gi,compressedTexImage3D:O,texImage2D:te,texImage3D:ne,pixelStorei:Ze,getParameter:ve,updateUBOMapping:it,uniformBlockBinding:dt,texStorage2D:de,texStorage3D:me,texSubImage2D:I,texSubImage3D:V,compressedTexSubImage2D:Y,compressedTexSubImage3D:ee,scissor:Ee,viewport:be,reset:Dt}}function IN(l,e,t,i,s,n,r){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,o=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ie,h=new WeakMap,d=new Set;let u;const p=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function m(O,I){return f?new OffscreenCanvas(O,I):cf("canvas")}function v(O,I,V){let Y=1;const ee=gi(O);if((ee.width>V||ee.height>V)&&(Y=V/Math.max(ee.width,ee.height)),Y<1)if(typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&O instanceof ImageBitmap||typeof VideoFrame<"u"&&O instanceof VideoFrame){const de=Math.floor(Y*ee.width),me=Math.floor(Y*ee.height);u===void 0&&(u=m(de,me));const te=I?m(de,me):u;return te.width=de,te.height=me,te.getContext("2d").drawImage(O,0,0,de,me),We("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+de+"x"+me+")."),te}else return"data"in O&&We("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),O;return O}function g(O){return O.generateMipmaps}function b(O){l.generateMipmap(O)}function w(O){return O.isWebGLCubeRenderTarget?l.TEXTURE_CUBE_MAP:O.isWebGL3DRenderTarget?l.TEXTURE_3D:O.isWebGLArrayRenderTarget||O.isCompressedArrayTexture?l.TEXTURE_2D_ARRAY:l.TEXTURE_2D}function y(O,I,V,Y,ee,de=!1){if(O!==null){if(l[O]!==void 0)return l[O];We("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+O+"'")}let me;Y&&(me=e.get("EXT_texture_norm16"),me||We("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let te=I;if(I===l.RED&&(V===l.FLOAT&&(te=l.R32F),V===l.HALF_FLOAT&&(te=l.R16F),V===l.UNSIGNED_BYTE&&(te=l.R8),V===l.UNSIGNED_SHORT&&me&&(te=me.R16_EXT),V===l.SHORT&&me&&(te=me.R16_SNORM_EXT)),I===l.RED_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.R8UI),V===l.UNSIGNED_SHORT&&(te=l.R16UI),V===l.UNSIGNED_INT&&(te=l.R32UI),V===l.BYTE&&(te=l.R8I),V===l.SHORT&&(te=l.R16I),V===l.INT&&(te=l.R32I)),I===l.RG&&(V===l.FLOAT&&(te=l.RG32F),V===l.HALF_FLOAT&&(te=l.RG16F),V===l.UNSIGNED_BYTE&&(te=l.RG8),V===l.UNSIGNED_SHORT&&me&&(te=me.RG16_EXT),V===l.SHORT&&me&&(te=me.RG16_SNORM_EXT)),I===l.RG_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RG8UI),V===l.UNSIGNED_SHORT&&(te=l.RG16UI),V===l.UNSIGNED_INT&&(te=l.RG32UI),V===l.BYTE&&(te=l.RG8I),V===l.SHORT&&(te=l.RG16I),V===l.INT&&(te=l.RG32I)),I===l.RGB_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RGB8UI),V===l.UNSIGNED_SHORT&&(te=l.RGB16UI),V===l.UNSIGNED_INT&&(te=l.RGB32UI),V===l.BYTE&&(te=l.RGB8I),V===l.SHORT&&(te=l.RGB16I),V===l.INT&&(te=l.RGB32I)),I===l.RGBA_INTEGER&&(V===l.UNSIGNED_BYTE&&(te=l.RGBA8UI),V===l.UNSIGNED_SHORT&&(te=l.RGBA16UI),V===l.UNSIGNED_INT&&(te=l.RGBA32UI),V===l.BYTE&&(te=l.RGBA8I),V===l.SHORT&&(te=l.RGBA16I),V===l.INT&&(te=l.RGBA32I)),I===l.RGB&&(V===l.UNSIGNED_SHORT&&me&&(te=me.RGB16_EXT),V===l.SHORT&&me&&(te=me.RGB16_SNORM_EXT),V===l.UNSIGNED_INT_5_9_9_9_REV&&(te=l.RGB9_E5),V===l.UNSIGNED_INT_10F_11F_11F_REV&&(te=l.R11F_G11F_B10F)),I===l.RGBA){const ne=de?$0:Kt.getTransfer(ee);V===l.FLOAT&&(te=l.RGBA32F),V===l.HALF_FLOAT&&(te=l.RGBA16F),V===l.UNSIGNED_BYTE&&(te=ne===Si?l.SRGB8_ALPHA8:l.RGBA8),V===l.UNSIGNED_SHORT&&me&&(te=me.RGBA16_EXT),V===l.SHORT&&me&&(te=me.RGBA16_SNORM_EXT),V===l.UNSIGNED_SHORT_4_4_4_4&&(te=l.RGBA4),V===l.UNSIGNED_SHORT_5_5_5_1&&(te=l.RGB5_A1)}return(te===l.R16F||te===l.R32F||te===l.RG16F||te===l.RG32F||te===l.RGBA16F||te===l.RGBA32F)&&e.get("EXT_color_buffer_float"),te}function M(O,I){let V;return O?I===null||I===Qr||I===of?V=l.DEPTH24_STENCIL8:I===yn?V=l.DEPTH32F_STENCIL8:I===af&&(V=l.DEPTH24_STENCIL8,We("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):I===null||I===Qr||I===of?V=l.DEPTH_COMPONENT24:I===yn?V=l.DEPTH_COMPONENT32F:I===af&&(V=l.DEPTH_COMPONENT16),V}function x(O,I){return g(O)===!0||O.isFramebufferTexture&&O.minFilter!==pi&&O.minFilter!==St?Math.log2(Math.max(I.width,I.height))+1:O.mipmaps!==void 0&&O.mipmaps.length>0?O.mipmaps.length:O.isCompressedTexture&&Array.isArray(O.image)?I.mipmaps.length:1}function E(O){const I=O.target;I.removeEventListener("dispose",E),A(I),I.isVideoTexture&&h.delete(I),I.isHTMLTexture&&d.delete(I)}function S(O){const I=O.target;I.removeEventListener("dispose",S),_(I)}function A(O){const I=i.get(O);if(I.__webglInit===void 0)return;const V=O.source,Y=p.get(V);if(Y){const ee=Y[I.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&T(O),Object.keys(Y).length===0&&p.delete(V)}i.remove(O)}function T(O){const I=i.get(O);l.deleteTexture(I.__webglTexture);const V=O.source,Y=p.get(V);delete Y[I.__cacheKey],r.memory.textures--}function _(O){const I=i.get(O);if(O.depthTexture&&(O.depthTexture.dispose(),i.remove(O.depthTexture)),O.isWebGLCubeRenderTarget)for(let Y=0;Y<6;Y++){if(Array.isArray(I.__webglFramebuffer[Y]))for(let ee=0;ee<I.__webglFramebuffer[Y].length;ee++)l.deleteFramebuffer(I.__webglFramebuffer[Y][ee]);else l.deleteFramebuffer(I.__webglFramebuffer[Y]);I.__webglDepthbuffer&&l.deleteRenderbuffer(I.__webglDepthbuffer[Y])}else{if(Array.isArray(I.__webglFramebuffer))for(let Y=0;Y<I.__webglFramebuffer.length;Y++)l.deleteFramebuffer(I.__webglFramebuffer[Y]);else l.deleteFramebuffer(I.__webglFramebuffer);if(I.__webglDepthbuffer&&l.deleteRenderbuffer(I.__webglDepthbuffer),I.__webglMultisampledFramebuffer&&l.deleteFramebuffer(I.__webglMultisampledFramebuffer),I.__webglColorRenderbuffer)for(let Y=0;Y<I.__webglColorRenderbuffer.length;Y++)I.__webglColorRenderbuffer[Y]&&l.deleteRenderbuffer(I.__webglColorRenderbuffer[Y]);I.__webglDepthRenderbuffer&&l.deleteRenderbuffer(I.__webglDepthRenderbuffer)}const V=O.textures;for(let Y=0,ee=V.length;Y<ee;Y++){const de=i.get(V[Y]);de.__webglTexture&&(l.deleteTexture(de.__webglTexture),r.memory.textures--),i.remove(V[Y])}i.remove(O)}let k=0;function L(){k=0}function P(){return k}function C(O){k=O}function N(){const O=k;return O>=s.maxTextures&&We("WebGLTextures: Trying to use "+O+" texture units while this GPU supports only "+s.maxTextures),k+=1,O}function F(O){const I=[];return I.push(O.wrapS),I.push(O.wrapT),I.push(O.wrapR||0),I.push(O.magFilter),I.push(O.minFilter),I.push(O.anisotropy),I.push(O.internalFormat),I.push(O.format),I.push(O.type),I.push(O.generateMipmaps),I.push(O.premultiplyAlpha),I.push(O.flipY),I.push(O.unpackAlignment),I.push(O.colorSpace),I.join()}function H(O,I){const V=i.get(O);if(O.isVideoTexture&&z(O),O.isRenderTargetTexture===!1&&O.isExternalTexture!==!0&&O.version>0&&V.__version!==O.version){const Y=O.image;if(Y===null)We("WebGLRenderer: Texture marked for update but no image data found.");else if(Y.complete===!1)We("WebGLRenderer: Texture marked for update but image is incomplete");else{$(V,O,I);return}}else O.isExternalTexture&&(V.__webglTexture=O.sourceTexture?O.sourceTexture:null);t.bindTexture(l.TEXTURE_2D,V.__webglTexture,l.TEXTURE0+I)}function j(O,I){const V=i.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&V.__version!==O.version){$(V,O,I);return}else O.isExternalTexture&&(V.__webglTexture=O.sourceTexture?O.sourceTexture:null);t.bindTexture(l.TEXTURE_2D_ARRAY,V.__webglTexture,l.TEXTURE0+I)}function W(O,I){const V=i.get(O);if(O.isRenderTargetTexture===!1&&O.version>0&&V.__version!==O.version){$(V,O,I);return}t.bindTexture(l.TEXTURE_3D,V.__webglTexture,l.TEXTURE0+I)}function J(O,I){const V=i.get(O);if(O.isCubeDepthTexture!==!0&&O.version>0&&V.__version!==O.version){Ue(V,O,I);return}t.bindTexture(l.TEXTURE_CUBE_MAP,V.__webglTexture,l.TEXTURE0+I)}const re={[sc]:l.REPEAT,[Ms]:l.CLAMP_TO_EDGE,[Pb]:l.MIRRORED_REPEAT},Le={[pi]:l.NEAREST,[bR]:l.NEAREST_MIPMAP_NEAREST,[Ff]:l.NEAREST_MIPMAP_LINEAR,[St]:l.LINEAR,[wv]:l.LINEAR_MIPMAP_NEAREST,[Nr]:l.LINEAR_MIPMAP_LINEAR},He={[ER]:l.NEVER,[DR]:l.ALWAYS,[AR]:l.LESS,[kw]:l.LEQUAL,[TR]:l.EQUAL,[Rw]:l.GEQUAL,[IR]:l.GREATER,[_R]:l.NOTEQUAL};function De(O,I){if(I.type===yn&&e.has("OES_texture_float_linear")===!1&&(I.magFilter===St||I.magFilter===wv||I.magFilter===Ff||I.magFilter===Nr||I.minFilter===St||I.minFilter===wv||I.minFilter===Ff||I.minFilter===Nr)&&We("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),l.texParameteri(O,l.TEXTURE_WRAP_S,re[I.wrapS]),l.texParameteri(O,l.TEXTURE_WRAP_T,re[I.wrapT]),(O===l.TEXTURE_3D||O===l.TEXTURE_2D_ARRAY)&&l.texParameteri(O,l.TEXTURE_WRAP_R,re[I.wrapR]),l.texParameteri(O,l.TEXTURE_MAG_FILTER,Le[I.magFilter]),l.texParameteri(O,l.TEXTURE_MIN_FILTER,Le[I.minFilter]),I.compareFunction&&(l.texParameteri(O,l.TEXTURE_COMPARE_MODE,l.COMPARE_REF_TO_TEXTURE),l.texParameteri(O,l.TEXTURE_COMPARE_FUNC,He[I.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(I.magFilter===pi||I.minFilter!==Ff&&I.minFilter!==Nr||I.type===yn&&e.has("OES_texture_float_linear")===!1)return;if(I.anisotropy>1||i.get(I).__currentAnisotropy){const V=e.get("EXT_texture_filter_anisotropic");l.texParameterf(O,V.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(I.anisotropy,s.getMaxAnisotropy())),i.get(I).__currentAnisotropy=I.anisotropy}}}function Z(O,I){let V=!1;O.__webglInit===void 0&&(O.__webglInit=!0,I.addEventListener("dispose",E));const Y=I.source;let ee=p.get(Y);ee===void 0&&(ee={},p.set(Y,ee));const de=F(I);if(de!==O.__cacheKey){ee[de]===void 0&&(ee[de]={texture:l.createTexture(),usedTimes:0},r.memory.textures++,V=!0),ee[de].usedTimes++;const me=ee[O.__cacheKey];me!==void 0&&(ee[O.__cacheKey].usedTimes--,me.usedTimes===0&&T(I)),O.__cacheKey=de,O.__webglTexture=ee[de].texture}return V}function ce(O,I,V){return Math.floor(Math.floor(O/V)/I)}function le(O,I,V,Y){const de=O.updateRanges;if(de.length===0)t.texSubImage2D(l.TEXTURE_2D,0,0,0,I.width,I.height,V,Y,I.data);else{de.sort((Ze,Ee)=>Ze.start-Ee.start);let me=0;for(let Ze=1;Ze<de.length;Ze++){const Ee=de[me],be=de[Ze],it=Ee.start+Ee.count,dt=ce(be.start,I.width,4),Dt=ce(Ee.start,I.width,4);be.start<=it+1&&dt===Dt&&ce(be.start+be.count-1,I.width,4)===dt?Ee.count=Math.max(Ee.count,be.start+be.count-Ee.start):(++me,de[me]=be)}de.length=me+1;const te=t.getParameter(l.UNPACK_ROW_LENGTH),ne=t.getParameter(l.UNPACK_SKIP_PIXELS),ve=t.getParameter(l.UNPACK_SKIP_ROWS);t.pixelStorei(l.UNPACK_ROW_LENGTH,I.width);for(let Ze=0,Ee=de.length;Ze<Ee;Ze++){const be=de[Ze],it=Math.floor(be.start/4),dt=Math.ceil(be.count/4),Dt=it%I.width,B=Math.floor(it/I.width),fe=dt,se=1;t.pixelStorei(l.UNPACK_SKIP_PIXELS,Dt),t.pixelStorei(l.UNPACK_SKIP_ROWS,B),t.texSubImage2D(l.TEXTURE_2D,0,Dt,B,fe,se,V,Y,I.data)}O.clearUpdateRanges(),t.pixelStorei(l.UNPACK_ROW_LENGTH,te),t.pixelStorei(l.UNPACK_SKIP_PIXELS,ne),t.pixelStorei(l.UNPACK_SKIP_ROWS,ve)}}function $(O,I,V){let Y=l.TEXTURE_2D;(I.isDataArrayTexture||I.isCompressedArrayTexture)&&(Y=l.TEXTURE_2D_ARRAY),I.isData3DTexture&&(Y=l.TEXTURE_3D);const ee=Z(O,I),de=I.source;t.bindTexture(Y,O.__webglTexture,l.TEXTURE0+V);const me=i.get(de);if(de.version!==me.__version||ee===!0){if(t.activeTexture(l.TEXTURE0+V),(typeof ImageBitmap<"u"&&I.image instanceof ImageBitmap)===!1){const se=Kt.getPrimaries(Kt.workingColorSpace),ye=I.colorSpace===Rl?null:Kt.getPrimaries(I.colorSpace),_e=I.colorSpace===Rl||se===ye?l.NONE:l.BROWSER_DEFAULT_WEBGL;t.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,I.flipY),t.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,I.premultiplyAlpha),t.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,_e)}t.pixelStorei(l.UNPACK_ALIGNMENT,I.unpackAlignment);let ne=v(I.image,!1,s.maxTextureSize);ne=ar(I,ne);const ve=n.convert(I.format,I.colorSpace),Ze=n.convert(I.type);let Ee=y(I.internalFormat,ve,Ze,I.normalized,I.colorSpace,I.isVideoTexture);De(Y,I);let be;const it=I.mipmaps,dt=I.isVideoTexture!==!0,Dt=me.__version===void 0||ee===!0,B=de.dataReady,fe=x(I,ne);if(I.isDepthTexture)Ee=M(I.format===Fc,I.type),Dt&&(dt?t.texStorage2D(l.TEXTURE_2D,1,Ee,ne.width,ne.height):t.texImage2D(l.TEXTURE_2D,0,Ee,ne.width,ne.height,0,ve,Ze,null));else if(I.isDataTexture)if(it.length>0){dt&&Dt&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,it[0].width,it[0].height);for(let se=0,ye=it.length;se<ye;se++)be=it[se],dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,Ze,be.data):t.texImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,ve,Ze,be.data);I.generateMipmaps=!1}else dt?(Dt&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,ne.width,ne.height),B&&le(I,ne,ve,Ze)):t.texImage2D(l.TEXTURE_2D,0,Ee,ne.width,ne.height,0,ve,Ze,ne.data);else if(I.isCompressedTexture)if(I.isCompressedArrayTexture){dt&&Dt&&t.texStorage3D(l.TEXTURE_2D_ARRAY,fe,Ee,it[0].width,it[0].height,ne.depth);for(let se=0,ye=it.length;se<ye;se++)if(be=it[se],I.format!==xs)if(ve!==null)if(dt){if(B)if(I.layerUpdates.size>0){const _e=pE(be.width,be.height,I.format,I.type);for(const ae of I.layerUpdates){const Xe=be.data.subarray(ae*_e/be.data.BYTES_PER_ELEMENT,(ae+1)*_e/be.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,ae,be.width,be.height,1,ve,Xe)}I.clearLayerUpdates()}else t.compressedTexSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,0,be.width,be.height,ne.depth,ve,be.data)}else t.compressedTexImage3D(l.TEXTURE_2D_ARRAY,se,Ee,be.width,be.height,ne.depth,0,be.data,0,0);else We("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else dt?B&&t.texSubImage3D(l.TEXTURE_2D_ARRAY,se,0,0,0,be.width,be.height,ne.depth,ve,Ze,be.data):t.texImage3D(l.TEXTURE_2D_ARRAY,se,Ee,be.width,be.height,ne.depth,0,ve,Ze,be.data)}else{dt&&Dt&&t.texStorage2D(l.TEXTURE_2D,fe,Ee,it[0].width,it[0].height);for(let se=0,ye=it.length;se<ye;se++)be=it[se],I.format!==xs?ve!==null?dt?B&&t.compressedTexSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,be.data):t.compressedTexImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,be.data):We("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,be.width,be.height,ve,Ze,be.data):t.texImage2D(l.TEXTURE_2D,se,Ee,be.width,be.height,0,ve,Ze,be.data)}else if(I.isDataArrayTexture)if(dt){if(Dt&&t.texStorage3D(l.TEXTURE_2D_ARRAY,fe,Ee,ne.width,ne.height,ne.depth),B)if(I.layerUpdates.size>0){const se=pE(ne.width,ne.height,I.format,I.type);for(const ye of I.layerUpdates){const _e=ne.data.subarray(ye*se/ne.data.BYTES_PER_ELEMENT,(ye+1)*se/ne.data.BYTES_PER_ELEMENT);t.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,ye,ne.width,ne.height,1,ve,Ze,_e)}I.clearLayerUpdates()}else t.texSubImage3D(l.TEXTURE_2D_ARRAY,0,0,0,0,ne.width,ne.height,ne.depth,ve,Ze,ne.data)}else t.texImage3D(l.TEXTURE_2D_ARRAY,0,Ee,ne.width,ne.height,ne.depth,0,ve,Ze,ne.data);else if(I.isData3DTexture)dt?(Dt&&t.texStorage3D(l.TEXTURE_3D,fe,Ee,ne.width,ne.height,ne.depth),B&&t.texSubImage3D(l.TEXTURE_3D,0,0,0,0,ne.width,ne.height,ne.depth,ve,Ze,ne.data)):t.texImage3D(l.TEXTURE_3D,0,Ee,ne.width,ne.height,ne.depth,0,ve,Ze,ne.data);else if(I.isFramebufferTexture){if(Dt)if(dt)t.texStorage2D(l.TEXTURE_2D,fe,Ee,ne.width,ne.height);else{let se=ne.width,ye=ne.height;for(let _e=0;_e<fe;_e++)t.texImage2D(l.TEXTURE_2D,_e,Ee,se,ye,0,ve,Ze,null),se>>=1,ye>>=1}}else if(I.isHTMLTexture){if("texElementImage2D"in l){const se=l.canvas;if(se.hasAttribute("layoutsubtree")||se.setAttribute("layoutsubtree","true"),ne.parentNode!==se){se.appendChild(ne),d.add(I),se.onpaint=ye=>{const _e=ye.changedElements;for(const ae of d)_e.includes(ae.image)&&(ae.needsUpdate=!0)},se.requestPaint();return}if(l.texElementImage2D.length===3)l.texElementImage2D(l.TEXTURE_2D,l.RGBA8,ne);else{const _e=l.RGBA,ae=l.RGBA,Xe=l.UNSIGNED_BYTE;l.texElementImage2D(l.TEXTURE_2D,0,_e,ae,Xe,ne)}l.texParameteri(l.TEXTURE_2D,l.TEXTURE_MIN_FILTER,l.LINEAR),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE)}}else if(it.length>0){if(dt&&Dt){const se=gi(it[0]);t.texStorage2D(l.TEXTURE_2D,fe,Ee,se.width,se.height)}for(let se=0,ye=it.length;se<ye;se++)be=it[se],dt?B&&t.texSubImage2D(l.TEXTURE_2D,se,0,0,ve,Ze,be):t.texImage2D(l.TEXTURE_2D,se,Ee,ve,Ze,be);I.generateMipmaps=!1}else if(dt){if(Dt){const se=gi(ne);t.texStorage2D(l.TEXTURE_2D,fe,Ee,se.width,se.height)}B&&t.texSubImage2D(l.TEXTURE_2D,0,0,0,ve,Ze,ne)}else t.texImage2D(l.TEXTURE_2D,0,Ee,ve,Ze,ne);g(I)&&b(Y),me.__version=de.version,I.onUpdate&&I.onUpdate(I)}O.__version=I.version}function Ue(O,I,V){if(I.image.length!==6)return;const Y=Z(O,I),ee=I.source;t.bindTexture(l.TEXTURE_CUBE_MAP,O.__webglTexture,l.TEXTURE0+V);const de=i.get(ee);if(ee.version!==de.__version||Y===!0){t.activeTexture(l.TEXTURE0+V);const me=Kt.getPrimaries(Kt.workingColorSpace),te=I.colorSpace===Rl?null:Kt.getPrimaries(I.colorSpace),ne=I.colorSpace===Rl||me===te?l.NONE:l.BROWSER_DEFAULT_WEBGL;t.pixelStorei(l.UNPACK_FLIP_Y_WEBGL,I.flipY),t.pixelStorei(l.UNPACK_PREMULTIPLY_ALPHA_WEBGL,I.premultiplyAlpha),t.pixelStorei(l.UNPACK_ALIGNMENT,I.unpackAlignment),t.pixelStorei(l.UNPACK_COLORSPACE_CONVERSION_WEBGL,ne);const ve=I.isCompressedTexture||I.image[0].isCompressedTexture,Ze=I.image[0]&&I.image[0].isDataTexture,Ee=[];for(let ae=0;ae<6;ae++)!ve&&!Ze?Ee[ae]=v(I.image[ae],!0,s.maxCubemapSize):Ee[ae]=Ze?I.image[ae].image:I.image[ae],Ee[ae]=ar(I,Ee[ae]);const be=Ee[0],it=n.convert(I.format,I.colorSpace),dt=n.convert(I.type),Dt=y(I.internalFormat,it,dt,I.normalized,I.colorSpace),B=I.isVideoTexture!==!0,fe=de.__version===void 0||Y===!0,se=ee.dataReady;let ye=x(I,be);De(l.TEXTURE_CUBE_MAP,I);let _e;if(ve){B&&fe&&t.texStorage2D(l.TEXTURE_CUBE_MAP,ye,Dt,be.width,be.height);for(let ae=0;ae<6;ae++){_e=Ee[ae].mipmaps;for(let Xe=0;Xe<_e.length;Xe++){const ze=_e[Xe];I.format!==xs?it!==null?B?se&&t.compressedTexSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,0,0,ze.width,ze.height,it,ze.data):t.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,Dt,ze.width,ze.height,0,ze.data):We("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,0,0,ze.width,ze.height,it,dt,ze.data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe,Dt,ze.width,ze.height,0,it,dt,ze.data)}}}else{if(_e=I.mipmaps,B&&fe){_e.length>0&&ye++;const ae=gi(Ee[0]);t.texStorage2D(l.TEXTURE_CUBE_MAP,ye,Dt,ae.width,ae.height)}for(let ae=0;ae<6;ae++)if(Ze){B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,0,0,Ee[ae].width,Ee[ae].height,it,dt,Ee[ae].data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,Dt,Ee[ae].width,Ee[ae].height,0,it,dt,Ee[ae].data);for(let Xe=0;Xe<_e.length;Xe++){const ps=_e[Xe].image[ae].image;B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,0,0,ps.width,ps.height,it,dt,ps.data):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,Dt,ps.width,ps.height,0,it,dt,ps.data)}}else{B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,0,0,it,dt,Ee[ae]):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,Dt,it,dt,Ee[ae]);for(let Xe=0;Xe<_e.length;Xe++){const ze=_e[Xe];B?se&&t.texSubImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,0,0,it,dt,ze.image[ae]):t.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+ae,Xe+1,Dt,it,dt,ze.image[ae])}}}g(I)&&b(l.TEXTURE_CUBE_MAP),de.__version=ee.version,I.onUpdate&&I.onUpdate(I)}O.__version=I.version}function je(O,I,V,Y,ee,de){const me=n.convert(V.format,V.colorSpace),te=n.convert(V.type),ne=y(V.internalFormat,me,te,V.normalized,V.colorSpace),ve=i.get(I),Ze=i.get(V);if(Ze.__renderTarget=I,!ve.__hasExternalTextures){const Ee=Math.max(1,I.width>>de),be=Math.max(1,I.height>>de);ee===l.TEXTURE_3D||ee===l.TEXTURE_2D_ARRAY?t.texImage3D(ee,de,ne,Ee,be,I.depth,0,me,te,null):t.texImage2D(ee,de,ne,Ee,be,0,me,te,null)}t.bindFramebuffer(l.FRAMEBUFFER,O),Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,Y,ee,Ze.__webglTexture,0,us(I)):(ee===l.TEXTURE_2D||ee>=l.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=l.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&l.framebufferTexture2D(l.FRAMEBUFFER,Y,ee,Ze.__webglTexture,de),t.bindFramebuffer(l.FRAMEBUFFER,null)}function Be(O,I,V){if(l.bindRenderbuffer(l.RENDERBUFFER,O),I.depthBuffer){const Y=I.depthTexture,ee=Y&&Y.isDepthTexture?Y.type:null,de=M(I.stencilBuffer,ee),me=I.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;Cs(I)?a.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,us(I),de,I.width,I.height):V?l.renderbufferStorageMultisample(l.RENDERBUFFER,us(I),de,I.width,I.height):l.renderbufferStorage(l.RENDERBUFFER,de,I.width,I.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,me,l.RENDERBUFFER,O)}else{const Y=I.textures;for(let ee=0;ee<Y.length;ee++){const de=Y[ee],me=n.convert(de.format,de.colorSpace),te=n.convert(de.type),ne=y(de.internalFormat,me,te,de.normalized,de.colorSpace);Cs(I)?a.renderbufferStorageMultisampleEXT(l.RENDERBUFFER,us(I),ne,I.width,I.height):V?l.renderbufferStorageMultisample(l.RENDERBUFFER,us(I),ne,I.width,I.height):l.renderbufferStorage(l.RENDERBUFFER,ne,I.width,I.height)}}l.bindRenderbuffer(l.RENDERBUFFER,null)}function Oe(O,I,V){const Y=I.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(l.FRAMEBUFFER,O),!(I.depthTexture&&I.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const ee=i.get(I.depthTexture);if(ee.__renderTarget=I,(!ee.__webglTexture||I.depthTexture.image.width!==I.width||I.depthTexture.image.height!==I.height)&&(I.depthTexture.image.width=I.width,I.depthTexture.image.height=I.height,I.depthTexture.needsUpdate=!0),Y){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,I.depthTexture.addEventListener("dispose",E)),ee.__webglTexture===void 0){ee.__webglTexture=l.createTexture(),t.bindTexture(l.TEXTURE_CUBE_MAP,ee.__webglTexture),De(l.TEXTURE_CUBE_MAP,I.depthTexture);const ve=n.convert(I.depthTexture.format),Ze=n.convert(I.depthTexture.type);let Ee;I.depthTexture.format===Zo?Ee=l.DEPTH_COMPONENT24:I.depthTexture.format===Fc&&(Ee=l.DEPTH24_STENCIL8);for(let be=0;be<6;be++)l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+be,0,Ee,I.width,I.height,0,ve,Ze,null)}}else H(I.depthTexture,0);const de=ee.__webglTexture,me=us(I),te=Y?l.TEXTURE_CUBE_MAP_POSITIVE_X+V:l.TEXTURE_2D,ne=I.depthTexture.format===Fc?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;if(I.depthTexture.format===Zo)Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,ne,te,de,0,me):l.framebufferTexture2D(l.FRAMEBUFFER,ne,te,de,0);else if(I.depthTexture.format===Fc)Cs(I)?a.framebufferTexture2DMultisampleEXT(l.FRAMEBUFFER,ne,te,de,0,me):l.framebufferTexture2D(l.FRAMEBUFFER,ne,te,de,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function nt(O){const I=i.get(O),V=O.isWebGLCubeRenderTarget===!0;if(I.__boundDepthTexture!==O.depthTexture){const Y=O.depthTexture;if(I.__depthDisposeCallback&&I.__depthDisposeCallback(),Y){const ee=()=>{delete I.__boundDepthTexture,delete I.__depthDisposeCallback,Y.removeEventListener("dispose",ee)};Y.addEventListener("dispose",ee),I.__depthDisposeCallback=ee}I.__boundDepthTexture=Y}if(O.depthTexture&&!I.__autoAllocateDepthBuffer)if(V)for(let Y=0;Y<6;Y++)Oe(I.__webglFramebuffer[Y],O,Y);else{const Y=O.texture.mipmaps;Y&&Y.length>0?Oe(I.__webglFramebuffer[0],O,0):Oe(I.__webglFramebuffer,O,0)}else if(V){I.__webglDepthbuffer=[];for(let Y=0;Y<6;Y++)if(t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer[Y]),I.__webglDepthbuffer[Y]===void 0)I.__webglDepthbuffer[Y]=l.createRenderbuffer(),Be(I.__webglDepthbuffer[Y],O,!1);else{const ee=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,de=I.__webglDepthbuffer[Y];l.bindRenderbuffer(l.RENDERBUFFER,de),l.framebufferRenderbuffer(l.FRAMEBUFFER,ee,l.RENDERBUFFER,de)}}else{const Y=O.texture.mipmaps;if(Y&&Y.length>0?t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer[0]):t.bindFramebuffer(l.FRAMEBUFFER,I.__webglFramebuffer),I.__webglDepthbuffer===void 0)I.__webglDepthbuffer=l.createRenderbuffer(),Be(I.__webglDepthbuffer,O,!1);else{const ee=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,de=I.__webglDepthbuffer;l.bindRenderbuffer(l.RENDERBUFFER,de),l.framebufferRenderbuffer(l.FRAMEBUFFER,ee,l.RENDERBUFFER,de)}}t.bindFramebuffer(l.FRAMEBUFFER,null)}function lt(O,I,V){const Y=i.get(O);I!==void 0&&je(Y.__webglFramebuffer,O,O.texture,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,0),V!==void 0&&nt(O)}function ct(O){const I=O.texture,V=i.get(O),Y=i.get(I);O.addEventListener("dispose",S);const ee=O.textures,de=O.isWebGLCubeRenderTarget===!0,me=ee.length>1;if(me||(Y.__webglTexture===void 0&&(Y.__webglTexture=l.createTexture()),Y.__version=I.version,r.memory.textures++),de){V.__webglFramebuffer=[];for(let te=0;te<6;te++)if(I.mipmaps&&I.mipmaps.length>0){V.__webglFramebuffer[te]=[];for(let ne=0;ne<I.mipmaps.length;ne++)V.__webglFramebuffer[te][ne]=l.createFramebuffer()}else V.__webglFramebuffer[te]=l.createFramebuffer()}else{if(I.mipmaps&&I.mipmaps.length>0){V.__webglFramebuffer=[];for(let te=0;te<I.mipmaps.length;te++)V.__webglFramebuffer[te]=l.createFramebuffer()}else V.__webglFramebuffer=l.createFramebuffer();if(me)for(let te=0,ne=ee.length;te<ne;te++){const ve=i.get(ee[te]);ve.__webglTexture===void 0&&(ve.__webglTexture=l.createTexture(),r.memory.textures++)}if(O.samples>0&&Cs(O)===!1){V.__webglMultisampledFramebuffer=l.createFramebuffer(),V.__webglColorRenderbuffer=[],t.bindFramebuffer(l.FRAMEBUFFER,V.__webglMultisampledFramebuffer);for(let te=0;te<ee.length;te++){const ne=ee[te];V.__webglColorRenderbuffer[te]=l.createRenderbuffer(),l.bindRenderbuffer(l.RENDERBUFFER,V.__webglColorRenderbuffer[te]);const ve=n.convert(ne.format,ne.colorSpace),Ze=n.convert(ne.type),Ee=y(ne.internalFormat,ve,Ze,ne.normalized,ne.colorSpace,O.isXRRenderTarget===!0),be=us(O);l.renderbufferStorageMultisample(l.RENDERBUFFER,be,Ee,O.width,O.height),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+te,l.RENDERBUFFER,V.__webglColorRenderbuffer[te])}l.bindRenderbuffer(l.RENDERBUFFER,null),O.depthBuffer&&(V.__webglDepthRenderbuffer=l.createRenderbuffer(),Be(V.__webglDepthRenderbuffer,O,!0)),t.bindFramebuffer(l.FRAMEBUFFER,null)}}if(de){t.bindTexture(l.TEXTURE_CUBE_MAP,Y.__webglTexture),De(l.TEXTURE_CUBE_MAP,I);for(let te=0;te<6;te++)if(I.mipmaps&&I.mipmaps.length>0)for(let ne=0;ne<I.mipmaps.length;ne++)je(V.__webglFramebuffer[te][ne],O,I,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+te,ne);else je(V.__webglFramebuffer[te],O,I,l.COLOR_ATTACHMENT0,l.TEXTURE_CUBE_MAP_POSITIVE_X+te,0);g(I)&&b(l.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(me){for(let te=0,ne=ee.length;te<ne;te++){const ve=ee[te],Ze=i.get(ve);let Ee=l.TEXTURE_2D;(O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(Ee=O.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),t.bindTexture(Ee,Ze.__webglTexture),De(Ee,ve),je(V.__webglFramebuffer,O,ve,l.COLOR_ATTACHMENT0+te,Ee,0),g(ve)&&b(Ee)}t.unbindTexture()}else{let te=l.TEXTURE_2D;if((O.isWebGL3DRenderTarget||O.isWebGLArrayRenderTarget)&&(te=O.isWebGL3DRenderTarget?l.TEXTURE_3D:l.TEXTURE_2D_ARRAY),t.bindTexture(te,Y.__webglTexture),De(te,I),I.mipmaps&&I.mipmaps.length>0)for(let ne=0;ne<I.mipmaps.length;ne++)je(V.__webglFramebuffer[ne],O,I,l.COLOR_ATTACHMENT0,te,ne);else je(V.__webglFramebuffer,O,I,l.COLOR_ATTACHMENT0,te,0);g(I)&&b(te),t.unbindTexture()}O.depthBuffer&&nt(O)}function fi(O){const I=O.textures;for(let V=0,Y=I.length;V<Y;V++){const ee=I[V];if(g(ee)){const de=w(O),me=i.get(ee).__webglTexture;t.bindTexture(de,me),b(de),t.unbindTexture()}}}const mi=[],ds=[];function ts(O){if(O.samples>0){if(Cs(O)===!1){const I=O.textures,V=O.width,Y=O.height;let ee=l.COLOR_BUFFER_BIT;const de=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT,me=i.get(O),te=I.length>1;if(te)for(let ve=0;ve<I.length;ve++)t.bindFramebuffer(l.FRAMEBUFFER,me.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.RENDERBUFFER,null),t.bindFramebuffer(l.FRAMEBUFFER,me.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.TEXTURE_2D,null,0);t.bindFramebuffer(l.READ_FRAMEBUFFER,me.__webglMultisampledFramebuffer);const ne=O.texture.mipmaps;ne&&ne.length>0?t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglFramebuffer[0]):t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglFramebuffer);for(let ve=0;ve<I.length;ve++){if(O.resolveDepthBuffer&&(O.depthBuffer&&(ee|=l.DEPTH_BUFFER_BIT),O.stencilBuffer&&O.resolveStencilBuffer&&(ee|=l.STENCIL_BUFFER_BIT)),te){l.framebufferRenderbuffer(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.RENDERBUFFER,me.__webglColorRenderbuffer[ve]);const Ze=i.get(I[ve]).__webglTexture;l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,Ze,0)}l.blitFramebuffer(0,0,V,Y,0,0,V,Y,ee,l.NEAREST),o===!0&&(mi.length=0,ds.length=0,mi.push(l.COLOR_ATTACHMENT0+ve),O.depthBuffer&&O.resolveDepthBuffer===!1&&(mi.push(de),ds.push(de),l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,ds)),l.invalidateFramebuffer(l.READ_FRAMEBUFFER,mi))}if(t.bindFramebuffer(l.READ_FRAMEBUFFER,null),t.bindFramebuffer(l.DRAW_FRAMEBUFFER,null),te)for(let ve=0;ve<I.length;ve++){t.bindFramebuffer(l.FRAMEBUFFER,me.__webglMultisampledFramebuffer),l.framebufferRenderbuffer(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.RENDERBUFFER,me.__webglColorRenderbuffer[ve]);const Ze=i.get(I[ve]).__webglTexture;t.bindFramebuffer(l.FRAMEBUFFER,me.__webglFramebuffer),l.framebufferTexture2D(l.DRAW_FRAMEBUFFER,l.COLOR_ATTACHMENT0+ve,l.TEXTURE_2D,Ze,0)}t.bindFramebuffer(l.DRAW_FRAMEBUFFER,me.__webglMultisampledFramebuffer)}else if(O.depthBuffer&&O.resolveDepthBuffer===!1&&o){const I=O.stencilBuffer?l.DEPTH_STENCIL_ATTACHMENT:l.DEPTH_ATTACHMENT;l.invalidateFramebuffer(l.DRAW_FRAMEBUFFER,[I])}}}function us(O){return Math.min(s.maxSamples,O.samples)}function Cs(O){const I=i.get(O);return O.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&I.__useRenderToTexture!==!1}function z(O){const I=r.render.frame;h.get(O)!==I&&(h.set(O,I),O.update())}function ar(O,I){const V=O.colorSpace,Y=O.format,ee=O.type;return O.isCompressedTexture===!0||O.isVideoTexture===!0||V!==W0&&V!==Rl&&(Kt.getTransfer(V)===Si?(Y!==xs||ee!==On)&&We("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ft("WebGLTextures: Unsupported texture color space:",V)),I}function gi(O){return typeof HTMLImageElement<"u"&&O instanceof HTMLImageElement?(c.width=O.naturalWidth||O.width,c.height=O.naturalHeight||O.height):typeof VideoFrame<"u"&&O instanceof VideoFrame?(c.width=O.displayWidth,c.height=O.displayHeight):(c.width=O.width,c.height=O.height),c}this.allocateTextureUnit=N,this.resetTextureUnits=L,this.getTextureUnits=P,this.setTextureUnits=C,this.setTexture2D=H,this.setTexture2DArray=j,this.setTexture3D=W,this.setTextureCube=J,this.rebindTextures=lt,this.setupRenderTarget=ct,this.updateRenderTargetMipmap=fi,this.updateMultisampleRenderTarget=ts,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=je,this.useMultisampledRTT=Cs,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function _N(l,e){function t(i,s=Rl){let n;const r=Kt.getTransfer(s);if(i===On)return l.UNSIGNED_BYTE;if(i===Ew)return l.UNSIGNED_SHORT_4_4_4_4;if(i===Aw)return l.UNSIGNED_SHORT_5_5_5_1;if(i===a3)return l.UNSIGNED_INT_5_9_9_9_REV;if(i===o3)return l.UNSIGNED_INT_10F_11F_11F_REV;if(i===n3)return l.BYTE;if(i===r3)return l.SHORT;if(i===af)return l.UNSIGNED_SHORT;if(i===Sw)return l.INT;if(i===Qr)return l.UNSIGNED_INT;if(i===yn)return l.FLOAT;if(i===ti)return l.HALF_FLOAT;if(i===l3)return l.ALPHA;if(i===c3)return l.RGB;if(i===xs)return l.RGBA;if(i===Zo)return l.DEPTH_COMPONENT;if(i===Fc)return l.DEPTH_STENCIL;if(i===iu)return l.RED;if(i===Tw)return l.RED_INTEGER;if(i===rh)return l.RG;if(i===Iw)return l.RG_INTEGER;if(i===_w)return l.RGBA_INTEGER;if(i===a0||i===o0||i===l0||i===c0)if(r===Si)if(n=e.get("WEBGL_compressed_texture_s3tc_srgb"),n!==null){if(i===a0)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===o0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===l0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===c0)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(n=e.get("WEBGL_compressed_texture_s3tc"),n!==null){if(i===a0)return n.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===o0)return n.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===l0)return n.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===c0)return n.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===Nb||i===Fb||i===Ub||i===Bb)if(n=e.get("WEBGL_compressed_texture_pvrtc"),n!==null){if(i===Nb)return n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Fb)return n.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Ub)return n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Bb)return n.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===zb||i===Hb||i===Gb||i===Vb||i===Wb||i===B0||i===$b)if(n=e.get("WEBGL_compressed_texture_etc"),n!==null){if(i===zb||i===Hb)return r===Si?n.COMPRESSED_SRGB8_ETC2:n.COMPRESSED_RGB8_ETC2;if(i===Gb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:n.COMPRESSED_RGBA8_ETC2_EAC;if(i===Vb)return n.COMPRESSED_R11_EAC;if(i===Wb)return n.COMPRESSED_SIGNED_R11_EAC;if(i===B0)return n.COMPRESSED_RG11_EAC;if(i===$b)return n.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===Kb||i===Xb||i===Yb||i===qb||i===jb||i===Zb||i===Jb||i===Qb||i===ey||i===ty||i===iy||i===sy||i===ny||i===ry)if(n=e.get("WEBGL_compressed_texture_astc"),n!==null){if(i===Kb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:n.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Xb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:n.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Yb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:n.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===qb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:n.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===jb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:n.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Zb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:n.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Jb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:n.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Qb)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:n.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===ey)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:n.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===ty)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:n.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===iy)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:n.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===sy)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:n.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===ny)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:n.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===ry)return r===Si?n.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:n.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===ay||i===oy||i===ly)if(n=e.get("EXT_texture_compression_bptc"),n!==null){if(i===ay)return r===Si?n.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:n.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===oy)return n.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===ly)return n.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===cy||i===hy||i===z0||i===dy)if(n=e.get("EXT_texture_compression_rgtc"),n!==null){if(i===cy)return n.COMPRESSED_RED_RGTC1_EXT;if(i===hy)return n.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===z0)return n.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===dy)return n.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===of?l.UNSIGNED_INT_24_8:l[i]!==void 0?l[i]:null}return{convert:t}}const DN=`
|
|
8907
8907
|
void main() {
|
|
8908
8908
|
|
|
8909
8909
|
gl_Position = vec4( position, 1.0 );
|
|
@@ -8927,7 +8927,7 @@ void main() {
|
|
|
8927
8927
|
|
|
8928
8928
|
}
|
|
8929
8929
|
|
|
8930
|
-
}`;class RN{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new M3(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Nt({vertexShader:DN,fragmentShader:kN,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Me(new zn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class CN extends oc{constructor(e,t){super();const i=this;let s=null,n=1,r=null,a="local-floor",o=1,c=null,h=null,d=null,u=null,p=null,f=null;const m=typeof XRWebGLBinding<"u",v=new RN,g={},b=t.getContextAttributes();let w=null,y=null;const M=[],x=[],E=new ie;let S=null;const A=new vn;A.viewport=new Lt;const T=new vn;T.viewport=new Lt;const _=[A,T],k=new IC;let L=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getTargetRaySpace()},this.getControllerGrip=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getGripSpace()},this.getHand=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getHandSpace()};function C(Z){const ce=x.indexOf(Z.inputSource);if(ce===-1)return;const le=M[ce];le!==void 0&&(le.update(Z.inputSource,Z.frame,c||r),le.dispatchEvent({type:Z.type,data:Z.inputSource}))}function N(){s.removeEventListener("select",C),s.removeEventListener("selectstart",C),s.removeEventListener("selectend",C),s.removeEventListener("squeeze",C),s.removeEventListener("squeezestart",C),s.removeEventListener("squeezeend",C),s.removeEventListener("end",N),s.removeEventListener("inputsourceschange",F);for(let Z=0;Z<M.length;Z++){const ce=x[Z];ce!==null&&(x[Z]=null,M[Z].disconnect(ce))}L=null,P=null,v.reset();for(const Z in g)delete g[Z];e.setRenderTarget(w),p=null,u=null,d=null,s=null,y=null,De.stop(),i.isPresenting=!1,e.setPixelRatio(S),e.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){n=Z,i.isPresenting===!0&&We("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&We("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||r},this.setReferenceSpace=function(Z){c=Z},this.getBaseLayer=function(){return u!==null?u:p},this.getBinding=function(){return d===null&&m&&(d=new XRWebGLBinding(s,t)),d},this.getFrame=function(){return f},this.getSession=function(){return s},this.setSession=async function(Z){if(s=Z,s!==null){if(w=e.getRenderTarget(),s.addEventListener("select",C),s.addEventListener("selectstart",C),s.addEventListener("selectend",C),s.addEventListener("squeeze",C),s.addEventListener("squeezestart",C),s.addEventListener("squeezeend",C),s.addEventListener("end",N),s.addEventListener("inputsourceschange",F),b.xrCompatible!==!0&&await t.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let le=null,$=null,Ue=null;b.depth&&(Ue=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,le=b.stencil?Fc:Zo,$=b.stencil?of:Qr);const je={colorFormat:t.RGBA8,depthFormat:Ue,scaleFactor:n};d=this.getBinding(),u=d.createProjectionLayer(je),s.updateRenderState({layers:[u]}),e.setPixelRatio(1),e.setSize(u.textureWidth,u.textureHeight,!1),y=new oi(u.textureWidth,u.textureHeight,{format:xs,type:On,depthTexture:new nc(u.textureWidth,u.textureHeight,$,void 0,void 0,void 0,void 0,void 0,void 0,le),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1})}else{const le={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:n};p=new XRWebGLLayer(s,t,le),s.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),y=new oi(p.framebufferWidth,p.framebufferHeight,{format:xs,type:On,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(o),c=null,r=await s.requestReferenceSpace(a),De.setContext(s),De.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return v.getDepthTexture()};function F(Z){for(let ce=0;ce<Z.removed.length;ce++){const le=Z.removed[ce],$=x.indexOf(le);$>=0&&(x[$]=null,M[$].disconnect(le))}for(let ce=0;ce<Z.added.length;ce++){const le=Z.added[ce];let $=x.indexOf(le);if($===-1){for(let je=0;je<M.length;je++)if(je>=x.length){x.push(le),$=je;break}else if(x[je]===null){x[je]=le,$=je;break}if($===-1)break}const Ue=M[$];Ue&&Ue.connect(le)}}const H=new D,j=new D;function W(Z,ce,le){H.setFromMatrixPosition(ce.matrixWorld),j.setFromMatrixPosition(le.matrixWorld);const $=H.distanceTo(j),Ue=ce.projectionMatrix.elements,je=le.projectionMatrix.elements,Be=Ue[14]/(Ue[10]-1),Oe=Ue[14]/(Ue[10]+1),nt=(Ue[9]+1)/Ue[5],lt=(Ue[9]-1)/Ue[5],ct=(Ue[8]-1)/Ue[0],fi=(je[8]+1)/je[0],mi=Be*ct,ds=Be*fi,ts=$/(-ct+fi),us=ts*-ct;if(ce.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(us),Z.translateZ(ts),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Ue[10]===-1)Z.projectionMatrix.copy(ce.projectionMatrix),Z.projectionMatrixInverse.copy(ce.projectionMatrixInverse);else{const Cs=Be+ts,z=Oe+ts,ar=mi-us,gi=ds+($-us),O=nt*Oe/z*Cs,I=lt*Oe/z*Cs;Z.projectionMatrix.makePerspective(ar,gi,O,I,Cs,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function J(Z,ce){ce===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ce.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let ce=Z.near,le=Z.far;v.texture!==null&&(v.depthNear>0&&(ce=v.depthNear),v.depthFar>0&&(le=v.depthFar)),k.near=T.near=A.near=ce,k.far=T.far=A.far=le,(L!==k.near||P!==k.far)&&(s.updateRenderState({depthNear:k.near,depthFar:k.far}),L=k.near,P=k.far),k.layers.mask=Z.layers.mask|6,A.layers.mask=k.layers.mask&-5,T.layers.mask=k.layers.mask&-3;const $=Z.parent,Ue=k.cameras;J(k,$);for(let je=0;je<Ue.length;je++)J(Ue[je],$);Ue.length===2?W(k,A,T):k.projectionMatrix.copy(A.projectionMatrix),re(Z,k,$)};function re(Z,ce,le){le===null?Z.matrix.copy(ce.matrixWorld):(Z.matrix.copy(le.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ce.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ce.projectionMatrix),Z.projectionMatrixInverse.copy(ce.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=su*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return k},this.getFoveation=function(){if(!(u===null&&p===null))return o},this.setFoveation=function(Z){o=Z,u!==null&&(u.fixedFoveation=Z),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=Z)},this.hasDepthSensing=function(){return v.texture!==null},this.getDepthSensingMesh=function(){return v.getMesh(k)},this.getCameraTexture=function(Z){return g[Z]};let Le=null;function He(Z,ce){if(h=ce.getViewerPose(c||r),f=ce,h!==null){const le=h.views;p!==null&&(e.setRenderTargetFramebuffer(y,p.framebuffer),e.setRenderTarget(y));let $=!1;le.length!==k.cameras.length&&(k.cameras.length=0,$=!0);for(let Oe=0;Oe<le.length;Oe++){const nt=le[Oe];let lt=null;if(p!==null)lt=p.getViewport(nt);else{const fi=d.getViewSubImage(u,nt);lt=fi.viewport,Oe===0&&(e.setRenderTargetTextures(y,fi.colorTexture,fi.depthStencilTexture),e.setRenderTarget(y))}let ct=_[Oe];ct===void 0&&(ct=new vn,ct.layers.enable(Oe),ct.viewport=new Lt,_[Oe]=ct),ct.matrix.fromArray(nt.transform.matrix),ct.matrix.decompose(ct.position,ct.quaternion,ct.scale),ct.projectionMatrix.fromArray(nt.projectionMatrix),ct.projectionMatrixInverse.copy(ct.projectionMatrix).invert(),ct.viewport.set(lt.x,lt.y,lt.width,lt.height),Oe===0&&(k.matrix.copy(ct.matrix),k.matrix.decompose(k.position,k.quaternion,k.scale)),$===!0&&k.cameras.push(ct)}const Ue=s.enabledFeatures;if(Ue&&Ue.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&m){d=i.getBinding();const Oe=d.getDepthInformation(le[0]);Oe&&Oe.isValid&&Oe.texture&&v.init(Oe,s.renderState)}if(Ue&&Ue.includes("camera-access")&&m){e.state.unbindTexture(),d=i.getBinding();for(let Oe=0;Oe<le.length;Oe++){const nt=le[Oe].camera;if(nt){let lt=g[nt];lt||(lt=new M3,g[nt]=lt);const ct=d.getCameraImage(nt);lt.sourceTexture=ct}}}}for(let le=0;le<M.length;le++){const $=x[le],Ue=M[le];$!==null&&Ue!==void 0&&Ue.update($,ce,c||r)}Le&&Le(Z,ce),ce.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ce}),f=null}const De=new U3;De.setAnimationLoop(He),this.setAnimationLoop=function(Z){Le=Z},this.dispose=function(){}}}const LN=new qe,W3=new bt;W3.set(-1,0,0,0,1,0,0,0,1);function ON(l,e){function t(v,g){v.matrixAutoUpdate===!0&&v.updateMatrix(),g.value.copy(v.matrix)}function i(v,g){g.color.getRGB(v.fogColor.value,k3(l)),g.isFog?(v.fogNear.value=g.near,v.fogFar.value=g.far):g.isFogExp2&&(v.fogDensity.value=g.density)}function s(v,g,b,w,y){g.isNodeMaterial?g.uniformsNeedUpdate=!1:g.isMeshBasicMaterial?n(v,g):g.isMeshLambertMaterial?(n(v,g),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)):g.isMeshToonMaterial?(n(v,g),d(v,g)):g.isMeshPhongMaterial?(n(v,g),h(v,g),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)):g.isMeshStandardMaterial?(n(v,g),u(v,g),g.isMeshPhysicalMaterial&&p(v,g,y)):g.isMeshMatcapMaterial?(n(v,g),f(v,g)):g.isMeshDepthMaterial?n(v,g):g.isMeshDistanceMaterial?(n(v,g),m(v,g)):g.isMeshNormalMaterial?n(v,g):g.isLineBasicMaterial?(r(v,g),g.isLineDashedMaterial&&a(v,g)):g.isPointsMaterial?o(v,g,b,w):g.isSpriteMaterial?c(v,g):g.isShadowMaterial?(v.color.value.copy(g.color),v.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function n(v,g){v.opacity.value=g.opacity,g.color&&v.diffuse.value.copy(g.color),g.emissive&&v.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(v.map.value=g.map,t(g.map,v.mapTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.bumpMap&&(v.bumpMap.value=g.bumpMap,t(g.bumpMap,v.bumpMapTransform),v.bumpScale.value=g.bumpScale,g.side===Ji&&(v.bumpScale.value*=-1)),g.normalMap&&(v.normalMap.value=g.normalMap,t(g.normalMap,v.normalMapTransform),v.normalScale.value.copy(g.normalScale),g.side===Ji&&v.normalScale.value.negate()),g.displacementMap&&(v.displacementMap.value=g.displacementMap,t(g.displacementMap,v.displacementMapTransform),v.displacementScale.value=g.displacementScale,v.displacementBias.value=g.displacementBias),g.emissiveMap&&(v.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,v.emissiveMapTransform)),g.specularMap&&(v.specularMap.value=g.specularMap,t(g.specularMap,v.specularMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest);const b=e.get(g),w=b.envMap,y=b.envMapRotation;w&&(v.envMap.value=w,v.envMapRotation.value.setFromMatrix4(LN.makeRotationFromEuler(y)).transpose(),w.isCubeTexture&&w.isRenderTargetTexture===!1&&v.envMapRotation.value.premultiply(W3),v.reflectivity.value=g.reflectivity,v.ior.value=g.ior,v.refractionRatio.value=g.refractionRatio),g.lightMap&&(v.lightMap.value=g.lightMap,v.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,v.lightMapTransform)),g.aoMap&&(v.aoMap.value=g.aoMap,v.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,v.aoMapTransform))}function r(v,g){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,g.map&&(v.map.value=g.map,t(g.map,v.mapTransform))}function a(v,g){v.dashSize.value=g.dashSize,v.totalSize.value=g.dashSize+g.gapSize,v.scale.value=g.scale}function o(v,g,b,w){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,v.size.value=g.size*b,v.scale.value=w*.5,g.map&&(v.map.value=g.map,t(g.map,v.uvTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest)}function c(v,g){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,v.rotation.value=g.rotation,g.map&&(v.map.value=g.map,t(g.map,v.mapTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest)}function h(v,g){v.specular.value.copy(g.specular),v.shininess.value=Math.max(g.shininess,1e-4)}function d(v,g){g.gradientMap&&(v.gradientMap.value=g.gradientMap)}function u(v,g){v.metalness.value=g.metalness,g.metalnessMap&&(v.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,v.metalnessMapTransform)),v.roughness.value=g.roughness,g.roughnessMap&&(v.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,v.roughnessMapTransform)),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)}function p(v,g,b){v.ior.value=g.ior,g.sheen>0&&(v.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),v.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(v.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,v.sheenColorMapTransform)),g.sheenRoughnessMap&&(v.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,v.sheenRoughnessMapTransform))),g.clearcoat>0&&(v.clearcoat.value=g.clearcoat,v.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(v.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,v.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(v.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,v.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(v.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,v.clearcoatNormalMapTransform),v.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===Ji&&v.clearcoatNormalScale.value.negate())),g.dispersion>0&&(v.dispersion.value=g.dispersion),g.iridescence>0&&(v.iridescence.value=g.iridescence,v.iridescenceIOR.value=g.iridescenceIOR,v.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],v.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(v.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,v.iridescenceMapTransform)),g.iridescenceThicknessMap&&(v.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,v.iridescenceThicknessMapTransform))),g.transmission>0&&(v.transmission.value=g.transmission,v.transmissionSamplerMap.value=b.texture,v.transmissionSamplerSize.value.set(b.width,b.height),g.transmissionMap&&(v.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,v.transmissionMapTransform)),v.thickness.value=g.thickness,g.thicknessMap&&(v.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,v.thicknessMapTransform)),v.attenuationDistance.value=g.attenuationDistance,v.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(v.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(v.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,v.anisotropyMapTransform))),v.specularIntensity.value=g.specularIntensity,v.specularColor.value.copy(g.specularColor),g.specularColorMap&&(v.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,v.specularColorMapTransform)),g.specularIntensityMap&&(v.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,v.specularIntensityMapTransform))}function f(v,g){g.matcap&&(v.matcap.value=g.matcap)}function m(v,g){const b=e.get(g).light;v.referencePosition.value.setFromMatrixPosition(b.matrixWorld),v.nearDistance.value=b.shadow.camera.near,v.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function PN(l,e,t,i){let s={},n={},r=[];const a=l.getParameter(l.MAX_UNIFORM_BUFFER_BINDINGS);function o(y,M){const x=M.program;i.uniformBlockBinding(y,x)}function c(y,M){let x=s[y.id];x===void 0&&(v(y),x=h(y),s[y.id]=x,y.addEventListener("dispose",b));const E=M.program;i.updateUBOMapping(y,E);const S=e.render.frame;n[y.id]!==S&&(u(y),n[y.id]=S)}function h(y){const M=d();y.__bindingPointIndex=M;const x=l.createBuffer(),E=y.__size,S=y.usage;return l.bindBuffer(l.UNIFORM_BUFFER,x),l.bufferData(l.UNIFORM_BUFFER,E,S),l.bindBuffer(l.UNIFORM_BUFFER,null),l.bindBufferBase(l.UNIFORM_BUFFER,M,x),x}function d(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ft("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function u(y){const M=s[y.id],x=y.uniforms,E=y.__cache;l.bindBuffer(l.UNIFORM_BUFFER,M);for(let S=0,A=x.length;S<A;S++){const T=x[S];if(Array.isArray(T))for(let _=0,k=T.length;_<k;_++)p(T[_],S,_,E);else p(T,S,0,E)}l.bindBuffer(l.UNIFORM_BUFFER,null)}function p(y,M,x,E){if(m(y,M,x,E)===!0){const S=y.__offset,A=y.value;if(Array.isArray(A)){let T=0;for(let _=0;_<A.length;_++){const k=A[_],L=g(k);f(k,y.__data,T),typeof k!="number"&&typeof k!="boolean"&&!k.isMatrix3&&!ArrayBuffer.isView(k)&&(T+=L.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(A,y.__data,0);l.bufferSubData(l.UNIFORM_BUFFER,S,y.__data)}}function f(y,M,x){typeof y=="number"||typeof y=="boolean"?M[0]=y:y.isMatrix3?(M[0]=y.elements[0],M[1]=y.elements[1],M[2]=y.elements[2],M[3]=0,M[4]=y.elements[3],M[5]=y.elements[4],M[6]=y.elements[5],M[7]=0,M[8]=y.elements[6],M[9]=y.elements[7],M[10]=y.elements[8],M[11]=0):ArrayBuffer.isView(y)?M.set(new y.constructor(y.buffer,y.byteOffset,M.length)):y.toArray(M,x)}function m(y,M,x,E){const S=y.value,A=M+"_"+x;if(E[A]===void 0)return typeof S=="number"||typeof S=="boolean"?E[A]=S:ArrayBuffer.isView(S)?E[A]=S.slice():E[A]=S.clone(),!0;{const T=E[A];if(typeof S=="number"||typeof S=="boolean"){if(T!==S)return E[A]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(T.equals(S)===!1)return T.copy(S),!0}}return!1}function v(y){const M=y.uniforms;let x=0;const E=16;for(let A=0,T=M.length;A<T;A++){const _=Array.isArray(M[A])?M[A]:[M[A]];for(let k=0,L=_.length;k<L;k++){const P=_[k],C=Array.isArray(P.value)?P.value:[P.value];for(let N=0,F=C.length;N<F;N++){const H=C[N],j=g(H),W=x%E,J=W%j.boundary,re=W+J;x+=J,re!==0&&E-re<j.storage&&(x+=E-re),P.__data=new Float32Array(j.storage/Float32Array.BYTES_PER_ELEMENT),P.__offset=x,x+=j.storage}}}const S=x%E;return S>0&&(x+=E-S),y.__size=x,y.__cache={},this}function g(y){const M={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(M.boundary=4,M.storage=4):y.isVector2?(M.boundary=8,M.storage=8):y.isVector3||y.isColor?(M.boundary=16,M.storage=12):y.isVector4?(M.boundary=16,M.storage=16):y.isMatrix3?(M.boundary=48,M.storage=48):y.isMatrix4?(M.boundary=64,M.storage=64):y.isTexture?We("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(M.boundary=16,M.storage=y.byteLength):We("WebGLRenderer: Unsupported uniform value type.",y),M}function b(y){const M=y.target;M.removeEventListener("dispose",b);const x=r.indexOf(M.__bindingPointIndex);r.splice(x,1),l.deleteBuffer(s[M.id]),delete s[M.id],delete n[M.id]}function w(){for(const y in s)l.deleteBuffer(s[y]);r=[],s={},n={}}return{bind:o,update:c,dispose:w}}const NN=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ka=null;function FN(){return ka===null&&(ka=new nr(NN,16,16,rh,ti),ka.name="DFG_LUT",ka.minFilter=St,ka.magFilter=St,ka.wrapS=Ms,ka.wrapT=Ms,ka.generateMipmaps=!1,ka.needsUpdate=!0),ka}class UN{constructor(e={}){const{canvas:t=CR(),context:i=null,depth:s=!0,stencil:n=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:p=On}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const m=p,v=new Set([_w,Iw,Tw]),g=new Set([On,Qr,af,of,Ew,Aw]),b=new Uint32Array(4),w=new Int32Array(4),y=new D;let M=null,x=null;const E=[],S=[];let A=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=oo,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let _=!1,k=null,L=null,P=null,C=null;this._outputColorSpace=an;let N=0,F=0,H=null,j=-1,W=null;const J=new Lt,re=new Lt;let Le=null;const He=new oe(0);let De=0,Z=t.width,ce=t.height,le=1,$=null,Ue=null;const je=new Lt(0,0,Z,ce),Be=new Lt(0,0,Z,ce);let Oe=!1;const nt=new zg;let lt=!1,ct=!1;const fi=new qe,mi=new D,ds=new Lt,ts={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let us=!1;function Cs(){return H===null?le:1}let z=i;function ar(R,G){return t.getContext(R,G)}try{const R={alpha:!0,depth:s,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Sf}`),t.addEventListener("webglcontextlost",ps,!1),t.addEventListener("webglcontextrestored",Pi,!1),t.addEventListener("webglcontextcreationerror",Aa,!1),z===null){const G="webgl2";if(z=ar(G,R),z===null)throw ar(G)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(R){throw ft("WebGLRenderer: "+R.message),R}let gi,O,I,V,Y,ee,de,me,te,ne,ve,Ze,Ee,be,it,dt,_t,B,fe,se,ye,_e,ae;function Xe(){gi=new FP(z),gi.init(),ye=new _N(z,gi),O=new DP(z,gi,e,ye),I=new TN(z,gi),O.reversedDepthBuffer&&u&&I.buffers.depth.setReversed(!0),L=z.createFramebuffer(),P=z.createFramebuffer(),C=z.createFramebuffer(),V=new zP(z),Y=new uN,ee=new IN(z,gi,I,Y,O,ye,V),de=new NP(T),me=new WC(z),_e=new IP(z,me),te=new UP(z,me,V,_e),ne=new GP(z,te,me,_e,V),B=new HP(z,O,ee),it=new kP(Y),ve=new dN(T,de,gi,O,_e,it),Ze=new ON(T,Y),Ee=new fN,be=new wN(gi),_t=new TP(T,de,I,ne,f,o),dt=new AN(T,ne,O),ae=new PN(z,V,O,I),fe=new _P(z,gi,V),se=new BP(z,gi,V),V.programs=ve.programs,T.capabilities=O,T.extensions=gi,T.properties=Y,T.renderLists=Ee,T.shadowMap=dt,T.state=I,T.info=V}Xe(),m!==On&&(A=new WP(m,t.width,t.height,a,s,n));const ze=new CN(T,z);this.xr=ze,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const R=gi.get("WEBGL_lose_context");R&&R.loseContext()},this.forceContextRestore=function(){const R=gi.get("WEBGL_lose_context");R&&R.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(R){R!==void 0&&(le=R,this.setSize(Z,ce,!1))},this.getSize=function(R){return R.set(Z,ce)},this.setSize=function(R,G,q=!0){if(ze.isPresenting){We("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=R,ce=G,t.width=Math.floor(R*le),t.height=Math.floor(G*le),q===!0&&(t.style.width=R+"px",t.style.height=G+"px"),A!==null&&A.setSize(t.width,t.height),this.setViewport(0,0,R,G)},this.getDrawingBufferSize=function(R){return R.set(Z*le,ce*le).floor()},this.setDrawingBufferSize=function(R,G,q){Z=R,ce=G,le=q,t.width=Math.floor(R*q),t.height=Math.floor(G*q),this.setViewport(0,0,R,G)},this.setEffects=function(R){if(m===On){ft("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(R){for(let G=0;G<R.length;G++)if(R[G].isOutputPass===!0){We("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(R||[])},this.getCurrentViewport=function(R){return R.copy(J)},this.getViewport=function(R){return R.copy(je)},this.setViewport=function(R,G,q,K){R.isVector4?je.set(R.x,R.y,R.z,R.w):je.set(R,G,q,K),I.viewport(J.copy(je).multiplyScalar(le).round())},this.getScissor=function(R){return R.copy(Be)},this.setScissor=function(R,G,q,K){R.isVector4?Be.set(R.x,R.y,R.z,R.w):Be.set(R,G,q,K),I.scissor(re.copy(Be).multiplyScalar(le).round())},this.getScissorTest=function(){return Oe},this.setScissorTest=function(R){I.setScissorTest(Oe=R)},this.setOpaqueSort=function(R){$=R},this.setTransparentSort=function(R){Ue=R},this.getClearColor=function(R){return R.copy(_t.getClearColor())},this.setClearColor=function(){_t.setClearColor(...arguments)},this.getClearAlpha=function(){return _t.getClearAlpha()},this.setClearAlpha=function(){_t.setClearAlpha(...arguments)},this.clear=function(R=!0,G=!0,q=!0){let K=0;if(R){let X=!1;if(H!==null){const Ie=H.texture.format;X=v.has(Ie)}if(X){const Ie=H.texture.type,Pe=g.has(Ie),Te=_t.getClearColor(),Ge=_t.getClearAlpha(),Je=Te.r,Dt=Te.g,Ft=Te.b;Pe?(b[0]=Je,b[1]=Dt,b[2]=Ft,b[3]=Ge,z.clearBufferuiv(z.COLOR,0,b)):(w[0]=Je,w[1]=Dt,w[2]=Ft,w[3]=Ge,z.clearBufferiv(z.COLOR,0,w))}else K|=z.COLOR_BUFFER_BIT}G&&(K|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),q&&(K|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),K!==0&&z.clear(K)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(R){R.setRenderer(this),k=R},this.dispose=function(){t.removeEventListener("webglcontextlost",ps,!1),t.removeEventListener("webglcontextrestored",Pi,!1),t.removeEventListener("webglcontextcreationerror",Aa,!1),_t.dispose(),Ee.dispose(),be.dispose(),Y.dispose(),de.dispose(),ne.dispose(),_e.dispose(),ae.dispose(),ve.dispose(),ze.dispose(),ze.removeEventListener("sessionstart",dM),ze.removeEventListener("sessionend",uM),cc.stop()};function ps(R){R.preventDefault(),X0("WebGLRenderer: Context Lost."),_=!0}function Pi(){X0("WebGLRenderer: Context Restored."),_=!1;const R=V.autoReset,G=dt.enabled,q=dt.autoUpdate,K=dt.needsUpdate,X=dt.type;Xe(),V.autoReset=R,dt.enabled=G,dt.autoUpdate=q,dt.needsUpdate=K,dt.type=X}function Aa(R){ft("WebGLRenderer: A WebGL context could not be created. Reason: ",R.statusMessage)}function Ta(R){const G=R.target;G.removeEventListener("dispose",Ta),DI(G)}function DI(R){kI(R),Y.remove(R)}function kI(R){const G=Y.get(R).programs;G!==void 0&&(G.forEach(function(q){ve.releaseProgram(q)}),R.isShaderMaterial&&ve.releaseShaderCache(R))}this.renderBufferDirect=function(R,G,q,K,X,Ie){G===null&&(G=ts);const Pe=X.isMesh&&X.matrixWorld.determinantAffine()<0,Te=LI(R,G,q,K,X);I.setMaterial(K,Pe);let Ge=q.index,Je=1;if(K.wireframe===!0){if(Ge=te.getWireframeAttribute(q),Ge===void 0)return;Je=2}const Dt=q.drawRange,Ft=q.attributes.position;let Qe=Dt.start*Je,_i=(Dt.start+Dt.count)*Je;Ie!==null&&(Qe=Math.max(Qe,Ie.start*Je),_i=Math.min(_i,(Ie.start+Ie.count)*Je)),Ge!==null?(Qe=Math.max(Qe,0),_i=Math.min(_i,Ge.count)):Ft!=null&&(Qe=Math.max(Qe,0),_i=Math.min(_i,Ft.count));const Es=_i-Qe;if(Es<0||Es===1/0)return;_e.setup(X,K,Te,q,Ge);let fs,ki=fe;if(Ge!==null&&(fs=me.get(Ge),ki=se,ki.setIndex(fs)),X.isMesh)K.wireframe===!0?(I.setLineWidth(K.wireframeLinewidth*Cs()),ki.setMode(z.LINES)):ki.setMode(z.TRIANGLES);else if(X.isLine){let wn=K.linewidth;wn===void 0&&(wn=1),I.setLineWidth(wn*Cs()),X.isLineSegments?ki.setMode(z.LINES):X.isLineLoop?ki.setMode(z.LINE_LOOP):ki.setMode(z.LINE_STRIP)}else X.isPoints?ki.setMode(z.POINTS):X.isSprite&&ki.setMode(z.TRIANGLES);if(X.isBatchedMesh)if(gi.get("WEBGL_multi_draw"))ki.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const wn=X._multiDrawStarts,ke=X._multiDrawCounts,Sr=X._multiDrawCount,qt=Ge?me.get(Ge).bytesPerElement:1,Br=Y.get(K).currentProgram.getUniforms();for(let Ia=0;Ia<Sr;Ia++)Br.setValue(z,"_gl_DrawID",Ia),ki.render(wn[Ia]/qt,ke[Ia])}else if(X.isInstancedMesh)ki.renderInstances(Qe,Es,X.count);else if(q.isInstancedBufferGeometry){const wn=q._maxInstanceCount!==void 0?q._maxInstanceCount:1/0,ke=Math.min(q.instanceCount,wn);ki.renderInstances(Qe,Es,ke)}else ki.render(Qe,Es)};function hM(R,G,q){R.transparent===!0&&R.side===$s&&R.forceSinglePass===!1?(R.side=Ji,R.needsUpdate=!0,If(R,G,q),R.side=ho,R.needsUpdate=!0,If(R,G,q),R.side=$s):If(R,G,q)}this.compile=function(R,G,q=null){q===null&&(q=R),x=be.get(q),x.init(G),S.push(x),q.traverseVisible(function(X){X.isLight&&X.layers.test(G.layers)&&(x.pushLight(X),X.castShadow&&x.pushShadow(X))}),R!==q&&R.traverseVisible(function(X){X.isLight&&X.layers.test(G.layers)&&(x.pushLight(X),X.castShadow&&x.pushShadow(X))}),x.setupLights();const K=new Set;return R.traverse(function(X){if(!(X.isMesh||X.isPoints||X.isLine||X.isSprite))return;const Ie=X.material;if(Ie)if(Array.isArray(Ie))for(let Pe=0;Pe<Ie.length;Pe++){const Te=Ie[Pe];hM(Te,q,X),K.add(Te)}else hM(Ie,q,X),K.add(Ie)}),x=S.pop(),K},this.compileAsync=function(R,G,q=null){const K=this.compile(R,G,q);return new Promise(X=>{function Ie(){if(K.forEach(function(Pe){Y.get(Pe).currentProgram.isReady()&&K.delete(Pe)}),K.size===0){X(R);return}setTimeout(Ie,10)}gi.get("KHR_parallel_shader_compile")!==null?Ie():setTimeout(Ie,10)})};let jg=null;function RI(R){jg&&jg(R)}function dM(){cc.stop()}function uM(){cc.start()}const cc=new U3;cc.setAnimationLoop(RI),typeof self<"u"&&cc.setContext(self),this.setAnimationLoop=function(R){jg=R,ze.setAnimationLoop(R),R===null?cc.stop():cc.start()},ze.addEventListener("sessionstart",dM),ze.addEventListener("sessionend",uM),this.render=function(R,G){if(G!==void 0&&G.isCamera!==!0){ft("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(_===!0)return;k!==null&&k.renderStart(R,G);const q=ze.enabled===!0&&ze.isPresenting===!0,K=A!==null&&(H===null||q)&&A.begin(T,H);if(R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),ze.enabled===!0&&ze.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(ze.cameraAutoUpdate===!0&&ze.updateCamera(G),G=ze.getCamera()),R.isScene===!0&&R.onBeforeRender(T,R,G,H),x=be.get(R,S.length),x.init(G),x.state.textureUnits=ee.getTextureUnits(),S.push(x),fi.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),nt.setFromProjectionMatrix(fi,ro,G.reversedDepth),ct=this.localClippingEnabled,lt=it.init(this.clippingPlanes,ct),M=Ee.get(R,E.length),M.init(),E.push(M),ze.enabled===!0&&ze.isPresenting===!0){const Pe=T.xr.getDepthSensingMesh();Pe!==null&&Zg(Pe,G,-1/0,T.sortObjects)}Zg(R,G,0,T.sortObjects),M.finish(),T.sortObjects===!0&&M.sort($,Ue,G.reversedDepth),us=ze.enabled===!1||ze.isPresenting===!1||ze.hasDepthSensing()===!1,us&&_t.addToRenderList(M,R),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),lt===!0&&it.beginShadows();const X=x.state.shadowsArray;if(dt.render(X,R,G),lt===!0&&it.endShadows(),(K&&A.hasRenderPass())===!1){const Pe=M.opaque,Te=M.transmissive;if(x.setupLights(),G.isArrayCamera){const Ge=G.cameras;if(Te.length>0)for(let Je=0,Dt=Ge.length;Je<Dt;Je++){const Ft=Ge[Je];fM(Pe,Te,R,Ft)}us&&_t.render(R);for(let Je=0,Dt=Ge.length;Je<Dt;Je++){const Ft=Ge[Je];pM(M,R,Ft,Ft.viewport)}}else Te.length>0&&fM(Pe,Te,R,G),us&&_t.render(R),pM(M,R,G)}H!==null&&F===0&&(ee.updateMultisampleRenderTarget(H),ee.updateRenderTargetMipmap(H)),K&&A.end(T),R.isScene===!0&&R.onAfterRender(T,R,G),_e.resetDefaultState(),j=-1,W=null,S.pop(),S.length>0?(x=S[S.length-1],ee.setTextureUnits(x.state.textureUnits),lt===!0&&it.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,E.pop(),E.length>0?M=E[E.length-1]:M=null,k!==null&&k.renderEnd()};function Zg(R,G,q,K){if(R.visible===!1)return;if(R.layers.test(G.layers)){if(R.isGroup)q=R.renderOrder;else if(R.isLOD)R.autoUpdate===!0&&R.update(G);else if(R.isLightProbeGrid)x.pushLightProbeGrid(R);else if(R.isLight)x.pushLight(R),R.castShadow&&x.pushShadow(R);else if(R.isSprite){if(!R.frustumCulled||nt.intersectsSprite(R)){K&&ds.setFromMatrixPosition(R.matrixWorld).applyMatrix4(fi);const Pe=ne.update(R),Te=R.material;Te.visible&&M.push(R,Pe,Te,q,ds.z,null)}}else if((R.isMesh||R.isLine||R.isPoints)&&(!R.frustumCulled||nt.intersectsObject(R))){const Pe=ne.update(R),Te=R.material;if(K&&(R.boundingSphere!==void 0?(R.boundingSphere===null&&R.computeBoundingSphere(),ds.copy(R.boundingSphere.center)):(Pe.boundingSphere===null&&Pe.computeBoundingSphere(),ds.copy(Pe.boundingSphere.center)),ds.applyMatrix4(R.matrixWorld).applyMatrix4(fi)),Array.isArray(Te)){const Ge=Pe.groups;for(let Je=0,Dt=Ge.length;Je<Dt;Je++){const Ft=Ge[Je],Qe=Te[Ft.materialIndex];Qe&&Qe.visible&&M.push(R,Pe,Qe,q,ds.z,Ft)}}else Te.visible&&M.push(R,Pe,Te,q,ds.z,null)}}const Ie=R.children;for(let Pe=0,Te=Ie.length;Pe<Te;Pe++)Zg(Ie[Pe],G,q,K)}function pM(R,G,q,K){const{opaque:X,transmissive:Ie,transparent:Pe}=R;x.setupLightsView(q),lt===!0&&it.setGlobalState(T.clippingPlanes,q),K&&I.viewport(J.copy(K)),X.length>0&&Tf(X,G,q),Ie.length>0&&Tf(Ie,G,q),Pe.length>0&&Tf(Pe,G,q),I.buffers.depth.setTest(!0),I.buffers.depth.setMask(!0),I.buffers.color.setMask(!0),I.setPolygonOffset(!1)}function fM(R,G,q,K){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[K.id]===void 0){const Qe=gi.has("EXT_color_buffer_half_float")||gi.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[K.id]=new oi(1,1,{generateMipmaps:!0,type:Qe?ti:On,minFilter:Nr,samples:Math.max(4,O.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Kt.workingColorSpace})}const Ie=x.state.transmissionRenderTarget[K.id],Pe=K.viewport||J;Ie.setSize(Pe.z*T.transmissionResolutionScale,Pe.w*T.transmissionResolutionScale);const Te=T.getRenderTarget(),Ge=T.getActiveCubeFace(),Je=T.getActiveMipmapLevel();T.setRenderTarget(Ie),T.getClearColor(He),De=T.getClearAlpha(),De<1&&T.setClearColor(16777215,.5),T.clear(),us&&_t.render(q);const Dt=T.toneMapping;T.toneMapping=oo;const Ft=K.viewport;if(K.viewport!==void 0&&(K.viewport=void 0),x.setupLightsView(K),lt===!0&&it.setGlobalState(T.clippingPlanes,K),Tf(R,q,K),ee.updateMultisampleRenderTarget(Ie),ee.updateRenderTargetMipmap(Ie),gi.has("WEBGL_multisampled_render_to_texture")===!1){let Qe=!1;for(let _i=0,Es=G.length;_i<Es;_i++){const fs=G[_i],{object:ki,geometry:wn,material:ke,group:Sr}=fs;if(ke.side===$s&&ki.layers.test(K.layers)){const qt=ke.side;ke.side=Ji,ke.needsUpdate=!0,mM(ki,q,K,wn,ke,Sr),ke.side=qt,ke.needsUpdate=!0,Qe=!0}}Qe===!0&&(ee.updateMultisampleRenderTarget(Ie),ee.updateRenderTargetMipmap(Ie))}T.setRenderTarget(Te,Ge,Je),T.setClearColor(He,De),Ft!==void 0&&(K.viewport=Ft),T.toneMapping=Dt}function Tf(R,G,q){const K=G.isScene===!0?G.overrideMaterial:null;for(let X=0,Ie=R.length;X<Ie;X++){const Pe=R[X],{object:Te,geometry:Ge,group:Je}=Pe;let Dt=Pe.material;Dt.allowOverride===!0&&K!==null&&(Dt=K),Te.layers.test(q.layers)&&mM(Te,G,q,Ge,Dt,Je)}}function mM(R,G,q,K,X,Ie){R.onBeforeRender(T,G,q,K,X,Ie),R.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse,R.matrixWorld),R.normalMatrix.getNormalMatrix(R.modelViewMatrix),X.onBeforeRender(T,G,q,K,R,Ie),X.transparent===!0&&X.side===$s&&X.forceSinglePass===!1?(X.side=Ji,X.needsUpdate=!0,T.renderBufferDirect(q,G,K,X,R,Ie),X.side=ho,X.needsUpdate=!0,T.renderBufferDirect(q,G,K,X,R,Ie),X.side=$s):T.renderBufferDirect(q,G,K,X,R,Ie),R.onAfterRender(T,G,q,K,X,Ie)}function If(R,G,q){G.isScene!==!0&&(G=ts);const K=Y.get(R),X=x.state.lights,Ie=x.state.shadowsArray,Pe=X.state.version,Te=ve.getParameters(R,X.state,Ie,G,q,x.state.lightProbeGridArray),Ge=ve.getProgramCacheKey(Te);let Je=K.programs;K.environment=R.isMeshStandardMaterial||R.isMeshLambertMaterial||R.isMeshPhongMaterial?G.environment:null,K.fog=G.fog;const Dt=R.isMeshStandardMaterial||R.isMeshLambertMaterial&&!R.envMap||R.isMeshPhongMaterial&&!R.envMap;K.envMap=de.get(R.envMap||K.environment,Dt),K.envMapRotation=K.environment!==null&&R.envMap===null?G.environmentRotation:R.envMapRotation,Je===void 0&&(R.addEventListener("dispose",Ta),Je=new Map,K.programs=Je);let Ft=Je.get(Ge);if(Ft!==void 0){if(K.currentProgram===Ft&&K.lightsStateVersion===Pe)return vM(R,Te),Ft}else Te.uniforms=ve.getUniforms(R),k!==null&&R.isNodeMaterial&&k.build(R,q,Te),R.onBeforeCompile(Te,T),Ft=ve.acquireProgram(Te,Ge),Je.set(Ge,Ft),K.uniforms=Te.uniforms;const Qe=K.uniforms;return(!R.isShaderMaterial&&!R.isRawShaderMaterial||R.clipping===!0)&&(Qe.clippingPlanes=it.uniform),vM(R,Te),K.needsLights=PI(R),K.lightsStateVersion=Pe,K.needsLights&&(Qe.ambientLightColor.value=X.state.ambient,Qe.lightProbe.value=X.state.probe,Qe.directionalLights.value=X.state.directional,Qe.directionalLightShadows.value=X.state.directionalShadow,Qe.spotLights.value=X.state.spot,Qe.spotLightShadows.value=X.state.spotShadow,Qe.rectAreaLights.value=X.state.rectArea,Qe.ltc_1.value=X.state.rectAreaLTC1,Qe.ltc_2.value=X.state.rectAreaLTC2,Qe.pointLights.value=X.state.point,Qe.pointLightShadows.value=X.state.pointShadow,Qe.hemisphereLights.value=X.state.hemi,Qe.directionalShadowMatrix.value=X.state.directionalShadowMatrix,Qe.spotLightMatrix.value=X.state.spotLightMatrix,Qe.spotLightMap.value=X.state.spotLightMap,Qe.pointShadowMatrix.value=X.state.pointShadowMatrix),K.lightProbeGrid=x.state.lightProbeGridArray.length>0,K.currentProgram=Ft,K.uniformsList=null,Ft}function gM(R){if(R.uniformsList===null){const G=R.currentProgram.getUniforms();R.uniformsList=u0.seqWithValue(G.seq,R.uniforms)}return R.uniformsList}function vM(R,G){const q=Y.get(R);q.outputColorSpace=G.outputColorSpace,q.batching=G.batching,q.batchingColor=G.batchingColor,q.instancing=G.instancing,q.instancingColor=G.instancingColor,q.instancingMorph=G.instancingMorph,q.skinning=G.skinning,q.morphTargets=G.morphTargets,q.morphNormals=G.morphNormals,q.morphColors=G.morphColors,q.morphTargetsCount=G.morphTargetsCount,q.numClippingPlanes=G.numClippingPlanes,q.numIntersection=G.numClipIntersection,q.vertexAlphas=G.vertexAlphas,q.vertexTangents=G.vertexTangents,q.toneMapping=G.toneMapping}function CI(R,G){if(R.length===0)return null;if(R.length===1)return R[0].texture!==null?R[0]:null;y.setFromMatrixPosition(G.matrixWorld);for(let q=0,K=R.length;q<K;q++){const X=R[q];if(X.texture!==null&&X.boundingBox.containsPoint(y))return X}return null}function LI(R,G,q,K,X){G.isScene!==!0&&(G=ts),ee.resetTextureUnits();const Ie=G.fog,Pe=K.isMeshStandardMaterial||K.isMeshLambertMaterial||K.isMeshPhongMaterial?G.environment:null,Te=H===null?T.outputColorSpace:H.isXRRenderTarget===!0?H.texture.colorSpace:Kt.workingColorSpace,Ge=K.isMeshStandardMaterial||K.isMeshLambertMaterial&&!K.envMap||K.isMeshPhongMaterial&&!K.envMap,Je=de.get(K.envMap||Pe,Ge),Dt=K.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,Ft=!!q.attributes.tangent&&(!!K.normalMap||K.anisotropy>0),Qe=!!q.morphAttributes.position,_i=!!q.morphAttributes.normal,Es=!!q.morphAttributes.color;let fs=oo;K.toneMapped&&(H===null||H.isXRRenderTarget===!0)&&(fs=T.toneMapping);const ki=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,wn=ki!==void 0?ki.length:0,ke=Y.get(K),Sr=x.state.lights;if(lt===!0&&(ct===!0||R!==W)){const Ni=R===W&&K.id===j;it.setState(K,R,Ni)}let qt=!1;K.version===ke.__version?(ke.needsLights&&ke.lightsStateVersion!==Sr.state.version||ke.outputColorSpace!==Te||X.isBatchedMesh&&ke.batching===!1||!X.isBatchedMesh&&ke.batching===!0||X.isBatchedMesh&&ke.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&ke.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&ke.instancing===!1||!X.isInstancedMesh&&ke.instancing===!0||X.isSkinnedMesh&&ke.skinning===!1||!X.isSkinnedMesh&&ke.skinning===!0||X.isInstancedMesh&&ke.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&ke.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&ke.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&ke.instancingMorph===!1&&X.morphTexture!==null||ke.envMap!==Je||K.fog===!0&&ke.fog!==Ie||ke.numClippingPlanes!==void 0&&(ke.numClippingPlanes!==it.numPlanes||ke.numIntersection!==it.numIntersection)||ke.vertexAlphas!==Dt||ke.vertexTangents!==Ft||ke.morphTargets!==Qe||ke.morphNormals!==_i||ke.morphColors!==Es||ke.toneMapping!==fs||ke.morphTargetsCount!==wn||!!ke.lightProbeGrid!=x.state.lightProbeGridArray.length>0)&&(qt=!0):(qt=!0,ke.__version=K.version);let Br=ke.currentProgram;qt===!0&&(Br=If(K,G,X),k&&K.isNodeMaterial&&k.onUpdateProgram(K,Br,ke));let Ia=!1,sl=!1,lh=!1;const Ri=Br.getUniforms(),As=ke.uniforms;if(I.useProgram(Br.program)&&(Ia=!0,sl=!0,lh=!0),K.id!==j&&(j=K.id,sl=!0),ke.needsLights){const Ni=CI(x.state.lightProbeGridArray,X);ke.lightProbeGrid!==Ni&&(ke.lightProbeGrid=Ni,sl=!0)}if(Ia||W!==R){I.buffers.depth.getReversed()&&R.reversedDepth!==!0&&(R._reversedDepth=!0,R.updateProjectionMatrix()),Ri.setValue(z,"projectionMatrix",R.projectionMatrix),Ri.setValue(z,"viewMatrix",R.matrixWorldInverse);const rl=Ri.map.cameraPosition;rl!==void 0&&rl.setValue(z,mi.setFromMatrixPosition(R.matrixWorld)),O.logarithmicDepthBuffer&&Ri.setValue(z,"logDepthBufFC",2/(Math.log(R.far+1)/Math.LN2)),(K.isMeshPhongMaterial||K.isMeshToonMaterial||K.isMeshLambertMaterial||K.isMeshBasicMaterial||K.isMeshStandardMaterial||K.isShaderMaterial)&&Ri.setValue(z,"isOrthographic",R.isOrthographicCamera===!0),W!==R&&(W=R,sl=!0,lh=!0)}if(ke.needsLights&&(Sr.state.directionalShadowMap.length>0&&Ri.setValue(z,"directionalShadowMap",Sr.state.directionalShadowMap,ee),Sr.state.spotShadowMap.length>0&&Ri.setValue(z,"spotShadowMap",Sr.state.spotShadowMap,ee),Sr.state.pointShadowMap.length>0&&Ri.setValue(z,"pointShadowMap",Sr.state.pointShadowMap,ee)),X.isSkinnedMesh){Ri.setOptional(z,X,"bindMatrix"),Ri.setOptional(z,X,"bindMatrixInverse");const Ni=X.skeleton;Ni&&(Ni.boneTexture===null&&Ni.computeBoneTexture(),Ri.setValue(z,"boneTexture",Ni.boneTexture,ee))}X.isBatchedMesh&&(Ri.setOptional(z,X,"batchingTexture"),Ri.setValue(z,"batchingTexture",X._matricesTexture,ee),Ri.setOptional(z,X,"batchingIdTexture"),Ri.setValue(z,"batchingIdTexture",X._indirectTexture,ee),Ri.setOptional(z,X,"batchingColorTexture"),X._colorsTexture!==null&&Ri.setValue(z,"batchingColorTexture",X._colorsTexture,ee));const nl=q.morphAttributes;if((nl.position!==void 0||nl.normal!==void 0||nl.color!==void 0)&&B.update(X,q,Br),(sl||ke.receiveShadow!==X.receiveShadow)&&(ke.receiveShadow=X.receiveShadow,Ri.setValue(z,"receiveShadow",X.receiveShadow)),(K.isMeshStandardMaterial||K.isMeshLambertMaterial||K.isMeshPhongMaterial)&&K.envMap===null&&G.environment!==null&&(As.envMapIntensity.value=G.environmentIntensity),As.dfgLUT!==void 0&&(As.dfgLUT.value=FN()),sl){if(Ri.setValue(z,"toneMappingExposure",T.toneMappingExposure),ke.needsLights&&OI(As,lh),Ie&&K.fog===!0&&Ze.refreshFogUniforms(As,Ie),Ze.refreshMaterialUniforms(As,K,le,ce,x.state.transmissionRenderTarget[R.id]),ke.needsLights&&ke.lightProbeGrid){const Ni=ke.lightProbeGrid;As.probesSH.value=Ni.texture,As.probesMin.value.copy(Ni.boundingBox.min),As.probesMax.value.copy(Ni.boundingBox.max),As.probesResolution.value.copy(Ni.resolution)}u0.upload(z,gM(ke),As,ee)}if(K.isShaderMaterial&&K.uniformsNeedUpdate===!0&&(u0.upload(z,gM(ke),As,ee),K.uniformsNeedUpdate=!1),K.isSpriteMaterial&&Ri.setValue(z,"center",X.center),Ri.setValue(z,"modelViewMatrix",X.modelViewMatrix),Ri.setValue(z,"normalMatrix",X.normalMatrix),Ri.setValue(z,"modelMatrix",X.matrixWorld),K.uniformsGroups!==void 0){const Ni=K.uniformsGroups;for(let rl=0,ch=Ni.length;rl<ch;rl++){const bM=Ni[rl];ae.update(bM,Br),ae.bind(bM,Br)}}return Br}function OI(R,G){R.ambientLightColor.needsUpdate=G,R.lightProbe.needsUpdate=G,R.directionalLights.needsUpdate=G,R.directionalLightShadows.needsUpdate=G,R.pointLights.needsUpdate=G,R.pointLightShadows.needsUpdate=G,R.spotLights.needsUpdate=G,R.spotLightShadows.needsUpdate=G,R.rectAreaLights.needsUpdate=G,R.hemisphereLights.needsUpdate=G}function PI(R){return R.isMeshLambertMaterial||R.isMeshToonMaterial||R.isMeshPhongMaterial||R.isMeshStandardMaterial||R.isShadowMaterial||R.isShaderMaterial&&R.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return F},this.getRenderTarget=function(){return H},this.setRenderTargetTextures=function(R,G,q){const K=Y.get(R);K.__autoAllocateDepthBuffer=R.resolveDepthBuffer===!1,K.__autoAllocateDepthBuffer===!1&&(K.__useRenderToTexture=!1),Y.get(R.texture).__webglTexture=G,Y.get(R.depthTexture).__webglTexture=K.__autoAllocateDepthBuffer?void 0:q,K.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(R,G){const q=Y.get(R);q.__webglFramebuffer=G,q.__useDefaultFramebuffer=G===void 0},this.setRenderTarget=function(R,G=0,q=0){H=R,N=G,F=q;let K=null,X=!1,Ie=!1;if(R){const Te=Y.get(R);if(Te.__useDefaultFramebuffer!==void 0){I.bindFramebuffer(z.FRAMEBUFFER,Te.__webglFramebuffer),J.copy(R.viewport),re.copy(R.scissor),Le=R.scissorTest,I.viewport(J),I.scissor(re),I.setScissorTest(Le),j=-1;return}else if(Te.__webglFramebuffer===void 0)ee.setupRenderTarget(R);else if(Te.__hasExternalTextures)ee.rebindTextures(R,Y.get(R.texture).__webglTexture,Y.get(R.depthTexture).__webglTexture);else if(R.depthBuffer){const Dt=R.depthTexture;if(Te.__boundDepthTexture!==Dt){if(Dt!==null&&Y.has(Dt)&&(R.width!==Dt.image.width||R.height!==Dt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");ee.setupDepthRenderbuffer(R)}}const Ge=R.texture;(Ge.isData3DTexture||Ge.isDataArrayTexture||Ge.isCompressedArrayTexture)&&(Ie=!0);const Je=Y.get(R).__webglFramebuffer;R.isWebGLCubeRenderTarget?(Array.isArray(Je[G])?K=Je[G][q]:K=Je[G],X=!0):R.samples>0&&ee.useMultisampledRTT(R)===!1?K=Y.get(R).__webglMultisampledFramebuffer:Array.isArray(Je)?K=Je[q]:K=Je,J.copy(R.viewport),re.copy(R.scissor),Le=R.scissorTest}else J.copy(je).multiplyScalar(le).floor(),re.copy(Be).multiplyScalar(le).floor(),Le=Oe;if(q!==0&&(K=L),I.bindFramebuffer(z.FRAMEBUFFER,K)&&I.drawBuffers(R,K),I.viewport(J),I.scissor(re),I.setScissorTest(Le),X){const Te=Y.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+G,Te.__webglTexture,q)}else if(Ie){const Te=G;for(let Ge=0;Ge<R.textures.length;Ge++){const Je=Y.get(R.textures[Ge]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+Ge,Je.__webglTexture,q,Te)}}else if(R!==null&&q!==0){const Te=Y.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Te.__webglTexture,q)}j=-1},this.readRenderTargetPixels=function(R,G,q,K,X,Ie,Pe,Te=0){if(!(R&&R.isWebGLRenderTarget)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ge=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0&&(Ge=Ge[Pe]),Ge){I.bindFramebuffer(z.FRAMEBUFFER,Ge);try{const Je=R.textures[Te],Dt=Je.format,Ft=Je.type;if(R.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+Te),!O.textureFormatReadable(Dt)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!O.textureTypeReadable(Ft)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}G>=0&&G<=R.width-K&&q>=0&&q<=R.height-X&&z.readPixels(G,q,K,X,ye.convert(Dt),ye.convert(Ft),Ie)}finally{const Je=H!==null?Y.get(H).__webglFramebuffer:null;I.bindFramebuffer(z.FRAMEBUFFER,Je)}}},this.readRenderTargetPixelsAsync=async function(R,G,q,K,X,Ie,Pe,Te=0){if(!(R&&R.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ge=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0&&(Ge=Ge[Pe]),Ge)if(G>=0&&G<=R.width-K&&q>=0&&q<=R.height-X){I.bindFramebuffer(z.FRAMEBUFFER,Ge);const Je=R.textures[Te],Dt=Je.format,Ft=Je.type;if(R.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+Te),!O.textureFormatReadable(Dt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!O.textureTypeReadable(Ft))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Qe=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Qe),z.bufferData(z.PIXEL_PACK_BUFFER,Ie.byteLength,z.STREAM_READ),z.readPixels(G,q,K,X,ye.convert(Dt),ye.convert(Ft),0);const _i=H!==null?Y.get(H).__webglFramebuffer:null;I.bindFramebuffer(z.FRAMEBUFFER,_i);const Es=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await LR(z,Es,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Qe),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,Ie),z.deleteBuffer(Qe),z.deleteSync(Es),Ie}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(R,G=null,q=0){const K=Math.pow(2,-q),X=Math.floor(R.image.width*K),Ie=Math.floor(R.image.height*K),Pe=G!==null?G.x:0,Te=G!==null?G.y:0;ee.setTexture2D(R,0),z.copyTexSubImage2D(z.TEXTURE_2D,q,0,0,Pe,Te,X,Ie),I.unbindTexture()},this.copyTextureToTexture=function(R,G,q=null,K=null,X=0,Ie=0){let Pe,Te,Ge,Je,Dt,Ft,Qe,_i,Es;const fs=R.isCompressedTexture?R.mipmaps[Ie]:R.image;if(q!==null)Pe=q.max.x-q.min.x,Te=q.max.y-q.min.y,Ge=q.isBox3?q.max.z-q.min.z:1,Je=q.min.x,Dt=q.min.y,Ft=q.isBox3?q.min.z:0;else{const As=Math.pow(2,-X);Pe=Math.floor(fs.width*As),Te=Math.floor(fs.height*As),R.isDataArrayTexture?Ge=fs.depth:R.isData3DTexture?Ge=Math.floor(fs.depth*As):Ge=1,Je=0,Dt=0,Ft=0}K!==null?(Qe=K.x,_i=K.y,Es=K.z):(Qe=0,_i=0,Es=0);const ki=ye.convert(G.format),wn=ye.convert(G.type);let ke;G.isData3DTexture?(ee.setTexture3D(G,0),ke=z.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(ee.setTexture2DArray(G,0),ke=z.TEXTURE_2D_ARRAY):(ee.setTexture2D(G,0),ke=z.TEXTURE_2D),I.activeTexture(z.TEXTURE0),I.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,G.flipY),I.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),I.pixelStorei(z.UNPACK_ALIGNMENT,G.unpackAlignment);const Sr=I.getParameter(z.UNPACK_ROW_LENGTH),qt=I.getParameter(z.UNPACK_IMAGE_HEIGHT),Br=I.getParameter(z.UNPACK_SKIP_PIXELS),Ia=I.getParameter(z.UNPACK_SKIP_ROWS),sl=I.getParameter(z.UNPACK_SKIP_IMAGES);I.pixelStorei(z.UNPACK_ROW_LENGTH,fs.width),I.pixelStorei(z.UNPACK_IMAGE_HEIGHT,fs.height),I.pixelStorei(z.UNPACK_SKIP_PIXELS,Je),I.pixelStorei(z.UNPACK_SKIP_ROWS,Dt),I.pixelStorei(z.UNPACK_SKIP_IMAGES,Ft);const lh=R.isDataArrayTexture||R.isData3DTexture,Ri=G.isDataArrayTexture||G.isData3DTexture;if(R.isDepthTexture){const As=Y.get(R),nl=Y.get(G),Ni=Y.get(As.__renderTarget),rl=Y.get(nl.__renderTarget);I.bindFramebuffer(z.READ_FRAMEBUFFER,Ni.__webglFramebuffer),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,rl.__webglFramebuffer);for(let ch=0;ch<Ge;ch++)lh&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(R).__webglTexture,X,Ft+ch),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(G).__webglTexture,Ie,Es+ch)),z.blitFramebuffer(Je,Dt,Pe,Te,Qe,_i,Pe,Te,z.DEPTH_BUFFER_BIT,z.NEAREST);I.bindFramebuffer(z.READ_FRAMEBUFFER,null),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(X!==0||R.isRenderTargetTexture||Y.has(R)){const As=Y.get(R),nl=Y.get(G);I.bindFramebuffer(z.READ_FRAMEBUFFER,P),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,C);for(let Ni=0;Ni<Ge;Ni++)lh?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,As.__webglTexture,X,Ft+Ni):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,As.__webglTexture,X),Ri?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,nl.__webglTexture,Ie,Es+Ni):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,nl.__webglTexture,Ie),X!==0?z.blitFramebuffer(Je,Dt,Pe,Te,Qe,_i,Pe,Te,z.COLOR_BUFFER_BIT,z.NEAREST):Ri?z.copyTexSubImage3D(ke,Ie,Qe,_i,Es+Ni,Je,Dt,Pe,Te):z.copyTexSubImage2D(ke,Ie,Qe,_i,Je,Dt,Pe,Te);I.bindFramebuffer(z.READ_FRAMEBUFFER,null),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else Ri?R.isDataTexture||R.isData3DTexture?z.texSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,wn,fs.data):G.isCompressedArrayTexture?z.compressedTexSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,fs.data):z.texSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,wn,fs):R.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,Pe,Te,ki,wn,fs.data):R.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,fs.width,fs.height,ki,fs.data):z.texSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,Pe,Te,ki,wn,fs);I.pixelStorei(z.UNPACK_ROW_LENGTH,Sr),I.pixelStorei(z.UNPACK_IMAGE_HEIGHT,qt),I.pixelStorei(z.UNPACK_SKIP_PIXELS,Br),I.pixelStorei(z.UNPACK_SKIP_ROWS,Ia),I.pixelStorei(z.UNPACK_SKIP_IMAGES,sl),Ie===0&&G.generateMipmaps&&z.generateMipmap(ke),I.unbindTexture()},this.initRenderTarget=function(R){Y.get(R).__webglFramebuffer===void 0&&ee.setupRenderTarget(R)},this.initTexture=function(R){R.isCubeTexture?ee.setTextureCube(R,0):R.isData3DTexture?ee.setTexture3D(R,0):R.isDataArrayTexture||R.isCompressedArrayTexture?ee.setTexture2DArray(R,0):ee.setTexture2D(R,0),I.unbindTexture()},this.resetState=function(){N=0,F=0,H=null,I.reset(),_e.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ro}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Kt._getDrawingBufferColorSpace(e),t.unpackColorSpace=Kt._getUnpackColorSpace()}}const BN=`
|
|
8930
|
+
}`;class RN{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new M3(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Nt({vertexShader:DN,fragmentShader:kN,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Me(new zn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class CN extends oc{constructor(e,t){super();const i=this;let s=null,n=1,r=null,a="local-floor",o=1,c=null,h=null,d=null,u=null,p=null,f=null;const m=typeof XRWebGLBinding<"u",v=new RN,g={},b=t.getContextAttributes();let w=null,y=null;const M=[],x=[],E=new ie;let S=null;const A=new vn;A.viewport=new Lt;const T=new vn;T.viewport=new Lt;const _=[A,T],k=new IC;let L=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getTargetRaySpace()},this.getControllerGrip=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getGripSpace()},this.getHand=function(Z){let ce=M[Z];return ce===void 0&&(ce=new Iv,M[Z]=ce),ce.getHandSpace()};function C(Z){const ce=x.indexOf(Z.inputSource);if(ce===-1)return;const le=M[ce];le!==void 0&&(le.update(Z.inputSource,Z.frame,c||r),le.dispatchEvent({type:Z.type,data:Z.inputSource}))}function N(){s.removeEventListener("select",C),s.removeEventListener("selectstart",C),s.removeEventListener("selectend",C),s.removeEventListener("squeeze",C),s.removeEventListener("squeezestart",C),s.removeEventListener("squeezeend",C),s.removeEventListener("end",N),s.removeEventListener("inputsourceschange",F);for(let Z=0;Z<M.length;Z++){const ce=x[Z];ce!==null&&(x[Z]=null,M[Z].disconnect(ce))}L=null,P=null,v.reset();for(const Z in g)delete g[Z];e.setRenderTarget(w),p=null,u=null,d=null,s=null,y=null,De.stop(),i.isPresenting=!1,e.setPixelRatio(S),e.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Z){n=Z,i.isPresenting===!0&&We("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Z){a=Z,i.isPresenting===!0&&We("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||r},this.setReferenceSpace=function(Z){c=Z},this.getBaseLayer=function(){return u!==null?u:p},this.getBinding=function(){return d===null&&m&&(d=new XRWebGLBinding(s,t)),d},this.getFrame=function(){return f},this.getSession=function(){return s},this.setSession=async function(Z){if(s=Z,s!==null){if(w=e.getRenderTarget(),s.addEventListener("select",C),s.addEventListener("selectstart",C),s.addEventListener("selectend",C),s.addEventListener("squeeze",C),s.addEventListener("squeezestart",C),s.addEventListener("squeezeend",C),s.addEventListener("end",N),s.addEventListener("inputsourceschange",F),b.xrCompatible!==!0&&await t.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(E),m&&"createProjectionLayer"in XRWebGLBinding.prototype){let le=null,$=null,Ue=null;b.depth&&(Ue=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,le=b.stencil?Fc:Zo,$=b.stencil?of:Qr);const je={colorFormat:t.RGBA8,depthFormat:Ue,scaleFactor:n};d=this.getBinding(),u=d.createProjectionLayer(je),s.updateRenderState({layers:[u]}),e.setPixelRatio(1),e.setSize(u.textureWidth,u.textureHeight,!1),y=new oi(u.textureWidth,u.textureHeight,{format:xs,type:On,depthTexture:new nc(u.textureWidth,u.textureHeight,$,void 0,void 0,void 0,void 0,void 0,void 0,le),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1})}else{const le={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:n};p=new XRWebGLLayer(s,t,le),s.updateRenderState({baseLayer:p}),e.setPixelRatio(1),e.setSize(p.framebufferWidth,p.framebufferHeight,!1),y=new oi(p.framebufferWidth,p.framebufferHeight,{format:xs,type:On,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:p.ignoreDepthValues===!1,resolveStencilBuffer:p.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(o),c=null,r=await s.requestReferenceSpace(a),De.setContext(s),De.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return v.getDepthTexture()};function F(Z){for(let ce=0;ce<Z.removed.length;ce++){const le=Z.removed[ce],$=x.indexOf(le);$>=0&&(x[$]=null,M[$].disconnect(le))}for(let ce=0;ce<Z.added.length;ce++){const le=Z.added[ce];let $=x.indexOf(le);if($===-1){for(let je=0;je<M.length;je++)if(je>=x.length){x.push(le),$=je;break}else if(x[je]===null){x[je]=le,$=je;break}if($===-1)break}const Ue=M[$];Ue&&Ue.connect(le)}}const H=new D,j=new D;function W(Z,ce,le){H.setFromMatrixPosition(ce.matrixWorld),j.setFromMatrixPosition(le.matrixWorld);const $=H.distanceTo(j),Ue=ce.projectionMatrix.elements,je=le.projectionMatrix.elements,Be=Ue[14]/(Ue[10]-1),Oe=Ue[14]/(Ue[10]+1),nt=(Ue[9]+1)/Ue[5],lt=(Ue[9]-1)/Ue[5],ct=(Ue[8]-1)/Ue[0],fi=(je[8]+1)/je[0],mi=Be*ct,ds=Be*fi,ts=$/(-ct+fi),us=ts*-ct;if(ce.matrixWorld.decompose(Z.position,Z.quaternion,Z.scale),Z.translateX(us),Z.translateZ(ts),Z.matrixWorld.compose(Z.position,Z.quaternion,Z.scale),Z.matrixWorldInverse.copy(Z.matrixWorld).invert(),Ue[10]===-1)Z.projectionMatrix.copy(ce.projectionMatrix),Z.projectionMatrixInverse.copy(ce.projectionMatrixInverse);else{const Cs=Be+ts,z=Oe+ts,ar=mi-us,gi=ds+($-us),O=nt*Oe/z*Cs,I=lt*Oe/z*Cs;Z.projectionMatrix.makePerspective(ar,gi,O,I,Cs,z),Z.projectionMatrixInverse.copy(Z.projectionMatrix).invert()}}function J(Z,ce){ce===null?Z.matrixWorld.copy(Z.matrix):Z.matrixWorld.multiplyMatrices(ce.matrixWorld,Z.matrix),Z.matrixWorldInverse.copy(Z.matrixWorld).invert()}this.updateCamera=function(Z){if(s===null)return;let ce=Z.near,le=Z.far;v.texture!==null&&(v.depthNear>0&&(ce=v.depthNear),v.depthFar>0&&(le=v.depthFar)),k.near=T.near=A.near=ce,k.far=T.far=A.far=le,(L!==k.near||P!==k.far)&&(s.updateRenderState({depthNear:k.near,depthFar:k.far}),L=k.near,P=k.far),k.layers.mask=Z.layers.mask|6,A.layers.mask=k.layers.mask&-5,T.layers.mask=k.layers.mask&-3;const $=Z.parent,Ue=k.cameras;J(k,$);for(let je=0;je<Ue.length;je++)J(Ue[je],$);Ue.length===2?W(k,A,T):k.projectionMatrix.copy(A.projectionMatrix),re(Z,k,$)};function re(Z,ce,le){le===null?Z.matrix.copy(ce.matrixWorld):(Z.matrix.copy(le.matrixWorld),Z.matrix.invert(),Z.matrix.multiply(ce.matrixWorld)),Z.matrix.decompose(Z.position,Z.quaternion,Z.scale),Z.updateMatrixWorld(!0),Z.projectionMatrix.copy(ce.projectionMatrix),Z.projectionMatrixInverse.copy(ce.projectionMatrixInverse),Z.isPerspectiveCamera&&(Z.fov=su*2*Math.atan(1/Z.projectionMatrix.elements[5]),Z.zoom=1)}this.getCamera=function(){return k},this.getFoveation=function(){if(!(u===null&&p===null))return o},this.setFoveation=function(Z){o=Z,u!==null&&(u.fixedFoveation=Z),p!==null&&p.fixedFoveation!==void 0&&(p.fixedFoveation=Z)},this.hasDepthSensing=function(){return v.texture!==null},this.getDepthSensingMesh=function(){return v.getMesh(k)},this.getCameraTexture=function(Z){return g[Z]};let Le=null;function He(Z,ce){if(h=ce.getViewerPose(c||r),f=ce,h!==null){const le=h.views;p!==null&&(e.setRenderTargetFramebuffer(y,p.framebuffer),e.setRenderTarget(y));let $=!1;le.length!==k.cameras.length&&(k.cameras.length=0,$=!0);for(let Oe=0;Oe<le.length;Oe++){const nt=le[Oe];let lt=null;if(p!==null)lt=p.getViewport(nt);else{const fi=d.getViewSubImage(u,nt);lt=fi.viewport,Oe===0&&(e.setRenderTargetTextures(y,fi.colorTexture,fi.depthStencilTexture),e.setRenderTarget(y))}let ct=_[Oe];ct===void 0&&(ct=new vn,ct.layers.enable(Oe),ct.viewport=new Lt,_[Oe]=ct),ct.matrix.fromArray(nt.transform.matrix),ct.matrix.decompose(ct.position,ct.quaternion,ct.scale),ct.projectionMatrix.fromArray(nt.projectionMatrix),ct.projectionMatrixInverse.copy(ct.projectionMatrix).invert(),ct.viewport.set(lt.x,lt.y,lt.width,lt.height),Oe===0&&(k.matrix.copy(ct.matrix),k.matrix.decompose(k.position,k.quaternion,k.scale)),$===!0&&k.cameras.push(ct)}const Ue=s.enabledFeatures;if(Ue&&Ue.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&m){d=i.getBinding();const Oe=d.getDepthInformation(le[0]);Oe&&Oe.isValid&&Oe.texture&&v.init(Oe,s.renderState)}if(Ue&&Ue.includes("camera-access")&&m){e.state.unbindTexture(),d=i.getBinding();for(let Oe=0;Oe<le.length;Oe++){const nt=le[Oe].camera;if(nt){let lt=g[nt];lt||(lt=new M3,g[nt]=lt);const ct=d.getCameraImage(nt);lt.sourceTexture=ct}}}}for(let le=0;le<M.length;le++){const $=x[le],Ue=M[le];$!==null&&Ue!==void 0&&Ue.update($,ce,c||r)}Le&&Le(Z,ce),ce.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ce}),f=null}const De=new U3;De.setAnimationLoop(He),this.setAnimationLoop=function(Z){Le=Z},this.dispose=function(){}}}const LN=new qe,W3=new bt;W3.set(-1,0,0,0,1,0,0,0,1);function ON(l,e){function t(v,g){v.matrixAutoUpdate===!0&&v.updateMatrix(),g.value.copy(v.matrix)}function i(v,g){g.color.getRGB(v.fogColor.value,k3(l)),g.isFog?(v.fogNear.value=g.near,v.fogFar.value=g.far):g.isFogExp2&&(v.fogDensity.value=g.density)}function s(v,g,b,w,y){g.isNodeMaterial?g.uniformsNeedUpdate=!1:g.isMeshBasicMaterial?n(v,g):g.isMeshLambertMaterial?(n(v,g),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)):g.isMeshToonMaterial?(n(v,g),d(v,g)):g.isMeshPhongMaterial?(n(v,g),h(v,g),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)):g.isMeshStandardMaterial?(n(v,g),u(v,g),g.isMeshPhysicalMaterial&&p(v,g,y)):g.isMeshMatcapMaterial?(n(v,g),f(v,g)):g.isMeshDepthMaterial?n(v,g):g.isMeshDistanceMaterial?(n(v,g),m(v,g)):g.isMeshNormalMaterial?n(v,g):g.isLineBasicMaterial?(r(v,g),g.isLineDashedMaterial&&a(v,g)):g.isPointsMaterial?o(v,g,b,w):g.isSpriteMaterial?c(v,g):g.isShadowMaterial?(v.color.value.copy(g.color),v.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function n(v,g){v.opacity.value=g.opacity,g.color&&v.diffuse.value.copy(g.color),g.emissive&&v.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(v.map.value=g.map,t(g.map,v.mapTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.bumpMap&&(v.bumpMap.value=g.bumpMap,t(g.bumpMap,v.bumpMapTransform),v.bumpScale.value=g.bumpScale,g.side===Ji&&(v.bumpScale.value*=-1)),g.normalMap&&(v.normalMap.value=g.normalMap,t(g.normalMap,v.normalMapTransform),v.normalScale.value.copy(g.normalScale),g.side===Ji&&v.normalScale.value.negate()),g.displacementMap&&(v.displacementMap.value=g.displacementMap,t(g.displacementMap,v.displacementMapTransform),v.displacementScale.value=g.displacementScale,v.displacementBias.value=g.displacementBias),g.emissiveMap&&(v.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,v.emissiveMapTransform)),g.specularMap&&(v.specularMap.value=g.specularMap,t(g.specularMap,v.specularMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest);const b=e.get(g),w=b.envMap,y=b.envMapRotation;w&&(v.envMap.value=w,v.envMapRotation.value.setFromMatrix4(LN.makeRotationFromEuler(y)).transpose(),w.isCubeTexture&&w.isRenderTargetTexture===!1&&v.envMapRotation.value.premultiply(W3),v.reflectivity.value=g.reflectivity,v.ior.value=g.ior,v.refractionRatio.value=g.refractionRatio),g.lightMap&&(v.lightMap.value=g.lightMap,v.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,v.lightMapTransform)),g.aoMap&&(v.aoMap.value=g.aoMap,v.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,v.aoMapTransform))}function r(v,g){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,g.map&&(v.map.value=g.map,t(g.map,v.mapTransform))}function a(v,g){v.dashSize.value=g.dashSize,v.totalSize.value=g.dashSize+g.gapSize,v.scale.value=g.scale}function o(v,g,b,w){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,v.size.value=g.size*b,v.scale.value=w*.5,g.map&&(v.map.value=g.map,t(g.map,v.uvTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest)}function c(v,g){v.diffuse.value.copy(g.color),v.opacity.value=g.opacity,v.rotation.value=g.rotation,g.map&&(v.map.value=g.map,t(g.map,v.mapTransform)),g.alphaMap&&(v.alphaMap.value=g.alphaMap,t(g.alphaMap,v.alphaMapTransform)),g.alphaTest>0&&(v.alphaTest.value=g.alphaTest)}function h(v,g){v.specular.value.copy(g.specular),v.shininess.value=Math.max(g.shininess,1e-4)}function d(v,g){g.gradientMap&&(v.gradientMap.value=g.gradientMap)}function u(v,g){v.metalness.value=g.metalness,g.metalnessMap&&(v.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,v.metalnessMapTransform)),v.roughness.value=g.roughness,g.roughnessMap&&(v.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,v.roughnessMapTransform)),g.envMap&&(v.envMapIntensity.value=g.envMapIntensity)}function p(v,g,b){v.ior.value=g.ior,g.sheen>0&&(v.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),v.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(v.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,v.sheenColorMapTransform)),g.sheenRoughnessMap&&(v.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,v.sheenRoughnessMapTransform))),g.clearcoat>0&&(v.clearcoat.value=g.clearcoat,v.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(v.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,v.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(v.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,v.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(v.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,v.clearcoatNormalMapTransform),v.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===Ji&&v.clearcoatNormalScale.value.negate())),g.dispersion>0&&(v.dispersion.value=g.dispersion),g.iridescence>0&&(v.iridescence.value=g.iridescence,v.iridescenceIOR.value=g.iridescenceIOR,v.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],v.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(v.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,v.iridescenceMapTransform)),g.iridescenceThicknessMap&&(v.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,v.iridescenceThicknessMapTransform))),g.transmission>0&&(v.transmission.value=g.transmission,v.transmissionSamplerMap.value=b.texture,v.transmissionSamplerSize.value.set(b.width,b.height),g.transmissionMap&&(v.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,v.transmissionMapTransform)),v.thickness.value=g.thickness,g.thicknessMap&&(v.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,v.thicknessMapTransform)),v.attenuationDistance.value=g.attenuationDistance,v.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(v.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(v.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,v.anisotropyMapTransform))),v.specularIntensity.value=g.specularIntensity,v.specularColor.value.copy(g.specularColor),g.specularColorMap&&(v.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,v.specularColorMapTransform)),g.specularIntensityMap&&(v.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,v.specularIntensityMapTransform))}function f(v,g){g.matcap&&(v.matcap.value=g.matcap)}function m(v,g){const b=e.get(g).light;v.referencePosition.value.setFromMatrixPosition(b.matrixWorld),v.nearDistance.value=b.shadow.camera.near,v.farDistance.value=b.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function PN(l,e,t,i){let s={},n={},r=[];const a=l.getParameter(l.MAX_UNIFORM_BUFFER_BINDINGS);function o(y,M){const x=M.program;i.uniformBlockBinding(y,x)}function c(y,M){let x=s[y.id];x===void 0&&(v(y),x=h(y),s[y.id]=x,y.addEventListener("dispose",b));const E=M.program;i.updateUBOMapping(y,E);const S=e.render.frame;n[y.id]!==S&&(u(y),n[y.id]=S)}function h(y){const M=d();y.__bindingPointIndex=M;const x=l.createBuffer(),E=y.__size,S=y.usage;return l.bindBuffer(l.UNIFORM_BUFFER,x),l.bufferData(l.UNIFORM_BUFFER,E,S),l.bindBuffer(l.UNIFORM_BUFFER,null),l.bindBufferBase(l.UNIFORM_BUFFER,M,x),x}function d(){for(let y=0;y<a;y++)if(r.indexOf(y)===-1)return r.push(y),y;return ft("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function u(y){const M=s[y.id],x=y.uniforms,E=y.__cache;l.bindBuffer(l.UNIFORM_BUFFER,M);for(let S=0,A=x.length;S<A;S++){const T=x[S];if(Array.isArray(T))for(let _=0,k=T.length;_<k;_++)p(T[_],S,_,E);else p(T,S,0,E)}l.bindBuffer(l.UNIFORM_BUFFER,null)}function p(y,M,x,E){if(m(y,M,x,E)===!0){const S=y.__offset,A=y.value;if(Array.isArray(A)){let T=0;for(let _=0;_<A.length;_++){const k=A[_],L=g(k);f(k,y.__data,T),typeof k!="number"&&typeof k!="boolean"&&!k.isMatrix3&&!ArrayBuffer.isView(k)&&(T+=L.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(A,y.__data,0);l.bufferSubData(l.UNIFORM_BUFFER,S,y.__data)}}function f(y,M,x){typeof y=="number"||typeof y=="boolean"?M[0]=y:y.isMatrix3?(M[0]=y.elements[0],M[1]=y.elements[1],M[2]=y.elements[2],M[3]=0,M[4]=y.elements[3],M[5]=y.elements[4],M[6]=y.elements[5],M[7]=0,M[8]=y.elements[6],M[9]=y.elements[7],M[10]=y.elements[8],M[11]=0):ArrayBuffer.isView(y)?M.set(new y.constructor(y.buffer,y.byteOffset,M.length)):y.toArray(M,x)}function m(y,M,x,E){const S=y.value,A=M+"_"+x;if(E[A]===void 0)return typeof S=="number"||typeof S=="boolean"?E[A]=S:ArrayBuffer.isView(S)?E[A]=S.slice():E[A]=S.clone(),!0;{const T=E[A];if(typeof S=="number"||typeof S=="boolean"){if(T!==S)return E[A]=S,!0}else{if(ArrayBuffer.isView(S))return!0;if(T.equals(S)===!1)return T.copy(S),!0}}return!1}function v(y){const M=y.uniforms;let x=0;const E=16;for(let A=0,T=M.length;A<T;A++){const _=Array.isArray(M[A])?M[A]:[M[A]];for(let k=0,L=_.length;k<L;k++){const P=_[k],C=Array.isArray(P.value)?P.value:[P.value];for(let N=0,F=C.length;N<F;N++){const H=C[N],j=g(H),W=x%E,J=W%j.boundary,re=W+J;x+=J,re!==0&&E-re<j.storage&&(x+=E-re),P.__data=new Float32Array(j.storage/Float32Array.BYTES_PER_ELEMENT),P.__offset=x,x+=j.storage}}}const S=x%E;return S>0&&(x+=E-S),y.__size=x,y.__cache={},this}function g(y){const M={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(M.boundary=4,M.storage=4):y.isVector2?(M.boundary=8,M.storage=8):y.isVector3||y.isColor?(M.boundary=16,M.storage=12):y.isVector4?(M.boundary=16,M.storage=16):y.isMatrix3?(M.boundary=48,M.storage=48):y.isMatrix4?(M.boundary=64,M.storage=64):y.isTexture?We("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(M.boundary=16,M.storage=y.byteLength):We("WebGLRenderer: Unsupported uniform value type.",y),M}function b(y){const M=y.target;M.removeEventListener("dispose",b);const x=r.indexOf(M.__bindingPointIndex);r.splice(x,1),l.deleteBuffer(s[M.id]),delete s[M.id],delete n[M.id]}function w(){for(const y in s)l.deleteBuffer(s[y]);r=[],s={},n={}}return{bind:o,update:c,dispose:w}}const NN=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ka=null;function FN(){return ka===null&&(ka=new nr(NN,16,16,rh,ti),ka.name="DFG_LUT",ka.minFilter=St,ka.magFilter=St,ka.wrapS=Ms,ka.wrapT=Ms,ka.generateMipmaps=!1,ka.needsUpdate=!0),ka}class UN{constructor(e={}){const{canvas:t=CR(),context:i=null,depth:s=!0,stencil:n=!1,alpha:r=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:c=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:d=!1,reversedDepthBuffer:u=!1,outputBufferType:p=On}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=r;const m=p,v=new Set([_w,Iw,Tw]),g=new Set([On,Qr,af,of,Ew,Aw]),b=new Uint32Array(4),w=new Int32Array(4),y=new D;let M=null,x=null;const E=[],S=[];let A=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=oo,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let _=!1,k=null,L=null,P=null,C=null;this._outputColorSpace=an;let N=0,F=0,H=null,j=-1,W=null;const J=new Lt,re=new Lt;let Le=null;const He=new oe(0);let De=0,Z=t.width,ce=t.height,le=1,$=null,Ue=null;const je=new Lt(0,0,Z,ce),Be=new Lt(0,0,Z,ce);let Oe=!1;const nt=new zg;let lt=!1,ct=!1;const fi=new qe,mi=new D,ds=new Lt,ts={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let us=!1;function Cs(){return H===null?le:1}let z=i;function ar(R,G){return t.getContext(R,G)}try{const R={alpha:!0,depth:s,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:c,powerPreference:h,failIfMajorPerformanceCaveat:d};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Sf}`),t.addEventListener("webglcontextlost",ps,!1),t.addEventListener("webglcontextrestored",Pi,!1),t.addEventListener("webglcontextcreationerror",Aa,!1),z===null){const G="webgl2";if(z=ar(G,R),z===null)throw ar(G)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(R){throw ft("WebGLRenderer: "+R.message),R}let gi,O,I,V,Y,ee,de,me,te,ne,ve,Ze,Ee,be,it,dt,Dt,B,fe,se,ye,_e,ae;function Xe(){gi=new FP(z),gi.init(),ye=new _N(z,gi),O=new DP(z,gi,e,ye),I=new TN(z,gi),O.reversedDepthBuffer&&u&&I.buffers.depth.setReversed(!0),L=z.createFramebuffer(),P=z.createFramebuffer(),C=z.createFramebuffer(),V=new zP(z),Y=new uN,ee=new IN(z,gi,I,Y,O,ye,V),de=new NP(T),me=new WC(z),_e=new IP(z,me),te=new UP(z,me,V,_e),ne=new GP(z,te,me,_e,V),B=new HP(z,O,ee),it=new kP(Y),ve=new dN(T,de,gi,O,_e,it),Ze=new ON(T,Y),Ee=new fN,be=new wN(gi),Dt=new TP(T,de,I,ne,f,o),dt=new AN(T,ne,O),ae=new PN(z,V,O,I),fe=new _P(z,gi,V),se=new BP(z,gi,V),V.programs=ve.programs,T.capabilities=O,T.extensions=gi,T.properties=Y,T.renderLists=Ee,T.shadowMap=dt,T.state=I,T.info=V}Xe(),m!==On&&(A=new WP(m,t.width,t.height,a,s,n));const ze=new CN(T,z);this.xr=ze,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){const R=gi.get("WEBGL_lose_context");R&&R.loseContext()},this.forceContextRestore=function(){const R=gi.get("WEBGL_lose_context");R&&R.restoreContext()},this.getPixelRatio=function(){return le},this.setPixelRatio=function(R){R!==void 0&&(le=R,this.setSize(Z,ce,!1))},this.getSize=function(R){return R.set(Z,ce)},this.setSize=function(R,G,q=!0){if(ze.isPresenting){We("WebGLRenderer: Can't change size while VR device is presenting.");return}Z=R,ce=G,t.width=Math.floor(R*le),t.height=Math.floor(G*le),q===!0&&(t.style.width=R+"px",t.style.height=G+"px"),A!==null&&A.setSize(t.width,t.height),this.setViewport(0,0,R,G)},this.getDrawingBufferSize=function(R){return R.set(Z*le,ce*le).floor()},this.setDrawingBufferSize=function(R,G,q){Z=R,ce=G,le=q,t.width=Math.floor(R*q),t.height=Math.floor(G*q),this.setViewport(0,0,R,G)},this.setEffects=function(R){if(m===On){ft("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(R){for(let G=0;G<R.length;G++)if(R[G].isOutputPass===!0){We("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(R||[])},this.getCurrentViewport=function(R){return R.copy(J)},this.getViewport=function(R){return R.copy(je)},this.setViewport=function(R,G,q,K){R.isVector4?je.set(R.x,R.y,R.z,R.w):je.set(R,G,q,K),I.viewport(J.copy(je).multiplyScalar(le).round())},this.getScissor=function(R){return R.copy(Be)},this.setScissor=function(R,G,q,K){R.isVector4?Be.set(R.x,R.y,R.z,R.w):Be.set(R,G,q,K),I.scissor(re.copy(Be).multiplyScalar(le).round())},this.getScissorTest=function(){return Oe},this.setScissorTest=function(R){I.setScissorTest(Oe=R)},this.setOpaqueSort=function(R){$=R},this.setTransparentSort=function(R){Ue=R},this.getClearColor=function(R){return R.copy(Dt.getClearColor())},this.setClearColor=function(){Dt.setClearColor(...arguments)},this.getClearAlpha=function(){return Dt.getClearAlpha()},this.setClearAlpha=function(){Dt.setClearAlpha(...arguments)},this.clear=function(R=!0,G=!0,q=!0){let K=0;if(R){let X=!1;if(H!==null){const Ie=H.texture.format;X=v.has(Ie)}if(X){const Ie=H.texture.type,Pe=g.has(Ie),Te=Dt.getClearColor(),Ge=Dt.getClearAlpha(),Je=Te.r,kt=Te.g,Ft=Te.b;Pe?(b[0]=Je,b[1]=kt,b[2]=Ft,b[3]=Ge,z.clearBufferuiv(z.COLOR,0,b)):(w[0]=Je,w[1]=kt,w[2]=Ft,w[3]=Ge,z.clearBufferiv(z.COLOR,0,w))}else K|=z.COLOR_BUFFER_BIT}G&&(K|=z.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),q&&(K|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),K!==0&&z.clear(K)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(R){R.setRenderer(this),k=R},this.dispose=function(){t.removeEventListener("webglcontextlost",ps,!1),t.removeEventListener("webglcontextrestored",Pi,!1),t.removeEventListener("webglcontextcreationerror",Aa,!1),Dt.dispose(),Ee.dispose(),be.dispose(),Y.dispose(),de.dispose(),ne.dispose(),_e.dispose(),ae.dispose(),ve.dispose(),ze.dispose(),ze.removeEventListener("sessionstart",dM),ze.removeEventListener("sessionend",uM),cc.stop()};function ps(R){R.preventDefault(),X0("WebGLRenderer: Context Lost."),_=!0}function Pi(){X0("WebGLRenderer: Context Restored."),_=!1;const R=V.autoReset,G=dt.enabled,q=dt.autoUpdate,K=dt.needsUpdate,X=dt.type;Xe(),V.autoReset=R,dt.enabled=G,dt.autoUpdate=q,dt.needsUpdate=K,dt.type=X}function Aa(R){ft("WebGLRenderer: A WebGL context could not be created. Reason: ",R.statusMessage)}function Ta(R){const G=R.target;G.removeEventListener("dispose",Ta),DI(G)}function DI(R){kI(R),Y.remove(R)}function kI(R){const G=Y.get(R).programs;G!==void 0&&(G.forEach(function(q){ve.releaseProgram(q)}),R.isShaderMaterial&&ve.releaseShaderCache(R))}this.renderBufferDirect=function(R,G,q,K,X,Ie){G===null&&(G=ts);const Pe=X.isMesh&&X.matrixWorld.determinantAffine()<0,Te=LI(R,G,q,K,X);I.setMaterial(K,Pe);let Ge=q.index,Je=1;if(K.wireframe===!0){if(Ge=te.getWireframeAttribute(q),Ge===void 0)return;Je=2}const kt=q.drawRange,Ft=q.attributes.position;let Qe=kt.start*Je,_i=(kt.start+kt.count)*Je;Ie!==null&&(Qe=Math.max(Qe,Ie.start*Je),_i=Math.min(_i,(Ie.start+Ie.count)*Je)),Ge!==null?(Qe=Math.max(Qe,0),_i=Math.min(_i,Ge.count)):Ft!=null&&(Qe=Math.max(Qe,0),_i=Math.min(_i,Ft.count));const Es=_i-Qe;if(Es<0||Es===1/0)return;_e.setup(X,K,Te,q,Ge);let fs,ki=fe;if(Ge!==null&&(fs=me.get(Ge),ki=se,ki.setIndex(fs)),X.isMesh)K.wireframe===!0?(I.setLineWidth(K.wireframeLinewidth*Cs()),ki.setMode(z.LINES)):ki.setMode(z.TRIANGLES);else if(X.isLine){let wn=K.linewidth;wn===void 0&&(wn=1),I.setLineWidth(wn*Cs()),X.isLineSegments?ki.setMode(z.LINES):X.isLineLoop?ki.setMode(z.LINE_LOOP):ki.setMode(z.LINE_STRIP)}else X.isPoints?ki.setMode(z.POINTS):X.isSprite&&ki.setMode(z.TRIANGLES);if(X.isBatchedMesh)if(gi.get("WEBGL_multi_draw"))ki.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const wn=X._multiDrawStarts,ke=X._multiDrawCounts,Sr=X._multiDrawCount,qt=Ge?me.get(Ge).bytesPerElement:1,Br=Y.get(K).currentProgram.getUniforms();for(let Ia=0;Ia<Sr;Ia++)Br.setValue(z,"_gl_DrawID",Ia),ki.render(wn[Ia]/qt,ke[Ia])}else if(X.isInstancedMesh)ki.renderInstances(Qe,Es,X.count);else if(q.isInstancedBufferGeometry){const wn=q._maxInstanceCount!==void 0?q._maxInstanceCount:1/0,ke=Math.min(q.instanceCount,wn);ki.renderInstances(Qe,Es,ke)}else ki.render(Qe,Es)};function hM(R,G,q){R.transparent===!0&&R.side===$s&&R.forceSinglePass===!1?(R.side=Ji,R.needsUpdate=!0,If(R,G,q),R.side=ho,R.needsUpdate=!0,If(R,G,q),R.side=$s):If(R,G,q)}this.compile=function(R,G,q=null){q===null&&(q=R),x=be.get(q),x.init(G),S.push(x),q.traverseVisible(function(X){X.isLight&&X.layers.test(G.layers)&&(x.pushLight(X),X.castShadow&&x.pushShadow(X))}),R!==q&&R.traverseVisible(function(X){X.isLight&&X.layers.test(G.layers)&&(x.pushLight(X),X.castShadow&&x.pushShadow(X))}),x.setupLights();const K=new Set;return R.traverse(function(X){if(!(X.isMesh||X.isPoints||X.isLine||X.isSprite))return;const Ie=X.material;if(Ie)if(Array.isArray(Ie))for(let Pe=0;Pe<Ie.length;Pe++){const Te=Ie[Pe];hM(Te,q,X),K.add(Te)}else hM(Ie,q,X),K.add(Ie)}),x=S.pop(),K},this.compileAsync=function(R,G,q=null){const K=this.compile(R,G,q);return new Promise(X=>{function Ie(){if(K.forEach(function(Pe){Y.get(Pe).currentProgram.isReady()&&K.delete(Pe)}),K.size===0){X(R);return}setTimeout(Ie,10)}gi.get("KHR_parallel_shader_compile")!==null?Ie():setTimeout(Ie,10)})};let jg=null;function RI(R){jg&&jg(R)}function dM(){cc.stop()}function uM(){cc.start()}const cc=new U3;cc.setAnimationLoop(RI),typeof self<"u"&&cc.setContext(self),this.setAnimationLoop=function(R){jg=R,ze.setAnimationLoop(R),R===null?cc.stop():cc.start()},ze.addEventListener("sessionstart",dM),ze.addEventListener("sessionend",uM),this.render=function(R,G){if(G!==void 0&&G.isCamera!==!0){ft("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(_===!0)return;k!==null&&k.renderStart(R,G);const q=ze.enabled===!0&&ze.isPresenting===!0,K=A!==null&&(H===null||q)&&A.begin(T,H);if(R.matrixWorldAutoUpdate===!0&&R.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),ze.enabled===!0&&ze.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(ze.cameraAutoUpdate===!0&&ze.updateCamera(G),G=ze.getCamera()),R.isScene===!0&&R.onBeforeRender(T,R,G,H),x=be.get(R,S.length),x.init(G),x.state.textureUnits=ee.getTextureUnits(),S.push(x),fi.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),nt.setFromProjectionMatrix(fi,ro,G.reversedDepth),ct=this.localClippingEnabled,lt=it.init(this.clippingPlanes,ct),M=Ee.get(R,E.length),M.init(),E.push(M),ze.enabled===!0&&ze.isPresenting===!0){const Pe=T.xr.getDepthSensingMesh();Pe!==null&&Zg(Pe,G,-1/0,T.sortObjects)}Zg(R,G,0,T.sortObjects),M.finish(),T.sortObjects===!0&&M.sort($,Ue,G.reversedDepth),us=ze.enabled===!1||ze.isPresenting===!1||ze.hasDepthSensing()===!1,us&&Dt.addToRenderList(M,R),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),lt===!0&&it.beginShadows();const X=x.state.shadowsArray;if(dt.render(X,R,G),lt===!0&&it.endShadows(),(K&&A.hasRenderPass())===!1){const Pe=M.opaque,Te=M.transmissive;if(x.setupLights(),G.isArrayCamera){const Ge=G.cameras;if(Te.length>0)for(let Je=0,kt=Ge.length;Je<kt;Je++){const Ft=Ge[Je];fM(Pe,Te,R,Ft)}us&&Dt.render(R);for(let Je=0,kt=Ge.length;Je<kt;Je++){const Ft=Ge[Je];pM(M,R,Ft,Ft.viewport)}}else Te.length>0&&fM(Pe,Te,R,G),us&&Dt.render(R),pM(M,R,G)}H!==null&&F===0&&(ee.updateMultisampleRenderTarget(H),ee.updateRenderTargetMipmap(H)),K&&A.end(T),R.isScene===!0&&R.onAfterRender(T,R,G),_e.resetDefaultState(),j=-1,W=null,S.pop(),S.length>0?(x=S[S.length-1],ee.setTextureUnits(x.state.textureUnits),lt===!0&&it.setGlobalState(T.clippingPlanes,x.state.camera)):x=null,E.pop(),E.length>0?M=E[E.length-1]:M=null,k!==null&&k.renderEnd()};function Zg(R,G,q,K){if(R.visible===!1)return;if(R.layers.test(G.layers)){if(R.isGroup)q=R.renderOrder;else if(R.isLOD)R.autoUpdate===!0&&R.update(G);else if(R.isLightProbeGrid)x.pushLightProbeGrid(R);else if(R.isLight)x.pushLight(R),R.castShadow&&x.pushShadow(R);else if(R.isSprite){if(!R.frustumCulled||nt.intersectsSprite(R)){K&&ds.setFromMatrixPosition(R.matrixWorld).applyMatrix4(fi);const Pe=ne.update(R),Te=R.material;Te.visible&&M.push(R,Pe,Te,q,ds.z,null)}}else if((R.isMesh||R.isLine||R.isPoints)&&(!R.frustumCulled||nt.intersectsObject(R))){const Pe=ne.update(R),Te=R.material;if(K&&(R.boundingSphere!==void 0?(R.boundingSphere===null&&R.computeBoundingSphere(),ds.copy(R.boundingSphere.center)):(Pe.boundingSphere===null&&Pe.computeBoundingSphere(),ds.copy(Pe.boundingSphere.center)),ds.applyMatrix4(R.matrixWorld).applyMatrix4(fi)),Array.isArray(Te)){const Ge=Pe.groups;for(let Je=0,kt=Ge.length;Je<kt;Je++){const Ft=Ge[Je],Qe=Te[Ft.materialIndex];Qe&&Qe.visible&&M.push(R,Pe,Qe,q,ds.z,Ft)}}else Te.visible&&M.push(R,Pe,Te,q,ds.z,null)}}const Ie=R.children;for(let Pe=0,Te=Ie.length;Pe<Te;Pe++)Zg(Ie[Pe],G,q,K)}function pM(R,G,q,K){const{opaque:X,transmissive:Ie,transparent:Pe}=R;x.setupLightsView(q),lt===!0&&it.setGlobalState(T.clippingPlanes,q),K&&I.viewport(J.copy(K)),X.length>0&&Tf(X,G,q),Ie.length>0&&Tf(Ie,G,q),Pe.length>0&&Tf(Pe,G,q),I.buffers.depth.setTest(!0),I.buffers.depth.setMask(!0),I.buffers.color.setMask(!0),I.setPolygonOffset(!1)}function fM(R,G,q,K){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(x.state.transmissionRenderTarget[K.id]===void 0){const Qe=gi.has("EXT_color_buffer_half_float")||gi.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[K.id]=new oi(1,1,{generateMipmaps:!0,type:Qe?ti:On,minFilter:Nr,samples:Math.max(4,O.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Kt.workingColorSpace})}const Ie=x.state.transmissionRenderTarget[K.id],Pe=K.viewport||J;Ie.setSize(Pe.z*T.transmissionResolutionScale,Pe.w*T.transmissionResolutionScale);const Te=T.getRenderTarget(),Ge=T.getActiveCubeFace(),Je=T.getActiveMipmapLevel();T.setRenderTarget(Ie),T.getClearColor(He),De=T.getClearAlpha(),De<1&&T.setClearColor(16777215,.5),T.clear(),us&&Dt.render(q);const kt=T.toneMapping;T.toneMapping=oo;const Ft=K.viewport;if(K.viewport!==void 0&&(K.viewport=void 0),x.setupLightsView(K),lt===!0&&it.setGlobalState(T.clippingPlanes,K),Tf(R,q,K),ee.updateMultisampleRenderTarget(Ie),ee.updateRenderTargetMipmap(Ie),gi.has("WEBGL_multisampled_render_to_texture")===!1){let Qe=!1;for(let _i=0,Es=G.length;_i<Es;_i++){const fs=G[_i],{object:ki,geometry:wn,material:ke,group:Sr}=fs;if(ke.side===$s&&ki.layers.test(K.layers)){const qt=ke.side;ke.side=Ji,ke.needsUpdate=!0,mM(ki,q,K,wn,ke,Sr),ke.side=qt,ke.needsUpdate=!0,Qe=!0}}Qe===!0&&(ee.updateMultisampleRenderTarget(Ie),ee.updateRenderTargetMipmap(Ie))}T.setRenderTarget(Te,Ge,Je),T.setClearColor(He,De),Ft!==void 0&&(K.viewport=Ft),T.toneMapping=kt}function Tf(R,G,q){const K=G.isScene===!0?G.overrideMaterial:null;for(let X=0,Ie=R.length;X<Ie;X++){const Pe=R[X],{object:Te,geometry:Ge,group:Je}=Pe;let kt=Pe.material;kt.allowOverride===!0&&K!==null&&(kt=K),Te.layers.test(q.layers)&&mM(Te,G,q,Ge,kt,Je)}}function mM(R,G,q,K,X,Ie){R.onBeforeRender(T,G,q,K,X,Ie),R.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse,R.matrixWorld),R.normalMatrix.getNormalMatrix(R.modelViewMatrix),X.onBeforeRender(T,G,q,K,R,Ie),X.transparent===!0&&X.side===$s&&X.forceSinglePass===!1?(X.side=Ji,X.needsUpdate=!0,T.renderBufferDirect(q,G,K,X,R,Ie),X.side=ho,X.needsUpdate=!0,T.renderBufferDirect(q,G,K,X,R,Ie),X.side=$s):T.renderBufferDirect(q,G,K,X,R,Ie),R.onAfterRender(T,G,q,K,X,Ie)}function If(R,G,q){G.isScene!==!0&&(G=ts);const K=Y.get(R),X=x.state.lights,Ie=x.state.shadowsArray,Pe=X.state.version,Te=ve.getParameters(R,X.state,Ie,G,q,x.state.lightProbeGridArray),Ge=ve.getProgramCacheKey(Te);let Je=K.programs;K.environment=R.isMeshStandardMaterial||R.isMeshLambertMaterial||R.isMeshPhongMaterial?G.environment:null,K.fog=G.fog;const kt=R.isMeshStandardMaterial||R.isMeshLambertMaterial&&!R.envMap||R.isMeshPhongMaterial&&!R.envMap;K.envMap=de.get(R.envMap||K.environment,kt),K.envMapRotation=K.environment!==null&&R.envMap===null?G.environmentRotation:R.envMapRotation,Je===void 0&&(R.addEventListener("dispose",Ta),Je=new Map,K.programs=Je);let Ft=Je.get(Ge);if(Ft!==void 0){if(K.currentProgram===Ft&&K.lightsStateVersion===Pe)return vM(R,Te),Ft}else Te.uniforms=ve.getUniforms(R),k!==null&&R.isNodeMaterial&&k.build(R,q,Te),R.onBeforeCompile(Te,T),Ft=ve.acquireProgram(Te,Ge),Je.set(Ge,Ft),K.uniforms=Te.uniforms;const Qe=K.uniforms;return(!R.isShaderMaterial&&!R.isRawShaderMaterial||R.clipping===!0)&&(Qe.clippingPlanes=it.uniform),vM(R,Te),K.needsLights=PI(R),K.lightsStateVersion=Pe,K.needsLights&&(Qe.ambientLightColor.value=X.state.ambient,Qe.lightProbe.value=X.state.probe,Qe.directionalLights.value=X.state.directional,Qe.directionalLightShadows.value=X.state.directionalShadow,Qe.spotLights.value=X.state.spot,Qe.spotLightShadows.value=X.state.spotShadow,Qe.rectAreaLights.value=X.state.rectArea,Qe.ltc_1.value=X.state.rectAreaLTC1,Qe.ltc_2.value=X.state.rectAreaLTC2,Qe.pointLights.value=X.state.point,Qe.pointLightShadows.value=X.state.pointShadow,Qe.hemisphereLights.value=X.state.hemi,Qe.directionalShadowMatrix.value=X.state.directionalShadowMatrix,Qe.spotLightMatrix.value=X.state.spotLightMatrix,Qe.spotLightMap.value=X.state.spotLightMap,Qe.pointShadowMatrix.value=X.state.pointShadowMatrix),K.lightProbeGrid=x.state.lightProbeGridArray.length>0,K.currentProgram=Ft,K.uniformsList=null,Ft}function gM(R){if(R.uniformsList===null){const G=R.currentProgram.getUniforms();R.uniformsList=u0.seqWithValue(G.seq,R.uniforms)}return R.uniformsList}function vM(R,G){const q=Y.get(R);q.outputColorSpace=G.outputColorSpace,q.batching=G.batching,q.batchingColor=G.batchingColor,q.instancing=G.instancing,q.instancingColor=G.instancingColor,q.instancingMorph=G.instancingMorph,q.skinning=G.skinning,q.morphTargets=G.morphTargets,q.morphNormals=G.morphNormals,q.morphColors=G.morphColors,q.morphTargetsCount=G.morphTargetsCount,q.numClippingPlanes=G.numClippingPlanes,q.numIntersection=G.numClipIntersection,q.vertexAlphas=G.vertexAlphas,q.vertexTangents=G.vertexTangents,q.toneMapping=G.toneMapping}function CI(R,G){if(R.length===0)return null;if(R.length===1)return R[0].texture!==null?R[0]:null;y.setFromMatrixPosition(G.matrixWorld);for(let q=0,K=R.length;q<K;q++){const X=R[q];if(X.texture!==null&&X.boundingBox.containsPoint(y))return X}return null}function LI(R,G,q,K,X){G.isScene!==!0&&(G=ts),ee.resetTextureUnits();const Ie=G.fog,Pe=K.isMeshStandardMaterial||K.isMeshLambertMaterial||K.isMeshPhongMaterial?G.environment:null,Te=H===null?T.outputColorSpace:H.isXRRenderTarget===!0?H.texture.colorSpace:Kt.workingColorSpace,Ge=K.isMeshStandardMaterial||K.isMeshLambertMaterial&&!K.envMap||K.isMeshPhongMaterial&&!K.envMap,Je=de.get(K.envMap||Pe,Ge),kt=K.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,Ft=!!q.attributes.tangent&&(!!K.normalMap||K.anisotropy>0),Qe=!!q.morphAttributes.position,_i=!!q.morphAttributes.normal,Es=!!q.morphAttributes.color;let fs=oo;K.toneMapped&&(H===null||H.isXRRenderTarget===!0)&&(fs=T.toneMapping);const ki=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,wn=ki!==void 0?ki.length:0,ke=Y.get(K),Sr=x.state.lights;if(lt===!0&&(ct===!0||R!==W)){const Ni=R===W&&K.id===j;it.setState(K,R,Ni)}let qt=!1;K.version===ke.__version?(ke.needsLights&&ke.lightsStateVersion!==Sr.state.version||ke.outputColorSpace!==Te||X.isBatchedMesh&&ke.batching===!1||!X.isBatchedMesh&&ke.batching===!0||X.isBatchedMesh&&ke.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&ke.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&ke.instancing===!1||!X.isInstancedMesh&&ke.instancing===!0||X.isSkinnedMesh&&ke.skinning===!1||!X.isSkinnedMesh&&ke.skinning===!0||X.isInstancedMesh&&ke.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&ke.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&ke.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&ke.instancingMorph===!1&&X.morphTexture!==null||ke.envMap!==Je||K.fog===!0&&ke.fog!==Ie||ke.numClippingPlanes!==void 0&&(ke.numClippingPlanes!==it.numPlanes||ke.numIntersection!==it.numIntersection)||ke.vertexAlphas!==kt||ke.vertexTangents!==Ft||ke.morphTargets!==Qe||ke.morphNormals!==_i||ke.morphColors!==Es||ke.toneMapping!==fs||ke.morphTargetsCount!==wn||!!ke.lightProbeGrid!=x.state.lightProbeGridArray.length>0)&&(qt=!0):(qt=!0,ke.__version=K.version);let Br=ke.currentProgram;qt===!0&&(Br=If(K,G,X),k&&K.isNodeMaterial&&k.onUpdateProgram(K,Br,ke));let Ia=!1,sl=!1,lh=!1;const Ri=Br.getUniforms(),As=ke.uniforms;if(I.useProgram(Br.program)&&(Ia=!0,sl=!0,lh=!0),K.id!==j&&(j=K.id,sl=!0),ke.needsLights){const Ni=CI(x.state.lightProbeGridArray,X);ke.lightProbeGrid!==Ni&&(ke.lightProbeGrid=Ni,sl=!0)}if(Ia||W!==R){I.buffers.depth.getReversed()&&R.reversedDepth!==!0&&(R._reversedDepth=!0,R.updateProjectionMatrix()),Ri.setValue(z,"projectionMatrix",R.projectionMatrix),Ri.setValue(z,"viewMatrix",R.matrixWorldInverse);const rl=Ri.map.cameraPosition;rl!==void 0&&rl.setValue(z,mi.setFromMatrixPosition(R.matrixWorld)),O.logarithmicDepthBuffer&&Ri.setValue(z,"logDepthBufFC",2/(Math.log(R.far+1)/Math.LN2)),(K.isMeshPhongMaterial||K.isMeshToonMaterial||K.isMeshLambertMaterial||K.isMeshBasicMaterial||K.isMeshStandardMaterial||K.isShaderMaterial)&&Ri.setValue(z,"isOrthographic",R.isOrthographicCamera===!0),W!==R&&(W=R,sl=!0,lh=!0)}if(ke.needsLights&&(Sr.state.directionalShadowMap.length>0&&Ri.setValue(z,"directionalShadowMap",Sr.state.directionalShadowMap,ee),Sr.state.spotShadowMap.length>0&&Ri.setValue(z,"spotShadowMap",Sr.state.spotShadowMap,ee),Sr.state.pointShadowMap.length>0&&Ri.setValue(z,"pointShadowMap",Sr.state.pointShadowMap,ee)),X.isSkinnedMesh){Ri.setOptional(z,X,"bindMatrix"),Ri.setOptional(z,X,"bindMatrixInverse");const Ni=X.skeleton;Ni&&(Ni.boneTexture===null&&Ni.computeBoneTexture(),Ri.setValue(z,"boneTexture",Ni.boneTexture,ee))}X.isBatchedMesh&&(Ri.setOptional(z,X,"batchingTexture"),Ri.setValue(z,"batchingTexture",X._matricesTexture,ee),Ri.setOptional(z,X,"batchingIdTexture"),Ri.setValue(z,"batchingIdTexture",X._indirectTexture,ee),Ri.setOptional(z,X,"batchingColorTexture"),X._colorsTexture!==null&&Ri.setValue(z,"batchingColorTexture",X._colorsTexture,ee));const nl=q.morphAttributes;if((nl.position!==void 0||nl.normal!==void 0||nl.color!==void 0)&&B.update(X,q,Br),(sl||ke.receiveShadow!==X.receiveShadow)&&(ke.receiveShadow=X.receiveShadow,Ri.setValue(z,"receiveShadow",X.receiveShadow)),(K.isMeshStandardMaterial||K.isMeshLambertMaterial||K.isMeshPhongMaterial)&&K.envMap===null&&G.environment!==null&&(As.envMapIntensity.value=G.environmentIntensity),As.dfgLUT!==void 0&&(As.dfgLUT.value=FN()),sl){if(Ri.setValue(z,"toneMappingExposure",T.toneMappingExposure),ke.needsLights&&OI(As,lh),Ie&&K.fog===!0&&Ze.refreshFogUniforms(As,Ie),Ze.refreshMaterialUniforms(As,K,le,ce,x.state.transmissionRenderTarget[R.id]),ke.needsLights&&ke.lightProbeGrid){const Ni=ke.lightProbeGrid;As.probesSH.value=Ni.texture,As.probesMin.value.copy(Ni.boundingBox.min),As.probesMax.value.copy(Ni.boundingBox.max),As.probesResolution.value.copy(Ni.resolution)}u0.upload(z,gM(ke),As,ee)}if(K.isShaderMaterial&&K.uniformsNeedUpdate===!0&&(u0.upload(z,gM(ke),As,ee),K.uniformsNeedUpdate=!1),K.isSpriteMaterial&&Ri.setValue(z,"center",X.center),Ri.setValue(z,"modelViewMatrix",X.modelViewMatrix),Ri.setValue(z,"normalMatrix",X.normalMatrix),Ri.setValue(z,"modelMatrix",X.matrixWorld),K.uniformsGroups!==void 0){const Ni=K.uniformsGroups;for(let rl=0,ch=Ni.length;rl<ch;rl++){const bM=Ni[rl];ae.update(bM,Br),ae.bind(bM,Br)}}return Br}function OI(R,G){R.ambientLightColor.needsUpdate=G,R.lightProbe.needsUpdate=G,R.directionalLights.needsUpdate=G,R.directionalLightShadows.needsUpdate=G,R.pointLights.needsUpdate=G,R.pointLightShadows.needsUpdate=G,R.spotLights.needsUpdate=G,R.spotLightShadows.needsUpdate=G,R.rectAreaLights.needsUpdate=G,R.hemisphereLights.needsUpdate=G}function PI(R){return R.isMeshLambertMaterial||R.isMeshToonMaterial||R.isMeshPhongMaterial||R.isMeshStandardMaterial||R.isShadowMaterial||R.isShaderMaterial&&R.lights===!0}this.getActiveCubeFace=function(){return N},this.getActiveMipmapLevel=function(){return F},this.getRenderTarget=function(){return H},this.setRenderTargetTextures=function(R,G,q){const K=Y.get(R);K.__autoAllocateDepthBuffer=R.resolveDepthBuffer===!1,K.__autoAllocateDepthBuffer===!1&&(K.__useRenderToTexture=!1),Y.get(R.texture).__webglTexture=G,Y.get(R.depthTexture).__webglTexture=K.__autoAllocateDepthBuffer?void 0:q,K.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(R,G){const q=Y.get(R);q.__webglFramebuffer=G,q.__useDefaultFramebuffer=G===void 0},this.setRenderTarget=function(R,G=0,q=0){H=R,N=G,F=q;let K=null,X=!1,Ie=!1;if(R){const Te=Y.get(R);if(Te.__useDefaultFramebuffer!==void 0){I.bindFramebuffer(z.FRAMEBUFFER,Te.__webglFramebuffer),J.copy(R.viewport),re.copy(R.scissor),Le=R.scissorTest,I.viewport(J),I.scissor(re),I.setScissorTest(Le),j=-1;return}else if(Te.__webglFramebuffer===void 0)ee.setupRenderTarget(R);else if(Te.__hasExternalTextures)ee.rebindTextures(R,Y.get(R.texture).__webglTexture,Y.get(R.depthTexture).__webglTexture);else if(R.depthBuffer){const kt=R.depthTexture;if(Te.__boundDepthTexture!==kt){if(kt!==null&&Y.has(kt)&&(R.width!==kt.image.width||R.height!==kt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");ee.setupDepthRenderbuffer(R)}}const Ge=R.texture;(Ge.isData3DTexture||Ge.isDataArrayTexture||Ge.isCompressedArrayTexture)&&(Ie=!0);const Je=Y.get(R).__webglFramebuffer;R.isWebGLCubeRenderTarget?(Array.isArray(Je[G])?K=Je[G][q]:K=Je[G],X=!0):R.samples>0&&ee.useMultisampledRTT(R)===!1?K=Y.get(R).__webglMultisampledFramebuffer:Array.isArray(Je)?K=Je[q]:K=Je,J.copy(R.viewport),re.copy(R.scissor),Le=R.scissorTest}else J.copy(je).multiplyScalar(le).floor(),re.copy(Be).multiplyScalar(le).floor(),Le=Oe;if(q!==0&&(K=L),I.bindFramebuffer(z.FRAMEBUFFER,K)&&I.drawBuffers(R,K),I.viewport(J),I.scissor(re),I.setScissorTest(Le),X){const Te=Y.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+G,Te.__webglTexture,q)}else if(Ie){const Te=G;for(let Ge=0;Ge<R.textures.length;Ge++){const Je=Y.get(R.textures[Ge]);z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0+Ge,Je.__webglTexture,q,Te)}}else if(R!==null&&q!==0){const Te=Y.get(R.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,Te.__webglTexture,q)}j=-1},this.readRenderTargetPixels=function(R,G,q,K,X,Ie,Pe,Te=0){if(!(R&&R.isWebGLRenderTarget)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ge=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0&&(Ge=Ge[Pe]),Ge){I.bindFramebuffer(z.FRAMEBUFFER,Ge);try{const Je=R.textures[Te],kt=Je.format,Ft=Je.type;if(R.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+Te),!O.textureFormatReadable(kt)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!O.textureTypeReadable(Ft)){ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}G>=0&&G<=R.width-K&&q>=0&&q<=R.height-X&&z.readPixels(G,q,K,X,ye.convert(kt),ye.convert(Ft),Ie)}finally{const Je=H!==null?Y.get(H).__webglFramebuffer:null;I.bindFramebuffer(z.FRAMEBUFFER,Je)}}},this.readRenderTargetPixelsAsync=async function(R,G,q,K,X,Ie,Pe,Te=0){if(!(R&&R.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ge=Y.get(R).__webglFramebuffer;if(R.isWebGLCubeRenderTarget&&Pe!==void 0&&(Ge=Ge[Pe]),Ge)if(G>=0&&G<=R.width-K&&q>=0&&q<=R.height-X){I.bindFramebuffer(z.FRAMEBUFFER,Ge);const Je=R.textures[Te],kt=Je.format,Ft=Je.type;if(R.textures.length>1&&z.readBuffer(z.COLOR_ATTACHMENT0+Te),!O.textureFormatReadable(kt))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!O.textureTypeReadable(Ft))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Qe=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Qe),z.bufferData(z.PIXEL_PACK_BUFFER,Ie.byteLength,z.STREAM_READ),z.readPixels(G,q,K,X,ye.convert(kt),ye.convert(Ft),0);const _i=H!==null?Y.get(H).__webglFramebuffer:null;I.bindFramebuffer(z.FRAMEBUFFER,_i);const Es=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await LR(z,Es,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Qe),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,Ie),z.deleteBuffer(Qe),z.deleteSync(Es),Ie}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(R,G=null,q=0){const K=Math.pow(2,-q),X=Math.floor(R.image.width*K),Ie=Math.floor(R.image.height*K),Pe=G!==null?G.x:0,Te=G!==null?G.y:0;ee.setTexture2D(R,0),z.copyTexSubImage2D(z.TEXTURE_2D,q,0,0,Pe,Te,X,Ie),I.unbindTexture()},this.copyTextureToTexture=function(R,G,q=null,K=null,X=0,Ie=0){let Pe,Te,Ge,Je,kt,Ft,Qe,_i,Es;const fs=R.isCompressedTexture?R.mipmaps[Ie]:R.image;if(q!==null)Pe=q.max.x-q.min.x,Te=q.max.y-q.min.y,Ge=q.isBox3?q.max.z-q.min.z:1,Je=q.min.x,kt=q.min.y,Ft=q.isBox3?q.min.z:0;else{const As=Math.pow(2,-X);Pe=Math.floor(fs.width*As),Te=Math.floor(fs.height*As),R.isDataArrayTexture?Ge=fs.depth:R.isData3DTexture?Ge=Math.floor(fs.depth*As):Ge=1,Je=0,kt=0,Ft=0}K!==null?(Qe=K.x,_i=K.y,Es=K.z):(Qe=0,_i=0,Es=0);const ki=ye.convert(G.format),wn=ye.convert(G.type);let ke;G.isData3DTexture?(ee.setTexture3D(G,0),ke=z.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(ee.setTexture2DArray(G,0),ke=z.TEXTURE_2D_ARRAY):(ee.setTexture2D(G,0),ke=z.TEXTURE_2D),I.activeTexture(z.TEXTURE0),I.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,G.flipY),I.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),I.pixelStorei(z.UNPACK_ALIGNMENT,G.unpackAlignment);const Sr=I.getParameter(z.UNPACK_ROW_LENGTH),qt=I.getParameter(z.UNPACK_IMAGE_HEIGHT),Br=I.getParameter(z.UNPACK_SKIP_PIXELS),Ia=I.getParameter(z.UNPACK_SKIP_ROWS),sl=I.getParameter(z.UNPACK_SKIP_IMAGES);I.pixelStorei(z.UNPACK_ROW_LENGTH,fs.width),I.pixelStorei(z.UNPACK_IMAGE_HEIGHT,fs.height),I.pixelStorei(z.UNPACK_SKIP_PIXELS,Je),I.pixelStorei(z.UNPACK_SKIP_ROWS,kt),I.pixelStorei(z.UNPACK_SKIP_IMAGES,Ft);const lh=R.isDataArrayTexture||R.isData3DTexture,Ri=G.isDataArrayTexture||G.isData3DTexture;if(R.isDepthTexture){const As=Y.get(R),nl=Y.get(G),Ni=Y.get(As.__renderTarget),rl=Y.get(nl.__renderTarget);I.bindFramebuffer(z.READ_FRAMEBUFFER,Ni.__webglFramebuffer),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,rl.__webglFramebuffer);for(let ch=0;ch<Ge;ch++)lh&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(R).__webglTexture,X,Ft+ch),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,Y.get(G).__webglTexture,Ie,Es+ch)),z.blitFramebuffer(Je,kt,Pe,Te,Qe,_i,Pe,Te,z.DEPTH_BUFFER_BIT,z.NEAREST);I.bindFramebuffer(z.READ_FRAMEBUFFER,null),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(X!==0||R.isRenderTargetTexture||Y.has(R)){const As=Y.get(R),nl=Y.get(G);I.bindFramebuffer(z.READ_FRAMEBUFFER,P),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,C);for(let Ni=0;Ni<Ge;Ni++)lh?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,As.__webglTexture,X,Ft+Ni):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,As.__webglTexture,X),Ri?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,nl.__webglTexture,Ie,Es+Ni):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,nl.__webglTexture,Ie),X!==0?z.blitFramebuffer(Je,kt,Pe,Te,Qe,_i,Pe,Te,z.COLOR_BUFFER_BIT,z.NEAREST):Ri?z.copyTexSubImage3D(ke,Ie,Qe,_i,Es+Ni,Je,kt,Pe,Te):z.copyTexSubImage2D(ke,Ie,Qe,_i,Je,kt,Pe,Te);I.bindFramebuffer(z.READ_FRAMEBUFFER,null),I.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else Ri?R.isDataTexture||R.isData3DTexture?z.texSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,wn,fs.data):G.isCompressedArrayTexture?z.compressedTexSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,fs.data):z.texSubImage3D(ke,Ie,Qe,_i,Es,Pe,Te,Ge,ki,wn,fs):R.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,Pe,Te,ki,wn,fs.data):R.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,fs.width,fs.height,ki,fs.data):z.texSubImage2D(z.TEXTURE_2D,Ie,Qe,_i,Pe,Te,ki,wn,fs);I.pixelStorei(z.UNPACK_ROW_LENGTH,Sr),I.pixelStorei(z.UNPACK_IMAGE_HEIGHT,qt),I.pixelStorei(z.UNPACK_SKIP_PIXELS,Br),I.pixelStorei(z.UNPACK_SKIP_ROWS,Ia),I.pixelStorei(z.UNPACK_SKIP_IMAGES,sl),Ie===0&&G.generateMipmaps&&z.generateMipmap(ke),I.unbindTexture()},this.initRenderTarget=function(R){Y.get(R).__webglFramebuffer===void 0&&ee.setupRenderTarget(R)},this.initTexture=function(R){R.isCubeTexture?ee.setTextureCube(R,0):R.isData3DTexture?ee.setTexture3D(R,0):R.isDataArrayTexture||R.isCompressedArrayTexture?ee.setTexture2DArray(R,0):ee.setTexture2D(R,0),I.unbindTexture()},this.resetState=function(){N=0,F=0,H=null,I.reset(),_e.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ro}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Kt._getDrawingBufferColorSpace(e),t.unpackColorSpace=Kt._getUnpackColorSpace()}}const BN=`
|
|
8931
8931
|
varying vec3 vDir;
|
|
8932
8932
|
varying vec3 vWorldDir;
|
|
8933
8933
|
|
|
@@ -9939,7 +9939,7 @@ float grassNoise(vec2 p) {
|
|
|
9939
9939
|
+ (grassNoise(vGrassPatchXZ * 21.0) - 0.5) * 0.6 * (1.0 - smoothstep(2.5, 12.0, eye));
|
|
9940
9940
|
float d = grain * uGrassContrast * grass;
|
|
9941
9941
|
diffuseColor.rgb *= vec3(1.0 + d * 1.1, 1.0 + d, 1.0 + d * 1.25);
|
|
9942
|
-
}`)},e.customProgramCacheKey=()=>t?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Oa{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(e,t,i){const s=i&&i.length>=2?Oa.alongRoute(e,i):void 0;let n=0;for(const r of t){const a=Oa.fill(e,r).filter(h=>!s?.[h]);if(a.length===0)continue;const o=a.map(h=>e.heights[h]).filter(Number.isFinite).sort((h,d)=>h-d);if(o.length===0)continue;const c=o[Math.floor((o.length-1)*Oa.LEVEL_QUANTILE)];for(const h of a)e.heights[h]>c&&(e.heights[h]=c,n++)}return n}static fill(e,t){const{width:i,height:s,bounds:n}=e,r=u=>(u-n.west)/(n.east-n.west)*(i-1),a=u=>(n.north-u)/(n.north-n.south)*(s-1),o=[];for(const u of t.rings)for(let p=0;p<u.length;p++){const f=u[p],m=u[(p+1)%u.length],v={r0:a(f.lat),c0:r(f.lng),r1:a(m.lat),c1:r(m.lng)};v.r0!==v.r1&&o.push(v)}const c=[];if(o.length===0)return c;const h=Math.max(0,Math.ceil(Math.min(...o.map(u=>Math.min(u.r0,u.r1))))),d=Math.min(s-1,Math.floor(Math.max(...o.map(u=>Math.max(u.r0,u.r1)))));for(let u=h;u<=d;u++){const p=[];for(const{r0:f,c0:m,r1:v,c1:g}of o)f<=u!=v<=u&&p.push(m+(g-m)*(u-f)/(v-f));p.sort((f,m)=>f-m);for(let f=0;f+1<p.length;f+=2){const m=Math.max(0,Math.ceil(p[f])),v=Math.min(i-1,Math.floor(p[f+1]));for(let g=m;g<=v;g++)c.push(u*i+g)}}return c}static alongRoute(e,t){const{width:i,height:s,bounds:n}=e,r=(n.east-n.west)*Oa.METRES_PER_DEGREE*Math.cos((n.north+n.south)/2*Math.PI/180)/(i-1),a=(n.north-n.south)*Oa.METRES_PER_DEGREE/(s-1),o=Math.ceil(Oa.ROUTE_CLEARANCE_M/r),c=Math.ceil(Oa.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*s),d=p=>(p-n.west)/(n.east-n.west)*(i-1),u=p=>(n.north-p)/(n.north-n.south)*(s-1);for(let p=0;p+1<t.length;p++){const[f,m,v,g]=[d(t[p].lng),u(t[p].lat),d(t[p+1].lng),u(t[p+1].lat)];if(Math.max(f,v)<-o||Math.min(f,v)>i-1+o||Math.max(m,g)<-c||Math.min(m,g)>s-1+c)continue;const b=Math.max(1,Math.ceil(Math.hypot(v-f,g-m)*2));for(let w=0;w<=b;w++){const y=Math.round(f+(v-f)*w/b),M=Math.round(m+(g-m)*w/b);for(let x=-c;x<=c;x++)for(let E=-o;E<=o;E++){const S=M+x,A=y+E;S<0||A<0||S>=s||A>=i||Math.hypot(E*r,x*a)<=Oa.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const l8=64,sg=l8+1,ng=2048,c8=900,h8=700/900,d8=0,u8=.01,p8=1500;function hp(l,e,t){return{north:tr(0,-t,l,e).lat,south:tr(0,t,l,e).lat,east:tr(t,0,l,e).lng,west:tr(-t,0,l,e).lng}}async function c1(l,e,t,i=c8,s,n){const r=i,a=i*h8,o=hp(l,e,r),c={width:sg,height:sg},h=n?void 0:t.water?.getWater(o).catch(L=>(console.warn("Water unavailable, drawing none:",L),[])),[d,u]=await Promise.all([t.elevation.getElevationGrid(o,c,s),t.imagery.getImageryTexture(o,{width:ng,height:ng})]);let p;const f=h?await Promise.race([h,new Promise(L=>{p=setTimeout(()=>L(void 0),p8)})]):void 0;if(clearTimeout(p),d.width!==d.height||d.width<3||d.heights.length!==d.width*d.height)throw new Error("The ground came as a grid that is not square");rg.fill(d.heights,d.width),f&&f.length>0&&Oa.flatten(d,f,s?.route);const m=d.width,v=m-1,g=Math.floor(m/2),b=d.heights[g*m+g],w=n?.referenceElevationM??b,y=new Float32Array(m*m*3),M=new Float32Array(m*m*2),x=new Float32Array(m*m*4);for(let L=0;L<m;L++){const P=L/(m-1),C=o.north+(o.south-o.north)*P;for(let N=0;N<m;N++){const F=N/(m-1),H=o.west+(o.east-o.west)*F,{x:j,z:W}=ot(C,H,l,e),J=d.heights[L*m+N],re=Math.max(Math.abs(j),Math.abs(W)),Le=n&&re<n.innerM?0:1-f8((re-a)/(r-a),0,1),He=d8+u8+(J-w),De=L*m+N;y[De*3]=j,y[De*3+1]=He,y[De*3+2]=W;const Z=UT(u.bounds,H,C);M[De*2]=Z.x,M[De*2+1]=Z.y,x[De*4]=1,x[De*4+1]=1,x[De*4+2]=1,x[De*4+3]=Le}}const E=m*m>65535?new Uint32Array(v*v*6):new Uint16Array(v*v*6);let S=0;for(let L=0;L<v;L++)for(let P=0;P<v;P++){const C=L*m+P,N=C+1,F=C+m,H=F+1;E[S++]=C,E[S++]=F,E[S++]=N,E[S++]=N,E[S++]=F,E[S++]=H}const A=new Tt;A.setAttribute("position",new Et(y,3)),A.setAttribute("uv",new Et(M,2)),A.setAttribute("color",new Et(x,4)),A.setIndex(new Et(E,1)),A.computeVertexNormals();const T=new lc(u.source);T.flipY=!1,T.colorSpace=an,T.anisotropy=8;const _=new ta({map:T,color:new oe(1,1,1),vertexColors:!0,transparent:!0,fog:!0});n||Ud.install(_);const k=new Me(A,_);return k.receiveShadow=!n,k.castShadow=!n,{mesh:k,attribution:t.imagery.attribution,originElevationM:Number.isFinite(b)?b:void 0,...f?{water:f}:h?{waterLater:h}:{}}}class rg{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(e,t){const i=n=>!Number.isFinite(n)||n<rg.LOWEST_GROUND_M;let s=0;for(let n=0;n<e.length;n++)i(e[n])&&s++;for(let n=0;s>0&&n<rg.MAX_PASSES;n++){const r=[];for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=a*t+o;if(!i(e[c]))continue;let h=0,d=0;for(const[u,p]of[[-1,0],[1,0],[0,-1],[0,1]]){const f=a+u,m=o+p;if(f<0||m<0||f>=t||m>=t)continue;const v=e[f*t+m];i(v)||(h+=v,d++)}d>0&&r.push([c,h/d])}for(const[a,o]of r)e[a]=o;if(s-=r.length,r.length===0)break}if(s>0)for(let n=0;n<e.length;n++)i(e[n])&&(e[n]=0)}}function f8(l,e,t){return Math.max(e,Math.min(t,l))}class At{static STEP_M=8;stepM=At.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new ie;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new ii;surveyed=new ii;stated=new ii;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(e){this.stepM=Number.isFinite(e)&&e>0?Math.min(At.STEP_M,Math.max(1.5,e/2)):At.STEP_M}set(e,t,i,s,n,r=1/0,a){const o=At.within(e,t,i,r);At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(t,i);const c=new Map,h=o.map(p=>p.points.map(f=>ot(f.lat,f.lng,t,i))),d=o.map((p,f)=>this.streetOf(p,h[f],a));for(const[p,f]of o.entries()){const m=c.get(f.surface)??At.batchFor(f.surface);c.set(f.surface,m);const v=d[p];this.appendPath(h[p],f.widthM,s,m,v?{lateralAt:(g,b,w,y)=>v(g,b,w,y).carriageway}:{})}for(const[p,f]of c){const m=this.meshOf(p,f,n);m&&this.surveyed.add(m)}const u=this.sidewalks(o,h,d,s);if(u.indices.length>0){const p=this.meshOf("paved",u,!1,At.SIDEWALK_ALBEDO,!1);p&&(p.name="roads sidewalks",this.surveyed.add(p))}this.paint(o,t,i,s,n)}paint(e,t,i,s,n){if(!e.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(At.markingsModule??=Q(()=>import("./RoadMarkings-GIdi730L.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const o={positions:[],indices:[]};if(a.lay(e,t,i,(d,u,p)=>this.appendPath(d,u,s,o,{offsetM:p.offsetM,liftM:At.LIFT_M+p.liftM,minHalfM:p.minHalfM}))>0&&o.indices.length>0){const d=this.meshOf("paved",o,n,At.MARKINGS_ALBEDO,!1);d&&(d.name="roads markings",d.renderOrder=At.MARKINGS_RENDER_ORDER,d.material.polygonOffsetFactor=-4,d.material.polygonOffsetUnits=-4,this.surveyed.add(d))}const h=a.barrierGeometry(a.barriers(e,t,i),s);if(h.indices.length>0){const d=this.meshOf("paved",h,n,At.BARRIER_ALBEDO,!1);d&&(d.name="roads barriers",d.material.polygonOffset=!1,d.castShadow=!0,this.surveyed.add(d))}this.onMarkings?.()})}onMarkings;anchorGrain(e,t){if(this.grainReference){const s=ot(this.grainReference.lat,this.grainReference.lng,e,t);Math.hypot(s.x,s.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:e,lng:t};const i=ot(this.grainReference.lat,this.grainReference.lng,e,t);this.grainOrigin.set(-i.x,-i.z)}static within(e,t,i,s){if(!Number.isFinite(s))return e;const n=s*1.1+100;return e.filter(r=>{let a;for(const o of r.points){const c=ot(o.lat,o.lng,t,i);if(Math.hypot(c.x,c.z)<=n||a&&Math.hypot((c.x+a.x)/2,(c.z+a.z)/2)<=n)return!0;a=c}return!1})}streetOf(e,t,i){if(!e.urban||e.surface!=="paved")return;const s=At.surveyedAcross(e);if(!i||!i.near(t))return()=>s;const n=new Map,r=(p,f,m,v)=>{const g=`${p.toFixed(2)}:${f.toFixed(2)}`;let b=n.get(g);return b||(b=i.across(p,f,m,v),n.set(g,b)),b},a=this.rungsOf(t),o=a.flatMap(p=>{const f=r(p.x,p.z,p.dirX,p.dirZ);return f.leftM!==void 0&&f.rightM!==void 0?[(f.leftM-f.rightM)/2]:[]}).sort((p,f)=>p-f),c=i.lampsAlong(t);if(o.length===0&&c.length===0)return()=>s;const h=o.length>0?o[Math.floor((o.length-1)/2)]:0,d=At.clearOf(c,e.widthM/2,Math.max(-2.5,Math.min(At.STREET_MIDDLE_MOST_M,h))),u={rungs:a,across:(p,f,m,v)=>At.betweenWalls(e,d,r(p,f,m,v).leftM,r(p,f,m,v).rightM)};return this.laidStreets.push(u),(p,f,m,v)=>{const g=r(p,f,m,v);return At.betweenWalls(e,d,g.leftM,g.rightM)}}static clearOf(e,t,i){const s=r=>e.every(a=>Math.abs(a-r)>=t+At.LAMP_CLEARANCE_M);if(s(i))return i;const n=At.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*n;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=n&&s(a))return a;return i}atKerb(e,t){let i;for(const u of this.laidStreets)for(const p of u.rungs){const f=Math.hypot(e-p.x,t-p.z);f<=At.KERB_REACH_M&&(!i||f<i.distance)&&(i={rung:p,across:u.across(p.x,p.z,p.dirX,p.dirZ),distance:f})}if(!i)return{x:e,z:t};const{rung:s,across:n}=i,r=(e-s.x)*-s.dirZ+(t-s.z)*s.dirX,a=(e-s.x)*s.dirX+(t-s.z)*s.dirZ,c=(r>=n.carriageway.offsetM?n.left:n.right)??n.left??n.right;if(!c)return{x:e,z:t};const h=Math.sign(c.outerM-c.kerbM),d=c.kerbM+h*Math.min(At.LAMP_FROM_KERB_M,Math.abs(c.outerM-c.kerbM)/2);return{x:s.x+s.dirX*a-s.dirZ*d,z:s.z+s.dirZ*a+s.dirX*d}}rungsOf(e){const t=this.resample(e);return t.map((i,s)=>{const n=t[Math.max(0,s-1)],r=t[Math.min(t.length-1,s+1)],a=r.x-n.x,o=r.z-n.z,c=Math.hypot(a,o);return c<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/c,dirZ:o/c}})}static surveyedAcross(e){const t=e.widthM/2,i={offsetM:0,halfM:t};return e.widthM<At.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:t,outerM:t+At.SIDEWALK_WIDTH_M},right:{kerbM:-t,outerM:-t-At.SIDEWALK_WIDTH_M}}}static betweenWalls(e,t,i,s){const n=e.widthM/2,r={offsetM:t,halfM:n},a=t+n,o=t-n,c=i??a+At.SIDEWALK_WIDTH_M,h=-(s??-o+At.SIDEWALK_WIDTH_M);return{carriageway:r,...c-a>=At.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:c}}:{},...o-h>=At.SIDEWALK_NONE_M?{right:{kerbM:o,outerM:h}}:{}}}sidewalks(e,t,i,s){const n={positions:[],indices:[]},r=new Pa(e,t);return e.forEach((a,o)=>{const c=i[o];if(!c)return;const h=(d,u)=>r.onAnotherCarriageway(d,u,o);for(const d of["left","right"]){const u=(p,f,m,v)=>{const g=c(p,f,m,v)[d];return g&&{offsetM:(g.kerbM+g.outerM)/2,halfM:Math.abs(g.outerM-g.kerbM)/2}};this.appendPath(t[o],0,s,n,{lateralAt:u,liftM:At.LIFT_M+At.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(t[o],s,n,(p,f,m,v)=>c(p,f,m,v)[d]?.kerbM,d==="left",h)}}),n}setStated(e,t){At.empty(this.stated);const i=new Map;for(const s of e){const n=i.get(s.surface)??At.batchFor(s.surface);i.set(s.surface,n),this.appendPath(s.path.map(r=>({x:r.eastM,z:-r.northM})),s.widthM,t,n)}for(const[s,n]of i){const r=this.meshOf(s,n,!1);r&&this.stated.add(r)}}clear(){At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(e){for(const t of[...e.children]){e.remove(t);const i=t;i.geometry?.dispose(),i.material?.dispose()}}dispose(){At.empty(this.surveyed),At.empty(this.stated)}appendPath(e,t,i,s,n={}){const r=this.resample(e);if(r.length<2)return;const a=Math.max(n.minHalfM??.5,t/2),o=n.liftM??At.LIFT_M,c=n.offsetM??0,h=s.positions.length/3,d=[],u=[],p=[];for(let m=0;m<r.length;m++){const v=r[Math.max(0,m-1)],g=r[Math.min(r.length-1,m+1)];let b=g.x-v.x,w=g.z-v.z;const y=Math.hypot(b,w);y<1e-6?(b=1,w=0):(b/=y,w/=y);const M=n.lateralAt?n.lateralAt(r[m].x,r[m].z,b,w):{offsetM:c,halfM:a},x=M?Math.max(n.minHalfM??.5,M.halfM):a,E=M?.offsetM??c,S=-w*x,A=b*x,T={x:r[m].x+-w*E,z:r[m].z+b*E};d.push(M!==void 0&&M.halfM>0&&!n.skip?.(T.x,T.z)),u.push([{x:T.x+S,z:T.z+A},T,{x:T.x-S,z:T.z-A}]),p.push(x)}const f=u.map(m=>m.map(v=>i(v.x,v.z)));for(let m=0;m<u.length-1;m++)for(let v=0;v<3;v++){const g=u[m][v],b=u[m+1][v],w=i((g.x+b.x)/2,(g.z+b.z)/2)-(f[m][v]+f[m+1][v])/2;w>0&&(f[m][v]+=w,f[m+1][v]+=w)}for(let m=0;m<u.length;m++){for(let v=0;v<3;v++)s.positions.push(u[m][v].x,f[m][v]+o,u[m][v].z);s.edges?.push(p[m],p[m],0,p[m],-p[m],p[m])}for(let m=0;m<r.length-1;m++){if(!d[m]||!d[m+1])continue;const v=h+m*3;s.indices.push(v,v+3,v+1,v+1,v+3,v+4),s.indices.push(v+1,v+4,v+2,v+2,v+4,v+5)}}appendKerb(e,t,i,s,n,r){const a=this.resample(e);if(a.length<2)return;const o=i.positions.length/3,c=[];for(let h=0;h<a.length;h++){const d=a[Math.max(0,h-1)],u=a[Math.min(a.length-1,h+1)];let p=u.x-d.x,f=u.z-d.z;const m=Math.hypot(p,f);m<1e-6?(p=1,f=0):(p/=m,f/=m);const v=s(a[h].x,a[h].z,p,f),g=a[h].x+-f*(v??0),b=a[h].z+p*(v??0);c.push(v!==void 0&&!r(g,b));const w=t(g,b)+At.LIFT_M;i.positions.push(g,w,b,g,w+At.SIDEWALK_KERB_M,b)}for(let h=0;h<a.length-1;h++){if(!c[h]||!c[h+1])continue;const d=o+h*2;n?i.indices.push(d,d+1,d+2,d+1,d+3,d+2):i.indices.push(d,d+2,d+1,d+1,d+2,d+3)}}static batchFor(e){return e==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(e,t,i,s,n=!0){if(t.indices.length===0)return;const r=new Tt;r.setAttribute("position",new Et(new Float32Array(t.positions),3));const a=t.edges!==void 0&&t.edges.length*3===t.positions.length*2;a&&r.setAttribute("aEdge",new Et(new Float32Array(t.edges),2)),r.setIndex(new Et(new Uint32Array(t.indices),1)),r.computeVertexNormals();const o=s??At.ALBEDO[e],c=new ta({color:new oe(o[0],o[1],o[2]),transparent:i,opacity:i?At.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});n&&this.addGrain(c,At.GRAIN_CONTRAST[e],a);const h=new Me(r,c);return h.name=`roads ${e}`,h.renderOrder=At.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(e,t,i=!1){const s=this.grainOrigin;e.onBeforeCompile=n=>{n.uniforms.uRoadOrigin={value:s},n.uniforms.uRoadContrast={value:t},i&&(n.defines={...n.defines,ROAD_VERGE:""}),n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
9942
|
+
}`)},e.customProgramCacheKey=()=>t?"rr0-grass-detail-everywhere":"rr0-grass-detail"}}class Oa{static LEVEL_QUANTILE=.2;static ROUTE_CLEARANCE_M=12;static METRES_PER_DEGREE=111320;static flatten(e,t,i){const s=i&&i.length>=2?Oa.alongRoute(e,i):void 0;let n=0;for(const r of t){const a=Oa.fill(e,r).filter(h=>!s?.[h]);if(a.length===0)continue;const o=a.map(h=>e.heights[h]).filter(Number.isFinite).sort((h,d)=>h-d);if(o.length===0)continue;const c=o[Math.floor((o.length-1)*Oa.LEVEL_QUANTILE)];for(const h of a)e.heights[h]>c&&(e.heights[h]=c,n++)}return n}static fill(e,t){const{width:i,height:s,bounds:n}=e,r=u=>(u-n.west)/(n.east-n.west)*(i-1),a=u=>(n.north-u)/(n.north-n.south)*(s-1),o=[];for(const u of t.rings)for(let p=0;p<u.length;p++){const f=u[p],m=u[(p+1)%u.length],v={r0:a(f.lat),c0:r(f.lng),r1:a(m.lat),c1:r(m.lng)};v.r0!==v.r1&&o.push(v)}const c=[];if(o.length===0)return c;const h=Math.max(0,Math.ceil(Math.min(...o.map(u=>Math.min(u.r0,u.r1))))),d=Math.min(s-1,Math.floor(Math.max(...o.map(u=>Math.max(u.r0,u.r1)))));for(let u=h;u<=d;u++){const p=[];for(const{r0:f,c0:m,r1:v,c1:g}of o)f<=u!=v<=u&&p.push(m+(g-m)*(u-f)/(v-f));p.sort((f,m)=>f-m);for(let f=0;f+1<p.length;f+=2){const m=Math.max(0,Math.ceil(p[f])),v=Math.min(i-1,Math.floor(p[f+1]));for(let g=m;g<=v;g++)c.push(u*i+g)}}return c}static alongRoute(e,t){const{width:i,height:s,bounds:n}=e,r=(n.east-n.west)*Oa.METRES_PER_DEGREE*Math.cos((n.north+n.south)/2*Math.PI/180)/(i-1),a=(n.north-n.south)*Oa.METRES_PER_DEGREE/(s-1),o=Math.ceil(Oa.ROUTE_CLEARANCE_M/r),c=Math.ceil(Oa.ROUTE_CLEARANCE_M/a),h=new Uint8Array(i*s),d=p=>(p-n.west)/(n.east-n.west)*(i-1),u=p=>(n.north-p)/(n.north-n.south)*(s-1);for(let p=0;p+1<t.length;p++){const[f,m,v,g]=[d(t[p].lng),u(t[p].lat),d(t[p+1].lng),u(t[p+1].lat)];if(Math.max(f,v)<-o||Math.min(f,v)>i-1+o||Math.max(m,g)<-c||Math.min(m,g)>s-1+c)continue;const b=Math.max(1,Math.ceil(Math.hypot(v-f,g-m)*2));for(let w=0;w<=b;w++){const y=Math.round(f+(v-f)*w/b),M=Math.round(m+(g-m)*w/b);for(let x=-c;x<=c;x++)for(let E=-o;E<=o;E++){const S=M+x,A=y+E;S<0||A<0||S>=s||A>=i||Math.hypot(E*r,x*a)<=Oa.ROUTE_CLEARANCE_M&&(h[S*i+A]=1)}}}return h}}const l8=64,sg=l8+1,ng=2048,c8=900,h8=700/900,d8=0,u8=.01,p8=1500;function hp(l,e,t){return{north:tr(0,-t,l,e).lat,south:tr(0,t,l,e).lat,east:tr(t,0,l,e).lng,west:tr(-t,0,l,e).lng}}async function c1(l,e,t,i=c8,s,n){const r=i,a=i*h8,o=hp(l,e,r),c={width:sg,height:sg},h=n||i>_t.ROADS_MAX_RADIUS_M?void 0:t.water?.getWater(o).catch(L=>(console.warn("Water unavailable, drawing none:",L),[])),[d,u]=await Promise.all([t.elevation.getElevationGrid(o,c,s),t.imagery.getImageryTexture(o,{width:ng,height:ng})]);let p;const f=h?await Promise.race([h,new Promise(L=>{p=setTimeout(()=>L(void 0),p8)})]):void 0;if(clearTimeout(p),d.width!==d.height||d.width<3||d.heights.length!==d.width*d.height)throw new Error("The ground came as a grid that is not square");rg.fill(d.heights,d.width),f&&f.length>0&&Oa.flatten(d,f,s?.route);const m=d.width,v=m-1,g=Math.floor(m/2),b=d.heights[g*m+g],w=n?.referenceElevationM??b,y=new Float32Array(m*m*3),M=new Float32Array(m*m*2),x=new Float32Array(m*m*4);for(let L=0;L<m;L++){const P=L/(m-1),C=o.north+(o.south-o.north)*P;for(let N=0;N<m;N++){const F=N/(m-1),H=o.west+(o.east-o.west)*F,{x:j,z:W}=ot(C,H,l,e),J=d.heights[L*m+N],re=Math.max(Math.abs(j),Math.abs(W)),Le=n&&re<n.innerM?0:1-f8((re-a)/(r-a),0,1),He=d8+u8+(J-w),De=L*m+N;y[De*3]=j,y[De*3+1]=He,y[De*3+2]=W;const Z=UT(u.bounds,H,C);M[De*2]=Z.x,M[De*2+1]=Z.y,x[De*4]=1,x[De*4+1]=1,x[De*4+2]=1,x[De*4+3]=Le}}const E=m*m>65535?new Uint32Array(v*v*6):new Uint16Array(v*v*6);let S=0;for(let L=0;L<v;L++)for(let P=0;P<v;P++){const C=L*m+P,N=C+1,F=C+m,H=F+1;E[S++]=C,E[S++]=F,E[S++]=N,E[S++]=N,E[S++]=F,E[S++]=H}const A=new Tt;A.setAttribute("position",new Et(y,3)),A.setAttribute("uv",new Et(M,2)),A.setAttribute("color",new Et(x,4)),A.setIndex(new Et(E,1)),A.computeVertexNormals();const T=new lc(u.source);T.flipY=!1,T.colorSpace=an,T.anisotropy=8;const _=new ta({map:T,color:new oe(1,1,1),vertexColors:!0,transparent:!0,fog:!0});n||Ud.install(_);const k=new Me(A,_);return k.receiveShadow=!n,k.castShadow=!n,{mesh:k,attribution:t.imagery.attribution,originElevationM:Number.isFinite(b)?b:void 0,...f?{water:f}:h?{waterLater:h}:{}}}class rg{static LOWEST_GROUND_M=-500;static MAX_PASSES=64;static fill(e,t){const i=n=>!Number.isFinite(n)||n<rg.LOWEST_GROUND_M;let s=0;for(let n=0;n<e.length;n++)i(e[n])&&s++;for(let n=0;s>0&&n<rg.MAX_PASSES;n++){const r=[];for(let a=0;a<t;a++)for(let o=0;o<t;o++){const c=a*t+o;if(!i(e[c]))continue;let h=0,d=0;for(const[u,p]of[[-1,0],[1,0],[0,-1],[0,1]]){const f=a+u,m=o+p;if(f<0||m<0||f>=t||m>=t)continue;const v=e[f*t+m];i(v)||(h+=v,d++)}d>0&&r.push([c,h/d])}for(const[a,o]of r)e[a]=o;if(s-=r.length,r.length===0)break}if(s>0)for(let n=0;n<e.length;n++)i(e[n])&&(e[n]=0)}}function f8(l,e,t){return Math.max(e,Math.min(t,l))}class At{static STEP_M=8;stepM=At.STEP_M;static LIFT_M=.06;static RENDER_ORDER=1.05;static MARKINGS_RENDER_ORDER=1.06;static BARRIER_ALBEDO=[.32,.33,.34];static MARKINGS_ALBEDO=[.55,.55,.5];static GRAIN_CONTRAST={paved:.25,gravel:1.1,dirt:1.1};static SIDEWALK_WIDTH_M=1.8;static SIDEWALK_NONE_M=.8;static STREET_MIDDLE_MOST_M=2.5;static LAMP_CLEARANCE_M=.4;static LAMP_FROM_KERB_M=.5;static KERB_REACH_M=12;static SIDEWALK_KERB_M=.12;static SIDEWALK_MIN_ROAD_M=3.5;static SIDEWALK_ALBEDO=[.3,.29,.27];static CONTEMPORARY_OPACITY=.45;static ALBEDO={paved:[.16,.16,.17],gravel:[.42,.38,.31],dirt:[.34,.28,.21]};grainOrigin=new ie;grainReference;laidStreets=[];markingsToken=0;static markingsModule;group=new ii;surveyed=new ii;stated=new ii;constructor(){this.group.name="roads",this.surveyed.name="roads surveyed",this.stated.name="roads stated",this.group.add(this.surveyed,this.stated)}setGroundSpacing(e){this.stepM=Number.isFinite(e)&&e>0?Math.min(At.STEP_M,Math.max(1.5,e/2)):At.STEP_M}set(e,t,i,s,n,r=1/0,a){const o=At.within(e,t,i,r);At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++,this.anchorGrain(t,i);const c=new Map,h=o.map(p=>p.points.map(f=>ot(f.lat,f.lng,t,i))),d=o.map((p,f)=>this.streetOf(p,h[f],a));for(const[p,f]of o.entries()){const m=c.get(f.surface)??At.batchFor(f.surface);c.set(f.surface,m);const v=d[p];this.appendPath(h[p],f.widthM,s,m,v?{lateralAt:(g,b,w,y)=>v(g,b,w,y).carriageway}:{})}for(const[p,f]of c){const m=this.meshOf(p,f,n);m&&this.surveyed.add(m)}const u=this.sidewalks(o,h,d,s);if(u.indices.length>0){const p=this.meshOf("paved",u,!1,At.SIDEWALK_ALBEDO,!1);p&&(p.name="roads sidewalks",this.surveyed.add(p))}this.paint(o,t,i,s,n)}paint(e,t,i,s,n){if(!e.some(a=>a.surface==="paved"&&a.widthM>=5.5&&a.kind!=="roundabout"))return;const r=this.markingsToken;(At.markingsModule??=Q(()=>import("./RoadMarkings-GIdi730L.js"),[],import.meta.url)).then(({RoadMarkings:a})=>{if(r!==this.markingsToken)return;const o={positions:[],indices:[]};if(a.lay(e,t,i,(d,u,p)=>this.appendPath(d,u,s,o,{offsetM:p.offsetM,liftM:At.LIFT_M+p.liftM,minHalfM:p.minHalfM}))>0&&o.indices.length>0){const d=this.meshOf("paved",o,n,At.MARKINGS_ALBEDO,!1);d&&(d.name="roads markings",d.renderOrder=At.MARKINGS_RENDER_ORDER,d.material.polygonOffsetFactor=-4,d.material.polygonOffsetUnits=-4,this.surveyed.add(d))}const h=a.barrierGeometry(a.barriers(e,t,i),s);if(h.indices.length>0){const d=this.meshOf("paved",h,n,At.BARRIER_ALBEDO,!1);d&&(d.name="roads barriers",d.material.polygonOffset=!1,d.castShadow=!0,this.surveyed.add(d))}this.onMarkings?.()})}onMarkings;anchorGrain(e,t){if(this.grainReference){const s=ot(this.grainReference.lat,this.grainReference.lng,e,t);Math.hypot(s.x,s.z)>2e4&&(this.grainReference=void 0)}this.grainReference??={lat:e,lng:t};const i=ot(this.grainReference.lat,this.grainReference.lng,e,t);this.grainOrigin.set(-i.x,-i.z)}static within(e,t,i,s){if(!Number.isFinite(s))return e;const n=s*1.1+100;return e.filter(r=>{let a;for(const o of r.points){const c=ot(o.lat,o.lng,t,i);if(Math.hypot(c.x,c.z)<=n||a&&Math.hypot((c.x+a.x)/2,(c.z+a.z)/2)<=n)return!0;a=c}return!1})}streetOf(e,t,i){if(!e.urban||e.surface!=="paved")return;const s=At.surveyedAcross(e);if(!i||!i.near(t))return()=>s;const n=new Map,r=(p,f,m,v)=>{const g=`${p.toFixed(2)}:${f.toFixed(2)}`;let b=n.get(g);return b||(b=i.across(p,f,m,v),n.set(g,b)),b},a=this.rungsOf(t),o=a.flatMap(p=>{const f=r(p.x,p.z,p.dirX,p.dirZ);return f.leftM!==void 0&&f.rightM!==void 0?[(f.leftM-f.rightM)/2]:[]}).sort((p,f)=>p-f),c=i.lampsAlong(t);if(o.length===0&&c.length===0)return()=>s;const h=o.length>0?o[Math.floor((o.length-1)/2)]:0,d=At.clearOf(c,e.widthM/2,Math.max(-2.5,Math.min(At.STREET_MIDDLE_MOST_M,h))),u={rungs:a,across:(p,f,m,v)=>At.betweenWalls(e,d,r(p,f,m,v).leftM,r(p,f,m,v).rightM)};return this.laidStreets.push(u),(p,f,m,v)=>{const g=r(p,f,m,v);return At.betweenWalls(e,d,g.leftM,g.rightM)}}static clearOf(e,t,i){const s=r=>e.every(a=>Math.abs(a-r)>=t+At.LAMP_CLEARANCE_M);if(s(i))return i;const n=At.STREET_MIDDLE_MOST_M;for(let r=.1;r<=2*n;r+=.1)for(const a of[i-r,i+r])if(Math.abs(a)<=n&&s(a))return a;return i}atKerb(e,t){let i;for(const u of this.laidStreets)for(const p of u.rungs){const f=Math.hypot(e-p.x,t-p.z);f<=At.KERB_REACH_M&&(!i||f<i.distance)&&(i={rung:p,across:u.across(p.x,p.z,p.dirX,p.dirZ),distance:f})}if(!i)return{x:e,z:t};const{rung:s,across:n}=i,r=(e-s.x)*-s.dirZ+(t-s.z)*s.dirX,a=(e-s.x)*s.dirX+(t-s.z)*s.dirZ,c=(r>=n.carriageway.offsetM?n.left:n.right)??n.left??n.right;if(!c)return{x:e,z:t};const h=Math.sign(c.outerM-c.kerbM),d=c.kerbM+h*Math.min(At.LAMP_FROM_KERB_M,Math.abs(c.outerM-c.kerbM)/2);return{x:s.x+s.dirX*a-s.dirZ*d,z:s.z+s.dirZ*a+s.dirX*d}}rungsOf(e){const t=this.resample(e);return t.map((i,s)=>{const n=t[Math.max(0,s-1)],r=t[Math.min(t.length-1,s+1)],a=r.x-n.x,o=r.z-n.z,c=Math.hypot(a,o);return c<1e-6?{x:i.x,z:i.z,dirX:1,dirZ:0}:{x:i.x,z:i.z,dirX:a/c,dirZ:o/c}})}static surveyedAcross(e){const t=e.widthM/2,i={offsetM:0,halfM:t};return e.widthM<At.SIDEWALK_MIN_ROAD_M?{carriageway:i}:{carriageway:i,left:{kerbM:t,outerM:t+At.SIDEWALK_WIDTH_M},right:{kerbM:-t,outerM:-t-At.SIDEWALK_WIDTH_M}}}static betweenWalls(e,t,i,s){const n=e.widthM/2,r={offsetM:t,halfM:n},a=t+n,o=t-n,c=i??a+At.SIDEWALK_WIDTH_M,h=-(s??-o+At.SIDEWALK_WIDTH_M);return{carriageway:r,...c-a>=At.SIDEWALK_NONE_M?{left:{kerbM:a,outerM:c}}:{},...o-h>=At.SIDEWALK_NONE_M?{right:{kerbM:o,outerM:h}}:{}}}sidewalks(e,t,i,s){const n={positions:[],indices:[]},r=new Pa(e,t);return e.forEach((a,o)=>{const c=i[o];if(!c)return;const h=(d,u)=>r.onAnotherCarriageway(d,u,o);for(const d of["left","right"]){const u=(p,f,m,v)=>{const g=c(p,f,m,v)[d];return g&&{offsetM:(g.kerbM+g.outerM)/2,halfM:Math.abs(g.outerM-g.kerbM)/2}};this.appendPath(t[o],0,s,n,{lateralAt:u,liftM:At.LIFT_M+At.SIDEWALK_KERB_M,minHalfM:0,skip:h}),this.appendKerb(t[o],s,n,(p,f,m,v)=>c(p,f,m,v)[d]?.kerbM,d==="left",h)}}),n}setStated(e,t){At.empty(this.stated);const i=new Map;for(const s of e){const n=i.get(s.surface)??At.batchFor(s.surface);i.set(s.surface,n),this.appendPath(s.path.map(r=>({x:r.eastM,z:-r.northM})),s.widthM,t,n)}for(const[s,n]of i){const r=this.meshOf(s,n,!1);r&&this.stated.add(r)}}clear(){At.empty(this.surveyed),this.laidStreets=[],this.markingsToken++}static empty(e){for(const t of[...e.children]){e.remove(t);const i=t;i.geometry?.dispose(),i.material?.dispose()}}dispose(){At.empty(this.surveyed),At.empty(this.stated)}appendPath(e,t,i,s,n={}){const r=this.resample(e);if(r.length<2)return;const a=Math.max(n.minHalfM??.5,t/2),o=n.liftM??At.LIFT_M,c=n.offsetM??0,h=s.positions.length/3,d=[],u=[],p=[];for(let m=0;m<r.length;m++){const v=r[Math.max(0,m-1)],g=r[Math.min(r.length-1,m+1)];let b=g.x-v.x,w=g.z-v.z;const y=Math.hypot(b,w);y<1e-6?(b=1,w=0):(b/=y,w/=y);const M=n.lateralAt?n.lateralAt(r[m].x,r[m].z,b,w):{offsetM:c,halfM:a},x=M?Math.max(n.minHalfM??.5,M.halfM):a,E=M?.offsetM??c,S=-w*x,A=b*x,T={x:r[m].x+-w*E,z:r[m].z+b*E};d.push(M!==void 0&&M.halfM>0&&!n.skip?.(T.x,T.z)),u.push([{x:T.x+S,z:T.z+A},T,{x:T.x-S,z:T.z-A}]),p.push(x)}const f=u.map(m=>m.map(v=>i(v.x,v.z)));for(let m=0;m<u.length-1;m++)for(let v=0;v<3;v++){const g=u[m][v],b=u[m+1][v],w=i((g.x+b.x)/2,(g.z+b.z)/2)-(f[m][v]+f[m+1][v])/2;w>0&&(f[m][v]+=w,f[m+1][v]+=w)}for(let m=0;m<u.length;m++){for(let v=0;v<3;v++)s.positions.push(u[m][v].x,f[m][v]+o,u[m][v].z);s.edges?.push(p[m],p[m],0,p[m],-p[m],p[m])}for(let m=0;m<r.length-1;m++){if(!d[m]||!d[m+1])continue;const v=h+m*3;s.indices.push(v,v+3,v+1,v+1,v+3,v+4),s.indices.push(v+1,v+4,v+2,v+2,v+4,v+5)}}appendKerb(e,t,i,s,n,r){const a=this.resample(e);if(a.length<2)return;const o=i.positions.length/3,c=[];for(let h=0;h<a.length;h++){const d=a[Math.max(0,h-1)],u=a[Math.min(a.length-1,h+1)];let p=u.x-d.x,f=u.z-d.z;const m=Math.hypot(p,f);m<1e-6?(p=1,f=0):(p/=m,f/=m);const v=s(a[h].x,a[h].z,p,f),g=a[h].x+-f*(v??0),b=a[h].z+p*(v??0);c.push(v!==void 0&&!r(g,b));const w=t(g,b)+At.LIFT_M;i.positions.push(g,w,b,g,w+At.SIDEWALK_KERB_M,b)}for(let h=0;h<a.length-1;h++){if(!c[h]||!c[h+1])continue;const d=o+h*2;n?i.indices.push(d,d+1,d+2,d+1,d+3,d+2):i.indices.push(d,d+2,d+1,d+1,d+2,d+3)}}static batchFor(e){return e==="paved"?{positions:[],indices:[]}:{positions:[],indices:[],edges:[]}}meshOf(e,t,i,s,n=!0){if(t.indices.length===0)return;const r=new Tt;r.setAttribute("position",new Et(new Float32Array(t.positions),3));const a=t.edges!==void 0&&t.edges.length*3===t.positions.length*2;a&&r.setAttribute("aEdge",new Et(new Float32Array(t.edges),2)),r.setIndex(new Et(new Uint32Array(t.indices),1)),r.computeVertexNormals();const o=s??At.ALBEDO[e],c=new ta({color:new oe(o[0],o[1],o[2]),transparent:i,opacity:i?At.CONTEMPORARY_OPACITY:1,fog:!0,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2});n&&this.addGrain(c,At.GRAIN_CONTRAST[e],a);const h=new Me(r,c);return h.name=`roads ${e}`,h.renderOrder=At.RENDER_ORDER,h.receiveShadow=!0,h.castShadow=!1,h}addGrain(e,t,i=!1){const s=this.grainOrigin;e.onBeforeCompile=n=>{n.uniforms.uRoadOrigin={value:s},n.uniforms.uRoadContrast={value:t},i&&(n.defines={...n.defines,ROAD_VERGE:""}),n.vertexShader=n.vertexShader.replace("#include <common>",`#include <common>
|
|
9943
9943
|
varying vec2 vRoadXZ;
|
|
9944
9944
|
uniform vec2 uRoadOrigin;
|
|
9945
9945
|
#ifdef ROAD_VERGE
|
|
@@ -10938,14 +10938,14 @@ ${Ke.OUTPUT_PROJECTION_GLSL}`)}}class Sn{constructor(e,t){this.width=e,this.heig
|
|
|
10938
10938
|
if (ice <= 0.0) discard;
|
|
10939
10939
|
gl_FragColor = vec4(iceHaloLight(dir, ice), 1.0);
|
|
10940
10940
|
}
|
|
10941
|
-
`,transparent:!0,blending:qs,depthWrite:!1,side:Ji,fog:!1}),this.object=new Me(new Rs(gs.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,s,n,r,a=si.DEFAULT_RARE_SHARE){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(s[0],s[1],s[2]),o.uIceCover.value=n.cover,o.uIceHeight.value=n.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r,a)}featureAt(e){const t=this.material.uniforms;if(!this.everDisplayed||!(t.uStrength.value>0)||this.mappedAltitudeDeg!==this.mappedAltitudeDeg)return;const i=t.uUp.value.clone().normalize(),s=t.uSource.value.clone().normalize(),n=Math.PI/180,r=Math.asin(Math.max(-1,Math.min(1,e.dot(i))))/n,a=Math.asin(Math.max(-1,Math.min(1,s.dot(i))))/n,o=v=>v.clone().sub(i.clone().multiplyScalar(v.dot(i))),c=o(s),h=o(e),d=c.length()<1e-4||h.length()<1e-4?0:Math.acos(Math.max(-1,Math.min(1,c.dot(h)/(c.length()*h.length()))))/n,u=si.AZIMUTH_BINS,p=si.ALTITUDE_BINS,f=this.texels,m=(v,g)=>{if(v<-90||v>90)return 0;const b=Math.min(u-1,Math.max(0,Math.floor(Math.min(180,Math.abs(g))/180*u))),w=Math.min(p-1,Math.max(0,Math.floor((v+90)/180*p)));return gs.halfToFloat(f[(w*u+b)*4+1])};return fd.at(a,r,d,m)}static halfToFloat(e){const t=e>>10&31,i=e&1023,s=e>>15?-1:1;return t===0?s*i*5960464477539063e-23:s*2**(t-15)*(1+i/1024)}requestMap(e,t,i){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<gs.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<gs.ALIGNMENT_STEP)||!(Math.abs(i-this.mappedRare)<gs.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t,i)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<gs.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<gs.LEAP_ALIGNMENT)||!(Math.abs(i-this.pendingRare)<gs.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t,rare:i};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.pendingRare=i,this.stopWork(),this.tracing=!0,this.startTracing(e,t,i)}startTracing(e,t,i){const s=++this.ticket,n=()=>{s!==this.ticket||!this.tracing||(this.sky.begin(e,t,void 0,si.populationsFor(i)),this.scheduleWork())};Ll.with(r=>{s!==this.ticket||!this.tracing||(this.job=r.trace(e,t,i,gs.RAYS,a=>{this.job=void 0,this.texels.set(a),this.display(),this.finishTracing()},n))},n)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;pendingRare=Number.NaN;next;tracingFor(e,t,i){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<gs.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<gs.ALIGNMENT_STEP&&Math.abs(i-this.pendingRare)<gs.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?gs.URGENT_BUDGET_MS:gs.BUDGET_MS;do this.sky.trace(gs.RAYS_PER_BATCH);while(this.sky.tracedRays<gs.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=gs.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment,this.mappedRare=this.pendingRare;const e=this.next;e&&this.requestMap(e.sourceAltitudeDeg,e.alignment,e.rare)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){k8.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class Qs{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Qs.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Qs.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];heads=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=Qs.MAX_CONCURRENT*Qs.SEGMENTS*Qs.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new Tt;t.setAttribute("position",new Et(this.positions,3)),t.setAttribute("color",new Et(this.colors,3)),t.setDrawRange(0,0),this.object=new Me(t,ao.material()),this.object.frustumCulled=!1,ao.track(this.object)}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.heads=[],this.meteors.length===0){t.setDrawRange(0,0);return}const i=Yr.aliveAt(this.meteors,e).slice(0,Qs.MAX_CONCURRENT);let s=0;for(const{meteor:n,progress:r}of i){const a=this.radiantOf(n);if(!a)continue;const o=Li(a.altitudeDeg,a.azimuthDeg,1),[c,h]=this.basisAround(o),d=n.fromRadiantDeg+r*n.lengthDeg,u=Math.max(n.fromRadiantDeg,d-n.lengthDeg*.6),p=Math.min(1,(1-r)*2.5),f=this.turn(c,h,n.bearingDeg),m=(.15+.85*n.brightness)*p,v=y=>m*y**1.6,g=y=>this.onSphere(o,f,u+(d-u)*y),b=g(1);p>0&&this.heads.push({...iI(b.x,b.y,b.z),magnitude:Yr.magnitudeOf(n)-2.5*Math.log10(p)});const w=y=>Qs.RADIUS*((Qs.MIN_HALF_WIDTH_DEG+Qs.BRIGHT_HALF_WIDTH_DEG*n.brightness*y)*Math.PI/180);for(let y=1;y<Qs.POINTS;y++){const M=(y-1)/Qs.SEGMENTS,x=y/Qs.SEGMENTS;s=this.pushRibbon(s,g(M),g(x),w(M),w(x),v(M),v(x))}}t.setDrawRange(0,s),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=Li(t.altitudeDeg,t.azimuthDeg,1),[s,n]=this.basisAround(i),r=this.turn(s,n,e.bearingDeg),a=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),o=Math.hypot(a.x,a.y,a.z)||1;return{altitudeDeg:Math.asin(a.y/o)*180/Math.PI,azimuthDeg:(Math.atan2(a.x,-a.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,s,n,r,a){const o=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Qs.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,o,s,h),p=this.across(i,o,n,h),f=this.across(t,o,s,d),m=this.across(i,o,n,d),v=(g,b)=>g===0?b:0;e=this.push(e,u,v(h,r)),e=this.push(e,p,v(h,a)),e=this.push(e,f,v(d,r)),e=this.push(e,p,v(h,a)),e=this.push(e,m,v(d,a)),e=this.push(e,f,v(d,r))}return e}across(e,t,i,s){return{x:e.x+t.x*i*s,y:e.y+t.y*i*s,z:e.z+t.z*i*s}}push(e,t,i){const s=e*3;this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z;const n=Ve.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=n*.9,this.colors[s+1]=n*.95,this.colors[s+2]=n,e+1}turn(e,t,i){const s=i*Math.PI/180,n=Math.cos(s),r=Math.sin(s);return{x:e.x*n+t.x*r,y:e.y*n+t.y*r,z:e.z*n+t.z*r}}onSphere(e,t,i){const s=i*Math.PI/180,n=Math.cos(s),r=Math.sin(s);return{x:(e.x*n+t.x*r)*Qs.RADIUS,y:(e.y*n+t.y*r)*Qs.RADIUS,z:(e.z*n+t.z*r)*Qs.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class un{static MEDIAN_BEDTIME=22+40/60;static MEDIAN_RISING=7;static BEDTIME_SPREAD_H=1.2;static RISING_SPREAD_H=.7;static ALWAYS_UP=.02;static LIT_WHEN_ALL_UP=.5;static UNKNOWN_HOUR=.16;static DUSK_DEG=-1;static NIGHT_DEG=-9;static awakeAt(e){const t=(e%24+24)%24,i=un.normal(((t<12?t+24:t)-un.MEDIAN_BEDTIME)/un.BEDTIME_SPREAD_H),s=un.normal((t-un.MEDIAN_RISING)/un.RISING_SPREAD_H),n=i*(t<12?1-s:1);return Math.max(un.ALWAYS_UP,1-n)}static shareAt(e){return e===void 0||!Number.isFinite(e)?un.UNKNOWN_HOUR:un.LIT_WHEN_ALL_UP*un.awakeAt(e)}static darknessAt(e){return Math.max(0,Math.min(1,(un.DUSK_DEG-e)/(un.DUSK_DEG-un.NIGHT_DEG)))}static share(e,t){return un.darknessAt(e)*un.shareAt(t)}static normal(e){const t=Math.abs(e)/Math.SQRT2,i=1/(1+.3275911*t),s=1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-t*t);return e>=0?.5*(1+s):.5*(1-s)}}class Ui{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??Ui.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Ui.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Ui.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Ui.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,s=[];if(this.span>0){s.push(Ui.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const o of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&s.push(Ui.box(e+1,c,Ui.ABUTMENT_THICKNESS_M,0,c/2,o*(i-Ui.ABUTMENT_THICKNESS_M/2)))}}const n=[];this.span>0&&n.push(Ui.box(e,.04,this.span,0,t+.02,0));const r=[];for(const o of[-1,1])this.bank<=0||(r.push(this.embankment(o)),n.push(this.bankRoad(o)));const a=[];for(const o of[-1,1])a.push(...this.railing(o*(e/2-Ui.POST_SIDE_M)));return{concrete:Ui.merge(s),road:Ui.merge(n),earth:Ui.merge(r),railing:Ui.merge(a)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),s=[],n=(c,h,d,u)=>{s.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Ui.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,p=(f,m,v,g)=>u?n(f,m,v,g):n(g,v,m,f);p(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),p(h.leftTop,h.rightTop,d.rightTop,d.leftTop),p(h.rightTop,h.rightFoot,d.rightFoot,d.rightTop)}const a=r(i[0]);e>0?n(a.leftFoot,a.rightFoot,a.rightTop,a.leftTop):n(a.leftTop,a.rightTop,a.rightFoot,a.leftFoot);const o=new Tt;return o.setAttribute("position",new wt(s,3)),o.computeVertexNormals(),o}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),s=[];for(let r=1;r<i.length;r++){const a=i[r-1],o=i[r],c=this.roadAt(a)+.02,h=this.roadAt(o)+.02,d=e>0?[[-t,c,a],[t,c,a],[t,h,o],[-t,h,o]]:[[-t,h,o],[t,h,o],[t,c,a],[-t,c,a]];for(const u of[0,2,1,0,3,2])s.push(...d[u])}const n=new Tt;return n.setAttribute("position",new wt(s,3)),n.computeVertexNormals(),n}stations(e){const t=[];for(let i=0;i<=Ui.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Ui.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),s=[];for(let a=0;a<=i;a++)s.push(-t+this.size.lengthM*a/i);const n=[],r=Ui.POST_SIDE_M;for(const a of s)n.push(Ui.box(r,this.railHeight,r,e,this.roadAt(a)+this.railHeight/2,a));for(let a=1;a<=this.rails;a++){const o=this.railHeight*a/this.rails-Ui.RAIL_HEIGHT_M/2;for(let c=1;c<s.length;c++){const h=new D(e,this.roadAt(s[c-1])+o,s[c-1]),d=new D(e,this.roadAt(s[c])+o,s[c]);n.push(Ui.beam(h,d))}}return n}static box(e,t,i,s,n,r){return new Ss(e,t,i).translate(s,n,r)}static beam(e,t){const i=new D().subVectors(t,e),s=new Ss(Ui.RAIL_DEPTH_M,Ui.RAIL_HEIGHT_M,i.length()),n=new Un().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return s.applyMatrix4(new qe().compose(r,n,new D(1,1,1)))}static merge(e){const t=e.map(o=>o.getIndex()?o.toNonIndexed():o),i=t.reduce((o,c)=>o+c.getAttribute("position").count,0),s=new Float32Array(i*3),n=new Float32Array(i*3);let r=0;for(const o of t){const c=o.getAttribute("position"),h=o.getAttribute("normal");s.set(c.array,r*3),h&&n.set(h.array,r*3),r+=c.count}const a=new Tt;a.setAttribute("position",new wt(s,3)),a.setAttribute("normal",new wt(n,3));for(const o of e)o.dispose();for(const o of t)o.dispose();return a}}class Ki{static OVERHANG_M=.25;static SLAB_M=.2;static MIN_RIDGE_M=.1;static DEFAULT_RISE_M=3;static normalised(e){const t=e.shape??"flat";return{shape:t,riseM:t==="flat"?0:Math.max(0,e.riseM??Ki.DEFAULT_RISE_M),ridge:e.ridge??"width",...e.color?{color:e.color}:{}}}static build(e,t,i){const s=Ki.normalised(e),n=s.shape==="gable"&&s.ridge==="depth",r=(n?i:t)/2+Ki.OVERHANG_M,a=(n?t:i)/2+Ki.OVERHANG_M,o=s.shape==="flat"||s.riseM<=0?Ki.slab(r,a):s.shape==="dome"?Ki.dome(r-Ki.OVERHANG_M,a-Ki.OVERHANG_M,r,a,s.riseM):Ki.pitched(s.shape,r,a,s.riseM);return n&&o.rotateY(Math.PI/2),o.computeVertexNormals(),o}static slab(e,t){const i=Ki.SLAB_M,s=[[-e,0,-t],[e,0,-t],[e,0,t],[-e,0,t]],n=s.map(([o,,c])=>[o,i,c]),r=[],a=(o,c,h,d)=>{r.push(o,c,h,o,h,d)};a(n[0],n[3],n[2],n[1]);for(let o=0;o<4;o++){const c=(o+1)%4;a(s[o],s[c],n[c],n[o])}return Ki.of(r)}static pitched(e,t,i,s){const n=(h,d)=>[h,0,d],r=e==="gable"?t:Math.max(Ki.MIN_RIDGE_M/2,t-i),a=[-r,s,0],o=[r,s,0],c=[];return c.push(n(-t,-i),n(t,-i),o,n(-t,-i),o,a),c.push(n(t,i),n(-t,i),a,n(t,i),a,o),c.push(n(-t,i),n(-t,-i),a),c.push(n(t,-i),n(t,i),o),c.push(n(-t,-i),n(-t,i),n(t,i),n(-t,-i),n(t,i),n(t,-i)),Ki.of(c)}static DOME_RINGS=12;static DOME_SECTORS=48;static dome(e,t,i,s,n){const r=Ki.slab(i,s).getAttribute("position").array,a=[];for(let c=0;c<r.length;c+=3)a.push([r[c],r[c+1],r[c+2]]);const o=(c,h)=>{const d=c/Ki.DOME_RINGS*(Math.PI/2),u=h/Ki.DOME_SECTORS*2*Math.PI,p=Math.cos(d);return[e*p*Math.cos(u),Ki.SLAB_M+n*Math.sin(d),t*p*Math.sin(u)]};for(let c=0;c<Ki.DOME_RINGS;c++)for(let h=0;h<Ki.DOME_SECTORS;h++){const d=h+1;a.push(o(c,h),o(c+1,d),o(c,d),o(c,h),o(c+1,h),o(c+1,d))}return Ki.of(a)}static of(e){const t=new Tt;return t.setAttribute("position",new wt(e.flat(),3)),t}}class $r{static SLAB_M=.6;static SLABS=4;static SIZE=512;static JOINT_M=.012;static made;static texture(){if($r.made)return $r.made;const e=$r.SIZE,t=new Uint8Array(e*e*4);let i=23063;const s=()=>{i=i+1831565813|0;let p=Math.imul(i^i>>>15,1|i);return p=p+Math.imul(p^p>>>7,61|p)^p,((p^p>>>14)>>>0)/4294967296},n=$r.SLABS,r=e/n,a=Math.max(1,Math.round($r.JOINT_M/$r.SLAB_M*r)),o=Array.from({length:n*n},()=>.9+.1*s()),c=n*8,h=Array.from({length:c*c},()=>s()),d=(p,f)=>h[(f%c+c)%c*c+(p%c+c)%c];for(let p=0;p<e;p++)for(let f=0;f<e;f++){const m=Math.floor(f/r),v=Math.floor(p/r),g=f-m*r,b=p-v*r,w=g<a||b<a,y=f/r*8,M=p/r*8,x=Math.floor(y),E=Math.floor(M),S=y-x,A=M-E,T=S*S*(3-2*S),_=A*A*(3-2*A),k=(d(x,E)*(1-T)+d(x+1,E)*T)*(1-_)+(d(x,E+1)*(1-T)+d(x+1,E+1)*T)*_,L=s(),P=w?.55:o[v*n+m]*(.9+.12*k)*(.88+.12*L),C=Math.min(255,Math.round(255*P)),N=(p*e+f)*4;t[N]=C,t[N+1]=C,t[N+2]=C,t[N+3]=255}const u=new nr(t,e,e,xs,On);return u.wrapS=u.wrapT=sc,u.minFilter=Nr,u.generateMipmaps=!0,u.colorSpace=an,u.anisotropy=8,u.needsUpdate=!0,$r.made=u,u}static layOn(e){const t=e.getAttribute("position"),i=$r.SLAB_M*$r.SLABS,s=new Float32Array(t.count*2);for(let n=0;n<t.count;n++)s[n*2]=t.getX(n)/i,s[n*2+1]=t.getZ(n)/i;e.setAttribute("uv",new wt(s,2))}}class Ne{static UPPER=0;static GROUND_WINDOW=1;static GROUND_DOOR=2;static PLAIN=3;static TALL=4;static LANCET=5;static TILES=6;static TALL_SILL=.5;static TALL_HEAD=2.62;static BAY_M=3;static FLOOR_M=3;static PIXELS=96;static shared;static sharedEmissive;static texture(){if(!Ne.shared){const e=new nr(Ne.pixels(),Ne.PIXELS*Ne.TILES,Ne.PIXELS,xs,On);e.colorSpace=an,e.wrapS=Ms,e.wrapT=Ms,e.magFilter=St,e.minFilter=Nr,e.generateMipmaps=!0,e.needsUpdate=!0,Ne.shared=e}return Ne.shared}static emissive(){if(!Ne.sharedEmissive){const e=new nr(Ne.glow(),Ne.PIXELS*Ne.TILES,Ne.PIXELS,xs,On);e.colorSpace=an,e.wrapS=Ms,e.wrapT=Ms,e.magFilter=St,e.minFilter=Nr,e.generateMipmaps=!0,e.needsUpdate=!0,Ne.sharedEmissive=e}return Ne.sharedEmissive}static glow(){const e=Ne.PIXELS,t=e*Ne.TILES,i=new Uint8Array(t*e*4);for(let r=3;r<i.length;r+=4)i[r]=255;const s=e/Ne.BAY_M,n=[[Ne.UPPER,.9,2.3],[Ne.GROUND_WINDOW,.9,2.3],[Ne.TALL,Ne.TALL_SILL,Ne.TALL_HEAD]];for(const[r,a,o]of n)for(let c=Math.round(a*s);c<Math.round(o*s);c++)for(let h=Math.round(.9*s);h<Math.round(2.1*s);h++){if(Math.abs(h-1.5*s)<.03*s)continue;const d=(c*t+r*e+h)*4,[u,p,f]=Ne.roomLight((h/s-.9)/1.2,(c/s-a)/(o-a));i[d]=u,i[d+1]=p,i[d+2]=f}return i}static roomLight(e,t){const i=.35+.65*Math.pow(Math.max(0,Math.min(1,t)),.8),s=1-.45*Math.pow(Math.abs(2*e-1),3),n=Math.min(e,1-e)<.16,r=i*s*(n?.35:1),a=n?[255,225,195]:[255,255,255],o=Math.pow(r,1/2.2);return[Math.round(a[0]*o),Math.round(a[1]*o),Math.round(a[2]*o)]}static pixels(){const e=Ne.PIXELS,t=e*Ne.TILES,i=new Uint8Array(t*e*4).fill(255),s=e/Ne.BAY_M,n=(f,m,v,g,b,w)=>{for(let y=Math.round(v*s);y<Math.round(b*s);y++)for(let M=Math.round(m*s);M<Math.round(g*s);M++){const x=(y*t+f*e+M)*4;i[x]=w[0],i[x+1]=w[1],i[x+2]=w[2],i[x+3]=255}},r=[225,225,222],a=[34,42,54],o=[200,198,192];for(const f of[Ne.UPPER,Ne.GROUND_WINDOW])n(f,.9-.06,.9-.06,2.1+.06,2.3+.06,r),n(f,.9,.9,2.1,2.3,a),n(f,1.5-.02,.9,1.5+.02,2.3,r),n(f,.8,.84,2.2,.9-.06,o);n(Ne.GROUND_DOOR,1-.06,0,2+.06,2.1+.06,r),n(Ne.GROUND_DOOR,1,0,2,2.1,[58,62,56]);const c=[44,44,46],h=Ne.TALL;n(h,0,0,3,.09,[214,210,202]),n(h,.9-.08,Ne.TALL_SILL-.04,2.1+.08,Ne.TALL_HEAD+.1,r),n(h,.9,Ne.TALL_SILL,2.1,Ne.TALL_HEAD,a),n(h,1.5-.02,Ne.TALL_SILL,1.5+.02,Ne.TALL_HEAD,r),n(h,.82,Ne.TALL_SILL,2.18,Ne.TALL_SILL+.05,c),n(h,.82,Ne.TALL_SILL+.38,2.18,Ne.TALL_SILL+.43,c);for(let f=.86;f<2.15;f+=.13)n(h,f,Ne.TALL_SILL,f+.03,Ne.TALL_SILL+.4,c);const d=Ne.LANCET,u=2,p=2.34;n(d,1.2,.66,1.8,u,[40,44,54]);for(let f=u;f<p;f+=1/s){const m=.3*Math.sqrt(1-((f-u)/(p-u))**2);n(d,1.5-m,f,1.5+m,f+1/s,[40,44,54])}return i}}class pp{static hash(e,t){const i=Math.sin(e*12.9898+t*78.233)*43758.5453;return i-Math.floor(i)}static LANCET_BAY_M=6;static LANCET_TIER_M=10;static build(e,t,i,s=!0,n=0,r,a=Ne.FLOOR_M){const o=[],c=[],h=[],d=e/2,u=t/2,p=r==="lancet",f=Math.max(1,Math.round(i/(p?pp.LANCET_TIER_M:Math.max(a,1)))),m=i/f,v=p?pp.LANCET_BAY_M:Ne.BAY_M,g=(y,M,x,E)=>{const S=Math.max(1,Math.round(x/v)),A=x/S;for(let T=0;T<f;T++)for(let _=0;_<S;_++){const k=E&&T===0&&_===Math.floor((S-1)/2),L=s?p?(f-1-T)%2===0?Ne.LANCET:Ne.PLAIN:k?Ne.GROUND_DOOR:r==="tall"?Ne.TALL:T>0?Ne.UPPER:Ne.GROUND_WINDOW:Ne.PLAIN,P=L===Ne.UPPER||L===Ne.GROUND_WINDOW||L===Ne.TALL?pp.hash(n,o.length):2;for(let Le=0;Le<6;Le++)h.push(P);const C=y[0]+M[0]*A*_,N=y[1]+M[1]*A*_,F=C+M[0]*A,H=N+M[1]*A,j=T*m,W=j+m,J=L/Ne.TILES+.002,re=(L+1)/Ne.TILES-.002;o.push(C,j,N,F,j,H,F,W,H,C,j,N,F,W,H,C,W,N),c.push(J,.002,re,.002,re,.998,J,.002,re,.998,J,.998)}};g([d,-u],[-1,0],e,!0),g([-d,u],[1,0],e,!1),g([-d,-u],[0,1],t,!1),g([d,u],[0,-1],t,!1);const b=Ne.PLAIN/Ne.TILES+.01;o.push(-d,i,-u,-d,i,u,d,i,u,-d,i,-u,d,i,u,d,i,-u);for(let y=0;y<6;y++)c.push(b,.5),h.push(2);const w=new Tt;return w.setAttribute("position",new wt(o,3)),w.setAttribute("uv",new wt(c,2)),w.setAttribute("litRank",new wt(h,1)),w.computeVertexNormals(),w}}class Bc{constructor(e,t={}){this.size=e,this.structure=t}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const e=this.structure.strands;return!e||e.length===0?[{heightM:this.size.heightM,acrossM:0}]:e.map(t=>({heightM:t.heightM,acrossM:t.acrossM??0}))}get poleStations(){const e=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[e];case"end":return[-e];case"none":return[];default:return[-e,e]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(e=>e.heightM))+Bc.POLE_ABOVE_M}build(){const e=this.structure.diameterM??Bc.DEFAULT_DIAMETER_M,t=this.strands.map(s=>{const n=new Bn(e/2,e/2,this.size.lengthM,6);return n.rotateX(Math.PI/2),n.translate(s.acrossM,s.heightM,0),n}),i=this.poleStations.map(s=>{const n=new Bn(Bc.POLE_RADIUS_M*.8,Bc.POLE_RADIUS_M,this.poleHeightM,8);return n.translate(0,this.poleHeightM/2,s),n});return{strands:t,poles:i}}}class Ps{static TILE_M=2.4;static COLUMNS=6;static COURSES=10;static SIZE_PX=256;static FOUNDATION_M=.8;static pattern;static build(e){const t=new ii,i=e.sizeM?.widthM??.6,s=e.sizeM?.heightM??1,n=e.sizeM?.lengthM??10,r=s+Ps.FOUNDATION_M,a=new Ss(i,r,n);Ps.layStones(a,i,r,n);const o=new ta({map:Ps.texture()}),c=new Me(a,o);return c.position.y=(s-Ps.FOUNDATION_M)/2,c.castShadow=!0,c.receiveShadow=!0,c.userData={emissive:!1},t.add(c),t}static layStones(e,t,i,s){const n=e.getAttribute("uv");[[s,i],[s,i],[t,s],[t,s],[t,i],[t,i]].forEach(([a,o],c)=>{for(let h=c*4;h<c*4+4;h++)n.setXY(h,n.getX(h)*a/Ps.TILE_M,n.getY(h)*o/Ps.TILE_M)}),n.needsUpdate=!0}static texture(){if(Ps.pattern)return Ps.pattern;const e=Ps.SIZE_PX,t=new Uint8Array(e*e*4),i=Ps.seeds();for(let n=0;n<e;n++)for(let r=0;r<e;r++){const a=r/e,o=n/e;let c=1/0,h=1/0,d=i[0];for(const b of i)for(let w=-1;w<=1;w++)for(let y=-1;y<=1;y++){const M=(a-(b.x+w))*Ps.COLUMNS,x=(o-(b.y+y))*Ps.COURSES*.5,E=.8*Math.max(Math.abs(M),Math.abs(x))+.2*Math.hypot(M,x);E<c?(h=c,c=E,d=b):E<h&&(h=E)}const u=h-c,p=Math.min(u/.1,1),f=.8+.2*Math.min(u/.5,1),m=.94+.12*Ps.noise(r,n),v=(.15+(d.tone-.15)*p)*(p>.999?f*m:1),g=(n*e+r)*4;t[g]=Math.round(255*v*d.warm),t[g+1]=Math.round(255*v),t[g+2]=Math.round(255*v*d.cool),t[g+3]=255}const s=new nr(t,e,e,xs);return s.wrapS=s.wrapT=sc,s.colorSpace=an,s.magFilter=St,s.minFilter=Nr,s.generateMipmaps=!0,s.anisotropy=4,s.needsUpdate=!0,Ps.pattern=s,s}static seeds(){let e=20260831;const t=()=>(e=e*1664525+1013904223>>>0,e/4294967296),i=[];for(let s=0;s<Ps.COURSES;s++)for(let n=0;n<Ps.COLUMNS;n++){const r=.34+t()*.24;i.push({x:(n+s%2*.5+.5+(t()-.5)*.35)/Ps.COLUMNS,y:(s+.5+(t()-.5)*.3)/Ps.COURSES,tone:r,warm:1+t()*.1,cool:.9+t()*.1})}return i}static noise(e,t){const i=Math.sin(e*12.9898+t*78.233)*43758.5453;return i-Math.floor(i)}}class kt{static HEAD_WIDTH_M=.34;static HEAD_DEPTH_M=.24;static HEAD_MARGIN_M=.18;static POLE_RADIUS_M=.055;static HOUSING=[.05,.05,.05];static POLE=[.16,.17,.17];static BAND_M=.5;static BAND_GAP_M=.5;static KERB_CLEAR_M=.25;static CROSSING_LIFT_M=.08;static PAINT=[.8,.8,.78];static SIGN_POLE_RADIUS_M=.03;static SIGN_CENTRE_Y_M=2.55;static SIGN_METAL=[.48,.49,.5];static SIGN_RED=[.62,.05,.05];static SIGN_WHITE=[.82,.82,.8];static trafficLight(e){const t=e?2:3,i=e?gt.PEDESTRIAN_HEAD_Y_M:gt.VEHICLE_HEAD_Y_M,s=gt.LENS_SPACING_M,n=(t-1)*s+2*kt.HEAD_MARGIN_M,r=i-n/2+.05,a=[kt.part(new Bn(kt.POLE_RADIUS_M,kt.POLE_RADIUS_M,r,8),kt.POLE,0,r/2,0),kt.part(new Ss(kt.HEAD_WIDTH_M,n,kt.HEAD_DEPTH_M),kt.HOUSING,0,i,0)];for(let o=0;o<t;o++){const c=i+((t-1)/2-o)*s;a.push(kt.part(new Ss(.26,.02,.16),kt.HOUSING,0,c+.12,-.2))}return kt.group(a)}static crossing(e,t){const i=kt.BAND_M,s=i+kt.BAND_GAP_M,n=Math.max(i,e-2*kt.KERB_CLEAR_M),r=Math.max(1,Math.floor((n+kt.BAND_GAP_M)/s)),a=-((r-1)*s)/2,o=[],c=[],h=kt.CROSSING_LIFT_M,d=t/2;for(let v=0;v<r;v++){const g=a+v*s-i/2,b=g+i;o.push(g,h,d,b,h,d,b,h,-d,g,h,d,b,h,-d,g,h,-d);for(let w=0;w<6;w++)c.push(0,1,0)}const u=new Tt;u.setAttribute("position",new wt(o,3)),u.setAttribute("normal",new wt(c,3));const p=new ta({color:16777215});p.color.setRGB(...kt.PAINT),p.polygonOffset=!0,p.polygonOffsetFactor=-4,p.polygonOffsetUnits=-4;const f=new Me(u,p);f.userData={emissive:!1},f.receiveShadow=!0,f.castShadow=!1;const m=new ii;return m.add(f),m}static drape(e,t){e.traverse(i=>{const s=i;if(!s.isMesh)return;const n=s.geometry.getAttribute("position"),r=s.userData.crossingRest??=Float32Array.from(n.array);for(let a=0;a<n.count;a++)n.setY(a,r[a*3+1]+t(r[a*3],r[a*3+2]));n.needsUpdate=!0,s.geometry.computeBoundingSphere(),s.geometry.computeBoundingBox()})}static roadSign(e){const t=kt.SIGN_CENTRE_Y_M,i=e?.face??"other",[s,n,r]=i==="stop"?[.38,8,Math.PI/8]:i==="give-way"?[.52,3,0]:i==="speed-limit"?[.325,24,0]:[0,0,0],a=t+(i==="other"?.3:s),o=kt.SIGN_POLE_RADIUS_M,c=[kt.part(new Bn(o,o,a,6),kt.SIGN_METAL,0,a/2,0)],h=(d,u,p,f)=>{const m=new Bn(d,d,u,n,1,!1,r);m.rotateX(Math.PI/2),c.push(kt.part(m,f,0,t,-p))};if(i==="other")c.push(kt.part(new Ss(.6,.6,.012),kt.SIGN_METAL,0,t,-.038)),c.push(kt.part(new Ss(.58,.58,.004),kt.SIGN_WHITE,0,t,-.047));else{h(s,.012,o+.008,kt.SIGN_METAL);const[d,u,p]=i==="stop"?[kt.SIGN_WHITE,kt.SIGN_RED,.92]:[kt.SIGN_RED,kt.SIGN_WHITE,i==="give-way"?.68:.77];h(s*.99,.004,o+.017,d),h(s*p,.003,o+.0205,u)}return kt.group(c)}static pedestrianFigure(e,t){const i=e==="standing"?[[-.17,.25],[.17,.25],[.17,-.08],[.1,-.08],[.1,-.5],[.02,-.5],[.02,-.12],[-.02,-.12],[-.02,-.5],[-.1,-.5],[-.1,-.08],[-.17,-.08]]:[[-.05,.26],[-.09,.22],[-.24,.05],[-.19,.01],[-.07,.13],[-.07,0],[-.18,-.22],[-.29,-.47],[-.22,-.5],[-.1,-.25],[-.01,-.07],[.09,-.27],[.13,-.5],[.21,-.48],[.16,-.24],[.07,0],[.07,.11],[.2,0],[.24,.05],[.08,.22],[.05,.26]],s=new gy(i.map(([a,o])=>new ie(a,o))),n=new gy;n.absarc(e==="standing"?0:-.02,.38,.1,0,2*Math.PI,!1);const r=new zw([s,n],6);return r.scale(t,t,t),r.rotateY(Math.PI),r}static part(e,t,i,s,n){return{geometry:e,color:t,matrix:new qe().makeTranslation(i,s,n)}}static group(e){const t=[],i=[],s=[];for(const{geometry:o,color:c,matrix:h}of e){const d=o.index?o.toNonIndexed():o;d.applyMatrix4(h);const u=d.getAttribute("position"),p=d.getAttribute("normal");for(let f=0;f<u.count;f++)t.push(u.getX(f),u.getY(f),u.getZ(f)),i.push(p.getX(f),p.getY(f),p.getZ(f)),s.push(...c);d!==o&&d.dispose(),o.dispose()}const n=new Tt;n.setAttribute("position",new wt(t,3)),n.setAttribute("normal",new wt(i,3)),n.setAttribute("color",new wt(s,3));const r=new Me(n,new ta({color:16777215,vertexColors:!0}));r.userData={emissive:!1},r.castShadow=!0,r.receiveShadow=!0;const a=new ii;return a.add(r),a}}class Bd{static MIN_K=1667;static MAX_K=25e3;static ofTemperature(e){const t=Math.min(Bd.MAX_K,Math.max(Bd.MIN_K,e)),i=t<=4e3?-266123900/t**3-234358.9/t**2+877.6956/t+.17991:-3025846900/t**3+21070379e-1/t**2+222.6347/t+.24039,s=t<=2222?-1.1063814*i**3-1.3481102*i**2+2.18555832*i-.20219683:t<=4e3?-.9549476*i**3-1.37418593*i**2+2.09137015*i-.16748867:3.081758*i**3-5.8733867*i**2+3.75112997*i-.37001483,n=i/s,r=(1-i-s)/s,a=[3.2406*n-1.5372-.4986*r,-.9689*n+1.8758+.0415*r,.0557*n-.204+1.057*r].map(c=>Math.max(0,c)),o=.2126*a[0]+.7152*a[1]+.0722*a[2];return[a[0]/o,a[1]/o,a[2]/o]}}const h1=Math.PI/180;function li(l,e,t,i,s=!1,n){const r=s&&n?new ta({color:new oe(...n),emissive:new oe(...t)}):s?new ir({color:new oe(...t)}):new ta({color:new oe(...t)}),a=new Me(e,r);return a.position.y=i,a.userData={emissive:s},a.castShadow=!s,a.receiveShadow=!s,l.add(a),a}const d1=.25,R8=.002,C8=100,VE=3e4,L8=1500,O8=.25,P8=1e3,N8=.15;function F8(l){const e=/^#([0-9a-f]{6})$/i.exec(l);if(!e)return[1,1,1];const t=parseInt(e[1],16),i=s=>{const n=s/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4};return[i(t>>16&255),i(t>>8&255),i(t&255)]}const U8=[.62,.62,.6],B8=[1,.85,.5],z8=[.25,.25,.25],sI=[1,.97,.85],H8=[.55,.68,.72],G8=.12,Xa=.03,Ya=.05,nI={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function Xn(l,e){return l?.[e]}function qa(l,e,t,i,s,n,r,a){if(a===void 0)return;const o=new ir({color:new oe(...H8).multiplyScalar(G8),transparent:!0,opacity:a/100,depthWrite:!1}),c=new Me(new Ss(e,t,i),o);c.position.set(s,n,r),c.renderOrder=2,l.add(c)}const Wr=.05,u1=[.6,.58,.53],WE=[.5,.5,.48];function md(l,e,t,i,s,n,r,a){const o=new ta({color:new oe(...a),side:Ji}),c=new Me(new Ss(e,t,i),o);c.position.set(s,n,r),l.add(c)}function V8(l,e,t,i,s,n,r,a,o){const c=(i-n)/2,h=(f,m,v,g)=>{f<=0||(e?md(l,f,m,Wr,v,a+g,r,o):md(l,Wr,m,f,r,a+g,v,o))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...s].sort((f,m)=>f.center-m.center);let u=-t/2;for(const f of d){const v=f.center-f.main/2-u;h(v,n,u+v/2,0),u=f.center+f.main/2}const p=t/2-u;h(p,n,u+p/2,0)}function rI(l,e,t,i,s,n,r,a,o,c){const h=(i+s)/2,d=s-i,u=(p,f,m,v)=>{p.length===0?f?md(l,m,d,Wr,0,h,v,u1):md(l,Wr,d,m,v,h,0,u1):V8(l,f,m,d,p,n,v,h,u1)};u(r,!0,e*2,-t+Wr),u(a,!0,e*2,t-Wr),u(o,!1,t*2,-e+Wr),u(c,!1,t*2,e-Wr),md(l,e*2,Wr,t*2,0,i+Wr,0,WE),md(l,e*2,Wr,t*2,0,s-Wr,0,WE)}function ky(l,e,t,i){switch(l){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-Za};case"front-right":return{x:e-i,z:-Za};case"behind-left":return{x:-(e-i),z:Za};case"behind-right":return{x:e-i,z:Za}}}function aI(l,e,t,i,s,n,r,a){const o=Ly();o.scale.setScalar(s),o.rotation.y=nI[t];const{x:c,z:h}=ky(e,n,r,a);o.position.set(c,i,h),l.add(o)}const Ry=6,Cy=6,ja=3,Ru=1.4,Cu=ja*.5,oI=1.2,lI=.35,W8=.75,$8=1.6;function $E(l,e,t,i,s){const n=new ii,r=Math.max(1,l+1),a=r*ja;li(n,new Ss(Ry,a,Cy),[.55,.54,.5],a/2);const o=Ry/2,c=Cy/2;for(let h=0;h<r;h++){const d=h*ja+ja/2;qa(n,Ru,Cu,Ya,0,d,-c-Xa,Xn(e,"front")),qa(n,Ru,Cu,Ya,0,d,c+Xa,Xn(e,"behind")),qa(n,Ya,Cu,Ru,-o-Xa,d,0,Xn(e,"left")),qa(n,Ya,Cu,Ru,o+Xa,d,0,Xn(e,"right"))}if(t){const h=Math.min(Math.max(i??0,0),r-1);aI(n,t,s??t,h*ja,.72,o,c,oI);const d=u=>Xn(e,u)!==void 0?[{main:Ru,center:0}]:[];rI(n,o,c,h*ja,(h+1)*ja,Cu,d("front"),d("behind"),d("left"),d("right"))}return n}function KE(){const l=new ii,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,s,n]of e){const r=new Rs(s,10,7);r.scale(1,.85,1),r.translate(t,0,i),li(l,r,[.26,.28,.17],n)}return l}function K8(l){const e=new ii,t=new Ui(ue.sizeOf(l),l.bridge).build();li(e,t.concrete,[.6,.6,.58],0);const i=li(e,t.road,[.2,.2,.21],0),s=li(e,t.earth,[.3,.36,.22],0);for(const n of[i,s])n.material.side=$s;return li(e,t.railing,[.5,.52,.55],0),e}function X8(l){const e=new ii,t=new Bc(ue.sizeOf(l),l.wire).build();for(const i of t.strands)li(e,i,[.1,.1,.11],0);for(const i of t.poles)li(e,i,[.3,.24,.18],0);return e}function XE(){const l=new ii;return li(l,new Bn(.15,.22,2,8),[.32,.22,.14],1),li(l,new lu(1.4,3,8),[.16,.32,.14],3.5),l}const YE=.275,Y8=.35,q8=.9,j8=34,Z8=8,J8=1.4;function qE(){const l=new ii,e=new Rs(YE,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,Y8/YE,1);const t=ue.repeatOnGrid(e,j8,q8,Z8,J8),i=li(l,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),l}function jE(){const l=new ii,e=new Rs(1,7,3,0,Math.PI*2,0,Math.PI/2);return li(l,e,[.38,.36,.32],0),l}const Q8=[.24,.22,.18],e9=[.14,.17,.08];function t9(){const l=new ii,e=li(l,new Ss(1,1,1),Q8,.5),t=li(l,new Ss(1,.03,1),e9,1.015);for(const i of[e,t])i.material.side=$s;return t.castShadow=!1,Ud.install(t.material,!0),l}function ZE(l,e,t){const i=new ii;e!=="wall"&&li(i,new Bn(.05,.08,5,8),[.28,.28,.3],2.5);const s=li(i,new Rs(.25,12,8),l?ue.lampHue(t):[0,0,0],5.1,!0,U8);return tI.applyOpaque(s.material),i}const i9=[.08,.08,.08],vl=.8,Jh=1,Ca=1.7,p1=.6,mc=.46,ym=1.5,Uh=.8,Za=.5,s9=Ca;function JE(l,e,t,i){const s=new ii;li(s,new Ss(1.8,1.4,4.2),[.45,.14,.14],.7),li(s,new Ss(vl*2,p1,Jh*2),[.4,.12,.12],Ca);for(const r of[-1.4,1.4])for(const a of[-.95,.95]){const o=li(s,new Bn(.4,.4,.3,12),i9,.4);o.rotation.z=Math.PI/2,o.position.x=a,o.position.z=r}const n=l?sI:[0,0,0];for(const r of[-.7,.7])li(s,new Rs(.15,8,6),n,.7,!0,z8).position.set(r,.7,-2.1);if(qa(s,ym,mc,Ya,0,Ca,-Jh-Xa,Xn(e,"front")),qa(s,ym,mc,Ya,0,Ca,Jh+Xa,Xn(e,"behind")),qa(s,Ya,mc,Uh,-vl-Xa,Ca,-Za,Xn(e,"front-left")),qa(s,Ya,mc,Uh,-vl-Xa,Ca,Za,Xn(e,"behind-left")),qa(s,Ya,mc,Uh,vl+Xa,Ca,-Za,Xn(e,"front-right")),qa(s,Ya,mc,Uh,vl+Xa,Ca,Za,Xn(e,"behind-right")),t){aI(s,t,i??t,W8,.5,vl,Jh,lI);const r=(c,h)=>{const d=[];return Xn(e,c)!==void 0&&d.push({main:Uh,center:-Za}),Xn(e,h)!==void 0&&d.push({main:Uh,center:Za}),d},a=Xn(e,"front")!==void 0?[{main:ym,center:0}]:[],o=Xn(e,"behind")!==void 0?[{main:ym,center:0}]:[];rI(s,vl,Jh,Ca-p1/2,Ca+p1/2,mc,a,o,r("front-left","behind-left"),r("front-right","behind-right"))}return s}const QE=new Map;function e2(l,e){if(!l)return;const t=[[l.lengthM,e.lengthM],[l.heightM,e.heightM],[l.widthM,e.widthM]];for(const[i,s]of t)if(i!==void 0&&s>1e-6)return i/s}function f1(l,e){return e>1e-6?l/e:1}const cI=[.95,.9,.82],t2=[.72,.74,.78];function i2(){const l=new ii;li(l,new Bn(.25,.3,1.5,10),t2,.75),li(l,new Rs(.26,10,8),t2,1.74);const e=li(l,new lu(.07,.16,8),cI,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,l}function Ly(){const l=new ii;li(l,new Bn(.25,.3,1.5,10),[.3,.3,.35],.75),li(l,new Rs(.22,10,8),[.62,.52,.46],1.72);const e=li(l,new lu(.07,.16,8),cI,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,l}const n9=17,s2=18.5,m1=[.16,.16,.18];function n2(){const l=new ii,e=li(l,new Bn(1.8,1.8,s2*2,10),m1,0);e.rotation.x=Math.PI/2,li(l,new Ss(n9*2,.5,4.5),m1,0);const t=li(l,new Ss(.4,5.5,4),m1,3);return t.position.z=-s2+2,l}class ue{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace","wall","building","bridge"]);static groundUnderFootprint(e,t,i,s,n,r=0){const a=ue.sizeOf(e);if(r>a.heightM)return n(t,i);const o=(s??0)*Math.PI/180,c=e.kind==="bridge"?Math.min(a.lengthM,e.bridge?.spanM??a.lengthM):a.lengthM,h=Math.min(21,Math.max(2,Math.ceil(c/.75)+1)),d=Math.min(21,Math.max(2,Math.ceil(a.widthM/.75)+1)),u=ue.GROWS_FROM_GROUND.has(e.kind);let p=u?1/0:-1/0;for(let f=0;f<h;f++){const m=(f/(h-1)-.5)*c;for(let v=0;v<d;v++){const g=(v/(d-1)-.5)*a.widthM,b=t+Math.sin(o)*m+Math.cos(o)*g,w=i-Math.cos(o)*m+Math.sin(o)*g;p=u?Math.min(p,n(b,w)):Math.max(p,n(b,w))}}return Number.isFinite(p)?p:n(t,i)}static wireGround(e,t,i,s,n){const r=ue.sizeOf(e).lengthM/2,a=(s??0)*Math.PI/180,o=n(t+Math.sin(a)*r,i-Math.cos(a)*r),c=n(t-Math.sin(a)*r,i+Math.cos(a)*r);return{startY:c,dropM:o-c}}static shearWire(e,t,i){t<=0||e.traverse(s=>{const n=s;if(!n.isMesh)return;const r=n.geometry.getAttribute("position"),a=n.userData.wireRest??=Float32Array.from(r.array);for(let o=0;o<r.count;o++){const c=.5-a[o*3+2]/t;r.setY(o,a[o*3+1]+i*c)}r.needsUpdate=!0,n.geometry.computeBoundingSphere(),n.geometry.computeBoundingBox()})}static occupantView(e,t=e.headingDeg){const i=e.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:s,z:n}=e.kind==="vehicle"?ky(i,vl,Jh,lI):ky(i,Ry/2,Cy/2,oI),r=e.kind==="vehicle"?s9:(e.occupiedFloor??0)*ja+$8,a=(t??0)-nI[e.observerFacing??i]/h1,o=this.scaleFor(e);return{x:s*o.x,z:n*o.z,eyeY:r*o.y,headingDeg:a}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName(ue.BODY_NAME)??e}static repeatOnGrid(e,t,i,s,n){const r=e.getAttribute("position"),a=e.getAttribute("normal"),o=e.getIndex();if(!o)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*s,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),p=new Uint32Array(o.count*h),f=-((t-1)*i)/2,m=-((s-1)*n)/2;let v=0;for(let b=0;b<s;b++)for(let w=0;w<t;w++,v++){const y=m+b*n,M=f+w*i;for(let x=0;x<c;x++){const E=(v*c+x)*3;d[E]=r.getX(x)+y,d[E+1]=r.getY(x),d[E+2]=r.getZ(x)+M,u[E]=a.getX(x),u[E+1]=a.getY(x),u[E+2]=a.getZ(x)}for(let x=0;x<o.count;x++)p[v*o.count+x]=o.getX(x)+v*c}const g=new Tt;return g.setAttribute("position",new wt(d,3)),g.setAttribute("normal",new wt(u,3)),g.setIndex(new Nw(p,1)),g}static fitTerrace(e,t,i){const s=ue.sizeOf(t),n=s.widthM/2,r=s.lengthM/2,a=i(0,0)+s.heightM,o=Math.min(16,Math.max(1,Math.ceil(s.lengthM/3))),c=ue.bodyOf(e).children.filter(y=>y.isMesh);if(c.length<2)return a;const h=Math.min(10,s.widthM/4),d=[-n];for(const y of[.25,.5,.75,1])d.push(-n+h*y);const u=Math.max(1,Math.ceil((s.widthM-2*h)/3));for(let y=1;y<u;y++)d.push(-n+h+(s.widthM-2*h)*y/u);for(const y of[1,.75,.5,.25,0])d.push(n-h*y);const p=y=>-r+s.lengthM*y/o,f=.8,m=(y,M)=>{const x=Math.min(1,Math.max(0,(n-Math.abs(y))/h)),E=x*x*(3-2*x);return E*a+(1-E)*Math.min(a,i(y,M))},v=[],g=(y,M)=>{const x=i(y[0],y[1])-f,E=i(M[0],M[1])-f,S=Math.max(m(y[0],y[1]),x),A=Math.max(m(M[0],M[1]),E);v.push(y[0],x,y[1],M[0],E,M[1],y[0],S,y[1]),v.push(M[0],E,M[1],M[0],A,M[1],y[0],S,y[1])};for(let y=0;y<d.length-1;y++)g([d[y],-r],[d[y+1],-r]),g([d[y],r],[d[y+1],r]);const b=[];for(let y=0;y<d.length-1;y++)for(let M=0;M<o;M++){const x=[d[y],p(M)],E=[d[y+1],p(M)],S=[d[y],p(M+1)],A=[d[y+1],p(M+1)];for(const[T,_,k]of[[x,S,E],[E,S,A]])for(const L of[T,_,k])b.push(L[0],m(L[0],L[1]),L[1])}const w=(y,M)=>{const x=new Tt;x.setAttribute("position",new wt(M,3)),x.computeVertexNormals(),y.geometry.dispose(),y.geometry=x,y.position.y=0};return w(c[0],v),w(c[1],b),a}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(s=>{const n=s,r=n.userData.cropBasePositions,a=n.userData.cropVerticesPerClump;if(!n.isMesh||!r||!a)return;const o=n.geometry.getAttribute("position"),c=new qe().copy(n.matrixWorld).invert();for(let h=0;h<o.count;h+=a){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(n.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(c);for(let d=h;d<h+a;d++)o.setY(d,r[d*3+1]+i.y)}o.needsUpdate=!0,n.geometry.computeBoundingBox(),n.geometry.computeBoundingSphere()})}static applyModelParameters(e,t,i){if(!(!t||!i))for(const[s,n]of Object.entries(i)){const r=t[s];if("materials"in n)typeof r=="string"&&ue.tint(e,n.materials,r);else if(typeof r=="boolean"){const a=n.nodes.map(c=>new RegExp(c)),o=r===(n.hideWhen??!0);e.traverse(c=>{a.some(h=>h.test(c.name))&&(c.visible=!o)})}}}static tint(e,t,i){const s=t.map(n=>new RegExp(n));e.traverse(n=>{const r=n;if(!r.isMesh)return;const a=r.userData.tintedMaterials??[],o=c=>{if(!c.color||!s.some(p=>p.test(c.name)))return c;const d=c.clone();d.color.set(i);const u=d.emissive?Math.max(d.emissive.r,d.emissive.g,d.emissive.b):0;return u>0&&(d.emissive.multiply(d.color),d.emissive.multiplyScalar(u/(Math.max(d.emissive.r,d.emissive.g,d.emissive.b)||1))),a.push(d),d};r.material=Array.isArray(r.material)?r.material.map(o):o(r.material),a.length>0&&(r.userData.tintedMaterials=a)})}static paint(e,t){e.traverse(i=>{const s=i,n=s.userData;if(!s.isMesh||n?.emissive)return;const r=s.material;r?.color&&r.color.set(t)})}static addRoof(e,t){const i=Ki.normalised(t.roof),s=ue.sizeOf(t),n=t.sizeM?.heightM===void 0?s.heightM:ue.wallHeightOf(t,s.heightM),r=ue.roofColor(i.color),a=Ki.build(i,s.widthM,s.lengthM);t.roof.material==="stone"&&$r.layOn(a);const o=li(e,a,r,n),c=o.material;c.side=$s,t.roof.material==="stone"&&(c.map=$r.texture(),c.bumpMap=c.map,c.bumpScale=ue.STONE_BUMP),o.name=ue.ROOF_NAME}static wallHeightOf(e,t){return Math.min(t,Math.max(ja,t-(e.roof?Ki.normalised(e.roof).riseM:0)))}static roofColor(e){const t=/^#([0-9a-f]{6})$/i.exec(e??"")?.[1];if(!t)return[.45,.25,.2];const i=new oe(`#${t}`);return[i.r,i.g,i.b]}static ROOF_NAME="decor-roof";static STONE_BUMP=2;static PLASTER="#d3cab8";static hasFacade(e){return e.kind==="building"&&ue.facadeOf(e)!==void 0&&!e.observerSide&&e.sizeM?.widthM!==void 0&&e.sizeM.lengthM!==void 0&&e.sizeM.heightM!==void 0}static facadeOf(e){if(e.kind!=="building"||e.facade?.openings==="none")return;if(e.facade)return e.facade;const t=e.sizeM?.heightM;return t===void 0?void 0:t-(e.roof?Ki.normalised(e.roof).riseM:0)>=ja?ue.HOUSE_FACADE:void 0}static isBare(e){return e.openings==="plain"||e.plain===!0}static HOUSE_FACADE={};static buildFacade(e){const t=new ii,i=ue.sizeOf(e),s=ue.facadeOf(e),n=s.openings==="tall"||s.openings==="lancet"?s.openings:void 0,r=pp.build(i.widthM,i.lengthM,ue.wallHeightOf(e,i.heightM),!ue.isBare(s),e.eastM*7.31+e.northM*3.17,n,s.storeyM);if(s.closedAtNight){const c=r.getAttribute("litRank");for(let h=0;h<c.count;h++)c.setX(h,c.getX(h)/ue.CLOSED_AT_NIGHT_SHARE)}const a=new ta({color:new oe(s.color??ue.PLASTER),map:Ne.texture(),emissiveMap:Ne.emissive(),emissive:new oe(1,1,1)});a.onBeforeCompile=c=>{c.uniforms.uLitShare=ue.litWindowShare,c.uniforms.uWindowLuminance=ue.windowLuminance,c.vertexShader=`attribute float litRank;
|
|
10941
|
+
`,transparent:!0,blending:qs,depthWrite:!1,side:Ji,fog:!1}),this.object=new Me(new Rs(gs.RADIUS,64,32),this.material),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1;const i=this.material.uniforms;this.deckUniforms={uSource:i.uSource,uUp:i.uUp,uStrength:i.uStrength,uTint:i.uTint,uMap:i.uMap,uGain:i.uGain,uHaloShown:{value:0}}}deckUniforms;shown=!1;hostedByDeck=!1;set hosted(e){this.hostedByDeck=e,this.show(this.shown)}show(e){this.shown=e,this.object.visible=e&&!this.hostedByDeck,this.deckUniforms.uHaloShown.value=e?1:0}get awaitingFirstDisplay(){return this.tracing&&!this.everDisplayed}setUrgent(e){this.urgent=e}set onReady(e){this.onRepaint=e}update(e,t,i,s,n,r,a=si.DEFAULT_RARE_SHARE){const o=this.material.uniforms;if(i<=0){o.uStrength.value=0,this.show(!1),this.stopWork();return}o.uSource.value.set(e.x,e.y,e.z).normalize(),o.uStrength.value=i,o.uTint.value.set(s[0],s[1],s[2]),o.uIceCover.value=n.cover,o.uIceHeight.value=n.layerHeight,this.show(this.everDisplayed),this.requestMap(t,r,a)}featureAt(e){const t=this.material.uniforms;if(!this.everDisplayed||!(t.uStrength.value>0)||this.mappedAltitudeDeg!==this.mappedAltitudeDeg)return;const i=t.uUp.value.clone().normalize(),s=t.uSource.value.clone().normalize(),n=Math.PI/180,r=Math.asin(Math.max(-1,Math.min(1,e.dot(i))))/n,a=Math.asin(Math.max(-1,Math.min(1,s.dot(i))))/n,o=v=>v.clone().sub(i.clone().multiplyScalar(v.dot(i))),c=o(s),h=o(e),d=c.length()<1e-4||h.length()<1e-4?0:Math.acos(Math.max(-1,Math.min(1,c.dot(h)/(c.length()*h.length()))))/n,u=si.AZIMUTH_BINS,p=si.ALTITUDE_BINS,f=this.texels,m=(v,g)=>{if(v<-90||v>90)return 0;const b=Math.min(u-1,Math.max(0,Math.floor(Math.min(180,Math.abs(g))/180*u))),w=Math.min(p-1,Math.max(0,Math.floor((v+90)/180*p)));return gs.halfToFloat(f[(w*u+b)*4+1])};return fd.at(a,r,d,m)}static halfToFloat(e){const t=e>>10&31,i=e&1023,s=e>>15?-1:1;return t===0?s*i*5960464477539063e-23:s*2**(t-15)*(1+i/1024)}requestMap(e,t,i){if(!(!(Math.abs(e-this.mappedAltitudeDeg)<gs.ALTITUDE_STEP_DEG)||!(Math.abs(t-this.mappedAlignment)<gs.ALIGNMENT_STEP)||!(Math.abs(i-this.mappedRare)<gs.ALIGNMENT_STEP))){this.next=void 0;return}if(this.tracing){if(this.tracingFor(e,t,i)){this.next=void 0;return}if(!(!(Math.abs(e-this.pendingAltitudeDeg)<gs.LEAP_ALTITUDE_DEG)||!(Math.abs(t-this.pendingAlignment)<gs.LEAP_ALIGNMENT)||!(Math.abs(i-this.pendingRare)<gs.LEAP_ALIGNMENT))){this.next={sourceAltitudeDeg:e,alignment:t,rare:i};return}}this.next=void 0,this.pendingAltitudeDeg=e,this.pendingAlignment=t,this.pendingRare=i,this.stopWork(),this.tracing=!0,this.startTracing(e,t,i)}startTracing(e,t,i){const s=++this.ticket,n=()=>{s!==this.ticket||!this.tracing||(this.sky.begin(e,t,void 0,si.populationsFor(i)),this.scheduleWork())};Ll.with(r=>{s!==this.ticket||!this.tracing||(this.job=r.trace(e,t,i,gs.RAYS,a=>{this.job=void 0,this.texels.set(a),this.display(),this.finishTracing()},n))},n)}ticket=0;job;pendingAltitudeDeg=Number.NaN;pendingAlignment=Number.NaN;pendingRare=Number.NaN;next;tracingFor(e,t,i){return this.tracing&&Math.abs(e-this.pendingAltitudeDeg)<gs.ALTITUDE_STEP_DEG&&Math.abs(t-this.pendingAlignment)<gs.ALIGNMENT_STEP&&Math.abs(i-this.pendingRare)<gs.ALIGNMENT_STEP}scheduleWork(){if(this.workHandle!==void 0)return;const e=()=>{if(this.workHandle=void 0,!this.tracing)return;const t=performance.now(),i=this.urgent?gs.URGENT_BUDGET_MS:gs.BUDGET_MS;do this.sky.trace(gs.RAYS_PER_BATCH);while(this.sky.tracedRays<gs.RAYS&&performance.now()-t<i);if(this.sky.tracedRays>=gs.RAYS){this.publish(),this.finishTracing();return}this.workHandle=requestAnimationFrame(e)};this.workHandle=requestAnimationFrame(e)}finishTracing(){this.tracing=!1,this.mappedAltitudeDeg=this.pendingAltitudeDeg,this.mappedAlignment=this.pendingAlignment,this.mappedRare=this.pendingRare;const e=this.next;e&&this.requestMap(e.sourceAltitudeDeg,e.alignment,e.rare)}stopWork(){this.ticket++,this.job?.cancel(),this.job=void 0,this.workHandle!==void 0&&cancelAnimationFrame(this.workHandle),this.workHandle=void 0,this.tracing=!1,this.next=void 0}publish(){k8.fromRadiance(this.sky.harvest().data,this.texels),this.display()}display(){this.texture.needsUpdate=!0,this.everDisplayed=!0,this.show(this.material.uniforms.uStrength.value>0),this.onRepaint?.()}dispose(){this.stopWork(),this.texture.dispose(),this.object.geometry.dispose(),this.material.dispose()}}class Qs{static MAX_CONCURRENT=24;static POINTS=8;static SEGMENTS=Qs.POINTS-1;static ACROSS=3;static VERTICES_PER_SEGMENT=(Qs.ACROSS-1)*6;static RADIUS=840;static MIN_HALF_WIDTH_DEG=.05;static BRIGHT_HALF_WIDTH_DEG=.22;object;positions;colors;meteors=[];heads=[];radiantAltitudeDeg=0;radiantAzimuthDeg=0;constructor(){const e=Qs.MAX_CONCURRENT*Qs.SEGMENTS*Qs.VERTICES_PER_SEGMENT;this.positions=new Float32Array(e*3),this.colors=new Float32Array(e*3);const t=new Tt;t.setAttribute("position",new Et(this.positions,3)),t.setAttribute("color",new Et(this.colors,3)),t.setDrawRange(0,0),this.object=new Me(t,ao.material()),this.object.frustumCulled=!1,ao.track(this.object)}get schedule(){return this.meteors}setShower(e,t,i){this.meteors=e,this.radiantAltitudeDeg=t,this.radiantAzimuthDeg=i}update(e){const t=this.object.geometry;if(this.heads=[],this.meteors.length===0){t.setDrawRange(0,0);return}const i=Yr.aliveAt(this.meteors,e).slice(0,Qs.MAX_CONCURRENT);let s=0;for(const{meteor:n,progress:r}of i){const a=this.radiantOf(n);if(!a)continue;const o=Li(a.altitudeDeg,a.azimuthDeg,1),[c,h]=this.basisAround(o),d=n.fromRadiantDeg+r*n.lengthDeg,u=Math.max(n.fromRadiantDeg,d-n.lengthDeg*.6),p=Math.min(1,(1-r)*2.5),f=this.turn(c,h,n.bearingDeg),m=(.15+.85*n.brightness)*p,v=y=>m*y**1.6,g=y=>this.onSphere(o,f,u+(d-u)*y),b=g(1);p>0&&this.heads.push({...iI(b.x,b.y,b.z),magnitude:Yr.magnitudeOf(n)-2.5*Math.log10(p)});const w=y=>Qs.RADIUS*((Qs.MIN_HALF_WIDTH_DEG+Qs.BRIGHT_HALF_WIDTH_DEG*n.brightness*y)*Math.PI/180);for(let y=1;y<Qs.POINTS;y++){const M=(y-1)/Qs.SEGMENTS,x=y/Qs.SEGMENTS;s=this.pushRibbon(s,g(M),g(x),w(M),w(x),v(M),v(x))}}t.setDrawRange(0,s),t.getAttribute("position").needsUpdate=!0,t.getAttribute("color").needsUpdate=!0}midpointOf(e){const t=this.radiantOf(e);if(!t)return;const i=Li(t.altitudeDeg,t.azimuthDeg,1),[s,n]=this.basisAround(i),r=this.turn(s,n,e.bearingDeg),a=this.onSphere(i,r,e.fromRadiantDeg+e.lengthDeg/2),o=Math.hypot(a.x,a.y,a.z)||1;return{altitudeDeg:Math.asin(a.y/o)*180/Math.PI,azimuthDeg:(Math.atan2(a.x,-a.z)*180/Math.PI+360)%360}}radiantOf(e){return e.radiant?e.radiant:this.radiantAltitudeDeg>0?{altitudeDeg:this.radiantAltitudeDeg,azimuthDeg:this.radiantAzimuthDeg}:void 0}pushRibbon(e,t,i,s,n,r,a){const o=this.normalise(this.cross(this.normalise(t),this.normalise(this.subtract(i,t))));for(let c=0;c<Qs.ACROSS-1;c++){const h=c-1,d=c,u=this.across(t,o,s,h),p=this.across(i,o,n,h),f=this.across(t,o,s,d),m=this.across(i,o,n,d),v=(g,b)=>g===0?b:0;e=this.push(e,u,v(h,r)),e=this.push(e,p,v(h,a)),e=this.push(e,f,v(d,r)),e=this.push(e,p,v(h,a)),e=this.push(e,m,v(d,a)),e=this.push(e,f,v(d,r))}return e}across(e,t,i,s){return{x:e.x+t.x*i*s,y:e.y+t.y*i*s,z:e.z+t.z*i*s}}push(e,t,i){const s=e*3;this.positions[s]=t.x,this.positions[s+1]=t.y,this.positions[s+2]=t.z;const n=Ve.relativeOfResponse(Math.max(0,Math.min(1,i)));return this.colors[s]=n*.9,this.colors[s+1]=n*.95,this.colors[s+2]=n,e+1}turn(e,t,i){const s=i*Math.PI/180,n=Math.cos(s),r=Math.sin(s);return{x:e.x*n+t.x*r,y:e.y*n+t.y*r,z:e.z*n+t.z*r}}onSphere(e,t,i){const s=i*Math.PI/180,n=Math.cos(s),r=Math.sin(s);return{x:(e.x*n+t.x*r)*Qs.RADIUS,y:(e.y*n+t.y*r)*Qs.RADIUS,z:(e.z*n+t.z*r)*Qs.RADIUS}}basisAround(e){const t=Math.abs(e.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=this.normalise(this.cross(e,t));return[i,this.normalise(this.cross(e,i))]}subtract(e,t){return{x:e.x-t.x,y:e.y-t.y,z:e.z-t.z}}cross(e,t){return{x:e.y*t.z-e.z*t.y,y:e.z*t.x-e.x*t.z,z:e.x*t.y-e.y*t.x}}normalise(e){const t=Math.hypot(e.x,e.y,e.z)||1;return{x:e.x/t,y:e.y/t,z:e.z/t}}dispose(){this.object.geometry.dispose(),this.object.material.dispose()}}class un{static MEDIAN_BEDTIME=22+40/60;static MEDIAN_RISING=7;static BEDTIME_SPREAD_H=1.2;static RISING_SPREAD_H=.7;static ALWAYS_UP=.02;static LIT_WHEN_ALL_UP=.5;static UNKNOWN_HOUR=.16;static DUSK_DEG=-1;static NIGHT_DEG=-9;static awakeAt(e){const t=(e%24+24)%24,i=un.normal(((t<12?t+24:t)-un.MEDIAN_BEDTIME)/un.BEDTIME_SPREAD_H),s=un.normal((t-un.MEDIAN_RISING)/un.RISING_SPREAD_H),n=i*(t<12?1-s:1);return Math.max(un.ALWAYS_UP,1-n)}static shareAt(e){return e===void 0||!Number.isFinite(e)?un.UNKNOWN_HOUR:un.LIT_WHEN_ALL_UP*un.awakeAt(e)}static darknessAt(e){return Math.max(0,Math.min(1,(un.DUSK_DEG-e)/(un.DUSK_DEG-un.NIGHT_DEG)))}static share(e,t){return un.darknessAt(e)*un.shareAt(t)}static normal(e){const t=Math.abs(e)/Math.SQRT2,i=1/(1+.3275911*t),s=1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-t*t);return e>=0?.5*(1+s):.5*(1-s)}}class Ui{constructor(e,t={}){this.size=e,this.span=Math.min(e.lengthM,Math.max(0,t.spanM??e.lengthM)),this.bank=(e.lengthM-this.span)/2,this.deck=Math.min(e.heightM,t.deckThicknessM??Ui.DEFAULT_DECK_THICKNESS_M),this.railHeight=t.railing?.heightM??Ui.DEFAULT_RAILING_HEIGHT_M,this.postSpacing=Math.max(.3,t.railing?.postSpacingM??Ui.DEFAULT_POST_SPACING_M),this.rails=Math.max(0,Math.round(t.railing?.rails??Ui.DEFAULT_RAILS))}static DEFAULT_DECK_THICKNESS_M=1.2;static DEFAULT_RAILING_HEIGHT_M=1.05;static DEFAULT_POST_SPACING_M=1.5;static DEFAULT_RAILS=2;static BANK_SLOPE=1.5;static ABUTMENT_THICKNESS_M=1;static POST_SIDE_M=.08;static RAIL_HEIGHT_M=.08;static RAIL_DEPTH_M=.06;static BANK_STATIONS=12;static NATURAL_SIZE=Object.freeze({widthM:9,lengthM:40,heightM:6.5});span;bank;deck;railHeight;postSpacing;rails;roadAt(e){const t=Math.abs(e)-this.span/2;return t<=0?this.size.heightM:this.bank<=0?0:Math.max(0,this.size.heightM*(1-t/this.bank))}build(){const{widthM:e,heightM:t}=this.size,i=this.span/2,s=[];if(this.span>0){s.push(Ui.box(e,this.deck,this.span,0,t-this.deck/2,0));for(const o of[-1,1]){const c=t-this.deck;c>0&&this.bank>0&&s.push(Ui.box(e+1,c,Ui.ABUTMENT_THICKNESS_M,0,c/2,o*(i-Ui.ABUTMENT_THICKNESS_M/2)))}}const n=[];this.span>0&&n.push(Ui.box(e,.04,this.span,0,t+.02,0));const r=[];for(const o of[-1,1])this.bank<=0||(r.push(this.embankment(o)),n.push(this.bankRoad(o)));const a=[];for(const o of[-1,1])a.push(...this.railing(o*(e/2-Ui.POST_SIDE_M)));return{concrete:Ui.merge(s),road:Ui.merge(n),earth:Ui.merge(r),railing:Ui.merge(a)}}embankment(e){const t=this.size.widthM/2,i=this.stations(e),s=[],n=(c,h,d,u)=>{s.push(c.x,c.y,c.z,h.x,h.y,h.z,d.x,d.y,d.z,c.x,c.y,c.z,d.x,d.y,d.z,u.x,u.y,u.z)},r=c=>{const h=this.roadAt(c),d=t+Ui.BANK_SLOPE*h;return{leftFoot:new D(-d,0,c),leftTop:new D(-t,h,c),rightTop:new D(t,h,c),rightFoot:new D(d,0,c)}};for(let c=1;c<i.length;c++){const h=r(i[c-1]),d=r(i[c]),u=e>0,p=(f,m,v,g)=>u?n(f,m,v,g):n(g,v,m,f);p(h.leftFoot,h.leftTop,d.leftTop,d.leftFoot),p(h.leftTop,h.rightTop,d.rightTop,d.leftTop),p(h.rightTop,h.rightFoot,d.rightFoot,d.rightTop)}const a=r(i[0]);e>0?n(a.leftFoot,a.rightFoot,a.rightTop,a.leftTop):n(a.leftTop,a.rightTop,a.rightFoot,a.leftFoot);const o=new Tt;return o.setAttribute("position",new wt(s,3)),o.computeVertexNormals(),o}bankRoad(e){const t=this.size.widthM/2,i=this.stations(e),s=[];for(let r=1;r<i.length;r++){const a=i[r-1],o=i[r],c=this.roadAt(a)+.02,h=this.roadAt(o)+.02,d=e>0?[[-t,c,a],[t,c,a],[t,h,o],[-t,h,o]]:[[-t,h,o],[t,h,o],[t,c,a],[-t,c,a]];for(const u of[0,2,1,0,3,2])s.push(...d[u])}const n=new Tt;return n.setAttribute("position",new wt(s,3)),n.computeVertexNormals(),n}stations(e){const t=[];for(let i=0;i<=Ui.BANK_STATIONS;i++)t.push(e*(this.span/2+this.bank*i/Ui.BANK_STATIONS));return t}railing(e){const t=this.size.lengthM/2,i=Math.max(1,Math.round(this.size.lengthM/this.postSpacing)),s=[];for(let a=0;a<=i;a++)s.push(-t+this.size.lengthM*a/i);const n=[],r=Ui.POST_SIDE_M;for(const a of s)n.push(Ui.box(r,this.railHeight,r,e,this.roadAt(a)+this.railHeight/2,a));for(let a=1;a<=this.rails;a++){const o=this.railHeight*a/this.rails-Ui.RAIL_HEIGHT_M/2;for(let c=1;c<s.length;c++){const h=new D(e,this.roadAt(s[c-1])+o,s[c-1]),d=new D(e,this.roadAt(s[c])+o,s[c]);n.push(Ui.beam(h,d))}}return n}static box(e,t,i,s,n,r){return new Ss(e,t,i).translate(s,n,r)}static beam(e,t){const i=new D().subVectors(t,e),s=new Ss(Ui.RAIL_DEPTH_M,Ui.RAIL_HEIGHT_M,i.length()),n=new Un().setFromUnitVectors(new D(0,0,1),i.clone().normalize()),r=new D().addVectors(e,t).multiplyScalar(.5);return s.applyMatrix4(new qe().compose(r,n,new D(1,1,1)))}static merge(e){const t=e.map(o=>o.getIndex()?o.toNonIndexed():o),i=t.reduce((o,c)=>o+c.getAttribute("position").count,0),s=new Float32Array(i*3),n=new Float32Array(i*3);let r=0;for(const o of t){const c=o.getAttribute("position"),h=o.getAttribute("normal");s.set(c.array,r*3),h&&n.set(h.array,r*3),r+=c.count}const a=new Tt;a.setAttribute("position",new wt(s,3)),a.setAttribute("normal",new wt(n,3));for(const o of e)o.dispose();for(const o of t)o.dispose();return a}}class Ki{static OVERHANG_M=.25;static SLAB_M=.2;static MIN_RIDGE_M=.1;static DEFAULT_RISE_M=3;static normalised(e){const t=e.shape??"flat";return{shape:t,riseM:t==="flat"?0:Math.max(0,e.riseM??Ki.DEFAULT_RISE_M),ridge:e.ridge??"width",...e.color?{color:e.color}:{}}}static build(e,t,i){const s=Ki.normalised(e),n=s.shape==="gable"&&s.ridge==="depth",r=(n?i:t)/2+Ki.OVERHANG_M,a=(n?t:i)/2+Ki.OVERHANG_M,o=s.shape==="flat"||s.riseM<=0?Ki.slab(r,a):s.shape==="dome"?Ki.dome(r-Ki.OVERHANG_M,a-Ki.OVERHANG_M,r,a,s.riseM):Ki.pitched(s.shape,r,a,s.riseM);return n&&o.rotateY(Math.PI/2),o.computeVertexNormals(),o}static slab(e,t){const i=Ki.SLAB_M,s=[[-e,0,-t],[e,0,-t],[e,0,t],[-e,0,t]],n=s.map(([o,,c])=>[o,i,c]),r=[],a=(o,c,h,d)=>{r.push(o,c,h,o,h,d)};a(n[0],n[3],n[2],n[1]);for(let o=0;o<4;o++){const c=(o+1)%4;a(s[o],s[c],n[c],n[o])}return Ki.of(r)}static pitched(e,t,i,s){const n=(h,d)=>[h,0,d],r=e==="gable"?t:Math.max(Ki.MIN_RIDGE_M/2,t-i),a=[-r,s,0],o=[r,s,0],c=[];return c.push(n(-t,-i),n(t,-i),o,n(-t,-i),o,a),c.push(n(t,i),n(-t,i),a,n(t,i),a,o),c.push(n(-t,i),n(-t,-i),a),c.push(n(t,-i),n(t,i),o),c.push(n(-t,-i),n(-t,i),n(t,i),n(-t,-i),n(t,i),n(t,-i)),Ki.of(c)}static DOME_RINGS=12;static DOME_SECTORS=48;static dome(e,t,i,s,n){const r=Ki.slab(i,s).getAttribute("position").array,a=[];for(let c=0;c<r.length;c+=3)a.push([r[c],r[c+1],r[c+2]]);const o=(c,h)=>{const d=c/Ki.DOME_RINGS*(Math.PI/2),u=h/Ki.DOME_SECTORS*2*Math.PI,p=Math.cos(d);return[e*p*Math.cos(u),Ki.SLAB_M+n*Math.sin(d),t*p*Math.sin(u)]};for(let c=0;c<Ki.DOME_RINGS;c++)for(let h=0;h<Ki.DOME_SECTORS;h++){const d=h+1;a.push(o(c,h),o(c+1,d),o(c,d),o(c,h),o(c+1,h),o(c+1,d))}return Ki.of(a)}static of(e){const t=new Tt;return t.setAttribute("position",new wt(e.flat(),3)),t}}class $r{static SLAB_M=.6;static SLABS=4;static SIZE=512;static JOINT_M=.012;static made;static texture(){if($r.made)return $r.made;const e=$r.SIZE,t=new Uint8Array(e*e*4);let i=23063;const s=()=>{i=i+1831565813|0;let p=Math.imul(i^i>>>15,1|i);return p=p+Math.imul(p^p>>>7,61|p)^p,((p^p>>>14)>>>0)/4294967296},n=$r.SLABS,r=e/n,a=Math.max(1,Math.round($r.JOINT_M/$r.SLAB_M*r)),o=Array.from({length:n*n},()=>.9+.1*s()),c=n*8,h=Array.from({length:c*c},()=>s()),d=(p,f)=>h[(f%c+c)%c*c+(p%c+c)%c];for(let p=0;p<e;p++)for(let f=0;f<e;f++){const m=Math.floor(f/r),v=Math.floor(p/r),g=f-m*r,b=p-v*r,w=g<a||b<a,y=f/r*8,M=p/r*8,x=Math.floor(y),E=Math.floor(M),S=y-x,A=M-E,T=S*S*(3-2*S),_=A*A*(3-2*A),k=(d(x,E)*(1-T)+d(x+1,E)*T)*(1-_)+(d(x,E+1)*(1-T)+d(x+1,E+1)*T)*_,L=s(),P=w?.55:o[v*n+m]*(.9+.12*k)*(.88+.12*L),C=Math.min(255,Math.round(255*P)),N=(p*e+f)*4;t[N]=C,t[N+1]=C,t[N+2]=C,t[N+3]=255}const u=new nr(t,e,e,xs,On);return u.wrapS=u.wrapT=sc,u.minFilter=Nr,u.generateMipmaps=!0,u.colorSpace=an,u.anisotropy=8,u.needsUpdate=!0,$r.made=u,u}static layOn(e){const t=e.getAttribute("position"),i=$r.SLAB_M*$r.SLABS,s=new Float32Array(t.count*2);for(let n=0;n<t.count;n++)s[n*2]=t.getX(n)/i,s[n*2+1]=t.getZ(n)/i;e.setAttribute("uv",new wt(s,2))}}class Ne{static UPPER=0;static GROUND_WINDOW=1;static GROUND_DOOR=2;static PLAIN=3;static TALL=4;static LANCET=5;static TILES=6;static TALL_SILL=.5;static TALL_HEAD=2.62;static BAY_M=3;static FLOOR_M=3;static PIXELS=96;static shared;static sharedEmissive;static texture(){if(!Ne.shared){const e=new nr(Ne.pixels(),Ne.PIXELS*Ne.TILES,Ne.PIXELS,xs,On);e.colorSpace=an,e.wrapS=Ms,e.wrapT=Ms,e.magFilter=St,e.minFilter=Nr,e.generateMipmaps=!0,e.needsUpdate=!0,Ne.shared=e}return Ne.shared}static emissive(){if(!Ne.sharedEmissive){const e=new nr(Ne.glow(),Ne.PIXELS*Ne.TILES,Ne.PIXELS,xs,On);e.colorSpace=an,e.wrapS=Ms,e.wrapT=Ms,e.magFilter=St,e.minFilter=Nr,e.generateMipmaps=!0,e.needsUpdate=!0,Ne.sharedEmissive=e}return Ne.sharedEmissive}static glow(){const e=Ne.PIXELS,t=e*Ne.TILES,i=new Uint8Array(t*e*4);for(let r=3;r<i.length;r+=4)i[r]=255;const s=e/Ne.BAY_M,n=[[Ne.UPPER,.9,2.3],[Ne.GROUND_WINDOW,.9,2.3],[Ne.TALL,Ne.TALL_SILL,Ne.TALL_HEAD]];for(const[r,a,o]of n)for(let c=Math.round(a*s);c<Math.round(o*s);c++)for(let h=Math.round(.9*s);h<Math.round(2.1*s);h++){if(Math.abs(h-1.5*s)<.03*s)continue;const d=(c*t+r*e+h)*4,[u,p,f]=Ne.roomLight((h/s-.9)/1.2,(c/s-a)/(o-a));i[d]=u,i[d+1]=p,i[d+2]=f}return i}static roomLight(e,t){const i=.35+.65*Math.pow(Math.max(0,Math.min(1,t)),.8),s=1-.45*Math.pow(Math.abs(2*e-1),3),n=Math.min(e,1-e)<.16,r=i*s*(n?.35:1),a=n?[255,225,195]:[255,255,255],o=Math.pow(r,1/2.2);return[Math.round(a[0]*o),Math.round(a[1]*o),Math.round(a[2]*o)]}static pixels(){const e=Ne.PIXELS,t=e*Ne.TILES,i=new Uint8Array(t*e*4).fill(255),s=e/Ne.BAY_M,n=(f,m,v,g,b,w)=>{for(let y=Math.round(v*s);y<Math.round(b*s);y++)for(let M=Math.round(m*s);M<Math.round(g*s);M++){const x=(y*t+f*e+M)*4;i[x]=w[0],i[x+1]=w[1],i[x+2]=w[2],i[x+3]=255}},r=[225,225,222],a=[34,42,54],o=[200,198,192];for(const f of[Ne.UPPER,Ne.GROUND_WINDOW])n(f,.9-.06,.9-.06,2.1+.06,2.3+.06,r),n(f,.9,.9,2.1,2.3,a),n(f,1.5-.02,.9,1.5+.02,2.3,r),n(f,.8,.84,2.2,.9-.06,o);n(Ne.GROUND_DOOR,1-.06,0,2+.06,2.1+.06,r),n(Ne.GROUND_DOOR,1,0,2,2.1,[58,62,56]);const c=[44,44,46],h=Ne.TALL;n(h,0,0,3,.09,[214,210,202]),n(h,.9-.08,Ne.TALL_SILL-.04,2.1+.08,Ne.TALL_HEAD+.1,r),n(h,.9,Ne.TALL_SILL,2.1,Ne.TALL_HEAD,a),n(h,1.5-.02,Ne.TALL_SILL,1.5+.02,Ne.TALL_HEAD,r),n(h,.82,Ne.TALL_SILL,2.18,Ne.TALL_SILL+.05,c),n(h,.82,Ne.TALL_SILL+.38,2.18,Ne.TALL_SILL+.43,c);for(let f=.86;f<2.15;f+=.13)n(h,f,Ne.TALL_SILL,f+.03,Ne.TALL_SILL+.4,c);const d=Ne.LANCET,u=2,p=2.34;n(d,1.2,.66,1.8,u,[40,44,54]);for(let f=u;f<p;f+=1/s){const m=.3*Math.sqrt(1-((f-u)/(p-u))**2);n(d,1.5-m,f,1.5+m,f+1/s,[40,44,54])}return i}}class pp{static hash(e,t){const i=Math.sin(e*12.9898+t*78.233)*43758.5453;return i-Math.floor(i)}static LANCET_BAY_M=6;static LANCET_TIER_M=10;static build(e,t,i,s=!0,n=0,r,a=Ne.FLOOR_M){const o=[],c=[],h=[],d=e/2,u=t/2,p=r==="lancet",f=Math.max(1,Math.round(i/(p?pp.LANCET_TIER_M:Math.max(a,1)))),m=i/f,v=p?pp.LANCET_BAY_M:Ne.BAY_M,g=(y,M,x,E)=>{const S=Math.max(1,Math.round(x/v)),A=x/S;for(let T=0;T<f;T++)for(let _=0;_<S;_++){const k=E&&T===0&&_===Math.floor((S-1)/2),L=s?p?(f-1-T)%2===0?Ne.LANCET:Ne.PLAIN:k?Ne.GROUND_DOOR:r==="tall"?Ne.TALL:T>0?Ne.UPPER:Ne.GROUND_WINDOW:Ne.PLAIN,P=L===Ne.UPPER||L===Ne.GROUND_WINDOW||L===Ne.TALL?pp.hash(n,o.length):2;for(let Le=0;Le<6;Le++)h.push(P);const C=y[0]+M[0]*A*_,N=y[1]+M[1]*A*_,F=C+M[0]*A,H=N+M[1]*A,j=T*m,W=j+m,J=L/Ne.TILES+.002,re=(L+1)/Ne.TILES-.002;o.push(C,j,N,F,j,H,F,W,H,C,j,N,F,W,H,C,W,N),c.push(J,.002,re,.002,re,.998,J,.002,re,.998,J,.998)}};g([d,-u],[-1,0],e,!0),g([-d,u],[1,0],e,!1),g([-d,-u],[0,1],t,!1),g([d,u],[0,-1],t,!1);const b=Ne.PLAIN/Ne.TILES+.01;o.push(-d,i,-u,-d,i,u,d,i,u,-d,i,-u,d,i,u,d,i,-u);for(let y=0;y<6;y++)c.push(b,.5),h.push(2);const w=new Tt;return w.setAttribute("position",new wt(o,3)),w.setAttribute("uv",new wt(c,2)),w.setAttribute("litRank",new wt(h,1)),w.computeVertexNormals(),w}}class Bc{constructor(e,t={}){this.size=e,this.structure=t}static DEFAULT_DIAMETER_M=.008;static POLE_RADIUS_M=.13;static POLE_ABOVE_M=.5;static NATURAL_SIZE=Object.freeze({widthM:1,lengthM:30,heightM:5});get strands(){const e=this.structure.strands;return!e||e.length===0?[{heightM:this.size.heightM,acrossM:0}]:e.map(t=>({heightM:t.heightM,acrossM:t.acrossM??0}))}get poleStations(){const e=this.size.lengthM/2;switch(this.structure.poles??"both"){case"start":return[e];case"end":return[-e];case"none":return[];default:return[-e,e]}}get poleHeightM(){return this.structure.poleHeightM??Math.max(...this.strands.map(e=>e.heightM))+Bc.POLE_ABOVE_M}build(){const e=this.structure.diameterM??Bc.DEFAULT_DIAMETER_M,t=this.strands.map(s=>{const n=new Bn(e/2,e/2,this.size.lengthM,6);return n.rotateX(Math.PI/2),n.translate(s.acrossM,s.heightM,0),n}),i=this.poleStations.map(s=>{const n=new Bn(Bc.POLE_RADIUS_M*.8,Bc.POLE_RADIUS_M,this.poleHeightM,8);return n.translate(0,this.poleHeightM/2,s),n});return{strands:t,poles:i}}}class Ps{static TILE_M=2.4;static COLUMNS=6;static COURSES=10;static SIZE_PX=256;static FOUNDATION_M=.8;static pattern;static build(e){const t=new ii,i=e.sizeM?.widthM??.6,s=e.sizeM?.heightM??1,n=e.sizeM?.lengthM??10,r=s+Ps.FOUNDATION_M,a=new Ss(i,r,n);Ps.layStones(a,i,r,n);const o=new ta({map:Ps.texture()}),c=new Me(a,o);return c.position.y=(s-Ps.FOUNDATION_M)/2,c.castShadow=!0,c.receiveShadow=!0,c.userData={emissive:!1},t.add(c),t}static layStones(e,t,i,s){const n=e.getAttribute("uv");[[s,i],[s,i],[t,s],[t,s],[t,i],[t,i]].forEach(([a,o],c)=>{for(let h=c*4;h<c*4+4;h++)n.setXY(h,n.getX(h)*a/Ps.TILE_M,n.getY(h)*o/Ps.TILE_M)}),n.needsUpdate=!0}static texture(){if(Ps.pattern)return Ps.pattern;const e=Ps.SIZE_PX,t=new Uint8Array(e*e*4),i=Ps.seeds();for(let n=0;n<e;n++)for(let r=0;r<e;r++){const a=r/e,o=n/e;let c=1/0,h=1/0,d=i[0];for(const b of i)for(let w=-1;w<=1;w++)for(let y=-1;y<=1;y++){const M=(a-(b.x+w))*Ps.COLUMNS,x=(o-(b.y+y))*Ps.COURSES*.5,E=.8*Math.max(Math.abs(M),Math.abs(x))+.2*Math.hypot(M,x);E<c?(h=c,c=E,d=b):E<h&&(h=E)}const u=h-c,p=Math.min(u/.1,1),f=.8+.2*Math.min(u/.5,1),m=.94+.12*Ps.noise(r,n),v=(.15+(d.tone-.15)*p)*(p>.999?f*m:1),g=(n*e+r)*4;t[g]=Math.round(255*v*d.warm),t[g+1]=Math.round(255*v),t[g+2]=Math.round(255*v*d.cool),t[g+3]=255}const s=new nr(t,e,e,xs);return s.wrapS=s.wrapT=sc,s.colorSpace=an,s.magFilter=St,s.minFilter=Nr,s.generateMipmaps=!0,s.anisotropy=4,s.needsUpdate=!0,Ps.pattern=s,s}static seeds(){let e=20260831;const t=()=>(e=e*1664525+1013904223>>>0,e/4294967296),i=[];for(let s=0;s<Ps.COURSES;s++)for(let n=0;n<Ps.COLUMNS;n++){const r=.34+t()*.24;i.push({x:(n+s%2*.5+.5+(t()-.5)*.35)/Ps.COLUMNS,y:(s+.5+(t()-.5)*.3)/Ps.COURSES,tone:r,warm:1+t()*.1,cool:.9+t()*.1})}return i}static noise(e,t){const i=Math.sin(e*12.9898+t*78.233)*43758.5453;return i-Math.floor(i)}}class Rt{static HEAD_WIDTH_M=.34;static HEAD_DEPTH_M=.24;static HEAD_MARGIN_M=.18;static POLE_RADIUS_M=.055;static HOUSING=[.05,.05,.05];static POLE=[.16,.17,.17];static BAND_M=.5;static BAND_GAP_M=.5;static KERB_CLEAR_M=.25;static CROSSING_LIFT_M=.08;static PAINT=[.8,.8,.78];static SIGN_POLE_RADIUS_M=.03;static SIGN_CENTRE_Y_M=2.55;static SIGN_METAL=[.48,.49,.5];static SIGN_RED=[.62,.05,.05];static SIGN_WHITE=[.82,.82,.8];static trafficLight(e){const t=e?2:3,i=e?gt.PEDESTRIAN_HEAD_Y_M:gt.VEHICLE_HEAD_Y_M,s=gt.LENS_SPACING_M,n=(t-1)*s+2*Rt.HEAD_MARGIN_M,r=i-n/2+.05,a=[Rt.part(new Bn(Rt.POLE_RADIUS_M,Rt.POLE_RADIUS_M,r,8),Rt.POLE,0,r/2,0),Rt.part(new Ss(Rt.HEAD_WIDTH_M,n,Rt.HEAD_DEPTH_M),Rt.HOUSING,0,i,0)];for(let o=0;o<t;o++){const c=i+((t-1)/2-o)*s;a.push(Rt.part(new Ss(.26,.02,.16),Rt.HOUSING,0,c+.12,-.2))}return Rt.group(a)}static crossing(e,t){const i=Rt.BAND_M,s=i+Rt.BAND_GAP_M,n=Math.max(i,e-2*Rt.KERB_CLEAR_M),r=Math.max(1,Math.floor((n+Rt.BAND_GAP_M)/s)),a=-((r-1)*s)/2,o=[],c=[],h=Rt.CROSSING_LIFT_M,d=t/2;for(let v=0;v<r;v++){const g=a+v*s-i/2,b=g+i;o.push(g,h,d,b,h,d,b,h,-d,g,h,d,b,h,-d,g,h,-d);for(let w=0;w<6;w++)c.push(0,1,0)}const u=new Tt;u.setAttribute("position",new wt(o,3)),u.setAttribute("normal",new wt(c,3));const p=new ta({color:16777215});p.color.setRGB(...Rt.PAINT),p.polygonOffset=!0,p.polygonOffsetFactor=-4,p.polygonOffsetUnits=-4;const f=new Me(u,p);f.userData={emissive:!1},f.receiveShadow=!0,f.castShadow=!1;const m=new ii;return m.add(f),m}static drape(e,t){e.traverse(i=>{const s=i;if(!s.isMesh)return;const n=s.geometry.getAttribute("position"),r=s.userData.crossingRest??=Float32Array.from(n.array);for(let a=0;a<n.count;a++)n.setY(a,r[a*3+1]+t(r[a*3],r[a*3+2]));n.needsUpdate=!0,s.geometry.computeBoundingSphere(),s.geometry.computeBoundingBox()})}static roadSign(e){const t=Rt.SIGN_CENTRE_Y_M,i=e?.face??"other",[s,n,r]=i==="stop"?[.38,8,Math.PI/8]:i==="give-way"?[.52,3,0]:i==="speed-limit"?[.325,24,0]:[0,0,0],a=t+(i==="other"?.3:s),o=Rt.SIGN_POLE_RADIUS_M,c=[Rt.part(new Bn(o,o,a,6),Rt.SIGN_METAL,0,a/2,0)],h=(d,u,p,f)=>{const m=new Bn(d,d,u,n,1,!1,r);m.rotateX(Math.PI/2),c.push(Rt.part(m,f,0,t,-p))};if(i==="other")c.push(Rt.part(new Ss(.6,.6,.012),Rt.SIGN_METAL,0,t,-.038)),c.push(Rt.part(new Ss(.58,.58,.004),Rt.SIGN_WHITE,0,t,-.047));else{h(s,.012,o+.008,Rt.SIGN_METAL);const[d,u,p]=i==="stop"?[Rt.SIGN_WHITE,Rt.SIGN_RED,.92]:[Rt.SIGN_RED,Rt.SIGN_WHITE,i==="give-way"?.68:.77];h(s*.99,.004,o+.017,d),h(s*p,.003,o+.0205,u)}return Rt.group(c)}static pedestrianFigure(e,t){const i=e==="standing"?[[-.17,.25],[.17,.25],[.17,-.08],[.1,-.08],[.1,-.5],[.02,-.5],[.02,-.12],[-.02,-.12],[-.02,-.5],[-.1,-.5],[-.1,-.08],[-.17,-.08]]:[[-.05,.26],[-.09,.22],[-.24,.05],[-.19,.01],[-.07,.13],[-.07,0],[-.18,-.22],[-.29,-.47],[-.22,-.5],[-.1,-.25],[-.01,-.07],[.09,-.27],[.13,-.5],[.21,-.48],[.16,-.24],[.07,0],[.07,.11],[.2,0],[.24,.05],[.08,.22],[.05,.26]],s=new gy(i.map(([a,o])=>new ie(a,o))),n=new gy;n.absarc(e==="standing"?0:-.02,.38,.1,0,2*Math.PI,!1);const r=new zw([s,n],6);return r.scale(t,t,t),r.rotateY(Math.PI),r}static part(e,t,i,s,n){return{geometry:e,color:t,matrix:new qe().makeTranslation(i,s,n)}}static group(e){const t=[],i=[],s=[];for(const{geometry:o,color:c,matrix:h}of e){const d=o.index?o.toNonIndexed():o;d.applyMatrix4(h);const u=d.getAttribute("position"),p=d.getAttribute("normal");for(let f=0;f<u.count;f++)t.push(u.getX(f),u.getY(f),u.getZ(f)),i.push(p.getX(f),p.getY(f),p.getZ(f)),s.push(...c);d!==o&&d.dispose(),o.dispose()}const n=new Tt;n.setAttribute("position",new wt(t,3)),n.setAttribute("normal",new wt(i,3)),n.setAttribute("color",new wt(s,3));const r=new Me(n,new ta({color:16777215,vertexColors:!0}));r.userData={emissive:!1},r.castShadow=!0,r.receiveShadow=!0;const a=new ii;return a.add(r),a}}class Bd{static MIN_K=1667;static MAX_K=25e3;static ofTemperature(e){const t=Math.min(Bd.MAX_K,Math.max(Bd.MIN_K,e)),i=t<=4e3?-266123900/t**3-234358.9/t**2+877.6956/t+.17991:-3025846900/t**3+21070379e-1/t**2+222.6347/t+.24039,s=t<=2222?-1.1063814*i**3-1.3481102*i**2+2.18555832*i-.20219683:t<=4e3?-.9549476*i**3-1.37418593*i**2+2.09137015*i-.16748867:3.081758*i**3-5.8733867*i**2+3.75112997*i-.37001483,n=i/s,r=(1-i-s)/s,a=[3.2406*n-1.5372-.4986*r,-.9689*n+1.8758+.0415*r,.0557*n-.204+1.057*r].map(c=>Math.max(0,c)),o=.2126*a[0]+.7152*a[1]+.0722*a[2];return[a[0]/o,a[1]/o,a[2]/o]}}const h1=Math.PI/180;function li(l,e,t,i,s=!1,n){const r=s&&n?new ta({color:new oe(...n),emissive:new oe(...t)}):s?new ir({color:new oe(...t)}):new ta({color:new oe(...t)}),a=new Me(e,r);return a.position.y=i,a.userData={emissive:s},a.castShadow=!s,a.receiveShadow=!s,l.add(a),a}const d1=.25,R8=.002,C8=100,VE=3e4,L8=1500,O8=.25,P8=1e3,N8=.15;function F8(l){const e=/^#([0-9a-f]{6})$/i.exec(l);if(!e)return[1,1,1];const t=parseInt(e[1],16),i=s=>{const n=s/255;return n<=.04045?n/12.92:((n+.055)/1.055)**2.4};return[i(t>>16&255),i(t>>8&255),i(t&255)]}const U8=[.62,.62,.6],B8=[1,.85,.5],z8=[.25,.25,.25],sI=[1,.97,.85],H8=[.55,.68,.72],G8=.12,Xa=.03,Ya=.05,nI={front:0,behind:Math.PI,left:Math.PI/2,right:-Math.PI/2,"front-left":Math.PI/2,"behind-left":Math.PI/2,"front-right":-Math.PI/2,"behind-right":-Math.PI/2};function Xn(l,e){return l?.[e]}function qa(l,e,t,i,s,n,r,a){if(a===void 0)return;const o=new ir({color:new oe(...H8).multiplyScalar(G8),transparent:!0,opacity:a/100,depthWrite:!1}),c=new Me(new Ss(e,t,i),o);c.position.set(s,n,r),c.renderOrder=2,l.add(c)}const Wr=.05,u1=[.6,.58,.53],WE=[.5,.5,.48];function md(l,e,t,i,s,n,r,a){const o=new ta({color:new oe(...a),side:Ji}),c=new Me(new Ss(e,t,i),o);c.position.set(s,n,r),l.add(c)}function V8(l,e,t,i,s,n,r,a,o){const c=(i-n)/2,h=(f,m,v,g)=>{f<=0||(e?md(l,f,m,Wr,v,a+g,r,o):md(l,Wr,m,f,r,a+g,v,o))};h(t,c,0,i/2-c/2),h(t,c,0,-(i/2-c/2));const d=[...s].sort((f,m)=>f.center-m.center);let u=-t/2;for(const f of d){const v=f.center-f.main/2-u;h(v,n,u+v/2,0),u=f.center+f.main/2}const p=t/2-u;h(p,n,u+p/2,0)}function rI(l,e,t,i,s,n,r,a,o,c){const h=(i+s)/2,d=s-i,u=(p,f,m,v)=>{p.length===0?f?md(l,m,d,Wr,0,h,v,u1):md(l,Wr,d,m,v,h,0,u1):V8(l,f,m,d,p,n,v,h,u1)};u(r,!0,e*2,-t+Wr),u(a,!0,e*2,t-Wr),u(o,!1,t*2,-e+Wr),u(c,!1,t*2,e-Wr),md(l,e*2,Wr,t*2,0,i+Wr,0,WE),md(l,e*2,Wr,t*2,0,s-Wr,0,WE)}function ky(l,e,t,i){switch(l){case"front":return{x:0,z:-(t-i)};case"behind":return{x:0,z:t-i};case"left":return{x:-(e-i),z:0};case"right":return{x:e-i,z:0};case"front-left":return{x:-(e-i),z:-Za};case"front-right":return{x:e-i,z:-Za};case"behind-left":return{x:-(e-i),z:Za};case"behind-right":return{x:e-i,z:Za}}}function aI(l,e,t,i,s,n,r,a){const o=Ly();o.scale.setScalar(s),o.rotation.y=nI[t];const{x:c,z:h}=ky(e,n,r,a);o.position.set(c,i,h),l.add(o)}const Ry=6,Cy=6,ja=3,Ru=1.4,Cu=ja*.5,oI=1.2,lI=.35,W8=.75,$8=1.6;function $E(l,e,t,i,s){const n=new ii,r=Math.max(1,l+1),a=r*ja;li(n,new Ss(Ry,a,Cy),[.55,.54,.5],a/2);const o=Ry/2,c=Cy/2;for(let h=0;h<r;h++){const d=h*ja+ja/2;qa(n,Ru,Cu,Ya,0,d,-c-Xa,Xn(e,"front")),qa(n,Ru,Cu,Ya,0,d,c+Xa,Xn(e,"behind")),qa(n,Ya,Cu,Ru,-o-Xa,d,0,Xn(e,"left")),qa(n,Ya,Cu,Ru,o+Xa,d,0,Xn(e,"right"))}if(t){const h=Math.min(Math.max(i??0,0),r-1);aI(n,t,s??t,h*ja,.72,o,c,oI);const d=u=>Xn(e,u)!==void 0?[{main:Ru,center:0}]:[];rI(n,o,c,h*ja,(h+1)*ja,Cu,d("front"),d("behind"),d("left"),d("right"))}return n}function KE(){const l=new ii,e=[[0,0,.55,.5],[.4,.1,.35,.4],[-.35,-.2,.4,.38],[.1,-.4,.35,.36],[-.15,.4,.3,.34]];for(const[t,i,s,n]of e){const r=new Rs(s,10,7);r.scale(1,.85,1),r.translate(t,0,i),li(l,r,[.26,.28,.17],n)}return l}function K8(l){const e=new ii,t=new Ui(ue.sizeOf(l),l.bridge).build();li(e,t.concrete,[.6,.6,.58],0);const i=li(e,t.road,[.2,.2,.21],0),s=li(e,t.earth,[.3,.36,.22],0);for(const n of[i,s])n.material.side=$s;return li(e,t.railing,[.5,.52,.55],0),e}function X8(l){const e=new ii,t=new Bc(ue.sizeOf(l),l.wire).build();for(const i of t.strands)li(e,i,[.1,.1,.11],0);for(const i of t.poles)li(e,i,[.3,.24,.18],0);return e}function XE(){const l=new ii;return li(l,new Bn(.15,.22,2,8),[.32,.22,.14],1),li(l,new lu(1.4,3,8),[.16,.32,.14],3.5),l}const YE=.275,Y8=.35,q8=.9,j8=34,Z8=8,J8=1.4;function qE(){const l=new ii,e=new Rs(YE,7,3,0,Math.PI*2,0,Math.PI/2);e.scale(1,Y8/YE,1);const t=ue.repeatOnGrid(e,j8,q8,Z8,J8),i=li(l,t,[.26,.28,.22],0);return i.castShadow=!0,i.userData.cropBasePositions=t.getAttribute("position").array.slice(),i.userData.cropVerticesPerClump=e.getAttribute("position").count,e.dispose(),l}function jE(){const l=new ii,e=new Rs(1,7,3,0,Math.PI*2,0,Math.PI/2);return li(l,e,[.38,.36,.32],0),l}const Q8=[.24,.22,.18],e9=[.14,.17,.08];function t9(){const l=new ii,e=li(l,new Ss(1,1,1),Q8,.5),t=li(l,new Ss(1,.03,1),e9,1.015);for(const i of[e,t])i.material.side=$s;return t.castShadow=!1,Ud.install(t.material,!0),l}function ZE(l,e,t){const i=new ii;e!=="wall"&&li(i,new Bn(.05,.08,5,8),[.28,.28,.3],2.5);const s=li(i,new Rs(.25,12,8),l?ue.lampHue(t):[0,0,0],5.1,!0,U8);return tI.applyOpaque(s.material),i}const i9=[.08,.08,.08],vl=.8,Jh=1,Ca=1.7,p1=.6,mc=.46,ym=1.5,Uh=.8,Za=.5,s9=Ca;function JE(l,e,t,i){const s=new ii;li(s,new Ss(1.8,1.4,4.2),[.45,.14,.14],.7),li(s,new Ss(vl*2,p1,Jh*2),[.4,.12,.12],Ca);for(const r of[-1.4,1.4])for(const a of[-.95,.95]){const o=li(s,new Bn(.4,.4,.3,12),i9,.4);o.rotation.z=Math.PI/2,o.position.x=a,o.position.z=r}const n=l?sI:[0,0,0];for(const r of[-.7,.7])li(s,new Rs(.15,8,6),n,.7,!0,z8).position.set(r,.7,-2.1);if(qa(s,ym,mc,Ya,0,Ca,-Jh-Xa,Xn(e,"front")),qa(s,ym,mc,Ya,0,Ca,Jh+Xa,Xn(e,"behind")),qa(s,Ya,mc,Uh,-vl-Xa,Ca,-Za,Xn(e,"front-left")),qa(s,Ya,mc,Uh,-vl-Xa,Ca,Za,Xn(e,"behind-left")),qa(s,Ya,mc,Uh,vl+Xa,Ca,-Za,Xn(e,"front-right")),qa(s,Ya,mc,Uh,vl+Xa,Ca,Za,Xn(e,"behind-right")),t){aI(s,t,i??t,W8,.5,vl,Jh,lI);const r=(c,h)=>{const d=[];return Xn(e,c)!==void 0&&d.push({main:Uh,center:-Za}),Xn(e,h)!==void 0&&d.push({main:Uh,center:Za}),d},a=Xn(e,"front")!==void 0?[{main:ym,center:0}]:[],o=Xn(e,"behind")!==void 0?[{main:ym,center:0}]:[];rI(s,vl,Jh,Ca-p1/2,Ca+p1/2,mc,a,o,r("front-left","behind-left"),r("front-right","behind-right"))}return s}const QE=new Map;function e2(l,e){if(!l)return;const t=[[l.lengthM,e.lengthM],[l.heightM,e.heightM],[l.widthM,e.widthM]];for(const[i,s]of t)if(i!==void 0&&s>1e-6)return i/s}function f1(l,e){return e>1e-6?l/e:1}const cI=[.95,.9,.82],t2=[.72,.74,.78];function i2(){const l=new ii;li(l,new Bn(.25,.3,1.5,10),t2,.75),li(l,new Rs(.26,10,8),t2,1.74);const e=li(l,new lu(.07,.16,8),cI,1.74);return e.rotation.x=-Math.PI/2,e.position.z=-.22,l}function Ly(){const l=new ii;li(l,new Bn(.25,.3,1.5,10),[.3,.3,.35],.75),li(l,new Rs(.22,10,8),[.62,.52,.46],1.72);const e=li(l,new lu(.07,.16,8),cI,1.72);return e.rotation.x=-Math.PI/2,e.position.z=-.2,l}const n9=17,s2=18.5,m1=[.16,.16,.18];function n2(){const l=new ii,e=li(l,new Bn(1.8,1.8,s2*2,10),m1,0);e.rotation.x=Math.PI/2,li(l,new Ss(n9*2,.5,4.5),m1,0);const t=li(l,new Ss(.4,5.5,4),m1,3);return t.position.z=-s2+2,l}class ue{static GROWS_FROM_GROUND=new Set(["tree","shrub","crop","mound","terrace","wall","building","bridge"]);static groundUnderFootprint(e,t,i,s,n,r=0){const a=ue.sizeOf(e);if(r>a.heightM)return n(t,i);const o=(s??0)*Math.PI/180,c=e.kind==="bridge"?Math.min(a.lengthM,e.bridge?.spanM??a.lengthM):a.lengthM,h=Math.min(21,Math.max(2,Math.ceil(c/.75)+1)),d=Math.min(21,Math.max(2,Math.ceil(a.widthM/.75)+1)),u=ue.GROWS_FROM_GROUND.has(e.kind);let p=u?1/0:-1/0;for(let f=0;f<h;f++){const m=(f/(h-1)-.5)*c;for(let v=0;v<d;v++){const g=(v/(d-1)-.5)*a.widthM,b=t+Math.sin(o)*m+Math.cos(o)*g,w=i-Math.cos(o)*m+Math.sin(o)*g;p=u?Math.min(p,n(b,w)):Math.max(p,n(b,w))}}return Number.isFinite(p)?p:n(t,i)}static wireGround(e,t,i,s,n){const r=ue.sizeOf(e).lengthM/2,a=(s??0)*Math.PI/180,o=n(t+Math.sin(a)*r,i-Math.cos(a)*r),c=n(t-Math.sin(a)*r,i+Math.cos(a)*r);return{startY:c,dropM:o-c}}static shearWire(e,t,i){t<=0||e.traverse(s=>{const n=s;if(!n.isMesh)return;const r=n.geometry.getAttribute("position"),a=n.userData.wireRest??=Float32Array.from(r.array);for(let o=0;o<r.count;o++){const c=.5-a[o*3+2]/t;r.setY(o,a[o*3+1]+i*c)}r.needsUpdate=!0,n.geometry.computeBoundingSphere(),n.geometry.computeBoundingBox()})}static occupantView(e,t=e.headingDeg){const i=e.observerSide;if(!i)throw new Error("occupantView requires object.observerSide to be set");const{x:s,z:n}=e.kind==="vehicle"?ky(i,vl,Jh,lI):ky(i,Ry/2,Cy/2,oI),r=e.kind==="vehicle"?s9:(e.occupiedFloor??0)*ja+$8,a=(t??0)-nI[e.observerFacing??i]/h1,o=this.scaleFor(e);return{x:s*o.x,z:n*o.z,eyeY:r*o.y,headingDeg:a}}static BODY_NAME="decor-body";static bodyOf(e){return e.getObjectByName(ue.BODY_NAME)??e}static repeatOnGrid(e,t,i,s,n){const r=e.getAttribute("position"),a=e.getAttribute("normal"),o=e.getIndex();if(!o)throw new Error("repeatOnGrid needs an indexed geometry");const c=r.count,h=t*s,d=new Float32Array(c*h*3),u=new Float32Array(c*h*3),p=new Uint32Array(o.count*h),f=-((t-1)*i)/2,m=-((s-1)*n)/2;let v=0;for(let b=0;b<s;b++)for(let w=0;w<t;w++,v++){const y=m+b*n,M=f+w*i;for(let x=0;x<c;x++){const E=(v*c+x)*3;d[E]=r.getX(x)+y,d[E+1]=r.getY(x),d[E+2]=r.getZ(x)+M,u[E]=a.getX(x),u[E+1]=a.getY(x),u[E+2]=a.getZ(x)}for(let x=0;x<o.count;x++)p[v*o.count+x]=o.getX(x)+v*c}const g=new Tt;return g.setAttribute("position",new wt(d,3)),g.setAttribute("normal",new wt(u,3)),g.setIndex(new Nw(p,1)),g}static fitTerrace(e,t,i){const s=ue.sizeOf(t),n=s.widthM/2,r=s.lengthM/2,a=i(0,0)+s.heightM,o=Math.min(16,Math.max(1,Math.ceil(s.lengthM/3))),c=ue.bodyOf(e).children.filter(y=>y.isMesh);if(c.length<2)return a;const h=Math.min(10,s.widthM/4),d=[-n];for(const y of[.25,.5,.75,1])d.push(-n+h*y);const u=Math.max(1,Math.ceil((s.widthM-2*h)/3));for(let y=1;y<u;y++)d.push(-n+h+(s.widthM-2*h)*y/u);for(const y of[1,.75,.5,.25,0])d.push(n-h*y);const p=y=>-r+s.lengthM*y/o,f=.8,m=(y,M)=>{const x=Math.min(1,Math.max(0,(n-Math.abs(y))/h)),E=x*x*(3-2*x);return E*a+(1-E)*Math.min(a,i(y,M))},v=[],g=(y,M)=>{const x=i(y[0],y[1])-f,E=i(M[0],M[1])-f,S=Math.max(m(y[0],y[1]),x),A=Math.max(m(M[0],M[1]),E);v.push(y[0],x,y[1],M[0],E,M[1],y[0],S,y[1]),v.push(M[0],E,M[1],M[0],A,M[1],y[0],S,y[1])};for(let y=0;y<d.length-1;y++)g([d[y],-r],[d[y+1],-r]),g([d[y],r],[d[y+1],r]);const b=[];for(let y=0;y<d.length-1;y++)for(let M=0;M<o;M++){const x=[d[y],p(M)],E=[d[y+1],p(M)],S=[d[y],p(M+1)],A=[d[y+1],p(M+1)];for(const[T,_,k]of[[x,S,E],[E,S,A]])for(const L of[T,_,k])b.push(L[0],m(L[0],L[1]),L[1])}const w=(y,M)=>{const x=new Tt;x.setAttribute("position",new wt(M,3)),x.computeVertexNormals(),y.geometry.dispose(),y.geometry=x,y.position.y=0};return w(c[0],v),w(c[1],b),a}static fitCropToGround(e,t){e.updateMatrixWorld(!0);const i=new D;e.traverse(s=>{const n=s,r=n.userData.cropBasePositions,a=n.userData.cropVerticesPerClump;if(!n.isMesh||!r||!a)return;const o=n.geometry.getAttribute("position"),c=new qe().copy(n.matrixWorld).invert();for(let h=0;h<o.count;h+=a){i.set(r[h*3],0,r[h*3+2]).applyMatrix4(n.matrixWorld),i.y=t(i.x,i.z),i.applyMatrix4(c);for(let d=h;d<h+a;d++)o.setY(d,r[d*3+1]+i.y)}o.needsUpdate=!0,n.geometry.computeBoundingBox(),n.geometry.computeBoundingSphere()})}static applyModelParameters(e,t,i){if(!(!t||!i))for(const[s,n]of Object.entries(i)){const r=t[s];if("materials"in n)typeof r=="string"&&ue.tint(e,n.materials,r);else if(typeof r=="boolean"){const a=n.nodes.map(c=>new RegExp(c)),o=r===(n.hideWhen??!0);e.traverse(c=>{a.some(h=>h.test(c.name))&&(c.visible=!o)})}}}static tint(e,t,i){const s=t.map(n=>new RegExp(n));e.traverse(n=>{const r=n;if(!r.isMesh)return;const a=r.userData.tintedMaterials??[],o=c=>{if(!c.color||!s.some(p=>p.test(c.name)))return c;const d=c.clone();d.color.set(i);const u=d.emissive?Math.max(d.emissive.r,d.emissive.g,d.emissive.b):0;return u>0&&(d.emissive.multiply(d.color),d.emissive.multiplyScalar(u/(Math.max(d.emissive.r,d.emissive.g,d.emissive.b)||1))),a.push(d),d};r.material=Array.isArray(r.material)?r.material.map(o):o(r.material),a.length>0&&(r.userData.tintedMaterials=a)})}static paint(e,t){e.traverse(i=>{const s=i,n=s.userData;if(!s.isMesh||n?.emissive)return;const r=s.material;r?.color&&r.color.set(t)})}static addRoof(e,t){const i=Ki.normalised(t.roof),s=ue.sizeOf(t),n=t.sizeM?.heightM===void 0?s.heightM:ue.wallHeightOf(t,s.heightM),r=ue.roofColor(i.color),a=Ki.build(i,s.widthM,s.lengthM);t.roof.material==="stone"&&$r.layOn(a);const o=li(e,a,r,n),c=o.material;c.side=$s,t.roof.material==="stone"&&(c.map=$r.texture(),c.bumpMap=c.map,c.bumpScale=ue.STONE_BUMP),o.name=ue.ROOF_NAME}static wallHeightOf(e,t){return Math.min(t,Math.max(ja,t-(e.roof?Ki.normalised(e.roof).riseM:0)))}static roofColor(e){const t=/^#([0-9a-f]{6})$/i.exec(e??"")?.[1];if(!t)return[.45,.25,.2];const i=new oe(`#${t}`);return[i.r,i.g,i.b]}static ROOF_NAME="decor-roof";static STONE_BUMP=2;static PLASTER="#d3cab8";static hasFacade(e){return e.kind==="building"&&ue.facadeOf(e)!==void 0&&!e.observerSide&&e.sizeM?.widthM!==void 0&&e.sizeM.lengthM!==void 0&&e.sizeM.heightM!==void 0}static facadeOf(e){if(e.kind!=="building"||e.facade?.openings==="none")return;if(e.facade)return e.facade;const t=e.sizeM?.heightM;return t===void 0?void 0:t-(e.roof?Ki.normalised(e.roof).riseM:0)>=ja?ue.HOUSE_FACADE:void 0}static isBare(e){return e.openings==="plain"||e.plain===!0}static HOUSE_FACADE={};static buildFacade(e){const t=new ii,i=ue.sizeOf(e),s=ue.facadeOf(e),n=s.openings==="tall"||s.openings==="lancet"?s.openings:void 0,r=pp.build(i.widthM,i.lengthM,ue.wallHeightOf(e,i.heightM),!ue.isBare(s),e.eastM*7.31+e.northM*3.17,n,s.storeyM);if(s.closedAtNight){const c=r.getAttribute("litRank");for(let h=0;h<c.count;h++)c.setX(h,c.getX(h)/ue.CLOSED_AT_NIGHT_SHARE)}const a=new ta({color:new oe(s.color??ue.PLASTER),map:Ne.texture(),emissiveMap:Ne.emissive(),emissive:new oe(1,1,1)});a.onBeforeCompile=c=>{c.uniforms.uLitShare=ue.litWindowShare,c.uniforms.uWindowLuminance=ue.windowLuminance,c.vertexShader=`attribute float litRank;
|
|
10942
10942
|
varying float vLitRank;
|
|
10943
10943
|
${c.vertexShader.replace("#include <begin_vertex>",`#include <begin_vertex>
|
|
10944
10944
|
vLitRank = litRank;`)}`,c.fragmentShader=`uniform float uLitShare;
|
|
10945
10945
|
uniform float uWindowLuminance;
|
|
10946
10946
|
varying float vLitRank;
|
|
10947
10947
|
${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissivemap_fragment>
|
|
10948
|
-
totalEmissiveRadiance *= step(vLitRank, uLitShare) * uWindowLuminance * ${ue.WINDOW_VARIETY_GLSL};`)}`},a.customProgramCacheKey=()=>"facade-lit-windows";const o=new Me(r,a);return o.castShadow=!0,o.receiveShadow=!0,t.add(o),t}static CLOSED_AT_NIGHT_SHARE=.2;static litWindowShare={value:0};static WINDOW_LUMINANCE_CD_M2=15;static ROOM_LIGHT_K=2900;static COLD_ROOM_LIGHT_K=4e3;static windowLuminance={value:0};static get WINDOW_VARIETY_GLSL(){const e=s=>`vec3(${s.map(n=>n.toFixed(4)).join(", ")})`,t=Bd.ofTemperature(ue.ROOM_LIGHT_K),i=Bd.ofTemperature(ue.COLD_ROOM_LIGHT_K);return`(mix(0.35, 2.0, fract(vLitRank * 97.13) * fract(vLitRank * 97.13)) * mix(${e(t)}, ${e(i)}, step(0.86, fract(vLitRank * 53.71))))`}static setWindowLuminance(e){ue.windowLuminance.value=ue.WINDOW_LUMINANCE_CD_M2*e}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"?$E(e.floors??Jd,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?XE():e.kind==="shrub"?KE():e.kind==="bridge"?K8(e):e.kind==="wire"?X8(e):e.kind==="wall"?Ps.build(e):e.kind==="crop"?qE():e.kind==="terrace"?t9():e.kind==="mound"?jE():e.kind==="streetlight"?ZE(t,e.lamp?.mount,e.lamp):e.kind==="trafficlight"?
|
|
10948
|
+
totalEmissiveRadiance *= step(vLitRank, uLitShare) * uWindowLuminance * ${ue.WINDOW_VARIETY_GLSL};`)}`},a.customProgramCacheKey=()=>"facade-lit-windows";const o=new Me(r,a);return o.castShadow=!0,o.receiveShadow=!0,t.add(o),t}static CLOSED_AT_NIGHT_SHARE=.2;static litWindowShare={value:0};static WINDOW_LUMINANCE_CD_M2=15;static ROOM_LIGHT_K=2900;static COLD_ROOM_LIGHT_K=4e3;static windowLuminance={value:0};static get WINDOW_VARIETY_GLSL(){const e=s=>`vec3(${s.map(n=>n.toFixed(4)).join(", ")})`,t=Bd.ofTemperature(ue.ROOM_LIGHT_K),i=Bd.ofTemperature(ue.COLD_ROOM_LIGHT_K);return`(mix(0.35, 2.0, fract(vLitRank * 97.13) * fract(vLitRank * 97.13)) * mix(${e(t)}, ${e(i)}, step(0.86, fract(vLitRank * 53.71))))`}static setWindowLuminance(e){ue.windowLuminance.value=ue.WINDOW_LUMINANCE_CD_M2*e}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"?$E(e.floors??Jd,e.windows,e.observerSide,e.occupiedFloor,e.observerFacing):e.kind==="tree"?XE():e.kind==="shrub"?KE():e.kind==="bridge"?K8(e):e.kind==="wire"?X8(e):e.kind==="wall"?Ps.build(e):e.kind==="crop"?qE():e.kind==="terrace"?t9():e.kind==="mound"?jE():e.kind==="streetlight"?ZE(t,e.lamp?.mount,e.lamp):e.kind==="trafficlight"?Rt.trafficLight(gt.isPedestrian(e.lights)):e.kind==="crossing"?Rt.crossing(ue.sizeOf(e).widthM,ue.sizeOf(e).lengthM):e.kind==="roadsign"?Rt.roadSign(e.sign):e.kind==="vehicle"?JE(t,e.windows,e.observerSide,e.observerFacing):e.kind==="aircraft"?n2():e.kind==="entity"?i2():Ly();e.color&&this.paint(i,e.color);const s=this.scaleFor(e),n=new ii;return e.kind==="building"&&e.roof&&this.addRoof(n,e),i.name=ue.BODY_NAME,i.scale.copy(s),n.add(i),e.headingDeg!==void 0&&(n.rotation.y=-e.headingDeg*h1),this.addLights(n,e.lights),ue.fitLights(n,e,e.sizeM??{}),n}static scaleFor(e){const t=e.sizeM;if(!t||ue.hasFacade(e)||e.kind==="bridge"||e.kind==="wire"||e.kind==="terrace"||e.kind==="wall"||e.kind==="crossing")return new D(1,1,1);const i=this.naturalSize(e.kind,e.floors);return new D(t.widthM===void 0?1:f1(t.widthM,i.widthM),t.heightM===void 0?1:f1(e.kind==="building"?this.wallHeightOf(e,t.heightM):t.heightM,i.heightM),t.lengthM===void 0?1:f1(t.lengthM,i.lengthM))}static naturalSize(e,t){const i=e==="building"?Math.max(1,(t??Jd)+1):0;if(e==="bridge")return Ui.NATURAL_SIZE;if(e==="wire")return Bc.NATURAL_SIZE;if(e==="terrace"||e==="wall")return{widthM:1,lengthM:1,heightM:1};if(e==="crossing")return{widthM:6,lengthM:2.5,heightM:Rt.CROSSING_LIFT_M};const s=`${e}:${i}`,n=QE.get(s);if(n)return n;const r=e==="building"?$E(i-1,void 0,void 0,void 0):e==="tree"?XE():e==="shrub"?KE():e==="crop"?qE():e==="mound"?jE():e==="streetlight"?ZE(!1):e==="trafficlight"?Rt.trafficLight(!1):e==="roadsign"?Rt.roadSign(void 0):e==="vehicle"?JE(!1,void 0,void 0):e==="aircraft"?n2():e==="entity"?i2():Ly(),a=new ai().setFromObject(r),o={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),QE.set(s,o),o}static usesModel(e){return ef(e)!==void 0&&!(e.observerSide!==void 0&&ic(e.kind))}static applyModel(e,t,i,s={}){const n=this.bodyOf(e),r=new ii;r.name=ue.BODY_NAME,i.rotation.y=-(s.headingOffsetDeg??0)*h1,i.updateMatrixWorld(!0);const a=new ai().setFromObject(i),o={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=e2(c,o)??e2(s.depictedSizeM,o)??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 Me&&(u.castShadow=!0,u.receiveShadow=!0)}),r.add(i),t.kind==="tree"&&r.add(ue.trunkShadow(o.heightM*h)),n.parent?(n.parent.add(r),n.removeFromParent()):e.add(r),this.dispose(n),ue.fitLights(e,t,{widthM:o.widthM*h,heightM:o.heightM*h,lengthM:o.lengthM*h})}static fitLights(e,t,i){const s=Zd.byId(va.rigOf(t)||void 0)?.referenceSizeM;if(!s||!t.lights)return;const n=(h,d)=>h===void 0||d===0?1:h/d,r=n(i.widthM,s.widthM),a=n(i.heightM,s.heightM),o=n(i.lengthM,s.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*o)})}static trunkShadow(e){ue.trunkProxy??={geometry:new Bn(1,1.15,1,8),material:new ir({colorWrite:!1,depthWrite:!1})};const t=new Me(ue.trunkProxy.geometry,ue.trunkProxy.material),i=Math.min(.3,Math.max(.12,e*.035)),s=e*.45;return t.scale.set(i,s,i),t.position.y=s/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 s=F8(i.color),n=gt.figureOf(i),r=n?Rt.pedestrianFigure(n,1.8*(i.radiusM??d1)):new Rs(i.radiusM??d1,8,6),a=li(e,r,s,i.offsetM.y,!0);a.position.set(i.offsetM.x,i.offsetM.y,i.offsetM.z),a.userData={emissive:!0,lightId:i.id,lightColor:s},a.visible=!1;const o=a.material;tI.apply(o),o.transparent=!0,o.depthWrite=!1,o.fog=!1}}static setLights(e,t,i,s,n=0,r=1,a=R8,o=[1,1,1],c){if(!t||t.length===0)return;const h=new Map(t.map(u=>[u.id,u]));let d;c&&t.some(u=>u.beamDeg!==void 0)&&(e.updateWorldMatrix(!0,!1),d=e.worldToLocal(ue.eyeScratch.copy(c)));for(const u of e.children){if(!(u instanceof Me))continue;const p=u.userData.lightId;if(!p)continue;const f=h.get(p);if(!f)continue;const m=n>0?IT(f,i,i+n):ck(f,i)?1:0,v=d&&f.beamDeg!==void 0?ue.beamShare(f.beamDeg,u.position,d):1;u.visible=m>0&&v>0;const g=f.radiusM??d1,b=Math.max(1,s*a/g),w=g*b,y=r/(Math.PI*w*w),M=u.material,x=u.userData.lightColor;if(x){const E=f.keyframes?.length?Math.max(kd(f,i).intensity,kd(f,i+n).intensity):f.intensity??1,S=m*v*C8*E*y,A=[x[0]*S*o[0],x[1]*S*o[1],x[2]*S*o[2]],T=Math.min(1,VE/Math.max(A[0],A[1],A[2],1e-30));M.color.setRGB(A[0]*T,A[1]*T,A[2]*T)}u.scale.setScalar(b)}}static eyeScratch=new D;static beamShare(e,t,i){const s=i.x-t.x,n=i.y-t.y,r=i.z-t.z,a=Math.hypot(s,n,r);if(a===0)return 1;const o=-r/a;if(o<=0)return 0;const c=Math.log(.5)/Math.log(Math.cos(e*Math.PI/180));return Math.pow(o,c)}static setLit(e,t,i,s=1,n){const[r,a,o]=t==="streetlight"?[L8*ue.lampShare(n),O8,ue.lampHue(n)]:[P8,N8,sI],c=i?r*s/(Math.PI*a*a):0,h=Math.min(1,VE/Math.max(o[0]*c,o[1]*c,o[2]*c,1e-30)),d=[o[0]*c*h,o[1]*c*h,o[2]*c*h];e.traverse(u=>{const p=u.userData;!(u instanceof Me)||!p.emissive||p.lightId||(u.material instanceof ta?u.material.emissive.setRGB(...d):u.material.color.setRGB(...d))})}static REFERENCE_LUMENS=1e4;static lampShare(e){return e?.lumens?e.lumens/ue.REFERENCE_LUMENS:1}static lampHue(e){return e?.colorTemperatureK?Bd.ofTemperature(e.colorTemperatureK):B8}static dispose(e){e.traverse(t=>{if(!(t instanceof Me))return;if(t.userData.sharedModel){for(const s of t.userData.tintedMaterials??[])s.dispose();return}t.geometry.dispose();const i=t.material;for(const s of Array.isArray(i)?i:[i])s.dispose()})}}class fr{static MATERIAL_NAME="Mirror";static REFLECTANCE=.85;static SIZE=512;static NEAR_M=12;static INTERVAL_MS=30;mirrors=[];drawnAtMs=-1/0;camera=new vn;eye=new D;centre=new D;normal=new D;image=new D;up=new D;normalMatrix=new bt;plane=new ma;clip=new Lt;q=new Lt;bias=new qe().set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1);get any(){return this.mirrors.length>0}adopt(e){e.traverse(t=>{const i=t;if(!i.isMesh||Array.isArray(i.material)||i.material.name!==fr.MATERIAL_NAME||this.mirrors.some(a=>a.mesh===i))return;const s=fr.flatten(i.geometry);if(!s)return;const n=new oi(fr.SIZE,fr.SIZE,{type:ti,minFilter:St,magFilter:St}),r=new Nt({name:fr.MATERIAL_NAME,uniforms:{uReflection:{value:n.texture},uTextureMatrix:{value:new qe},uReflectance:{value:fr.REFLECTANCE}},vertexShader:`
|
|
10949
10949
|
uniform mat4 uTextureMatrix;
|
|
10950
10950
|
varying vec4 vUv;
|
|
10951
10951
|
void main() {
|
|
@@ -10998,7 +10998,7 @@ ${c.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
10998
10998
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
10999
10999
|
}
|
|
11000
11000
|
`,transparent:!0,depthWrite:!1,side:$s,fog:!1,blending:ih,blendSrc:sh,blendDst:rf})}static wallReflectance(e,t,i){const s=i(e,1,t);return 2*s/(1+s)}setSurroundings(e){this.uniforms.uSurroundings.value=e}static reflectedResponse(e,t){return Ve.respond(t*Ve.relativeOfResponse(Math.max(e,1e-5)))}}class hr{static SIZE=64;static MOVE_M=.01;holder=new Qi;cameras=[];faces=[];target=new oi(hr.SIZE,hr.SIZE);white=new ir({color:new oe(1,1,1),side:$s});scene=new Fr;cabin;meshes=0;eye=new D;scratch=new D;constructor(){const e=[[new D(1,0,0),new D(0,1,0)],[new D(-1,0,0),new D(0,1,0)],[new D(0,1,0),new D(0,0,1)],[new D(0,-1,0),new D(0,0,-1)],[new D(0,0,1),new D(0,1,0)],[new D(0,0,-1),new D(0,1,0)]];for(const[t,i]of e){const s=new vn(90,1,.02,20);s.up.copy(i),s.lookAt(t),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(hr.SIZE*hr.SIZE*4))}this.scene.background=new oe(0,0,0)}get any(){return this.cabin!==void 0}update(e,t,i){if(!t){this.forget();return}t.updateWorldMatrix(!0,!0);const s=this.scratch.copy(i);t.worldToLocal(s);let n=0;t.traverse(r=>{r.isMesh&&n++}),!(t===this.cabin&&n===this.meshes&&s.distanceTo(this.eye)<hr.MOVE_M)&&(this.cabin=t,this.meshes=n,this.eye.copy(s),this.draw(e,t))}hides(e){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let t=0;t<6;t++){const i=this.cameras[t],s=this.scratch.copy(e).transformDirection(i.matrixWorldInverse);if(s.z>=0)continue;const n=s.x/-s.z,r=s.y/-s.z;if(Math.abs(n)>1||Math.abs(r)>1)continue;const a=Math.min(hr.SIZE-1,Math.floor((n+1)/2*hr.SIZE)),o=Math.min(hr.SIZE-1,Math.floor((r+1)/2*hr.SIZE));return this.faces[t][(o*hr.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(e,t){t.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];t.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof qo))return;const c=new Me(a.geometry,this.white);c.matrixAutoUpdate=!1,c.matrix.copy(a.matrixWorld),c.matrixWorld.copy(a.matrixWorld),i.push(c)});for(const r of i)this.scene.add(r);const s=e.getRenderTarget(),n=e.shadowMap.autoUpdate;e.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),e.setRenderTarget(this.target),e.clear(),e.render(this.scene,a),e.readRenderTargetPixels(this.target,0,0,hr.SIZE,hr.SIZE,this.faces[r])}e.setRenderTarget(s),e.shadowMap.autoUpdate=n;for(const r of i)r.removeFromParent()}}const g1="https://ufoathome.org/models/index.json";class fp{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??r9()}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(`
|
|
11001
|
-
`);let t=fp.shared.get(e);return t||(t=this.fetchFirstAvailable(),fp.shared.set(e,t),t.then(i=>{i.length===0&&fp.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:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function r9(){const l=`?v=${encodeURIComponent("0.170.
|
|
11001
|
+
`);let t=fp.shared.get(e);return t||(t=this.fetchFirstAvailable(),fp.shared.set(e,t),t.then(i=>{i.length===0&&fp.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:s,...n})=>({...n,url:new URL(s,e).href})):void 0}catch{return}}}function r9(){const l=`?v=${encodeURIComponent("0.170.1")}`,e=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(e&&e!==g1?[e,g1]:[g1]).map(t=>t+l)}const Oy=Ye.point("decorModels").provide(Ye.BUILT_IN,[{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 fp}]);class mp{constructor(e,t=Oy){this.preferredId=e,this.sources=t}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const e=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(e?[e,...this.sources.filter(i=>i!==e)]:[]).map(i=>{let s=this.built.get(i);return s||(s=i.create(),this.built.set(i,s)),s})}entries(e){const t=this.catalogues()[0];return t?t.entries(e):Promise.resolve([])}async entry(e){for(const t of this.catalogues()){const i=await t.entry(e).catch(()=>{});if(i)return i}}async moduleOf(e){const t=Ye.point("decorModels");for(const i of this.sources){const s=t.ownerOf(i.id);if(!(s===void 0||s===Ye.BUILT_IN)&&await this.catalogueOf(i).entry(e).catch(()=>{}))return s}}catalogueOf(e){return this.catalogues(),this.built.get(e)}}async function v1(l){const{GLTFLoader:e}=await Q(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-DQ9JYWIM.js");return{GLTFLoader:i}},[],import.meta.url),t=new e;return new Promise((i,s)=>{t.load(l,n=>i(Object.assign(n.scene,{animations:n.animations})),void 0,n=>s(new Error(`Could not load 3D model ${l}: ${n instanceof Error?n.message:String(n)}`)))})}class Cr{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(e,t){this.mesh=new Me(new zn(2,2),new Nt({uniforms:{uColor:{value:new oe(0,0,0)},uRadius:{value:1}},vertexShader:Cr.VERTEX,fragmentShader:Cr.FRAGMENT,transparent:!0,depthWrite:!1,blending:qs,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,s){const n=Math.max(e,s*Cr.MIN_ANGLE_RAD),r=Cr.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(Cr.MAX_SHARE,t/r)}}static conserving(e){return Math.sqrt(e/(Cr.MAX_SHARE*Cr.FILL*Math.PI))}static VERTEX=`
|
|
11002
11002
|
uniform float uRadius;
|
|
11003
11003
|
varying vec2 vOffset;
|
|
11004
11004
|
void main() {
|
|
@@ -11607,7 +11607,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
11607
11607
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
11608
11608
|
gl_FragColor = vec4(light, 1.0);
|
|
11609
11609
|
}
|
|
11610
|
-
`,transparent:!0,blending:qs,depthWrite:!1,side:Ji,fog:!1});this.object=new Me(new Rs(jw.RADIUS,128,32,0,Math.PI*2,0,$t.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<$t.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=ln.toHalfFloat(Math.min(t[i*3+s],6e4));this.texels[i*4+3]=ln.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class lg{constructor(e){this.generator=e}static SIZE=128;target=new pf(lg.SIZE,{type:ti,generateMipmaps:!0,minFilter:Nr,magFilter:St});camera=new $w(.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,s=[]){const n=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const c=o;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?n:!1;const a=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),s.forEach((o,c)=>{o.visible=a[c]}),e.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class kn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){kn.install(),this.generator=new wy(e),this.eye=new lg(this.generator)}static decor;refresh(e,t,i,s,n,r,a,o=[],c,h=kn.REFRESH_MS){for(const v of[...this.probes.keys()])s.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of s){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new lg(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,b)=>b.probe.capturedAtMs<g.probe.capturedAtMs?b:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...n]),kn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...n,...o]),c?.(v.probe.sharp),kn.decor=v.probe.filtered;for(const g of r)kn.reflectOn(g,v.probe);for(const g of s)g.shiny||kn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:kn.decor}){e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof qo?t.sharp&&n.setSurroundings(t.sharp):n instanceof Cl&&t.filtered&&n.envMap!==t.filtered&&(n.envMap=t.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(kn.installed)return;kn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!vt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}vt.lights_fragment_maps=vt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const pI=0,l9=1,c9=2,a2=2,b1=1.25,o2=1,Nn=32,Ks=Nn/4,fI=65535,m0=Math.pow(2,-24),Zw=Symbol("SKIP_GENERATION"),mI={strategy:pI,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Zw]:!1};function ws(l,e,t){return t.min.x=e[l],t.min.y=e[l+1],t.min.z=e[l+2],t.max.x=e[l+3],t.max.y=e[l+4],t.max.z=e[l+5],t}function Ny(l){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=l[i+3]-l[i];s>t&&(t=s,e=i)}return e}function l2(l,e){e.set(l)}function c2(l,e,t){let i,s;for(let n=0;n<3;n++){const r=n+3;i=l[n],s=e[n],t[n]=i<s?i:s,i=l[r],s=e[r],t[r]=i>s?i:s}}function wm(l,e,t){for(let i=0;i<3;i++){const s=e[l+2*i],n=e[l+2*i+1],r=s-n,a=s+n;r<t[i]&&(t[i]=r),a>t[i+3]&&(t[i+3]=a)}}function Ou(l){const e=l[3]-l[0],t=l[4]-l[1],i=l[5]-l[2];return 2*(e*t+t*i+i*e)}function Ds(l,e){return e[l+15]===fI}function cn(l,e){return e[l+6]}function Fn(l,e){return e[l+14]}function Xs(l){return l+Ks}function Ys(l,e){const t=e[l+6];return l+t*Ks}function Jw(l,e){return e[l+7]}function y1(l,e,t,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,v=-1/0;const g=l.offset||0;for(let b=(e-g)*6,w=(e+t-g)*6;b<w;b+=6){const y=l[b+0],M=l[b+1],x=y-M,E=y+M;x<n&&(n=x),E>o&&(o=E),y<d&&(d=y),y>f&&(f=y);const S=l[b+2],A=l[b+3],T=S-A,_=S+A;T<r&&(r=T),_>c&&(c=_),S<u&&(u=S),S>m&&(m=S);const k=l[b+4],L=l[b+5],P=k-L,C=k+L;P<a&&(a=P),C>h&&(h=C),k<p&&(p=k),k>v&&(v=k)}i[0]=n,i[1]=r,i[2]=a,i[3]=o,i[4]=c,i[5]=h,s[0]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=v}const _o=32,h9=(l,e)=>l.candidate-e.candidate,ml=new Array(_o).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Mm=new Float32Array(6);function d9(l,e,t,i,s,n){let r=-1,a=0;if(n===pI)r=Ny(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(n===l9)r=Ny(l),r!==-1&&(a=u9(t,i,s,r));else if(n===c9){const o=Ou(l);let c=b1*s;const h=t.offset||0,d=(i-h)*6,u=(i+s-h)*6;for(let p=0;p<3;p++){const f=e[p],g=(e[p+3]-f)/_o;if(s<_o/4){const b=[...ml];b.length=s;let w=0;for(let M=d;M<u;M+=6,w++){const x=b[w];x.candidate=t[M+2*p],x.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=x;for(let T=0;T<3;T++)A[T]=1/0,A[T+3]=-1/0,S[T]=1/0,S[T+3]=-1/0,E[T]=1/0,E[T+3]=-1/0;wm(M,t,E)}b.sort(h9);let y=s;for(let M=0;M<y;M++){const x=b[M];for(;M+1<y&&b[M+1].candidate===x.candidate;)b.splice(M+1,1),y--}for(let M=d;M<u;M+=6){const x=t[M+2*p];for(let E=0;E<y;E++){const S=b[E];x>=S.candidate?wm(M,t,S.rightCacheBounds):(wm(M,t,S.leftCacheBounds),S.count++)}}for(let M=0;M<y;M++){const x=b[M],E=x.count,S=s-x.count,A=x.leftCacheBounds,T=x.rightCacheBounds;let _=0;E!==0&&(_=Ou(A)/o);let k=0;S!==0&&(k=Ou(T)/o);const L=o2+b1*(_*E+k*S);L<c&&(r=p,c=L,a=x.candidate)}}else{for(let y=0;y<_o;y++){const M=ml[y];M.count=0,M.candidate=f+g+y*g;const x=M.bounds;for(let E=0;E<3;E++)x[E]=1/0,x[E+3]=-1/0}for(let y=d;y<u;y+=6){let E=~~((t[y+2*p]-f)/g);E>=_o&&(E=_o-1);const S=ml[E];S.count++,wm(y,t,S.bounds)}const b=ml[_o-1];l2(b.bounds,b.rightCacheBounds);for(let y=_o-2;y>=0;y--){const M=ml[y],x=ml[y+1];c2(M.bounds,x.rightCacheBounds,M.rightCacheBounds)}let w=0;for(let y=0;y<_o-1;y++){const M=ml[y],x=M.count,E=M.bounds,A=ml[y+1].rightCacheBounds;x!==0&&(w===0?l2(E,Mm):c2(E,Mm,Mm)),w+=x;let T=0,_=0;w!==0&&(T=Ou(Mm)/o);const k=s-w;k!==0&&(_=Ou(A)/o);const L=o2+b1*(T*w+_*k);L<c&&(r=p,c=L,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:r,pos:a}}function u9(l,e,t,i){let s=0;const n=l.offset;for(let r=e,a=e+t;r<a;r++)s+=l[(r-n)*6+i*2];return s/t}class w1{constructor(){this.boundingData=new Float32Array(6)}}function p9(l,e,t,i,s,n){let r=i,a=i+s-1;const o=n.pos,c=n.axis*2,h=t.offset||0;for(;;){for(;r<=a&&t[(r-h)*6+c]<o;)r++;for(;r<=a&&t[(a-h)*6+c]>=o;)a--;if(r<a){for(let d=0;d<e;d++){let u=l[r*e+d];l[r*e+d]=l[a*e+d],l[a*e+d]=u}for(let d=0;d<6;d++){const u=r-h,p=a-h,f=t[u*6+d];t[u*6+d]=t[p*6+d],t[p*6+d]=f}r++,a--}else return r}}let gI,g0,Fy,vI;const f9=Math.pow(2,32);function Uy(l){return"count"in l?1:1+Uy(l.left)+Uy(l.right)}function m9(l,e,t){return gI=new Float32Array(t),g0=new Uint32Array(t),Fy=new Uint16Array(t),vI=new Uint8Array(t),By(l,e)}function By(l,e){const t=l/4,i=l/2,s="count"in e,n=e.boundingData;for(let r=0;r<6;r++)gI[t+r]=n[r];if(s)return e.buffer?(vI.set(new Uint8Array(e.buffer),l),l+e.buffer.byteLength):(g0[t+6]=e.offset,Fy[i+14]=e.count,Fy[i+15]=fI,l+Nn);{const{left:r,right:a,splitAxis:o}=e,c=l+Nn;let h=By(c,r);const d=l/Nn,p=h/Nn-d;if(p>f9)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return g0[t+6]=p,g0[t+7]=o,By(h,a)}}function g9(l,e,t,i,s,n){const{maxDepth:r,verbose:a,targetLeafSize:o,_strictLeafSize:c=1/0,strategy:h,onProgress:d}=s,u=l.primitiveBuffer,p=l.primitiveBufferStride,f=new Float32Array(6);let m=!1;const v=new w1;return y1(e,t,i,v.boundingData,f),b(v,t,i,f),v;function g(w){d&&d((w-n.offset)/n.count)}function b(w,y,M,x=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=M>c;if(M<=o&&!S||E>=r)return g(y+M),w.offset=y,w.count=M,w;const A=d9(w.boundingData,x,e,y,M,h);let T=A.axis===-1?-1:p9(u,p,e,y,M,A);if(A.axis===-1||T===y||T===y+M){if(!S)return g(y+M),w.offset=y,w.count=M,w;A.axis=Math.max(0,Ny(w.boundingData)),T=y+Math.max(1,Math.floor(M/2))}w.splitAxis=A.axis;const _=new w1,k=y,L=T-y;w.left=_,y1(e,k,L,_.boundingData,f),b(_,k,L,f,E+1);const P=new w1,C=T,N=M-L;return w.right=P,y1(e,C,N,P.boundingData,f),b(P,C,N,f,E+1),w}}function v9(l,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=l.getRootRanges(e.range),s=i[0],n=i[i.length-1],r={offset:s.offset,count:n.offset+n.count-s.offset},a=new Float32Array(6*r.count);a.offset=r.offset,l.computePrimitiveBounds(r.offset,r.count,a),l._roots=i.map(o=>{const c=g9(l,a,o.offset,o.count,e,r),h=Uy(c),d=new t(Nn*h);return m9(0,c,d),d})}class Qw{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class b9{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const es=new b9;let Xl,vd;const Bh=[],xm=new Qw(()=>new ai);function y9(l,e,t,i,s,n){Xl=xm.getPrimitive(),vd=xm.getPrimitive(),Bh.push(Xl,vd),es.setBuffer(l._roots[e]);const r=zy(0,l.geometry,t,i,s,n);es.clearBuffer(),xm.releasePrimitive(Xl),xm.releasePrimitive(vd),Bh.pop(),Bh.pop();const a=Bh.length;return a>0&&(vd=Bh[a-1],Xl=Bh[a-2]),r}function zy(l,e,t,i,s=null,n=0,r=0){const{float32Array:a,uint16Array:o,uint32Array:c}=es;let h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);return ws(l,a,Xl),i(u,p,!1,r,n+l/Ks,Xl)}else{let T=function(k){const{uint16Array:L,uint32Array:P}=es;let C=k*2;for(;!Ds(C,L);)k=Xs(k),C=k*2;return cn(k,P)},_=function(k){const{uint16Array:L,uint32Array:P}=es;let C=k*2;for(;!Ds(C,L);)k=Ys(k,P),C=k*2;return cn(k,P)+Fn(C,L)};const u=Xs(l),p=Ys(l,c);let f=u,m=p,v,g,b,w;if(s&&(b=Xl,w=vd,ws(f,a,b),ws(m,a,w),v=s(b),g=s(w),g<v)){f=p,m=u;const k=v;v=g,g=k,b=w}b||(b=Xl,ws(f,a,b));const y=Ds(f*2,o),M=t(b,y,v,r+1,n+f/Ks);let x;if(M===a2){const k=T(f),P=_(f)-k;x=i(k,P,!0,r+1,n+f/Ks,b)}else x=M&&zy(f,e,t,i,s,n,r+1);if(x)return!0;w=vd,ws(m,a,w);const E=Ds(m*2,o),S=t(w,E,g,r+1,n+m/Ks);let A;if(S===a2){const k=T(m),P=_(m)-k;A=i(k,P,!0,r+1,n+m/Ks,w)}else A=S&&zy(m,e,t,i,s,n,r+1);return!!A}}const vp=new es.constructor,cg=new es.constructor,Il=new Qw(()=>new ai),zh=new ai,Hh=new ai,M1=new ai,x1=new ai;let S1=!1;function w9(l,e,t,i){if(S1)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");S1=!0;const s=l._roots,n=e._roots;let r,a=0,o=0;const c=new qe().copy(t).invert();for(let h=0,d=s.length;h<d;h++){vp.setBuffer(s[h]),o=0;const u=Il.getPrimitive();ws(0,vp.float32Array,u),u.applyMatrix4(c);for(let p=0,f=n.length;p<f&&(cg.setBuffer(n[p]),r=ra(0,0,t,c,i,a,o,0,0,u),cg.clearBuffer(),o+=n[p].byteLength/Nn,!r);p++);if(Il.releasePrimitive(u),vp.clearBuffer(),a+=s[h].byteLength/Nn,r)break}return S1=!1,r}function ra(l,e,t,i,s,n=0,r=0,a=0,o=0,c=null,h=!1){let d,u;h?(d=cg,u=vp):(d=vp,u=cg);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,v=u.float32Array,g=u.uint32Array,b=u.uint16Array,w=l*2,y=e*2,M=Ds(w,m),x=Ds(y,b);let E=!1;if(x&&M)h?E=s(cn(e,g),Fn(e*2,b),cn(l,f),Fn(l*2,m),o,r+e/Ks,a,n+l/Ks):E=s(cn(l,f),Fn(l*2,m),cn(e,g),Fn(e*2,b),a,n+l/Ks,o,r+e/Ks);else if(x){const S=Il.getPrimitive();ws(e,v,S),S.applyMatrix4(t);const A=Xs(l),T=Ys(l,f);ws(A,p,zh),ws(T,p,Hh);const _=S.intersectsBox(zh),k=S.intersectsBox(Hh);E=_&&ra(e,A,i,t,s,r,n,o,a+1,S,!h)||k&&ra(e,T,i,t,s,r,n,o,a+1,S,!h),Il.releasePrimitive(S)}else{const S=Xs(e),A=Ys(e,g);ws(S,v,M1),ws(A,v,x1);const T=c.intersectsBox(M1),_=c.intersectsBox(x1);if(T&&_)E=ra(l,S,t,i,s,n,r,a,o+1,c,h)||ra(l,A,t,i,s,n,r,a,o+1,c,h);else if(T)if(M)E=ra(l,S,t,i,s,n,r,a,o+1,c,h);else{const k=Il.getPrimitive();k.copy(M1).applyMatrix4(t);const L=Xs(l),P=Ys(l,f);ws(L,p,zh),ws(P,p,Hh);const C=k.intersectsBox(zh),N=k.intersectsBox(Hh);E=C&&ra(S,L,i,t,s,r,n,o,a+1,k,!h)||N&&ra(S,P,i,t,s,r,n,o,a+1,k,!h),Il.releasePrimitive(k)}else if(_)if(M)E=ra(l,A,t,i,s,n,r,a,o+1,c,h);else{const k=Il.getPrimitive();k.copy(x1).applyMatrix4(t);const L=Xs(l),P=Ys(l,f);ws(L,p,zh),ws(P,p,Hh);const C=k.intersectsBox(zh),N=k.intersectsBox(Hh);E=C&&ra(A,L,i,t,s,r,n,o,a+1,k,!h)||N&&ra(A,P,i,t,s,r,n,o,a+1,k,!h),Il.releasePrimitive(k)}}return E}const E1=new class{constructor(){let l=null,e=null,t=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=l=n._roots[r],this.uint16Array=t=new Uint16Array(l),this.uint32Array=e=new Uint32Array(l)},this.reset=()=>{this.root=null,this.buffer=l=null,this.uint16Array=t=null,this.uint32Array=e=null},this.getRangeStart=n=>{let r=n*2;for(;!Ds(r,t);)n=Xs(n),r=n*2;return cn(n,e)},this.getRangeEnd=n=>{let r=n*2;for(;!Ds(r,t);)n=Ys(n,e),r=n*2;return cn(n,e)+Fn(r,t)};const s=(n,r,a)=>{const o=r*2,c=Ds(o,t);if(!n(a,c,r)&&!c){const d=Xs(r),u=Ys(r,e);s(n,d,a+1),s(n,u,a+1)}};this.traverseBuffer=n=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{s(n,0,0)}finally{i=!1}},this.traverse=n=>{this.traverseBuffer((r,a,o)=>{if(a){const c=o*2,h=e[o+6],d=t[c+14];return n(r,a,new Float32Array(l,o*4,6),h,d)}else{const c=Jw(o,e);return n(r,a,new Float32Array(l,o*4,6),c)}})}}},h2=new ai,Gh=new Float32Array(6);class M9{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...mI,...e},"maxLeafSize"in e&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafSize}),v9(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0;for(let d=e,u=e+t;d<u;d++){this.writePrimitiveBounds(d,Gh,0);const[p,f,m,v,g,b]=Gh;p<n&&(n=p),v>o&&(o=v),f<r&&(r=f),g>c&&(c=g),m<a&&(a=m),b>h&&(h=b)}return i[s+0]=n,i[s+1]=r,i[s+2]=a,i[s+3]=o,i[s+4]=c,i[s+5]=h,i}computePrimitiveBounds(e,t,i){const s=i.offset||0;for(let n=e,r=e+t;n<r;n++){this.writePrimitiveBounds(n,Gh,0);const[a,o,c,h,d,u]=Gh,p=(a+h)/2,f=(o+d)/2,m=(c+u)/2,v=(h-a)/2,g=(d-o)/2,b=(u-c)/2,w=(n-s)*6;i[w+0]=p,i[w+1]=v+(Math.abs(p)+v)*m0,i[w+2]=f,i[w+3]=g+(Math.abs(f)+g)*m0,i[w+4]=m,i[w+5]=b+(Math.abs(m)+b)*m0}return i}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const n=i[s],r=new Uint32Array(n),a=new Uint16Array(n),o=n.byteLength/Nn;for(let c=0;c<o;c++){const h=Ks*c,d=2*h;Ds(d,a)&&(r[h+6]+=e)}}}}traverse(e,t=0){E1.setBVH(this,t),E1.traverse(e),E1.reset()}refit(){const e=this._roots;for(let t=0,i=e.length;t<i;t++){const s=e[t],n=new Uint32Array(s),r=new Uint16Array(s),a=new Float32Array(s),o=s.byteLength/Nn;for(let c=o-1;c>=0;c--){const h=c*Ks,d=h*2;if(Ds(d,r)){const p=cn(h,n),f=Fn(d,r);this.writePrimitiveRangeBounds(p,f,Gh,0),a.set(Gh,h)}else{const p=Xs(h),f=Ys(h,n);for(let m=0;m<3;m++){const v=a[p+m],g=a[p+m+3],b=a[f+m],w=a[f+m+3];a[h+m]=v<b?v:b,a[h+m+3]=g>w?g:w}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{ws(0,new Float32Array(i),h2),e.union(h2)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:n,scratchPrimitive:r,iterate:a}=e;if(s&&n){const d=s;s=(u,p,f,m,v)=>d(u,p,f,m,v)?!0:a(u,p,this,n,f,m,r)}else s||(n?s=(d,u,p,f)=>a(d,u,this,n,p,f,r):s=(d,u,p)=>p);let o=!1,c=0;const h=this._roots;for(let d=0,u=h.length;d<u;d++){const p=h[d];if(o=y9(this,d,i,s,t,c),o)break;c+=p.byteLength/Nn}return o}bvhcast(e,t,i){let{intersectsRanges:s}=i;return w9(this,e,t,s)}}function x9(){return typeof SharedArrayBuffer<"u"}function eM(l){return l.index?l.index.count:l.attributes.position.count}function Xg(l){return eM(l)/3}function S9(l,e=ArrayBuffer){return l>65535?new Uint32Array(new e(4*l)):new Uint16Array(new e(2*l))}function E9(l,e){if(!l.index){const t=l.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=S9(t,i);l.setIndex(new Et(s,1));for(let n=0;n<t;n++)s[n]=n}}function A9(l,e,t){const i=eM(l)/t,s=e||l.drawRange,n=s.start/t,r=(s.start+s.count)/t,a=Math.max(0,n),o=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(o)}}function T9(l,e){return l.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function d2(l,e,t){const i=A9(l,e,t),s=T9(l,t);if(!s.length)return[i];const n=[],r=i.offset,a=i.offset+i.count,o=eM(l)/t,c=[];for(const u of s){const{offset:p,count:f}=u,m=p,v=isFinite(f)?f:o-p,g=p+v;m<a&&g>r&&(c.push({pos:Math.max(r,m),isStart:!0}),c.push({pos:Math.min(a,g),isStart:!1}))}c.sort((u,p)=>u.pos!==p.pos?u.pos-p.pos:u.type==="end"?-1:1);let h=0,d=null;for(const u of c){const p=u.pos;h!==0&&p!==d&&n.push({offset:d,count:p-d}),h+=u.isStart?1:-1,d=p}return n}function I9(l,e){const t=l[l.length-1],i=t.offset+t.count>2**16,s=l.reduce((c,h)=>c+h.count,0),n=i?4:2,r=e?new SharedArrayBuffer(s*n):new ArrayBuffer(s*n),a=i?new Uint32Array(r):new Uint16Array(r);let o=0;for(let c=0;c<l.length;c++){const{offset:h,count:d}=l[c];for(let u=0;u<d;u++)a[o+u]=h+u;o+=d}return a}class _9 extends M9{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!x9())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...mI,...t},t[Zw]||this.init(t)}init(e){const{geometry:t,primitiveStride:i}=this;if(e.indirect){const s=d2(t,e.range,i),n=I9(s,e.useSharedArrayBuffer);this._indirectBuffer=n}else E9(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new ai))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:d2(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class el{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let n=0,r=e.length;n<r;n++){const o=e[n][t];i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let n=0,r=t.length;n<r;n++){const a=t[n],o=e.dot(a);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}el.prototype.setFromBox=(function(){const l=new D;return function(t,i){const s=i.min,n=i.max;let r=1/0,a=-1/0;for(let o=0;o<=1;o++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){l.x=s.x*o+n.x*(1-o),l.y=s.y*c+n.y*(1-c),l.z=s.z*h+n.z*(1-h);const d=t.dot(l);r=Math.min(d,r),a=Math.max(d,a)}this.min=r,this.max=a}})();const D9=(function(){const l=new D,e=new D,t=new D;return function(s,n,r){const a=s.start,o=l,c=n.start,h=e;t.subVectors(a,c),l.subVectors(s.end,s.start),e.subVectors(n.end,n.start);const d=t.dot(h),u=h.dot(o),p=h.dot(h),f=t.dot(o),v=o.dot(o)*p-u*u;let g,b;v!==0?g=(d*u-f*p)/v:g=0,b=(d+g*u)/p,r.x=g,r.y=b}})(),tM=(function(){const l=new ie,e=new D,t=new D;return function(s,n,r,a){D9(s,n,l);let o=l.x,c=l.y;if(o>=0&&o<=1&&c>=0&&c<=1){s.at(o,r),n.at(c,a);return}else if(o>=0&&o<=1){c<0?n.at(0,a):n.at(1,a),s.closestPointToPoint(a,!0,r);return}else if(c>=0&&c<=1){o<0?s.at(0,r):s.at(1,r),n.closestPointToPoint(r,!0,a);return}else{let h;o<0?h=s.start:h=s.end;let d;c<0?d=n.start:d=n.end;const u=e,p=t;if(s.closestPointToPoint(d,!0,e),n.closestPointToPoint(h,!0,t),u.distanceToSquared(d)<=p.distanceToSquared(h)){r.copy(u),a.copy(d);return}else{r.copy(h),a.copy(p);return}}}})(),k9=(function(){const l=new D,e=new D,t=new ma,i=new Jo;return function(n,r){const{radius:a,center:o}=n,{a:c,b:h,c:d}=r;if(i.start=c,i.end=h,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a||(i.start=c,i.end=d,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a)||(i.start=h,i.end=d,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a))return!0;const m=r.getPlane(t);if(Math.abs(m.distanceToPoint(o))<=a){const g=m.projectPoint(o,e);if(r.containsPoint(g))return!0}return!1}})(),R9=["x","y","z"],Ro=1e-15,u2=Ro*Ro;function Gr(l){return Math.abs(l)<Ro}class Sa extends on{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new D),this.satBounds=new Array(4).fill().map(()=>new el),this.points=[this.a,this.b,this.c],this.plane=new ma,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Jo,this.needsUpdate=!0}intersectsSphere(e){return k9(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,n=this.satAxes,r=this.satBounds,a=n[0],o=r[0];this.getNormal(a),o.setFromPoints(a,s);const c=n[1],h=r[1];c.subVectors(e,t),h.setFromPoints(c,s);const d=n[2],u=r[2];d.subVectors(t,i),u.setFromPoints(d,s);const p=n[3],f=r[3];p.subVectors(i,e),f.setFromPoints(p,s);const m=c.length(),v=d.length(),g=p.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Ro?v<Ro||g<Ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):v<Ro?g<Ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<Ro&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Sa.prototype.closestPointToSegment=(function(){const l=new D,e=new D,t=new Jo;return function(s,n=null,r=null){const{start:a,end:o}=s,c=this.points;let h,d=1/0;for(let u=0;u<3;u++){const p=(u+1)%3;t.start.copy(c[u]),t.end.copy(c[p]),tM(t,s,l,e),h=l.distanceToSquared(e),h<d&&(d=h,n&&n.copy(l),r&&r.copy(e))}return this.closestPointToPoint(a,l),h=a.distanceToSquared(l),h<d&&(d=h,n&&n.copy(l),r&&r.copy(a)),this.closestPointToPoint(o,l),h=o.distanceToSquared(l),h<d&&(d=h,n&&n.copy(l),r&&r.copy(o)),Math.sqrt(d)}})();Sa.prototype.intersectsTriangle=(function(){const l=new Sa,e=new el,t=new el,i=new D,s=new D,n=new D,r=new D,a=new Jo,o=new Jo,c=new D,h=new ie,d=new ie;function u(w,y,M,x){const E=i;!w.isDegenerateIntoPoint&&!w.isDegenerateIntoSegment?E.copy(w.plane.normal):E.copy(y.plane.normal);const S=w.satBounds,A=w.satAxes;for(let k=1;k<4;k++){const L=S[k],P=A[k];if(e.setFromPoints(P,y.points),L.isSeparated(e)||(r.copy(E).cross(P),e.setFromPoints(r,w.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}const T=y.satBounds,_=y.satAxes;for(let k=1;k<4;k++){const L=T[k],P=_[k];if(e.setFromPoints(P,w.points),L.isSeparated(e)||(r.crossVectors(E,P),e.setFromPoints(r,w.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}return M&&(x||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function p(w,y,M,x,E,S,A,T,_,k,L){let P=A/(A-T);k.x=x+(E-x)*P,L.start.subVectors(y,w).multiplyScalar(P).add(w),P=A/(A-_),k.y=x+(S-x)*P,L.end.subVectors(M,w).multiplyScalar(P).add(w)}function f(w,y,M,x,E,S,A,T,_,k,L){if(E>0)p(w.c,w.a,w.b,x,y,M,_,A,T,k,L);else if(S>0)p(w.b,w.a,w.c,M,y,x,T,A,_,k,L);else if(T*_>0||A!=0)p(w.a,w.b,w.c,y,M,x,A,T,_,k,L);else if(T!=0)p(w.b,w.a,w.c,M,y,x,T,A,_,k,L);else if(_!=0)p(w.c,w.a,w.b,x,y,M,_,A,T,k,L);else return!0;return!1}function m(w,y,M,x){const E=y.degenerateSegment,S=w.plane.distanceToPoint(E.start),A=w.plane.distanceToPoint(E.end);return Gr(S)?Gr(A)?u(w,y,M,x):(M&&(M.start.copy(E.start),M.end.copy(E.start)),w.containsPoint(E.start)):Gr(A)?(M&&(M.start.copy(E.end),M.end.copy(E.end)),w.containsPoint(E.end)):w.plane.intersectLine(E,i)!=null?(M&&(M.start.copy(i),M.end.copy(i)),w.containsPoint(i)):!1}function v(w,y,M){const x=y.a;return Gr(w.plane.distanceToPoint(x))&&w.containsPoint(x)?(M&&(M.start.copy(x),M.end.copy(x)),!0):!1}function g(w,y,M){const x=w.degenerateSegment,E=y.a;return x.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<u2?(M&&(M.start.copy(E),M.end.copy(E)),!0):!1}function b(w,y,M,x){if(w.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=w.degenerateSegment,S=y.degenerateSegment,A=s,T=n;E.delta(A),S.delta(T);const _=i.subVectors(S.start,E.start),k=A.x*T.y-A.y*T.x;if(Gr(k))return!1;const L=(_.x*T.y-_.y*T.x)/k,P=-(A.x*_.y-A.y*_.x)/k;if(L<0||L>1||P<0||P>1)return!1;const C=E.start.z+A.z*L,N=S.start.z+T.z*P;return Gr(C-N)?(M&&(M.start.copy(E.start).addScaledVector(A,L),M.end.copy(E.start).addScaledVector(A,L)),!0):!1}else return y.isDegenerateIntoPoint?g(w,y,M):m(y,w,M,x);else{if(w.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(w.a)<u2?(M&&(M.start.copy(w.a),M.end.copy(w.a)),!0):!1:y.isDegenerateIntoSegment?g(y,w,M):v(y,w,M);if(y.isDegenerateIntoPoint)return v(w,y,M);if(y.isDegenerateIntoSegment)return m(w,y,M,x)}}return function(y,M=null,x=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(l.copy(y),l.update(),y=l);const E=b(this,y,M,x);if(E!==void 0)return E;const S=this.plane,A=y.plane;let T=A.distanceToPoint(this.a),_=A.distanceToPoint(this.b),k=A.distanceToPoint(this.c);Gr(T)&&(T=0),Gr(_)&&(_=0),Gr(k)&&(k=0);const L=T*_,P=T*k;if(L>0&&P>0)return!1;let C=S.distanceToPoint(y.a),N=S.distanceToPoint(y.b),F=S.distanceToPoint(y.c);Gr(C)&&(C=0),Gr(N)&&(N=0),Gr(F)&&(F=0);const H=C*N,j=C*F;if(H>0&&j>0)return!1;s.copy(S.normal),n.copy(A.normal);const W=s.cross(n);let J=0,re=Math.abs(W.x);const Le=Math.abs(W.y);Le>re&&(re=Le,J=1),Math.abs(W.z)>re&&(J=2);const De=R9[J],Z=this.a[De],ce=this.b[De],le=this.c[De],$=y.a[De],Ue=y.b[De],je=y.c[De];if(f(this,Z,ce,le,L,P,T,_,k,h,a))return u(this,y,M,x);if(f(y,$,Ue,je,H,j,C,N,F,d,o))return u(this,y,M,x);if(h.y<h.x){const Be=h.y;h.y=h.x,h.x=Be,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(d.y<d.x){const Be=d.y;d.y=d.x,d.x=Be,c.copy(o.start),o.start.copy(o.end),o.end.copy(c)}return h.y<d.x||d.y<h.x?!1:(M&&(d.x>h.x?M.start.copy(o.start):M.start.copy(a.start),d.y<h.y?M.end.copy(o.end):M.end.copy(a.end)),!0)}})();Sa.prototype.distanceToPoint=(function(){const l=new D;return function(t){return this.closestPointToPoint(t,l),t.distanceTo(l)}})();Sa.prototype.distanceToTriangle=(function(){const l=new D,e=new D,t=["a","b","c"],i=new Jo,s=new Jo;return function(r,a=null,o=null){const c=a||o?i:null;if(this.intersectsTriangle(r,c,!0))return(a||o)&&(a&&c.getCenter(a),o&&c.getCenter(o)),0;let h=1/0;for(let d=0;d<3;d++){let u;const p=t[d],f=r[p];this.closestPointToPoint(f,l),u=f.distanceToSquared(l),u<h&&(h=u,a&&a.copy(l),o&&o.copy(f));const m=this[p];r.closestPointToPoint(m,l),u=m.distanceToSquared(l),u<h&&(h=u,a&&a.copy(m),o&&o.copy(l))}for(let d=0;d<3;d++){const u=t[d],p=t[(d+1)%3];i.set(this[u],this[p]);for(let f=0;f<3;f++){const m=t[f],v=t[(f+1)%3];s.set(r[m],r[v]),tM(i,s,l,e);const g=l.distanceToSquared(e);g<h&&(h=g,a&&a.copy(l),o&&o.copy(e))}}return Math.sqrt(h)}})();class rr{constructor(e,t,i){this.isOrientedBox=!0,this.min=new D,this.max=new D,this.matrix=new qe,this.invMatrix=new qe,this.points=new Array(8).fill().map(()=>new D),this.satAxes=new Array(3).fill().map(()=>new D),this.satBounds=new Array(3).fill().map(()=>new el),this.alignedSatBounds=new Array(3).fill().map(()=>new el),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}rr.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const u=1*c|2*h|4*d,p=s[u];p.x=c?i.x:t.x,p.y=h?i.y:t.y,p.z=d?i.z:t.z,p.applyMatrix4(e)}const n=this.satBounds,r=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=r[c],d=n[c],u=1<<c,p=s[u];h.subVectors(a,p),d.setFromPoints(h,s)}const o=this.alignedSatBounds;o[0].setFromPointsField(s,"x"),o[1].setFromPointsField(s,"y"),o[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();rr.prototype.intersectsBox=(function(){const l=new el;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,n=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(l.min=i.x,l.max=s.x,a[0].isSeparated(l)||(l.min=i.y,l.max=s.y,a[1].isSeparated(l))||(l.min=i.z,l.max=s.z,a[2].isSeparated(l)))return!1;for(let o=0;o<3;o++){const c=r[o],h=n[o];if(l.setFromBox(c,t),h.isSeparated(l))return!1}return!0}})();rr.prototype.intersectsTriangle=(function(){const l=new Sa,e=new Array(3),t=new el,i=new el,s=new D;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(l.copy(r),l.update(),r=l);const a=this.satBounds,o=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let u=0;u<3;u++){const p=a[u],f=o[u];if(t.setFromPoints(f,e),p.isSeparated(t))return!1}const c=r.satBounds,h=r.satAxes,d=this.points;for(let u=0;u<3;u++){const p=c[u],f=h[u];if(t.setFromPoints(f,d),p.isSeparated(t))return!1}for(let u=0;u<3;u++){const p=o[u];for(let f=0;f<4;f++){const m=h[f];if(s.crossVectors(p,m),t.setFromPoints(s,e),i.setFromPoints(s,d),t.isSeparated(i))return!1}}return!0}})();rr.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();rr.prototype.distanceToPoint=(function(){const l=new D;return function(t){return this.closestPointToPoint(t,l),t.distanceTo(l)}})();rr.prototype.distanceToBox=(function(){const l=["x","y","z"],e=new Array(12).fill().map(()=>new Jo),t=new Array(12).fill().map(()=>new Jo),i=new D,s=new D;return function(r,a=0,o=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(o||c)&&(r.getCenter(s),this.closestPointToPoint(s,i),r.closestPointToPoint(i,s),o&&o.copy(i),c&&c.copy(s)),0;const h=a*a,d=r.min,u=r.max,p=this.points;let f=1/0;for(let v=0;v<8;v++){const g=p[v];s.copy(g).clamp(d,u);const b=g.distanceToSquared(s);if(b<f&&(f=b,o&&o.copy(g),c&&c.copy(s),b<h))return Math.sqrt(b)}let m=0;for(let v=0;v<3;v++)for(let g=0;g<=1;g++)for(let b=0;b<=1;b++){const w=(v+1)%3,y=(v+2)%3,M=g<<w|b<<y,x=1<<v|g<<w|b<<y,E=p[M],S=p[x];e[m].set(E,S);const T=l[v],_=l[w],k=l[y],L=t[m],P=L.start,C=L.end;P[T]=d[T],P[_]=g?d[_]:u[_],P[k]=b?d[k]:u[_],C[T]=u[T],C[_]=g?d[_]:u[_],C[k]=b?d[k]:u[_],m++}for(let v=0;v<=1;v++)for(let g=0;g<=1;g++)for(let b=0;b<=1;b++){s.x=v?u.x:d.x,s.y=g?u.y:d.y,s.z=b?u.z:d.z,this.closestPointToPoint(s,i);const w=s.distanceToSquared(i);if(w<f&&(f=w,o&&o.copy(i),c&&c.copy(s),w<h))return Math.sqrt(w)}for(let v=0;v<12;v++){const g=e[v];for(let b=0;b<12;b++){const w=t[b];tM(g,w,i,s);const y=i.distanceToSquared(s);if(y<f&&(f=y,o&&o.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(f)}})();class C9 extends Qw{constructor(){super(()=>new Sa)}}const jr=new C9,Pu=new D,A1=new D;function L9(l,e,t={},i=0,s=1/0){const n=i*i,r=s*s;let a=1/0,o=null;if(l.shapecast({boundsTraverseOrder:h=>(Pu.copy(e).clamp(h.min,h.max),Pu.distanceToSquared(e)),intersectsBounds:(h,d,u)=>u<a&&u<r,intersectsTriangle:(h,d)=>{h.closestPointToPoint(e,Pu);const u=e.distanceToSquared(Pu);return u<a&&(A1.copy(Pu),a=u,o=d),u<n}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(A1):t.point=A1.clone(),t.distance=c,t.faceIndex=o,t}const Sm=parseInt(Sf)>=169,O9=parseInt(Sf)<=161,gc=new D,vc=new D,bc=new D,Em=new ie,Am=new ie,Tm=new ie,p2=new D,f2=new D,m2=new D,Nu=new D;function P9(l,e,t,i,s,n,r,a){let o;if(n===Ji?o=l.intersectTriangle(i,t,e,!0,s):o=l.intersectTriangle(e,t,i,n!==$s,s),o===null)return null;const c=l.origin.distanceTo(s);return c<r||c>a?null:{distance:c,point:s.clone()}}function g2(l,e,t,i,s,n,r,a,o,c,h){gc.fromBufferAttribute(e,n),vc.fromBufferAttribute(e,r),bc.fromBufferAttribute(e,a);const d=P9(l,gc,vc,bc,Nu,o,c,h);if(d){if(i){Em.fromBufferAttribute(i,n),Am.fromBufferAttribute(i,r),Tm.fromBufferAttribute(i,a),d.uv=new ie;const p=on.getInterpolation(Nu,gc,vc,bc,Em,Am,Tm,d.uv);Sm||(d.uv=p)}if(s){Em.fromBufferAttribute(s,n),Am.fromBufferAttribute(s,r),Tm.fromBufferAttribute(s,a),d.uv1=new ie;const p=on.getInterpolation(Nu,gc,vc,bc,Em,Am,Tm,d.uv1);Sm||(d.uv1=p),O9&&(d.uv2=d.uv1)}if(t){p2.fromBufferAttribute(t,n),f2.fromBufferAttribute(t,r),m2.fromBufferAttribute(t,a),d.normal=new D;const p=on.getInterpolation(Nu,gc,vc,bc,p2,f2,m2,d.normal);d.normal.dot(l.direction)>0&&d.normal.multiplyScalar(-1),Sm||(d.normal=p)}const u={a:n,b:r,c:a,normal:new D,materialIndex:0};if(on.getNormal(gc,vc,bc,u.normal),d.face=u,d.faceIndex=n,Sm){const p=new D;on.getBarycoord(Nu,gc,vc,bc,p),d.barycoord=p}}return d}function v2(l){return l&&l.isMaterial?l.side:l}function Yg(l,e,t,i,s,n,r){const a=i*3;let o=a+0,c=a+1,h=a+2;const{index:d,groups:u}=l;l.index&&(o=d.getX(o),c=d.getX(c),h=d.getX(h));const{position:p,normal:f,uv:m,uv1:v}=l.attributes;if(Array.isArray(e)){const g=i*3;for(let b=0,w=u.length;b<w;b++){const{start:y,count:M,materialIndex:x}=u[b];if(g>=y&&g<y+M){const E=v2(e[x]),S=g2(t,p,f,m,v,o,c,h,E,n,r);if(S)if(S.faceIndex=i,S.face.materialIndex=x,s)s.push(S);else return S}}}else{const g=v2(e),b=g2(t,p,f,m,v,o,c,h,g,n,r);if(b)if(b.faceIndex=i,b.face.materialIndex=0,s)s.push(b);else return b}return null}function Us(l,e,t,i){const s=l.a,n=l.b,r=l.c;let a=e,o=e+1,c=e+2;t&&(a=t.getX(a),o=t.getX(o),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),r.x=i.getX(c),r.y=i.getY(c),r.z=i.getZ(c)}function N9(l,e,t,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=l;for(let h=i,d=i+s;h<d;h++)Yg(o,e,t,h,n,r,a)}function F9(l,e,t,i,s,n,r){const{geometry:a,_indirectBuffer:o}=l;let c=1/0,h=null;for(let d=i,u=i+s;d<u;d++){let p;p=Yg(a,e,t,d,null,n,r),p&&p.distance<c&&(h=p,c=p.distance)}return h}function U9(l,e,t,i,s,n,r){const{geometry:a}=t,{index:o}=a,c=a.attributes.position;for(let h=l,d=e+l;h<d;h++){let u;if(u=h,Us(r,u*3,o,c),r.needsUpdate=!0,i(r,u,s,n))return!0}return!1}function B9(l,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=l.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let n,r,a,o,c=0;const h=l._roots;for(let u=0,p=h.length;u<p;u++)n=h[u],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),d(0,c),c+=n.byteLength;function d(u,p,f=!1){const m=u*2;if(Ds(m,a)){const v=cn(u,r),g=Fn(m,a);let b=1/0,w=1/0,y=1/0,M=-1/0,x=-1/0,E=-1/0;for(let S=3*v,A=3*(v+g);S<A;S++){let T=i[S];const _=s.getX(T),k=s.getY(T),L=s.getZ(T);_<b&&(b=_),_>M&&(M=_),k<w&&(w=k),k>x&&(x=k),L<y&&(y=L),L>E&&(E=L)}return o[u+0]!==b||o[u+1]!==w||o[u+2]!==y||o[u+3]!==M||o[u+4]!==x||o[u+5]!==E?(o[u+0]=b,o[u+1]=w,o[u+2]=y,o[u+3]=M,o[u+4]=x,o[u+5]=E,!0):!1}else{const v=Xs(u),g=Ys(u,r);let b=f,w=!1,y=!1;if(e){if(!b){const T=v/Ks+p/Nn,_=g/Ks+p/Nn;w=e.has(T),y=e.has(_),b=!w&&!y}}else w=!0,y=!0;const M=b||w,x=b||y;let E=!1;M&&(E=d(v,p,b));let S=!1;x&&(S=d(g,p,b));const A=E||S;if(A)for(let T=0;T<3;T++){const _=v+T,k=g+T,L=o[_],P=o[_+3],C=o[k],N=o[k+3];o[u+T]=L<C?L:C,o[u+T+3]=P>N?P:N}return A}}}function rc(l,e,t,i,s){let n,r,a,o,c,h;const d=1/t.direction.x,u=1/t.direction.y,p=1/t.direction.z,f=t.origin.x,m=t.origin.y,v=t.origin.z;let g=e[l],b=e[l+3],w=e[l+1],y=e[l+3+1],M=e[l+2],x=e[l+3+2];return d>=0?(n=(g-f)*d,r=(b-f)*d):(n=(b-f)*d,r=(g-f)*d),u>=0?(a=(w-m)*u,o=(y-m)*u):(a=(y-m)*u,o=(w-m)*u),n>o||a>r||((a>n||isNaN(n))&&(n=a),(o<r||isNaN(r))&&(r=o),p>=0?(c=(M-v)*p,h=(x-v)*p):(c=(x-v)*p,h=(M-v)*p),n>h||c>r)?!1:((c>n||n!==n)&&(n=c),(h<r||r!==r)&&(r=h),n<=s&&r>=i)}function z9(l,e,t,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=l;for(let h=i,d=i+s;h<d;h++){let u=c?c[h]:h;Yg(o,e,t,u,n,r,a)}}function H9(l,e,t,i,s,n,r){const{geometry:a,_indirectBuffer:o}=l;let c=1/0,h=null;for(let d=i,u=i+s;d<u;d++){let p;p=Yg(a,e,t,o?o[d]:d,null,n,r),p&&p.distance<c&&(h=p,c=p.distance)}return h}function G9(l,e,t,i,s,n,r){const{geometry:a}=t,{index:o}=a,c=a.attributes.position;for(let h=l,d=e+l;h<d;h++){let u;if(u=t.resolveTriangleIndex(h),Us(r,u*3,o,c),r.needsUpdate=!0,i(r,u,s,n))return!0}return!1}function V9(l,e,t,i,s,n,r){es.setBuffer(l._roots[e]),Hy(0,l,t,i,s,n,r),es.clearBuffer()}function Hy(l,e,t,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=es,h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);N9(e,t,i,u,p,s,n,r)}else{const u=Xs(l);rc(u,a,i,n,r)&&Hy(u,e,t,i,s,n,r);const p=Ys(l,c);rc(p,a,i,n,r)&&Hy(p,e,t,i,s,n,r)}}const W9=["x","y","z"];function $9(l,e,t,i,s,n){es.setBuffer(l._roots[e]);const r=Gy(0,l,t,i,s,n);return es.clearBuffer(),r}function Gy(l,e,t,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=es;let c=l*2;if(Ds(c,a)){const d=cn(l,o),u=Fn(c,a);return F9(e,t,i,d,u,s,n)}else{const d=Jw(l,o),u=W9[d],f=i.direction[u]>=0;let m,v;f?(m=Xs(l),v=Ys(l,o)):(m=Ys(l,o),v=Xs(l));const b=rc(m,r,i,s,n)?Gy(m,e,t,i,s,n):null;if(b){const M=b.point[u];if(f?M<=r[v+d]:M>=r[v+d+3])return b}const y=rc(v,r,i,s,n)?Gy(v,e,t,i,s,n):null;return b&&y?b.distance<=y.distance?b:y:b||y||null}}const Im=new ai,Vh=new Sa,Wh=new Sa,Fu=new qe,b2=new rr,_m=new rr;function K9(l,e,t,i){es.setBuffer(l._roots[e]);const s=Vy(0,l,t,i);return es.clearBuffer(),s}function Vy(l,e,t,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=es;let o=l*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),b2.set(t.boundingBox.min,t.boundingBox.max,i),s=b2),Ds(o,r)){const h=e.geometry,d=h.index,u=h.attributes.position,p=t.index,f=t.attributes.position,m=cn(l,a),v=Fn(o,r);if(Fu.copy(i).invert(),t.boundsTree)return ws(l,n,_m),_m.matrix.copy(Fu),_m.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>_m.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(i),b.b.applyMatrix4(i),b.c.applyMatrix4(i),b.needsUpdate=!0;for(let w=m*3,y=(v+m)*3;w<y;w+=3)if(Us(Wh,w,d,u),Wh.needsUpdate=!0,b.intersectsTriangle(Wh))return!0;return!1}});{const g=Xg(t);for(let b=m*3,w=(v+m)*3;b<w;b+=3){Us(Vh,b,d,u),Vh.a.applyMatrix4(Fu),Vh.b.applyMatrix4(Fu),Vh.c.applyMatrix4(Fu),Vh.needsUpdate=!0;for(let y=0,M=g*3;y<M;y+=3)if(Us(Wh,y,p,f),Wh.needsUpdate=!0,Vh.intersectsTriangle(Wh))return!0}}}else{const h=Xs(l),d=Ys(l,a);return ws(h,n,Im),!!(s.intersectsBox(Im)&&Vy(h,e,t,i,s)||(ws(d,n,Im),s.intersectsBox(Im)&&Vy(d,e,t,i,s)))}}const Dm=new qe,T1=new rr,Uu=new rr,X9=new D,Y9=new D,q9=new D,j9=new D;function Z9(l,e,t,i={},s={},n=0,r=1/0){e.boundingBox||e.computeBoundingBox(),T1.set(e.boundingBox.min,e.boundingBox.max,t),T1.needsUpdate=!0;const a=l.geometry,o=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=jr.getPrimitive(),p=jr.getPrimitive();let f=X9,m=Y9,v=null,g=null;s&&(v=q9,g=j9);let b=1/0,w=null,y=null;return Dm.copy(t).invert(),Uu.matrix.copy(Dm),l.shapecast({boundsTraverseOrder:M=>T1.distanceToBox(M),intersectsBounds:(M,x,E)=>E<b&&E<r?(x&&(Uu.min.copy(M.min),Uu.max.copy(M.max),Uu.needsUpdate=!0),!0):!1,intersectsRange:(M,x)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:S=>Uu.distanceToBox(S),intersectsBounds:(S,A,T)=>T<b&&T<r,intersectsRange:(S,A)=>{for(let T=S,_=S+A;T<_;T++){Us(p,3*T,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let k=M,L=M+x;k<L;k++){Us(u,3*k,c,o),u.needsUpdate=!0;const P=u.distanceToTriangle(p,f,v);if(P<b&&(m.copy(f),g&&g.copy(v),b=P,w=k,y=T),P<n)return!0}}}});{const E=Xg(e);for(let S=0,A=E;S<A;S++){Us(p,3*S,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let T=M,_=M+x;T<_;T++){Us(u,3*T,c,o),u.needsUpdate=!0;const k=u.distanceToTriangle(p,f,v);if(k<b&&(m.copy(f),g&&g.copy(v),b=k,w=T,y=S),k<n)return!0}}}}}),jr.releasePrimitive(u),jr.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=b,i.faceIndex=w,s&&(s.point?s.point.copy(g):s.point=g.clone(),s.point.applyMatrix4(Dm),m.applyMatrix4(Dm),s.distance=m.sub(s.point).length(),s.faceIndex=y),i)}function J9(l,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=l.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let n,r,a,o,c=0;const h=l._roots;for(let u=0,p=h.length;u<p;u++)n=h[u],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),d(0,c),c+=n.byteLength;function d(u,p,f=!1){const m=u*2;if(Ds(m,a)){const v=cn(u,r),g=Fn(m,a);let b=1/0,w=1/0,y=1/0,M=-1/0,x=-1/0,E=-1/0;for(let S=v,A=v+g;S<A;S++){const T=3*l.resolveTriangleIndex(S);for(let _=0;_<3;_++){let k=T+_;k=i?i[k]:k;const L=s.getX(k),P=s.getY(k),C=s.getZ(k);L<b&&(b=L),L>M&&(M=L),P<w&&(w=P),P>x&&(x=P),C<y&&(y=C),C>E&&(E=C)}}return o[u+0]!==b||o[u+1]!==w||o[u+2]!==y||o[u+3]!==M||o[u+4]!==x||o[u+5]!==E?(o[u+0]=b,o[u+1]=w,o[u+2]=y,o[u+3]=M,o[u+4]=x,o[u+5]=E,!0):!1}else{const v=Xs(u),g=Ys(u,r);let b=f,w=!1,y=!1;if(e){if(!b){const T=v/Ks+p/Nn,_=g/Ks+p/Nn;w=e.has(T),y=e.has(_),b=!w&&!y}}else w=!0,y=!0;const M=b||w,x=b||y;let E=!1;M&&(E=d(v,p,b));let S=!1;x&&(S=d(g,p,b));const A=E||S;if(A)for(let T=0;T<3;T++){const _=v+T,k=g+T,L=o[_],P=o[_+3],C=o[k],N=o[k+3];o[u+T]=L<C?L:C,o[u+T+3]=P>N?P:N}return A}}}function Q9(l,e,t,i,s,n,r){es.setBuffer(l._roots[e]),Wy(0,l,t,i,s,n,r),es.clearBuffer()}function Wy(l,e,t,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=es,h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);z9(e,t,i,u,p,s,n,r)}else{const u=Xs(l);rc(u,a,i,n,r)&&Wy(u,e,t,i,s,n,r);const p=Ys(l,c);rc(p,a,i,n,r)&&Wy(p,e,t,i,s,n,r)}}const e7=["x","y","z"];function t7(l,e,t,i,s,n){es.setBuffer(l._roots[e]);const r=$y(0,l,t,i,s,n);return es.clearBuffer(),r}function $y(l,e,t,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=es;let c=l*2;if(Ds(c,a)){const d=cn(l,o),u=Fn(c,a);return H9(e,t,i,d,u,s,n)}else{const d=Jw(l,o),u=e7[d],f=i.direction[u]>=0;let m,v;f?(m=Xs(l),v=Ys(l,o)):(m=Ys(l,o),v=Xs(l));const b=rc(m,r,i,s,n)?$y(m,e,t,i,s,n):null;if(b){const M=b.point[u];if(f?M<=r[v+d]:M>=r[v+d+3])return b}const y=rc(v,r,i,s,n)?$y(v,e,t,i,s,n):null;return b&&y?b.distance<=y.distance?b:y:b||y||null}}const km=new ai,$h=new Sa,Kh=new Sa,Bu=new qe,y2=new rr,Rm=new rr;function i7(l,e,t,i){es.setBuffer(l._roots[e]);const s=Ky(0,l,t,i);return es.clearBuffer(),s}function Ky(l,e,t,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=es;let o=l*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),y2.set(t.boundingBox.min,t.boundingBox.max,i),s=y2),Ds(o,r)){const h=e.geometry,d=h.index,u=h.attributes.position,p=t.index,f=t.attributes.position,m=cn(l,a),v=Fn(o,r);if(Bu.copy(i).invert(),t.boundsTree)return ws(l,n,Rm),Rm.matrix.copy(Bu),Rm.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>Rm.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(i),b.b.applyMatrix4(i),b.c.applyMatrix4(i),b.needsUpdate=!0;for(let w=m,y=v+m;w<y;w++)if(Us(Kh,3*e.resolveTriangleIndex(w),d,u),Kh.needsUpdate=!0,b.intersectsTriangle(Kh))return!0;return!1}});{const g=Xg(t);for(let b=m,w=v+m;b<w;b++){const y=e.resolveTriangleIndex(b);Us($h,3*y,d,u),$h.a.applyMatrix4(Bu),$h.b.applyMatrix4(Bu),$h.c.applyMatrix4(Bu),$h.needsUpdate=!0;for(let M=0,x=g*3;M<x;M+=3)if(Us(Kh,M,p,f),Kh.needsUpdate=!0,$h.intersectsTriangle(Kh))return!0}}}else{const h=Xs(l),d=Ys(l,a);return ws(h,n,km),!!(s.intersectsBox(km)&&Ky(h,e,t,i,s)||(ws(d,n,km),s.intersectsBox(km)&&Ky(d,e,t,i,s)))}}const Cm=new qe,I1=new rr,zu=new rr,s7=new D,n7=new D,r7=new D,a7=new D;function o7(l,e,t,i={},s={},n=0,r=1/0){e.boundingBox||e.computeBoundingBox(),I1.set(e.boundingBox.min,e.boundingBox.max,t),I1.needsUpdate=!0;const a=l.geometry,o=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=jr.getPrimitive(),p=jr.getPrimitive();let f=s7,m=n7,v=null,g=null;s&&(v=r7,g=a7);let b=1/0,w=null,y=null;return Cm.copy(t).invert(),zu.matrix.copy(Cm),l.shapecast({boundsTraverseOrder:M=>I1.distanceToBox(M),intersectsBounds:(M,x,E)=>E<b&&E<r?(x&&(zu.min.copy(M.min),zu.max.copy(M.max),zu.needsUpdate=!0),!0):!1,intersectsRange:(M,x)=>{if(e.boundsTree){const E=e.boundsTree;return E.shapecast({boundsTraverseOrder:S=>zu.distanceToBox(S),intersectsBounds:(S,A,T)=>T<b&&T<r,intersectsRange:(S,A)=>{for(let T=S,_=S+A;T<_;T++){const k=E.resolveTriangleIndex(T);Us(p,3*k,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let L=M,P=M+x;L<P;L++){const C=l.resolveTriangleIndex(L);Us(u,3*C,c,o),u.needsUpdate=!0;const N=u.distanceToTriangle(p,f,v);if(N<b&&(m.copy(f),g&&g.copy(v),b=N,w=L,y=T),N<n)return!0}}}})}else{const E=Xg(e);for(let S=0,A=E;S<A;S++){Us(p,3*S,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let T=M,_=M+x;T<_;T++){const k=l.resolveTriangleIndex(T);Us(u,3*k,c,o),u.needsUpdate=!0;const L=u.distanceToTriangle(p,f,v);if(L<b&&(m.copy(f),g&&g.copy(v),b=L,w=T,y=S),L<n)return!0}}}}}),jr.releasePrimitive(u),jr.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=b,i.faceIndex=w,s&&(s.point?s.point.copy(g):s.point=g.clone(),s.point.applyMatrix4(Cm),m.applyMatrix4(Cm),s.distance=m.sub(s.point).length(),s.faceIndex=y),i)}function w2(l,e,t){return l===null?null:(l.point.applyMatrix4(e.matrixWorld),l.distance=l.point.distanceTo(t.ray.origin),l.object=e,l)}const Lm=new rr,Om=new oh,M2=new D,x2=new qe,S2=new D,_1=["getX","getY","getZ"];class hg extends _9{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,n=e._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(o=>o.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=n?n.slice():null):(a.roots=s,a.index=r?r.array:null,a.indirectBuffer=n),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:n,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),o(n));const a=new hg(t,{...i,[Zw]:!0});if(a._roots=n,a._indirectBuffer=r||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new Et(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function o(c){for(let h=0;h<c.length;h++){const d=c[h],u=new Uint32Array(d),p=new Uint16Array(d);for(let f=0,m=d.byteLength/Nn;f<m;f++){const v=Ks*f,g=2*v;Ds(g,p)||(u[v+6]=u[v+6]/Ks-f)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,c=(n?n[e]:e)*3;let h=c+0,d=c+1,u=c+2;a&&(h=a[h],d=a[d],u=a[u]);for(let p=0;p<3;p++){const f=r[_1[p]](h),m=r[_1[p]](d),v=r[_1[p]](u);let g=f;m<g&&(g=m),v<g&&(g=v);let b=f;m>b&&(b=m),v>b&&(b=v),t[i+p]=g,t[i+p+3]=b}return t}computePrimitiveBounds(e,t,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,o=r.normalized;if(e<0||t+e-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const c=r.array,h=r.offset||0;let d=3;r.isInterleavedBufferAttribute&&(d=r.data.stride);const u=["getX","getY","getZ"],p=i.offset;for(let f=e,m=e+t;f<m;f++){const g=(n?n[f]:f)*3,b=(f-p)*6;let w=g+0,y=g+1,M=g+2;a&&(w=a[w],y=a[y],M=a[M]),o||(w=w*d+h,y=y*d+h,M=M*d+h);for(let x=0;x<3;x++){let E,S,A;o?(E=r[u[x]](w),S=r[u[x]](y),A=r[u[x]](M)):(E=c[w+x],S=c[y+x],A=c[M+x]);let T=E;S<T&&(T=S),A<T&&(T=A);let _=E;S>_&&(_=S),A>_&&(_=A);const k=(_-T)/2,L=x*2;i[b+L+0]=T+k,i[b+L+1]=k+(Math.abs(T)+k)*m0}}return i}raycastObject3D(e,t,i=[]){const{material:s}=e;if(s===void 0)return;x2.copy(e.matrixWorld).invert(),Om.copy(t.ray).applyMatrix4(x2),S2.setFromMatrixScale(e.matrixWorld),M2.copy(Om.direction).multiply(S2);const n=M2.length(),r=t.near/n,a=t.far/n;if(t.firstHitOnly===!0){let o=this.raycastFirst(Om,s,r,a);o=w2(o,e,t),o&&i.push(o)}else{const o=this.raycast(Om,s,r,a);for(let c=0,h=o.length;c<h;c++){const d=w2(o[c],e,t);d&&i.push(d)}}return i}refit(e=null){return(this.indirect?J9:B9)(this,e)}raycast(e,t=ho,i=0,s=1/0){const n=this._roots,r=[],a=this.indirect?Q9:V9;for(let o=0,c=n.length;o<c;o++)a(this,o,t,e,r,i,s);return r}raycastFirst(e,t=ho,i=0,s=1/0){const n=this._roots;let r=null;const a=this.indirect?t7:$9;for(let o=0,c=n.length;o<c;o++){const h=a(this,o,t,e,i,s);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(e,t){let i=!1;const s=this._roots,n=this.indirect?i7:K9;for(let r=0,a=s.length;r<a&&(i=n(this,r,e,t),!i);r++);return i}shapecast(e){const t=jr.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?G9:U9});return jr.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const r=jr.getPrimitive(),a=this.geometry.index,o=this.geometry.attributes.position,c=this.indirect?f=>{const m=this.resolveTriangleIndex(f);Us(r,m*3,a,o)}:f=>{Us(r,f*3,a,o)},h=jr.getPrimitive(),d=e.geometry.index,u=e.geometry.attributes.position,p=e.indirect?f=>{const m=e.resolveTriangleIndex(f);Us(h,m*3,d,u)}:f=>{Us(h,f*3,d,u)};if(n){if(!(e instanceof hg))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const f=(m,v,g,b,w,y,M,x)=>{for(let E=g,S=g+b;E<S;E++){p(E),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let A=m,T=m+v;A<T;A++)if(c(A),r.needsUpdate=!0,n(r,h,A,E,w,y,M,x))return!0}return!1};if(s){const m=s;s=function(v,g,b,w,y,M,x,E){return m(v,g,b,w,y,M,x,E)?!0:f(v,g,b,w,y,M,x,E)}}else s=f}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return Lm.set(e.min,e.max,t),Lm.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Lm.intersectsBox(i),intersectsTriangle:i=>Lm.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},n=0,r=1/0){return(this.indirect?o7:Z9)(this,e,t,i,s,n,r)}closestPointToPoint(e,t={},i=0,s=1/0){return L9(this,e,t,i,s)}}class Na{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ea;static install(){if(Na.installed)return;Na.installed=!0;const e=Me.prototype.raycast;Me.prototype.raycast=function(t,i){const s=Na.treeOf(this,t);s!==null&&(s?s.raycastObject3D(this,t,i):e.call(this,t,i))}}static treeOf(e,t){const i=e.geometry,s=i?.attributes.position;if(!(s instanceof Et)||e.material===void 0||e.isSkinnedMesh||e.isInstancedMesh||e.isBatchedMesh||i.morphAttributes.position)return;const n=i.index;if((n?n.count:s.count)/3<Na.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Na.sphere.copy(i.boundingSphere).applyMatrix4(e.matrixWorld);if(!t.ray.intersectsSphere(r))return null;const a=Na.trees.get(i);if(a){if(!a.bvh)return;if(a.position===s&&a.positionVersion===s.version&&a.index===n&&a.indexVersion===(n?.version??0))return a.bvh;Na.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const o=new hg(i,{indirect:!0});return Na.trees.set(i,{bvh:o,position:s,positionVersion:s.version,index:n,indexVersion:n?.version??0}),o}}function l7(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.rareIceCrystals===e.rareIceCrystals&&l.lowerCloudCover===e.lowerCloudCover&&l.relativeHumidity===e.relativeHumidity&&l.precipitationType===e.precipitationType&&l.precipitationIntensity===e.precipitationIntensity&&l.precipitationAmount===e.precipitationAmount&&l.windDirectionDeg===e.windDirectionDeg&&l.windSpeed===e.windSpeed&&l.storm===e.storm}const Pm=900,D1=1,E2=4,k1=5,Nm=.5,Fm=Rt.GROUND_RADIUS_M;function A2(l){return Rt.groundRadiusFor(l)}const R1=.5,C1=850,Um=.03,c7=.015,Gn=850,Xh=300,xo=120,h7=700,L1=.03,d7=3.5,Bm=20,O1=.04,u7=.26,T2=4,P1=1.5,I2=-1,p7=.01,v0=-4,f7=2,m7=20,zm=2600,g7=.97,v7=.38,Hu=v0,b7=8,y7=2,_2=1500,w7=.7,M7=.3,x7=.32,S7=.65,D2=2.4,E7=.9,A7=400,T7=[0,45,90,135,180,225,270,315],I7=2,_7=16,k2=4e3,R2=880,Hm=40,C2=60,D7=10,L2=1,k7=Rt.REBUILD_DISTANCE_M,O2=.265,P2=[[0,0],...Array.from({length:8},(l,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*O2,Math.sin(t)*O2]})],N1=700,F1=250/Yy,R7=12,N2=5,U1=6,yc=[.92,.92,.95],B1=[.15,.15,.19],z1={snow:{fallSpeedMPerS:2,size:.3,color:new oe(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new oe(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Qh=0,H1=0,C7=150,G1=3e3,Gu=20,L7=15,F2=Qh,O7=40,U2=1,P7=9;function V1(l){return U2+(P7-U2)*l}const B2=new oe(.75,.82,.92),N7=10,F7=.5;function z2(l){return Fa(l/N7,F7,1)}const wc=200,H2=.18,G2=.32,U7=.35,V2=new oe(.85,.9,.98),W2=5,$2=.85,K2=.01;function B7(l,e,t=1){return Math.round(l*(K2+(1-K2)*e)*t)}function z7(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.lowerCloudCover===e.lowerCloudCover}const X2=230,Y2=.7,q2=.05,H7=.6,G7=.7,V7=.15,j2=.35,W7=3,$7=1/12,K7=.5,Ra=new oe(.82,.86,1),X7=2500,Y7=1.6,W1=15,q7={Venus:new oe(1,.96,.85),Mars:new oe(1,.55,.4),Jupiter:new oe(.95,.87,.72),Saturn:new oe(.92,.86,.68)};class he{renderer;scene=new Fr;phenomena=new da(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new ii;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=t===void 0?void 0:setTimeout(s,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(n),s()})}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()+k2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),k2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new At;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ie;decorModelProvider=new mp;decorModelToken=0;decorModelCredits=new Map;emitterLights=new Wn(this.scene,()=>this.relativeScale,{halfExtentM:xo,depthHalfRangeM:Xh,biasM:L1,normalBiasM:O1,mapSize:1024});bodySystem=new ut(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale,e=>this.emitterLights.set("bodies",e));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??he.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*he.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Z0(16777215,0);celestialLightTarget=new Qi;skyLight=new SC(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 d0;weather=xg;observerElevationM=0;siteElevationM=0;air=new Xr;groundRadius=Fm;terrainRadius=Fm;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 ie;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Z0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new d0;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new d0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=xi.NONE;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;iceHalos;lunarDiffraction;eclipsedSun=new ff;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=VT()){cp.install(),Na.install(),this.renderer=new UN({canvas:e,antialias:!0}),this.resolution=new di(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=tp,this.camera=new vn(60,e.width/Math.max(e.height,1),.1,Pm*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=-xo,this.celestialLight.shadow.camera.right=xo,this.celestialLight.shadow.camera.top=xo,this.celestialLight.shadow.camera.bottom=-xo,this.celestialLight.shadow.camera.near=Gn-Xh,this.celestialLight.shadow.camera.far=Gn+Xh,this.celestialLight.shadow.bias=-L1/(2*Xh),this.celestialLight.shadow.normalBias=O1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Ra),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 yt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(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*F1,0,e.z*F1);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){this.updateLookPatch(e);const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*ci,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ci;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ci,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(A2(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Fm),this.camera.far=Math.max(Pm*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.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=he.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return Rt.decorReachFor(e,t)}placeTerrain(e,t,i,s){const n=(r,a)=>{const o=ot(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.z+s};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=L2+.1;updateLookPatch(e){if(e.lat===void 0||e.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const t=Rt.lookPatchFor(e.elevationM??0,e.pitchDeg,this.terrainRadius);if(!t){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(e.headingDeg??0)*Math.PI/180,s=e.lat+t.distanceM*Math.cos(i)/111320,n=e.lng+t.distanceM*Math.sin(i)/(111320*Math.cos(e.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const c=ot(s,n,r.lat,r.lng);if(Math.hypot(c.x,c.z)<r.radiusM*he.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:s,lng:n,radiusM:t.radiusM};const a=++this.lookPatchToken,o=this.terrainProviders;c1(s,n,{elevation:o.elevation,imagery:o.imagery},t.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:c})=>{if(a!==this.lookPatchToken||this.terrainProviders!==o||!this.terrainMesh){this.disposeMesh(c);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),c.renderOrder=he.LOOK_PATCH_RENDER_ORDER,c.position.y=this.terrainMesh.position.y;const h=c.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:c,origin:{lat:s,lng:n},radiusM:t.radiusM};const d=ot(s,n,e.lat,e.lng);c.position.x=d.x,c.position.z=d.z,this.scene.add(c),this.compileNextFrameOffThread(),this.render()},c=>console.warn("No sharp ground under what is looked at:",c))}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:e,lng:t,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const u=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const p=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===u&&p&&this.setTerrainOrigin(p.lat,p.lng,p.onSettled)}),he.TERRAIN_PATIENCE_MS)}return}const d=s.nearest(e,t);d&&(e=d.lat,t=d.lng,n=d.radiusM)}const r=n??Math.max(Rt.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=ot(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<k7*(r/Fm))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(ot(e,t,o.lat,o.lng).x,ot(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(c1(e,t,this.terrainProviders,r,{route:this.observerRoute}),he.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,b=g?ot(e,t,g.lat,g.lng):void 0;v&&b&&Math.hypot(b.x,b.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,b.x,b.z)),v&&g&&b&&Math.hypot(b.x,b.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=L2,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,s,n){s.geometry.computeBoundingBox();const r=s.position.y+(s.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=this.skyEventReachM({lat:e,lng:t});if(!Rt.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=ot(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*he.FAR_RING_KEPT_SHARE)return}const c=this.terrainProviders.patches,h=c?.farRingOf?.(e,t);if(c&&!h){this.dropFarRing();return}const d=h?.radiusM??Rt.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(c1(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*he.FAR_RING_OPEN_SHARE,referenceElevationM:n}),he.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=he.FAR_RING_RENDER_ORDER,f.position.y=s.position.y-he.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=s.position.x,f.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=ot(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 s=ot(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const s=e.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-n)/he.TERRAIN_CROSSFADE_MS);if(s.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}s.polygonOffset=!1,s.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=Rt.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const s=this.terrainProviders.roads;if(!s||i>he.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRoads(n.ways,e,t,s.contemporary);return}n&&Math.hypot(ot(e,t,n.lat,n.lng).x,ot(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,e,t,s.contemporary),this.awaitArrival(s.getRoads(hp(e,t,i)),he.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,s.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,s,n){const r=this.terrainProviders.water;if(!r||i>he.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,e,t,i),he.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(ot(e,t,a.lat,a.lng).x,ot(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((n??r.getWater(hp(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),he.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,s){if(e.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s,this.patchSpacingM(r)),kn.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Q(async()=>{const{WaterSystem:e}=await import("./WaterSystem-BBrkl1Y3.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const s=this.terrainProviders.railways;if(!s||i>he.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRailways(n.lines,e,t,i);return}n&&Math.hypot(ot(e,t,n.lat,n.lng).x,ot(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,e,t,i),this.awaitArrival(s.getRailways(hp(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),he.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,s){if(!this.railwaySystem&&!e.some(a=>a.level>=0))return;const n=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.setGroundSpacing(this.patchSpacingM(r)),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s),kn.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Q(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-CuqGInI5.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}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??=Q(async()=>{const{TraceSystem:e}=await import("./TraceSystem-CUMKKQY4.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(k1);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,(s,n)=>this.groundYOfPatch(t,s,n)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ue.naturalSize(s.kind,s.floors),r=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ot(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="streetlight"&&!s.lamp?.supposed&&!s.track).map(s=>({x:i.x+s.eastM,z:i.z-s.northM}))}lampNudges=new Map;lampsToKerb(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,r=i.z-s.northM,a=this.roadSystem.atKerb(n,r);(a.x!==n||a.z!==r)&&this.lampNudges.set(s.id,{eastM:a.x-n,northM:-(a.z-r)})}}static onlyMoved(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,s)=>{const n=t[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(n)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==n[a])return!1;return!0})}layStreetsIfWallsMoved(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const s=this.wallsOf(e,t.lat,t.lng),n=this.roadWalls;n?.lat===t.lat&&n.lng===t.lng&&n.walls.length===s.length&&n.walls.every((a,o)=>a.what===s[o].what&&Math.hypot(a.x-s[o].x,a.z-s[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const s=this.decorOriginInRoads(t,i);return e.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:s.x+n.eastM,z:s.z-n.northM}))}roadWalls;drapeRoads(e,t,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(n,r,a),s,this.terrainRadius,new Fi(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),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;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,s=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?Vs.LENS_K:Vs.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.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(l7(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!z7(t,e),s=t.precipitationType!==e.precipitationType,n=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||s||n)&&(this.air=Xr.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Vo.steppedOpticalDepth(e.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),s?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||s||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=e.storm&&e.cloudDarkness>=K7,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(he.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=he.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=he.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.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,b7);for(const i of e){const s=ue.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,s,t.indexOf(i)<y7,i.lamp),i.model&&i.id.startsWith(Yi.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,s)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=he.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(e),e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(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??=Q(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-DYAYamnm.js");return{ContrailSystem:e}},__vite__mapDeps([15,16]),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,s=he.CONTRAIL_SCATTERING,n=this.skyLight.color,r=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(t&&i){const a=qn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=$t.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=s*c*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(e,t=!1,i){if(this.skyEventsStart=i,e===this.skyEventsStated&&!t)return;this.skyEventsStated=e;let s=!1;const n=new Set;for(const r of Qp){const a=Or.of(r);n.add(a.key);const o=Or.eventsOf(e,a);let c=this.skyEventLayers.get(a.key);if(c?.kind!==a&&c&&(this.disposeSkyEventLayer(a.key,c),c=void 0),!(!c&&o.length===0)){if(!c)c={kind:a,events:o},this.skyEventLayers.set(a.key,c);else if(c.events===o)continue;c.events=o,s||=a.reachM!==void 0,this.loadSkyEventSimulation(c)}}for(const[r,a]of this.skyEventLayers)n.has(r)||(this.disposeSkyEventLayer(r,a),s||=a.kind.reachM!==void 0);s&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(e){if(e.simulation){this.updateSkyEvents(),this.render();return}e.loading??=e.kind.simulation().then(t=>{if(this.skyEventLayers.get(e.kind.key)!==e)return;const i=t();(i.inSky?this.celestialGroup:this.scene).add(i.object),e.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(e.loading)}disposeSkyEventLayer(e,t){t.simulation?.dispose(),this.skyEventLayers.delete(e),this.skyEventLight(e,[]),this.skyEventGlare(e,[])}skyEventLight(e,t){this.emitterLights.set(`skyEvent:${e}`,[],t.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(e,t){const i=`skyEvent:${e}:`,s=new Set;for(const n of t){const r=i+n.key,{x:a,y:o,z:c}=Li(n.position.altitudeDeg,n.position.azimuthDeg,Gn),[h,d,u]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(r,a,o,c,[h*n.fade,d*n.fade,u*n.fade],0,he.POINT_VEIL_HOLD_DEG),s.add(r)}for(const n of[...this.glareSprites.keys()])n.startsWith(i)&&!s.has(n)&&this.disposeGlare(n)}skyEventReachM(e){let t=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(t=Math.max(t,i.kind.reachM(i.events,e)));return t}skyEventDrawnCount(e){return this.skyEventLayers.get(e)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const e=this.decorReferencePose;if(this.skyEventLayers.size===0||e?.lat===void 0||e.lng===void 0)return;const t=this.decorCurrentPose,i={lat:t?.lat??e.lat,lng:t?.lng??e.lng,heightM:this.siteElevationM+(t?.lat!==void 0?t.elevationM??0:e.elevationM??0)},s=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$a(-90,this.instrumentMagnitudeGain);let r;for(const[a,o]of this.skyEventLayers)o.simulation&&(r??={observer:i,date:s,magnitudeLimit:n,cloudTransmission:c=>this.cloudTransmission(c),arrivingIlluminance:(c,h,d)=>this.arrivingIlluminance(c,h,d),transmittanceFromSpace:c=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,c.altitudeDeg),reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(c,h,d)=>this.transmittanceTo(c,h,d),groundYAt:(c,h)=>this.groundYUnder(c,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*ci)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*ci)*this.weather.windSpeed}},o.simulation.update(o.events,this.decorTime,{...r,lightFrom:c=>this.skyEventLight(a,c),glareFrom:c=>this.skyEventGlare(a,c)}));this.render()}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?Li(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}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(()=>{})}holdUntil(e){this.awaitArrival(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),s=this.bodyEastScale;return{heightAt:(n,r)=>this.groundYUnder(e+n*s,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*ci)/Math.cos(e.lat*ci)}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),s=[],n){const{x:r,z:a}=this.bodyOrigin,o=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:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,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,s=this.skyLight.groundColor,n=this.skyLight.intensity,r=(a,o,c)=>(a*t+(o+c)/2*n)/Math.PI;return[r(e.r,i.r,s.r),r(e.g,i.g,s.g),r(e.b,i.b,s.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,s=e.credit??t?.credit;if(!(!i||!s))return{scene:await v1(i),credit:s,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(ef(e))||!ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const s=hI(i.scene);s.traverse(n=>{n instanceof Me&&(n.userData.sharedModel=!0)}),ue.applyModelParameters(s,e.modelParameters,i.bindings),ue.applyModel(t,e,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(e.id,i.credit)}mirrors=new fr;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(e,t,i=!1){const s=i?R0[e.kind]:ef(e);if(!(!s||!ue.usesModel(e)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,r=this.modelUrl(s)??n?.url,a=s.credit??n?.credit;if(!r||!a)return;const o=i||e.kind==="tree"?await this.standInScene(r):await v1(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"&&(ut.glaze(o),kn.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:a,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=v1(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||kn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const s=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ot(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},n=this.decorObjects.find(f=>f.observerSide!==void 0&&ic(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(s.x-=this.gaitOffset.eastM,s.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,o;if(n){const f=Pr(n,i),m=ue.occupantView(n,f.headingDeg),v=-(f.headingDeg??0)*ci,g=m.x*Math.cos(v)+m.z*Math.sin(v),b=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+s.x,y=-f.northM+s.z;r.x=-(w+g),r.z=-(y+b),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ci,-(m.headingDeg+this.indoorLookYawDeg)*ci,0,"YXZ")}this.bodyOrigin={x:s.x+r.x,z:s.z+r.z};const c=this.findCabin(i,s,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,s,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!n&&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 f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=Pr(f,i),g=this.lampNudges.get(f.id),b=v.eastM+(g?.eastM??0)+s.x+r.x,w=-(v.northM+(g?.northM??0))+s.z+r.z,y=this.terrainMesh,M=`${y?.geometry.uuid}:${(b-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const L=ue.wireGround(f,b,w,v.headingDeg,(P,C)=>this.groundYUnder(P,C));m.userData.footprintGroundY=L.startY,ue.shearWire(m,ue.sizeOf(f).lengthM,L.dropM)}else if(f.kind==="crossing"){const L=this.groundYUnder(b,w),P=-(v.headingDeg??0)*ci,C=Math.cos(P),N=Math.sin(P);m.userData.footprintGroundY=L,kt.drape(ue.bodyOf(m),(F,H)=>this.groundYUnder(b+F*C+H*N,w-F*N+H*C)-L)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,b,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>he.AIRBORNE_M&&Math.hypot(b,w)<he.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=f.id.startsWith(Yi.ID_PREFIX)?he.trafficHeight(v.altitudeM,m.userData.footprintGroundY):E+v.altitudeM;if(m.position.set(b,S,w),f.kind==="crop"){const L=Math.hypot(b,w);m.visible=L<=C7}const A=this.decorPresence.get(f.id),T=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!T);const _=this.decorSunlight.get(f.id);_&&!T&&this.lightFromAbove(m,_),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*ci);const k=hk(f,i);if(k!==void 0&&he.turnHead(m,v.headingDeg??0,k),f.kind==="crop"&&m.visible){const L=this.terrainMesh,P=[L?.geometry.uuid,b-(L?.position.x??0),w-(L?.position.z??0),m.position.y-(L?.position.y??0),v.headingDeg,v.altitudeM].map(C=>typeof C=="number"?C.toFixed(4):C).join(":");m.userData.cropGroundKey!==P&&(ue.fitCropToGround(m,(C,N)=>this.groundYUnder(C,N)+v.altitudeM),m.userData.cropGroundKey=P)}if(!T){const L=m.position.distanceTo(this.camera.position);a=Math.max(a,L),L<he.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(n&&o!==void 0){const f=this.decorGroups.get(n.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateSkyEvents();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,p=Math.max(Pm*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let s=i;for(const n of this.terraces){const r=e-n.x,a=t-n.z,o=r*n.cos-a*n.sin,c=r*n.sin+a*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(c)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),d=h*h*(3-2*h);s=Math.max(s,d*n.levelY+(1-d)*Math.min(n.levelY,i))}}return s}placeTerraces(e,t,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Pr(n,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=-(a.headingDeg??0)*ci,u=Math.cos(d),p=Math.sin(d),f=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(c-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=ue.fitTerrace(r,n,(m,v)=>this.terrainYUnder(o+m*u+v*p,c-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,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):H1}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((e%360+360)%360/(360/s))%s;let r=this.horizonByBearing[n];return Number.isNaN(r)&&(r=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),r}groundHidesDirection(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+he.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=e*Math.PI/180,n=Math.sin(s),r=-Math.cos(s),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=c;d<=o;d=Math.max(d+c,d*1.02)){const u=i.x+n*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*he.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}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 s=e.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return H1;const r=s.getX(0),a=s.getX(n-1),o=s.getZ(0),c=s.getZ((n-1)*n),h=Fa((t-r)/(a-r)*(n-1),0,n-1),d=Fa((i-o)/(c-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(d))return H1;const u=Math.min(Math.floor(h),n-2),p=Math.min(Math.floor(d),n-2),f=h-u,m=d-p,v=(M,x)=>s.getY(M*n+x),g=v(p,u),b=v(p,u+1),w=v(p+1,u),y=v(p+1,u+1);return f+m<=1?g+(b-g)*f+(w-g)*m:y+(w-y)*(1-f)+(b-y)*(1-m)}groundUnderFootprint(e,t,i,s,n=0){return ue.groundUnderFootprint(e,t,i,s,(r,a)=>this.groundYUnder(r,a),n)}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=Mr.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,s,n){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:s??e.iso,autoExposure:e.autoExposure===!0&&s===void 0,maxIso:e.maxIso,metering:n??e.metering??"average",exposureSeconds:t,fNumber:i,development:e.development,exposureFollowMs:e.exposureFollowMs,print:e.print,monochrome:e.monochrome}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?Mr.NONE:this.perception??Mr.NONE;if(qi.uColorVision.value.set(...i.colorMatrix),qi.uContrast.value=i.contrastGain,!e){qi.uMedium.value=0;return}const s=e.kind==="sensor"&&e.development==="computational";qi.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:s?4:3;const n=e.autoExposure?this.frameLight:void 0,r=e.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),o=r===void 0?void 0:r+a.mean,c=u=>.065*e.exposureSeconds*u*this.filterTransmittance/(e.fNumber*e.fNumber*t);let h=o!==void 0&&o>0?1/(t*o):void 0;h!==void 0&&e.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,he.HIGHLIGHT_KEPT_AT/(.18*t*a.brightest))),h!==void 0&&e.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,he.ZONE_KEPT_AT/(.18*t*n.brightest)));const d=h!==void 0?Math.min(h,e.maxIso!==void 0?c(e.maxIso):1/0):c(e.iso);qi.uMediumExposure.value=d,qi.uPhoneStrength.value=s&&o!==void 0&&o>0?ha.strengthFor(ha.MID_GREY*d*t*o):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),n=new D;let r=0,a=0;for(const{position:o,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(e),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(r+=c*h,a=Math.max(a,c*Math.min(1,h/(he.HIGHLIGHT_SHARE*s))**2));return{mean:r/s,brightest:a}}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 ie;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))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ue.setLights(n,s.lights,e,n.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=s.kind==="vehicle"?TT(s,e):void 0,o=a!==void 0?tc.lamps(a):Ng(s,e,this.lastAstronomy?.sun.altitudeDeg);ue.setLit(r,s.kind,o,this.relativeScale,s.lamp);const c=this.streetlightLights.get(s.id);c&&(c.visible=o),a!==void 0&&(this.headlightSettings.set(s.id,a),this.aimDecorBeam(s,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=Q(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-FfcayJJX.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 s=new D(0,0,-1).transformDirection(t.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ue.sizeOf(e).lengthM,r=t.getWorldPosition(new D).addScaledVector(s,n/2-M7);r.y+=w7;const a=ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,s,a*x7,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?tc.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,s=new D(Math.sin(i),0,-Math.cos(i)),n=new D(s.x*D2,this.camera.position.y-E7,s.z*D2);this.headlightSystem.aim("observer",t,n,s,S7,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,s){const n=ue.bodyOf(t),r=n.children.find(c=>c.userData.emissive);if(!r)return;const a=_2*ue.lampShare(s),o=new N3(16764006,a*this.relativeScale,A7);s?.colorTemperatureK&&o.color.setRGB(...ue.lampHue(s)),o.userData.candela=a,o.position.copy(r.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;ue.setLitWindowShare(e?un.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=gr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Ve.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},s=i(e.zenith),n=i(e.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=bs.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,T2,new oe(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<v0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=T2/Gn*(180/Math.PI),s=i/t.sunRadiusDeg,n=Li(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=Li(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(Fa(n.x*r.x+n.y*r.y+n.z*r.z,-1,1)),o=a>1e-9?Fa(t.separationDeg*s*ci/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/c,Math.sin(o*a)/c]:[1,0],u={x:n.x*h+r.x*d,y:n.y*h+r.y*d,z:n.z*h+r.z*d},p=t.moonRadiusDeg*s;this.eclipseDiscs={sun:new D(n.x,n.y,n.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*ci,moonRadiusRad:p*ci};const f=.01,m=(b,w)=>Li(e.sun.altitudeDeg+b,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:s,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new gd(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,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),this.updateSkyEvents());const t=this.scatteredSky?.ambient??he.relativeSkyOf(Dy(e.sun.altitudeDeg),this.relativeScale),i=t,s=this.lightUnderClouds(e),n=r=>s?[0,1,2].map(a=>r[a]*s.through+s.radiance[a]*(1-s.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=n(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=(r.userData.candela??_2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),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,s=(i===void 0?et.DEFAULT_AEROSOL_OPTICAL_DEPTH:Vo.opticalDepth(i))*et.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=$t.aureoleScale(s,$t.airMass(e.altitudeDeg))*n,o=$t.coronaScale(r),c=$t.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.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 jw,this.celestialGroup.add(this.lunarDiffraction.object));const d=$t.profile($t.HAZE_COARSE_MODE),u=$t.profile($t.CLOUD_DROPLETS),p=o8(e.altitudeDeg),f=new Float32Array($t.STEPS*3);let m=0;for(let w=0;w<$t.STEPS;w++){const y=w*3,M=[0,1,2].map(E=>c*p[E]*(a*d[y+E]+o*u[y+E])),x=gr.shown(M,gr.luminanceOf(M),(E,S)=>t.relativeOfLuminance(E,S));f.set(x,y),m=Math.max(m,gr.response(x))}const{x:v,y:g,z:b}=Li(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof Yc||(this.scene.fog=new Yc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+t,Math.hypot(e-s.x,t-s.y,i-s.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(e,t){return Math.max(e,t)}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,s]=this.air.transmittance(e,e,he.UMBRA_PATH_M),n=.2126*t+.7152*i+.0722*s;return n>0?[(.4124*t+.3576*i+.1805*s)/n,1,(.0193*t+.1192*i+.9505*s)/n]:[.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:bs.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?bs.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},flare:this.skyFlare}}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?_7:I7),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 D8(C1),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$a(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,s)=>this.arrivingIlluminance(i,s,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(e){const t=`${Yi.ID_PREFIX}${e}-`;for(const[i,s]of this.decorGroups){if(!s.visible||!i.startsWith(t))continue;const n=this.screenPointOf(new D().copy(s.position).sub(this.camera.position).normalize());if(n&&Math.abs(n.ndcX)<=1&&Math.abs(n.ndcY)<=1&&!this.groundHides(n.ndcX,n.ndcY))return n}}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(Um*this.camera.fov*Math.PI/180);let n,r=s;const a=new D;for(const[o,c]of this.decorGroups){if(!c.visible||!o.startsWith(Yi.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,n=o)}return n&&!this.groundHides(e,t)?n:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(Um*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}updateCelestialLight(e,t){const i=this.relativeScale,s=e.sun.altitudeDeg>=Hu,n=!s&&e.moon.altitudeDeg>=Hu,r=s?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ci)),c=this.siteElevationM+this.observerElevationM;let h=r,d=s||n?r2.directFraction(r.altitudeDeg,c):0;s&&d<=0&&e.moon.altitudeDeg>=Hu&&(h=e.moon,d=r2.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*ci)),p=s||n?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(s||n){const x=$t.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let _=0;_<3;_++)v[_]=x*E[_]*m*o,this.cloudBeam[_]=x*E[_];const{x:S,y:A,z:T}=Li(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,T),d>0){const _=$t.illuminanceOf(h.magnitude)*i,k=h===r?E:this.air.transmittanceFromSpace(c,h.altitudeDeg),L=h===r?p:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=_*k[P]*L*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const x=this.skyCloudTransmission(),E=t.skyIrradiance,S=[0,1,2].map(T=>E[T]*x+v[T]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=at.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*u),A*(S[1]+a[1]*u),A*(S[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!s&&!n||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:w,z:y}=Li(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,w,y),this.celestialLight.shadow.normalBias=O1*Fa(w/u7,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,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,s=[0,0,0];if(i){const n=qn.litFraction(t.sunElevationDeg,t.heightM);if(n>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=$t.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=he.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)s[c]=Math.max(0,a*r[c]*n*o-this.sceneSunBeam[c])}}e.traverse(n=>{const r=n.material;if(!(r instanceof ta||r instanceof Cl)||n.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=he.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*s[0]*a,r.color.g*s[1]*a,r.color.b*s[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,s=this.shadowAxisX.crossVectors(this.shadowUp,e);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(e,s).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},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,a(s)).addScaledVector(n,a(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).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,s=d7;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=Bm+5,i.near=this.shadowLightDistanceM-Bm,i.far=this.shadowLightDistanceM+Bm,i.updateProjectionMatrix(),t.bias=-.004/(2*Bm),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 s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const r=n;r.isMeshStandardMaterial&&r.envMapIntensity!==he.CABIN_SKY_SHARE&&(r.envMapIntensity=he.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(h7,Math.max(xo,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,s=i.camera;s.left=-t,s.right=t,s.top=t,s.bottom=-t;const n=Math.max(Xh,t*(Xh/xo));this.shadowLightDistanceM=Math.max(Gn,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-L1/(2*n);const r=t>2*xo?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=xo;shadowLightDistanceM=Gn;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 s=i*ci,n=Math.sin(s)*Math.cos(s)*2;for(let r=0;r<360;r+=60)e+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=n}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ve.semiSaturation(Ve.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Qs,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&&(this.meteorSystem.update(e),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(t=>this.farEmitterOf(t,t.magnitude)).filter(t=>t!==void 0)),this.refreshSkyFlare())}farEmitterOf(e,t){if(!(e.altitudeDeg>0)||!Number.isFinite(t))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(e,t,this.cloudTransmission(e)),{x:n,y:r,z:a}=Li(e.altitudeDeg,e.azimuthDeg,1);return{direction:new D(n,r,a),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:e.altitudeDeg,azimuthDeg:e.azimuthDeg,magnitude:t}}}skyFlare;refreshSkyFlare(){const e=this.emitterLights.brightestInSky;e===this.skyFlare||!e&&!this.skyFlare||(this.skyFlare=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(e,t){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const i=Qt.starPointsOf(e,t);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(e){const t=pe.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return $a(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 s=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,s,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{const e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e.develop(this.renderer,e.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}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()+he.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.size===0||performance.now()>i?s():setTimeout(n,10)};n()})}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 s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&ic(n.kind))continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Pr(n,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&s.push(r)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new kn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof Rr),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(o=>o.name.startsWith("body:")),...[this.meteorSystem?.object].filter(o=>o!==void 0),...[...this.skyEventLayers.values()].filter(o=>o.simulation?.hiddenFromEye).map(o=>o.simulation.object)],s=this.relativeScale,n=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],n,i,o=>this.measureSurroundings(o,s,n,r),e?0:kn.REFRESH_MS);a===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()}))},a))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,he.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new pd,this.framePhotograph={texture:e,scale:t,atMs:s};const r=[n.sun,n.moon].filter(a=>a.altitudeDeg>-2).map(a=>Li(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,r,a=>{const o=f=>f.map(m=>m/t),c=this.surroundings,h={up:o(a.up),down:o(a.down)},d=(f,m)=>f.some((v,g)=>Math.abs(v-m[g])>.03*Math.max(Math.abs(v),Math.abs(m[g]),1e-12)),u=!c||d(c.up,h.up)||d(c.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const p=this.scatteredSky?.adaptToSurroundings(he.adaptingLuminance(Math.exp(a.logAverage)/t,h.down))??!1;if(!u&&!p){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>=Hu?e.sun:e.moon.altitudeDeg>=Hu?e.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*s,t.up[1]*s,t.up[2]*s]}}probeIrradiance;meterFrame(){const e=this.framePhotograph;if(!this.medium?.autoExposure||!e)return;this.frameMeter??=new la;const t=this.lastAstronomy?.sun,i=t&&t.altitudeDeg>-2?Li(t.altitudeDeg,t.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??he.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,e.texture,this.camera,i,n=>{const r={mean:n.mean/e.scale,brightest:n.brightest/e.scale},a=this.frameLight,o=e.atMs,c=a?o-a.atMs:1/0,h=c<0||c>he.EXPOSURE_JUMP_MS,d=h||c===0&&a?.jumped?1:1-Math.exp(-c/s),u=(m,v)=>m>0&&v>0?m*(v/m)**d:v,p={mean:u(a?.mean??0,r.mean),brightest:u(a?.brightest??0,r.brightest),atMs:o,jumped:h||c===0&&(a?.jumped??!1)};this.frameLight=p;const f=(m,v)=>Math.abs(m-v)>.01*Math.max(m,v);(!a||f(a.mean,p.mean)||f(a.brightest,p.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(qi.uRetinaOn.value=0,this.medium)return;const e=[];for(const a of this.emitterLights.farEmitters){const o=this.screenPointOf(a.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||e.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:gr.luminanceOf(a.lux)})}const t=this.renderer.getDrawingBufferSize(this.retinaSize),i=t.x/Math.max(t.y,1),s={width:this.camera.fov*i,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>mt.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new mt,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),s,this.retinaHistoryOf);else{if(!this.retina&&e.length===0)return;this.retina??=new mt,this.retina.advance(this.recordingTimeMs,e,s)}this.retina.any&&(qi.uRetina.value=this.retina.texture,qi.uRetinaOn.value=1,qi.uRetinaViewport.value.copy(t))}retinaSize=new ie;retinaHistory;setRetinaHistory(e,t){this.retinaHistory=e,this.retinaHistoryOf=t}retinaHistoryOf;historicBleachingAt(e,t){const i=this.retinaHistory?.(e);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*ci,-(s?.headingDeg??0)*ci,(s?.rollDeg??0)*ci,"YXZ")).invert(),r=s?.fovDeg??this.camera.fov,a=[];for(const o of i.views){const c=this.farEmitterOf(o.head,o.magnitude);if(!c)continue;const h=this.screenPointIn(this.historicDirection.copy(c.direction).applyQuaternion(n),r,t);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:gr.luminanceOf(c.lux)})}return a}historicQuaternion=new Un;historicEuler=new uo;historicDirection=new D;pickAfterimageAt(e,t){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(e,t)<he.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(e){this.recordingTimeMs=e}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(e){const t=[];for(const i of e)i.traverse(s=>{s.userData.emissive===!0&&t.push(s)});return t}surroundings;animate(e,t){const i=Math.min(t/1e3,$7);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(),ue.setWindowLuminance(this.relativeScale),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.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[Py]:[],!e)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},fr.INTERVAL_MS)),qi.uRodShare.value=this.scatteredSky?.rodShare??0,qi.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);qi.uHasOverlay.value=s?1:0;const n=s?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,n,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,e);return}t.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,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 Rr&&t.userData.pointSource||t instanceof Me&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},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(n=>n.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(k1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}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(uI),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 ir({blending:ih,blendSrc:io,blendDst:io,blendSrcAlpha:io,blendDstAlpha:io,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(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=Q(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-DIlZXaIz.js");return{ReferenceSystem:s}},__vite__mapDeps([17,18]),import.meta.url).then(({ReferenceSystem:s})=>{const n=new s(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n,n.onFrame=()=>this.render(),this.referenceClock&&n.setTime(this.referenceClock);for(const[a,o]of this.referenceViews)n.setView(a,o);n.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&n.set(r.references,void 0,r.observerAt),this.render(),n})}setReferencesTime(e){this.referenceClock=e,this.references?.setTime(e)}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new D)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;e.updateMatrixWorld();const t=this.phenomena.screenBox(e);if(t&&(t.x0>1||t.x1<-1||t.y0>1||t.y1<-1))return;const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=t?this.narrowTo(e,t):e,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),a=this.phenomena.furthestM;let o=0;for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const d=c.kind!=="crop"&&this.mayHide(h,e,r,a);he.markDecorDepth(h,d),d&&o++}o>0&&(e.layers.set(D1),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null),e.layers.set(Py),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new zg;phenomenaViewProjection=new qe;occluderSphere=new ea;localBounds=new WeakMap;mayHide(e,t,i,s){let n=0;e.traverse(()=>n++);let r=this.localBounds.get(e);if(!r||r.objects!==n){e.updateMatrixWorld(!0);const o=new ai().setFromObject(e);if(o.isEmpty())return!1;r={sphere:o.getBoundingSphere(new ea).applyMatrix4(new qe().copy(e.matrixWorld).invert()),objects:n},this.localBounds.set(e,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(e.matrixWorld);return a.center.distanceTo(t.position)-a.radius>s?!1:i.intersectsSphere(a)}narrowTo(e,t){const i=this.renderer.getDrawingBufferSize(new ie),s=he.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,t.x0)+1)/2*i.x-s)),r=Math.max(0,Math.floor((Math.max(-1,t.y0)+1)/2*i.y-s)),a=Math.min(i.x,Math.ceil((Math.min(1,t.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,t.y1)+1)/2*i.y+s)),c=this.narrowCamera.copy(e);return c.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,a-n),Math.max(1,o-r)),c.updateMatrixWorld(),c}narrowCamera=new vn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ir({colorWrite:!1,side:$s});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const s=e.getObjectByName("head");if(!s)return;const n=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(he.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-r*ci}static isSolidSurface(e){if(!(e instanceof Me))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==qs}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Me))return;t&&he.isSolidSurface(i)?i.layers.enable(D1):i.layers.disable(D1)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ie),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new YN(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 s=performance.now()+he.EXPOSURE_BUDGET_MS,n=he.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,c)=>{o.visible=a[c]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&r<n);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){qi.uRodShare.value=this.scatteredSky?.rodShare??0,qi.uHasOverlay.value=1,qi.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Fr,s=new Ur(-1,1,1,-1,0,2),n=Hm/(R2*Math.tan(C2*ci/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new D).sub(this.camera.position).normalize(),c=this.screenPointOf(o);if(!c)continue;const h=new Su(a.material);h.position.set(c.ndcX,c.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new ai,i=new D,s=this.camera.getWorldDirection(new D),n=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[...n,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<he.MAP_SUBJECT_NEAREST_M)continue;let o=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(s)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),c=Math.max(c,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=o&&d>=h&&e.push({x:o,y:h,width:c-o,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 ie),i=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new up(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(e,t){return this.ghostPass?.holdsPictureAt(this.renderer,e,t)??!1}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,qi.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new ie);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new Ts(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new ie);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new qw(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ie);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new Xi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){this.aimStraightAtScreenPoint(e,t,i),e===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(e,s=>{const n=he.firstSolid(e.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(e,t,i){const s=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!s){e.setFromCamera(new ie(t,i),this.camera);return}const n=s.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(n.x,n.y,n.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),s=i.x/Math.max(i.y,1);return this.screenPointIn(t,this.camera.fov,s)}screenPointIn(e,t,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Xi.ndcFor(e,t,i);if(e.z>=0)return;const s=Math.tan(t/2*ci);return{ndcX:e.x/-e.z/(i*s),ndcY:e.y/-e.z/s}}screenPointScratch=new D;screenPointQuaternion=new Un;screenPointSize=new ie;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 s=this.renderer.domElement.width,n=this.renderer.domElement.height;e.uniforms.uResolution.value.set(s,n),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(c=>Math.max(0,c-he.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=e.uniforms.uLensPosition.value,r=e.uniforms.uTanHalfFov.value,a=this.camera.aspect,o=xi.offFrameShare(Math.atan(Math.hypot(n.x*a,n.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(o<=0))return{x:n.x,y:n.y,radius:i,flux:[t[0]*s*o,t[1]*s*o,t[2]*s*o]}}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 s=this.renderer.getDrawingBufferSize(this.screenPointSize);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(s.x,s.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(E2),this.camera.layers.set(E2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of P2)this.isSunOccluded(t[0],t[1])||e++;return e/P2.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){return this.isOccludedToward(this.sunWorldPosition,e,t)}isOccludedToward(e,t=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(e).sub(this.camera.position),r=n.length();if(n.normalize(),t!==0||i!==0){const c=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const d=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,t*c).addScaledVector(d,i*c).normalize()}if(this.groundBlocks(this.camera.position,n,r)||this.cabinMask.hides(n))return!0;const a=this.cabinMask.any?s.filter(c=>!this.cabinGroups.includes(c)):s;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(c=>!(c.object.material instanceof qo));return o!==void 0&&o.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let e=!1;for(const t of this.glareSprites.values()){if(!t.mesh.visible)continue;e||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),e=!0);const i=t.mesh.getWorldPosition(this.veilTargetScratch),s=t.mesh.material.uniforms.uSourceDeg.value,n=s>.05?he.VEIL_SAMPLES:he.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,o]of n)this.isOccludedToward(i,a*s,o*s)||r++;t.share=r/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new hr;veilTargetScratch=new D;groundBlocks(e,t,i,s=0){const n=this.groundMesh;if(n&&t.y<0){const v=(n.position.y-e.y)/t.y;if(v>s&&v<i){const g=e.x+t.x*v-n.position.x,b=e.z+t.z*v-n.position.z;if(Math.hypot(g,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=s,p=i;for(const[v,g,b]of[[e.x,t.x,c],[e.z,t.z,h]]){const w=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(g)<1e-12){if(v<w||v>y)return!1;continue}const M=(w-v)/g,x=(y-v)/g;u=Math.max(u,Math.min(M,x)),p=Math.min(p,Math.max(M,x))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,b=e.x+t.x*g,w=e.y+t.y*g,y=e.z+t.z*g;if(w<=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=Nm;let s,n;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>he.isSolidSurface(c.object));o&&(r.occludesSourceIds?.includes(i)?s=s===void 0?o.distance:Math.max(s,o.distance):n=n===void 0?o.distance:Math.min(n,o.distance))}return{behindM:s,inFrontM:n}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=p7*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,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=he.nearestBody(s,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],n);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 s,n=1/0,r=1/0,a=!1;for(const o of t){const c=Math.acos(Fa(o.direction.dot(e),-1,1))-o.radiusRad;if(c>i)continue;const h=c<=0,d=n<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:c<n)&&(s=o.key,n=c,r=o.radiusRad,a=u)}return s}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 s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,r=c7*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?he.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new ai,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,m=u.clone().sub(n),v=m.length();if(v===0||m.dot(s)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(s))),b=Math.atan(f/v);if(b>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>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,s=Math.cos(Um*this.camera.fov*Math.PI/180);let n,r=s;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,n={star:a.star,altitudeDeg:a.altitudeDeg})}return n&&this.groundHides(e,t)?void 0:n}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,Nm)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,s=1/0,n=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=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(o.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),n=Math.max(n,c.ndcX),s=Math.min(s,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:s,maxX:n,maxY:r}}bodyBoxScratch=new ai;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 s=1/0,n=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;s=Math.min(s,h.ndcX),r=Math.max(r,h.ndcX),n=Math.min(n,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:s,minY:n,maxX:r,maxY:a}}decorDrawnOffset(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,s=0){const n=this.decorGroups.get(e);if(!n)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),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*ci/2):0}decorGrabHeightAt(e,t,i){const s=this.decorGroups.get(e);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,s.position),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new ma;decorHitScratch=new D;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<he.SEE_THROUGH_BELOW||n instanceof qo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],s=he.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let r=s.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new oh().copy(s).applyMatrix4(new qe().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new D(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(n.origin,n.direction,a,he.RAILWAY_PICK_ABOVE_M))return;const o=he.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-he.RAILWAY_GROUND_MARGIN_M,Nm))return;const c=i.group.worldToLocal(o.point.clone()),h=i.lineAt(c.x,c.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickSkyEventAt(e,t,i=()=>!0){const s=[...this.skyEventLayers.values()].filter(c=>c.simulation?.pick&&c.simulation.drawnCount>0&&i(c.kind,c.simulation));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray,r={toleranceRad:he.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Um*this.camera.fov*Math.PI/180),skyLightTowards:c=>this.skyLightTowards(c)};let a;for(const c of s){const h=c.simulation.pick(n.origin,n.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:c.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(e,t)?void 0:a;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,a.distanceM-1,Nm))return;const o=he.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(o&&o.distance<a.distanceM))return a}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],s=Math.hypot(e.x,e.y,e.z)||1,n=Math.max(0,Math.min(1,e.y/s));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),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.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const e of this.skyEventLayers.values())e.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.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.mirrors.clear(),this.decorLamps=[],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 s=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!e&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),n&&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<he.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 Rs(Pm,32,16),i=t.attributes.position,s=t.getAttribute("color")??new wt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=iI(i.getX(r),i.getY(r),i.getZ(r)),c=n8(a,o,e.azimuthDeg,e.altitudeDeg);s.setXYZ(r,c[0],c[1],c[2])}if(s.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",s);const n=new ir({vertexColors:!0,side:Ji,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new Me(t,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=A2(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Fw(this.groundRadius,48),i=new ta({color:new oe(R1,R1,R1),fog:!0});Yc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Me(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 s=0;if(i){const n=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<n.count;r++)Math.abs(n.getX(r)+i.position.x)>600||Math.abs(n.getZ(r)+i.position.z)>600||(s=Math.min(s,n.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}this.groundMesh.position.y=s,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":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=Li(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Gt.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*g7);const r=t?0:this.weather.highCloudCover??0;return r>0&&(s*=1-Gt.iceAlphaAt(i,zm,r,this.cloudFieldOffset)*v7),Math.max(0,Math.min(1,s))}setBodyMesh(e,t,i,s,n){if(t.altitudeDeg<v0){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:o}=Li(t.altitudeDeg,t.azimuthDeg,Gn),c=this.cloudTransmission(t),h=this.arrivingIlluminance(t,n,c),d=he.unitLuminance(s);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Gn)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(he.BRIGHTEST_RELATIVE,v));u instanceof Me||(this.disposeMesh(u),u=new Me(new Rs(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof Rr)){this.disposeMesh(u);const m=new Tt;m.setAttribute("position",new Et(new Float32Array(3),3)),m.setAttribute("color",new Et(new Float32Array(3),3)),u=new Rr(m,Ke.material(Fd[Fd.length-1].size,!1)),Ke.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Gn*(180/Math.PI),he.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=_8(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<v0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:s,y:n,z:r}=Li(e.altitudeDeg,e.azimuthDeg,Gn),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??Ln.MEAN_RADIUS_DEG,h=Gn*Math.tan(c*ci),d=Math.max(Fa(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Gn)**2,u=new oe(...o.map(m=>Math.min(he.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(Fa(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Su?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=J2(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Su(new h0({map:J2(e.phase),color:u,fog:!1,blending:qs,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(s,n,r),this.setHitArea(i,s,n,r,h),this.setGlare(i,s,n,r,o,c)}bentLight(e,t,i=f7){const[s,n,r]=this.arrivingIlluminance(e,t,1),a=Math.max(n,1e-30);return{scale:n/i,tint:[s/a,1,r/a]}}static litBySky(e,t){return he.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new oe;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 ie;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),n=$t.illuminanceOf(t)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(e){const t=gr.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,s,n){let r=this.hitAreas.get(e);if(!r){const o=new h0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Su(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,s);const a=n*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,s,n,r,a=0){if(Vs.radiusDeg(Vs.K*Math.max(...n))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Vs(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:s},n,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 s=ud(e.magnitude,t),n=l1(s);this.cometKey=i,this.setBodyMesh(i,e.position,P1*(.5+.5*s),new oe(n,n,n),e.magnitude),this.cometTail||(this.cometTail=new _r(Gn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,s)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new gs,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(),s=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(s?.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:zm},0);return}const n=this.lowerCloudCover(),r=Mt.deckLitUntilDeg(Mt.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?yt.SUN_MAGNITUDE:t.magnitude),c=Mt.strength(i,n,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=Li(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??zm},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??y0,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Uc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=e.altitudeDeg>0,n=s?e:t,r=this.lowerCloudCover(),a=this.bentLight(n,s?yt.SUN_MAGNITUDE:t.magnitude,m7),o=Dn.strength(i,r,n.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=Li(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},o,a.tint,s)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Al,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=e.frame,n=kr.galactic(i,s),r=he.directionOf(n.centre),a=he.directionOf(n.rotation),o=he.directionOf(n.pole),c=new bt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=he.directionOf(kr.eclipticPole(i,s)),d=he.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:he.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:pe.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:s}=Li(e.altitudeDeg,e.azimuthDeg,1);return new D(t,i,s).normalize()}buildNovae(e,t){const i=new Set;for(const s of e){if(s.magnitude>t)continue;const n=`nova:${s.id}`;i.add(n);const r=ud(s.magnitude,t),a=l1(r);this.setBodyMesh(n,s.position,P1*(.5+.5*r),new oe(a,a,a),s.magnitude)}for(const s of this.novaKeys)i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s));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 s of e){if(s.magnitude>t)continue;i.add(s.body);const n=ud(s.magnitude,t),r=l1(n),a=q7[s.body]??new oe(1,1,1),o=new oe(a.r*r,a.g*r,a.b*r),c=P1*(.5+.5*n);this.setBodyMesh(s.body,s.position,c,o,s.magnitude)}for(const s of[...this.bodyMeshes.keys()])i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s))}buildStars(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=e,r=new fa(s,n),a=$1(1337),o=[],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<I2)continue;const{x:f,y:m,z:v}=Li(u,p,C1);o.push({x:f,y:m,z:v,brightness:ud(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*$t.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of wT){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<I2)continue;const{x:p,y:f,z:m}=Li(d,u,C1);this.namedStars.push({star:h,direction:new D(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=Fd.map((h,d)=>{const u=o.filter(M=>Yw(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,x)=>{p[x*3]=M.x,p[x*3+1]=M.y,p[x*3+2]=M.z,f[x]=M.brightness,m.set(M.illuminance,x*3),v[x]=M.phase,g[x]=M.speedFactor});const b=new Tt;b.setAttribute("position",new Et(p,3)),b.setAttribute("seed",new Et(v.map(M=>M/(2*Math.PI)),1));const w=new Et(new Float32Array(u.length*3),3);b.setAttribute("color",w);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new Rr(b,Ke.material(h.size)),Ke.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),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 s=i.colorAttribute.array;for(let n=0;n<i.brightness.length;n++)s[n*3]=i.illuminance[n*3]*t,s[n*3+1]=i.illuminance[n*3+1]*t,s[n*3+2]=i.illuminance[n*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Nd(this.celestialGroup,N1,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 oe(yc[0]+(B1[0]-yc[0])*t,yc[1]+(B1[1]-yc[1])*t,yc[2]+(B1[2]-yc[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:s,uniforms:n}=Ey(i,e,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=s,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Ay(N1);this.cloudMesh=new Me(r,s),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}=Ey(new oe(...yc),e,zm,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Me(Ay(N1*1.04),t),this.cirrusMesh.renderOrder=N2-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?Nd.deckOrder(!0,0,1):N2}cloudLayerOffset(){const t=((this.weather.cloudBaseM??Yy)-this.observerElevationM)*F1;return Math.sign(t||1)*Math.max(Math.abs(t),R7)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*W1*this.relativeScale/Math.PI,c=new oe(t[0]+Ra.r*o,t[1]+Ra.g*o,t[2]+Ra.b*o);this.layeredClouds?.setLighting(s.clone(),new oe(n,r,a),c,c);const h=Math.max(0,s.y);for(const d of i)d.sunDir.value.copy(s),d.sunColor.value.setRGB(n*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 B7(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,G1],[this.rainSplashSystem?.points,wc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:z1[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=z2(V1(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=z1[e],i=t.poolSize,s=$1(9001),n=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=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 w=0;w<i;w++){const y=s()*Math.PI*2,M=s()*t.radiusM;n[w*3]=Math.cos(y)*M,n[w*3+1]=Qh+s()*(t.topYM-Qh),n[w*3+2]=Math.sin(y)*M,r[w]=s()*Math.PI*2,a[w]=.7+s()*.6,o[w]=.6+s()*.8,c[w]=.4+s()*1.2}const m=new Tt;m.setAttribute("position",new Et(n,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new oe(...this.baseFogColor)},uTexture:{value:j7(e)},uNearFocusDistance:{value:W2},uHazeDistance:{value:t.radiusM*$2}},g=new Nt({uniforms:v,vertexShader:iF,fragmentShader:sF,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const b=new Rr(m,g);b.renderOrder=U1,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=n,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,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 s=z1[i];if(this.precipitationUniforms?.uColor.value.copy(he.litBySky(s.color,this.baseFogColor)),t<=0)return;const n=this.weather.windDirectionDeg*ci,r=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,a=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let y=0,M=0;y<o.length;y+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(S)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(S)*A,p[M]=0}else{const S=1-p[M]/m[M];o[y+1]=Qh+Math.sin(Math.PI*S)*f[M],o[y]=Gm(o[y]+(r+v[M])*t,s.radiusM),o[y+2]=Gm(o[y+2]+(a+g[M])*t,s.radiusM)}continue}let x=0,E=0;if(b){const S=H7*d[M],A=G7*u[M];x=Math.sin(e*S*Math.PI*2+c[M])*A,E=Math.sin(e*S*Math.PI*2+c[M]+Math.PI/2)*A}if(o[y]+=(r+x)*t,o[y+1]-=s.fallSpeedMPerS*h[M]*t,o[y+2]+=(a+E)*t,o[y]=Gm(o[y],s.radiusM),o[y+2]=Gm(o[y+2],s.radiusM),o[y+1]<Qh){if(w){f[M]=j2*(.2+Math.random()*1.6),m[M]=V7*(.5+Math.random()),p[M]=m[M];const T=Math.random()*Math.PI*2,_=W7*(f[M]/j2);v[M]=Math.cos(T)*_,g[M]=Math.sin(T)*_,o[y+1]=Qh;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(S)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=V1(this.weather.precipitationIntensity);this.rainSystem=A8({count:G1,radiusM:Gu,heightM:L7,bottomYM:F2,overallSpeed:O7,color:B2.clone(),opacity:.85,visibleCount:this.precipitationCount(G1),speedStreak:z2(e),pixelSize:X2,seed:9001,nearFocusDistanceM:W2,hazeDistanceM:Gu*$2,hazeColor:new oe(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=U1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=$1(4242),t=new Float32Array(wc*3),i=new Float32Array(wc),s=new Float32Array(wc),n=new Float32Array(wc);for(let h=0;h<wc;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Gu;t[h*3]=Math.cos(d)*u,t[h*3+1]=F2,t[h*3+2]=Math.sin(d)*u,s[h]=Z2(H2,G2),i[h]=e()*s[h],n[h]=i[h]/s[h]}const r=new Tt;r.setAttribute("position",new Et(t,3));const a=new Et(n,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(wc));const o=new Nt({uniforms:{uMaxSize:{value:U7},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:V2.clone()},uTexture:{value:Q7()}},vertexShader:eF,fragmentShader:tF,transparent:!0,depthWrite:!1}),c=new Rr(r,o);c.renderOrder=U1,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:s,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*ci;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-V1(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(he.litBySky(B2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(he.litBySky(V2,this.baseFogColor));const s=this.weather.windDirectionDeg*ci,n=Math.sin(s)*this.weather.windSpeed,r=-Math.cos(s)*this.weather.windSpeed,a=Gu,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+n*e),o(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=Y2+(1-Y2)*(1-c),d=q2+(1-q2)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=X2*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:r}=t,a=r.array;for(let o=0,c=0;o<i.length;o+=3,c++){if(s[c]+=e,s[c]>=n[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*Gu;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,n[c]=Z2(H2,G2),s[c]=0}a[c]=s[c]/n[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 o of this.lightningFlashes){if(o.t>e)break;const c=zs.brightnessAt(o,e);c>i&&(t=o,i=c)}const s=t?Math.min(1,Math.max(.1,(X7/t.distanceM)**2)):0,n=i*s*(t?.cloudToGround?1:.6);if(n===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,c=n*W1*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Ra.r*c,this.airlight[1]+Ra.g*c,this.airlight[2]+Ra.b*c)}const r=this.skyMesh?.material?.color;if(r){const o=n*Y7;r.setRGB(1+o*Ra.r,1+o*Ra.g,1+o*Ra.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*W1*this.relativeScale,t){const{x:o,y:c,z:h}=Li(25,t.azimuthDeg,Gn);this.lightningLight.position.set(o,c,h)}this.lightningBolt||(this.lightningBolt=new Tl(Gn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=T7.map(e=>{const t=Xc.point(e,this.compassPoints),i=new h0({map:nF(t),depthTest:!1,fog:!1}),s=new Su(i),{x:n,y:r,z:a}=Li(0,e,R2);return s.position.set(n,r,a),s.scale.set(Hm,Hm,1),s.renderOrder=D7,s.layers.set(k1),s.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=C2*Math.PI/360,i=Hm*Math.tan(e)/Math.tan(t);for(const s of this.compassSprites)s.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 s=i.map;s&&s.dispose(),i.dispose()}}}const ci=Math.PI/180;function Fa(l,e,t){return Math.max(e,Math.min(t,l))}function Z2(l,e){return l+Math.random()*(e-l)}function Gm(l,e){return(l%(e*2)+e*3)%(e*2)-e}let Vm,Wm;function j7(l){switch(l){case"snow":return Z7();case"hail":return J7()}}function Z7(){if(Vm)return Vm;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),Vm=new lc(e),Vm}function J7(){if(Wm)return Wm;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),Wm=new lc(e),Wm}let $m;function Q7(){if($m)return $m;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),$m=new lc(e),$m}const eF=`
|
|
11610
|
+
`,transparent:!0,blending:qs,depthWrite:!1,side:Ji,fog:!1});this.object=new Me(new Rs(jw.RADIUS,128,32,0,Math.PI*2,0,$t.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<$t.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=ln.toHalfFloat(Math.min(t[i*3+s],6e4));this.texels[i*4+3]=ln.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class lg{constructor(e){this.generator=e}static SIZE=128;target=new pf(lg.SIZE,{type:ti,generateMipmaps:!0,minFilter:Nr,magFilter:St});camera=new $w(.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,s=[]){const n=e.shadowMap.autoUpdate;let r=!1;t.traverse(o=>{const c=o;c.isLight&&c.castShadow&&c.shadow&&!c.shadow.map&&(r=!0)}),e.shadowMap.autoUpdate=r?n:!1;const a=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(e,t),s.forEach((o,c)=>{o.visible=a[c]}),e.shadowMap.autoUpdate=n,this.filteredTarget=this.generator.fromCubemap(this.target.texture,this.filteredTarget),this.capturedAtMs=performance.now()}dispose(){this.target.dispose(),this.filteredTarget?.dispose()}}class kn{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(e){kn.install(),this.generator=new wy(e),this.eye=new lg(this.generator)}static decor;refresh(e,t,i,s,n,r,a,o=[],c,h=kn.REFRESH_MS){for(const v of[...this.probes.keys()])s.some(g=>g.id===v&&g.shiny)||(this.probes.get(v).dispose(),this.probes.delete(v));const d=[{probe:this.eye}];for(const v of s){if(!v.shiny)continue;let g=this.probes.get(v.id);g||(g=new lg(this.generator),this.probes.set(v.id,g)),d.push({probe:g,reflector:v})}const u=performance.now(),p=()=>d.filter(({probe:v})=>v.capturedVersion!==a),f=p().filter(({probe:v})=>u-v.capturedAtMs>=h);if(f.length>0){const v=f.reduce((g,b)=>b.probe.capturedAtMs<g.probe.capturedAtMs?b:g);if(v.reflector){const g=v.reflector.holder.getWorldPosition(this.scratch);v.probe.capture(e,t,g,[v.reflector.holder,...n]),kn.reflectOn(v.reflector.holder,v.probe)}else{v.probe.capture(e,t,i,[...n,...o]),c?.(v.probe.sharp),kn.decor=v.probe.filtered;for(const g of r)kn.reflectOn(g,v.probe);for(const g of s)g.shiny||kn.reflectOn(g.holder,v.probe)}v.probe.capturedVersion=a}const m=p();if(m.length!==0)return Math.max(16,Math.min(...m.map(({probe:v})=>h-(u-v.capturedAtMs))))}scratch=new D;static reflectOn(e,t={filtered:kn.decor}){e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof qo?t.sharp&&n.setSurroundings(t.sharp):n instanceof Cl&&t.filtered&&n.envMap!==t.filtered&&(n.envMap=t.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const e of this.probes.values())e.dispose();this.generator.dispose()}static installed=!1;static install(){if(kn.installed)return;kn.installed=!0;const e="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!vt.lights_fragment_maps.includes(e)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}vt.lights_fragment_maps=vt.lights_fragment_maps.replace(e,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const pI=0,l9=1,c9=2,a2=2,b1=1.25,o2=1,Nn=32,Ks=Nn/4,fI=65535,m0=Math.pow(2,-24),Zw=Symbol("SKIP_GENERATION"),mI={strategy:pI,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Zw]:!1};function ws(l,e,t){return t.min.x=e[l],t.min.y=e[l+1],t.min.z=e[l+2],t.max.x=e[l+3],t.max.y=e[l+4],t.max.z=e[l+5],t}function Ny(l){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=l[i+3]-l[i];s>t&&(t=s,e=i)}return e}function l2(l,e){e.set(l)}function c2(l,e,t){let i,s;for(let n=0;n<3;n++){const r=n+3;i=l[n],s=e[n],t[n]=i<s?i:s,i=l[r],s=e[r],t[r]=i>s?i:s}}function wm(l,e,t){for(let i=0;i<3;i++){const s=e[l+2*i],n=e[l+2*i+1],r=s-n,a=s+n;r<t[i]&&(t[i]=r),a>t[i+3]&&(t[i+3]=a)}}function Ou(l){const e=l[3]-l[0],t=l[4]-l[1],i=l[5]-l[2];return 2*(e*t+t*i+i*e)}function Ds(l,e){return e[l+15]===fI}function cn(l,e){return e[l+6]}function Fn(l,e){return e[l+14]}function Xs(l){return l+Ks}function Ys(l,e){const t=e[l+6];return l+t*Ks}function Jw(l,e){return e[l+7]}function y1(l,e,t,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,v=-1/0;const g=l.offset||0;for(let b=(e-g)*6,w=(e+t-g)*6;b<w;b+=6){const y=l[b+0],M=l[b+1],x=y-M,E=y+M;x<n&&(n=x),E>o&&(o=E),y<d&&(d=y),y>f&&(f=y);const S=l[b+2],A=l[b+3],T=S-A,_=S+A;T<r&&(r=T),_>c&&(c=_),S<u&&(u=S),S>m&&(m=S);const k=l[b+4],L=l[b+5],P=k-L,C=k+L;P<a&&(a=P),C>h&&(h=C),k<p&&(p=k),k>v&&(v=k)}i[0]=n,i[1]=r,i[2]=a,i[3]=o,i[4]=c,i[5]=h,s[0]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=v}const _o=32,h9=(l,e)=>l.candidate-e.candidate,ml=new Array(_o).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Mm=new Float32Array(6);function d9(l,e,t,i,s,n){let r=-1,a=0;if(n===pI)r=Ny(e),r!==-1&&(a=(e[r]+e[r+3])/2);else if(n===l9)r=Ny(l),r!==-1&&(a=u9(t,i,s,r));else if(n===c9){const o=Ou(l);let c=b1*s;const h=t.offset||0,d=(i-h)*6,u=(i+s-h)*6;for(let p=0;p<3;p++){const f=e[p],g=(e[p+3]-f)/_o;if(s<_o/4){const b=[...ml];b.length=s;let w=0;for(let M=d;M<u;M+=6,w++){const x=b[w];x.candidate=t[M+2*p],x.count=0;const{bounds:E,leftCacheBounds:S,rightCacheBounds:A}=x;for(let T=0;T<3;T++)A[T]=1/0,A[T+3]=-1/0,S[T]=1/0,S[T+3]=-1/0,E[T]=1/0,E[T+3]=-1/0;wm(M,t,E)}b.sort(h9);let y=s;for(let M=0;M<y;M++){const x=b[M];for(;M+1<y&&b[M+1].candidate===x.candidate;)b.splice(M+1,1),y--}for(let M=d;M<u;M+=6){const x=t[M+2*p];for(let E=0;E<y;E++){const S=b[E];x>=S.candidate?wm(M,t,S.rightCacheBounds):(wm(M,t,S.leftCacheBounds),S.count++)}}for(let M=0;M<y;M++){const x=b[M],E=x.count,S=s-x.count,A=x.leftCacheBounds,T=x.rightCacheBounds;let _=0;E!==0&&(_=Ou(A)/o);let k=0;S!==0&&(k=Ou(T)/o);const L=o2+b1*(_*E+k*S);L<c&&(r=p,c=L,a=x.candidate)}}else{for(let y=0;y<_o;y++){const M=ml[y];M.count=0,M.candidate=f+g+y*g;const x=M.bounds;for(let E=0;E<3;E++)x[E]=1/0,x[E+3]=-1/0}for(let y=d;y<u;y+=6){let E=~~((t[y+2*p]-f)/g);E>=_o&&(E=_o-1);const S=ml[E];S.count++,wm(y,t,S.bounds)}const b=ml[_o-1];l2(b.bounds,b.rightCacheBounds);for(let y=_o-2;y>=0;y--){const M=ml[y],x=ml[y+1];c2(M.bounds,x.rightCacheBounds,M.rightCacheBounds)}let w=0;for(let y=0;y<_o-1;y++){const M=ml[y],x=M.count,E=M.bounds,A=ml[y+1].rightCacheBounds;x!==0&&(w===0?l2(E,Mm):c2(E,Mm,Mm)),w+=x;let T=0,_=0;w!==0&&(T=Ou(Mm)/o);const k=s-w;k!==0&&(_=Ou(A)/o);const L=o2+b1*(T*w+_*k);L<c&&(r=p,c=L,a=M.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:r,pos:a}}function u9(l,e,t,i){let s=0;const n=l.offset;for(let r=e,a=e+t;r<a;r++)s+=l[(r-n)*6+i*2];return s/t}class w1{constructor(){this.boundingData=new Float32Array(6)}}function p9(l,e,t,i,s,n){let r=i,a=i+s-1;const o=n.pos,c=n.axis*2,h=t.offset||0;for(;;){for(;r<=a&&t[(r-h)*6+c]<o;)r++;for(;r<=a&&t[(a-h)*6+c]>=o;)a--;if(r<a){for(let d=0;d<e;d++){let u=l[r*e+d];l[r*e+d]=l[a*e+d],l[a*e+d]=u}for(let d=0;d<6;d++){const u=r-h,p=a-h,f=t[u*6+d];t[u*6+d]=t[p*6+d],t[p*6+d]=f}r++,a--}else return r}}let gI,g0,Fy,vI;const f9=Math.pow(2,32);function Uy(l){return"count"in l?1:1+Uy(l.left)+Uy(l.right)}function m9(l,e,t){return gI=new Float32Array(t),g0=new Uint32Array(t),Fy=new Uint16Array(t),vI=new Uint8Array(t),By(l,e)}function By(l,e){const t=l/4,i=l/2,s="count"in e,n=e.boundingData;for(let r=0;r<6;r++)gI[t+r]=n[r];if(s)return e.buffer?(vI.set(new Uint8Array(e.buffer),l),l+e.buffer.byteLength):(g0[t+6]=e.offset,Fy[i+14]=e.count,Fy[i+15]=fI,l+Nn);{const{left:r,right:a,splitAxis:o}=e,c=l+Nn;let h=By(c,r);const d=l/Nn,p=h/Nn-d;if(p>f9)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return g0[t+6]=p,g0[t+7]=o,By(h,a)}}function g9(l,e,t,i,s,n){const{maxDepth:r,verbose:a,targetLeafSize:o,_strictLeafSize:c=1/0,strategy:h,onProgress:d}=s,u=l.primitiveBuffer,p=l.primitiveBufferStride,f=new Float32Array(6);let m=!1;const v=new w1;return y1(e,t,i,v.boundingData,f),b(v,t,i,f),v;function g(w){d&&d((w-n.offset)/n.count)}function b(w,y,M,x=null,E=0){!m&&E>=r&&(m=!0,a&&console.warn(`BVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`));const S=M>c;if(M<=o&&!S||E>=r)return g(y+M),w.offset=y,w.count=M,w;const A=d9(w.boundingData,x,e,y,M,h);let T=A.axis===-1?-1:p9(u,p,e,y,M,A);if(A.axis===-1||T===y||T===y+M){if(!S)return g(y+M),w.offset=y,w.count=M,w;A.axis=Math.max(0,Ny(w.boundingData)),T=y+Math.max(1,Math.floor(M/2))}w.splitAxis=A.axis;const _=new w1,k=y,L=T-y;w.left=_,y1(e,k,L,_.boundingData,f),b(_,k,L,f,E+1);const P=new w1,C=T,N=M-L;return w.right=P,y1(e,C,N,P.boundingData,f),b(P,C,N,f,E+1),w}}function v9(l,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=l.getRootRanges(e.range),s=i[0],n=i[i.length-1],r={offset:s.offset,count:n.offset+n.count-s.offset},a=new Float32Array(6*r.count);a.offset=r.offset,l.computePrimitiveBounds(r.offset,r.count,a),l._roots=i.map(o=>{const c=g9(l,a,o.offset,o.count,e,r),h=Uy(c),d=new t(Nn*h);return m9(0,c,d),d})}class Qw{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class b9{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const es=new b9;let Xl,vd;const Bh=[],xm=new Qw(()=>new ai);function y9(l,e,t,i,s,n){Xl=xm.getPrimitive(),vd=xm.getPrimitive(),Bh.push(Xl,vd),es.setBuffer(l._roots[e]);const r=zy(0,l.geometry,t,i,s,n);es.clearBuffer(),xm.releasePrimitive(Xl),xm.releasePrimitive(vd),Bh.pop(),Bh.pop();const a=Bh.length;return a>0&&(vd=Bh[a-1],Xl=Bh[a-2]),r}function zy(l,e,t,i,s=null,n=0,r=0){const{float32Array:a,uint16Array:o,uint32Array:c}=es;let h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);return ws(l,a,Xl),i(u,p,!1,r,n+l/Ks,Xl)}else{let T=function(k){const{uint16Array:L,uint32Array:P}=es;let C=k*2;for(;!Ds(C,L);)k=Xs(k),C=k*2;return cn(k,P)},_=function(k){const{uint16Array:L,uint32Array:P}=es;let C=k*2;for(;!Ds(C,L);)k=Ys(k,P),C=k*2;return cn(k,P)+Fn(C,L)};const u=Xs(l),p=Ys(l,c);let f=u,m=p,v,g,b,w;if(s&&(b=Xl,w=vd,ws(f,a,b),ws(m,a,w),v=s(b),g=s(w),g<v)){f=p,m=u;const k=v;v=g,g=k,b=w}b||(b=Xl,ws(f,a,b));const y=Ds(f*2,o),M=t(b,y,v,r+1,n+f/Ks);let x;if(M===a2){const k=T(f),P=_(f)-k;x=i(k,P,!0,r+1,n+f/Ks,b)}else x=M&&zy(f,e,t,i,s,n,r+1);if(x)return!0;w=vd,ws(m,a,w);const E=Ds(m*2,o),S=t(w,E,g,r+1,n+m/Ks);let A;if(S===a2){const k=T(m),P=_(m)-k;A=i(k,P,!0,r+1,n+m/Ks,w)}else A=S&&zy(m,e,t,i,s,n,r+1);return!!A}}const vp=new es.constructor,cg=new es.constructor,Il=new Qw(()=>new ai),zh=new ai,Hh=new ai,M1=new ai,x1=new ai;let S1=!1;function w9(l,e,t,i){if(S1)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");S1=!0;const s=l._roots,n=e._roots;let r,a=0,o=0;const c=new qe().copy(t).invert();for(let h=0,d=s.length;h<d;h++){vp.setBuffer(s[h]),o=0;const u=Il.getPrimitive();ws(0,vp.float32Array,u),u.applyMatrix4(c);for(let p=0,f=n.length;p<f&&(cg.setBuffer(n[p]),r=ra(0,0,t,c,i,a,o,0,0,u),cg.clearBuffer(),o+=n[p].byteLength/Nn,!r);p++);if(Il.releasePrimitive(u),vp.clearBuffer(),a+=s[h].byteLength/Nn,r)break}return S1=!1,r}function ra(l,e,t,i,s,n=0,r=0,a=0,o=0,c=null,h=!1){let d,u;h?(d=cg,u=vp):(d=vp,u=cg);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,v=u.float32Array,g=u.uint32Array,b=u.uint16Array,w=l*2,y=e*2,M=Ds(w,m),x=Ds(y,b);let E=!1;if(x&&M)h?E=s(cn(e,g),Fn(e*2,b),cn(l,f),Fn(l*2,m),o,r+e/Ks,a,n+l/Ks):E=s(cn(l,f),Fn(l*2,m),cn(e,g),Fn(e*2,b),a,n+l/Ks,o,r+e/Ks);else if(x){const S=Il.getPrimitive();ws(e,v,S),S.applyMatrix4(t);const A=Xs(l),T=Ys(l,f);ws(A,p,zh),ws(T,p,Hh);const _=S.intersectsBox(zh),k=S.intersectsBox(Hh);E=_&&ra(e,A,i,t,s,r,n,o,a+1,S,!h)||k&&ra(e,T,i,t,s,r,n,o,a+1,S,!h),Il.releasePrimitive(S)}else{const S=Xs(e),A=Ys(e,g);ws(S,v,M1),ws(A,v,x1);const T=c.intersectsBox(M1),_=c.intersectsBox(x1);if(T&&_)E=ra(l,S,t,i,s,n,r,a,o+1,c,h)||ra(l,A,t,i,s,n,r,a,o+1,c,h);else if(T)if(M)E=ra(l,S,t,i,s,n,r,a,o+1,c,h);else{const k=Il.getPrimitive();k.copy(M1).applyMatrix4(t);const L=Xs(l),P=Ys(l,f);ws(L,p,zh),ws(P,p,Hh);const C=k.intersectsBox(zh),N=k.intersectsBox(Hh);E=C&&ra(S,L,i,t,s,r,n,o,a+1,k,!h)||N&&ra(S,P,i,t,s,r,n,o,a+1,k,!h),Il.releasePrimitive(k)}else if(_)if(M)E=ra(l,A,t,i,s,n,r,a,o+1,c,h);else{const k=Il.getPrimitive();k.copy(x1).applyMatrix4(t);const L=Xs(l),P=Ys(l,f);ws(L,p,zh),ws(P,p,Hh);const C=k.intersectsBox(zh),N=k.intersectsBox(Hh);E=C&&ra(A,L,i,t,s,r,n,o,a+1,k,!h)||N&&ra(A,P,i,t,s,r,n,o,a+1,k,!h),Il.releasePrimitive(k)}}return E}const E1=new class{constructor(){let l=null,e=null,t=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=l=n._roots[r],this.uint16Array=t=new Uint16Array(l),this.uint32Array=e=new Uint32Array(l)},this.reset=()=>{this.root=null,this.buffer=l=null,this.uint16Array=t=null,this.uint32Array=e=null},this.getRangeStart=n=>{let r=n*2;for(;!Ds(r,t);)n=Xs(n),r=n*2;return cn(n,e)},this.getRangeEnd=n=>{let r=n*2;for(;!Ds(r,t);)n=Ys(n,e),r=n*2;return cn(n,e)+Fn(r,t)};const s=(n,r,a)=>{const o=r*2,c=Ds(o,t);if(!n(a,c,r)&&!c){const d=Xs(r),u=Ys(r,e);s(n,d,a+1),s(n,u,a+1)}};this.traverseBuffer=n=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{s(n,0,0)}finally{i=!1}},this.traverse=n=>{this.traverseBuffer((r,a,o)=>{if(a){const c=o*2,h=e[o+6],d=t[c+14];return n(r,a,new Float32Array(l,o*4,6),h,d)}else{const c=Jw(o,e);return n(r,a,new Float32Array(l,o*4,6),c)}})}}},h2=new ai,Gh=new Float32Array(6);class M9{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){e={...mI,...e},"maxLeafSize"in e&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafSize}),v9(this,e)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0;for(let d=e,u=e+t;d<u;d++){this.writePrimitiveBounds(d,Gh,0);const[p,f,m,v,g,b]=Gh;p<n&&(n=p),v>o&&(o=v),f<r&&(r=f),g>c&&(c=g),m<a&&(a=m),b>h&&(h=b)}return i[s+0]=n,i[s+1]=r,i[s+2]=a,i[s+3]=o,i[s+4]=c,i[s+5]=h,i}computePrimitiveBounds(e,t,i){const s=i.offset||0;for(let n=e,r=e+t;n<r;n++){this.writePrimitiveBounds(n,Gh,0);const[a,o,c,h,d,u]=Gh,p=(a+h)/2,f=(o+d)/2,m=(c+u)/2,v=(h-a)/2,g=(d-o)/2,b=(u-c)/2,w=(n-s)*6;i[w+0]=p,i[w+1]=v+(Math.abs(p)+v)*m0,i[w+2]=f,i[w+3]=g+(Math.abs(f)+g)*m0,i[w+4]=m,i[w+5]=b+(Math.abs(m)+b)*m0}return i}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const n=i[s],r=new Uint32Array(n),a=new Uint16Array(n),o=n.byteLength/Nn;for(let c=0;c<o;c++){const h=Ks*c,d=2*h;Ds(d,a)&&(r[h+6]+=e)}}}}traverse(e,t=0){E1.setBVH(this,t),E1.traverse(e),E1.reset()}refit(){const e=this._roots;for(let t=0,i=e.length;t<i;t++){const s=e[t],n=new Uint32Array(s),r=new Uint16Array(s),a=new Float32Array(s),o=s.byteLength/Nn;for(let c=o-1;c>=0;c--){const h=c*Ks,d=h*2;if(Ds(d,r)){const p=cn(h,n),f=Fn(d,r);this.writePrimitiveRangeBounds(p,f,Gh,0),a.set(Gh,h)}else{const p=Xs(h),f=Ys(h,n);for(let m=0;m<3;m++){const v=a[p+m],g=a[p+m+3],b=a[f+m],w=a[f+m+3];a[h+m]=v<b?v:b,a[h+m+3]=g>w?g:w}}}}}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{ws(0,new Float32Array(i),h2),e.union(h2)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:n,scratchPrimitive:r,iterate:a}=e;if(s&&n){const d=s;s=(u,p,f,m,v)=>d(u,p,f,m,v)?!0:a(u,p,this,n,f,m,r)}else s||(n?s=(d,u,p,f)=>a(d,u,this,n,p,f,r):s=(d,u,p)=>p);let o=!1,c=0;const h=this._roots;for(let d=0,u=h.length;d<u;d++){const p=h[d];if(o=y9(this,d,i,s,t,c),o)break;c+=p.byteLength/Nn}return o}bvhcast(e,t,i){let{intersectsRanges:s}=i;return w9(this,e,t,s)}}function x9(){return typeof SharedArrayBuffer<"u"}function eM(l){return l.index?l.index.count:l.attributes.position.count}function Xg(l){return eM(l)/3}function S9(l,e=ArrayBuffer){return l>65535?new Uint32Array(new e(4*l)):new Uint16Array(new e(2*l))}function E9(l,e){if(!l.index){const t=l.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=S9(t,i);l.setIndex(new Et(s,1));for(let n=0;n<t;n++)s[n]=n}}function A9(l,e,t){const i=eM(l)/t,s=e||l.drawRange,n=s.start/t,r=(s.start+s.count)/t,a=Math.max(0,n),o=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(o)}}function T9(l,e){return l.groups.map(t=>({offset:t.start/e,count:t.count/e}))}function d2(l,e,t){const i=A9(l,e,t),s=T9(l,t);if(!s.length)return[i];const n=[],r=i.offset,a=i.offset+i.count,o=eM(l)/t,c=[];for(const u of s){const{offset:p,count:f}=u,m=p,v=isFinite(f)?f:o-p,g=p+v;m<a&&g>r&&(c.push({pos:Math.max(r,m),isStart:!0}),c.push({pos:Math.min(a,g),isStart:!1}))}c.sort((u,p)=>u.pos!==p.pos?u.pos-p.pos:u.type==="end"?-1:1);let h=0,d=null;for(const u of c){const p=u.pos;h!==0&&p!==d&&n.push({offset:d,count:p-d}),h+=u.isStart?1:-1,d=p}return n}function I9(l,e){const t=l[l.length-1],i=t.offset+t.count>2**16,s=l.reduce((c,h)=>c+h.count,0),n=i?4:2,r=e?new SharedArrayBuffer(s*n):new ArrayBuffer(s*n),a=i?new Uint32Array(r):new Uint16Array(r);let o=0;for(let c=0;c<l.length;c++){const{offset:h,count:d}=l[c];for(let u=0;u<d;u++)a[o+u]=h+u;o+=d}return a}class _9 extends M9{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(t.useSharedArrayBuffer&&!x9())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,t={...mI,...t},t[Zw]||this.init(t)}init(e){const{geometry:t,primitiveStride:i}=this;if(e.indirect){const s=d2(t,e.range,i),n=I9(s,e.useSharedArrayBuffer);this._indirectBuffer=n}else E9(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new ai))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:d2(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class el{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let n=0,r=e.length;n<r;n++){const o=e[n][t];i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let n=0,r=t.length;n<r;n++){const a=t[n],o=e.dot(a);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}el.prototype.setFromBox=(function(){const l=new D;return function(t,i){const s=i.min,n=i.max;let r=1/0,a=-1/0;for(let o=0;o<=1;o++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){l.x=s.x*o+n.x*(1-o),l.y=s.y*c+n.y*(1-c),l.z=s.z*h+n.z*(1-h);const d=t.dot(l);r=Math.min(d,r),a=Math.max(d,a)}this.min=r,this.max=a}})();const D9=(function(){const l=new D,e=new D,t=new D;return function(s,n,r){const a=s.start,o=l,c=n.start,h=e;t.subVectors(a,c),l.subVectors(s.end,s.start),e.subVectors(n.end,n.start);const d=t.dot(h),u=h.dot(o),p=h.dot(h),f=t.dot(o),v=o.dot(o)*p-u*u;let g,b;v!==0?g=(d*u-f*p)/v:g=0,b=(d+g*u)/p,r.x=g,r.y=b}})(),tM=(function(){const l=new ie,e=new D,t=new D;return function(s,n,r,a){D9(s,n,l);let o=l.x,c=l.y;if(o>=0&&o<=1&&c>=0&&c<=1){s.at(o,r),n.at(c,a);return}else if(o>=0&&o<=1){c<0?n.at(0,a):n.at(1,a),s.closestPointToPoint(a,!0,r);return}else if(c>=0&&c<=1){o<0?s.at(0,r):s.at(1,r),n.closestPointToPoint(r,!0,a);return}else{let h;o<0?h=s.start:h=s.end;let d;c<0?d=n.start:d=n.end;const u=e,p=t;if(s.closestPointToPoint(d,!0,e),n.closestPointToPoint(h,!0,t),u.distanceToSquared(d)<=p.distanceToSquared(h)){r.copy(u),a.copy(d);return}else{r.copy(h),a.copy(p);return}}}})(),k9=(function(){const l=new D,e=new D,t=new ma,i=new Jo;return function(n,r){const{radius:a,center:o}=n,{a:c,b:h,c:d}=r;if(i.start=c,i.end=h,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a||(i.start=c,i.end=d,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a)||(i.start=h,i.end=d,i.closestPointToPoint(o,!0,l).distanceTo(o)<=a))return!0;const m=r.getPlane(t);if(Math.abs(m.distanceToPoint(o))<=a){const g=m.projectPoint(o,e);if(r.containsPoint(g))return!0}return!1}})(),R9=["x","y","z"],Ro=1e-15,u2=Ro*Ro;function Gr(l){return Math.abs(l)<Ro}class Sa extends on{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new D),this.satBounds=new Array(4).fill().map(()=>new el),this.points=[this.a,this.b,this.c],this.plane=new ma,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Jo,this.needsUpdate=!0}intersectsSphere(e){return k9(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,n=this.satAxes,r=this.satBounds,a=n[0],o=r[0];this.getNormal(a),o.setFromPoints(a,s);const c=n[1],h=r[1];c.subVectors(e,t),h.setFromPoints(c,s);const d=n[2],u=r[2];d.subVectors(t,i),u.setFromPoints(d,s);const p=n[3],f=r[3];p.subVectors(i,e),f.setFromPoints(p,s);const m=c.length(),v=d.length(),g=p.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Ro?v<Ro||g<Ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):v<Ro?g<Ro?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<Ro&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Sa.prototype.closestPointToSegment=(function(){const l=new D,e=new D,t=new Jo;return function(s,n=null,r=null){const{start:a,end:o}=s,c=this.points;let h,d=1/0;for(let u=0;u<3;u++){const p=(u+1)%3;t.start.copy(c[u]),t.end.copy(c[p]),tM(t,s,l,e),h=l.distanceToSquared(e),h<d&&(d=h,n&&n.copy(l),r&&r.copy(e))}return this.closestPointToPoint(a,l),h=a.distanceToSquared(l),h<d&&(d=h,n&&n.copy(l),r&&r.copy(a)),this.closestPointToPoint(o,l),h=o.distanceToSquared(l),h<d&&(d=h,n&&n.copy(l),r&&r.copy(o)),Math.sqrt(d)}})();Sa.prototype.intersectsTriangle=(function(){const l=new Sa,e=new el,t=new el,i=new D,s=new D,n=new D,r=new D,a=new Jo,o=new Jo,c=new D,h=new ie,d=new ie;function u(w,y,M,x){const E=i;!w.isDegenerateIntoPoint&&!w.isDegenerateIntoSegment?E.copy(w.plane.normal):E.copy(y.plane.normal);const S=w.satBounds,A=w.satAxes;for(let k=1;k<4;k++){const L=S[k],P=A[k];if(e.setFromPoints(P,y.points),L.isSeparated(e)||(r.copy(E).cross(P),e.setFromPoints(r,w.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}const T=y.satBounds,_=y.satAxes;for(let k=1;k<4;k++){const L=T[k],P=_[k];if(e.setFromPoints(P,w.points),L.isSeparated(e)||(r.crossVectors(E,P),e.setFromPoints(r,w.points),t.setFromPoints(r,y.points),e.isSeparated(t)))return!1}return M&&(x||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),M.start.set(0,0,0),M.end.set(0,0,0)),!0}function p(w,y,M,x,E,S,A,T,_,k,L){let P=A/(A-T);k.x=x+(E-x)*P,L.start.subVectors(y,w).multiplyScalar(P).add(w),P=A/(A-_),k.y=x+(S-x)*P,L.end.subVectors(M,w).multiplyScalar(P).add(w)}function f(w,y,M,x,E,S,A,T,_,k,L){if(E>0)p(w.c,w.a,w.b,x,y,M,_,A,T,k,L);else if(S>0)p(w.b,w.a,w.c,M,y,x,T,A,_,k,L);else if(T*_>0||A!=0)p(w.a,w.b,w.c,y,M,x,A,T,_,k,L);else if(T!=0)p(w.b,w.a,w.c,M,y,x,T,A,_,k,L);else if(_!=0)p(w.c,w.a,w.b,x,y,M,_,A,T,k,L);else return!0;return!1}function m(w,y,M,x){const E=y.degenerateSegment,S=w.plane.distanceToPoint(E.start),A=w.plane.distanceToPoint(E.end);return Gr(S)?Gr(A)?u(w,y,M,x):(M&&(M.start.copy(E.start),M.end.copy(E.start)),w.containsPoint(E.start)):Gr(A)?(M&&(M.start.copy(E.end),M.end.copy(E.end)),w.containsPoint(E.end)):w.plane.intersectLine(E,i)!=null?(M&&(M.start.copy(i),M.end.copy(i)),w.containsPoint(i)):!1}function v(w,y,M){const x=y.a;return Gr(w.plane.distanceToPoint(x))&&w.containsPoint(x)?(M&&(M.start.copy(x),M.end.copy(x)),!0):!1}function g(w,y,M){const x=w.degenerateSegment,E=y.a;return x.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<u2?(M&&(M.start.copy(E),M.end.copy(E)),!0):!1}function b(w,y,M,x){if(w.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=w.degenerateSegment,S=y.degenerateSegment,A=s,T=n;E.delta(A),S.delta(T);const _=i.subVectors(S.start,E.start),k=A.x*T.y-A.y*T.x;if(Gr(k))return!1;const L=(_.x*T.y-_.y*T.x)/k,P=-(A.x*_.y-A.y*_.x)/k;if(L<0||L>1||P<0||P>1)return!1;const C=E.start.z+A.z*L,N=S.start.z+T.z*P;return Gr(C-N)?(M&&(M.start.copy(E.start).addScaledVector(A,L),M.end.copy(E.start).addScaledVector(A,L)),!0):!1}else return y.isDegenerateIntoPoint?g(w,y,M):m(y,w,M,x);else{if(w.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(w.a)<u2?(M&&(M.start.copy(w.a),M.end.copy(w.a)),!0):!1:y.isDegenerateIntoSegment?g(y,w,M):v(y,w,M);if(y.isDegenerateIntoPoint)return v(w,y,M);if(y.isDegenerateIntoSegment)return m(w,y,M,x)}}return function(y,M=null,x=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(l.copy(y),l.update(),y=l);const E=b(this,y,M,x);if(E!==void 0)return E;const S=this.plane,A=y.plane;let T=A.distanceToPoint(this.a),_=A.distanceToPoint(this.b),k=A.distanceToPoint(this.c);Gr(T)&&(T=0),Gr(_)&&(_=0),Gr(k)&&(k=0);const L=T*_,P=T*k;if(L>0&&P>0)return!1;let C=S.distanceToPoint(y.a),N=S.distanceToPoint(y.b),F=S.distanceToPoint(y.c);Gr(C)&&(C=0),Gr(N)&&(N=0),Gr(F)&&(F=0);const H=C*N,j=C*F;if(H>0&&j>0)return!1;s.copy(S.normal),n.copy(A.normal);const W=s.cross(n);let J=0,re=Math.abs(W.x);const Le=Math.abs(W.y);Le>re&&(re=Le,J=1),Math.abs(W.z)>re&&(J=2);const De=R9[J],Z=this.a[De],ce=this.b[De],le=this.c[De],$=y.a[De],Ue=y.b[De],je=y.c[De];if(f(this,Z,ce,le,L,P,T,_,k,h,a))return u(this,y,M,x);if(f(y,$,Ue,je,H,j,C,N,F,d,o))return u(this,y,M,x);if(h.y<h.x){const Be=h.y;h.y=h.x,h.x=Be,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(d.y<d.x){const Be=d.y;d.y=d.x,d.x=Be,c.copy(o.start),o.start.copy(o.end),o.end.copy(c)}return h.y<d.x||d.y<h.x?!1:(M&&(d.x>h.x?M.start.copy(o.start):M.start.copy(a.start),d.y<h.y?M.end.copy(o.end):M.end.copy(a.end)),!0)}})();Sa.prototype.distanceToPoint=(function(){const l=new D;return function(t){return this.closestPointToPoint(t,l),t.distanceTo(l)}})();Sa.prototype.distanceToTriangle=(function(){const l=new D,e=new D,t=["a","b","c"],i=new Jo,s=new Jo;return function(r,a=null,o=null){const c=a||o?i:null;if(this.intersectsTriangle(r,c,!0))return(a||o)&&(a&&c.getCenter(a),o&&c.getCenter(o)),0;let h=1/0;for(let d=0;d<3;d++){let u;const p=t[d],f=r[p];this.closestPointToPoint(f,l),u=f.distanceToSquared(l),u<h&&(h=u,a&&a.copy(l),o&&o.copy(f));const m=this[p];r.closestPointToPoint(m,l),u=m.distanceToSquared(l),u<h&&(h=u,a&&a.copy(m),o&&o.copy(l))}for(let d=0;d<3;d++){const u=t[d],p=t[(d+1)%3];i.set(this[u],this[p]);for(let f=0;f<3;f++){const m=t[f],v=t[(f+1)%3];s.set(r[m],r[v]),tM(i,s,l,e);const g=l.distanceToSquared(e);g<h&&(h=g,a&&a.copy(l),o&&o.copy(e))}}return Math.sqrt(h)}})();class rr{constructor(e,t,i){this.isOrientedBox=!0,this.min=new D,this.max=new D,this.matrix=new qe,this.invMatrix=new qe,this.points=new Array(8).fill().map(()=>new D),this.satAxes=new Array(3).fill().map(()=>new D),this.satBounds=new Array(3).fill().map(()=>new el),this.alignedSatBounds=new Array(3).fill().map(()=>new el),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}rr.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const u=1*c|2*h|4*d,p=s[u];p.x=c?i.x:t.x,p.y=h?i.y:t.y,p.z=d?i.z:t.z,p.applyMatrix4(e)}const n=this.satBounds,r=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=r[c],d=n[c],u=1<<c,p=s[u];h.subVectors(a,p),d.setFromPoints(h,s)}const o=this.alignedSatBounds;o[0].setFromPointsField(s,"x"),o[1].setFromPointsField(s,"y"),o[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})();rr.prototype.intersectsBox=(function(){const l=new el;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,n=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(l.min=i.x,l.max=s.x,a[0].isSeparated(l)||(l.min=i.y,l.max=s.y,a[1].isSeparated(l))||(l.min=i.z,l.max=s.z,a[2].isSeparated(l)))return!1;for(let o=0;o<3;o++){const c=r[o],h=n[o];if(l.setFromBox(c,t),h.isSeparated(l))return!1}return!0}})();rr.prototype.intersectsTriangle=(function(){const l=new Sa,e=new Array(3),t=new el,i=new el,s=new D;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(l.copy(r),l.update(),r=l);const a=this.satBounds,o=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let u=0;u<3;u++){const p=a[u],f=o[u];if(t.setFromPoints(f,e),p.isSeparated(t))return!1}const c=r.satBounds,h=r.satAxes,d=this.points;for(let u=0;u<3;u++){const p=c[u],f=h[u];if(t.setFromPoints(f,d),p.isSeparated(t))return!1}for(let u=0;u<3;u++){const p=o[u];for(let f=0;f<4;f++){const m=h[f];if(s.crossVectors(p,m),t.setFromPoints(s,e),i.setFromPoints(s,d),t.isSeparated(i))return!1}}return!0}})();rr.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})();rr.prototype.distanceToPoint=(function(){const l=new D;return function(t){return this.closestPointToPoint(t,l),t.distanceTo(l)}})();rr.prototype.distanceToBox=(function(){const l=["x","y","z"],e=new Array(12).fill().map(()=>new Jo),t=new Array(12).fill().map(()=>new Jo),i=new D,s=new D;return function(r,a=0,o=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(o||c)&&(r.getCenter(s),this.closestPointToPoint(s,i),r.closestPointToPoint(i,s),o&&o.copy(i),c&&c.copy(s)),0;const h=a*a,d=r.min,u=r.max,p=this.points;let f=1/0;for(let v=0;v<8;v++){const g=p[v];s.copy(g).clamp(d,u);const b=g.distanceToSquared(s);if(b<f&&(f=b,o&&o.copy(g),c&&c.copy(s),b<h))return Math.sqrt(b)}let m=0;for(let v=0;v<3;v++)for(let g=0;g<=1;g++)for(let b=0;b<=1;b++){const w=(v+1)%3,y=(v+2)%3,M=g<<w|b<<y,x=1<<v|g<<w|b<<y,E=p[M],S=p[x];e[m].set(E,S);const T=l[v],_=l[w],k=l[y],L=t[m],P=L.start,C=L.end;P[T]=d[T],P[_]=g?d[_]:u[_],P[k]=b?d[k]:u[_],C[T]=u[T],C[_]=g?d[_]:u[_],C[k]=b?d[k]:u[_],m++}for(let v=0;v<=1;v++)for(let g=0;g<=1;g++)for(let b=0;b<=1;b++){s.x=v?u.x:d.x,s.y=g?u.y:d.y,s.z=b?u.z:d.z,this.closestPointToPoint(s,i);const w=s.distanceToSquared(i);if(w<f&&(f=w,o&&o.copy(i),c&&c.copy(s),w<h))return Math.sqrt(w)}for(let v=0;v<12;v++){const g=e[v];for(let b=0;b<12;b++){const w=t[b];tM(g,w,i,s);const y=i.distanceToSquared(s);if(y<f&&(f=y,o&&o.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(f)}})();class C9 extends Qw{constructor(){super(()=>new Sa)}}const jr=new C9,Pu=new D,A1=new D;function L9(l,e,t={},i=0,s=1/0){const n=i*i,r=s*s;let a=1/0,o=null;if(l.shapecast({boundsTraverseOrder:h=>(Pu.copy(e).clamp(h.min,h.max),Pu.distanceToSquared(e)),intersectsBounds:(h,d,u)=>u<a&&u<r,intersectsTriangle:(h,d)=>{h.closestPointToPoint(e,Pu);const u=e.distanceToSquared(Pu);return u<a&&(A1.copy(Pu),a=u,o=d),u<n}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(A1):t.point=A1.clone(),t.distance=c,t.faceIndex=o,t}const Sm=parseInt(Sf)>=169,O9=parseInt(Sf)<=161,gc=new D,vc=new D,bc=new D,Em=new ie,Am=new ie,Tm=new ie,p2=new D,f2=new D,m2=new D,Nu=new D;function P9(l,e,t,i,s,n,r,a){let o;if(n===Ji?o=l.intersectTriangle(i,t,e,!0,s):o=l.intersectTriangle(e,t,i,n!==$s,s),o===null)return null;const c=l.origin.distanceTo(s);return c<r||c>a?null:{distance:c,point:s.clone()}}function g2(l,e,t,i,s,n,r,a,o,c,h){gc.fromBufferAttribute(e,n),vc.fromBufferAttribute(e,r),bc.fromBufferAttribute(e,a);const d=P9(l,gc,vc,bc,Nu,o,c,h);if(d){if(i){Em.fromBufferAttribute(i,n),Am.fromBufferAttribute(i,r),Tm.fromBufferAttribute(i,a),d.uv=new ie;const p=on.getInterpolation(Nu,gc,vc,bc,Em,Am,Tm,d.uv);Sm||(d.uv=p)}if(s){Em.fromBufferAttribute(s,n),Am.fromBufferAttribute(s,r),Tm.fromBufferAttribute(s,a),d.uv1=new ie;const p=on.getInterpolation(Nu,gc,vc,bc,Em,Am,Tm,d.uv1);Sm||(d.uv1=p),O9&&(d.uv2=d.uv1)}if(t){p2.fromBufferAttribute(t,n),f2.fromBufferAttribute(t,r),m2.fromBufferAttribute(t,a),d.normal=new D;const p=on.getInterpolation(Nu,gc,vc,bc,p2,f2,m2,d.normal);d.normal.dot(l.direction)>0&&d.normal.multiplyScalar(-1),Sm||(d.normal=p)}const u={a:n,b:r,c:a,normal:new D,materialIndex:0};if(on.getNormal(gc,vc,bc,u.normal),d.face=u,d.faceIndex=n,Sm){const p=new D;on.getBarycoord(Nu,gc,vc,bc,p),d.barycoord=p}}return d}function v2(l){return l&&l.isMaterial?l.side:l}function Yg(l,e,t,i,s,n,r){const a=i*3;let o=a+0,c=a+1,h=a+2;const{index:d,groups:u}=l;l.index&&(o=d.getX(o),c=d.getX(c),h=d.getX(h));const{position:p,normal:f,uv:m,uv1:v}=l.attributes;if(Array.isArray(e)){const g=i*3;for(let b=0,w=u.length;b<w;b++){const{start:y,count:M,materialIndex:x}=u[b];if(g>=y&&g<y+M){const E=v2(e[x]),S=g2(t,p,f,m,v,o,c,h,E,n,r);if(S)if(S.faceIndex=i,S.face.materialIndex=x,s)s.push(S);else return S}}}else{const g=v2(e),b=g2(t,p,f,m,v,o,c,h,g,n,r);if(b)if(b.faceIndex=i,b.face.materialIndex=0,s)s.push(b);else return b}return null}function Us(l,e,t,i){const s=l.a,n=l.b,r=l.c;let a=e,o=e+1,c=e+2;t&&(a=t.getX(a),o=t.getX(o),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),r.x=i.getX(c),r.y=i.getY(c),r.z=i.getZ(c)}function N9(l,e,t,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=l;for(let h=i,d=i+s;h<d;h++)Yg(o,e,t,h,n,r,a)}function F9(l,e,t,i,s,n,r){const{geometry:a,_indirectBuffer:o}=l;let c=1/0,h=null;for(let d=i,u=i+s;d<u;d++){let p;p=Yg(a,e,t,d,null,n,r),p&&p.distance<c&&(h=p,c=p.distance)}return h}function U9(l,e,t,i,s,n,r){const{geometry:a}=t,{index:o}=a,c=a.attributes.position;for(let h=l,d=e+l;h<d;h++){let u;if(u=h,Us(r,u*3,o,c),r.needsUpdate=!0,i(r,u,s,n))return!0}return!1}function B9(l,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=l.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let n,r,a,o,c=0;const h=l._roots;for(let u=0,p=h.length;u<p;u++)n=h[u],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),d(0,c),c+=n.byteLength;function d(u,p,f=!1){const m=u*2;if(Ds(m,a)){const v=cn(u,r),g=Fn(m,a);let b=1/0,w=1/0,y=1/0,M=-1/0,x=-1/0,E=-1/0;for(let S=3*v,A=3*(v+g);S<A;S++){let T=i[S];const _=s.getX(T),k=s.getY(T),L=s.getZ(T);_<b&&(b=_),_>M&&(M=_),k<w&&(w=k),k>x&&(x=k),L<y&&(y=L),L>E&&(E=L)}return o[u+0]!==b||o[u+1]!==w||o[u+2]!==y||o[u+3]!==M||o[u+4]!==x||o[u+5]!==E?(o[u+0]=b,o[u+1]=w,o[u+2]=y,o[u+3]=M,o[u+4]=x,o[u+5]=E,!0):!1}else{const v=Xs(u),g=Ys(u,r);let b=f,w=!1,y=!1;if(e){if(!b){const T=v/Ks+p/Nn,_=g/Ks+p/Nn;w=e.has(T),y=e.has(_),b=!w&&!y}}else w=!0,y=!0;const M=b||w,x=b||y;let E=!1;M&&(E=d(v,p,b));let S=!1;x&&(S=d(g,p,b));const A=E||S;if(A)for(let T=0;T<3;T++){const _=v+T,k=g+T,L=o[_],P=o[_+3],C=o[k],N=o[k+3];o[u+T]=L<C?L:C,o[u+T+3]=P>N?P:N}return A}}}function rc(l,e,t,i,s){let n,r,a,o,c,h;const d=1/t.direction.x,u=1/t.direction.y,p=1/t.direction.z,f=t.origin.x,m=t.origin.y,v=t.origin.z;let g=e[l],b=e[l+3],w=e[l+1],y=e[l+3+1],M=e[l+2],x=e[l+3+2];return d>=0?(n=(g-f)*d,r=(b-f)*d):(n=(b-f)*d,r=(g-f)*d),u>=0?(a=(w-m)*u,o=(y-m)*u):(a=(y-m)*u,o=(w-m)*u),n>o||a>r||((a>n||isNaN(n))&&(n=a),(o<r||isNaN(r))&&(r=o),p>=0?(c=(M-v)*p,h=(x-v)*p):(c=(x-v)*p,h=(M-v)*p),n>h||c>r)?!1:((c>n||n!==n)&&(n=c),(h<r||r!==r)&&(r=h),n<=s&&r>=i)}function z9(l,e,t,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=l;for(let h=i,d=i+s;h<d;h++){let u=c?c[h]:h;Yg(o,e,t,u,n,r,a)}}function H9(l,e,t,i,s,n,r){const{geometry:a,_indirectBuffer:o}=l;let c=1/0,h=null;for(let d=i,u=i+s;d<u;d++){let p;p=Yg(a,e,t,o?o[d]:d,null,n,r),p&&p.distance<c&&(h=p,c=p.distance)}return h}function G9(l,e,t,i,s,n,r){const{geometry:a}=t,{index:o}=a,c=a.attributes.position;for(let h=l,d=e+l;h<d;h++){let u;if(u=t.resolveTriangleIndex(h),Us(r,u*3,o,c),r.needsUpdate=!0,i(r,u,s,n))return!0}return!1}function V9(l,e,t,i,s,n,r){es.setBuffer(l._roots[e]),Hy(0,l,t,i,s,n,r),es.clearBuffer()}function Hy(l,e,t,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=es,h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);N9(e,t,i,u,p,s,n,r)}else{const u=Xs(l);rc(u,a,i,n,r)&&Hy(u,e,t,i,s,n,r);const p=Ys(l,c);rc(p,a,i,n,r)&&Hy(p,e,t,i,s,n,r)}}const W9=["x","y","z"];function $9(l,e,t,i,s,n){es.setBuffer(l._roots[e]);const r=Gy(0,l,t,i,s,n);return es.clearBuffer(),r}function Gy(l,e,t,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=es;let c=l*2;if(Ds(c,a)){const d=cn(l,o),u=Fn(c,a);return F9(e,t,i,d,u,s,n)}else{const d=Jw(l,o),u=W9[d],f=i.direction[u]>=0;let m,v;f?(m=Xs(l),v=Ys(l,o)):(m=Ys(l,o),v=Xs(l));const b=rc(m,r,i,s,n)?Gy(m,e,t,i,s,n):null;if(b){const M=b.point[u];if(f?M<=r[v+d]:M>=r[v+d+3])return b}const y=rc(v,r,i,s,n)?Gy(v,e,t,i,s,n):null;return b&&y?b.distance<=y.distance?b:y:b||y||null}}const Im=new ai,Vh=new Sa,Wh=new Sa,Fu=new qe,b2=new rr,_m=new rr;function K9(l,e,t,i){es.setBuffer(l._roots[e]);const s=Vy(0,l,t,i);return es.clearBuffer(),s}function Vy(l,e,t,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=es;let o=l*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),b2.set(t.boundingBox.min,t.boundingBox.max,i),s=b2),Ds(o,r)){const h=e.geometry,d=h.index,u=h.attributes.position,p=t.index,f=t.attributes.position,m=cn(l,a),v=Fn(o,r);if(Fu.copy(i).invert(),t.boundsTree)return ws(l,n,_m),_m.matrix.copy(Fu),_m.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>_m.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(i),b.b.applyMatrix4(i),b.c.applyMatrix4(i),b.needsUpdate=!0;for(let w=m*3,y=(v+m)*3;w<y;w+=3)if(Us(Wh,w,d,u),Wh.needsUpdate=!0,b.intersectsTriangle(Wh))return!0;return!1}});{const g=Xg(t);for(let b=m*3,w=(v+m)*3;b<w;b+=3){Us(Vh,b,d,u),Vh.a.applyMatrix4(Fu),Vh.b.applyMatrix4(Fu),Vh.c.applyMatrix4(Fu),Vh.needsUpdate=!0;for(let y=0,M=g*3;y<M;y+=3)if(Us(Wh,y,p,f),Wh.needsUpdate=!0,Vh.intersectsTriangle(Wh))return!0}}}else{const h=Xs(l),d=Ys(l,a);return ws(h,n,Im),!!(s.intersectsBox(Im)&&Vy(h,e,t,i,s)||(ws(d,n,Im),s.intersectsBox(Im)&&Vy(d,e,t,i,s)))}}const Dm=new qe,T1=new rr,Uu=new rr,X9=new D,Y9=new D,q9=new D,j9=new D;function Z9(l,e,t,i={},s={},n=0,r=1/0){e.boundingBox||e.computeBoundingBox(),T1.set(e.boundingBox.min,e.boundingBox.max,t),T1.needsUpdate=!0;const a=l.geometry,o=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=jr.getPrimitive(),p=jr.getPrimitive();let f=X9,m=Y9,v=null,g=null;s&&(v=q9,g=j9);let b=1/0,w=null,y=null;return Dm.copy(t).invert(),Uu.matrix.copy(Dm),l.shapecast({boundsTraverseOrder:M=>T1.distanceToBox(M),intersectsBounds:(M,x,E)=>E<b&&E<r?(x&&(Uu.min.copy(M.min),Uu.max.copy(M.max),Uu.needsUpdate=!0),!0):!1,intersectsRange:(M,x)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:S=>Uu.distanceToBox(S),intersectsBounds:(S,A,T)=>T<b&&T<r,intersectsRange:(S,A)=>{for(let T=S,_=S+A;T<_;T++){Us(p,3*T,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let k=M,L=M+x;k<L;k++){Us(u,3*k,c,o),u.needsUpdate=!0;const P=u.distanceToTriangle(p,f,v);if(P<b&&(m.copy(f),g&&g.copy(v),b=P,w=k,y=T),P<n)return!0}}}});{const E=Xg(e);for(let S=0,A=E;S<A;S++){Us(p,3*S,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let T=M,_=M+x;T<_;T++){Us(u,3*T,c,o),u.needsUpdate=!0;const k=u.distanceToTriangle(p,f,v);if(k<b&&(m.copy(f),g&&g.copy(v),b=k,w=T,y=S),k<n)return!0}}}}}),jr.releasePrimitive(u),jr.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=b,i.faceIndex=w,s&&(s.point?s.point.copy(g):s.point=g.clone(),s.point.applyMatrix4(Dm),m.applyMatrix4(Dm),s.distance=m.sub(s.point).length(),s.faceIndex=y),i)}function J9(l,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=l.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let n,r,a,o,c=0;const h=l._roots;for(let u=0,p=h.length;u<p;u++)n=h[u],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),d(0,c),c+=n.byteLength;function d(u,p,f=!1){const m=u*2;if(Ds(m,a)){const v=cn(u,r),g=Fn(m,a);let b=1/0,w=1/0,y=1/0,M=-1/0,x=-1/0,E=-1/0;for(let S=v,A=v+g;S<A;S++){const T=3*l.resolveTriangleIndex(S);for(let _=0;_<3;_++){let k=T+_;k=i?i[k]:k;const L=s.getX(k),P=s.getY(k),C=s.getZ(k);L<b&&(b=L),L>M&&(M=L),P<w&&(w=P),P>x&&(x=P),C<y&&(y=C),C>E&&(E=C)}}return o[u+0]!==b||o[u+1]!==w||o[u+2]!==y||o[u+3]!==M||o[u+4]!==x||o[u+5]!==E?(o[u+0]=b,o[u+1]=w,o[u+2]=y,o[u+3]=M,o[u+4]=x,o[u+5]=E,!0):!1}else{const v=Xs(u),g=Ys(u,r);let b=f,w=!1,y=!1;if(e){if(!b){const T=v/Ks+p/Nn,_=g/Ks+p/Nn;w=e.has(T),y=e.has(_),b=!w&&!y}}else w=!0,y=!0;const M=b||w,x=b||y;let E=!1;M&&(E=d(v,p,b));let S=!1;x&&(S=d(g,p,b));const A=E||S;if(A)for(let T=0;T<3;T++){const _=v+T,k=g+T,L=o[_],P=o[_+3],C=o[k],N=o[k+3];o[u+T]=L<C?L:C,o[u+T+3]=P>N?P:N}return A}}}function Q9(l,e,t,i,s,n,r){es.setBuffer(l._roots[e]),Wy(0,l,t,i,s,n,r),es.clearBuffer()}function Wy(l,e,t,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=es,h=l*2;if(Ds(h,o)){const u=cn(l,c),p=Fn(h,o);z9(e,t,i,u,p,s,n,r)}else{const u=Xs(l);rc(u,a,i,n,r)&&Wy(u,e,t,i,s,n,r);const p=Ys(l,c);rc(p,a,i,n,r)&&Wy(p,e,t,i,s,n,r)}}const e7=["x","y","z"];function t7(l,e,t,i,s,n){es.setBuffer(l._roots[e]);const r=$y(0,l,t,i,s,n);return es.clearBuffer(),r}function $y(l,e,t,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=es;let c=l*2;if(Ds(c,a)){const d=cn(l,o),u=Fn(c,a);return H9(e,t,i,d,u,s,n)}else{const d=Jw(l,o),u=e7[d],f=i.direction[u]>=0;let m,v;f?(m=Xs(l),v=Ys(l,o)):(m=Ys(l,o),v=Xs(l));const b=rc(m,r,i,s,n)?$y(m,e,t,i,s,n):null;if(b){const M=b.point[u];if(f?M<=r[v+d]:M>=r[v+d+3])return b}const y=rc(v,r,i,s,n)?$y(v,e,t,i,s,n):null;return b&&y?b.distance<=y.distance?b:y:b||y||null}}const km=new ai,$h=new Sa,Kh=new Sa,Bu=new qe,y2=new rr,Rm=new rr;function i7(l,e,t,i){es.setBuffer(l._roots[e]);const s=Ky(0,l,t,i);return es.clearBuffer(),s}function Ky(l,e,t,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=es;let o=l*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),y2.set(t.boundingBox.min,t.boundingBox.max,i),s=y2),Ds(o,r)){const h=e.geometry,d=h.index,u=h.attributes.position,p=t.index,f=t.attributes.position,m=cn(l,a),v=Fn(o,r);if(Bu.copy(i).invert(),t.boundsTree)return ws(l,n,Rm),Rm.matrix.copy(Bu),Rm.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:b=>Rm.intersectsBox(b),intersectsTriangle:b=>{b.a.applyMatrix4(i),b.b.applyMatrix4(i),b.c.applyMatrix4(i),b.needsUpdate=!0;for(let w=m,y=v+m;w<y;w++)if(Us(Kh,3*e.resolveTriangleIndex(w),d,u),Kh.needsUpdate=!0,b.intersectsTriangle(Kh))return!0;return!1}});{const g=Xg(t);for(let b=m,w=v+m;b<w;b++){const y=e.resolveTriangleIndex(b);Us($h,3*y,d,u),$h.a.applyMatrix4(Bu),$h.b.applyMatrix4(Bu),$h.c.applyMatrix4(Bu),$h.needsUpdate=!0;for(let M=0,x=g*3;M<x;M+=3)if(Us(Kh,M,p,f),Kh.needsUpdate=!0,$h.intersectsTriangle(Kh))return!0}}}else{const h=Xs(l),d=Ys(l,a);return ws(h,n,km),!!(s.intersectsBox(km)&&Ky(h,e,t,i,s)||(ws(d,n,km),s.intersectsBox(km)&&Ky(d,e,t,i,s)))}}const Cm=new qe,I1=new rr,zu=new rr,s7=new D,n7=new D,r7=new D,a7=new D;function o7(l,e,t,i={},s={},n=0,r=1/0){e.boundingBox||e.computeBoundingBox(),I1.set(e.boundingBox.min,e.boundingBox.max,t),I1.needsUpdate=!0;const a=l.geometry,o=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=jr.getPrimitive(),p=jr.getPrimitive();let f=s7,m=n7,v=null,g=null;s&&(v=r7,g=a7);let b=1/0,w=null,y=null;return Cm.copy(t).invert(),zu.matrix.copy(Cm),l.shapecast({boundsTraverseOrder:M=>I1.distanceToBox(M),intersectsBounds:(M,x,E)=>E<b&&E<r?(x&&(zu.min.copy(M.min),zu.max.copy(M.max),zu.needsUpdate=!0),!0):!1,intersectsRange:(M,x)=>{if(e.boundsTree){const E=e.boundsTree;return E.shapecast({boundsTraverseOrder:S=>zu.distanceToBox(S),intersectsBounds:(S,A,T)=>T<b&&T<r,intersectsRange:(S,A)=>{for(let T=S,_=S+A;T<_;T++){const k=E.resolveTriangleIndex(T);Us(p,3*k,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let L=M,P=M+x;L<P;L++){const C=l.resolveTriangleIndex(L);Us(u,3*C,c,o),u.needsUpdate=!0;const N=u.distanceToTriangle(p,f,v);if(N<b&&(m.copy(f),g&&g.copy(v),b=N,w=L,y=T),N<n)return!0}}}})}else{const E=Xg(e);for(let S=0,A=E;S<A;S++){Us(p,3*S,d,h),p.a.applyMatrix4(t),p.b.applyMatrix4(t),p.c.applyMatrix4(t),p.needsUpdate=!0;for(let T=M,_=M+x;T<_;T++){const k=l.resolveTriangleIndex(T);Us(u,3*k,c,o),u.needsUpdate=!0;const L=u.distanceToTriangle(p,f,v);if(L<b&&(m.copy(f),g&&g.copy(v),b=L,w=T,y=S),L<n)return!0}}}}}),jr.releasePrimitive(u),jr.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=b,i.faceIndex=w,s&&(s.point?s.point.copy(g):s.point=g.clone(),s.point.applyMatrix4(Cm),m.applyMatrix4(Cm),s.distance=m.sub(s.point).length(),s.faceIndex=y),i)}function w2(l,e,t){return l===null?null:(l.point.applyMatrix4(e.matrixWorld),l.distance=l.point.distanceTo(t.ray.origin),l.object=e,l)}const Lm=new rr,Om=new oh,M2=new D,x2=new qe,S2=new D,_1=["getX","getY","getZ"];class hg extends _9{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,n=e._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(o=>o.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=n?n.slice():null):(a.roots=s,a.index=r?r.array:null,a.indirectBuffer=n),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:n,indirectBuffer:r}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),o(n));const a=new hg(t,{...i,[Zw]:!0});if(a._roots=n,a._indirectBuffer=r||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new Et(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function o(c){for(let h=0;h<c.length;h++){const d=c[h],u=new Uint32Array(d),p=new Uint16Array(d);for(let f=0,m=d.byteLength/Nn;f<m;f++){const v=Ks*f,g=2*v;Ds(g,p)||(u[v+6]=u[v+6]/Ks-f)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,c=(n?n[e]:e)*3;let h=c+0,d=c+1,u=c+2;a&&(h=a[h],d=a[d],u=a[u]);for(let p=0;p<3;p++){const f=r[_1[p]](h),m=r[_1[p]](d),v=r[_1[p]](u);let g=f;m<g&&(g=m),v<g&&(g=v);let b=f;m>b&&(b=m),v>b&&(b=v),t[i+p]=g,t[i+p+3]=b}return t}computePrimitiveBounds(e,t,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,o=r.normalized;if(e<0||t+e-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const c=r.array,h=r.offset||0;let d=3;r.isInterleavedBufferAttribute&&(d=r.data.stride);const u=["getX","getY","getZ"],p=i.offset;for(let f=e,m=e+t;f<m;f++){const g=(n?n[f]:f)*3,b=(f-p)*6;let w=g+0,y=g+1,M=g+2;a&&(w=a[w],y=a[y],M=a[M]),o||(w=w*d+h,y=y*d+h,M=M*d+h);for(let x=0;x<3;x++){let E,S,A;o?(E=r[u[x]](w),S=r[u[x]](y),A=r[u[x]](M)):(E=c[w+x],S=c[y+x],A=c[M+x]);let T=E;S<T&&(T=S),A<T&&(T=A);let _=E;S>_&&(_=S),A>_&&(_=A);const k=(_-T)/2,L=x*2;i[b+L+0]=T+k,i[b+L+1]=k+(Math.abs(T)+k)*m0}}return i}raycastObject3D(e,t,i=[]){const{material:s}=e;if(s===void 0)return;x2.copy(e.matrixWorld).invert(),Om.copy(t.ray).applyMatrix4(x2),S2.setFromMatrixScale(e.matrixWorld),M2.copy(Om.direction).multiply(S2);const n=M2.length(),r=t.near/n,a=t.far/n;if(t.firstHitOnly===!0){let o=this.raycastFirst(Om,s,r,a);o=w2(o,e,t),o&&i.push(o)}else{const o=this.raycast(Om,s,r,a);for(let c=0,h=o.length;c<h;c++){const d=w2(o[c],e,t);d&&i.push(d)}}return i}refit(e=null){return(this.indirect?J9:B9)(this,e)}raycast(e,t=ho,i=0,s=1/0){const n=this._roots,r=[],a=this.indirect?Q9:V9;for(let o=0,c=n.length;o<c;o++)a(this,o,t,e,r,i,s);return r}raycastFirst(e,t=ho,i=0,s=1/0){const n=this._roots;let r=null;const a=this.indirect?t7:$9;for(let o=0,c=n.length;o<c;o++){const h=a(this,o,t,e,i,s);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(e,t){let i=!1;const s=this._roots,n=this.indirect?i7:K9;for(let r=0,a=s.length;r<a&&(i=n(this,r,e,t),!i);r++);return i}shapecast(e){const t=jr.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?G9:U9});return jr.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const r=jr.getPrimitive(),a=this.geometry.index,o=this.geometry.attributes.position,c=this.indirect?f=>{const m=this.resolveTriangleIndex(f);Us(r,m*3,a,o)}:f=>{Us(r,f*3,a,o)},h=jr.getPrimitive(),d=e.geometry.index,u=e.geometry.attributes.position,p=e.indirect?f=>{const m=e.resolveTriangleIndex(f);Us(h,m*3,d,u)}:f=>{Us(h,f*3,d,u)};if(n){if(!(e instanceof hg))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const f=(m,v,g,b,w,y,M,x)=>{for(let E=g,S=g+b;E<S;E++){p(E),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let A=m,T=m+v;A<T;A++)if(c(A),r.needsUpdate=!0,n(r,h,A,E,w,y,M,x))return!0}return!1};if(s){const m=s;s=function(v,g,b,w,y,M,x,E){return m(v,g,b,w,y,M,x,E)?!0:f(v,g,b,w,y,M,x,E)}}else s=f}return super.bvhcast(e,t,{intersectsRanges:s})}intersectsBox(e,t){return Lm.set(e.min,e.max,t),Lm.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Lm.intersectsBox(i),intersectsTriangle:i=>Lm.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},n=0,r=1/0){return(this.indirect?o7:Z9)(this,e,t,i,s,n,r)}closestPointToPoint(e,t={},i=0,s=1/0){return L9(this,e,t,i,s)}}class Na{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ea;static install(){if(Na.installed)return;Na.installed=!0;const e=Me.prototype.raycast;Me.prototype.raycast=function(t,i){const s=Na.treeOf(this,t);s!==null&&(s?s.raycastObject3D(this,t,i):e.call(this,t,i))}}static treeOf(e,t){const i=e.geometry,s=i?.attributes.position;if(!(s instanceof Et)||e.material===void 0||e.isSkinnedMesh||e.isInstancedMesh||e.isBatchedMesh||i.morphAttributes.position)return;const n=i.index;if((n?n.count:s.count)/3<Na.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const r=Na.sphere.copy(i.boundingSphere).applyMatrix4(e.matrixWorld);if(!t.ray.intersectsSphere(r))return null;const a=Na.trees.get(i);if(a){if(!a.bvh)return;if(a.position===s&&a.positionVersion===s.version&&a.index===n&&a.indexVersion===(n?.version??0))return a.bvh;Na.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const o=new hg(i,{indirect:!0});return Na.trees.set(i,{bvh:o,position:s,positionVersion:s.version,index:n,indexVersion:n?.version??0}),o}}function l7(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.rareIceCrystals===e.rareIceCrystals&&l.lowerCloudCover===e.lowerCloudCover&&l.relativeHumidity===e.relativeHumidity&&l.precipitationType===e.precipitationType&&l.precipitationIntensity===e.precipitationIntensity&&l.precipitationAmount===e.precipitationAmount&&l.windDirectionDeg===e.windDirectionDeg&&l.windSpeed===e.windSpeed&&l.storm===e.storm}const Pm=900,D1=1,E2=4,k1=5,Nm=.5,Fm=_t.GROUND_RADIUS_M;function A2(l){return _t.groundRadiusFor(l)}const R1=.5,C1=850,Um=.03,c7=.015,Gn=850,Xh=300,xo=120,h7=700,L1=.03,d7=3.5,Bm=20,O1=.04,u7=.26,T2=4,P1=1.5,I2=-1,p7=.01,v0=-4,f7=2,m7=20,zm=2600,g7=.97,v7=.38,Hu=v0,b7=8,y7=2,_2=1500,w7=.7,M7=.3,x7=.32,S7=.65,D2=2.4,E7=.9,A7=400,T7=[0,45,90,135,180,225,270,315],I7=2,_7=16,k2=4e3,R2=880,Hm=40,C2=60,D7=10,L2=1,k7=_t.REBUILD_DISTANCE_M,O2=.265,P2=[[0,0],...Array.from({length:8},(l,e)=>{const t=e*Math.PI/4;return[Math.cos(t)*O2,Math.sin(t)*O2]})],N1=700,F1=250/Yy,R7=12,N2=5,U1=6,yc=[.92,.92,.95],B1=[.15,.15,.19],z1={snow:{fallSpeedMPerS:2,size:.3,color:new oe(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new oe(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},Qh=0,H1=0,C7=150,G1=3e3,Gu=20,L7=15,F2=Qh,O7=40,U2=1,P7=9;function V1(l){return U2+(P7-U2)*l}const B2=new oe(.75,.82,.92),N7=10,F7=.5;function z2(l){return Fa(l/N7,F7,1)}const wc=200,H2=.18,G2=.32,U7=.35,V2=new oe(.85,.9,.98),W2=5,$2=.85,K2=.01;function B7(l,e,t=1){return Math.round(l*(K2+(1-K2)*e)*t)}function z7(l,e){return JSON.stringify(l.cloudLayers)===JSON.stringify(e.cloudLayers)&&l.cloudCover===e.cloudCover&&l.cloudDarkness===e.cloudDarkness&&l.cloudBaseM===e.cloudBaseM&&l.highCloudCover===e.highCloudCover&&l.iceCrystalAlignment===e.iceCrystalAlignment&&l.lowerCloudCover===e.lowerCloudCover}const X2=230,Y2=.7,q2=.05,H7=.6,G7=.7,V7=.15,j2=.35,W7=3,$7=1/12,K7=.5,Ra=new oe(.82,.86,1),X7=2500,Y7=1.6,W1=15,q7={Venus:new oe(1,.96,.85),Mars:new oe(1,.55,.4),Jupiter:new oe(.95,.87,.72),Saturn:new oe(.92,.86,.68)};class he{renderer;scene=new Fr;phenomena=new da(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new ii;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(e,t){if(this.skyHoldUntilMs===null)return e;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=t===void 0?void 0:setTimeout(s,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(n),s()})}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()+k2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),k2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new At;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new ie;decorModelProvider=new mp;decorModelToken=0;decorModelCredits=new Map;emitterLights=new Wn(this.scene,()=>this.relativeScale,{halfExtentM:xo,depthHalfRangeM:Xh,biasM:L1,normalBiasM:O1,mapSize:1024});bodySystem=new ut(e=>this.awaitArrival(this.loadBodyModel(e)),()=>this.render(),()=>this.relativeScale,e=>this.emitterLights.set("bodies",e));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??he.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*he.TRAFFIC_MODEL_RANGE_PER_METRE}pendingTrafficModels=new Map;contrails=[];contrailSystem;contrailSystemLoading;skyEventsStated;skyEventsStart;skyEventLayers=new Map;contrailSunlight=new Map;sceneSunBeam=[0,0,0];decorReferencePose;decorCurrentPose;decorTime=0;celestialLight=new Z0(16777215,0);celestialLightTarget=new Qi;skyLight=new SC(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 d0;weather=xg;observerElevationM=0;siteElevationM=0;air=new Xr;groundRadius=Fm;terrainRadius=Fm;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 ie;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new Z0(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new D;sunVisible=!1;lensFlareScratch=new D;sunOcclusionRaycaster=new d0;sunOcclusionDirectionScratch=new D;sunOcclusionRightScratch=new D;sunOcclusionUpScratch=new D;ufoOcclusionRaycaster=new d0;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=xi.NONE;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;iceHalos;lunarDiffraction;eclipsedSun=new ff;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(e,t=VT()){cp.install(),Na.install(),this.renderer=new UN({canvas:e,antialias:!0}),this.resolution=new di(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=tp,this.camera=new vn(60,e.width/Math.max(e.height,1),.1,Pm*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=-xo,this.celestialLight.shadow.camera.right=xo,this.celestialLight.shadow.camera.top=xo,this.celestialLight.shadow.camera.bottom=-xo,this.celestialLight.shadow.camera.near=Gn-Xh,this.celestialLight.shadow.camera.far=Gn+Xh,this.celestialLight.shadow.bias=-L1/(2*Xh),this.celestialLight.shadow.normalBias=O1,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Ra),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 yt(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(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*F1,0,e.z*F1);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){this.updateLookPatch(e);const t=((e.rollDeg??0)+this.gaitOffset.rollDeg)*ci,i=(e.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*ci;e.headingDeg!==void 0?this.camera.rotation.set(i,-(e.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*ci,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(A2(e.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Fm),this.camera.far=Math.max(Pm*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.dropFarRing(),this.dropLookPatch(),this.terrainOrigin=void 0,this.terrainMeshOrigin=void 0,this.terrainAttribution=void 0,this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.roadWays=void 0,this.clearWater(),this.waterSurfaces=void 0,this.clearRailways(),this.railwayLines=void 0,this.applyGroundDepthWrite(),this.terrainBuildToken++}farRing;farRingRadiusM=0;farRingToken=0;patchesAwaited;patchesAwaitedFor;observerRoute;setObserverRoute(e){this.observerRoute=e,this.decorTerrainRadiusM=he.terrainReachFor(this.decorObjects,e)}decorTerrainRadiusM=0;static terrainReachFor(e,t){return _t.decorReachFor(e,t)}placeTerrain(e,t,i,s){const n=(r,a)=>{const o=ot(a.lat,a.lng,e,t);r.position.x=o.x-i,r.position.z=o.z+s};if(this.terrainMesh&&this.terrainMeshOrigin&&n(this.terrainMesh,this.terrainMeshOrigin),this.fadingTerrain&&n(this.fadingTerrain.mesh,this.fadingTerrain.origin),this.farRing){const r=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=r}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=L2+.1;updateLookPatch(e){if(e.lat===void 0||e.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const t=_t.lookPatchFor(e.elevationM??0,e.pitchDeg,this.terrainRadius);if(!t){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(e.headingDeg??0)*Math.PI/180,s=e.lat+t.distanceM*Math.cos(i)/111320,n=e.lng+t.distanceM*Math.sin(i)/(111320*Math.cos(e.lat*Math.PI/180)),r=this.lookPatchAsked;if(r){const c=ot(s,n,r.lat,r.lng);if(Math.hypot(c.x,c.z)<r.radiusM*he.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:s,lng:n,radiusM:t.radiusM};const a=++this.lookPatchToken,o=this.terrainProviders;c1(s,n,{elevation:o.elevation,imagery:o.imagery},t.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:c})=>{if(a!==this.lookPatchToken||this.terrainProviders!==o||!this.terrainMesh){this.disposeMesh(c);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),c.renderOrder=he.LOOK_PATCH_RENDER_ORDER,c.position.y=this.terrainMesh.position.y;const h=c.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:c,origin:{lat:s,lng:n},radiusM:t.radiusM};const d=ot(s,n,e.lat,e.lng);c.position.x=d.x,c.position.z=d.z,this.scene.add(c),this.compileNextFrameOffThread(),this.render()},c=>console.warn("No sharp ground under what is looked at:",c))}setTerrainOrigin(e,t,i){if(e===void 0||t===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:e,lng:t,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const u=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const p=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===u&&p&&this.setTerrainOrigin(p.lat,p.lng,p.onSettled)}),he.TERRAIN_PATIENCE_MS)}return}const d=s.nearest(e,t);d&&(e=d.lat,t=d.lng,n=d.radiusM)}const r=n??Math.max(_t.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-r)<r*.1){const{x:d,z:u}=ot(e,t,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(d*d+u*u)<k7*(r/Fm))return}const a=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(ot(e,t,o.lat,o.lng).x,ot(e,t,o.lat,o.lng).z)<=a||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:e,lng:t},this.terrainRadius=r;const h=++this.terrainBuildToken;this.awaitArrival(c1(e,t,this.terrainProviders,r,{route:this.observerRoute}),he.TERRAIN_PATIENCE_MS).then(({mesh:d,attribution:u,originElevationM:p,water:f,waterLater:m})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(p??0),this.anchorGrassTo(d,e,t);const v=this.terrainMesh,g=this.terrainMeshOrigin,b=g?ot(e,t,g.lat,g.lng):void 0;v&&b&&Math.hypot(b.x,b.z)<=a&&(d.position.y=v.position.y+this.groundYOfPatch(v,b.x,b.z)),v&&g&&b&&Math.hypot(b.x,b.z)<=a?this.crossfadeTerrain(d,v,g):this.disposeMesh(this.terrainMesh),d.renderOrder=L2,this.terrainMesh=d,this.terrainMeshOrigin={lat:e,lng:t},this.compileNextFrameOffThread(),this.terrainAttribution=u,this.scene.add(d),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(e,t,r),this.buildWater(e,t,r,f,m),this.buildRailways(e,t,r),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(e,t,r,d,p),this.render(),i?.()}).catch(d=>{console.warn("Terrain build failed, keeping the flat ground fallback:",d),i?.()})}buildFarRing(e,t,i,s,n){s.geometry.computeBoundingBox();const r=s.position.y+(s.geometry.boundingBox?.min.y??0),a=this.camera.position.y-r,o=this.skyEventReachM({lat:e,lng:t});if(!_t.needsFarRing(i,a,o)){this.dropFarRing();return}if(this.farRing){const{x:f,z:m}=ot(e,t,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(f,m)<i*he.FAR_RING_KEPT_SHARE)return}const c=this.terrainProviders.patches,h=c?.farRingOf?.(e,t);if(c&&!h){this.dropFarRing();return}const d=h?.radiusM??_t.FAR_RING_RADIUS_M,u=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(c1(e,t,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*he.FAR_RING_OPEN_SHARE,referenceElevationM:n}),he.TERRAIN_PATIENCE_MS).then(({mesh:f})=>{if(u!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(f);return}this.dropFarRing(),this.farRingToken=u,f.renderOrder=he.FAR_RING_RENDER_ORDER,f.position.y=s.position.y-he.FAR_RING_DROP_M;const m=f.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:f,origin:{lat:e,lng:t}},this.farRingRadiusM=d,this.scene.add(f),f.position.x=s.position.x,f.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},f=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",f))}dropLookPatch(){this.lookPatchToken++,this.lookPatchAsked=void 0,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0)}dropFarRing(){this.farRing&&(this.disposeMesh(this.farRing.mesh),this.farRing=void 0)}static FAR_RING_OPEN_SHARE=.75;static FAR_RING_KEPT_SHARE=.3;static FAR_RING_DROP_M=3;static FAR_RING_RENDER_ORDER=.5;grassReference;anchorGrassTo(e,t,i){if(this.grassReference){const r=ot(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 s=ot(this.grassReference.lat,this.grassReference.lng,t,i);e.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(e,t,i){this.stopTerrainFade();const s=e.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),r=()=>{const a=Math.min(1,(performance.now()-n)/he.TERRAIN_CROSSFADE_MS);if(s.opacity=a*a*(3-2*a),this.render(),a<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(r);return}s.polygonOffset=!1,s.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=_t.ROADS_MAX_RADIUS_M;buildRoads(e,t,i){const s=this.terrainProviders.roads;if(!s||i>he.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRoads(n.ways,e,t,s.contemporary);return}n&&Math.hypot(ot(e,t,n.lat,n.lng).x,ot(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,e,t,s.contemporary),this.awaitArrival(s.getRoads(hp(e,t,i)),he.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,s.contemporary))}).catch(r=>{console.warn("Roads unavailable, drawing none:",r)})}buildWater(e,t,i,s,n){const r=this.terrainProviders.water;if(!r||i>he.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,e,t,i),he.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const a=this.waterSurfaces;if(a&&a.lat===e&&a.lng===t&&a.radiusM===i){this.drapeWater(a.surfaces,e,t,i);return}a&&Math.hypot(ot(e,t,a.lat,a.lng).x,ot(e,t,a.lat,a.lng).z)<=a.radiusM&&this.drapeWater(a.surfaces,e,t,i),this.awaitArrival((n??r.getWater(hp(e,t,i))).then(o=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.waterSurfaces={lat:e,lng:t,radiusM:i,surfaces:o},this.drapeWater(o,e,t,i)}),he.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(e,t,i,s){if(e.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s,this.patchSpacingM(r)),kn.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Q(async()=>{const{WaterSystem:e}=await import("./WaterSystem-BBrkl1Y3.js");return{WaterSystem:e}},[],import.meta.url).then(({WaterSystem:e})=>{const t=new e;return this.scene.add(t.group),this.waterSystem=t,t})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(e,t,i){const s=this.terrainProviders.railways;if(!s||i>he.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===e&&n.lng===t&&n.radiusM===i){this.drapeRailways(n.lines,e,t,i);return}n&&Math.hypot(ot(e,t,n.lat,n.lng).x,ot(e,t,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,e,t,i),this.awaitArrival(s.getRailways(hp(e,t,i)).then(r=>{if(!(this.terrainOrigin?.lat!==e||this.terrainOrigin?.lng!==t))return this.railwayLines={lat:e,lng:t,radiusM:i,lines:r},this.drapeRailways(r,e,t,i)}),he.ROADS_PATIENCE_MS).catch(r=>{console.warn("Railways unavailable, drawing none:",r)})}async drapeRailways(e,t,i,s){if(!this.railwaySystem&&!e.some(a=>a.level>=0))return;const n=await this.loadRailwaySystem(),r=this.terrainMesh;r&&(n.group.position.copy(r.position),n.setGroundSpacing(this.patchSpacingM(r)),n.set(e,t,i,(a,o)=>this.groundYOfPatch(r,a,o),s),kn.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Q(async()=>{const{RailwaySystem:e}=await import("./RailwaySystem-CuqGInI5.js");return{RailwaySystem:e}},[],import.meta.url).then(({RailwaySystem:e})=>{const t=new e;return this.scene.add(t.group),this.railwaySystem=t,t})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}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??=Q(async()=>{const{TraceSystem:e}=await import("./TraceSystem-CUMKKQY4.js");return{TraceSystem:e}},[],import.meta.url).then(({TraceSystem:e})=>{const t=new e(k1);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,(s,n)=>this.groundYOfPatch(t,s,n)))}buildingFootprints(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ue.naturalSize(s.kind,s.floors),r=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(r),alongZ:-Math.cos(r),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(e,t){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?ot(i.lat,i.lng,e,t):{x:0,z:0}}surveyedLamps(e,t){const i=this.decorOriginInRoads(e,t);return this.decorObjects.filter(s=>s.kind==="streetlight"&&!s.lamp?.supposed&&!s.track).map(s=>({x:i.x+s.eastM,z:i.z-s.northM}))}lampNudges=new Map;lampsToKerb(e,t){this.lampNudges.clear();const i=this.decorOriginInRoads(e,t);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,r=i.z-s.northM,a=this.roadSystem.atKerb(n,r);(a.x!==n||a.z!==r)&&this.lampNudges.set(s.id,{eastM:a.x-n,northM:-(a.z-r)})}}static onlyMoved(e,t){return e.length!==t.length||e.length===0?!1:e.every((i,s)=>{const n=t[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const r=new Set([...Object.keys(i),...Object.keys(n)]);for(const a of r)if(!(a==="eastM"||a==="northM"||a==="track")&&i[a]!==n[a])return!1;return!0})}layStreetsIfWallsMoved(e){const t=this.roadWays,i=this.terrainProviders.roads;if(!t||!i)return;const s=this.wallsOf(e,t.lat,t.lng),n=this.roadWalls;n?.lat===t.lat&&n.lng===t.lng&&n.walls.length===s.length&&n.walls.every((a,o)=>a.what===s[o].what&&Math.hypot(a.x-s[o].x,a.z-s[o].z)<.1)||this.drapeRoads(t.ways,t.lat,t.lng,i.contemporary)}wallsOf(e,t,i){const s=this.decorOriginInRoads(t,i);return e.filter(n=>n.kind==="building"||n.kind==="streetlight").map(n=>({what:`${n.kind}:${n.lamp?.supposed?"s":""}${n.headingDeg??0}:${n.sizeM?.widthM??""}:${n.sizeM?.lengthM??""}`,x:s.x+n.eastM,z:s.z-n.northM}))}roadWalls;drapeRoads(e,t,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(e,t,i,(r,a)=>this.groundYOfPatch(n,r,a),s,this.terrainRadius,new Fi(this.buildingFootprints(t,i),this.surveyedLamps(t,i))),this.roadWalls={lat:t,lng:i,walls:this.wallsOf(this.decorObjects,t,i)},this.lampsToKerb(t,i),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;applyDazzleStrength(){if(!this.lensFlare)return;const[e,t,i]=this.sunArriving,s=Math.max(t,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(e/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?Vs.LENS_K:Vs.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.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(e){if(l7(this.weather,e))return;this.cloudTransmissionMemo.clear();const t=this.weather;this.weather=e;const i=!z7(t,e),s=t.precipitationType!==e.precipitationType,n=t.precipitationIntensity!==e.precipitationIntensity||t.precipitationAmount!==e.precipitationAmount;(t.relativeHumidity!==e.relativeHumidity||s||n)&&(this.air=Xr.of(e),this.applyAir(),this.scatteredSky?.setConditions({aerosolOpticalDepth:e.relativeHumidity===void 0?void 0:Vo.steppedOpticalDepth(e.relativeHumidity)}),this.pumpScatteredSky()),i&&(this.buildClouds(),this.buildCirrus()),s?this.buildPrecipitation():n&&this.updatePrecipitationDensity(),this.lastAstronomy&&(i&&(this.buildIceHalos(this.lastAstronomy.sun,this.lastAstronomy.moon),this.buildLunarDiffraction(this.lastAstronomy.moon)),(i||s||n)&&this.buildRainbow(this.lastAstronomy.sun,this.lastAstronomy.moon)),this.lightningArmed=e.storm&&e.cloudDarkness>=K7,this.syncAnimationLoop(),this.render()}setDecor(e){if(this.decorObjects===e)return;if(he.onlyMoved(this.decorObjects,e)){this.decorObjects=e,this.decorTerrainRadiusM=he.terrainReachFor(e,this.observerRoute),this.layStreetsIfWallsMoved(e);return}this.decorObjects=e,this.decorTerrainRadiusM=he.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.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const t=e.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,b7);for(const i of e){const s=ue.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&t.includes(i)&&this.addStreetlightLight(i.id,s,t.indexOf(i)<y7,i.lamp),i.model&&i.id.startsWith(Yi.ID_PREFIX)?(this.pendingTrafficModels.set(i.id,i),this.awaitArrival(this.loadDecorModel(i,this.decorModelToken,!0))):this.reuseLoadedDecorModel(i,s)||this.awaitArrival(this.loadDecorModel(i,this.decorModelToken))}this.decorLamps=he.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(e),e.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(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??=Q(async()=>{const{ContrailSystem:e}=await import("./ContrailSystem-DYAYamnm.js");return{ContrailSystem:e}},__vite__mapDeps([15,16]),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,s=he.CONTRAIL_SCATTERING,n=this.skyLight.color,r=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(t&&i){const a=qn.litFraction(t.sunElevationDeg,t.heightM);if(a>0){const o=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),c=$t.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)r[h]+=s*c*o[h]*a}}return r}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(e,t=!1,i){if(this.skyEventsStart=i,e===this.skyEventsStated&&!t)return;this.skyEventsStated=e;let s=!1;const n=new Set;for(const r of Qp){const a=Or.of(r);n.add(a.key);const o=Or.eventsOf(e,a);let c=this.skyEventLayers.get(a.key);if(c?.kind!==a&&c&&(this.disposeSkyEventLayer(a.key,c),c=void 0),!(!c&&o.length===0)){if(!c)c={kind:a,events:o},this.skyEventLayers.set(a.key,c);else if(c.events===o)continue;c.events=o,s||=a.reachM!==void 0,this.loadSkyEventSimulation(c)}}for(const[r,a]of this.skyEventLayers)n.has(r)||(this.disposeSkyEventLayer(r,a),s||=a.kind.reachM!==void 0);s&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(e){if(e.simulation){this.updateSkyEvents(),this.render();return}e.loading??=e.kind.simulation().then(t=>{if(this.skyEventLayers.get(e.kind.key)!==e)return;const i=t();(i.inSky?this.celestialGroup:this.scene).add(i.object),e.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(e.loading)}disposeSkyEventLayer(e,t){t.simulation?.dispose(),this.skyEventLayers.delete(e),this.skyEventLight(e,[]),this.skyEventGlare(e,[])}skyEventLight(e,t){this.emitterLights.set(`skyEvent:${e}`,[],t.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(e,t){const i=`skyEvent:${e}:`,s=new Set;for(const n of t){const r=i+n.key,{x:a,y:o,z:c}=Li(n.position.altitudeDeg,n.position.azimuthDeg,Gn),[h,d,u]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(r,a,o,c,[h*n.fade,d*n.fade,u*n.fade],0,he.POINT_VEIL_HOLD_DEG),s.add(r)}for(const n of[...this.glareSprites.keys()])n.startsWith(i)&&!s.has(n)&&this.disposeGlare(n)}skyEventReachM(e){let t=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(t=Math.max(t,i.kind.reachM(i.events,e)));return t}skyEventDrawnCount(e){return this.skyEventLayers.get(e)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const e=this.decorReferencePose;if(this.skyEventLayers.size===0||e?.lat===void 0||e.lng===void 0)return;const t=this.decorCurrentPose,i={lat:t?.lat??e.lat,lng:t?.lng??e.lng,heightM:this.siteElevationM+(t?.lat!==void 0?t.elevationM??0:e.elevationM??0)},s=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$a(-90,this.instrumentMagnitudeGain);let r;for(const[a,o]of this.skyEventLayers)o.simulation&&(r??={observer:i,date:s,magnitudeLimit:n,cloudTransmission:c=>this.cloudTransmission(c),arrivingIlluminance:(c,h,d)=>this.arrivingIlluminance(c,h,d),transmittanceFromSpace:c=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,c.altitudeDeg),reference:{lat:e.lat,lng:e.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(c,h,d)=>this.transmittanceTo(c,h,d),groundYAt:(c,h)=>this.groundYUnder(c,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*ci)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*ci)*this.weather.windSpeed}},o.simulation.update(o.events,this.decorTime,{...r,lightFrom:c=>this.skyEventLight(a,c),glareFrom:c=>this.skyEventGlare(a,c)}));this.render()}updateContrails(){const e=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:e?Li(e.altitudeDeg,e.azimuthDeg,1):void 0},t=>this.contrailTint(t))}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(()=>{})}holdUntil(e){this.awaitArrival(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),s=this.bodyEastScale;return{heightAt:(n,r)=>this.groundYUnder(e+n*s,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*ci)/Math.cos(e.lat*ci)}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),s=[],n){const{x:r,z:a}=this.bodyOrigin,o=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:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(d,u,p)=>this.transmittanceTo(d,u,p),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y)},t,o?Object.assign((d,u)=>o.relativeOfLuminance(d,u),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,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,s=this.skyLight.groundColor,n=this.skyLight.intensity,r=(a,o,c)=>(a*t+(o+c)/2*n)/Math.PI;return[r(e.r,i.r,s.r),r(e.g,i.g,s.g),r(e.b,i.b,s.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,s=e.credit??t?.credit;if(!(!i||!s))return{scene:await v1(i),credit:s,headingOffsetDeg:e.headingOffsetDeg??t?.headingOffsetDeg,bindings:t?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(e,t){const i=this.loadedDecorModels.get(e.id);return!i||i.ref!==JSON.stringify(ef(e))||!ue.usesModel(e)?!1:(this.applyLoadedDecorModel(e,t,i),!0)}applyLoadedDecorModel(e,t,i){const s=hI(i.scene);s.traverse(n=>{n instanceof Me&&(n.userData.sharedModel=!0)}),ue.applyModelParameters(s,e.modelParameters,i.bindings),ue.applyModel(t,e,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(e.id,i.credit)}mirrors=new fr;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(e,t,i=!1){const s=i?R0[e.kind]:ef(e);if(!(!s||!ue.usesModel(e)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,r=this.modelUrl(s)??n?.url,a=s.credit??n?.credit;if(!r||!a)return;const o=i||e.kind==="tree"?await this.standInScene(r):await v1(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"&&(ut.glaze(o),kn.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:a,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(e.id,h),this.applyLoadedDecorModel(e,c,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${e.id}":`,n)}}standInScene(e){let t=this.standInScenes.get(e);return t||(t=v1(e).then(i=>(/jungle-jim-realistic-trees/.test(e)||kn.reflectOn(i),i)),this.standInScenes.set(e,t)),t}updateDecorAnchoring(e,t,i=0){this.decorReferencePose=e,this.decorCurrentPose=t,this.decorTime=i;const s=e?.lat!==void 0&&e.lng!==void 0&&t?.lat!==void 0&&t?.lng!==void 0?ot(e.lat,e.lng,t.lat,t.lng):{x:0,z:0},n=this.decorObjects.find(f=>f.observerSide!==void 0&&ic(f.kind));this.terrainMesh&&t?.lat!==void 0&&t.lng!==void 0&&(this.placeTerrain(t.lat,t.lng,n?0:this.gaitOffset.eastM,n?0:this.gaitOffset.northM),this.roadSystem.group.position.copy(this.terrainMesh.position),this.waterSystem?.group.position.copy(this.terrainMesh.position),this.railwaySystem?.group.position.copy(this.terrainMesh.position),this.traceSystem?.group.position.copy(this.terrainMesh.position)),n||(s.x-=this.gaitOffset.eastM,s.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,o;if(n){const f=Pr(n,i),m=ue.occupantView(n,f.headingDeg),v=-(f.headingDeg??0)*ci,g=m.x*Math.cos(v)+m.z*Math.sin(v),b=-m.x*Math.sin(v)+m.z*Math.cos(v),w=f.eastM+s.x,y=-f.northM+s.z;r.x=-(w+g),r.z=-(y+b),this.camera.position.y=this.groundYUnder(w,y)+m.eyeY,o=m.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*ci,-(m.headingDeg+this.indoorLookYawDeg)*ci,0,"YXZ")}this.bodyOrigin={x:s.x+r.x,z:s.z+r.z};const c=this.findCabin(i,s,r);this.fitShadowToCabin(c.length>0),this.dimCabinSky(c),this.placeShadowFrustum(),this.placeTerraces(i,s,r);const h=this.terraces.map(f=>[f.x,f.z,f.cos,f.sin,f.halfWidthM,f.halfLengthM,f.levelY].map(m=>m.toFixed(3)).join(",")).join(";");!n&&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 f of this.decorObjects){if(f.kind==="terrace")continue;const m=this.decorGroups.get(f.id);if(!m)continue;const v=Pr(f,i),g=this.lampNudges.get(f.id),b=v.eastM+(g?.eastM??0)+s.x+r.x,w=-(v.northM+(g?.northM??0))+s.z+r.z,y=this.terrainMesh,M=`${y?.geometry.uuid}:${(b-(y?.position.x??0)).toFixed(3)}:${(w-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${v.headingDeg}:${v.altitudeM}:${h}`;if(m.userData.footprintKey!==M){if(f.kind==="wire"){const L=ue.wireGround(f,b,w,v.headingDeg,(P,C)=>this.groundYUnder(P,C));m.userData.footprintGroundY=L.startY,ue.shearWire(m,ue.sizeOf(f).lengthM,L.dropM)}else if(f.kind==="crossing"){const L=this.groundYUnder(b,w),P=-(v.headingDeg??0)*ci,C=Math.cos(P),N=Math.sin(P);m.userData.footprintGroundY=L,Rt.drape(ue.bodyOf(m),(F,H)=>this.groundYUnder(b+F*C+H*N,w-F*N+H*C)-L)}else m.userData.footprintGroundY=this.groundUnderFootprint(f,b,w,v.headingDeg,v.altitudeM);m.userData.footprintKey=M}const E=v.altitudeM>he.AIRBORNE_M&&Math.hypot(b,w)<he.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseElevationM:m.userData.footprintGroundY,S=f.id.startsWith(Yi.ID_PREFIX)?he.trafficHeight(v.altitudeM,m.userData.footprintGroundY):E+v.altitudeM;if(m.position.set(b,S,w),f.kind==="crop"){const L=Math.hypot(b,w);m.visible=L<=C7}const A=this.decorPresence.get(f.id),T=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(m.visible=!T);const _=this.decorSunlight.get(f.id);_&&!T&&this.lightFromAbove(m,_),v.headingDeg!==void 0&&(m.rotation.y=-v.headingDeg*ci);const k=hk(f,i);if(k!==void 0&&he.turnHead(m,v.headingDeg??0,k),f.kind==="crop"&&m.visible){const L=this.terrainMesh,P=[L?.geometry.uuid,b-(L?.position.x??0),w-(L?.position.z??0),m.position.y-(L?.position.y??0),v.headingDeg,v.altitudeM].map(C=>typeof C=="number"?C.toFixed(4):C).join(":");m.userData.cropGroundKey!==P&&(ue.fitCropToGround(m,(C,N)=>this.groundYUnder(C,N)+v.altitudeM),m.userData.cropGroundKey=P)}if(!T){const L=m.position.distanceTo(this.camera.position);a=Math.max(a,L),L<he.trafficModelRangeM(f)&&this.pendingTrafficModels.delete(f.id)&&this.loadDecorModel(f,this.decorModelToken)}}if(n&&o!==void 0){const f=this.decorGroups.get(n.id);f&&(this.camera.position.y=f.position.y+o)}this.updateContrails(),this.updateSkyEvents();const d=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,u=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,p=Math.max(Pm*1.2,this.groundRadius*2.5,a*1.2,d*1.05,u*1.2);Math.abs(this.camera.far-p)>1&&(this.camera.far=p,this.camera.updateProjectionMatrix())}groundYUnder(e,t){const i=this.terrainYUnder(e,t);let s=i;for(const n of this.terraces){const r=e-n.x,a=t-n.z,o=r*n.cos-a*n.sin,c=r*n.sin+a*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(c)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),d=h*h*(3-2*h);s=Math.max(s,d*n.levelY+(1-d)*Math.min(n.levelY,i))}}return s}placeTerraces(e,t,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Pr(n,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=-(a.headingDeg??0)*ci,u=Math.cos(d),p=Math.sin(d),f=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(c-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${a.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;r.position.set(o,0,c),a.headingDeg!==void 0&&(r.rotation.y=d),r.userData.terraceKey!==f&&(r.userData.terraceLevelY=ue.fitTerrace(r,n,(m,v)=>this.terrainYUnder(o+m*u+v*p,c-m*p+v*u)),r.userData.terraceKey=f),this.terraces.push({x:o,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):H1}horizonAltitudeDeg(e){const t=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(t.x)}|${Math.round(t.y*10)}|${Math.round(t.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((e%360+360)%360/(360/s))%s;let r=this.horizonByBearing[n];return Number.isNaN(r)&&(r=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),r}groundHidesDirection(e,t){return e<Math.max(0,this.horizonAltitudeDeg(t))+he.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;static SIGHT_EARTH_RADIUS_M=6371e3*7/6;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(e){const t=this.terrainMesh;if(!t)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=e*Math.PI/180,n=Math.sin(s),r=-Math.cos(s),a=this.farRing?.mesh,o=Math.max(this.terrainRadius,a?this.farRingRadiusM:0),c=Math.min(Math.max(this.patchSpacingM(t),1),50);let h=Number.NEGATIVE_INFINITY;for(let d=c;d<=o;d=Math.max(d+c,d*1.02)){const u=i.x+n*d,p=i.z+r*d,f=d<=this.terrainRadius?this.terrainYUnder(u,p):a.position.y+this.groundYOfPatch(a,u-a.position.x,p-a.position.z),m=d*d/(2*he.SIGHT_EARTH_RADIUS_M);h=Math.max(h,Math.atan2(f-m-i.y,d))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}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 s=e.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return H1;const r=s.getX(0),a=s.getX(n-1),o=s.getZ(0),c=s.getZ((n-1)*n),h=Fa((t-r)/(a-r)*(n-1),0,n-1),d=Fa((i-o)/(c-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(d))return H1;const u=Math.min(Math.floor(h),n-2),p=Math.min(Math.floor(d),n-2),f=h-u,m=d-p,v=(M,x)=>s.getY(M*n+x),g=v(p,u),b=v(p,u+1),w=v(p+1,u),y=v(p+1,u+1);return f+m<=1?g+(b-g)*f+(w-g)*m:y+(w-y)*(1-f)+(b-y)*(1-m)}groundUnderFootprint(e,t,i,s,n=0){return ue.groundUnderFootprint(e,t,i,s,(r,a)=>this.groundYUnder(r,a),n)}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=Mr.NONE;setPerception(e){JSON.stringify(e)!==JSON.stringify(this.perception)&&(this.perception=e,this.render())}medium;setMedium(e,t,i,s,n){const r=e&&t!==void 0&&t>0&&i!==void 0&&i>0?{kind:e.kind,iso:s??e.iso,autoExposure:e.autoExposure===!0&&s===void 0,maxIso:e.maxIso,metering:n??e.metering??"average",exposureSeconds:t,fNumber:i,development:e.development,exposureFollowMs:e.exposureFollowMs,print:e.print,monochrome:e.monochrome}:void 0;JSON.stringify(r)!==JSON.stringify(this.medium)&&(this.medium=r,this.render())}applyMedium(){const e=this.medium,t=Math.max(this.relativeScale,1e-30),i=e?Mr.NONE:this.perception??Mr.NONE;if(qi.uColorVision.value.set(...i.colorMatrix),qi.uContrast.value=i.contrastGain,!e){qi.uMedium.value=0;return}const s=e.kind==="sensor"&&e.development==="computational";qi.uMedium.value=e.kind==="negative"?1:e.kind==="slide"?2:s?4:3;const n=e.autoExposure?this.frameLight:void 0,r=e.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,a=r===void 0?void 0:this.meteredBodies(),o=r===void 0?void 0:r+a.mean,c=u=>.065*e.exposureSeconds*u*this.filterTransmittance/(e.fNumber*e.fNumber*t);let h=o!==void 0&&o>0?1/(t*o):void 0;h!==void 0&&e.metering==="highlights"&&a.brightest>0&&(h=Math.min(h,he.HIGHLIGHT_KEPT_AT/(.18*t*a.brightest))),h!==void 0&&e.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,he.ZONE_KEPT_AT/(.18*t*n.brightest)));const d=h!==void 0?Math.min(h,e.maxIso!==void 0?c(e.maxIso):1/0):c(e.iso);qi.uMediumExposure.value=d,qi.uPhoneStrength.value=s&&o!==void 0&&o>0?ha.strengthFor(ha.MID_GREY*d*t*o):0}static HIGHLIGHT_KEPT_AT=.3;static ZONE_KEPT_AT=1.6;static HIGHLIGHT_SHARE=2e-4;meteredBodies(){if(this.bodySystem.metered.size===0)return{mean:0,brightest:0};const e=this.camera;e.updateMatrixWorld();const t=e.fov*Math.PI/180,i=2*Math.atan(Math.tan(t/2)*e.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(t/2)),n=new D;let r=0,a=0;for(const{position:o,luminanceCdM2:c,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(e),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(r+=c*h,a=Math.max(a,c*Math.min(1,h/(he.HIGHLIGHT_SHARE*s))**2));return{mean:r/s,brightest:a}}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 ie;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))}decorLitAt;updateDecorLitState(e,t=0){this.decorLitAt={t:e,stepMs:t};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ue.setLights(n,s.lights,e,n.position.distanceTo(this.camera.position),t,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const r=this.decorGroups.get(s.id);if(!r)continue;const a=s.kind==="vehicle"?TT(s,e):void 0,o=a!==void 0?tc.lamps(a):Ng(s,e,this.lastAstronomy?.sun.altitudeDeg);ue.setLit(r,s.kind,o,this.relativeScale,s.lamp);const c=this.streetlightLights.get(s.id);c&&(c.visible=o),a!==void 0&&(this.headlightSettings.set(s.id,a),this.aimDecorBeam(s,r,a))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=Q(async()=>{const{HeadlightSystem:e}=await import("./HeadlightSystem-FfcayJJX.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 s=new D(0,0,-1).transformDirection(t.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ue.sizeOf(e).lengthM,r=t.getWorldPosition(new D).addScaledVector(s,n/2-M7);r.y+=w7;const a=ue.sizeOf(e).widthM;this.headlightSystem.aim(e.id,i,r,s,a*x7,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?tc.auto(this.lastAstronomy.sun.altitudeDeg):"off":e.setting,i=e.headingDeg*Math.PI/180,s=new D(Math.sin(i),0,-Math.cos(i)),n=new D(s.x*D2,this.camera.position.y-E7,s.z*D2);this.headlightSystem.aim("observer",t,n,s,S7,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(e,t,i,s){const n=ue.bodyOf(t),r=n.children.find(c=>c.userData.emissive);if(!r)return;const a=_2*ue.lampShare(s),o=new N3(16764006,a*this.relativeScale,A7);s?.colorTemperatureK&&o.color.setRGB(...ue.lampHue(s)),o.userData.candela=a,o.position.copy(r.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,t.add(o),this.streetlightLights.set(e,o)}applyWindowGlow(){const e=this.lastAstronomy;ue.setLitWindowShare(e?un.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=gr.luminanceOf(r);if(!(a>0))return[0,0,0];const o=Ve.relativeOfResponse(a)/a;return[r[0]*o,r[1]*o,r[2]*o]},s=i(e.zenith),n=i(e.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:t}}placeBodies(e,t){this.bodiesScale=this.relativeScale,this.sunBeamFraction=bs.beamFraction(e.eclipse),this.setBodyMesh("sun",e.sun,T2,new oe(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<v0){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=T2/Gn*(180/Math.PI),s=i/t.sunRadiusDeg,n=Li(e.sun.altitudeDeg,e.sun.azimuthDeg,1),r=Li(e.moon.altitudeDeg,e.moon.azimuthDeg,1),a=Math.acos(Fa(n.x*r.x+n.y*r.y+n.z*r.z,-1,1)),o=a>1e-9?Fa(t.separationDeg*s*ci/a,0,2):0,c=Math.sin(a),[h,d]=a>1e-9?[Math.sin((1-o)*a)/c,Math.sin(o*a)/c]:[1,0],u={x:n.x*h+r.x*d,y:n.y*h+r.y*d,z:n.z*h+r.z*d},p=t.moonRadiusDeg*s;this.eclipseDiscs={sun:new D(n.x,n.y,n.z).normalize(),moon:new D(u.x,u.y,u.z).normalize(),sunRadiusRad:i*ci,moonRadiusRad:p*ci};const f=.01,m=(b,w)=>Li(e.sun.altitudeDeg+b,e.sun.azimuthDeg+w,1),v={x:m(f,0).x-m(-f,0).x,y:m(f,0).y-m(-f,0).y,z:m(f,0).z-m(-f,0).z},g={x:m(0,f).x-m(0,-f).x,y:m(0,f).y-m(0,-f).y,z:m(0,f).z-m(0,-f).z};if(this.eclipsedSun.setMoon(u,p,t.limb?{profile:t.limb,scale:s,up:v,right:g}:void 0),t.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new gd(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,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),this.updateSkyEvents());const t=this.scatteredSky?.ambient??he.relativeSkyOf(Dy(e.sun.altitudeDeg),this.relativeScale),i=t,s=this.lightUnderClouds(e),n=r=>s?[0,1,2].map(a=>r[a]*s.through+s.radiance[a]*(1-s.through)):[r[0],r[1],r[2]];this.baseFogColor=[i.horizon[0],i.horizon[1],i.horizon[2]],this.airlight=n(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=(r.userData.candela??_2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),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,s=(i===void 0?et.DEFAULT_AEROSOL_OPTICAL_DEPTH:Vo.opticalDepth(i))*et.aerosolDensity(this.siteElevationM+this.observerElevationM),n=this.cloudTransmission(e),r=-Math.log(Math.max(this.cloudTransmission(e,!0),1e-4)),a=$t.aureoleScale(s,$t.airMass(e.altitudeDeg))*n,o=$t.coronaScale(r),c=$t.illuminanceOf(e.magnitude),h=[e.altitudeDeg.toFixed(1),e.azimuthDeg.toFixed(1),e.magnitude.toFixed(2),a.toExponential(2),o.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 jw,this.celestialGroup.add(this.lunarDiffraction.object));const d=$t.profile($t.HAZE_COARSE_MODE),u=$t.profile($t.CLOUD_DROPLETS),p=o8(e.altitudeDeg),f=new Float32Array($t.STEPS*3);let m=0;for(let w=0;w<$t.STEPS;w++){const y=w*3,M=[0,1,2].map(E=>c*p[E]*(a*d[y+E]+o*u[y+E])),x=gr.shown(M,gr.luminanceOf(M),(E,S)=>t.relativeOfLuminance(E,S));f.set(x,y),m=Math.max(m,gr.response(x))}const{x:v,y:g,z:b}=Li(e.altitudeDeg,e.azimuthDeg,1);this.lunarDiffraction.show(m>1/200?{x:v,y:g,z:b}:void 0,f)}applyAir(){this.scene.fog instanceof Yc||(this.scene.fog=new Yc),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(e,t,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+t,Math.hypot(e-s.x,t-s.y,i-s.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(e,t){return Math.max(e,t)}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,s]=this.air.transmittance(e,e,he.UMBRA_PATH_M),n=.2126*t+.7152*i+.0722*s;return n>0?[(.4124*t+.3576*i+.1805*s)/n,1,(.0193*t+.1192*i+.9505*s)/n]:[.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:bs.beamFraction(e.eclipse),zenithFloorCdM2:e.eclipse?bs.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(e),moon:{altitudeDeg:e.moon.altitudeDeg,azimuthDeg:e.moon.azimuthDeg,magnitude:e.moon.magnitude,phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction)},flare:this.skyFlare}}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?_7:I7),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 D8(C1),this.celestialGroup.add(this.satelliteField.object));const t=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):$a(-90,this.instrumentMagnitudeGain);this.satelliteField.set(e,t,i=>this.cloudTransmission(i),(i,s)=>this.arrivingIlluminance(i,s,1)),this.render()}get plumePuffCount(){return this.skyEventDrawnCount("launches")}get reentryCount(){return this.skyEventDrawnCount("reentries")}flightScreenPoint(e){const t=`${Yi.ID_PREFIX}${e}-`;for(const[i,s]of this.decorGroups){if(!s.visible||!i.startsWith(t))continue;const n=this.screenPointOf(new D().copy(s.position).sub(this.camera.position).normalize());if(n&&Math.abs(n.ndcX)<=1&&Math.abs(n.ndcY)<=1&&!this.groundHides(n.ndcX,n.ndcY))return n}}pickTrafficAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.direction,s=Math.cos(Um*this.camera.fov*Math.PI/180);let n,r=s;const a=new D;for(const[o,c]of this.decorGroups){if(!c.visible||!o.startsWith(Yi.ID_PREFIX))continue;a.copy(c.position).sub(this.camera.position).normalize();const h=a.dot(i);h>r&&(r=h,n=o)}return n&&!this.groundHides(e,t)?n:void 0}pickSatelliteAt(e,t){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,e,t);const i=Math.cos(Um*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(e,t)?void 0:s}updateCelestialLight(e,t){const i=this.relativeScale,s=e.sun.altitudeDeg>=Hu,n=!s&&e.moon.altitudeDeg>=Hu,r=s?e.sun:e.moon,a=[0,0,0],o=Math.max(0,Math.sin(Math.max(r.altitudeDeg,0)*ci)),c=this.siteElevationM+this.observerElevationM;let h=r,d=s||n?r2.directFraction(r.altitudeDeg,c):0;s&&d<=0&&e.moon.altitudeDeg>=Hu&&(h=e.moon,d=r2.directFraction(h.altitudeDeg,c));const u=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*ci)),p=s||n?this.cloudTransmission(r):1,f=-Math.log(Math.max(p,1e-6)),m=Math.max(0,1/(1+.1125*f)-p),v=[0,0,0];if(s||n){const x=$t.illuminanceOf(r.magnitude)*i,E=this.air.transmittanceFromSpace(c,r.altitudeDeg);for(let _=0;_<3;_++)v[_]=x*E[_]*m*o,this.cloudBeam[_]=x*E[_];const{x:S,y:A,z:T}=Li(r.altitudeDeg,r.azimuthDeg,1);if(this.cloudBeamDirection.set(S,A,T),d>0){const _=$t.illuminanceOf(h.magnitude)*i,k=h===r?E:this.air.transmittanceFromSpace(c,h.altitudeDeg),L=h===r?p:this.cloudTransmission(h);for(let P=0;P<3;P++)a[P]=_*k[P]*L*d}}else this.cloudBeam.fill(0);const g=this.surroundings;if(g)this.skyLight.color.setRGB(g.up[0]*i,g.up[1]*i,g.up[2]*i),this.skyLight.groundColor.setRGB(g.down[0]*i,g.down[1]*i,g.down[2]*i);else{const x=this.skyCloudTransmission(),E=t.skyIrradiance,S=[0,1,2].map(T=>E[T]*x+v[T]);this.skyLight.color.setRGB(S[0],S[1],S[2]);const A=at.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(S[0]+a[0]*u),A*(S[1]+a[1]*u),A*(S[2]+a[2]*u))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===e.sun?[a[0],a[1],a[2]]:[0,0,0],!s&&!n||d<=0){this.celestialLight.intensity=0;return}const{x:b,y:w,z:y}=Li(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(b,w,y),this.celestialLight.shadow.normalBias=O1*Fa(w/u7,.1,1),this.placeShadowFrustum();const M=Math.max(a[0],a[1],a[2],1e-30);this.celestialLight.color.setRGB(a[0]/M,a[1]/M,a[2]/M),this.celestialLight.intensity=M,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,s=[0,0,0];if(i){const n=qn.litFraction(t.sunElevationDeg,t.heightM);if(n>0){const r=this.air.transmittanceFromSpace(t.heightM,t.sunElevationDeg),a=$t.illuminanceOf(i.magnitude)*this.relativeScale,o=t.heightM>=he.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let c=0;c<3;c++)s[c]=Math.max(0,a*r[c]*n*o-this.sceneSunBeam[c])}}e.traverse(n=>{const r=n.material;if(!(r instanceof ta||r instanceof Cl)||n.userData.emissive)return;r.map&&!r.emissiveMap&&(r.emissiveMap=r.map,r.needsUpdate=!0);const a=he.MEAN_COSINE/Math.PI;r.emissive.setRGB(r.color.r*s[0]*a,r.color.g*s[1]*a,r.color.b*s[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,s=this.shadowAxisX.crossVectors(this.shadowUp,e);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(e,s).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},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,a(s)).addScaledVector(n,a(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).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,s=d7;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=Bm+5,i.near=this.shadowLightDistanceM-Bm,i.far=this.shadowLightDistanceM+Bm,i.updateProjectionMatrix(),t.bias=-.004/(2*Bm),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 s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const r=n;r.isMeshStandardMaterial&&r.envMapIntensity!==he.CABIN_SKY_SHARE&&(r.envMapIntensity=he.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const e=this.bodySystem.reachFrom(this.camera.position),t=Math.min(h7,Math.max(xo,Math.ceil(e*1.25/20)*20));if(t===this.shadowHalfExtentM)return;this.shadowHalfExtentM=t;const i=this.celestialLight.shadow,s=i.camera;s.left=-t,s.right=t,s.top=t,s.bottom=-t;const n=Math.max(Xh,t*(Xh/xo));this.shadowLightDistanceM=Math.max(Gn,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-L1/(2*n);const r=t>2*xo?2048:1024;i.mapSize.x!==r&&(i.mapSize.set(r,r),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=xo;shadowLightDistanceM=Gn;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 s=i*ci,n=Math.sin(s)*Math.cos(s)*2;for(let r=0;r<360;r+=60)e+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:r}),t+=n}return e/t}cloudBeam=[0,0,0];cloudBeamDirection=new D(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/Ve.semiSaturation(Ve.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(e,t,i){this.meteorSystem||(this.meteorSystem=new Qs,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&&(this.meteorSystem.update(e),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(t=>this.farEmitterOf(t,t.magnitude)).filter(t=>t!==void 0)),this.refreshSkyFlare())}farEmitterOf(e,t){if(!(e.altitudeDeg>0)||!Number.isFinite(t))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(e,t,this.cloudTransmission(e)),{x:n,y:r,z:a}=Li(e.altitudeDeg,e.azimuthDeg,1);return{direction:new D(n,r,a),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:e.altitudeDeg,azimuthDeg:e.azimuthDeg,magnitude:t}}}skyFlare;refreshSkyFlare(){const e=this.emitterLights.brightestInSky;e===this.skyFlare||!e&&!this.skyFlare||(this.skyFlare=e,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(e,t){this.projectionKind=e.projection,this.grain=e.detailUm!==void 0&&e.frame?{detailUm:e.detailUm,frameHeightMm:e.frame.heightMm}:void 0;const i=Qt.starPointsOf(e,t);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(e){const t=pe.starLossMagnitudes(e.sun.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(e.moon.phase.illuminatedFraction),altitudeDeg:e.moon.altitudeDeg},this.lightPollution);return $a(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 s=Number.isFinite(e)?e:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(t,s,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{const e=this.usableGhostPass();e?(this.exposureSubjectBounds=[],this.renderOnce(e.frame),e.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e.develop(this.renderer,e.frame,this.ghostOptics,1,this.sunBeyondPicture(),!this.poseFollows),this.onMapSubjectBounds?.(this.exposureSubjectBounds)):this.renderOnce(),this.drawn++}finally{this.resolution.endDrawing()}this.poseFollows&&this.startExposure()}}}get poseFollows(){return this.developingExposure&&!this.framesDriven}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()+he.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const r of e){const a=t.get(r)?.currentProgram;(!a||a.isReady())&&e.delete(r)}e.size===0||performance.now()>i?s():setTimeout(n,10)};n()})}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 s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&ic(n.kind))continue;const r=this.decorGroups.get(n.id);if(!r)continue;const a=Pr(n,e),o=a.eastM+t.x+i.x,c=-a.northM+t.z+i.z,h=ue.sizeOf(n),d=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,c)<d&&Math.abs(a.altitudeM-this.poseElevationM-1.6)<d&&s.push(r)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(e=!1){this.reflections??=new kn(this.renderer);const t=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...[...this.glareSprites.values()].map(o=>o.mesh)],i=[...this.starTiers.map(o=>o.points),...[...this.bodyMeshes.values()].filter(o=>o instanceof Rr),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(o=>o!==void 0),...this.cabinDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(o=>o.name.startsWith("body:")),...[this.meteorSystem?.object].filter(o=>o!==void 0),...[...this.skyEventLayers.values()].filter(o=>o.simulation?.hiddenFromEye).map(o=>o.simulation.object)],s=this.relativeScale,n=this.sceneVersion,r=this.recordingTimeMs,a=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,t,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],n,i,o=>this.measureSurroundings(o,s,n,r),e?0:kn.REFRESH_MS);a===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()}))},a))}static adaptingLuminance(e,t){const i=(.2126*t[0]+.7152*t[1]+.0722*t[2])/Math.PI;return Math.max(e,he.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(e,t,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new pd,this.framePhotograph={texture:e,scale:t,atMs:s};const r=[n.sun,n.moon].filter(a=>a.altitudeDeg>-2).map(a=>Li(a.altitudeDeg,a.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,e,r,a=>{const o=f=>f.map(m=>m/t),c=this.surroundings,h={up:o(a.up),down:o(a.down)},d=(f,m)=>f.some((v,g)=>Math.abs(v-m[g])>.03*Math.max(Math.abs(v),Math.abs(m[g]),1e-12)),u=!c||d(c.up,h.up)||d(c.down,h.down);u&&(this.surroundings=h),this.eyeSettledVersion=-1;const p=this.scatteredSky?.adaptToSurroundings(he.adaptingLuminance(Math.exp(a.logAverage)/t,h.down))??!1;if(!u&&!p){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>=Hu?e.sun:e.moon.altitudeDeg>=Hu?e.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[t.up[0]*s,t.up[1]*s,t.up[2]*s]}}probeIrradiance;meterFrame(){const e=this.framePhotograph;if(!this.medium?.autoExposure||!e)return;this.frameMeter??=new la;const t=this.lastAstronomy?.sun,i=t&&t.altitudeDeg>-2?Li(t.altitudeDeg,t.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??he.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,e.texture,this.camera,i,n=>{const r={mean:n.mean/e.scale,brightest:n.brightest/e.scale},a=this.frameLight,o=e.atMs,c=a?o-a.atMs:1/0,h=c<0||c>he.EXPOSURE_JUMP_MS,d=h||c===0&&a?.jumped?1:1-Math.exp(-c/s),u=(m,v)=>m>0&&v>0?m*(v/m)**d:v,p={mean:u(a?.mean??0,r.mean),brightest:u(a?.brightest??0,r.brightest),atMs:o,jumped:h||c===0&&(a?.jumped??!1)};this.frameLight=p;const f=(m,v)=>Math.abs(m-v)>.01*Math.max(m,v);(!a||f(a.mean,p.mean)||f(a.brightest,p.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(qi.uRetinaOn.value=0,this.medium)return;const e=[];for(const a of this.emitterLights.farEmitters){const o=this.screenPointOf(a.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||e.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:gr.luminanceOf(a.lux)})}const t=this.renderer.getDrawingBufferSize(this.retinaSize),i=t.x/Math.max(t.y,1),s={width:this.camera.fov*i,height:this.camera.fov},n=this.retina?.atMs;if((n===void 0||this.recordingTimeMs<n||this.recordingTimeMs-n>mt.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new mt,this.retina.replay(0,this.recordingTimeMs,a=>this.historicBleachingAt(a,i),s,this.retinaHistoryOf);else{if(!this.retina&&e.length===0)return;this.retina??=new mt,this.retina.advance(this.recordingTimeMs,e,s)}this.retina.any&&(qi.uRetina.value=this.retina.texture,qi.uRetinaOn.value=1,qi.uRetinaViewport.value.copy(t))}retinaSize=new ie;retinaHistory;setRetinaHistory(e,t){this.retinaHistory=e,this.retinaHistoryOf=t}retinaHistoryOf;historicBleachingAt(e,t){const i=this.retinaHistory?.(e);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*ci,-(s?.headingDeg??0)*ci,(s?.rollDeg??0)*ci,"YXZ")).invert(),r=s?.fovDeg??this.camera.fov,a=[];for(const o of i.views){const c=this.farEmitterOf(o.head,o.magnitude);if(!c)continue;const h=this.screenPointIn(this.historicDirection.copy(c.direction).applyQuaternion(n),r,t);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||a.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:gr.luminanceOf(c.lux)})}return a}historicQuaternion=new Un;historicEuler=new uo;historicDirection=new D;pickAfterimageAt(e,t){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(e,t)<he.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(e){this.recordingTimeMs=e}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(e){const t=[];for(const i of e)i.traverse(s=>{s.userData.emissive===!0&&t.push(s)});return t}surroundings;animate(e,t){const i=Math.min(t/1e3,$7);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(),ue.setWindowLuminance(this.relativeScale),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.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(r,a,o)=>this.directionAtScreenPoint(r,a,o),r=>this.screenPointOf(r)),this.references?.place(this.camera);const i=Math.max(this.phenomena.furthestM,this.references?.furthestM??0)*1.2;i>this.camera.far&&(this.camera.far=i,this.camera.updateProjectionMatrix()),this.hideVeilsBehindDecor(),this.mirrors.any&&!this.mirrors.render(this.renderer,this.scene,this.camera,this.phenomena.any?[Py]:[],!e)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},fr.INTERVAL_MS)),qi.uRodShare.value=this.scatteredSky?.rodShare??0,qi.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina();const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(r=>r.visible);qi.uHasOverlay.value=s?1:0;const n=s?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,n,e):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,e);return}t.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,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 Rr&&t.userData.pointSource||t instanceof Me&&t.userData.skyRibbon)&&e.push(t)}),[...e,...this.bodySystem.pointSources]},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(n=>n.visible))return;t&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),e.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,e.layers.set(k1),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}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(uI),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 ir({blending:ih,blendSrc:io,blendDst:io,blendSrcAlpha:io,blendDstAlpha:io,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(this.references.layer),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=t,this.renderer.shadowMap.autoUpdate=i}setReferences(e,t){const i=e.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,t);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:t},this.referencesLoading??=Q(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-DIlZXaIz.js");return{ReferenceSystem:s}},__vite__mapDeps([17,18]),import.meta.url).then(({ReferenceSystem:s})=>{const n=new s(this.scene,()=>{this.render(),this.onReferencesSettled?.()});this.references=n,n.onFrame=()=>this.render(),this.referenceClock&&n.setTime(this.referenceClock);for(const[a,o]of this.referenceViews)n.setView(a,o);n.setShown(this.referencesShown);const r=this.pendingReferences;return this.pendingReferences=void 0,r&&n.set(r.references,void 0,r.observerAt),this.render(),n})}setReferencesTime(e){this.referenceClock=e,this.references?.setTime(e)}referenceAspect(e){return this.references?.aspectOf(e)}directionAt(e,t){return this.directionAtScreenPoint(e,t,new D)}referenceFailure(e){return this.references?.failureOf(this.documentRelative(e))}setReferencesShown(e){this.referencesShown=e,this.references?.setShown(e),this.render()}setReferenceView(e,t){this.referenceViews.set(e,t),this.references?.setView(e,t),this.render()}renderPhenomenaPass(e){if(!this.phenomena.any)return;e.updateMatrixWorld();const t=this.phenomena.screenBox(e);if(t&&(t.x0>1||t.x1<-1||t.y0>1||t.y1<-1))return;const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,this.renderer.clearDepth();const n=t?this.narrowTo(e,t):e,r=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),a=this.phenomena.furthestM;let o=0;for(const c of this.decorObjects){const h=this.decorGroups.get(c.id);if(!h)continue;const d=c.kind!=="crop"&&this.mayHide(h,e,r,a);he.markDecorDepth(h,d),d&&o++}o>0&&(e.layers.set(D1),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,e),this.scene.overrideMaterial=null),e.layers.set(Py),this.renderer.render(this.scene,e),e.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new zg;phenomenaViewProjection=new qe;occluderSphere=new ea;localBounds=new WeakMap;mayHide(e,t,i,s){let n=0;e.traverse(()=>n++);let r=this.localBounds.get(e);if(!r||r.objects!==n){e.updateMatrixWorld(!0);const o=new ai().setFromObject(e);if(o.isEmpty())return!1;r={sphere:o.getBoundingSphere(new ea).applyMatrix4(new qe().copy(e.matrixWorld).invert()),objects:n},this.localBounds.set(e,r)}const a=this.occluderSphere.copy(r.sphere).applyMatrix4(e.matrixWorld);return a.center.distanceTo(t.position)-a.radius>s?!1:i.intersectsSphere(a)}narrowTo(e,t){const i=this.renderer.getDrawingBufferSize(new ie),s=he.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,t.x0)+1)/2*i.x-s)),r=Math.max(0,Math.floor((Math.max(-1,t.y0)+1)/2*i.y-s)),a=Math.min(i.x,Math.ceil((Math.min(1,t.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,t.y1)+1)/2*i.y+s)),c=this.narrowCamera.copy(e);return c.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,a-n),Math.max(1,o-r)),c.updateMatrixWorld(),c}narrowCamera=new vn;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new ir({colorWrite:!1,side:$s});static HEAD_TURN_LIMIT_DEG=85;static turnHead(e,t,i){const s=e.getObjectByName("head");if(!s)return;const n=((i-t)%360+540)%360-180,r=Math.max(-85,Math.min(he.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-r*ci}static isSolidSurface(e){if(!(e instanceof Me))return!0;const t=Array.isArray(e.material)?e.material[0]:e.material;return t.depthWrite!==!1&&t.blending!==qs}static markDecorDepth(e,t){e.traverse(i=>{if(!(i instanceof Me))return;t&&he.isSolidSurface(i)?i.layers.enable(D1):i.layers.disable(D1)})}startExposure(){this.cancelExposure(),this.exposureSubjectBounds=[];const e=this.renderer.getDrawingBufferSize(new ie),t=Math.max(1,Math.round(e.x)),i=Math.max(1,Math.round(e.y));this.exposureAccumulation||(this.exposureAccumulation=new YN(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 s=performance.now()+he.EXPOSURE_BUDGET_MS,n=he.exposureInstantsPerFrame(t.instantTarget.scene.width*t.instantTarget.scene.height);let r=0;do{this.restateAt(e,this.exposureInstantsDone);const a=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(t.instantTarget)}finally{this.compassSprites.forEach((o,c)=>{o.visible=a[c]})}t.add(this.renderer,i),this.exposureInstantsDone++,r++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&r<n);this.restateAt(e,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){qi.uRodShare.value=this.scatteredSky?.rodShare??0,qi.uHasOverlay.value=1,qi.uRelativeScale.value=this.relativeScale,this.applyMedium();const e=this.exposureInstants/this.exposureInstantsDone,t=this.usableGhostPass();if(t?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t&&this.exposureAccumulation?t.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,e,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,e),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(a=>a.visible))return;const i=new Fr,s=new Ur(-1,1,1,-1,0,2),n=Hm/(R2*Math.tan(C2*ci/2));for(const a of this.compassSprites){if(!a.visible)continue;const o=a.getWorldPosition(new D).sub(this.camera.position).normalize(),c=this.screenPointOf(o);if(!c)continue;const h=new Su(a.material);h.position.set(c.ndcX,c.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const r=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=r}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const e=[],t=new ai,i=new D,s=this.camera.getWorldDirection(new D),n=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[...n,...r]){if(!a?.visible||(t.setFromObject(a),t.isEmpty())||t.distanceToPoint(this.camera.position)<he.MAP_SUBJECT_NEAREST_M)continue;let o=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(s)<=0)continue;const m=this.screenPointOf(i);if(!m)continue;const v=(m.ndcX+1)/2,g=(1-m.ndcY)/2;o=Math.min(o,v),c=Math.max(c,v),h=Math.min(h,g),d=Math.max(d,g)}o=Math.max(o,0),c=Math.min(c,1),h=Math.max(h,0),d=Math.min(d,1),c>=o&&d>=h&&e.push({x:o,y:h,width:c-o,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 ie),i=Math.max(1,Math.round(t.x)),s=Math.max(1,Math.round(t.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new up(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(e.focalLengthMm,e.fNumber,e.focusDistance,e.frameHeightMm),this.depthOfFieldPass}setLensGhosts(e){JSON.stringify(e)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=e,e.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(e,t){return this.ghostPass?.holdsPictureAt(this.renderer,e,t)??!1}pickGhostAt(e,t){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,e,t,this.ghostOptics,qi.uMediumExposure.value)}pickDropAt(e,t){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,e,t)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const e=this.renderer.getDrawingBufferSize(new ie);return this.ghostPass?this.ghostPass.resize(e.x,e.y):this.ghostPass=new Ts(e.x,e.y),this.ghostPass}usableFinishPass(){const e=this.renderer.getDrawingBufferSize(new ie);return this.finishPass?this.finishPass.resize(e.x,e.y):this.finishPass=new qw(e.x,e.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant")return;const e=this.renderer.getDrawingBufferSize(new ie);return this.equidistantPass?this.equidistantPass.resize(e.x,e.y):this.equidistantPass=new Xi(e.x,e.y),this.equidistantPass}aimAtScreenPoint(e,t,i){this.aimStraightAtScreenPoint(e,t,i),e===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(e,s=>{const n=he.firstSolid(e.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(e,t,i){const s=this.projectionKind==="equidistant"?this.equidistantPass:void 0;if(!s){e.setFromCamera(new ie(t,i),this.camera);return}const n=s.directionFor(t,i,this.camera.fov);this.camera.updateMatrixWorld(),e.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),e.ray.direction.set(n.x,n.y,n.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),s=i.x/Math.max(i.y,1);return this.screenPointIn(t,this.camera.fov,s)}screenPointIn(e,t,i){if(this.projectionKind==="equidistant"&&this.equidistantPass)return Xi.ndcFor(e,t,i);if(e.z>=0)return;const s=Math.tan(t/2*ci);return{ndcX:e.x/-e.z/(i*s),ndcY:e.y/-e.z/s}}screenPointScratch=new D;screenPointQuaternion=new Un;screenPointSize=new ie;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 s=this.renderer.domElement.width,n=this.renderer.domElement.height;e.uniforms.uResolution.value.set(s,n),e.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const e=this.lensFlare;if(!e||!e.mesh.visible)return;const t=this.sunDiscRadiance.map(c=>Math.max(0,c-he.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(t[1]<=0)return;const i=Math.tan(e.uniforms.uSourceRadiusDeg.value*Math.PI/180)/e.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=e.uniforms.uLensPosition.value,r=e.uniforms.uTanHalfFov.value,a=this.camera.aspect,o=xi.offFrameShare(Math.atan(Math.hypot(n.x*a,n.y)*r)*180/Math.PI,Math.atan(Math.hypot(a,1)*r)*180/Math.PI);if(!(o<=0))return{x:n.x,y:n.y,radius:i,flux:[t[0]*s*o,t[1]*s*o,t[2]*s*o]}}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 s=this.renderer.getDrawingBufferSize(this.screenPointSize);e.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),e.uniforms.uResolution.value.set(s.x,s.y),e.uniforms.uEquidistant.value=1,e.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,e.mesh.visible=!0,e.mesh.layers.enable(E2),this.camera.layers.set(E2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),e.mesh.visible=!1,e.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let e=0;for(const t of P2)this.isSunOccluded(t[0],t[1])||e++;return e/P2.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){return this.isOccludedToward(this.sunWorldPosition,e,t)}isOccludedToward(e,t=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(e).sub(this.camera.position),r=n.length();if(n.normalize(),t!==0||i!==0){const c=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const d=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,t*c).addScaledVector(d,i*c).normalize()}if(this.groundBlocks(this.camera.position,n,r)||this.cabinMask.hides(n))return!0;const a=this.cabinMask.any?s.filter(c=>!this.cabinGroups.includes(c)):s;if(a.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(a,!0).find(c=>!(c.object.material instanceof qo));return o!==void 0&&o.distance<r}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let e=!1;for(const t of this.glareSprites.values()){if(!t.mesh.visible)continue;e||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),e=!0);const i=t.mesh.getWorldPosition(this.veilTargetScratch),s=t.mesh.material.uniforms.uSourceDeg.value,n=s>.05?he.VEIL_SAMPLES:he.VEIL_SAMPLES.slice(0,1);let r=0;for(const[a,o]of n)this.isOccludedToward(i,a*s,o*s)||r++;t.share=r/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new hr;veilTargetScratch=new D;groundBlocks(e,t,i,s=0){const n=this.groundMesh;if(n&&t.y<0){const v=(n.position.y-e.y)/t.y;if(v>s&&v<i){const g=e.x+t.x*v-n.position.x,b=e.z+t.z*v-n.position.z;if(Math.hypot(g,b)<=this.groundRadius)return!0}}const r=this.terrainMesh;if(!r)return!1;const a=r.geometry.getAttribute("position"),o=Math.round(Math.sqrt(a.count));if(o<2||o*o!==a.count)return!1;const c=[r.position.x+a.getX(0),r.position.x+a.getX(o-1)],h=[r.position.z+a.getZ(0),r.position.z+a.getZ((o-1)*o)],d=Math.min(Math.abs(c[1]-c[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(d>0))return!1;let u=s,p=i;for(const[v,g,b]of[[e.x,t.x,c],[e.z,t.z,h]]){const w=Math.min(b[0],b[1]),y=Math.max(b[0],b[1]);if(Math.abs(g)<1e-12){if(v<w||v>y)return!1;continue}const M=(w-v)/g,x=(y-v)/g;u=Math.max(u,Math.min(M,x)),p=Math.min(p,Math.max(M,x))}if(!(p>u))return!1;const f=Math.hypot(t.x,t.z),m=Math.min(4096,Math.max(8,Math.ceil((p-u)*f/(d/2))));for(let v=0;v<=m;v++){const g=u+(p-u)*v/m,b=e.x+t.x*g,w=e.y+t.y*g,y=e.z+t.z*g;if(w<=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=Nm;let s,n;for(const r of this.decorObjects){if(r.kind==="crop")continue;const a=this.decorGroups.get(r.id);if(!a)continue;const o=this.ufoOcclusionRaycaster.intersectObject(a,!0).find(c=>he.isSolidSurface(c.object));o&&(r.occludesSourceIds?.includes(i)?s=s===void 0?o.distance:Math.max(s,o.distance):n=n===void 0?o.distance:Math.min(n,o.distance))}return{behindM:s,inFrontM:n}}pickBodyAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=p7*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,o=a?[{key:"sun",direction:a.sun,radiusRad:a.sunRadiusRad},{key:"moon",direction:a.moon,radiusRad:a.moonRadiusRad,inFront:!0}]:[],c=he.nearestBody(s,[...r.filter(h=>!a||h.key!=="sun"&&h.key!=="moon"),...o],n);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 s,n=1/0,r=1/0,a=!1;for(const o of t){const c=Math.acos(Fa(o.direction.dot(e),-1,1))-o.radiusRad;if(c>i)continue;const h=c<=0,d=n<=0,u=o.inFront===!0;(h!==d?h:h?u!==a?u:o.radiusRad<r:c<n)&&(s=o.key,n=c,r=o.radiusRad,a=u)}return s}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 s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,r=c7*this.camera.fov*Math.PI/180,a=[...this.decorGroups.values()],o=a.length>0?he.firstSolid(this.raycaster.intersectObjects(a,!0))?.distance:void 0;let c,h=1/0;const d=new ai,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,m=u.clone().sub(n),v=m.length();if(v===0||m.dot(s)<=0||o!==void 0&&o<v-f)continue;const g=Math.acos(Math.min(1,m.normalize().dot(s))),b=Math.atan(f/v);if(b>r){const w=this.raycaster.intersectObject(p,!0)[0];if(!w||o!==void 0&&o<w.distance)continue}else if(g>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,s=Math.cos(Um*this.camera.fov*Math.PI/180);let n,r=s;for(const a of this.namedStars){const o=a.direction.dot(i);o>r&&(r=o,n={star:a.star,altitudeDeg:a.altitudeDeg})}return n&&this.groundHides(e,t)?void 0:n}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,Nm)}bodyScreenBox(e){const t=this.bodySystem.boxOf(e,this.bodyBoxScratch);if(!t)return;let i=1/0,s=1/0,n=-1/0,r=-1/0;for(let a=0;a<8;a++){const o=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(o.sub(this.camera.position).normalize());if(!c)return;i=Math.min(i,c.ndcX),n=Math.max(n,c.ndcX),s=Math.min(s,c.ndcY),r=Math.max(r,c.ndcY)}return{minX:i,minY:s,maxX:n,maxY:r}}bodyBoxScratch=new ai;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 s=1/0,n=1/0,r=-1/0,a=-1/0;for(let o=0;o<8;o++){const c=this.bodyCornerScratch.set(o&1?i.max.x:i.min.x,o&2?i.max.y:i.min.y,o&4?i.max.z:i.min.z),h=this.screenPointOf(c.sub(this.camera.position).normalize());if(!h)return;s=Math.min(s,h.ndcX),r=Math.max(r,h.ndcX),n=Math.min(n,h.ndcY),a=Math.max(a,h.ndcY)}return{minX:s,minY:n,maxX:r,maxY:a}}decorDrawnOffset(e){return this.lampNudges.get(e)}decorGroundPointAt(e,t,i,s=0){const n=this.decorGroups.get(e);if(!n)return;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),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*ci/2):0}decorGrabHeightAt(e,t,i){const s=this.decorGroups.get(e);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,t,i);const r=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(r.lengthSq()<1e-6)return 0;r.normalize();const a=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(r,s.position),o=this.raycaster.ray.intersectPlane(a,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new ma;decorHitScratch=new D;static firstSolid(e){return e.find(t=>{const i=t.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<he.SEE_THROUGH_BELOW||n instanceof qo))})}static SEE_THROUGH_BELOW=.9;pickDecorAt(e,t){this.aimAtScreenPoint(this.raycaster,e,t);const i=[...this.decorGroups.entries()],s=he.firstSolid(this.raycaster.intersectObjects(i.map(([,a])=>a),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let r=s.object;for(;r&&!i.some(([,a])=>a===r);)r=r.parent;return i.find(([,a])=>a===r)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(e,t){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new oh().copy(s).applyMatrix4(new qe().copy(i.group.matrixWorld).invert()),r=i.group.matrixWorld,a=(u,p)=>{const f=new D(u,0,p).applyMatrix4(r);return this.groundYUnder(f.x,f.z)-r.elements[13]};if(!i.mayMeet(n.origin,n.direction,a,he.RAILWAY_PICK_ABOVE_M))return;const o=he.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-he.RAILWAY_GROUND_MARGIN_M,Nm))return;const c=i.group.worldToLocal(o.point.clone()),h=i.lineAt(c.x,c.z);if(!h)return;const d=i.contactHeightM(h);return{line:h,distanceM:o.distance,...d!==void 0?{contactM:d}:{}}}pickSkyEventAt(e,t,i=()=>!0){const s=[...this.skyEventLayers.values()].filter(c=>c.simulation?.pick&&c.simulation.drawnCount>0&&i(c.kind,c.simulation));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,e,t);const n=this.raycaster.ray,r={toleranceRad:he.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Um*this.camera.fov*Math.PI/180),skyLightTowards:c=>this.skyLightTowards(c)};let a;for(const c of s){const h=c.simulation.pick(n.origin,n.direction,r);h&&(!a||(h.distanceM??1/0)<(a.distanceM??1/0))&&(a={kind:c.kind.key,...h})}if(!a)return;if(a.distanceM===void 0)return this.groundHides(e,t)?void 0:a;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,a.distanceM-1,Nm))return;const o=he.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(o&&o.distance<a.distanceM))return a}skyLightTowards(e){const t=this.scatteredSky?.ambient;if(!t)return 0;const i=r=>.2126*r[0]+.7152*r[1]+.0722*r[2],s=Math.hypot(e.x,e.y,e.z)||1,n=Math.max(0,Math.min(1,e.y/s));return i(t.horizon)+(i(t.zenith)-i(t.horizon))*Math.sqrt(n)}static BEAM_PICK_PIXELS=6;static RAILWAY_GROUND_MARGIN_M=1;dispose(){this.stopTerrainFade(),this.stopTwinkle(),this.cancelFlush(),clearTimeout(this.mirrorCatchUp),this.cabinMask.dispose(),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.retina?.dispose(),this.disposeMesh(this.skyMesh),this.disposeMesh(this.groundMesh),this.disposeMesh(this.terrainMesh),this.dropFarRing(),this.roadSystem.dispose(),this.waterSystem?.dispose(),this.railwaySystem?.dispose(),this.traceSystem?.dispose(),this.contrailSystem?.dispose(),this.contrailSystem=void 0;for(const e of this.skyEventLayers.values())e.simulation?.dispose();this.skyEventLayers.clear(),this.skyEventsStated=void 0,this.disposeCloudSystem(),this.disposeCirrus(),this.disposePrecipitationPoints(),this.disposeRain(),this.disposeStarTiers(),this.meteorSystem?.dispose(),this.meteorSystem=void 0,this.iceHalos?.dispose(),this.iceHalos=void 0,this.rainbow?.dispose(),this.rainbow=void 0,this.skyGlow?.dispose(),this.skyGlow=void 0,this.depthOfFieldPass?.dispose(),this.finishPass?.dispose(),this.ghostPass?.dispose(),this.ghostPass=void 0,this.depthOfFieldPass=void 0,this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0,this.cometTail?.dispose(),this.cometTail=void 0,this.satelliteField?.dispose(),this.satelliteField=void 0,this.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.mirrors.clear(),this.decorLamps=[],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 s=this.animationsRunning;this.animationsRunning=e,this.framesDriven=i,e&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!e&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!e&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!e||this.frameDirty)&&this.render(),n&&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<he.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 Rs(Pm,32,16),i=t.attributes.position,s=t.getAttribute("color")??new wt(new Float32Array(i.count*3),3);for(let r=0;r<i.count;r++){const{altitudeDeg:a,azimuthDeg:o}=iI(i.getX(r),i.getY(r),i.getZ(r)),c=n8(a,o,e.azimuthDeg,e.altitudeDeg);s.setXYZ(r,c[0],c[1],c[2])}if(s.needsUpdate=!0,this.skyMesh)return;t.setAttribute("color",s);const n=new ir({vertexColors:!0,side:Ji,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new Me(t,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const e=A2(this.observerElevationM);if(this.groundMesh&&e===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=e;const t=new Fw(this.groundRadius,48),i=new ta({color:new oe(R1,R1,R1),fog:!0});Yc.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new Me(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 s=0;if(i){const n=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<n.count;r++)Math.abs(n.getX(r)+i.position.x)>600||Math.abs(n.getZ(r)+i.position.z)>600||(s=Math.min(s,n.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}this.groundMesh.position.y=s,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":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(e,t);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(e,t=!1){const i=Li(e.altitudeDeg,e.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,t);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Gt.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*g7);const r=t?0:this.weather.highCloudCover??0;return r>0&&(s*=1-Gt.iceAlphaAt(i,zm,r,this.cloudFieldOffset)*v7),Math.max(0,Math.min(1,s))}setBodyMesh(e,t,i,s,n){if(t.altitudeDeg<v0){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:o}=Li(t.altitudeDeg,t.azimuthDeg,Gn),c=this.cloudTransmission(t),h=this.arrivingIlluminance(t,n,c),d=he.unitLuminance(s);let u=this.bodyMeshes.get(e);if(e==="sun"){const p=Math.PI*(i/Gn)**2,f=[0,1,2].map(v=>d[v]*h[v]/(this.sunBeamFraction*p));this.sunDiscRadiance=f;const m=f.map(v=>Math.min(he.BRIGHTEST_RELATIVE,v));u instanceof Me||(this.disposeMesh(u),u=new Me(new Rs(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)),u.material.color.setRGB(m[0],m[1],m[2]),u.scale.setScalar(i)}else{if(!(u instanceof Rr)){this.disposeMesh(u);const m=new Tt;m.setAttribute("position",new Et(new Float32Array(3),3)),m.setAttribute("color",new Et(new Float32Array(3),3)),u=new Rr(m,Ke.material(Fd[Fd.length-1].size,!1)),Ke.track(u),this.celestialGroup.add(u),this.bodyMeshes.set(e,u)}const p=u.geometry.getAttribute("color"),f=e.startsWith("comet:")?this.pointToPixel():1;p.setXYZ(0,d[0]*h[0]*f,d[1]*h[1]*f,d[2]*h[2]*f),p.needsUpdate=!0}if(u.position.set(r,a,o),this.setHitArea(e,r,a,o,i),e==="sun"&&(this.sunArriving=h),e.startsWith("comet:")?this.disposeGlare(e):e!=="sun"&&this.setGlare(e,r,a,o,h,i/Gn*(180/Math.PI),he.POINT_VEIL_HOLD_DEG),e==="sun"){this.sunVisible=!0;const p=this.celestialGroup.scale.x;this.sunWorldPosition.set(r*p,a*p+this.celestialGroup.position.y,o*p),this.lensFlare||(this.lensFlare=_8(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(e,t){const i="moon";if(e.magnitude>t||e.altitudeDeg<v0){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i);return}const{x:s,y:n,z:r}=Li(e.altitudeDeg,e.azimuthDeg,Gn),a=this.cloudTransmission(e),o=this.arrivingIlluminance(e,e.magnitude,a),c=e.radiusDeg??Ln.MEAN_RADIUS_DEG,h=Gn*Math.tan(c*ci),d=Math.max(Fa(e.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Gn)**2,u=new oe(...o.map(m=>Math.min(he.BRIGHTEST_RELATIVE,m/d))),p=`${e.phase.phaseFraction<.5}:${Math.round(Fa(e.phase.illuminatedFraction,0,1)*500)}`;let f=this.bodyMeshes.get(i);f instanceof Su?(f.userData.phaseKey!==p&&(f.material.map?.dispose(),f.material.map=J2(e.phase),f.userData.phaseKey=p),f.material.color.copy(u)):(this.disposeMesh(f),f=new Su(new h0({map:J2(e.phase),color:u,fog:!1,blending:qs,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(s,n,r),this.setHitArea(i,s,n,r,h),this.setGlare(i,s,n,r,o,c)}bentLight(e,t,i=f7){const[s,n,r]=this.arrivingIlluminance(e,t,1),a=Math.max(n,1e-30);return{scale:n/i,tint:[s/a,1,r/a]}}static litBySky(e,t){return he.litScratch.setRGB(e.r*t[0],e.g*t[1],e.b*t[2])}static litScratch=new oe;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 ie;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(e,t,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,e.altitudeDeg),n=$t.illuminanceOf(t)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(e){const t=gr.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,s,n){let r=this.hitAreas.get(e);if(!r){const o=new h0({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});r=new Su(o),this.celestialGroup.add(r),this.hitAreas.set(e,r)}r.position.set(t,i,s);const a=n*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,s,n,r,a=0){if(Vs.radiusDeg(Vs.K*Math.max(...n))<=Math.max(r,a)){this.disposeGlare(e);return}let o=this.glareSprites.get(e);o||(o=new Vs(`veil:${e}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(e,o)),o.shine({x:t,y:i,z:s},n,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 s=ud(e.magnitude,t),n=l1(s);this.cometKey=i,this.setBodyMesh(i,e.position,P1*(.5+.5*s),new oe(n,n,n),e.magnitude),this.cometTail||(this.cometTail=new _r(Gn),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(e.position,e.tailEnd,s)}buildIceHalos(e,t){this.iceHalos||(this.iceHalos=new gs,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(),s=this.layeredClouds?.cirrusMask;if(this.iceHalos.setCloudOffset(s?.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:zm},0);return}const n=this.lowerCloudCover(),r=Mt.deckLitUntilDeg(Mt.DECK_HEIGHT_M),a=e.altitudeDeg>-r?e:t,o=this.bentLight(a,a===e?yt.SUN_MAGNITUDE:t.magnitude),c=Mt.strength(i,n,a.altitudeDeg,r)*o.scale,{x:h,y:d,z:u}=Li(a.altitudeDeg,a.azimuthDeg,1);this.iceHalos.update({x:h,y:d,z:u},a.altitudeDeg,c,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??zm},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??y0,this.weather.rareIceCrystals)}buildRainbow(e,t){this.rainbow||(this.rainbow=new Uc,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=e.altitudeDeg>0,n=s?e:t,r=this.lowerCloudCover(),a=this.bentLight(n,s?yt.SUN_MAGNITUDE:t.magnitude,m7),o=Dn.strength(i,r,n.altitudeDeg)*a.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:c,y:h,z:d}=Li(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:c,y:h,z:d},o,a.tint,s)}buildSkyGlow(e,t){if(!e.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new Al,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=e.frame,n=kr.galactic(i,s),r=he.directionOf(n.centre),a=he.directionOf(n.rotation),o=he.directionOf(n.pole),c=new bt().set(r.x,r.y,r.z,a.x,a.y,a.z,o.x,o.y,o.z),h=he.directionOf(kr.eclipticPole(i,s)),d=he.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:he.directionOf(e.moon),altitudeDeg:e.moon.altitudeDeg,phaseAngleDeg:pe.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:s}=Li(e.altitudeDeg,e.azimuthDeg,1);return new D(t,i,s).normalize()}buildNovae(e,t){const i=new Set;for(const s of e){if(s.magnitude>t)continue;const n=`nova:${s.id}`;i.add(n);const r=ud(s.magnitude,t),a=l1(r);this.setBodyMesh(n,s.position,P1*(.5+.5*r),new oe(a,a,a),s.magnitude)}for(const s of this.novaKeys)i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s));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 s of e){if(s.magnitude>t)continue;i.add(s.body);const n=ud(s.magnitude,t),r=l1(n),a=q7[s.body]??new oe(1,1,1),o=new oe(a.r*r,a.g*r,a.b*r),c=P1*(.5+.5*n);this.setBodyMesh(s.body,s.position,c,o,s.magnitude)}for(const s of[...this.bodyMeshes.keys()])i.has(s)||(this.disposeMesh(this.bodyMeshes.get(s)),this.bodyMeshes.delete(s),this.disposeHitArea(s),this.disposeGlare(s))}buildStars(e,t){if(this.namedStars=[],!e||e.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=e,r=new fa(s,n),a=$1(1337),o=[],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<I2)continue;const{x:f,y:m,z:v}=Li(u,p,C1);o.push({x:f,y:m,z:v,brightness:ud(d,t),illuminance:this.air.transmittanceFromSpace(c,u).map(g=>g*$t.illuminanceOf(d)),phase:a()*Math.PI*2,speedFactor:.7+a()*.6})}for(const h of wT){if(h.mag>t)continue;const{altitudeDeg:d,azimuthDeg:u}=r.position(h.raHours,h.decDeg);if(d<I2)continue;const{x:p,y:f,z:m}=Li(d,u,C1);this.namedStars.push({star:h,direction:new D(p,f,m).normalize(),altitudeDeg:d})}this.starTiers=Fd.map((h,d)=>{const u=o.filter(M=>Yw(M.brightness)===d),p=new Float32Array(u.length*3),f=new Float32Array(u.length),m=new Float32Array(u.length*3),v=new Float32Array(u.length),g=new Float32Array(u.length);u.forEach((M,x)=>{p[x*3]=M.x,p[x*3+1]=M.y,p[x*3+2]=M.z,f[x]=M.brightness,m.set(M.illuminance,x*3),v[x]=M.phase,g[x]=M.speedFactor});const b=new Tt;b.setAttribute("position",new Et(p,3)),b.setAttribute("seed",new Et(v.map(M=>M/(2*Math.PI)),1));const w=new Et(new Float32Array(u.length*3),3);b.setAttribute("color",w);let y=this.starTiers[d]?.points;return y?(y.geometry.dispose(),y.geometry=b):(y=new Rr(b,Ke.material(h.size)),Ke.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:w,brightness:f,illuminance:m,phase:v,speedFactor:g}}),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 s=i.colorAttribute.array;for(let n=0;n<i.brightness.length;n++)s[n*3]=i.illuminance[n*3]*t,s[n*3+1]=i.illuminance[n*3+1]*t,s[n*3+2]=i.illuminance[n*3+2]*t;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Nd(this.celestialGroup,N1,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 oe(yc[0]+(B1[0]-yc[0])*t,yc[1]+(B1[1]-yc[1])*t,yc[2]+(B1[2]-yc[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:s,uniforms:n}=Ey(i,e,Math.abs(this.cloudLayerOffset()));this.cloudMaterial=s,this.cloudUniforms=n,n.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);const r=Ay(N1);this.cloudMesh=new Me(r,s),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}=Ey(new oe(...yc),e,zm,1);this.cirrusMaterial=t,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new Me(Ay(N1*1.04),t),this.cirrusMesh.renderOrder=N2-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?Nd.deckOrder(!0,0,1):N2}cloudLayerOffset(){const t=((this.weather.cloudBaseM??Yy)-this.observerElevationM)*F1;return Math.sign(t||1)*Math.max(Math.abs(t),R7)}updateCloudLighting(e,t){const i=[this.cloudUniforms,this.cirrusUniforms].filter(d=>d!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,r,a]=this.cloudBeam.map(d=>d/Math.PI),o=this.lightningLevel*W1*this.relativeScale/Math.PI,c=new oe(t[0]+Ra.r*o,t[1]+Ra.g*o,t[2]+Ra.b*o);this.layeredClouds?.setLighting(s.clone(),new oe(n,r,a),c,c);const h=Math.max(0,s.y);for(const d of i)d.sunDir.value.copy(s),d.sunColor.value.setRGB(n*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 B7(e,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const e=[[this.rainSystem?.points,G1],[this.rainSplashSystem?.points,wc],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:z1[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=z2(V1(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=z1[e],i=t.poolSize,s=$1(9001),n=new Float32Array(i*3),r=new Float32Array(i),a=new Float32Array(i),o=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 w=0;w<i;w++){const y=s()*Math.PI*2,M=s()*t.radiusM;n[w*3]=Math.cos(y)*M,n[w*3+1]=Qh+s()*(t.topYM-Qh),n[w*3+2]=Math.sin(y)*M,r[w]=s()*Math.PI*2,a[w]=.7+s()*.6,o[w]=.6+s()*.8,c[w]=.4+s()*1.2}const m=new Tt;m.setAttribute("position",new Et(n,3)),m.setDrawRange(0,this.precipitationCount(i));const v={uSize:{value:t.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:t.opacity},uColor:{value:t.color.clone()},uHazeColor:{value:new oe(...this.baseFogColor)},uTexture:{value:j7(e)},uNearFocusDistance:{value:W2},uHazeDistance:{value:t.radiusM*$2}},g=new Nt({uniforms:v,vertexShader:iF,fragmentShader:sF,transparent:!0,depthWrite:!1});this.precipitationUniforms=v;const b=new Rr(m,g);b.renderOrder=U1,this.scene.add(b),this.precipitationPoints=b,this.precipitationPositions=n,this.precipitationPhase=r,this.precipitationSpeedJitter=a,this.precipitationWobbleFreqJitter=o,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 s=z1[i];if(this.precipitationUniforms?.uColor.value.copy(he.litBySky(s.color,this.baseFogColor)),t<=0)return;const n=this.weather.windDirectionDeg*ci,r=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,a=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,c=this.precipitationPhase,h=this.precipitationSpeedJitter,d=this.precipitationWobbleFreqJitter,u=this.precipitationWobbleAmpJitter,p=this.precipitationBounceRemaining,f=this.precipitationBounceHeight,m=this.precipitationBounceDuration,v=this.precipitationBounceVelX,g=this.precipitationBounceVelZ,b=i==="snow"&&d&&u,w=i==="hail"&&p&&f&&m&&v&&g;for(let y=0,M=0;y<o.length;y+=3,M++){if(w&&p[M]>0){if(p[M]-=t,p[M]<=0){const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(S)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(S)*A,p[M]=0}else{const S=1-p[M]/m[M];o[y+1]=Qh+Math.sin(Math.PI*S)*f[M],o[y]=Gm(o[y]+(r+v[M])*t,s.radiusM),o[y+2]=Gm(o[y+2]+(a+g[M])*t,s.radiusM)}continue}let x=0,E=0;if(b){const S=H7*d[M],A=G7*u[M];x=Math.sin(e*S*Math.PI*2+c[M])*A,E=Math.sin(e*S*Math.PI*2+c[M]+Math.PI/2)*A}if(o[y]+=(r+x)*t,o[y+1]-=s.fallSpeedMPerS*h[M]*t,o[y+2]+=(a+E)*t,o[y]=Gm(o[y],s.radiusM),o[y+2]=Gm(o[y+2],s.radiusM),o[y+1]<Qh){if(w){f[M]=j2*(.2+Math.random()*1.6),m[M]=V7*(.5+Math.random()),p[M]=m[M];const T=Math.random()*Math.PI*2,_=W7*(f[M]/j2);v[M]=Math.cos(T)*_,g[M]=Math.sin(T)*_,o[y+1]=Qh;continue}const S=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(S)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(S)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const e=V1(this.weather.precipitationIntensity);this.rainSystem=A8({count:G1,radiusM:Gu,heightM:L7,bottomYM:F2,overallSpeed:O7,color:B2.clone(),opacity:.85,visibleCount:this.precipitationCount(G1),speedStreak:z2(e),pixelSize:X2,seed:9001,nearFocusDistanceM:W2,hazeDistanceM:Gu*$2,hazeColor:new oe(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=U1,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const e=$1(4242),t=new Float32Array(wc*3),i=new Float32Array(wc),s=new Float32Array(wc),n=new Float32Array(wc);for(let h=0;h<wc;h++){const d=e()*Math.PI*2,u=Math.sqrt(e())*Gu;t[h*3]=Math.cos(d)*u,t[h*3+1]=F2,t[h*3+2]=Math.sin(d)*u,s[h]=Z2(H2,G2),i[h]=e()*s[h],n[h]=i[h]/s[h]}const r=new Tt;r.setAttribute("position",new Et(t,3));const a=new Et(n,1);r.setAttribute("aLife",a),r.setDrawRange(0,this.precipitationCount(wc));const o=new Nt({uniforms:{uMaxSize:{value:U7},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:V2.clone()},uTexture:{value:Q7()}},vertexShader:eF,fragmentShader:tF,transparent:!0,depthWrite:!1}),c=new Rr(r,o);c.renderOrder=U1,this.scene.add(c),this.rainSplashSystem={points:c,positions:t,life:i,duration:s,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*ci;e.uniforms.uDropVelocity.value.set(Math.sin(t)*this.weather.windSpeed,-V1(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(he.litBySky(B2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(he.litBySky(V2,this.baseFogColor));const s=this.weather.windDirectionDeg*ci,n=Math.sin(s)*this.weather.windSpeed,r=-Math.cos(s)*this.weather.windSpeed,a=Gu,o=h=>(h%(a*2)+a*3)%(a*2)-a;t.uniforms.uWindOffset.value.set(o(t.uniforms.uWindOffset.value.x+n*e),o(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=Y2+(1-Y2)*(1-c),d=q2+(1-q2)*(1-c);t.uniforms.uUvSquash.value=d,t.uniforms.uPixelSize.value=X2*h*(.5+.5*d)}this.updateRainSplashes(e)}updateRainSplashes(e){const t=this.rainSplashSystem;if(!t||e<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:r}=t,a=r.array;for(let o=0,c=0;o<i.length;o+=3,c++){if(s[c]+=e,s[c]>=n[c]){const h=Math.random()*Math.PI*2,d=Math.sqrt(Math.random())*Gu;i[o]=Math.cos(h)*d,i[o+2]=Math.sin(h)*d,n[c]=Z2(H2,G2),s[c]=0}a[c]=s[c]/n[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 o of this.lightningFlashes){if(o.t>e)break;const c=zs.brightnessAt(o,e);c>i&&(t=o,i=c)}const s=t?Math.min(1,Math.max(.1,(X7/t.distanceM)**2)):0,n=i*s*(t?.cloudToGround?1:.6);if(n===this.lightningLevel&&!t?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,c=n*W1*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Ra.r*c,this.airlight[1]+Ra.g*c,this.airlight[2]+Ra.b*c)}const r=this.skyMesh?.material?.color;if(r){const o=n*Y7;r.setRGB(1+o*Ra.r,1+o*Ra.g,1+o*Ra.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*W1*this.relativeScale,t){const{x:o,y:c,z:h}=Li(25,t.azimuthDeg,Gn);this.lightningLight.position.set(o,c,h)}this.lightningBolt||(this.lightningBolt=new Tl(Gn*.95),this.celestialGroup.add(this.lightningBolt.object));const a=this.weather.cloudBaseM??1500;this.lightningBolt.set(t,i,a),this.render()}buildCompassLabels(){this.compassSprites=T7.map(e=>{const t=Xc.point(e,this.compassPoints),i=new h0({map:nF(t),depthTest:!1,fog:!1}),s=new Su(i),{x:n,y:r,z:a}=Li(0,e,R2);return s.position.set(n,r,a),s.scale.set(Hm,Hm,1),s.renderOrder=D7,s.layers.set(k1),s.visible=this.compassHovered||this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const e=this.camera.fov*Math.PI/360,t=C2*Math.PI/360,i=Hm*Math.tan(e)/Math.tan(t);for(const s of this.compassSprites)s.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 s=i.map;s&&s.dispose(),i.dispose()}}}const ci=Math.PI/180;function Fa(l,e,t){return Math.max(e,Math.min(t,l))}function Z2(l,e){return l+Math.random()*(e-l)}function Gm(l,e){return(l%(e*2)+e*3)%(e*2)-e}let Vm,Wm;function j7(l){switch(l){case"snow":return Z7();case"hail":return J7()}}function Z7(){if(Vm)return Vm;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),Vm=new lc(e),Vm}function J7(){if(Wm)return Wm;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),Wm=new lc(e),Wm}let $m;function Q7(){if($m)return $m;const l=64,e=document.createElement("canvas");e.width=l,e.height=l;const t=e.getContext("2d"),i=t.createRadialGradient(l/2,l/2,0,l/2,l/2,l/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,l,l),$m=new lc(e),$m}const eF=`
|
|
11611
11611
|
uniform float uMaxSize;
|
|
11612
11612
|
uniform float uScale;
|
|
11613
11613
|
attribute float aLife;
|
|
@@ -11751,7 +11751,7 @@ ${Ht.rules([],[".model-picker .model-picker-address p"])}
|
|
|
11751
11751
|
.model-picker .model-thumb img { width: 100%; height: 100%; object-fit: contain; }
|
|
11752
11752
|
.model-picker .model-name { font-weight: 600; }
|
|
11753
11753
|
.model-picker .model-credit { font-size: .8em; color: #666; }
|
|
11754
|
-
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await Q(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-cuvgO3ks.js");return{ModelThumbnails:i}},__vite__mapDeps([20,21]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const a=()=>{const c=++n,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(m=>m.value).join()]);if(u===r){--n;return}r=u,s.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,s.title=this.messages().choose,s.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>xp.pictureOf(m)).then(m=>{if(!m||c!==n)return;const v=new Image;v.src=m,v.alt="",s.prepend(v)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};s.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,s){this.ensureStyle(),this.open(e,t,s,i)}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=xp.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const c=document.createElement("button");c.type="button",c.className="model-picker-close",c.setAttribute("aria-label",n.close),c.title=n.close,c.innerHTML=we.CLOSE;const h=document.createElement("header");h.append(o,c);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),Q(async()=>{const{ModelViewer:E}=await import("./ModelViewer-DjGC6fMB.js");return{ModelViewer:E}},__vite__mapDeps([22,21]),import.meta.url).then(({ModelViewer:E})=>E.end())},p=E=>{E.key==="Escape"&&(E.stopPropagation(),u())},f=i?.current(),m="\0address",v=E=>E===m&&f?Promise.resolve({url:f.url}):t(E),g=E=>{if(u(),s){E!==m&&s(E);return}E===m||E===e.value||(e.value=E,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const w=new Map,y=E=>{const S=document.createElement("button");S.type="button",S.className="model-card",S.dataset.value=E.value,S.setAttribute("aria-pressed",String(!s&&(E.value===m||E.value===e.value&&!f)));const A=document.createElement("div");A.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=E.textContent,S.append(A,T),E.title){const C=document.createElement("span");C.className="model-credit",C.textContent=E.title,S.append(C)}v(E.value).then(C=>xp.pictureOf(C)).then(C=>{if(!C)return;const N=new Image;N.src=C,N.alt="",A.append(N)});let _,k=!1;const L=()=>{k&&!(_&&!_.active)||(k=!0,Promise.all([v(E.value),Q(()=>import("./ModelViewer-DjGC6fMB.js"),__vite__mapDeps([22,21]),import.meta.url)]).then(([C,{ModelViewer:N}])=>{!C||!k||(_=N.show(A,C))}).catch(()=>{}))},P=()=>{k=!1,_?.stop(),_=void 0};return w.set(S,L),S.addEventListener("pointerenter",L),S.addEventListener("focus",L),S.addEventListener("pointerleave",()=>{document.activeElement!==S&&P()}),S.addEventListener("blur",P),S.addEventListener("click",C=>{if(_?.consumeDrag()){C.preventDefault();return}g(E.value)}),S},M=()=>(b=document.createElement("div"),b.className="model-picker-grid",d.append(b),b);if(f){const E=new Option(f.title||f.url,m);E.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(y(E))}for(const E of Array.from(e.children))if(E instanceof HTMLOptGroupElement){const S=document.createElement("h3");S.textContent=E.label,d.append(S);const A=M();for(const T of Array.from(E.children))A.append(y(T));b=void 0}else E instanceof HTMLOptionElement&&(b??M()).append(y(E));i&&this.addAddressForm(h,c,a,d,i,n,u),c.addEventListener("click",u),r.addEventListener("click",E=>{E.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const x=a.querySelector('.model-card[aria-pressed="true"]');(x??c).focus(),x&&w.get(x)?.()}addAddressForm(e,t,i,s,n,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(w,y,M="")=>{const x=document.createElement("label"),E=document.createElement("span");E.textContent=w;const S=document.createElement("input");return S.type=y,S.placeholder=M,x.append(E,S),c.append(x),S},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"),m=h(r.addressSource,"url","https://…"),v=document.createElement("p");v.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,c.append(v,g),i.insertBefore(c,s);const b=()=>{g.disabled=d.value.trim()==="",v.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",b);o.addEventListener("click",()=>{const w=c.hidden;if(c.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const y=n.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",m.value=y?.source??"",b(),d.focus()}),c.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(n.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),b()}}class cM{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=cM.SPAN_DEG;try{const n=(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(n)?n:void 0}catch{return}}}class bU{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),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}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 s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[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(s=>this.offsetHoursAt(s,i)===e)}}class jn{static STEP_MS=100;static plan(e){const t=jn.routeOf(e),i=Rt.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const a=new Set,o=(h,d,u,p)=>{if(Math.abs(h.radiusM-p)>=p*.1)return!1;const{x:f,z:m}=ot(d,u,h.lat,h.lng);return Math.hypot(f,m)<Rt.rebuildDistanceFor(p)};for(let h=0;;h=Math.min(s,h+jn.STEP_MS)){const d=tt(e,h);if(d?.lat!==void 0&&d.lng!==void 0){const u=Rt.groundRadiusFor(d.elevationM??0),p=Rt.patchRadiusFor(u,d.elevationM??0),f=Math.max(p,i);(!r||!o(r,d.lat,d.lng,f))&&(r=n.find(m=>o(m,d.lat,d.lng,f)),r||n.push(r={lat:d.lat,lng:d.lng,radiusM:f})),f<u&&a.add(r)}if(h>=s)break}for(const h of a)n.push({lat:h.lat,lng:h.lng,radiusM:Rt.FAR_RING_RADIUS_M,far:!0});const c=Qp.map(h=>Or.of(h)).filter(h=>h.reachM&&Or.eventsOf(e.skyEvents,h).length>0);if(c.length>0){const h=d=>Math.max(...c.map(u=>u.reachM(Or.eventsOf(e.skyEvents,u),d)));for(const d of[...n])d.far||a.has(d)||Rt.needsFarRing(d.radiusM,0,h(d))&&n.push({lat:d.lat,lng:d.lng,radiusM:Rt.FAR_RING_RADIUS_M,far:!0})}return n}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,s,n){const r=new Date().toISOString().slice(0,10),a=o=>n?.(o,i.length);switch(e){case"relief":{const o=jn.routeOf(t),c=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(sr.boundsOf(p),{width:sg,height:sg},{route:o});c.push({...p,grid:f})}catch(f){console.warn("Relief not snapshots for a patch:",f)}a(u+1)}if(c.length===0)return;const h=s.elevationCredit;return{bytes:await mf.encode({takenOn:r,attribution:h,patches:c}),attribution:h,takenOn:r,answered:c.length,patches:i.length}}case"imagery":{const o=new Q2,c=zi(qc,s.imagery),h=c.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(sr.boundsOf(m),{width:ng,height:ng}),d++}catch(v){console.warn("Imagery not snapshots for a patch:",v)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await ug.encode({takenOn:r,source:c.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return jn.vector(s.roads,i,r,a,(o,c)=>o.getRoads(c),o=>o.contemporary);case"water":return jn.vector(s.water,i,r,a,(o,c)=>o.getWater(c));case"railways":return jn.vector(s.railways,i,r,a,(o,c)=>o.getRailways(c),o=>o.contemporary)}}static mapGround(e){const t=Vc.of(e);return t&&ui.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=jn.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Q2,r=zi(qc,t),a=r.create(n.fetch),o=ui.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not snapshots:",d);return}const c=a.attribution;return{bytes:await ug.encode({takenOn:s,source:r.id,attribution:c,patches:[],map:{bounds:i,pixels:o},tiles:n.tiles}),attribution:c,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=Rt.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await n(e,sr.boundsOf(d))})}catch(u){console.warn("Not snapshots for a patch:",u)}s(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class cs{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#snapshot-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#snapshot-note")}localize(e){this.messages=e,this.root.title=e.snapshotHint;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-annex-source",e.annexSource),t("snapshot-refresh",e.snapshotRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.snapshotLiveState:!t||t.refresh?this.messages.snapshotPending:cs.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&cs.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return os.isLive(this.host.sighting().snapshots,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().snapshots??{}};if(i.live){delete i.live;for(const n of os.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setSnapshots(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#snapshot-state");s.textContent=t?this.messages.snapshotLiveState:i&&!i.refresh?[this.messages.snapshotTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.snapshotPending;const n=this.root.querySelector("#snapshot-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&cs.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!cs.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await Q(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-bXm0nVE4.js");return{SightingFileEditor:r}},__vite__mapDeps([23,3,24]),import.meta.url);if(t!==this.shown||!this.editorHost.isConnected){this.editorFor=void 0;return}this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().snapshots??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await cs.describe(e,n)}}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Ht.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}Ct.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Ht.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await Q(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>AI);return{InputFileElement:s}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().snapshots??{}},n=this.annex(e);let r;try{r=await cs.describe(e,t)}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&cs.isInline(n.src),o=a?cs.dataUrl(e,t):n?.src??os.annexName(this.host.base(),e);a||Ct.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Ht.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setSnapshots(s)}async setStorage(e,t){const i={...this.host.sighting().snapshots??{}},s=this.annex(e);if(!s||cs.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=cs.dataUrl(e,n):(r=os.annexName(this.host.base(),e),Ct.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setSnapshots(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=cs.isInline(t.src)?os.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:cs.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(cs.isZip(e)){const{unzipSync:s}=await Q(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(s(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return Ct.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let s=0;s<t.length;s+=32768)i+=String.fromCharCode(...t.subarray(s,s+32768));return`data:${cs.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().snapshots??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setSnapshots(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,s=(i&&!cs.isInline(i)?cs.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,jn.plan(this.host.sighting()),this.host.sources(),s))?Ht.show(this.note,void 0):Ht.show(this.note,this.messages.snapshotFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setSnapshots(t)}hasWork(){const e=this.host.sighting();return os.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||jn.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.snapshots??{}},s=new Map;this.busy=!0,this.render();try{const n=d=>os.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of os.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=jn.plan(t);let o;for(const d of os.TERRAIN){if(n(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),s);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),s)}if(!n("map")){const d=r("map");jn.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),s):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),s))}const c=this.host.upperAirHeard(),h=r("upperAir");if(!n("upperAir")&&c&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:c.answer.source.name,answers:[c]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:c.answer.source.name},cs.isInline(f)||s.set(f,p)}else h&&!n("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),s))}finally{this.busy=!1}return this.setSnapshots(i),s}async take(e,t,i,s,n){const r=this.groupName(e),a=await jn.freeze(e,this.host.sighting(),i,s,(o,c)=>Ht.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(c))));return Ht.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,n,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Ht.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await jn.freezeMap(this.host.sighting(),t.imagery);return Ht.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=jn.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Ct.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&sr.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const s=this.address(t.src),n=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await Ct.zip(s))["index.json"])).patches:(await Ct.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=Rt.ROADS_MAX_RADIUS_M);return sr.samePatches(n.map(({lat:a,lng:o,radiusM:c})=>({lat:a,lng:o,radiusM:c})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&cs.isInline(t))return cs.dataUrl(e,s);const n=t??os.annexName(i,e);return Ct.hold(this.address(n),s),n}async keep(e,t){if(!cs.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Ht.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Ct.bytes(this.address(e.src))}address(e){return Ct.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of os.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=os.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.snapshotRelief,imagery:this.messages.snapshotImagery,roads:this.messages.snapshotRoads,water:this.messages.snapshotWater,railways:this.messages.snapshotRailways,upperAir:this.messages.snapshotUpperAir,map:this.messages.snapshotMap}[e]}}class Mg{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Ht.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().snapshots?.[e]?.src}itemLabel(e){const t=this.messages;return t?{weather:t.fileItemWeather,place:t.fileItemPlace,lightPollution:t.fileItemLightPollution,decor:t.fileItemDecor}[e]:""}where(e){return this.srcOf(e)??this.messages?.annexStorageInline??""}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Yt.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return t.provenance.at("lightPollution")?.rationale??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().snapshots??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:Yt.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=P0(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:Ol.CURRENT.sighting,takenOn:i,attribution:s,...Yt.taken(e,t)};return new TextEncoder().encode(JSON.stringify(n))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Yt.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().snapshots??{}};o[e]={...o[e]??{},src:t.url},Ht.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await Q(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>AI);return{InputFileElement:h}},void 0,import.meta.url),c=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Oi.toCurrent(JSON.parse(new TextDecoder().decode(c))),typeof i!="object"||i===null||Yt.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...P0(s)};if(e==="decor")Yt.put(e,n,"timeline"in i?Yt.taken(e,i):i);else for(const o of Yt.KEYS[e])n[o]=i[o];const r=Mw(n);Mg.copy(e,r,s);const a={...s.snapshots??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Ht.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().snapshots=os.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of Yt.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class yU{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 s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const wU=Ye.point("timeZone").provide(Ye.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new yU}]),MU=["appearance","movement","incongruity","detection","close","beings","traces"];class J1{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class ms{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=ms.select("observerOccupationKind");graduate=ms.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=ms.select("observersRelation");activity=ms.select("observerActivity");factors=new Map(MU.map(e=>[e,ms.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Jn.register(),e.append(this.label(this.occupationKind,h=>[h.occupationKind,h.occupationKindHint]),this.label(this.graduate,h=>[h.graduate]));const n=this.label(this.enquiryMinutes,h=>[h.enquiryMinutes,h.enquiryMinutesHint]);n.append(this.unit);const r=t.querySelector("#accountSource")?.closest("label");r?r.after(n):t.append(n),t.append(this.label(this.relation,h=>[h.relation]),this.label(this.activity,h=>[h.activity]));const a=Object.assign(document.createElement("h3"),{className:"section-title"});a.append(this.strangenessTitle),i.append(a,this.strangenessIntro,...[...this.factors].map(([h,d])=>this.label(d,u=>[u.factors[h],u.factorHints[h]])));const o=[["yes","yes"],["no","no"]],c=h=>h.map(d=>[d,d]);ms.choices(this.occupationKind,"",c(Object.keys(J1.OCCUPATIONS))),ms.choices(this.graduate,"",o),ms.choices(this.relation,"",c(J1.RELATIONS)),ms.choices(this.activity,"",c(J1.ACTIVITIES));for(const h of this.factors.values())ms.choices(h,"",o);for(const h of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])h.addEventListener("change",s)}set messages(e){this.wording=e;for(const t of this.labels.values())t();this.unit.textContent=` ${e.minutes}`,this.strangenessTitle.textContent=e.strangenessSection,this.strangenessIntro.textContent=e.strangenessIntro,ms.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),ms.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),ms.choices(this.relation,e.unknown,Object.entries(e.relations)),ms.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)ms.choices(i,ms.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=ms.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=ms.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=ms.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:ms.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Jn.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Qm=new Set;Ug();OF();Ed.register();const jh={width:48,height:28},xU=2500,xA=40,SU=10,SA=600,EA=900,Zh=2e-4,EU=900,AU=-1.46,TU=3,Q1=.2,IU=.5,_U=3,DU=.01,kU=1.6,eb=2e3,RU=250,AA=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),CU=1,LU=5,OU=10,gl=4,$u="ufo-1",PU={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function NU(l){return l.kind==="oval"?"oval":"polygon"}const FU=-6,UU=21;class xe extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=wU[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new bU;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;candidatesView;sectionFolds;snapshotsPanel;sectionFilePanel;eventsPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=pU();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;filmStockSelect;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;evaluationFields;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;skyParts=new Map;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 Wu(dU());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;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=new mp;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=ls.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...PU};currentSourceId=$u;selectedSourceIds=new Set([$u]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceVideoFromInput;referenceVideoToInput;referenceVideoRateInput;referenceRemoveKeyButton;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;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(AA.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;AA.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):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(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${yk}</style>${bk}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(M0))a.build();for(const a of this.shadow.querySelectorAll(yg))a.build();for(const a of this.shadow.querySelectorAll(gf))a.build();for(const a of this.shadow.querySelectorAll(E0))a.build();this.sceneElement=document.createElement(vg),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:o,lng:c}=a.detail;this.latInput.value=String(Number(o.toFixed(6))),this.lngInput.value=String(Number(c.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.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.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.timeZoneWarning=this.shadow.getElementById("time-zone-warning"),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.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),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 ep(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.addEventListener("keydown",o=>{o.key!=="Enter"&&o.key!==" "||(o.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(yg),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new XA(this.shadow);const t=this;this.witnessErrorView=new yT({get sighting(){return t.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const o=this.ufoElement.sighting,{conditions:c,...h}=o.account??{},d={...h,...a?{conditions:a}:{}};o.account=Object.values(d).some(u=>u!==void 0)?d:void 0},recordingJson:()=>this.sightingData,lawsChanged:()=>{this.sceneElement.confrontationTolerance=Bi.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new xf(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.resizeScene(this.shadow.getElementById("scene-resize")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new xT(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const o=a.target.id;xe.SCENE_LINKED.includes(o)&&this.setActiveSceneField(o)}),this.shadow.addEventListener("focusout",a=>{const o=a.relatedTarget;(!o||!xe.SCENE_LINKED.includes(o.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),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.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.filmStockSelect=this.shadow.getElementById("filmStock"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),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.evaluationFields=new ms(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),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.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.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.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.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${E0}[name="observer"]`),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.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(xe.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),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.snapshotsPanel=new cs(this.shadow.getElementById("snapshot-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.snapshotSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o)}),this.sectionFilePanel=new Mg(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const o=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=o===void 0?"":String(o),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const o=this.ufoElement.sighting.interpretation?.bodies.find(c=>c.id===a);return this.said.read(o?.title)??a}};this.eventsPanel=new to(this.shadow.getElementById("events-section"),i,void 0),this.phenomenonEventsPanel=new to(this.shadow.getElementById("phenomenon-events-section"),i,void 0,"phenomenon"),this.bodiesEventsPanel=new to(this.shadow.getElementById("bodies-events-section"),i,void 0,"bodies"),this.samplingRateInput.addEventListener("change",()=>{const a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,ht.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),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",a=>{a.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.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.aircraftFlights=new PF(this.shadow.getElementById("aircraft-flights"),a=>this.aimAtFlight(a),a=>this.naming.point(a)),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),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 gn({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),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:"trafficlight",label:"Traffic light"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{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",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new gn({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectObserver(a),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),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 dn(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,o)=>this.sceneElement.setBusy(a,o),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},this.messages,async(a,o)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,o)?this.surroundingsProvider:void 0:(await Q(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources-DXpzMDPy.js");return{SurroundingsSources:c}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,o),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const a=this.scenerySource.value===xe.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===xe.NO_SCENERY){this.surroundings.withdraw();return}const o=this.plantingCentre();o&&this.surroundings.survey(o.lat,o.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const o=this.plantingCentre();this.surroundings.radiusChanged(a,o?.lat,o?.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.referenceSourceInput=this.shadow.getElementById("reference-source"),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.referenceVideoFromInput=this.shadow.getElementById("referenceVideoFrom"),this.referenceVideoToInput=this.shadow.getElementById("referenceVideoTo"),this.referenceVideoRateInput=this.shadow.getElementById("referenceVideoRate"),this.referenceRemoveKeyButton=this.shadow.getElementById("reference-remove-key"),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.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Yp(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),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.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),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.traceImportInput=this.shadow.getElementById("trace-import"),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.addTraceButton=this.shadow.getElementById("add-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.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceVideoFromInput,this.referenceVideoToInput,this.referenceVideoRateInput,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 xp(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 ga(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new ga(this.decorBaseHost,"en","decorBase.",s,(a,o)=>this.enhanceDecorModelChoice(a,o)),this.decorStateForm=new ga(this.decorStateHost,"en","decorState.",s),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",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const o=n;n=void 0,!(!o?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-o.x,a.clientY-o.y)>xe.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),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.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",a=>{const o=a.detail;o.file?this.importFromFile(o.file):this.importFromUrl(o.url)}),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()});for(const a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.type==="checkbox"?"change":"input",()=>this.updateLens());this.lightPollutionInput.addEventListener("input",()=>{const a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",a=>{const{seconds:o,text:c}=a.detail;this.ufoElement.sighting.event.durationText=c,this.ufoElement.durationSeconds=o,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((o??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.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),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.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 a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.detail)),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.addTraceButton.addEventListener("click",()=>{const a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.detail)),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",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{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 a of[this.milestoneLabelInput,this.milestoneNoteInput])a.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(xI,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(MI,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(wI,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(yI,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncVideoRegistrationFields(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Yp(this.addShapeButton,"add-shape-kind",a=>{const o=Co.byId(a);if(o){this.addModel(o);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),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 a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.filmStockSelect.addEventListener("change",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const o=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(o,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.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 a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const o=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(c=>[c.t,Ti.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Ti.reproject(this.ufoElement.sighting,a,o),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.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const r=a=>this.shadow.querySelector(`${M0}[name="${a}"]`);this.startDate=r("obs-time"),this.endDate=r("obs-end-time"),this.birthDate=r("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=ya.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=o}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=o})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(xe.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));this.buildSkyParts(),fn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),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=C5(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,o)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},jd(yr.preferencesFor(this),qd),this.framePlace()),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.ready=this.loadLocaleMessages())}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),yr.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=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),Ye.changes.addEventListener("change",this.onModulesChanged),Q(async()=>{const{ModuleSession:t}=await import("./ModuleSession-BXk5ijvF.js");return{ModuleSession:t}},[],import.meta.url).then(({ModuleSession:t})=>t.shared.start(),()=>{});const e=this.getAttribute("src");e&&this.importFromUrl(e)}relisters=[];onModulesChanged=e=>{for(const i of this.relisters)i();const t=e.detail;t==="weather"&&(this.followWeatherRecord(),this.fillWeatherProvider()),t==="surroundings"&&this.surveyIds&&this.fillScenerySources(),t==="decorModels"&&this.sceneElement.setDecorModelProvider(this.decorModelProvider),(t==="skyEvents"||t==="interpretations")&&this.buildSkyParts(),t==="perception"&&(this.perceptionSettings.providers=ya.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),Ye.changes.removeEventListener("change",this.onModulesChanged),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),clearTimeout(this.moduleNamingTimer),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){const t=Oi.toCurrent(e);this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=t,this.sceneElement.requireModules(t.modules),this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncModulesPanel(),this.syncBodiesShown(),this.isGroupIdOpen("group-shape")&&this.showPhenomenonPartWithContent(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??$u,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.placeZone=void 0,this.timeZoneLookedUpAt=void 0,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.scheduleTimeZoneLookup(!1);const i=this.plantingCentre();this.surroundings.placeLoaded(i?.lat,i?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.snapshotsPanel.render(),this.refreshFileItems(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${Yd.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.scheduleModuleNaming(),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(),this.refreshEditorHead())}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(),this.refreshEditorHead())}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=this.shadow.getElementById("save-refused"),t=Vt.issues(this.ufoElement.sighting);if(Ht.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=rs.inspect(this.sightingData,this.loadedJson());if(i.length===0){this.downloadJson();return}this.askAboutIdentity(i)}actorIssue(e){const t=this.messages;if(e.kind==="duplicate-id")return t.duplicateId.replace("{id}",e.id).replace("{kinds}",e.path.split(", ").map(n=>t.actorKinds[n]??n).join(", "));const i=Number(e.path.split(".")[1]),s=this.ufoElement.sighting.events?.[i];return t.unknownWho.replace("{n}",String(i+1)).replace("{kind}",(s&&t.events.kinds[s.eventType])??s?.eventType??"").replace("{id}",e.id)}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(n=>{const r=document.createElement("li");return r.textContent=t[n.kind].replaceAll("{value}",n.found),r}));const s=e.some(n=>["lastName","firstNames","nameInId","nameInText"].includes(n.kind));this.shadow.getElementById("identity-ask-initials").hidden=!s,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=rs.namesOf(this.sightingData);this.observerLastNameInput.value=rs.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>rs.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=rs.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=rs.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=rs.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.snapshotsPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.snapshotsPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Yt.NAMES){const a=this.sectionFilePanel.annex(r);a&&(/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes),Yt.strip(r,i))}const s=`${e}.json`,n=this.writtenText(i);if(t.size===0)this.download(new Blob([n],{type:"application/json"}),s);else{const{zipSync:r,strToU8:a}=await Q(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-_Ncw3Jhn.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[s]:a(n)};for(const[h,d]of t)o[h]=d;const c=r(o,{level:0});this.download(new Blob([c],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",cs.size(c.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e||!this.worded)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Yt.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...os.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,xe.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=os.NAMES.includes(e),i=Yt.NAMES.includes(e)?e:void 0,s=e===xe.MODULES_ITEM;this.shadow.getElementById("file-recording").hidden=t||i!==void 0||s,this.shadow.getElementById("snapshot-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0,this.shadow.getElementById("file-modules").hidden=!s,s&&this.loadModulesPanel();for(const r of["file-recording","snapshot-data","file-section","file-modules"]){const a=this.shadow.getElementById(r);a.hidden||gn.glue(a)}t&&this.snapshotsPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.snapshotsPanel.isInlineGroup(e)?["snapshots",e,"src"]:i&&this.sectionFilePanel.isInline(i)?Mg.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0||s)&&n===void 0,n&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(r=>{this.syncFileEditor(!1),r.reveal(n)},()=>{})}moduleNamingTimer;scheduleModuleNaming(){clearTimeout(this.moduleNamingTimer),this.moduleNamingTimer=setTimeout(()=>void this.nameModulesOfModels(),400)}async nameModulesOfModels(){const e=this.decorModelProvider;if(!(e instanceof mp)||Ye.installed().length===0)return;const t=this.ufoElement.sighting,i=new Set([...t.decor.map(r=>r.model?.id),...(t.interpretation?.bodies??[]).map(r=>r.model?.id)].filter(r=>typeof r=="string")),s=this.sceneElement.documentUrl;let n=t.modules;for(const r of i){const a=await e.moduleOf(r),o=a===void 0?void 0:Ye.installed().find(c=>c.id===a)?.url;!o||MA.names(n,o,s)||(n=[...n??[],MA.of(o,s)])}n===t.modules||this.ufoElement.sighting!==t||(t.modules=n,this.syncModulesPanel(),this.syncFileEditor(!1))}static MODULES_ITEM="modules";modulesPanel;modulesPanelLoading;loadModulesPanel(){return this.modulesPanelLoading??=Q(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-B1KHXTpq.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([25,26]),import.meta.url).then(({register:e,ModulesPanelElement:t})=>{e();const i=this.shadow.getElementById("modules-panel");this.modulesPanel=i,i.addEventListener("recordingmoduleschange",()=>{const s=i.recordingModules;this.ufoElement.sighting.modules=s.length>0?s:void 0,this.syncFileEditor(!1)}),i.checkContext=()=>({weatherQuery:this.weatherInference.queryOf(this.ufoElement.sighting),interpretation:this.ufoElement.sighting.interpretation}),i.setLanguage(this.language),this.syncModulesPanel()}),this.modulesPanelLoading}syncModulesPanel(){this.modulesPanel&&(this.modulesPanel.base=this.sceneElement.documentUrl,this.modulesPanel.recordingModules=this.ufoElement.sighting.modules)}sectionFromFile(e){return Yt.fromFile(this.ufoElement.sighting.snapshots,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}snapshotSources(){const e=zi(Km,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:zi(qc,this.chosenSourceId.get("imagery")).id,roads:KT(),water:XT(),railways:YT()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){this.showLoadError(void 0);try{const t=new Uint8Array(await new Promise((n,r)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));Ct.release();const i=await this.recordingText(t),s=JSON.parse(i);if(Vi.isCase(s)){if(Vi.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.resetHistory(),this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){this.showLoadError(t)}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await Q(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),s=t(e),n=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather|place|light-pollution|decor)\.json$/,r=Object.keys(s).find(d=>d.endsWith(".json")&&!n.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(s))d!==r&&d.startsWith(a)&&Ct.hold(Ct.address(d.slice(a.length),void 0),u);const o=i(s[r]),c=JSON.parse(o);let h=!1;for(const d of Yt.NAMES){const u=c.snapshots?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=Oi.toCurrent(JSON.parse(i(p)));Yt.put(d,c,f),h=!0}return h?JSON.stringify(c):o}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.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){this.showLoadError(void 0);try{const t=await Ma.recording(e);if(Vi.isCase(t)){Vi.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;Ct.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=new URL(e,location.href).href,this.resetHistory(),this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){this.showLoadError(t)}}loadError;showLoadError(e){this.loadError=e===void 0?void 0:{error:e},this.sayLoadError()}sayLoadError(){Ht.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Sp)return e.said(this.messages.formatVersionError);if(!(e instanceof Sc))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=Nf[0].create();get narrativeSourceId(){return zi(Nf,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:xe.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof Ir&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,a=Ba.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,c=Tb(this.ufoElement.sighting);this.sightingData=Ba.apply(c,O0.loadable(r),a),this.ufoElement.sighting.provenance=o,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,s=new Set(t);for(const n of e.claims)!s.has(n.path)&&!t.some(r=>n.path.startsWith(`${r}.`))||i.provenance.set(n.path,{basis:n.basis,rationale:n.rationale,of:xe.valueAt(Tb(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[BU[t]]));for(const s of i){const n=document.createElement("div");n.className=`claim ${t}`;const r=document.createElement("code");r.textContent=s.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=s.rationale,n.append(r,a),this.narrativeReport.append(n)}}}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 s=document.createElement("li");s.textContent=i,t.append(s)}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=zi(Nf,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(s=>s.required&&(this.narrativeSettingInputs.get(s.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:"";for(const s of this.narrativeProvider.settings){const n=this.narrativeSettingInputs.get(s.id);if(!n||!s.suspect)continue;const r=n.value.trim(),a=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",a!==void 0),n.title=a?this.said.read(a)??"":this.said.read(s.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const s=document.createElement("label"),n=document.createElement("span");n.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const c=document.createElement("option");c.value=o.value,c.textContent=this.said.read(o.label)??o.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),s.append(n,document.createTextNode(" "),r),s});this.narrativeSettingsBox.replaceChildren(...t),this.forgetStoredCredentials(),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const s=i.value.trim();s!==""&&(e[t]=s)}return e}narrativeErrorFor(e){if(!(e instanceof Ir))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}}static pageCredentials=new Map;static forgetCredentials(){xe.pageCredentials.clear(),$o.forget()}rememberNarrativeSettings(){for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";if(e.remembered==="credential")i!==""?xe.pageCredentials.set(t,i):xe.pageCredentials.delete(t);else if(e.remembered==="preference")try{i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}catch{}}}forgetStoredCredentials(){try{for(const e of this.narrativeProvider.settings)e.remembered==="credential"&&localStorage.removeItem(this.narrativeStorageKey(e.id));localStorage.removeItem(xe.NARRATIVE_KEY_STORAGE),localStorage.removeItem(xe.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){const t=this.narrativeStorageKey(e),i=this.narrativeProvider.settings.find(s=>s.id===e);if(i?.remembered==="credential")return xe.pageCredentials.get(t);if(i?.remembered==="preference")try{return localStorage.getItem(t)??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.relisters.length=0,this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(Z1,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.snapshotUpperAir,this.sourcePicker("upper-air",vU,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(qm,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",Nf,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",Z1,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",qm,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",Km,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",qc,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[xe.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[xe.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[xe.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.shadow.getElementById("label-aircraft-source").textContent=this.messages.sourceAircraft,this.shadow.getElementById("aircraft-source-row").replaceChildren(this.aircraftPicker()),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",Oy,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;const a=()=>{r.replaceChildren(...t.map(v=>{const g=document.createElement("option");return g.value=v.id,g.textContent=v.name,g.title=v.credit,g})),s&&r.appendChild(new Option(this.messages.sourceFile,xe.FILE_SOURCE))};a();const o=()=>{const v=this.chosenSourceId.get(e);return v!==void 0&&t.some(g=>g.id===v)?v:t[0].id};r.value=s?.fromFile()?xe.FILE_SOURCE:o();const c=document.createElement("a");c.className="source-credit",c.target="_blank",c.rel="noopener noreferrer";const h=document.createElement("button");h.type="button",h.className="link source-file-link",h.addEventListener("click",()=>this.openFileItem(s.item));const d=document.createElement("label");d.className="source-key";const u=document.createElement("input");u.type="password",u.id=`${e}SourceKey`,u.autocomplete="off",u.spellcheck=!1,u.title=this.messages.sourceKeyHint;const p=document.createElement("a");p.className="source-credit",p.target="_blank",p.rel="noopener noreferrer",p.textContent=this.messages.sourceKeyGet,d.append(document.createTextNode(`${this.messages.sourceKey} `),u,document.createTextNode(" "),p),u.addEventListener("change",()=>{const v=zi(t,r.value);$o.set(v.id,u.value),i(v,!0)});const f=()=>{const v=r.value===xe.FILE_SOURCE,g=zi(t,v?o():r.value);d.hidden=v||!g.keyUrl,p.href=g.keyUrl??"",u.value=$o.of(g.id)??"",r.title=v?s.where():g.credit,c.hidden=v,c.href=g.creditUrl,c.textContent=g.credit,h.hidden=!v,v&&(h.textContent=s.label(),h.title=s.where())};f(),r.addEventListener("change",()=>{const v=r.value===xe.FILE_SOURCE;v||this.chosenSourceId.set(e,r.value),s?.setFromFile(v),f(),v||i(zi(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?xe.FILE_SOURCE:o(),f()});const m=()=>{const v=r.value,g=this.chosenSourceId.has(e)&&!t.some(b=>b.id===this.chosenSourceId.get(e));g&&this.chosenSourceId.delete(e),a(),r.value=v===xe.FILE_SOURCE&&s?v:o(),f(),g&&r.value!==xe.FILE_SOURCE&&i(zi(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),c,h,d),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Xy,(t,i)=>this.applyAircraftSource(i));return e.append(this.aircraftStatus),this.showAircraftStatus(),e}get aircraftTabOpen(){return this.isGroupIdOpen("group-weather")&&this.shadow.getElementById("weather-aircraft")?.hidden===!1}showAircraftFlights(){if(this.aircraftTabOpen){if(this.ufoElement.playbackState==="playing"){const e=performance.now();if(e-this.aircraftFlightsShownAt<1e3)return;this.aircraftFlightsShownAt=e}this.aircraftFlights.show(this.sceneElement.aircraftFlights,this.messages)}}aimAtFlight(e){if(e.key===this.aircraftFlights.selectedKey){this.aircraftFlights.select(void 0,this.messages),this.sceneElement.markFlight(void 0);return}if(!e.sky&&e.firstMs===void 0)return;const t=e.sky?this.ufoElement.currentTime:e.firstMs;e.sky||this.goToMark(t),this.sceneElement.lookAtFlight(e.key,t),this.aircraftFlights.select(e.key,this.messages),this.sceneElement.markFlight(e.key),this.showAircraftFlights()}showAircraftStatus(){this.showAircraftFlights();const{status:e,problem:t,partial:i,creditsSpent:s,total:n}=this.sceneElement.aircraftState,r=[];e==="loading"&&r.push(this.messages.aircraftLoading),e==="outside"&&r.push(this.messages.aircraftOutside),e==="unavailable"&&!t&&r.push(this.messages.aircraftProblems.network),e==="ready"&&n===0&&r.push(this.messages.aircraftNone),i&&r.push(this.messages.aircraftPartial.replace("{traced}",String(i.traced)).replace("{seen}",`${i.seen}${i.moreSeen?"+":""}`).replace("{km}",String(i.withinKm))),s&&r.push(this.messages.aircraftCredits.replace("{credits}",String(s))),t?Ht.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):Ht.show(this.aircraftStatus,r.length>0?r.join(" "):void 0,"info")}groupChoice(e){return{item:e[0],fromFile:()=>!this.snapshotsPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.snapshotsPanel.setLive(i,!t)},label:()=>this.snapshotsPanel.itemLabel(e[0]),where:()=>this.snapshotsPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.snapshots??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.snapshots=os.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=xe.LIVE_ROADS;static LIVE_RAILWAYS=xe.LIVE_ROADS;sourcePickers(e,t,i,s){const n=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=s.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??s[0][0];const c=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",c),c(),n.append(r,document.createTextNode(" "),a),e.replaceChildren(n,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(Z1,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(qm,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:zi(Km,this.chosenSourceId.get("elevation")).create(),imagery:zi(qc,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(zi(Xy,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new mp(zi(Oy,this.chosenSourceId.get("decor-model")).id),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===""||this.sectionFromFile("place"))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||this.sectionFromFile("place"))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)<Zh&&Math.abs(t-this.namedCoordinates.lng)<Zh||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),EA))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(e=!0){const t=this.numberOrUndefined(this.latInput.value),i=this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const s=this.timeZoneLookedUpAt;s&&Math.abs(t-s.lat)<Zh&&Math.abs(i-s.lng)<Zh||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),EA))}async lookUpTimeZone(e,t,i){const s={lat:e,lng:t};this.timeZoneLookedUpAt=s;const n=await this.timeZoneProvider.zoneAt(e,t);if(this.timeZoneLookedUpAt===s){if(this.placeZone=n??void 0,!n||!i||this.timeZoneIsStated()||!this.timeZones.available().includes(n)){this.timeZoneSelect.value=this.zoneShown(),this.updateUtcOffsetValidity();return}this.autoFilledTimeZone=n,this.timeZoneSelect.value=n,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange"))}}async reversePlace(e,t){const i=++this.placeSearchToken;let s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=s?.name??"",this.placeNameInput.title=s?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=s?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!s;const n=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:n.lat,lng:n.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}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),s=this.numberOrUndefined(this.pitchInput.value)??0,n=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Qt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),m=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,g=ji.byId(c.getLatestPoseAt(h-1)?.filter),b=v===ji.NONE.id||v===""?g===ji.NONE?void 0:ji.NONE.id:v,w=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=w===u.exposureSeconds?void 0:w;const y=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(f-Qt.fieldOfViewDeg(u))>.01||m!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&a===0&&!M?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:f,fNumber:m,focusDistanceM:y,filter:b});const E=this.plantingCentre();this.surroundings.placeChanged(E?.lat,E?.lng),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&&!Ym.isFirm(t))return;const s=Ym.at(t,i);s!==void 0&&(this.observerAgeInput.value=String(s),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&&Ym.at(i,e)===t)return;const s=Ym.birthFor(t,e);s&&(this.birthDate.setPrecise(!1),this.birth=s,this.birthDate.time=s,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&&Qc({...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(s=>{const n=document.createElement("option");return n.value=s,n.textContent=s,n})),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.zoneKnownToRead(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){return this.zoneKnownToRead(e)??this.timeZones.zonesAt(e,this.timeZoneReference())[0]}zoneKnownToRead(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference()),i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const s=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return s&&t.includes(s)?s:void 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.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0},s=Vt.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Vt.renamed(e,s,Vt.observerId(e)),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:ya.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",...this.evaluationFields.values(),conditions:e.account?.conditions};e.account=Object.values(i).some(s=>s!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...s]=e.sources??[],{url:n,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...s]:s;e.sources=o.length>0?o: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()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...ys(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={...ys(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(s=>s.id===this.currentReferenceId),t=e!==void 0;gn.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",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.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.syncVideoFields(e),this.showRegistration(this.registrationShown(e)),this.syncReferenceStatus(e)}syncVideoFields(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.referenceVideoFromInput.value=e.video?.fromS===void 0?"":String(e.video.fromS),this.referenceVideoToInput.value=e.video?.toS===void 0?"":String(e.video.toS),this.referenceVideoRateInput.value=e.video?.rate===void 0?"":String(e.video.rate),this.syncReferenceKeyButton(e)}syncReferenceKeyButton(e){this.referenceRemoveKeyButton.hidden=e.kind!=="video"||as.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=as.registrationAt(e,this.ufoElement.currentTime);return{headingDeg:this.rounded(t),pitchDeg:this.rounded(i),rollDeg:s===void 0?void 0:this.rounded(s),fovDeg:this.rounded(n)}}showRegistration({headingDeg:e,pitchDeg:t,rollDeg:i,fovDeg:s}){this.referenceHeadingInput.value=String(e),this.referencePitchInput.value=String(t),this.referenceRollInput.value=String(i??0),this.referenceFovInput.value=String(s)}syncVideoRegistrationFields(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);e?.kind==="video"&&(this.syncReferenceKeyButton(e),e.registrationTrack?.length&&this.showRegistration(this.registrationShown(e)))}removeReferenceKey(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId);if(!e)return;const t=as.withoutKey(e,this.ufoElement.currentTime);this.ufoElement.sighting.references=this.ufoElement.sighting.references.map(i=>i===e?t:i),this.syncReferenceFields(),this.ufoElement.refresh()}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Ht.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>jF?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;case"notVideo":return this.messages.referenceNotVideo;default:return 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(n=>{if(n.id!==this.currentReferenceId)return n;const r=n.src,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)||jm))},o=this.registrationShown(n),c=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg,h=this.referenceKindSelect.value;return h==="video"?{...c?as.withKey(n,this.ufoElement.currentTime,a):n,kind:h,src:r,title:this.said.write(n.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),video:this.videoClipOfFields(),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),from:void 0}:{...n,kind:h,video:void 0,registrationTrack:void 0,src:r,title:this.said.write(n.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()??n.from:n.from}});const s=e.references.find(n=>n.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(s),this.syncVideoFieldsKeepingInput(s),this.syncReferenceStatus(s),this.ufoElement.refresh()}videoClipOfFields(){const e={fromS:this.numberOrUndefined(this.referenceVideoFromInput.value),toS:this.numberOrUndefined(this.referenceVideoToInput.value),rate:this.numberOrUndefined(this.referenceVideoRateInput.value)};return e.fromS===void 0&&e.toS===void 0&&e.rate===void 0?void 0:e}syncVideoFieldsKeepingInput(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.syncReferenceKeyButton(e)}useObserverPoseForReference(){const e=tt(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(as.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=tt(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 s=this.ufoElement.sighting,n=tt(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:qF,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:jm},from:this.observerPositionNow(),...i};s.references=[...s.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const r=e.file;i=await new Promise((a,o)=>{const c=new FileReader;c.onload=()=>a(c.result),c.onerror=()=>o(c.error),c.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=as.kindOfSource(e.file?{type:e.file.type}:{url:e.url});s.references=s.references.map(r=>r.id!==t?r:{...r,src:i,kind:n==="video"||n==="photo"&&r.kind==="video"?n:r.kind,from:n==="video"?void 0:r.from,title:r.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=Q(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-ZyvGfReK.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);return e?.registrationTrack?.length?{...e,registration:as.registrationAt(e,this.ufoElement.currentTime)}:e}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 s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==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.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=s)return{landmarkId:n.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 s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===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:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,s.registration,n);return o?{...a,picture:o}: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)||jm,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.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const s=this.currentLandmarks(),n=this.nextLandmarkId(s);this.writeLandmarks([...s,{id:n,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=n,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.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),s=this.pictureRegistration.solve(i,t,e.registration.fovDeg);s?(this.referenceFit={n:i.length,residualDeg:s.residualDeg},this.referenceHeadingInput.value=String(this.rounded(s.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(s.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(s.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(s.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.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.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[n,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,n)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(n=>n.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const s=t.find(n=>n.id===this.currentLandmarkId);gn.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.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(),s=i.findIndex(a=>a.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const a=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+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.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,s,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,s,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(n.every(a=>a!==void 0)?n:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const s=this.ghostFinding;if(!s||!this.ghostsShown||s.referenceId!==t.id||s.src!==t.src)return;const{search:n}=s,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/n.width,v:d.y/n.height},r,i)),o=[];for(const d of n.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const c=n.centre?a(n.centre):void 0,h=n.cropped?a({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(o,c,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:s}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(as.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===n);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)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[c,h]of o)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.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const s=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...s?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=tt(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 s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await Q(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,s)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const n=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!n,this.referenceStreetAddButton.hidden=!n,this.referenceStatus.textContent=n?"":this.messages.referenceStreetNone.replace("{m}",String(s))}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:jm}})}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;gn.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!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(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{KmlImport:h}=await Q(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url);i=await h.fromBytes(await lM.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const s=this.ufoElement.sighting,n=new Set(s.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;n.has(`trace-${r}`);)r++;const d=`trace-${r}`;return n.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});s.traces=[...s.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const c=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+c,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 s_){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(),xU)}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=sw(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 Wu(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===xe.FILE_SOURCE;if(!e){const t=zi(La,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new Wu(t.create()),this.scheduleWeatherLookup(!0),this.syncWeatherProvider())}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Yt.fromFile(t.snapshots,"weather")===e)return;const i={...t.snapshots??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.snapshots=os.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=La.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==zi(La,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new Wu(e.create())}else!e&&t!==void 0&&!La.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new Wu(zi(La,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...La.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,xe.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!Jm(t)?t:void 0;if(this.weatherProviderSelect.querySelector("option[data-stated]")?.remove(),i){const r=new Option(i.name??i.id,i.id);r.dataset.stated="",this.weatherProviderSelect.add(r,this.weatherProviderSelect.options.length-1)}this.weatherProviderSelect.value=e?xe.FILE_SOURCE:i?i.id:zi(La,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=zi(La,this.chosenSourceId.get("weather")),n=this.shadow.getElementById("weather-credit");n.hidden=e||i!==void 0,n.href=s.creditUrl,n.textContent=s.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(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&&!Jm(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),SA))}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||!Jm(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=this.fieldHints.get(a.id)??"");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&Jm(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 s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=[e.name,this.observationInstantLabel()].filter(Boolean).join(", ");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&&mn(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.followWeatherRecord(),this.weatherFromRecords=!Yt.fromFile(e.snapshots,"weather")&&(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=qm[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;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(),SA)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,s=this.lightPollutionProvider,n=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||n===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(n<s.year){r(),this.lightPollutionLookup={status:"too-early",year:n},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await s.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:`${s.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=Qc(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=r5(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;we.show(this.playPauseButton,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[s,n]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])s.title=n,s.setAttribute("aria-label",n);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,s]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${s} — ${t}`:s,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(sn.opensPrecise(e.time)),this.endDate.setPrecise(sn.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),s=e!==void 0&&i!==void 0&&Math.abs(e-i)>TU;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):"",this.showTimeZoneConsistency(s)}showTimeZoneConsistency(e){const t=this.ufoElement.sighting.event,i=this.placeZone&&t.time?.year!==void 0?this.timeZones.offsetHoursAt(this.placeZone,t.time):void 0,s=t.utcOffsetHours??(t.timeZone?this.timeZones.offsetHoursAt(t.timeZone,this.timeZoneReference()):void 0),n=i!==void 0&&s!==void 0&&s!==i;this.timeZoneSelect.classList.toggle("inconsistent",n&&this.timeZoneSelect.value!==""),this.utcOffsetInput.classList.toggle("inconsistent",n&&!e),this.timeZoneWarning.hidden=!n,this.timeZoneWarning.textContent=n?this.messages.utcOffsetInconsistent.replace("{zone}",this.placeZone).replace("{offset}",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),EU))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Zh&&Math.abs(e.lng-i)<Zh}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=zi(Km,this.chosenSourceId.get("elevation")),n=await new cM(s.create()).at(e,t);if(i!==this.groundElevationToken||n===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(n),this.syncElevationField(r)}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||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(tt(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(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(xe.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(sn.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.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=ys(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??y0)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??CA)),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],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==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.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,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{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 s=xM(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,s]of this.groupTabs.entries()){const n=s===e&&t;s.setAttribute("aria-expanded",String(n)),this.groupPanels[i].hidden=!n}if(t){const i=e.parentElement.getBoundingClientRect(),s=e.getBoundingClientRect();(s.left<i.left||s.right>i.right)&&(e.parentElement.scrollLeft+=s.left-i.left-(i.width-s.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==xe.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-shape"&&this.showPhenomenonPartWithContent(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await Q(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-bXm0nVE4.js");return{SightingFileEditor:t}},__vite__mapDeps([23,3,24]),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 s=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(s!==void 0){this.fileFocus="shape",this.selectUnit(s.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(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){Ht.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of Yt.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&Yt.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of Yt.NAMES){const n=Yt.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||Yt.put(s,e,Yt.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return wx.of(e,t,t==="thin"?Ti.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(xe.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(xe.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Mw(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=wx.of(this.ownJson(P0(e)),t,t==="thin"?Ti.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}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){if(t.edited)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))return;const s=JSON.stringify(i.weatherTrack);if(i=this.withAnnexed(i),!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,r=!t&&this.fileTextApplied!==void 0&&s!==JSON.stringify(xe.weatherOf(this.fileTextApplied)),a={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,r&&!this.restoringWeather&&this.weatherFromRecords){const o=this.ufoElement.sighting.weatherSource;o===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):La.some(c=>c.id===o.id)&&this.askAboutWeather(a,o.name??o.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(o){this.showFileNote(o instanceof Sp?o.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),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))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,s=this.ufoElement.currentTime,n=this.ufoElement.canvasElement,r=this.messages,a=c=>this.numberOrUndefined(c.value),o=(c,h=1)=>c===void 0?"?":c.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch"){const c=a(this.pitchInput)??0,h=br.of(i.instrument,n.height,Ti.fovOf(i,s)),d=Math.sign(c)*h.angleDegToRadiusPx(Math.min(89,Math.abs(c))),u=Math.min(1,Math.max(0,(n.height/2+d)/n.height));e.horizon(u,r.overlayHorizon.replaceAll("{deg}",o(c)))}else if(t==="focalLength"){const c=Ti.fovOf(i,s),d=2*br.of(i.instrument,n.height,c).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",o(c)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const c=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!c){e.hide();return}const h=c.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/n.width,(h.y+h.height/2)/n.height,Math.max(h.width,h.height)*1.3/n.width,u)}else if(t==="windDirection"||t==="windSpeed"){const c=a(this.windDirectionInput)??0,h=c-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(c)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,s=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:s.closest("label"),input:s,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const n=c=>{let h=-1;return c.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&c.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const c=n(t().observerTrack.allKeyframes.map(h=>h.t));return c===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${c}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const c=t().timeline.allKeyframes,h=n(c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=c.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=c=>c?.closest("label")??void 0;this.candidatesView=new Tn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const c=this.ufoElement.sighting.event,h=c.place?.[0];if(!h||c.time?.year===void 0||c.time.hour===void 0)return;const d=mn(c.time,h.lng,c.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:c=>$a(c,this.instrumentGain()),fieldLabels:()=>({time:o(s),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:c=>{const h=`${c}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:jl.load(c,this.language,d=>Ma.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const c=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(c);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const c=this.ufoElement.sighting.interpretation;return[...c&&c.bodies.length>0?[{id:"own",label:this.said.read(c.title)??this.principalObserverLabel(),interpretation:c}]:[],...this.readings]},starName:c=>this.naming.star({name:c}),projectionAt:(c,h)=>this.sceneElement.bodyProjectionAt(c,h),variants:()=>this.ufoElement.sighting.variants,keep:c=>this.editVariants(h=>[...h,c]),remove:c=>this.editVariants(h=>h.filter((d,u)=>u!==c))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=mn(i.time,s.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=Hi("Sun",h,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=ys(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const h=n.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:n.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=n.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(g,b)=>{const w=Math.PI/180,y=Math.sin(g.altitudeDeg*w)*Math.sin(b.altitudeDeg*w)+Math.cos(g.altitudeDeg*w)*Math.cos(b.altitudeDeg*w)*Math.cos((g.azimuthDeg-b.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,y)))/w},f=d.slice(1).map((g,b)=>({deg:p(d[b].shape.aim,g.shape.aim),s:(g.t-d[b].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const v=(d[d.length-1].t-d[0].t)/1e3;if(v>0){t.speedDegPerS=m/v;const g=Math.max(...f.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const a=new Set(n.sourceIds.map(h=>n.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>n.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const v of d)Math.hypot(m.x-v.x,m.y-v.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,v]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const c=new Set([...a].map(h=>n.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return c.size>0&&(t.colors=[...c]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(xe.SCENE_HEIGHT_KEY):localStorage.setItem(xe.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(xe.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,a=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const o=h=>s(a+h.clientY-r),c=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",c),e.removeEventListener("pointercancel",c)};e.addEventListener("pointermove",o),e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=a=>{const o=this.groupTabs.find(c=>c.getAttribute("aria-controls")===a);o&&this.toggleGroup(o,!0)},s=a=>()=>{this.touch(),this.armHistory(),a(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},r=[this.showsBodies?{id:"bodies",label:t.bodiesTrack,color:"#f5c451",...this.eventMarks("bodies"),open:()=>this.chooseAccountView(!0),selected:this.pickedEvent(this.bodiesEventsPanel),select:a=>this.pickEvent(Number(a)),add:()=>this.bodyEditor?s(()=>this.bodyEditor.keyframeHere())():this.chooseAccountView(!0)}:{id:"shapes",label:t.shapesTrack,color:"#f5c451",...this.eventMarks("phenomenon"),open:()=>this.revealShapePanel(),selected:this.pickedEvent(this.phenomenonEventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",...this.eventMarks("observer"),open:()=>i("group-location"),selected:this.pickedEvent(this.eventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(a=>a.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(a=>a.t),open:()=>i("group-sound"),add:s(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(r,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}eventMarks(e){const t=this.ufoElement.sighting;if(e==="bodies")return this.bodyMarks();const i=e==="observer"?ht.observerTrackIsExpanded(t):ht.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(h=>h.t)};const n=this.ufoElement.seekableDuration,r=h=>e==="observer"?Vt.isObserver(t,h):Vt.isPhenomenon(t,h),a=(t.events??[]).map((h,d)=>({event:h,index:d})).filter(({event:h})=>r(h)),o=new Set(a.map(({event:h})=>h.who)).size>1,c=a.map(({event:h,index:d})=>{const u=this.messages.events.kinds[h.eventType]??h.eventType;return{id:String(d),t:h.t,until:h.until??n,label:e==="phenomenon"&&o?`${this.shapesLabel(h.who??"")} · ${u}`:u}});return{times:[],spans:c}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(o=>o.id)),s=o=>Vt.partOf(o)?.element??o??"",n=(e.events??[]).map((o,c)=>({event:o,index:c})).filter(({event:o})=>i.has(s(o.who)));if(n.length===0||!ht.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(o=>o.track.map(c=>c.t)))].sort((o,c)=>o-c)};const r=this.ufoElement.seekableDuration,a=n.map(({event:o,index:c})=>{const h=t.find(f=>f.id===s(o.who)),d=Vt.partOf(o.who)?.part,u=this.messages.events.kinds[o.eventType]??o.eventType,p=[...t.length>1?[this.said.read(h?.title)??s(o.who)]:[],...d?[d]:[]];return{id:String(c),t:o.t,until:o.until??r,label:[...p,u].join(" · ")}});return{times:[],spans:a}}pickedEvent(e){const t=e?.pickedIndex,i=e===this.eventsPanel?"events-section":e===this.phenomenonEventsPanel?"phenomenon-events-section":"bodies-events-section",s=this.shadow.getElementById(i);return t===void 0||!s||s.closest("[hidden]")?void 0:String(t)}pickEvent(e){const t=this.ufoElement.sighting,i=t.events?.[e];if(!i)return;const s=i.who??Vt.observerId(t);if(Vt.isObserver(t,i)){const n=this.groupTabs.find(r=>r.getAttribute("aria-controls")==="group-location");n&&this.toggleGroup(n,!0),this.eventsPanel.pick(e)}else Vt.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Vt.partOf(s)?.element??s),this.bodiesEventsPanel.pick(e),this.refreshTracks()}));this.goToMark(i.t),this.refreshTracks()}shapesLabel(e){const t=this.ufoElement.sighting,i=t.timeline.groupOf(e);if(i)return this.said.read(i.title)??e;const s=t.timeline.allKeyframes.map(n=>n.shapes.find(r=>r.sourceId===e)?.shape.title).find(n=>n!==void 0);return this.said.read(s)??e}get showsBodies(){return this.accountViewSelect.value==="bodies"}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>{if(this.showsBodies){const h=this.eventMarks("bodies");return h.spans?h.spans.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.bodiesTrack,h.times)}const{spans:c}=this.eventMarks("phenomenon");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(h=>!o||h.shapes.some(d=>this.selectedSourceIds.has(d.sourceId))).map(h=>h.t))},s=()=>{const{times:o,spans:c}=this.eventMarks("observer");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.observerTrack,o)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?s():this.isGroupIdOpen("group-weather")?n():this.isGroupIdOpen("group-sound")?r():[...i(!1),...s(),...n(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.eventsPanel?.sync(),this.phenomenonEventsPanel?.sync(),this.bodiesEventsPanel?.sync(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.className="at",n.innerHTML=st.PLAY,n.append(i.clock),n.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),s.append(n,r),s})),t.hidden=t.childElementCount===0}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}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-weather")&&this.openSkyParts().some(e=>e.category==="skyEvent")?"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",s=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,s&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const n=this.currentReference();n&&this.syncReferenceStatus(n),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){const t=Zc.kinds();if(Zn.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Zn.computedPart(e,t)}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,s=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&s!==void 0&&this.accountCompareInput.checked,this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s);const n=t&&s!==void 0?"bodies":"shapes",r=this.accountViewSelect.value!==n;this.accountViewSelect.value=n,r&&this.refreshTimelineMarks(),this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading,this.shadow.getElementById("account-compare-row").hidden=this.isReading||n!=="bodies"}syncSkyParts(){if(this.isGroupIdOpen("group-weather"))for(const e of this.openSkyParts())this.loadSkyPartEditor(e)?.then(t=>t.refresh())}chooseAccountView(e){const t=this.groupTabs.find(s=>s.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const s of this.subgroupTabs){if(s.parentElement!==t)continue;const n=s===e;s.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(s.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(s=>s.sync());const i=[...this.skyParts.values()].find(s=>s.tab===e);i&&this.loadSkyPartEditor(i)?.then(s=>s.sync()),this.syncCanvasMode()}showPhenomenonPartWithContent(){const e=this.ufoElement.sighting,t=e.timeline.sourceIds.length>0,i=(e.interpretation?.bodies?.length??0)>0,n=this.shadow.getElementById("shape-bodies")?.hidden===!1?!i&&t?"shape-shapes":void 0:!t&&i?"shape-bodies":void 0,r=n&&this.subgroupTabs.find(c=>c.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:a,opensMostLacking:o}=this;this.openSubgroup(r),this.sectionChosen=a,this.opensMostLacking=o}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){if(!this.paramSummaryBuilder)return;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("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount?(this.assessedAccount=s,this.assessSoon()):this.assessmentsOwed&&this.ufoElement.playbackState!=="playing"&&this.assessSoon();return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.assessSoon()}assessmentsOwed=!1;assessSoon(){if(this.ufoElement.playbackState==="playing"){this.assessmentsOwed=!0;return}this.assessmentsOwed=!1,this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=xe.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:xe.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(a),i={group:s.group,element:r},t.push(r)}const n=this.paramChip(s);i?i.element.append(n):t.push(n)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),kT.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 this.panelIndex(e==="phenomenon"?"shape":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"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new ww(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.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
11754
|
+
`;static async pictureOf(e){if(!e)return;const{ModelThumbnails:t}=await Q(async()=>{const{ModelThumbnails:i}=await import("./ModelThumbnails-cuvgO3ks.js");return{ModelThumbnails:i}},__vite__mapDeps([20,21]),import.meta.url);return t.of(e)}enhance(e,t,i){this.ensureStyle();const s=document.createElement("button");s.type="button",s.className="model-picker-button",e.after(s),e.hidden=!0;let n=0,r;const a=()=>{const c=++n,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(m=>m.value).join()]);if(u===r){--n;return}r=u,s.replaceChildren();const p=document.createElement("span");p.textContent=`${d?d.title||d.url:h?.textContent??""} …`,s.title=this.messages().choose,s.append(p);const f=e.value;(d?Promise.resolve({url:d.url}):t(f)).then(m=>xp.pictureOf(m)).then(m=>{if(!m||c!==n)return;const v=new Image;v.src=m,v.alt="",s.prepend(v)})};e.addEventListener("change",a),new MutationObserver(a).observe(e,{childList:!0,subtree:!0});const o=i&&{current:()=>i.current(),apply:c=>{i.apply(c),a()}};s.addEventListener("click",()=>void this.open(e,t,o)),a()}chooseFrom(e,t,i,s){this.ensureStyle(),this.open(e,t,s,i)}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=xp.STYLE,t.append(i)}open(e,t,i,s){const n=this.messages(),r=document.createElement("div");r.className="model-picker-backdrop";const a=document.createElement("div");a.className="model-picker",a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true");const o=document.createElement("h2");o.textContent=n.title;const c=document.createElement("button");c.type="button",c.className="model-picker-close",c.setAttribute("aria-label",n.close),c.title=n.close,c.innerHTML=we.CLOSE;const h=document.createElement("header");h.append(o,c);const d=document.createElement("div");d.className="model-picker-body",a.append(h,d),r.append(a);const u=()=>{r.remove(),document.removeEventListener("keydown",p,!0),Q(async()=>{const{ModelViewer:E}=await import("./ModelViewer-DjGC6fMB.js");return{ModelViewer:E}},__vite__mapDeps([22,21]),import.meta.url).then(({ModelViewer:E})=>E.end())},p=E=>{E.key==="Escape"&&(E.stopPropagation(),u())},f=i?.current(),m="\0address",v=E=>E===m&&f?Promise.resolve({url:f.url}):t(E),g=E=>{if(u(),s){E!==m&&s(E);return}E===m||E===e.value||(e.value=E,e.dispatchEvent(new Event("change",{bubbles:!0})))};let b;const w=new Map,y=E=>{const S=document.createElement("button");S.type="button",S.className="model-card",S.dataset.value=E.value,S.setAttribute("aria-pressed",String(!s&&(E.value===m||E.value===e.value&&!f)));const A=document.createElement("div");A.className="model-thumb";const T=document.createElement("span");if(T.className="model-name",T.textContent=E.textContent,S.append(A,T),E.title){const C=document.createElement("span");C.className="model-credit",C.textContent=E.title,S.append(C)}v(E.value).then(C=>xp.pictureOf(C)).then(C=>{if(!C)return;const N=new Image;N.src=C,N.alt="",A.append(N)});let _,k=!1;const L=()=>{k&&!(_&&!_.active)||(k=!0,Promise.all([v(E.value),Q(()=>import("./ModelViewer-DjGC6fMB.js"),__vite__mapDeps([22,21]),import.meta.url)]).then(([C,{ModelViewer:N}])=>{!C||!k||(_=N.show(A,C))}).catch(()=>{}))},P=()=>{k=!1,_?.stop(),_=void 0};return w.set(S,L),S.addEventListener("pointerenter",L),S.addEventListener("focus",L),S.addEventListener("pointerleave",()=>{document.activeElement!==S&&P()}),S.addEventListener("blur",P),S.addEventListener("click",C=>{if(_?.consumeDrag()){C.preventDefault();return}g(E.value)}),S},M=()=>(b=document.createElement("div"),b.className="model-picker-grid",d.append(b),b);if(f){const E=new Option(f.title||f.url,m);E.title=[f.author,f.license].filter(Boolean).join(" — "),M().append(y(E))}for(const E of Array.from(e.children))if(E instanceof HTMLOptGroupElement){const S=document.createElement("h3");S.textContent=E.label,d.append(S);const A=M();for(const T of Array.from(E.children))A.append(y(T));b=void 0}else E instanceof HTMLOptionElement&&(b??M()).append(y(E));i&&this.addAddressForm(h,c,a,d,i,n,u),c.addEventListener("click",u),r.addEventListener("click",E=>{E.target===r&&u()}),document.addEventListener("keydown",p,!0),this.root.append(r);const x=a.querySelector('.model-card[aria-pressed="true"]');(x??c).focus(),x&&w.get(x)?.()}addAddressForm(e,t,i,s,n,r,a){const o=document.createElement("button");o.type="button",o.className="model-picker-add",o.textContent="+",o.title=r.address,o.setAttribute("aria-label",r.address),o.setAttribute("aria-expanded","false"),e.insertBefore(o,t);const c=document.createElement("form");c.className="model-picker-address",c.hidden=!0;const h=(w,y,M="")=>{const x=document.createElement("label"),E=document.createElement("span");E.textContent=w;const S=document.createElement("input");return S.type=y,S.placeholder=M,x.append(E,S),c.append(x),S},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"),m=h(r.addressSource,"url","https://…"),v=document.createElement("p");v.textContent=r.addressIncomplete;const g=document.createElement("button");g.type="submit",g.className="model-picker-use",g.textContent=r.addressUse,c.append(v,g),i.insertBefore(c,s);const b=()=>{g.disabled=d.value.trim()==="",v.hidden=d.value.trim()===""||u.value.trim()!==""&&f.value.trim()!==""};for(const w of[d,u,p,f,m])w.addEventListener("input",b);o.addEventListener("click",()=>{const w=c.hidden;if(c.hidden=!w,o.setAttribute("aria-expanded",String(w)),!w)return;const y=n.current();d.value=y?.url??"",u.value=y?.title??"",p.value=y?.author??"",f.value=y?.license??"",m.value=y?.source??"",b(),d.focus()}),c.addEventListener("submit",w=>{w.preventDefault(),d.value.trim()!==""&&(n.apply({url:d.value.trim(),title:u.value.trim(),author:p.value.trim(),license:f.value.trim(),source:m.value.trim()}),a())}),b()}}class cM{constructor(e){this.provider=e}static SPAN_DEG=.002;async at(e,t){const i=cM.SPAN_DEG;try{const n=(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(n)?n:void 0}catch{return}}}class bU{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),s=this.zoneOffsetHours(e,new Date(i));if(s!==void 0)return this.zoneOffsetHours(e,new Date(i-s*36e5))??s}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 s=i.formatToParts(t).find(r=>r.type==="timeZoneName")?.value??"",n=/^GMT(?:([+-])(\d{2}):(\d{2}))?$/.exec(s);if(n)return n[1]?(n[1]==="-"?-1:1)*(Number(n[2])+Number(n[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(s=>this.offsetHoursAt(s,i)===e)}}class jn{static STEP_MS=100;static plan(e){const t=jn.routeOf(e),i=_t.decorReachFor(e.decor,t),s=Math.max(e.observerTrack.duration,e.timeline.duration,0),n=[];let r;const a=new Set,o=(h,d,u,p)=>{if(Math.abs(h.radiusM-p)>=p*.1)return!1;const{x:f,z:m}=ot(d,u,h.lat,h.lng);return Math.hypot(f,m)<_t.rebuildDistanceFor(p)};for(let h=0;;h=Math.min(s,h+jn.STEP_MS)){const d=tt(e,h);if(d?.lat!==void 0&&d.lng!==void 0){const u=_t.groundRadiusFor(d.elevationM??0),p=_t.patchRadiusFor(u,d.elevationM??0),f=Math.max(p,i);(!r||!o(r,d.lat,d.lng,f))&&(r=n.find(m=>o(m,d.lat,d.lng,f)),r||n.push(r={lat:d.lat,lng:d.lng,radiusM:f})),f<u&&a.add(r)}if(h>=s)break}for(const h of a)n.push({lat:h.lat,lng:h.lng,radiusM:_t.FAR_RING_RADIUS_M,far:!0});const c=Qp.map(h=>Or.of(h)).filter(h=>h.reachM&&Or.eventsOf(e.skyEvents,h).length>0);if(c.length>0){const h=d=>Math.max(...c.map(u=>u.reachM(Or.eventsOf(e.skyEvents,u),d)));for(const d of[...n])d.far||a.has(d)||_t.needsFarRing(d.radiusM,0,h(d))&&n.push({lat:d.lat,lng:d.lng,radiusM:_t.FAR_RING_RADIUS_M,far:!0})}return n}static routeOf(e){const t=e.observerTrack.allKeyframes.flatMap(i=>i.pose.lat!==void 0&&i.pose.lng!==void 0?[{lat:i.pose.lat,lng:i.pose.lng}]:[]);return t.length>=2?t:void 0}static async freeze(e,t,i,s,n){const r=new Date().toISOString().slice(0,10),a=o=>n?.(o,i.length);switch(e){case"relief":{const o=jn.routeOf(t),c=[];for(const[u,p]of i.entries()){try{const f=await s.elevation.getElevationGrid(sr.boundsOf(p),{width:sg,height:sg},{route:o});c.push({...p,grid:f})}catch(f){console.warn("Relief not snapshots for a patch:",f)}a(u+1)}if(c.length===0)return;const h=s.elevationCredit;return{bytes:await mf.encode({takenOn:r,attribution:h,patches:c}),attribution:h,takenOn:r,answered:c.length,patches:i.length}}case"imagery":{const o=new Q2,c=zi(qc,s.imagery),h=c.create(o.fetch);let d=0;for(const[f,m]of i.entries()){try{await h.getImageryTexture(sr.boundsOf(m),{width:ng,height:ng}),d++}catch(v){console.warn("Imagery not snapshots for a patch:",v)}a(f+1)}if(o.tiles.size===0)return;const u=h.attribution;return{bytes:await ug.encode({takenOn:r,source:c.id,attribution:u,patches:[...i],tiles:o.tiles}),attribution:u,takenOn:r,answered:d,patches:i.length}}case"roads":return jn.vector(s.roads,i,r,a,(o,c)=>o.getRoads(c),o=>o.contemporary);case"water":return jn.vector(s.water,i,r,a,(o,c)=>o.getWater(c));case"railways":return jn.vector(s.railways,i,r,a,(o,c)=>o.getRailways(c),o=>o.contemporary)}}static mapGround(e){const t=Vc.of(e);return t&&ui.fitted(t,e.traces.flatMap(i=>i.points))}static async freezeMap(e,t){const i=jn.mapGround(e);if(!i)return;const s=new Date().toISOString().slice(0,10),n=new Q2,r=zi(qc,t),a=r.create(n.fetch),o=ui.IMAGERY_PX;try{await a.getImageryTexture(i,{width:o,height:o})}catch(d){console.warn("Map imagery not snapshots:",d);return}const c=a.attribution;return{bytes:await ug.encode({takenOn:s,source:r.id,attribution:c,patches:[],map:{bounds:i,pixels:o},tiles:n.tiles}),attribution:c,takenOn:s,answered:1,patches:1}}static async vector(e,t,i,s,n,r){if(!e)return;const a=[];for(const[h,d]of t.entries()){if(d.radiusM<=_t.ROADS_MAX_RADIUS_M)try{a.push({...d,items:await n(e,sr.boundsOf(d))})}catch(u){console.warn("Not snapshots for a patch:",u)}s(h+1)}if(a.length===0)return;const o={version:1,takenOn:i,attribution:e.attribution,contemporary:r?.(e),patches:a};return{bytes:new TextEncoder().encode(JSON.stringify(o)),attribution:e.attribution,takenOn:i,answered:a.length,patches:t.length}}}class cs{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.replace(this.shown,i.detail)),this.root.querySelector("#snapshot-refresh").addEventListener("click",()=>void this.refresh(this.shown)),this.root.querySelector("#annex-export").addEventListener("click",()=>void this.exportAnnex(this.shown))}messages;busy=!1;shown="relief";editor;editorFor;editTimer;get sourceInput(){return this.root.querySelector("#annex-source")}get editorHost(){return this.root.querySelector("#annex-editor")}get note(){return this.root.querySelector("#snapshot-note")}localize(e){this.messages=e,this.root.title=e.snapshotHint;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-annex-source",e.annexSource),t("snapshot-refresh",e.snapshotRefresh),t("annex-export",e.export),this.sourceInput.messages=e,this.render()}itemLabel(e){return this.groupName(e)}where(e){const t=this.annex(e);return this.isLive(e)?this.messages.snapshotLiveState:!t||t.refresh?this.messages.snapshotPending:cs.isInline(t.src)?this.messages.annexStorageInline:t.src}isInlineGroup(e){const t=this.annex(e);return t!==void 0&&!this.isLive(e)&&cs.isInline(t.src)}annex(e){const t=this.host.sighting().snapshots?.[e];return t?.src!==void 0?t:void 0}isLive(e){return os.isLive(this.host.sighting().snapshots,e)}setLive(e,t){if(this.isLive(e)===t)return;const i={...this.host.sighting().snapshots??{}};if(i.live){delete i.live;for(const n of os.NAMES)i[n]={...i[n]??{},live:!0}}const s={...i[e]??{}};t?s.live=!0:delete s.live,i[e]=Object.keys(s).length>0?s:void 0,this.setSnapshots(i)}show(e){this.shown=e,this.render()}render(){if(!this.messages)return;const e=this.shown,t=this.isLive(e),i=this.annex(e),s=this.root.querySelector("#snapshot-state");s.textContent=t?this.messages.snapshotLiveState:i&&!i.refresh?[this.messages.snapshotTakenOn.replaceAll("{date}",i.takenOn??"?"),i.attribution].filter(Boolean).join(" · "):this.messages.snapshotPending;const n=this.root.querySelector("#snapshot-refresh");n.disabled=this.busy||t;const r=i!==void 0&&!i.refresh&&!t,a=r&&cs.isInline(i.src);this.sourceInput.url=r?a?this.host.masterUrl():this.address(i.src):"",r||(this.sourceInput.mode="file"),this.sourceInput.disabled=this.busy||t,this.root.querySelector("#annex-export").disabled=i===void 0||this.busy,this.renderEditor(r&&!a?i:void 0)}async renderEditor(e){const t=this.shown,i=e&&!cs.isZip(t)?await this.textOf(e).catch(()=>{}):void 0;if(t!==this.shown||(this.editorHost.hidden=i===void 0,i===void 0))return;const s=`${t}|${e.src}`;if(this.editor&&this.editorFor===s)return;if(this.editorFor=s,this.editor){this.editor.replaceText(i,!1);return}const{SightingFileEditor:n}=await Q(async()=>{const{SightingFileEditor:r}=await import("./SightingFileEditor-bXm0nVE4.js");return{SightingFileEditor:r}},__vite__mapDeps([23,3,24]),import.meta.url);if(t!==this.shown||!this.editorHost.isConnected){this.editorFor=void 0;return}this.editor??=new n(this.editorHost,i,r=>this.edited(r),this.messages.annexEditorLabel,{schema:{},phrases:this.messages.fileSearchPhrases})}async textOf(e){return JSON.stringify(JSON.parse(new TextDecoder().decode(await this.bytesOf(e))),null,1)}edited(e){const t=this.shown;clearTimeout(this.editTimer),this.editTimer=setTimeout(()=>{let i;try{i=JSON.parse(e)}catch{return}this.write(t,new TextEncoder().encode(JSON.stringify(i)),{keepEditor:!0})},600)}async replace(e,t){if(t.url){if(this.address(t.url)===new URL(this.host.masterUrl(),location.href).href){await this.setStorage(e,!0);return}const s={...this.host.sighting().snapshots??{}};let n;try{n=await this.bytesAt(t.url)}catch{n=void 0}if(n!==void 0)try{s[e]={src:t.url,...await cs.describe(e,n)}}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}else{const r=this.annex(e);if(!r){Ht.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",t.url),"warning");return}Ct.hold(this.address(t.url),await this.bytesOf(r)),s[e]={...r,src:t.url}}Ht.show(this.note,void 0),this.setSnapshots(s);return}const{InputFileElement:i}=await Q(async()=>{const{InputFileElement:s}=await Promise.resolve().then(()=>AI);return{InputFileElement:s}},void 0,import.meta.url);await this.write(e,await i.bytesOf(t))}async write(e,t,i={}){const s={...this.host.sighting().snapshots??{}},n=this.annex(e);let r;try{r=await cs.describe(e,t)}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}const a=n!==void 0&&cs.isInline(n.src),o=a?cs.dataUrl(e,t):n?.src??os.annexName(this.host.base(),e);a||Ct.hold(this.address(o),t),s[e]={...s[e]?.live?{live:!0}:{},src:o,...r},Ht.show(this.note,void 0),i.keepEditor&&(this.editorFor=`${e}|${o}`),this.setSnapshots(s)}async setStorage(e,t){const i={...this.host.sighting().snapshots??{}},s=this.annex(e);if(!s||cs.isInline(s.src)===t)return;const n=await this.bytesOf(s);let r;t?r=cs.dataUrl(e,n):(r=os.annexName(this.host.base(),e),Ct.hold(this.address(r),n)),i[e]={...s,src:r},this.editorFor=`${e}|${r}`,this.setSnapshots(i)}async exportAnnex(e){const t=this.annex(e);if(!t)return;const i=await this.bytesOf(t),s=cs.isInline(t.src)?os.annexName(this.host.base(),e):decodeURIComponent(t.src.split("/").pop()??t.src);this.host.download(new Blob([i],{type:cs.isZip(e)?"application/zip":"application/json"}),s)}static async describe(e,t){let i;if(cs.isZip(e)){const{unzipSync:s}=await Q(async()=>{const{unzipSync:n}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:n}},[],import.meta.url);i=JSON.parse(new TextDecoder().decode(s(t)["index.json"]))}else i=JSON.parse(new TextDecoder().decode(t));if(typeof i!="object"||i===null)throw new Error("Not an annex");return{takenOn:typeof i.takenOn=="string"?i.takenOn:void 0,attribution:typeof i.attribution=="string"?i.attribution:void 0}}async bytesAt(e){return Ct.bytes(this.address(e))}static isInline(e){return e.startsWith("data:")}static isZip(e){return e==="relief"||e==="imagery"||e==="map"}static dataUrl(e,t){let i="";for(let s=0;s<t.length;s+=32768)i+=String.fromCharCode(...t.subarray(s,s+32768));return`data:${cs.isZip(e)?"application/zip":"application/json"};base64,${btoa(i)}`}async refresh(e){if(this.busy)return;const t={...this.host.sighting().snapshots??{}};if(e==="upperAir"){const i=t.upperAir;i&&(t.upperAir={...i,refresh:!0}),this.setSnapshots(t);return}this.busy=!0,this.render();try{const i=t[e]?.src,s=(i&&!cs.isInline(i)?cs.baseOf(i):void 0)??this.host.base();(e==="map"?await this.takeMap(t,this.host.sources(),s):await this.take(e,t,jn.plan(this.host.sighting()),this.host.sources(),s))?Ht.show(this.note,void 0):Ht.show(this.note,this.messages.snapshotFailed.replaceAll("{group}",this.groupName(e)),"warning")}finally{this.busy=!1}this.setSnapshots(t)}hasWork(){const e=this.host.sighting();return os.isEmpty(e.snapshots)?this.host.upperAirHeard()!==void 0||jn.plan(e).length>0:!0}async prepare(e){const t=this.host.sighting(),i={...t.snapshots??{}},s=new Map;this.busy=!0,this.render();try{const n=d=>os.isLive(i,d),r=d=>i[d]?.src!==void 0?i[d]:void 0;for(const d of os.NAMES)!i.live&&i[d]?.live&&(i[d]={live:!0});const a=jn.plan(t);let o;for(const d of os.TERRAIN){if(n(d))continue;const u=r(d);if(a.length>0&&(!u||u.refresh||!await this.fits(d,u,a))&&await this.take(d,i,a,o??=this.host.sources(),e)){await this.keep(r(d),s);continue}u?.refresh&&(i[d]={...u,refresh:void 0}),r(d)&&await this.keep(r(d),s)}if(!n("map")){const d=r("map");jn.mapGround(t)!==void 0&&(!d||d.refresh||!await this.fitsMap(d))&&await this.takeMap(i,o??=this.host.sources(),e)?await this.keep(r("map"),s):d&&(d.refresh&&(i.map={...d,refresh:void 0}),await this.keep(r("map"),s))}const c=this.host.upperAirHeard(),h=r("upperAir");if(!n("upperAir")&&c&&(!h||h.refresh)){const d=new Date().toISOString().slice(0,10),u={version:1,takenOn:d,attribution:c.answer.source.name,answers:[c]},p=new TextEncoder().encode(JSON.stringify(u)),f=this.place("upperAir",h?.src,e,p);i.upperAir={src:f,takenOn:d,attribution:c.answer.source.name},cs.isInline(f)||s.set(f,p)}else h&&!n("upperAir")&&(h.refresh&&(i.upperAir={...h,refresh:void 0}),await this.keep(r("upperAir"),s))}finally{this.busy=!1}return this.setSnapshots(i),s}async take(e,t,i,s,n){const r=this.groupName(e),a=await jn.freeze(e,this.host.sighting(),i,s,(o,c)=>Ht.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",r).replaceAll("{done}",String(o)).replaceAll("{of}",String(c))));return Ht.show(this.note,void 0),a?(t[e]={src:this.place(e,t[e]?.src,n,a.bytes),takenOn:a.takenOn,attribution:a.attribution},!0):!1}async takeMap(e,t,i){Ht.show(this.note,this.messages.snapshotTaking.replaceAll("{group}",this.groupName("map")).replaceAll("{done}","0").replaceAll("{of}","1"));const s=await jn.freezeMap(this.host.sighting(),t.imagery);return Ht.show(this.note,void 0),s?(e.map={src:this.place("map",e.map?.src,i,s.bytes),takenOn:s.takenOn,attribution:s.attribution},!0):!1}async fitsMap(e){const t=jn.mapGround(this.host.sighting());try{const i=JSON.parse(new TextDecoder().decode((await Ct.zip(this.address(e.src)))["index.json"]));return t!==void 0&&i.map!==void 0&&sr.sameBounds(i.map.bounds,t)}catch{return!1}}async fits(e,t,i){try{const s=this.address(t.src),n=t.src.endsWith(".zip")?JSON.parse(new TextDecoder().decode((await Ct.zip(s))["index.json"])).patches:(await Ct.json(s)).patches,r=e==="relief"||e==="imagery"?i:i.filter(a=>a.radiusM<=_t.ROADS_MAX_RADIUS_M);return sr.samePatches(n.map(({lat:a,lng:o,radiusM:c})=>({lat:a,lng:o,radiusM:c})),r)}catch{return!1}}place(e,t,i,s){if(t!==void 0&&cs.isInline(t))return cs.dataUrl(e,s);const n=t??os.annexName(i,e);return Ct.hold(this.address(n),s),n}async keep(e,t){if(!cs.isInline(e.src))try{t.set(e.src,await this.bytesOf(e))}catch{Ht.show(this.note,this.messages.snapshotMissing.replaceAll("{file}",e.src),"warning")}}bytesOf(e){return Ct.bytes(this.address(e.src))}address(e){return Ct.address(e,this.host.documentUrl())}setSnapshots(e){for(const t of os.NAMES)e[t]===void 0&&delete e[t];this.host.sighting().snapshots=os.isEmpty(e)?void 0:e,this.render(),this.host.changed()}destroy(){clearTimeout(this.editTimer),this.editor?.destroy(),this.editor=void 0,this.editorFor=void 0}static baseOf(e){return e?.match(/^(.*)\.[a-z-]+\.(zip|json)$/)?.[1]}static size(e){return e<1e6?`${Math.max(1,Math.round(e/1e3))} kB`:`${(e/1e6).toFixed(1)} MB`}groupName(e){return{relief:this.messages.snapshotRelief,imagery:this.messages.snapshotImagery,roads:this.messages.snapshotRoads,water:this.messages.snapshotWater,railways:this.messages.snapshotRailways,upperAir:this.messages.snapshotUpperAir,map:this.messages.snapshotMap}[e]}}class Mg{constructor(e,t){this.root=e,this.host=t,this.sourceInput.addEventListener("filepick",i=>void this.take(this.shown,i.detail)),this.root.querySelector("#section-annex-export").addEventListener("click",()=>this.exportAnnex(this.shown))}messages;shown="weather";get sourceInput(){return this.root.querySelector("#section-annex-source")}get note(){return this.root.querySelector("#section-annex-note")}localize(e){this.messages=e;const t=(i,s)=>{this.root.querySelector(`#${i}`).textContent=s};t("label-section-annex-source",e.annexSource),t("section-annex-export",e.export),this.sourceInput.messages=e,this.render()}show(e){this.shown=e,Ht.show(this.note,void 0),this.render()}srcOf(e){return this.host.sighting().snapshots?.[e]?.src}itemLabel(e){const t=this.messages;return t?{weather:t.fileItemWeather,place:t.fileItemPlace,lightPollution:t.fileItemLightPollution,decor:t.fileItemDecor}[e]:""}where(e){return this.srcOf(e)??this.messages?.annexStorageInline??""}isInline(e){return this.srcOf(e)===void 0}static pathOf(e){return[Yt.KEYS[e][0]]}render(){if(!this.messages)return;const e=this.srcOf(this.shown);this.sourceInput.url=e?this.resolve(e):this.host.masterUrl(),this.root.querySelector("#section-annex-state").textContent=this.state(this.shown)}state(e){const t=this.host.sighting();switch(e){case"weather":return t.weatherSource?.name??this.messages.weatherStatedByObserver;case"place":return t.event.place?.[0]?.name??"";case"lightPollution":return t.provenance.at("lightPollution")?.rationale??(t.lightPollution===void 0?"":String(t.lightPollution));case"decor":return""}}setStorage(e,t){const i={...this.host.sighting().snapshots??{}};if(t===(i[e]?.src===void 0))return;const{src:s,...n}=i[e]??{};i[e]=t?n:{...n,src:Yt.annexName(this.host.base(),e)},this.write(e,i)}annex(e){const t=this.srcOf(e);return t===void 0?void 0:{src:t,bytes:this.bytesOf(e)}}bytesOf(e){const t=P0(this.host.sighting()),{takenOn:i,attribution:s}=this.host.sighting().snapshots?.[e]??{},n={version:Ol.CURRENT.sighting,takenOn:i,attribution:s,...Yt.taken(e,t)};return new TextEncoder().encode(JSON.stringify(n))}resolve(e){return new URL(e,this.host.documentUrl()??location.href).href}exportAnnex(e){const t=this.srcOf(e)??Yt.annexName(this.host.base(),e);this.host.download(new Blob([this.bytesOf(e)],{type:"application/json"}),decodeURIComponent(t.split("/").pop()??t))}async take(e,t){if(t.url&&this.resolve(t.url)===this.resolve(this.host.masterUrl())){this.setStorage(e,!0);return}if(t.url)try{await fetch(this.resolve(t.url),{method:"HEAD"}).then(o=>{if(!o.ok)throw new Error(String(o.status))})}catch{const o={...this.host.sighting().snapshots??{}};o[e]={...o[e]??{},src:t.url},Ht.show(this.note,void 0),this.write(e,o);return}let i;try{const{InputFileElement:o}=await Q(async()=>{const{InputFileElement:h}=await Promise.resolve().then(()=>AI);return{InputFileElement:h}},void 0,import.meta.url),c=await o.bytesOf(t.url?{url:this.resolve(t.url)}:t);if(i=Oi.toCurrent(JSON.parse(new TextDecoder().decode(c))),typeof i!="object"||i===null||Yt.KEYS[e].every(h=>i[h]===void 0))throw new Error("Not this section")}catch{Ht.show(this.note,this.messages.annexUnreadable,"warning");return}const s=this.host.sighting(),n={...P0(s)};if(e==="decor")Yt.put(e,n,"timeline"in i?Yt.taken(e,i):i);else for(const o of Yt.KEYS[e])n[o]=i[o];const r=Mw(n);Mg.copy(e,r,s);const a={...s.snapshots??{}};t.url?a[e]={...a[e]??{},src:t.url}:a[e]=a[e]??{},Ht.show(this.note,void 0),this.write(e,a)}write(e,t){this.host.sighting().snapshots=os.isEmpty(t)?void 0:t,this.render(),this.host.changed(e)}static copy(e,t,i){switch(e){case"weather":i.weatherTrack.clear();for(const s of t.weatherTrack.allKeyframes)i.weatherTrack.addKeyframe(s.t,s.weather);i.weatherSource=t.weatherSource;break;case"place":i.event.place=t.event.place;break;case"lightPollution":i.lightPollution=t.lightPollution;break;case"decor":i.decor=t.decor;break}for(const s of Yt.KEYS[e]){i.provenance.clear(s);for(const n of t.provenance.paths())(n===s||n.startsWith(`${s}.`))&&i.provenance.set(n,t.provenance.at(n))}}}class yU{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 s=await fetch(i.toString());if(!s.ok)return;const n=await s.json();return n.timezone&&n.timezone!=="GMT"?n.timezone:void 0}catch{return}}}const wU=Ye.point("timeZone").provide(Ye.BUILT_IN,[{id:"open-meteo",name:"Open-Meteo",credit:"© Open-Meteo",creditUrl:"https://open-meteo.com/en/docs",create:()=>new yU}]),MU=["appearance","movement","incongruity","detection","close","beings","traces"];class J1{static OCCUPATIONS={student:!0,worker:!0,farmer:!0,homemaker:!0,merchant:!0,business:!0,employee:!0,artist:!0,technician:!0,police:!0,pilot:!0,military:!0};static RELATIONS=["friends","family","professional","none"];static ACTIVITIES=["leisure","travelling","cultural","working"]}class ms{static READ_FROM_RECORDING=["detection","close","beings"];occupationKind=ms.select("observerOccupationKind");graduate=ms.select("observerGraduate");enquiryMinutes=Object.assign(document.createElement("input"),{id:"enquiryMinutes",type:"number",min:"0",step:"1",size:5});relation=ms.select("observersRelation");activity=ms.select("observerActivity");factors=new Map(MU.map(e=>[e,ms.select(`strangeness-${e}`)]));labels=new Map;unit=document.createTextNode(" min");strangenessTitle=document.createElement("span");strangenessIntro=Object.assign(document.createElement("p"),{className:"section-intro"});wording;constructor(e,t,i,s){Jn.register(),e.append(this.label(this.occupationKind,h=>[h.occupationKind,h.occupationKindHint]),this.label(this.graduate,h=>[h.graduate]));const n=this.label(this.enquiryMinutes,h=>[h.enquiryMinutes,h.enquiryMinutesHint]);n.append(this.unit);const r=t.querySelector("#accountSource")?.closest("label");r?r.after(n):t.append(n),t.append(this.label(this.relation,h=>[h.relation]),this.label(this.activity,h=>[h.activity]));const a=Object.assign(document.createElement("h3"),{className:"section-title"});a.append(this.strangenessTitle),i.append(a,this.strangenessIntro,...[...this.factors].map(([h,d])=>this.label(d,u=>[u.factors[h],u.factorHints[h]])));const o=[["yes","yes"],["no","no"]],c=h=>h.map(d=>[d,d]);ms.choices(this.occupationKind,"",c(Object.keys(J1.OCCUPATIONS))),ms.choices(this.graduate,"",o),ms.choices(this.relation,"",c(J1.RELATIONS)),ms.choices(this.activity,"",c(J1.ACTIVITIES));for(const h of this.factors.values())ms.choices(h,"",o);for(const h of[this.occupationKind,this.graduate,this.enquiryMinutes,this.relation,this.activity,...this.factors.values()])h.addEventListener("change",s)}set messages(e){this.wording=e;for(const t of this.labels.values())t();this.unit.textContent=` ${e.minutes}`,this.strangenessTitle.textContent=e.strangenessSection,this.strangenessIntro.textContent=e.strangenessIntro,ms.choices(this.occupationKind,e.unknown,Object.entries(e.occupationKinds)),ms.choices(this.graduate,e.unknown,[["yes",e.yes],["no",e.no]]),ms.choices(this.relation,e.unknown,Object.entries(e.relations)),ms.choices(this.activity,e.unknown,Object.entries(e.activities));for(const[t,i]of this.factors)ms.choices(i,ms.READ_FROM_RECORDING.includes(t)?e.fromRecording:e.unknown,[["yes",e.yes],["no",e.no]])}show(e){this.occupationKind.value=e?.observerOccupationKind??"",this.graduate.value=ms.yesNo(e?.observerGraduate),this.enquiryMinutes.value=e?.enquiryMinutes?.toString()??"",this.relation.value=e?.observersRelation??"",this.activity.value=e?.activity??"";for(const[t,i]of this.factors)i.value=ms.yesNo(e?.strangeness?.[t])}values(){const e=this.enquiryMinutes.value.trim()===""?void 0:Number(this.enquiryMinutes.value),t={};for(const[i,s]of this.factors){const n=ms.boolean(s.value);n!==void 0&&(t[i]=n)}return{observerOccupationKind:this.occupationKind.value||void 0,observerGraduate:ms.boolean(this.graduate.value),enquiryMinutes:e!==void 0&&Number.isFinite(e)&&e>=0?e:void 0,observersRelation:this.relation.value||void 0,activity:this.activity.value||void 0,strangeness:Object.keys(t).length>0?t:void 0}}label(e,t){const i=document.createElement("label"),s=document.createElement("span");return i.append(s," ",e),this.labels.set(s,()=>{if(!this.wording)return;const[n,r]=t(this.wording);Jn.say(s,n,r)}),i}static select(e){return Object.assign(document.createElement("select"),{id:e})}static choices(e,t,i){const s=e.value;e.replaceChildren(new Option(t,""),...i.map(([n,r])=>new Option(r,n))),e.value=s}static yesNo(e){return e===void 0?"":e?"yes":"no"}static boolean(e){return e===""?void 0:e==="yes"}}const Qm=new Set;Ug();OF();Ed.register();const jh={width:48,height:28},xU=2500,xA=40,SU=10,SA=600,EA=900,Zh=2e-4,EU=900,AU=-1.46,TU=3,Q1=.2,IU=.5,_U=3,DU=.01,kU=1.6,eb=2e3,RU=250,AA=new Set(["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"]),CU=1,LU=5,OU=10,gl=4,$u="ufo-1",PU={presetId:"oval",color:"#39ff14",transparency:0,haloScale:1.5,blur:0,brightness:0};function NU(l){return l.kind==="oval"?"oval":"polygon"}const FU=-6,UU=21;class xe extends HTMLElement{shadow;sceneElement;ufoElement;recordButton;samplingRateInput;shapeAddMenu;colorInput;transparencyInput;haloScaleInput;blurInput;brightnessInput;blurBoundOutput;sourceSelect;shapeTitleInput;shapeRotationInput;utcOffsetInput;timeZoneSelect;timeZoneWarning;timeZoneProvider=wU[0].create();timeZoneLookupTimer;timeZoneLookedUpAt;offsetIsAuthors=!1;placeZone;autoFilledTimeZone;timeZones=new bU;apparentWidthInput;realWidthInput;objectDistanceInput;sizeLockSelect;apparentSizeOutput;realSizeOutput;clearDistanceHypothesisButton;depthBasisOutput;addShapeButton;deleteShapeButton;contextMenu;contextGroupButton;contextUngroupButton;contextDuplicateButton;contextBringToFrontButton;contextSendToBackButton;contextDeleteButton;contextAddVertexButton;contextDeleteVertexButton;decorContextMenu;contextViewAccountButton;contextMasksSubmenu;labelContextMasks;playPauseButton;seekInput;previousMarkButton;nextMarkButton;timelineMarks;timeStartLabel;timeEndLabel;durationInput;accountViewSelect;accountCompareInput;durationElement;exportButton;saveButton;timelineTracks;tracksToggle;sceneFieldOverlay;activeSceneField;referencesShownForField=!1;overlayTimer;witnessErrorView;candidatesView;sectionFolds;snapshotsPanel;sectionFilePanel;eventsPanel;phenomenonEventsPanel;bodiesEventsPanel;fileItemSelect;importInput;narrativeSourceRow;narrativeSettingsBox;narrativeSettingInputs=new Map;aircraftStatus=Object.assign(document.createElement("span"),{className:"source-status"});aircraftFlights;aircraftFlightsShownAt=0;narrativeDraftButton;narrativeStopButton;narrativeStatus;narrativeReport;placeNameInput;searchPlaceButton;placeMatchRow;placeMatchSelect;placeStatusText;placeProvider=pU();placeMatches=[];placeSearchToken=0;placeReverseTimer;namedCoordinates;latInput;lngInput;headingInput;headingUnit;pitchInput;rollInput;swayInput;lensGlassSelect;isoInput;filmStockSelect;meteringSelect;lensDropsInput;lensCondensationInput;lensDirtInput;lensShelteredInput;lightPollutionInput;lightPollutionStatusText;lightPollutionSourceRow;elevationInput;groundElevationOutput;weatherFromRecords=!0;groundElevationM;groundElevationFor;groundElevationTimer;groundElevationToken=0;obsTimeInput;startDate;endDate;obsEndTimeInput;observerIdInput;observerTitleInput;observerLastNameInput;observerFirstNamesInput;observerAgeInput;observerOccupationInput;accountSourceSelect;evaluationFields;accountUrlInput;labelAccountUrl;accountFollowedUpSelect;sightingIdInput;descriptionInput;tagsInput;cloudEditor;bodyEditor;bodyEditorLoading;skyParts=new Map;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 Wu(dU());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;labelShapeTitle;labelUtcOffset;labelApparentWidth;labelRealWidth;labelObjectDistance;labelSizeLock;labelSamplingRate;labelDuration;placeSourceRow;weatherSourceRow;terrainSourceRows;chosenSourceId=new Map;labelPlaceName;labelPlaceMatch;labelPosition;observerSaid;observerSaidShown;observerPosition;labelHeading;labelPitch;labelRoll;labelSway;labelLightPollution;labelElevation;labelObservationTime;labelObservationEndTime;labelObserverId;labelObserverTitle;labelObserverLastName;labelObserverFirstNames;labelObserverAge;labelObserverBirth;birthDate;perceptionSettings;birth;labelObserverOccupation;labelAccountSource;labelAccountFollowedUp;labelSightingId;labelDescription;labelTags;wholeKeyframesInput;labelImportFile;get reading(){return this.isReading}set reading(e){this.isReading=e,this.syncBodiesShown()}isReading=!1;accountShapeIds;labelNarrativeSource;groupTabs;groupPanels;paramSummary;paramSummaryBuilder;paramSummarySignature="";labelShapeGroup;labelTemporalGroup;labelLocationGroup;labelObservationGroup;labelObserverGroup;labelWeatherGroup;labelCloudCover;labelHighCloud;labelIceAlignment;labelRareIce;highCloudCoverInput;iceCrystalAlignmentInput;rareIceCrystalsInput;labelCloudDarkness;labelCloudBase;labelPrecipitationType;labelPrecipitationIntensity;labelWindDirection;labelWindSpeed;labelStorm;labelCloudsGroup;labelShapesSubgroup;labelBodiesSubgroup;labelPrecipitationGroup;labelWindGroup;subgroupTabs;labelWeatherInferred;weatherProviderSelect;weatherFileLink;labelSoundGroup;labelSoundKind;labelSoundVolume;labelSoundPitch;labelSoundSrc;labelInstrument;optionPrecipitationNone;optionPrecipitationRain;optionPrecipitationSnow;optionPrecipitationHail;decorList;observerList;observerShown="principal";static CLICK_SLOP_PX=5;static OBSERVER_PRINCIPAL="principal";surroundings;surroundingsProvider;sceneryStatus;scenerySource;labelScenerySource;sceneryWarning;sceneryRadius;labelSceneryRadius;sceneryChoice;decorModelProvider=new mp;milestoneSelect;milestoneLabelInput;milestoneNoteInput;addMilestoneButton;deleteMilestoneButton;goToMilestoneButton;currentMilestoneT;decorParameterForm;decorBaseForm;decorStateForm;decorBaseHost;decorStateHost;decorBaseShown=!1;decorParametersHost;decorParametersShownFor;labelDecorGroup;labelMilestones;labelMilestoneLabel;labelMilestoneNote;recorder;isRecording=!1;messages=ls.blank();ready=Promise.resolve();decorParameterTexts={};worded=!1;fieldHints=new Map;currentAppearance={...PU};currentSourceId=$u;selectedSourceIds=new Set([$u]);currentDecorId;currentReferenceId;referenceSelect;deleteReferenceButton;referenceTitleInput;referenceSourceInput;referenceKindSelect;referenceCreditInput;referenceCreditUrlInput;referenceTInput;referenceVideoFromInput;referenceVideoToInput;referenceVideoRateInput;referenceRemoveKeyButton;referenceDrawingInput;referenceOpacityInput;referenceHeadingInput;referencePitchInput;referenceRollInput;referenceFovInput;referenceUsePoseButton;referenceStatus;referenceFailure;addReferenceButton;referenceAddMenu;referenceLandmarksSelect;addReferenceLandmarkButton;deleteReferenceLandmarkButton;referenceLandmarkLabelInput;findGhostsButton;searchingGhosts=!1;ghostsStatus;ghostFinding;ghostsShown=!0;ghostsShownButton;labelReferenceLandmarks;labelReferenceLandmarkLabel;referenceAdoptPoseButton;traceImportInput;traceSelect;deleteTraceButton;traceTitleInput;traceSourceInput;traceStatus;labelTraceImport;addTraceButton;labelTraceTitle;labelTraceSource;currentTraceId;referenceStreetSelect;referenceStreetAddButton;lastCanvasMode="shape";referenceDragState;armingLandmark=!1;pendingLandmark;currentLandmarkId;referenceFit;streetPictures=[];streetPictures$;pictureRegistration;pictureRegistrationLoading;referenceFields;labelReferenceGroup;labelReferenceTitle;labelReferenceSrc;labelReferenceKind;labelReferenceCredit;labelReferenceCreditUrl;labelReferenceT;labelReferenceDrawing;labelReferenceOpacity;labelReferenceHeading;labelReferencePitch;labelReferenceRoll;labelReferenceFov;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(AA.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;AA.has(e.key)?this.selectedMembers().length===0&&t===this?this.walkOrTurn(e):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(),this.flash(this.shadow.querySelector("#decor-item label, #decor-item .field")))};constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>${yk}</style>${bk}`,this.shadow.appendChild(e.content.cloneNode(!0)),customElements.upgrade(this.shadow);for(const a of this.shadow.querySelectorAll(M0))a.build();for(const a of this.shadow.querySelectorAll(yg))a.build();for(const a of this.shadow.querySelectorAll(gf))a.build();for(const a of this.shadow.querySelectorAll(E0))a.build();this.sceneElement=document.createElement(vg),this.sceneElement.setAttribute("show-compass",""),this.sceneElement.addEventListener("observermapchange",a=>{this.ufoElement.sighting.observerMap=a.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",a=>{const{lat:o,lng:c}=a.detail;this.latInput.value=String(Number(o.toFixed(6))),this.lngInput.value=String(Number(c.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.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.shapeRotationInput=this.shadow.getElementById("shapeRotation"),this.utcOffsetInput=this.shadow.getElementById("utcOffsetHours"),this.timeZoneSelect=this.shadow.getElementById("timeZone"),this.timeZoneWarning=this.shadow.getElementById("time-zone-warning"),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.contextDuplicateButton=this.shadow.getElementById("context-duplicate"),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 ep(this.seekInput,this.shadow.getElementById("timeline-marks")),this.timeStartLabel=this.shadow.getElementById("time-start"),this.timeEndLabel=this.shadow.getElementById("time-end");for(const a of[this.timeStartLabel,this.timeEndLabel])a.addEventListener("click",()=>this.switchTimeDisplay()),a.addEventListener("keydown",o=>{o.key!=="Enter"&&o.key!==" "||(o.preventDefault(),this.switchTimeDisplay())});this.accountViewSelect=this.shadow.getElementById("account-view"),this.accountCompareInput=this.shadow.getElementById("account-compare"),this.durationElement=this.shadow.querySelector(yg),this.durationInput=this.durationElement.input,this.exportButton=this.shadow.getElementById("export"),this.saveButton=this.shadow.getElementById("save"),this.shareButton=this.shadow.getElementById("share"),this.shareDialog=this.shadow.getElementById("share-dialog"),this.shareDialog.subject=this.shareSubject,this.sectionFolds=new XA(this.shadow);const t=this;this.witnessErrorView=new yT({get sighting(){return t.ufoElement.sighting},messages:()=>this.worded?this.messages.witnessError:void 0,changed:()=>{this.touch(),this.armHistory(),this.scheduleHistoryRecord()},conditionsChanged:a=>{const o=this.ufoElement.sighting,{conditions:c,...h}=o.account??{},d={...h,...a?{conditions:a}:{}};o.account=Object.values(d).some(u=>u!==void 0)?d:void 0},recordingJson:()=>this.sightingData,lawsChanged:()=>{this.sceneElement.confrontationTolerance=Bi.lawsOf(this.witnessErrorView.errorModel,this.ufoElement.sighting.account?.conditions),this.refreshCandidatesSoon()}}),this.timelineTracks=new xf(this.shadow.getElementById("timeline-tracks"),a=>this.goToMark(a),this.messages),this.tracksToggle=this.shadow.getElementById("toggle-tracks"),this.tracksToggle.addEventListener("click",()=>this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")!=="true")),this.resizeScene(this.shadow.getElementById("scene-resize")),this.shadow.querySelector(".scene-card").addEventListener("pointerdown",a=>{a.pointerType==="touch"&&this.showOverlays()}),this.sceneFieldOverlay=new xT(this.shadow.querySelector(".scene-card"),()=>this.ufoElement.canvasElement),this.shadow.addEventListener("focusin",a=>{const o=a.target.id;xe.SCENE_LINKED.includes(o)&&this.setActiveSceneField(o)}),this.shadow.addEventListener("focusout",a=>{const o=a.relatedTarget;(!o||!xe.SCENE_LINKED.includes(o.id))&&this.setActiveSceneField(void 0)}),this.shadow.addEventListener("input",()=>this.refreshSceneField()),this.importInput=this.shadow.getElementById("import"),this.narrativeSourceRow=this.shadow.getElementById("narrative-source-row"),this.narrativeSettingsBox=this.shadow.getElementById("narrative-settings"),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.lensGlassSelect=this.shadow.getElementById("lens-glass"),this.isoInput=this.shadow.getElementById("iso"),this.filmStockSelect=this.shadow.getElementById("filmStock"),this.meteringSelect=this.shadow.getElementById("metering"),this.lensDropsInput=this.shadow.getElementById("lens-drops"),this.lensCondensationInput=this.shadow.getElementById("lens-condensation"),this.lensDirtInput=this.shadow.getElementById("lens-dirt"),this.lensShelteredInput=this.shadow.getElementById("lens-sheltered"),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.evaluationFields=new ms(this.shadow.getElementById("profile-section"),this.shadow.getElementById("testimony-section"),this.shadow.getElementById("strangeness-section"),()=>this.updateObserverMetadata()),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.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.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.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.labelPosition=this.shadow.getElementById("label-position"),this.observerPosition=this.shadow.querySelector(`${E0}[name="observer"]`),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.wholeKeyframesInput=this.shadow.getElementById("whole-keyframes");try{this.wholeKeyframesInput.checked=localStorage.getItem(xe.WHOLE_KEYFRAMES_STORAGE)==="true"}catch{}this.wholeKeyframesInput.addEventListener("change",()=>this.setKeyframesWritten()),this.labelNarrativeSource=this.shadow.getElementById("label-narrative-source"),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.snapshotsPanel=new cs(this.shadow.getElementById("snapshot-data"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,sources:()=>this.snapshotSources(),upperAirHeard:()=>this.sceneElement.upperAirHeard,changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleFileSync(),this.refreshFileItems()},base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o)}),this.sectionFilePanel=new Mg(this.shadow.getElementById("file-section"),{sighting:()=>this.ufoElement.sighting,documentUrl:()=>this.sceneElement.documentUrl,base:()=>this.fileBase(),masterUrl:()=>this.masterUrl(),download:(a,o)=>this.download(a,o),changed:a=>{if(this.touch(),this.ufoElement.refresh(),a==="weather"&&(this.syncWeatherFromTimeline(),this.syncWeatherSourceState()),a==="place"&&this.syncPlaceNameField(),a==="lightPollution"){const o=this.ufoElement.sighting.lightPollution;this.lightPollutionInput.value=o===void 0?"":String(o),this.scheduleLightPollutionLookup()}this.scheduleFileSync(),this.refreshFileItems()}});const i={sighting:()=>this.ufoElement.sighting,editing:()=>this.armHistory(),changed:()=>{this.touch(),this.ufoElement.refresh(),this.scheduleHistoryRecord(),this.refreshTimelineMarks(),this.scheduleFileSync(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render()},seek:a=>this.goToMark(a),now:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,currentBody:()=>this.bodyEditor?.selectedId??this.ufoElement.sighting.interpretation?.bodies[0]?.id,currentShapes:()=>{const a=this.ufoElement.sighting.timeline;return a.sourceIds.includes(this.currentSourceId)?a.topOf(this.currentSourceId):void 0},shapesLabel:a=>this.shapesLabel(a),picked:()=>this.refreshTracks(),positionFrame:()=>this.positionFrame(),positionMessages:()=>this.messages,compassPoint:a=>this.naming.point(a),lookedAt:()=>{const a=this.ufoElement.sighting.observerTrack.getInterpolatedPoseAt(this.ufoElement.currentTime);return a?.headingDeg===void 0||a.pitchDeg===void 0?void 0:{azimuthDeg:a.headingDeg,altitudeDeg:a.pitchDeg}},bodyLabel:a=>{const o=this.ufoElement.sighting.interpretation?.bodies.find(c=>c.id===a);return this.said.read(o?.title)??a}};this.eventsPanel=new to(this.shadow.getElementById("events-section"),i,void 0),this.phenomenonEventsPanel=new to(this.shadow.getElementById("phenomenon-events-section"),i,void 0,"phenomenon"),this.bodiesEventsPanel=new to(this.shadow.getElementById("bodies-events-section"),i,void 0,"bodies"),this.samplingRateInput.addEventListener("change",()=>{const a=Number(this.samplingRateInput.value);i.editing(),this.ufoElement.sighting.sampleMs=Number.isFinite(a)&&a>0?a:void 0,ht.refresh(this.ufoElement.sighting),i.changed()}),this.fileItemSelect=this.shadow.getElementById("file-item"),this.fileItemSelect.addEventListener("change",()=>this.showFileItem(this.fileItemSelect.value)),this.snapshotsPanel.localize(this.messages),this.sectionFilePanel.localize(this.messages),this.refreshFileItems(),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",a=>{a.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.labelPrecipitationGroup=this.shadow.getElementById("label-precipitation-group"),this.labelWindGroup=this.shadow.getElementById("label-wind-group"),this.aircraftFlights=new PF(this.shadow.getElementById("aircraft-flights"),a=>this.aimAtFlight(a),a=>this.naming.point(a)),this.labelWeatherInferred=this.shadow.getElementById("label-weather-inferred"),this.weatherProviderSelect=this.shadow.getElementById("weatherSource"),this.weatherFileLink=this.shadow.getElementById("weather-file-link"),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 gn({header:this.shadow.getElementById("decor-list-header"),body:this.shadow.getElementById("decor-item"),ids:{list:"decor",remove:"delete-decor",add:"add-decor-building",kinds:"decorKind",kind:a=>`option-decor-${a}`},actions:[{id:"look-at-decor",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectDecor(a),onAdd:a=>this.addDecor(a),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:"trafficlight",label:"Traffic light"},{value:"crossing",label:"Pedestrian crossing"},{value:"roadsign",label:"Road sign"},{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",empty:"No decor",actions:{"look-at-decor":"Look at it"}}),this.observerList=new gn({header:this.shadow.getElementById("observer-list-header"),body:this.shadow.getElementById("observer-item"),ids:{list:"observer-pick",remove:"delete-observer",add:"add-decor-observer"},actions:[{id:"look-at-observer",glyph:"🎯",onClick:()=>this.lookAtDecor()}],onSelect:a=>this.selectObserver(a),onAdd:()=>this.addDecor("observer"),onRemove:()=>this.deleteDecor()}),this.observerList.setLabels({list:"Observer",remove:"Delete observer",add:"Add observer",actions:{"look-at-observer":"Look at it"}}),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 dn(this.sceneryStatus,{decor:()=>this.ufoElement.sighting.decor,setDecor:a=>this.setPlantedDecor(a),kindName:a=>this.decorList.kindLabel(a),cite:a=>this.citeSource(a),busy:(a,o)=>this.sceneElement.setBusy(a,o),centre:()=>this.plantingCentre(),track:()=>this.ufoElement.sighting.observerTrack.toJSON().keyframes.map(a=>({lat:a.pose.lat,lng:a.pose.lng})).filter(a=>typeof a.lat=="number"&&typeof a.lng=="number")},this.messages,async(a,o)=>this.surroundingsProvider?this.surroundingsProvider.covers(a,o)?this.surroundingsProvider:void 0:(await Q(async()=>{const{SurroundingsSources:c}=await import("./surroundingsSources-DXpzMDPy.js");return{SurroundingsSources:c}},[],import.meta.url)).SurroundingsSources.providerFor(this.sceneryChoice,a,o),{radiusM:Number(this.sceneryRadius.value)}),this.sceneryChoice=this.readSceneryChoice(),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-file-link").addEventListener("click",()=>this.openFileItem("decor")),this.scenerySource.addEventListener("change",()=>{const a=this.scenerySource.value===xe.FILE_SOURCE;if(this.setDecorFromFile(a),a){this.syncSceneryPicker();return}if(this.sceneryChoice=this.scenerySource.value,this.writeSceneryChoice(this.sceneryChoice),this.surroundings.setEnabled(this.sceneryAsked()),this.syncSceneryPicker(),this.sceneryChoice===xe.NO_SCENERY){this.surroundings.withdraw();return}const o=this.plantingCentre();o&&this.surroundings.survey(o.lat,o.lng)}),this.sceneryRadius.addEventListener("input",()=>{const a=Number(this.sceneryRadius.value);if(!Number.isFinite(a)||a<20)return;this.writeSceneryRadius(this.sceneryRadius.value);const o=this.plantingCentre();this.surroundings.radiusChanged(a,o?.lat,o?.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.referenceSourceInput=this.shadow.getElementById("reference-source"),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.referenceVideoFromInput=this.shadow.getElementById("referenceVideoFrom"),this.referenceVideoToInput=this.shadow.getElementById("referenceVideoTo"),this.referenceVideoRateInput=this.shadow.getElementById("referenceVideoRate"),this.referenceRemoveKeyButton=this.shadow.getElementById("reference-remove-key"),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.referenceFailure=this.shadow.getElementById("reference-failure"),this.addReferenceButton=this.shadow.getElementById("add-reference"),this.referenceAddMenu=new Yp(this.addReferenceButton,"reference-add-kind",a=>this.addReferenceOfKind(a),a=>({address:"reference-add-address",file:"reference-add-file-option",street:"reference-add-street"})[a]??`reference-add-${a}`),this.setReferenceAddKinds("From an address","From a file","Street-level pictures nearby"),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.findGhostsButton=this.shadow.getElementById("reference-find-ghosts"),this.ghostsStatus=this.shadow.getElementById("reference-ghosts-status"),this.findGhostsButton.addEventListener("click",()=>void this.findGhosts()),this.ghostsShownButton=this.shadow.getElementById("reference-ghosts-shown"),this.ghostsShownButton.addEventListener("click",()=>{this.ghostsShown=!this.ghostsShown,this.syncGhostsShown(),this.ufoElement.refresh()}),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.traceImportInput=this.shadow.getElementById("trace-import"),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.addTraceButton=this.shadow.getElementById("add-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.referenceKindSelect,this.referenceCreditInput,this.referenceCreditUrlInput,this.referenceTInput,this.referenceVideoFromInput,this.referenceVideoToInput,this.referenceVideoRateInput,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 xp(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 ga(this.decorParametersHost,"en","decorParam.");const s={said:()=>this.said,writingLanguage:()=>this.writingLanguage};this.decorBaseHost=this.shadow.getElementById("decor-base"),this.decorStateHost=this.shadow.getElementById("decor-state"),this.decorBaseForm=new ga(this.decorBaseHost,"en","decorBase.",s,(a,o)=>this.enhanceDecorModelChoice(a,o)),this.decorStateForm=new ga(this.decorStateHost,"en","decorState.",s),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",a=>{this.focus({preventScroll:!0}),this.onPointerDown(a)}),this.ufoElement.canvasElement.addEventListener("pointermove",a=>this.onPointerMove(a));let n;this.ufoElement.canvasElement.addEventListener("pointerdown",a=>{n={x:a.clientX,y:a.clientY,playing:this.ufoElement.playbackState==="playing"}}),this.ufoElement.canvasElement.addEventListener("click",a=>{const o=n;n=void 0,!(!o?.playing||this.isRecording||this.ufoElement.playbackState!=="playing")&&(Math.hypot(a.clientX-o.x,a.clientY-o.y)>xe.CLICK_SLOP_PX||(this.ufoElement.togglePlayPause(),this.syncPlaybackControls()))}),this.ufoElement.canvasElement.addEventListener("contextmenu",a=>this.onContextMenu(a)),this.contextGroupButton.addEventListener("click",()=>this.groupSelected()),this.contextUngroupButton.addEventListener("click",()=>this.ungroupSelected()),this.contextDuplicateButton.addEventListener("click",()=>this.duplicateSelected()),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.deleteShapeButton.addEventListener("click",()=>this.deleteShape()),this.exportButton.addEventListener("click",()=>this.exportJson()),this.saveButton.addEventListener("click",()=>this.exportJson()),this.shareButton.addEventListener("click",()=>this.openShare()),this.importInput.addEventListener("filepick",a=>{const o=a.detail;o.file?this.importFromFile(o.file):this.importFromUrl(o.url)}),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()});for(const a of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])a.addEventListener(a instanceof HTMLSelectElement||a.type==="checkbox"?"change":"input",()=>this.updateLens());this.lightPollutionInput.addEventListener("input",()=>{const a=this.ufoElement.sighting;a.lightPollution=this.numberOrUndefined(this.lightPollutionInput.value),a.provenance.clear("lightPollution"),this.lightPollutionLookup=void 0,this.ufoElement.refresh(),a.lightPollution===void 0?this.scheduleLightPollutionLookup():this.syncLightPollutionStatus()}),this.narrativeDraftButton.addEventListener("click",()=>this.draftFromDescription()),this.narrativeStopButton.addEventListener("click",()=>this.narrativeAbort?.abort()),this.renderNarrativeSettings(),this.durationElement.addEventListener("durationchange",a=>{const{seconds:o,text:c}=a.detail;this.ufoElement.sighting.event.durationText=c,this.ufoElement.durationSeconds=o,this.ufoElement.sighting.timeline.hasSpan&&this.ufoElement.sighting.timeline.setSpan((o??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.shapeRotationInput.addEventListener("input",()=>this.updateShapeRotation()),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.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 a of this.referenceFields)a.addEventListener("input",()=>this.updateReference());this.referenceUsePoseButton.addEventListener("click",()=>this.useObserverPoseForReference()),this.referenceRemoveKeyButton.addEventListener("click",()=>this.removeReferenceKey()),this.referenceSourceInput.addEventListener("filepick",a=>void this.setReferenceSource(a.detail)),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.addTraceButton.addEventListener("click",()=>{const a=this.shadow.getElementById("trace-import-row");a.hidden=!1,this.traceImportInput.mode==="file"?this.traceImportInput.openPicker():this.traceImportInput.focus()}),this.traceImportInput.addEventListener("filepick",a=>void this.addTraces(a.detail)),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",a=>this.onReferenceWheel(a),{passive:!1}),this.ufoElement.canvasElement.addEventListener("wheel",a=>this.onBodyWheel(a),{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 a of[this.milestoneLabelInput,this.milestoneNoteInput])a.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(xI,()=>this.showAircraftStatus()),this.sceneElement.addEventListener(MI,()=>{const a=this.currentReference();a&&this.syncReferenceStatus(a)}),this.sceneElement.addEventListener(wI,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.sceneElement.addEventListener(yI,()=>{this.skyCandidatesKey=void 0,this.refreshSkyCandidates()}),this.ufoElement.addEventListener("timeupdate",()=>{this.onSelectionOrTimeChanged(),this.syncVideoRegistrationFields(),this.syncPlaybackControls(),this.scheduleFileSync(),this.dispatchEvent(new CustomEvent("sightingchange"))}),this.addEventListener("keydown",this.handleKeyDown),this.shapeAddMenu=new Yp(this.addShapeButton,"add-shape-kind",a=>{const o=Co.byId(a);if(o){this.addModel(o);return}this.currentAppearance={...this.currentAppearance,presetId:a},this.addShape()},a=>`add-shape-${a}`),this.shapeAddMenu.setKinds(this.shapeAddKinds()),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 a of[this.latInput,this.lngInput,this.headingInput,this.pitchInput,this.rollInput,this.elevationInput])a.addEventListener("input",()=>this.updateObserver());for(const a of[this.focalLengthInput,this.fNumberInput,this.exposureInput,this.focusDistanceInput])a.addEventListener("input",()=>this.updateObserver());this.isoInput.addEventListener("input",()=>this.updateExposureSettings()),this.filmStockSelect.addEventListener("change",()=>this.updateExposureSettings()),this.meteringSelect.addEventListener("change",()=>this.updateExposureSettings()),this.observerPosition.addEventListener("positionchange",a=>{if(this.observerSaid=a.detail.said,!this.observerPosition.relative)return;const o=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(o,this.plantingCentre())}),this.observerPosition.addEventListener("basischange",a=>this.writeObserverBasis(a.detail.basis)),this.searchPlaceButton.addEventListener("click",()=>void this.searchPlace()),this.placeNameInput.addEventListener("keydown",a=>{a.key==="Enter"&&(a.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 a=this.ufoElement.sighting.instrument;this.ufoElement.sighting.instrumentId=this.instrumentSelect.value;const o=new Map(this.ufoElement.sighting.timeline.allKeyframes.map(c=>[c.t,Ti.fovOf(this.ufoElement.sighting,c.t)]));this.retuneFieldOfView(a),this.retuneExposure(a),Ti.reproject(this.ufoElement.sighting,a,o),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.accountCompareInput.addEventListener("change",()=>this.syncBodiesShown()),this.utcOffsetInput.addEventListener("input",()=>this.updateUtcOffset()),this.timeZoneSelect.addEventListener("change",()=>{this.autoFilledTimeZone=void 0,this.updateTimeZone()});const r=a=>this.shadow.querySelector(`${M0}[name="${a}"]`);this.startDate=r("obs-time"),this.endDate=r("obs-end-time"),this.birthDate=r("observer-birth"),this.perceptionSettings=this.shadow.getElementById("observerPerception"),this.perceptionSettings.providers=ya.ALL,this.applyPerceptionLabels(),this.perceptionSettings.addEventListener("settingschange",()=>this.updateObserverMetadata());for(const a of["input","change"])this.shadow.getElementById("obs-time-native")?.addEventListener(a,()=>{this.syncWeatherSourceState(),this.weatherFromRecords&&this.ufoElement.sighting.weatherSource===void 0&&this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered()&&this.scheduleWeatherLookup()});this.startDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.time=o}),this.syncAgeFromBirth(!0)}),this.birthDate.addEventListener("datechange",a=>{this.birth=a.detail.time,this.syncAgeFromBirth(!1),this.updateObserverMetadata()}),this.observerAgeInput.addEventListener("input",()=>this.syncBirthFromAge()),this.endDate.addEventListener("datechange",a=>{const{time:o}=a.detail;this.editDate(()=>{this.ufoElement.sighting.event.endTime=o})});for(const a of[this.observerIdInput,this.observerTitleInput,this.observerLastNameInput,this.observerFirstNamesInput,this.observerAgeInput,this.observerOccupationInput,this.sightingIdInput])a.addEventListener("input",()=>{this.updateObserverMetadata(),this.observerList.rename(xe.OBSERVER_PRINCIPAL,this.principalObserverLabel())});this.descriptionInput.addEventListener("input",()=>{this.updateDescription(),this.syncNarrativeEnabled()}),this.tagsInput.addEventListener("input",()=>this.updateTags());for(const a of this.weatherFields){if(a===this.iceCrystalAlignmentInput||a===this.rareIceCrystalsInput){a.addEventListener("input",()=>this.applyIceAlignmentAtPlayhead());continue}a.addEventListener("input",()=>this.applyWeatherAtPlayhead())}for(const a of this.soundFields)a.addEventListener("input",()=>this.applySoundAtPlayhead());this.weatherInferredInput.addEventListener("change",()=>this.onWeatherInferredToggled()),this.weatherProviderSelect.addEventListener("change",()=>this.onWeatherProviderChosen()),this.weatherFileLink.addEventListener("click",()=>this.openFileItem("weather")),this.groupTabs=[...this.shadow.querySelectorAll(".group-tab")],this.groupPanels=this.groupTabs.map(a=>this.shadow.getElementById(a.getAttribute("aria-controls")));for(const a of this.groupTabs)a.addEventListener("click",()=>this.toggleGroup(a,!this.isGroupOpen(a)));new ResizeObserver(()=>this.fitGroupTabs()).observe(this.groupTabs[0].parentElement),this.subgroupTabs=[...this.shadow.querySelectorAll(".subgroup-tab")];for(const a of this.subgroupTabs)a.addEventListener("click",()=>this.openSubgroup(a));this.buildSkyParts(),fn.fit(this.shadow),this.paramSummary=this.shadow.getElementById("param-summary"),this.paramSummary.addEventListener("click",a=>this.onParamSummaryClick(a)),this.toggleGroup(this.groupTabs[this.groupPanels.findIndex(a=>a.id==="group-shape")],!0),this.sectionChosen=!1,this.opensMostLacking=!0,this.attachWitnessErrors(),this.fileEditorHost.addEventListener("focusout",()=>this.leaveFileEditor()),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=C5(this.shadow.getElementById("cloud-editor"),this.sceneElement,(a=!0)=>{a&&(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState())},(a,o)=>{this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),this.updateObserver()},jd(yr.preferencesFor(this),qd),this.framePlace()),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.ready=this.loadLocaleMessages())}static get observedAttributes(){return["src"]}connectedCallback(){this.hasAttribute("tabindex")||(this.tabIndex=-1),yr.preferencesFor(this).join()!==this.preferences.join()&&(this.ready=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),Ye.changes.addEventListener("change",this.onModulesChanged),Q(async()=>{const{ModuleSession:t}=await import("./ModuleSession-BXk5ijvF.js");return{ModuleSession:t}},[],import.meta.url).then(({ModuleSession:t})=>t.shared.start(),()=>{});const e=this.getAttribute("src");e&&this.importFromUrl(e)}relisters=[];onModulesChanged=e=>{for(const i of this.relisters)i();const t=e.detail;t==="weather"&&(this.followWeatherRecord(),this.fillWeatherProvider()),t==="surroundings"&&this.surveyIds&&this.fillScenerySources(),t==="decorModels"&&this.sceneElement.setDecorModelProvider(this.decorModelProvider),(t==="skyEvents"||t==="interpretations")&&this.buildSkyParts(),t==="perception"&&(this.perceptionSettings.providers=ya.ALL,this.applyPerceptionLabels())};attributeChangedCallback(e,t,i){e==="src"&&i&&i!==t&&this.isConnected&&this.importFromUrl(i)}disconnectedCallback(){window.removeEventListener("beforeunload",this.warnBeforeLeaving),Ye.changes.removeEventListener("change",this.onModulesChanged),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),clearTimeout(this.moduleNamingTimer),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){const t=Oi.toCurrent(e);this.sourceUrl=void 0,this.endDrag(),this.ufoElement.sightingData=t,this.sceneElement.requireModules(t.modules),this.sceneElement.applyFrameFormat(),this.cloudEditor.reset(),this.bodyEditor?.sync(),this.syncModulesPanel(),this.syncBodiesShown(),this.isGroupIdOpen("group-shape")&&this.showPhenomenonPartWithContent(),this.eventsPanel.render(),this.phenomenonEventsPanel.render(),this.bodiesEventsPanel.render(),this.currentSourceId=this.ufoElement.sighting.timeline.sourceIds[0]??$u,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.placeZone=void 0,this.timeZoneLookedUpAt=void 0,this.refreshTimeZoneOptions(),this.syncUtcOffsetField(),this.syncPlaceNameField(),this.syncGroundElevationField(),this.scheduleTimeZoneLookup(!1);const i=this.plantingCentre();this.surroundings.placeLoaded(i?.lat,i?.lng),this.syncSceneryPicker(),this.syncWeatherOwnership(),this.snapshotsPanel.render(),this.refreshFileItems(),this.markClean(),this.sectionChosen||(this.opensMostLacking=!0)}baseline="";touched=!1;guardsLeaving=!0;get dirty(){return this.touched&&this.fileText()!==this.baseline}get edited(){return this.touched}markClean(){this.applyingFileText||(this.baseline=this.fileText(),this.touched=!1,this.savedFileText=this.baseline,this.fileEditor?.markSaved(),this.refreshEditorHead())}set embedded(e){this.shadow.getElementById("editor-head").hidden=e,this.shadow.querySelector(".app").classList.toggle("embedded",e),e||this.shadow.querySelector("#editor-head .head-actions").prepend(this.historyControls)}get historyControls(){return this.undoButton.parentElement}refreshEditorHead(){this.saveButton&&(this.refreshEditorTitle(),this.saveButton.disabled=!this.dirty,this.shareButton.disabled=this.sourceUrl===void 0,this.shareButton.title=this.sourceUrl===void 0?this.shareMessages?.unavailable??"":"")}sourceUrl;shareButton;shareDialog;shareMessages;shareSubject={module:"rr0-sighting-editor",link:()=>`${Yd.home()}/edit/?file=${encodeURIComponent(this.sourceUrl??"")}`,element:()=>`<rr0-sighting-editor src="${this.sourceUrl??""}"></rr0-sighting-editor>`};openShare(){this.sourceUrl!==void 0&&(this.shareDialog.note=this.dirty?this.shareMessages?.unsaved:void 0,this.shareDialog.open())}refreshEditorTitle(){const e=this.ufoElement.sighting.event,t=e.place?.[0]?.name?.split(",")[0].trim(),i=e.time;let s="";i?.year!==void 0&&(s=i.month!==void 0&&i.day!==void 0?new Date(Date.UTC(i.year,i.month-1,i.day)).toLocaleDateString(this.language,{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"}):String(i.year));const n=[t,s].filter(Boolean).join(", ")||this.sightingIdInput.value||this.messages.stateNew,r=this.shadow.getElementById("editor-title");r.textContent!==n&&(r.textContent=n)}savedFileText;touch=()=>{this.touched=!0};armHistory=()=>{this.historySnapshot??=this.fileText(),this.fileEditor===void 0&&this.loadFileEditor().then(()=>{this.recordHistory(),this.syncHistoryButtons()},()=>{})};scheduleHistoryRecord=()=>{this.scheduleModuleNaming(),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(),this.refreshEditorHead())}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(),this.refreshEditorHead())}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=this.shadow.getElementById("save-refused"),t=Vt.issues(this.ufoElement.sighting);if(Ht.show(e,t.length===0?void 0:this.messages.saveRefused.replace("{reasons}",t.map(s=>this.actorIssue(s)).join(" ; ")),"error"),t.length>0)return;const i=rs.inspect(this.sightingData,this.loadedJson());if(i.length===0){this.downloadJson();return}this.askAboutIdentity(i)}actorIssue(e){const t=this.messages;if(e.kind==="duplicate-id")return t.duplicateId.replace("{id}",e.id).replace("{kinds}",e.path.split(", ").map(n=>t.actorKinds[n]??n).join(", "));const i=Number(e.path.split(".")[1]),s=this.ufoElement.sighting.events?.[i];return t.unknownWho.replace("{n}",String(i+1)).replace("{kind}",(s&&t.events.kinds[s.eventType])??s?.eventType??"").replace("{id}",e.id)}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(n=>{const r=document.createElement("li");return r.textContent=t[n.kind].replaceAll("{value}",n.found),r}));const s=e.some(n=>["lastName","firstNames","nameInId","nameInText"].includes(n.kind));this.shadow.getElementById("identity-ask-initials").hidden=!s,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=rs.namesOf(this.sightingData);this.observerLastNameInput.value=rs.withInitials(this.observerLastNameInput.value,e),this.observerFirstNamesInput.value=this.observerFirstNamesInput.value.split(",").map(t=>rs.withInitials(t.trim(),e)).join(", "),this.observerIdInput.value=rs.withInitials(this.observerIdInput.value,e,!0),this.sightingIdInput.value=rs.withInitials(this.sightingIdInput.value,e,!0),this.descriptionInput.value=rs.withInitials(this.descriptionInput.value,e),this.touch(),this.updateObserverMetadata(),this.descriptionInput.dispatchEvent(new Event("input"))}async downloadJson(){const e=this.fileBase();let t=new Map;if(this.snapshotsPanel.hasWork()){this.exportButton.disabled=!0;try{t=await this.snapshotsPanel.prepare(e)}finally{this.exportButton.disabled=!1}}const i=this.sightingData;for(const r of Yt.NAMES){const a=this.sectionFilePanel.annex(r);a&&(/^[a-z][a-z0-9+.-]*:/i.test(a.src)||t.set(a.src,a.bytes),Yt.strip(r,i))}const s=`${e}.json`,n=this.writtenText(i);if(t.size===0)this.download(new Blob([n],{type:"application/json"}),s);else{const{zipSync:r,strToU8:a}=await Q(async()=>{const{zipSync:h,strToU8:d}=await import("./browser-_Ncw3Jhn.js");return{zipSync:h,strToU8:d}},[],import.meta.url),o={[s]:a(n)};for(const[h,d]of t)o[h]=d;const c=r(o,{level:0});this.download(new Blob([c],{type:"application/zip"}),`${e}.zip`),this.showFileNote(this.messages.snapshotExported.replaceAll("{count}",String(t.size)).replaceAll("{size}",cs.size(c.length)))}this.markClean()}fileBase(){const e=this.sceneElement.documentUrl?.split(/[?#]/)[0].split("/").pop();return e?.endsWith(".json")&&e.length>5?decodeURIComponent(e.slice(0,-5)):`${this.sightingData.observer?.id??"sighting"}-sighting`}refreshFileItems(){const e=this.fileItemSelect;if(!e||!this.worded)return;this.syncFilePickers();const t=e.value||"recording";e.replaceChildren(new Option(this.messages.fileItemRecording,"recording"),...Yt.NAMES.map(i=>new Option(this.sectionFilePanel.itemLabel(i),i)),...os.NAMES.map(i=>new Option(this.snapshotsPanel.itemLabel(i),i)),new Option(this.messages.fileItemModules,xe.MODULES_ITEM)),e.value=t,this.showFileItem(e.value)}showFileItem(e){const t=os.NAMES.includes(e),i=Yt.NAMES.includes(e)?e:void 0,s=e===xe.MODULES_ITEM;this.shadow.getElementById("file-recording").hidden=t||i!==void 0||s,this.shadow.getElementById("snapshot-data").hidden=!t,this.shadow.getElementById("file-section").hidden=i===void 0,this.shadow.getElementById("file-modules").hidden=!s,s&&this.loadModulesPanel();for(const r of["file-recording","snapshot-data","file-section","file-modules"]){const a=this.shadow.getElementById(r);a.hidden||gn.glue(a)}t&&this.snapshotsPanel.show(e),i&&this.sectionFilePanel.show(i);const n=t&&this.snapshotsPanel.isInlineGroup(e)?["snapshots",e,"src"]:i&&this.sectionFilePanel.isInline(i)?Mg.pathOf(i):void 0;this.fileEditorHost.hidden=(t||i!==void 0||s)&&n===void 0,n&&this.isGroupIdOpen("group-file")&&this.loadFileEditor().then(r=>{this.syncFileEditor(!1),r.reveal(n)},()=>{})}moduleNamingTimer;scheduleModuleNaming(){clearTimeout(this.moduleNamingTimer),this.moduleNamingTimer=setTimeout(()=>void this.nameModulesOfModels(),400)}async nameModulesOfModels(){const e=this.decorModelProvider;if(!(e instanceof mp)||Ye.installed().length===0)return;const t=this.ufoElement.sighting,i=new Set([...t.decor.map(r=>r.model?.id),...(t.interpretation?.bodies??[]).map(r=>r.model?.id)].filter(r=>typeof r=="string")),s=this.sceneElement.documentUrl;let n=t.modules;for(const r of i){const a=await e.moduleOf(r),o=a===void 0?void 0:Ye.installed().find(c=>c.id===a)?.url;!o||MA.names(n,o,s)||(n=[...n??[],MA.of(o,s)])}n===t.modules||this.ufoElement.sighting!==t||(t.modules=n,this.syncModulesPanel(),this.syncFileEditor(!1))}static MODULES_ITEM="modules";modulesPanel;modulesPanelLoading;loadModulesPanel(){return this.modulesPanelLoading??=Q(async()=>{const{register:e,ModulesPanelElement:t}=await import("./ModulesPanelElement-B1KHXTpq.js");return{register:e,ModulesPanelElement:t}},__vite__mapDeps([25,26]),import.meta.url).then(({register:e,ModulesPanelElement:t})=>{e();const i=this.shadow.getElementById("modules-panel");this.modulesPanel=i,i.addEventListener("recordingmoduleschange",()=>{const s=i.recordingModules;this.ufoElement.sighting.modules=s.length>0?s:void 0,this.syncFileEditor(!1)}),i.checkContext=()=>({weatherQuery:this.weatherInference.queryOf(this.ufoElement.sighting),interpretation:this.ufoElement.sighting.interpretation}),i.setLanguage(this.language),this.syncModulesPanel()}),this.modulesPanelLoading}syncModulesPanel(){this.modulesPanel&&(this.modulesPanel.base=this.sceneElement.documentUrl,this.modulesPanel.recordingModules=this.ufoElement.sighting.modules)}sectionFromFile(e){return Yt.fromFile(this.ufoElement.sighting.snapshots,e)}masterUrl(){return this.sceneElement.documentUrl??new URL(`${this.fileBase()}.json`,location.href).href}weatherFileItemLabel(){return this.sectionFilePanel?.itemLabel("weather")??""}download(e,t){const i=URL.createObjectURL(e),s=document.createElement("a");s.href=i,s.download=t,s.click(),URL.revokeObjectURL(i)}snapshotSources(){const e=zi(Km,this.chosenSourceId.get("elevation"));return{elevation:e.create(),elevationCredit:e.credit,imagery:zi(qc,this.chosenSourceId.get("imagery")).id,roads:KT(),water:XT(),railways:YT()}}async importFromFile(e){this.holdLoad(()=>void this.loadFile(e))||await this.loadFile(e)}async loadFile(e){this.showLoadError(void 0);try{const t=new Uint8Array(await new Promise((n,r)=>{const a=new FileReader;a.onload=()=>n(a.result),a.onerror=()=>r(a.error),a.readAsArrayBuffer(e)}));Ct.release();const i=await this.recordingText(t),s=JSON.parse(i);if(Vi.isCase(s)){if(Vi.check(s),this.offerCase(s,void 0))return;throw new Error("A case has no recording to edit here")}this.sceneElement.documentUrl=void 0,this.sightingData=s,this.resetHistory(),this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0})),this.importInput.url=""}catch(t){this.showLoadError(t)}}async recordingText(e){if(e[0]!==80||e[1]!==75)return new TextDecoder().decode(e);const{unzipSync:t,strFromU8:i}=await Q(async()=>{const{unzipSync:d,strFromU8:u}=await import("./browser-_Ncw3Jhn.js");return{unzipSync:d,strFromU8:u}},[],import.meta.url),s=t(e),n=/\.(relief|imagery|map)\.zip$|\.(roads|water|railways|upper-air|weather|place|light-pollution|decor)\.json$/,r=Object.keys(s).find(d=>d.endsWith(".json")&&!n.test(d));if(!r)throw new Error("No recording in this archive");const a=r.includes("/")?r.slice(0,r.lastIndexOf("/")+1):"";for(const[d,u]of Object.entries(s))d!==r&&d.startsWith(a)&&Ct.hold(Ct.address(d.slice(a.length),void 0),u);const o=i(s[r]),c=JSON.parse(o);let h=!1;for(const d of Yt.NAMES){const u=c.snapshots?.[d]?.src,p=u!==void 0?s[a+u]:void 0;if(!p)continue;const f=Oi.toCurrent(JSON.parse(i(p)));Yt.put(d,c,f),h=!0}return h?JSON.stringify(c):o}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.importInput.url){e&&(this.holdLoad(()=>void this.loadUrl(e))||await this.loadUrl(e))}async loadUrl(e){this.showLoadError(void 0);try{const t=await Ma.recording(e);if(Vi.isCase(t)){Vi.check(t);const s=new URL(e,location.href).href;if(this.offerCase(t,s)){this.importInput.url=s;return}throw new Error("A case has no recording to edit here")}const i=t;Ct.release(),this.sceneElement.documentUrl=new URL(e,location.href).href,this.sightingData=i,this.sourceUrl=new URL(e,location.href).href,this.resetHistory(),this.importInput.url=new URL(e,location.href).href,this.refreshEditorHead(),this.dispatchEvent(new CustomEvent("recordingloaded",{bubbles:!0,composed:!0}))}catch(t){this.showLoadError(t)}}loadError;showLoadError(e){this.loadError=e===void 0?void 0:{error:e},this.sayLoadError()}sayLoadError(){Ht.show(this.shadow.getElementById("load-error"),this.loadError&&this.importErrorFor(this.loadError.error),"error")}importErrorFor(e){if(e instanceof Sp)return e.said(this.messages.formatVersionError);if(!(e instanceof Sc))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=Nf[0].create();get narrativeSourceId(){return zi(Nf,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:xe.LANGUAGE_NAMES.of(this.showerLanguage())??"English",settings:this.narrativeSettingValues()},t.signal);this.applyNarrativeDraft(i)}catch(i){const s=i instanceof Ir&&i.kind==="cancelled";this.narrativeStatus.textContent=s?"":this.narrativeErrorFor(i),this.narrativeStatus.classList.toggle("error",!s)}finally{this.narrativeAbort=void 0,this.setNarrativeBusy(!1)}}applyNarrativeDraft(e){const{description:t,...i}=e.recording,{utcOffsetHours:s,...n}=i,r=i.timeZone?n:i,a=Ba.stated(r);if(a.length>0){const o=this.ufoElement.sighting.provenance,c=Tb(this.ufoElement.sighting);this.sightingData=Ba.apply(c,O0.loadable(r),a),this.ufoElement.sighting.provenance=o,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,s=new Set(t);for(const n of e.claims)!s.has(n.path)&&!t.some(r=>n.path.startsWith(`${r}.`))||i.provenance.set(n.path,{basis:n.basis,rationale:n.rationale,of:xe.valueAt(Tb(this.ufoElement.sighting),n.path)})}static valueAt(e,t){let i=e;for(const s of t.split(".")){if(typeof i!="object"||i===null)return;i=i[s]}return i}showNarrativeReport(e){this.narrativeReport.replaceChildren();for(const t of["assumed","derived","stated"]){const i=e.claims.filter(s=>s.basis===t);if(i.length!==0){this.narrativeReport.append(this.narrativeHeading(this.messages[BU[t]]));for(const s of i){const n=document.createElement("div");n.className=`claim ${t}`;const r=document.createElement("code");r.textContent=s.path;const a=document.createElement(t==="stated"?"q":"span");a.textContent=s.rationale,n.append(r,a),this.narrativeReport.append(n)}}}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 s=document.createElement("li");s.textContent=i,t.append(s)}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=zi(Nf,this.chosenSourceId.get("narrative")).name,t=this.narrativeProvider.settings.find(s=>s.required&&(this.narrativeSettingInputs.get(s.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:"";for(const s of this.narrativeProvider.settings){const n=this.narrativeSettingInputs.get(s.id);if(!n||!s.suspect)continue;const r=n.value.trim(),a=r===""?void 0:s.suspect(r);n.classList.toggle("invalid",a!==void 0),n.title=a?this.said.read(a)??"":this.said.read(s.hint)??""}}renderNarrativeSettings(){const e=this.narrativeSettingValues();this.narrativeSettingInputs=new Map;const t=this.narrativeProvider.settings.map(i=>{const s=document.createElement("label"),n=document.createElement("span");n.textContent=this.said.read(i.label)??i.id;let r;if(i.kind==="choice"){r=document.createElement("select");for(const o of i.choices??[]){const c=document.createElement("option");c.value=o.value,c.textContent=this.said.read(o.label)??o.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),s.append(n,document.createTextNode(" "),r),s});this.narrativeSettingsBox.replaceChildren(...t),this.forgetStoredCredentials(),this.syncNarrativeEnabled()}narrativeSettingValues(){const e={};for(const[t,i]of this.narrativeSettingInputs){const s=i.value.trim();s!==""&&(e[t]=s)}return e}narrativeErrorFor(e){if(!(e instanceof Ir))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}}static pageCredentials=new Map;static forgetCredentials(){xe.pageCredentials.clear(),$o.forget()}rememberNarrativeSettings(){for(const e of this.narrativeProvider.settings){const t=this.narrativeStorageKey(e.id),i=this.narrativeSettingInputs.get(e.id)?.value??"";if(e.remembered==="credential")i!==""?xe.pageCredentials.set(t,i):xe.pageCredentials.delete(t);else if(e.remembered==="preference")try{i!==""?localStorage.setItem(t,i):localStorage.removeItem(t)}catch{}}}forgetStoredCredentials(){try{for(const e of this.narrativeProvider.settings)e.remembered==="credential"&&localStorage.removeItem(this.narrativeStorageKey(e.id));localStorage.removeItem(xe.NARRATIVE_KEY_STORAGE),localStorage.removeItem(xe.NARRATIVE_SCOPE_STORAGE)}catch{}}narrativeStorageKey(e){return`rr0-sighting-editor.narrative.${this.narrativeSourceId}.${e}`}storedNarrativeSetting(e){const t=this.narrativeStorageKey(e),i=this.narrativeProvider.settings.find(s=>s.id===e);if(i?.remembered==="credential")return xe.pageCredentials.get(t);if(i?.remembered==="preference")try{return localStorage.getItem(t)??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.relisters.length=0,this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(Z1,this.chosenSourceId.get("place")))),this.weatherSourceRow.replaceChildren(),this.fillWeatherProvider(),this.sourcePickers(this.shadow.getElementById("weather-source-rows"),"weather-source-kind","weather",[["weather",this.messages.fileItemWeather,this.shadow.getElementById("weather-picker")],["upper-air",this.messages.snapshotUpperAir,this.sourcePicker("upper-air",vU,()=>{},this.groupChoice(["upperAir"]))]]),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(qm,this.chosenSourceId.get("light-pollution")))),this.narrativeSourceRow.replaceChildren(this.sourcePicker("narrative",Nf,e=>{const t=this.narrativeProvider=e.create();this.renderNarrativeSettings(),t.localize?.(this.language).then(()=>{t===this.narrativeProvider&&this.renderNarrativeSettings()})})),this.sourcePickers(this.terrainSourceRows,"source-kind","location",[["place",this.messages.fileItemPlace,this.sourcePicker("place",Z1,e=>{this.placeProvider=e.create(),this.refreshSourceCredits()},this.sectionChoice("place",()=>this.schedulePlaceReverse()))],["light-pollution",this.messages.fileItemLightPollution,this.sourcePicker("light-pollution",qm,e=>{this.lightPollutionProvider=e.create(),this.refreshSourceCredits(),this.scheduleLightPollutionLookup()},this.sectionChoice("lightPollution",()=>this.scheduleLightPollutionLookup()))],["elevation",this.messages.sourceElevation,this.sourcePicker("elevation",Km,()=>this.applyTerrainSources(),this.groupChoice(["relief"]))],["imagery",this.messages.sourceImagery,this.sourcePicker("imagery",qc,()=>this.applyTerrainSources(),this.groupChoice(["imagery","map"]))],["roads",this.messages.snapshotRoads,this.sourcePicker("roads",[xe.LIVE_ROADS],()=>{},this.groupChoice(["roads"]))],["water",this.messages.snapshotWater,this.sourcePicker("water",[xe.LIVE_WATER],()=>{},this.groupChoice(["water"]))],["railways",this.messages.snapshotRailways,this.sourcePicker("railways",[xe.LIVE_RAILWAYS],()=>{},this.groupChoice(["railways"]))]]),this.shadow.getElementById("label-aircraft-source").textContent=this.messages.sourceAircraft,this.shadow.getElementById("aircraft-source-row").replaceChildren(this.aircraftPicker()),this.sourcePickers(this.shadow.getElementById("decor-source-rows"),"decor-source-kind","decor",[["scenery",this.messages.fileItemDecor,this.shadow.getElementById("scenery-picker")],["decor-model",this.messages.decorModel,this.sourcePicker("decor-model",Oy,()=>this.applyDecorModelSource())]])}sourcePicker(e,t,i,s){const n=document.createDocumentFragment(),r=document.createElement("select");r.id=`${e}Source`;const a=()=>{r.replaceChildren(...t.map(v=>{const g=document.createElement("option");return g.value=v.id,g.textContent=v.name,g.title=v.credit,g})),s&&r.appendChild(new Option(this.messages.sourceFile,xe.FILE_SOURCE))};a();const o=()=>{const v=this.chosenSourceId.get(e);return v!==void 0&&t.some(g=>g.id===v)?v:t[0].id};r.value=s?.fromFile()?xe.FILE_SOURCE:o();const c=document.createElement("a");c.className="source-credit",c.target="_blank",c.rel="noopener noreferrer";const h=document.createElement("button");h.type="button",h.className="link source-file-link",h.addEventListener("click",()=>this.openFileItem(s.item));const d=document.createElement("label");d.className="source-key";const u=document.createElement("input");u.type="password",u.id=`${e}SourceKey`,u.autocomplete="off",u.spellcheck=!1,u.title=this.messages.sourceKeyHint;const p=document.createElement("a");p.className="source-credit",p.target="_blank",p.rel="noopener noreferrer",p.textContent=this.messages.sourceKeyGet,d.append(document.createTextNode(`${this.messages.sourceKey} `),u,document.createTextNode(" "),p),u.addEventListener("change",()=>{const v=zi(t,r.value);$o.set(v.id,u.value),i(v,!0)});const f=()=>{const v=r.value===xe.FILE_SOURCE,g=zi(t,v?o():r.value);d.hidden=v||!g.keyUrl,p.href=g.keyUrl??"",u.value=$o.of(g.id)??"",r.title=v?s.where():g.credit,c.hidden=v,c.href=g.creditUrl,c.textContent=g.credit,h.hidden=!v,v&&(h.textContent=s.label(),h.title=s.where())};f(),r.addEventListener("change",()=>{const v=r.value===xe.FILE_SOURCE;v||this.chosenSourceId.set(e,r.value),s?.setFromFile(v),f(),v||i(zi(t,r.value))}),s&&this.filePickers.set(e,()=>{r.value=s.fromFile()?xe.FILE_SOURCE:o(),f()});const m=()=>{const v=r.value,g=this.chosenSourceId.has(e)&&!t.some(b=>b.id===this.chosenSourceId.get(e));g&&this.chosenSourceId.delete(e),a(),r.value=v===xe.FILE_SOURCE&&s?v:o(),f(),g&&r.value!==xe.FILE_SOURCE&&i(zi(t,r.value))};return this.relisters.push(m),n.append(r,document.createTextNode(" "),c,h,d),n}aircraftPicker(){const e=this.sourcePicker("aircraft",Xy,(t,i)=>this.applyAircraftSource(i));return e.append(this.aircraftStatus),this.showAircraftStatus(),e}get aircraftTabOpen(){return this.isGroupIdOpen("group-weather")&&this.shadow.getElementById("weather-aircraft")?.hidden===!1}showAircraftFlights(){if(this.aircraftTabOpen){if(this.ufoElement.playbackState==="playing"){const e=performance.now();if(e-this.aircraftFlightsShownAt<1e3)return;this.aircraftFlightsShownAt=e}this.aircraftFlights.show(this.sceneElement.aircraftFlights,this.messages)}}aimAtFlight(e){if(e.key===this.aircraftFlights.selectedKey){this.aircraftFlights.select(void 0,this.messages),this.sceneElement.markFlight(void 0);return}if(!e.sky&&e.firstMs===void 0)return;const t=e.sky?this.ufoElement.currentTime:e.firstMs;e.sky||this.goToMark(t),this.sceneElement.lookAtFlight(e.key,t),this.aircraftFlights.select(e.key,this.messages),this.sceneElement.markFlight(e.key),this.showAircraftFlights()}showAircraftStatus(){this.showAircraftFlights();const{status:e,problem:t,partial:i,creditsSpent:s,total:n}=this.sceneElement.aircraftState,r=[];e==="loading"&&r.push(this.messages.aircraftLoading),e==="outside"&&r.push(this.messages.aircraftOutside),e==="unavailable"&&!t&&r.push(this.messages.aircraftProblems.network),e==="ready"&&n===0&&r.push(this.messages.aircraftNone),i&&r.push(this.messages.aircraftPartial.replace("{traced}",String(i.traced)).replace("{seen}",`${i.seen}${i.moreSeen?"+":""}`).replace("{km}",String(i.withinKm))),s&&r.push(this.messages.aircraftCredits.replace("{credits}",String(s))),t?Ht.show(this.aircraftStatus,[this.messages.aircraftProblems[t],...r].join(" "),"warning"):Ht.show(this.aircraftStatus,r.length>0?r.join(" "):void 0,"info")}groupChoice(e){return{item:e[0],fromFile:()=>!this.snapshotsPanel.isLive(e[0]),setFromFile:t=>{for(const i of e)this.snapshotsPanel.setLive(i,!t)},label:()=>this.snapshotsPanel.itemLabel(e[0]),where:()=>this.snapshotsPanel.where(e[0])}}sectionChoice(e,t){return{item:e,fromFile:()=>this.sectionFromFile(e),setFromFile:i=>{const s={...this.ufoElement.sighting.snapshots??{}};i?s[e]=s[e]??{}:delete s[e],this.ufoElement.sighting.snapshots=os.isEmpty(s)?void 0:s,this.touch(),this.scheduleFileSync(),this.refreshFileItems(),i||t()},label:()=>this.sectionFilePanel.itemLabel(e),where:()=>this.sectionFilePanel.where(e)}}static FILE_SOURCE="file";filePickers=new Map;syncFilePickers(){for(const e of this.filePickers.values())e()}openFileItem(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")==="group-file");t&&this.toggleGroup(t,!0),this.fileItemSelect.value=e,this.showFileItem(e)}static LIVE_ROADS={id:"ign-osm",name:"IGN BD TOPO / OpenStreetMap",credit:"© IGN, BD TOPO (Licence Ouverte 2.0) in France; © OpenStreetMap contributors (ODbL) elsewhere",creditUrl:"https://www.openstreetmap.org/copyright",create:()=>{}};static LIVE_WATER=xe.LIVE_ROADS;static LIVE_RAILWAYS=xe.LIVE_ROADS;sourcePickers(e,t,i,s){const n=document.createElement("label"),r=document.createElement("span");r.id=`label-${t}`,r.textContent=this.messages.sourceKind;const a=document.createElement("select");a.id=t;const o=s.map(([h,d,u])=>{a.append(new Option(d,h));const p=document.createElement("span");return p.className="source-picker",p.dataset.kind=h,p.append(u),p});a.value=this.sourceKindShown.get(i)??s[0][0];const c=()=>{this.sourceKindShown.set(i,a.value);for(const h of o)h.hidden=h.dataset.kind!==a.value};a.addEventListener("change",c),c(),n.append(r,document.createTextNode(" "),a),e.replaceChildren(n,...o)}sourceKindShown=new Map;static creditLink(e){const t=document.createElement("a");return t.className="source-credit",t.target="_blank",t.rel="noopener noreferrer",t.href=e.creditUrl,t.textContent=e.credit,t}refreshSourceCredits(){this.placeSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(Z1,this.chosenSourceId.get("place")))),this.lightPollutionSourceRow.replaceChildren(document.createTextNode(`${this.messages.according} `),xe.creditLink(zi(qm,this.chosenSourceId.get("light-pollution"))))}applyTerrainSources(){this.sceneElement.setTerrainProviders({elevation:zi(Km,this.chosenSourceId.get("elevation")).create(),imagery:zi(qc,this.chosenSourceId.get("imagery")).create()}),this.ufoElement.refresh()}applyAircraftSource(e=!1){this.sceneElement.setAircraftSource(zi(Xy,this.chosenSourceId.get("aircraft")),e),this.showAircraftStatus(),this.ufoElement.refresh()}applyDecorModelSource(){this.decorModelProvider=new mp(zi(Oy,this.chosenSourceId.get("decor-model")).id),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===""||this.sectionFromFile("place"))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||this.sectionFromFile("place"))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)<Zh&&Math.abs(t-this.namedCoordinates.lng)<Zh||(clearTimeout(this.placeReverseTimer),this.placeReverseTimer=setTimeout(()=>void this.reversePlace(e,t),EA))}timeZoneIsStated(){const e=this.ufoElement.sighting.event;return e.timeZone?e.timeZone!==this.autoFilledTimeZone:e.utcOffsetHours!==void 0}scheduleTimeZoneLookup(e=!0){const t=this.numberOrUndefined(this.latInput.value),i=this.numberOrUndefined(this.lngInput.value);if(t===void 0||i===void 0)return;const s=this.timeZoneLookedUpAt;s&&Math.abs(t-s.lat)<Zh&&Math.abs(i-s.lng)<Zh||(clearTimeout(this.timeZoneLookupTimer),this.timeZoneLookupTimer=setTimeout(()=>void this.lookUpTimeZone(t,i,e),EA))}async lookUpTimeZone(e,t,i){const s={lat:e,lng:t};this.timeZoneLookedUpAt=s;const n=await this.timeZoneProvider.zoneAt(e,t);if(this.timeZoneLookedUpAt===s){if(this.placeZone=n??void 0,!n||!i||this.timeZoneIsStated()||!this.timeZones.available().includes(n)){this.timeZoneSelect.value=this.zoneShown(),this.updateUtcOffsetValidity();return}this.autoFilledTimeZone=n,this.timeZoneSelect.value=n,this.updateTimeZone(),this.dispatchEvent(new CustomEvent("sightingchange"))}}async reversePlace(e,t){const i=++this.placeSearchToken;let s;try{s=await this.placeProvider.reverse(e,t,{language:this.placeSearchLanguage})}catch{return}if(i!==this.placeSearchToken)return;this.namedCoordinates={lat:e,lng:t},this.placeNameInput.value=s?.name??"",this.placeNameInput.title=s?.name??"",this.placeMatches=[],this.placeMatchRow.hidden=!0,this.placeStatusText.textContent=s?"":this.messages.placeNotFound,this.placeSourceRow.hidden=!s;const n=this.ufoElement.sighting.event.place?.[0]??{lat:e,lng:t};this.ufoElement.sighting.event.place=[{lat:n.lat,lng:n.lng,name:this.stringOrUndefined(this.placeNameInput.value.trim())}]}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),s=this.numberOrUndefined(this.pitchInput.value)??0,n=this.numberOrUndefined(this.rollInput.value)??0,r=this.numberOrUndefined(this.elevationInput.value)??this.groundElevationM??0,a=Math.max(0,r-(this.groundElevationM??0)),o=this.ufoElement.sighting.event,c=this.ufoElement.sighting.observerTrack,h=this.ufoElement.currentTime,d=this.stringOrUndefined(this.placeNameInput.value.trim());o.place=e!==void 0&&t!==void 0?[{lat:e,lng:t,name:d}]:void 0;const u=this.ufoElement.sighting.instrument,p=this.numberOrUndefined(this.focalLengthInput.value),f=(u.frame&&p!==void 0?Qt.fieldOfViewDegAt(u,p):p)??this.currentFovDeg(),m=this.numberOrUndefined(this.fNumberInput.value),v=this.filterSelect.value,g=ji.byId(c.getLatestPoseAt(h-1)?.filter),b=v===ji.NONE.id||v===""?g===ji.NONE?void 0:ji.NONE.id:v,w=this.statedExposureSeconds(u);this.ufoElement.sighting.exposureSeconds=w===u.exposureSeconds?void 0:w;const y=this.numberOrUndefined(this.focusDistanceInput.value),M=Math.abs(f-Qt.fieldOfViewDeg(u))>.01||m!==u.fNumber||y!==void 0||b!==void 0;e===void 0&&t===void 0&&i===void 0&&s===0&&n===0&&a===0&&!M?c.removeKeyframeAt(h):c.addKeyframe(h,{lat:e,lng:t,elevationM:a,headingDeg:i,pitchDeg:s,rollDeg:n===0?void 0:n,...this.observerSaid&&e!==void 0?{saidPosition:this.observerSaid}:{},fovDeg:f,fNumber:m,focusDistanceM:y,filter:b});const E=this.plantingCentre();this.surroundings.placeChanged(E?.lat,E?.lng),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&&!Ym.isFirm(t))return;const s=Ym.at(t,i);s!==void 0&&(this.observerAgeInput.value=String(s),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&&Ym.at(i,e)===t)return;const s=Ym.birthFor(t,e);s&&(this.birthDate.setPrecise(!1),this.birth=s,this.birthDate.time=s,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&&Qc({...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(s=>{const n=document.createElement("option");return n.value=s,n.textContent=s,n})),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.zoneKnownToRead(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){return this.zoneKnownToRead(e)??this.timeZones.zonesAt(e,this.timeZoneReference())[0]}zoneKnownToRead(e){const t=this.timeZones.zonesAt(e,this.timeZoneReference()),i=this.ufoElement.sighting.event.timeZone;if(i&&t.includes(i))return i;if(this.placeZone&&t.includes(this.placeZone))return this.placeZone;const s=Number.isInteger(e)?e===0?"UTC":`Etc/GMT${e>0?"-":"+"}${Math.abs(e)}`:void 0;return s&&t.includes(s)?s:void 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.observerTitleInput.value.trim()===""?void 0:this.said.write(e.observer?.title,this.observerTitleInput.value.trim(),this.writingLanguage),lastName:this.stringOrUndefined(this.observerLastNameInput.value),firstNames:t.length>0?t:void 0},s=Vt.observerId(e);e.observer=Object.values(i).some(n=>n!==void 0)?i:void 0,Vt.renamed(e,s,Vt.observerId(e)),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:ya.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",...this.evaluationFields.values(),conditions:e.account?.conditions};e.account=Object.values(i).some(s=>s!==void 0)?i:void 0}updateSourceUrl(){const e=this.ufoElement.sighting,t=this.accountUrlInput.value.trim(),[i,...s]=e.sources??[],{url:n,...r}=i??{},a=t===""?r:{...r,url:t},o=Object.keys(a).length>0?[a,...s]:s;e.sources=o.length>0?o: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()):this.ufoElement.sighting.weatherSource!==void 0&&(this.ufoElement.sighting.weatherSource=void 0,this.syncWeatherSourceState());const e={...ys(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={...ys(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(s=>s.id===this.currentReferenceId),t=e!==void 0;gn.showPresence(this.shadow.getElementById("reference-row"),this.shadow.getElementById("reference-item"),t),this.deleteReferenceButton.disabled=!t,this.referenceUsePoseButton.disabled=!t;for(const s of[this.referenceSelect,...this.referenceFields])s.disabled=!t;if(this.referenceSourceInput.disabled=!t,this.refreshLandmarkList(),this.syncCanvasMode(),!e){this.referenceStatus.textContent="";return}this.referenceTitleInput.value=this.said.read(e.title)??"";const i=e.src.startsWith("data:");this.referenceSourceInput.url=i?"":e.src,this.referenceSourceInput.mode=i?"file":"url",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.ghostFinding&&(this.ghostFinding.referenceId!==e.id||this.ghostFinding.src!==e.src)&&(this.ghostFinding=void 0,this.ghostsStatus.textContent="",this.syncGhostsShown(),this.ufoElement.refresh()),this.referenceOpacityInput.value=String(e.opacity),this.syncVideoFields(e),this.showRegistration(this.registrationShown(e)),this.syncReferenceStatus(e)}syncVideoFields(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.referenceVideoFromInput.value=e.video?.fromS===void 0?"":String(e.video.fromS),this.referenceVideoToInput.value=e.video?.toS===void 0?"":String(e.video.toS),this.referenceVideoRateInput.value=e.video?.rate===void 0?"":String(e.video.rate),this.syncReferenceKeyButton(e)}syncReferenceKeyButton(e){this.referenceRemoveKeyButton.hidden=e.kind!=="video"||as.keyIndexAt(e,this.ufoElement.currentTime)<0}registrationShown(e){if(!e.registrationTrack?.length)return e.registration;const{headingDeg:t,pitchDeg:i,rollDeg:s,fovDeg:n}=as.registrationAt(e,this.ufoElement.currentTime);return{headingDeg:this.rounded(t),pitchDeg:this.rounded(i),rollDeg:s===void 0?void 0:this.rounded(s),fovDeg:this.rounded(n)}}showRegistration({headingDeg:e,pitchDeg:t,rollDeg:i,fovDeg:s}){this.referenceHeadingInput.value=String(e),this.referencePitchInput.value=String(t),this.referenceRollInput.value=String(i??0),this.referenceFovInput.value=String(s)}syncVideoRegistrationFields(){if(this.currentReferenceId===void 0)return;const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);e?.kind==="video"&&(this.syncReferenceKeyButton(e),e.registrationTrack?.length&&this.showRegistration(this.registrationShown(e)))}removeReferenceKey(){const e=this.ufoElement.sighting.references.find(i=>i.id===this.currentReferenceId);if(!e)return;const t=as.withoutKey(e,this.ufoElement.currentTime);this.ufoElement.sighting.references=this.ufoElement.sighting.references.map(i=>i===e?t:i),this.syncReferenceFields(),this.ufoElement.refresh()}syncReferenceStatus(e){const t=this.sceneElement.referenceFailure(e.src);if(Ht.show(this.referenceFailure,t?this.pictureFailureText(t):void 0,"error"),this.syncFindGhosts(e),this.canvasMode()==="picture"){this.syncRegisterStatus();return}if(e.src.startsWith("data:")){const i=Math.round(e.src.length*3/4/1024);this.referenceStatus.textContent=e.src.length>jF?this.messages.referenceEmbedded.replace("{kb}",String(i)):"";return}this.referenceStatus.textContent=""}pictureFailureText(e){switch(e.kind){case"notShared":return this.messages.referenceNotShared;case"status":return this.messages.referenceNotFound.replace("{status}",String(e.status));case"notPicture":return this.messages.referenceNotPicture;case"notVideo":return this.messages.referenceNotVideo;default:return 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(n=>{if(n.id!==this.currentReferenceId)return n;const r=n.src,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)||jm))},o=this.registrationShown(n),c=a.headingDeg!==o.headingDeg||a.pitchDeg!==o.pitchDeg||a.rollDeg!==o.rollDeg||a.fovDeg!==o.fovDeg,h=this.referenceKindSelect.value;return h==="video"?{...c?as.withKey(n,this.ufoElement.currentTime,a):n,kind:h,src:r,title:this.said.write(n.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),video:this.videoClipOfFields(),drawing:this.referenceDrawingInput.checked||void 0,opacity:Number(this.referenceOpacityInput.value),from:void 0}:{...n,kind:h,video:void 0,registrationTrack:void 0,src:r,title:this.said.write(n.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()??n.from:n.from}});const s=e.references.find(n=>n.id===this.currentReferenceId);this.referenceSelect.options[this.referenceSelect.selectedIndex].textContent=this.referenceLabel(s),this.syncVideoFieldsKeepingInput(s),this.syncReferenceStatus(s),this.ufoElement.refresh()}videoClipOfFields(){const e={fromS:this.numberOrUndefined(this.referenceVideoFromInput.value),toS:this.numberOrUndefined(this.referenceVideoToInput.value),rate:this.numberOrUndefined(this.referenceVideoRateInput.value)};return e.fromS===void 0&&e.toS===void 0&&e.rate===void 0?void 0:e}syncVideoFieldsKeepingInput(e){const t=e.kind==="video";for(const i of this.shadow.querySelectorAll(".reference-video-field"))i.hidden=!t;this.labelReferenceT.textContent=t?this.messages.referenceVideoT:this.messages.referenceT,this.syncReferenceKeyButton(e)}useObserverPoseForReference(){const e=tt(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(as.rollOfPicture(e.rollDeg)??0)),this.referenceFovInput.value=String(this.rounded(e.fovDeg)),this.updateReference())}observerPositionNow(){const e=tt(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 s=this.ufoElement.sighting,n=tt(this.ufoElement.sighting,this.ufoElement.currentTime),r=`picture-${s.references.length+1}`,a={id:r,kind:"photo",src:e,title:t?this.said.write(void 0,t,this.writingLanguage):void 0,opacity:qF,registration:{headingDeg:n?.headingDeg??0,pitchDeg:n?.pitchDeg??0,fovDeg:jm},from:this.observerPositionNow(),...i};s.references=[...s.references,a],this.currentReferenceId=r,this.refreshReferenceList(),this.ufoElement.refresh()}addReferenceFromAddress(){this.addReference(""),this.referenceSourceInput.mode="url",this.referenceSourceInput.focus()}addReferenceFromFile(){this.addReference(""),this.referenceSourceInput.mode="file",this.referenceSourceInput.openPicker()}async setReferenceSource(e){const t=this.currentReferenceId;if(t===void 0)return;let i;if(e.file){const r=e.file;i=await new Promise((a,o)=>{const c=new FileReader;c.onload=()=>a(c.result),c.onerror=()=>o(c.error),c.readAsDataURL(r)})}else i=e.url;const s=this.ufoElement.sighting,n=as.kindOfSource(e.file?{type:e.file.type}:{url:e.url});s.references=s.references.map(r=>r.id!==t?r:{...r,src:i,kind:n==="video"||n==="photo"&&r.kind==="video"?n:r.kind,from:n==="video"?void 0:r.from,title:r.title??(e.file?this.said.write(void 0,e.file.name.replace(/\.[^.]+$/,""),this.writingLanguage):void 0)}),this.touch(),this.refreshReferenceList(),this.ufoElement.refresh()}pictureAspect(e){if(!this.pictureRegistration){this.loadPictureRegistration();return}return this.sceneElement.referenceAspect(e)}loadPictureRegistration(){return this.pictureRegistrationLoading??=Q(async()=>{const{PictureRegistration:e}=await import("./PictureRegistration-ZyvGfReK.js");return{PictureRegistration:e}},[],import.meta.url).then(({PictureRegistration:e})=>{this.pictureRegistration=e,this.ufoElement.refresh()})}currentReference(){const e=this.ufoElement.sighting.references.find(t=>t.id===this.currentReferenceId);return e?.registrationTrack?.length?{...e,registration:as.registrationAt(e,this.ufoElement.currentTime)}:e}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 s=this.pictureAspect(t.id);if(!(s!==void 0&&this.pictureRegistration.picturePointOf(this.directionAtCanvasPoint(e),t.registration,s)!==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.pictureAspect(t.id):void 0;if(!t||i===void 0)return;const s=8;for(const n of this.currentLandmarks()){const r=this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(n.picture,t.registration,i));if(r&&Math.hypot(r.x-e.x,r.y-e.y)<=s)return{landmarkId:n.id,end:"picture"};const a=this.canvasPointOfDirection(this.pictureRegistration.worldDirection(n.scene));if(a&&Math.hypot(a.x-e.x,a.y-e.y)<=s)return{landmarkId:n.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 s=i.x-t.startPointer.x,n=i.y-t.startPointer.y;if(!t.moved&&Math.hypot(s,n)<3)return;t.moved=!0;const r=this.currentFovDeg()/this.ufoElement.canvasElement.height;this.referenceHeadingInput.value=String(this.rounded(t.startHeadingDeg+s*r)),this.referencePitchInput.value=String(this.rounded(Math.max(-90,Math.min(90,t.startPitchDeg-n*r)))),this.updateReference()}moveLandmarkEnd(e,t,i){const s=this.currentReference(),n=s?this.pictureAspect(s.id):void 0;if(!s||n===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:this.pictureRegistration.aimOf(r)};const o=this.pictureRegistration.picturePointOf(r,s.registration,n);return o?{...a,picture:o}: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)||jm,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.pictureAspect(t.id);if(r===void 0){this.referenceStatus.textContent=this.messages.referenceNotLoaded;return}const a=this.pictureRegistration.picturePointOf(i,t.registration,r);if(!a){this.referenceStatus.textContent=this.messages.referenceLandmarkOffPicture;return}this.pendingLandmark=a,this.syncRegisterStatus(),this.ufoElement.refresh();return}const s=this.currentLandmarks(),n=this.nextLandmarkId(s);this.writeLandmarks([...s,{id:n,picture:this.pendingLandmark,scene:this.pictureRegistration.aimOf(i)}]),this.armingLandmark=!1,this.pendingLandmark=void 0,this.currentLandmarkId=n,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.pictureAspect(e.id):void 0;if(!e||t===void 0)return;const i=this.currentLandmarks(),s=this.pictureRegistration.solve(i,t,e.registration.fovDeg);s?(this.referenceFit={n:i.length,residualDeg:s.residualDeg},this.referenceHeadingInput.value=String(this.rounded(s.registration.headingDeg)),this.referencePitchInput.value=String(this.rounded(s.registration.pitchDeg)),this.referenceRollInput.value=String(this.rounded(s.registration.rollDeg??0)),this.referenceFovInput.value=String(this.rounded(s.registration.fovDeg)),this.updateReference()):this.referenceFit=void 0,this.refreshLandmarkList(),this.syncRegisterStatus(),this.ufoElement.refresh()}landmarkResidualDeg(e,t,i){return this.pictureRegistration.worldDirectionOf(e.picture,t.registration,i).angleTo(this.pictureRegistration.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.pictureAspect(e.id):void 0;this.referenceLandmarksSelect.innerHTML="";for(const[n,r]of t.entries()){const a=document.createElement("option");a.value=r.id;const o=e&&i!==void 0?` · ${this.landmarkResidualDeg(r,e,i).toFixed(1)}°`:"";a.textContent=this.landmarkLabel(r,n)+o,this.referenceLandmarksSelect.appendChild(a)}this.currentLandmarkId!==void 0&&!t.some(n=>n.id===this.currentLandmarkId)&&(this.currentLandmarkId=void 0),this.currentLandmarkId!==void 0&&(this.referenceLandmarksSelect.value=this.currentLandmarkId);const s=t.find(n=>n.id===this.currentLandmarkId);gn.showPresence(this.shadow.getElementById("reference-landmark-row"),this.shadow.getElementById("reference-landmark-item"),t.length>0),this.referenceLandmarksSelect.disabled=t.length===0,this.deleteReferenceLandmarkButton.disabled=s===void 0,this.referenceLandmarkLabelInput.disabled=s===void 0,this.shadow.activeElement!==this.referenceLandmarkLabelInput&&(this.referenceLandmarkLabelInput.value=this.said.read(s?.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(),s=i.findIndex(a=>a.id===e),n=this.currentReference(),r=n?this.pictureAspect(n.id):void 0;if(t&&s>=0){const a=n&&r!==void 0?` · ${this.landmarkResidualDeg(i[s],n,r).toFixed(1)}°`:"";t.textContent=this.landmarkLabel(i[s],s)+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.pictureAspect(t.id);if(i===void 0)return;const{registration:s}=t,n=[{u:0,v:0},{u:1,v:0},{u:1,v:1},{u:0,v:1}].map(a=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a,s,i))),r=this.currentLandmarks().map((a,o)=>({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(a.picture,s,i)),scene:this.canvasPointOfDirection(this.pictureRegistration.worldDirection(a.scene)),label:this.landmarkLabel(a,o),selected:a.id===this.currentLandmarkId,residualDeg:this.landmarkResidualDeg(a,t,i)}));this.pendingLandmark&&r.push({picture:this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf(this.pendingLandmark,s,i)),scene:void 0,label:String(this.currentLandmarks().length+1),selected:!0,residualDeg:void 0}),e.paintPictureFrame(n.every(a=>a!==void 0)?n:void 0,r.filter(a=>a.picture!==void 0),this.landmarkHint()),this.paintGhostFinding(e,t,i)};paintGhostFinding(e,t,i){const s=this.ghostFinding;if(!s||!this.ghostsShown||s.referenceId!==t.id||s.src!==t.src)return;const{search:n}=s,r=t.registration,a=d=>this.canvasPointOfDirection(this.pictureRegistration.worldDirectionOf({u:d.x/n.width,v:d.y/n.height},r,i)),o=[];for(const d of n.pairs){const u=a(d.ghost),p=a(d.light),f=a({x:d.ghost.x+d.ghost.radius,y:d.ghost.y});!u||!p||o.push({ghost:u,light:p,ghostRadius:f?Math.hypot(f.x-u.x,f.y-u.y):0})}const c=n.centre?a(n.centre):void 0,h=n.cropped?a({x:n.width/2,y:n.height/2}):void 0;e.paintGhosts(o,c,h)}adoptReferencePose(){const e=this.currentReference();if(!e)return;const{headingDeg:t,pitchDeg:i,rollDeg:s}=e.registration;this.headingInput.value=String(this.rounded(t)),this.pitchInput.value=String(this.rounded(i)),this.rollInput.value=String(this.rounded(as.rollOfPicture(s)??0)),this.updateObserver();const n=this.ufoElement.currentTime,r=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(c=>c.t===n);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)),o=[["headingDeg",t],["pitchDeg",i],["rollDeg",s??0]];for(const[c,h]of o)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.referenceAddMenu.setDisabled("street",e?void 0:this.messages.referenceStreetNoPlace)}setReferenceAddKinds(e,t,i){const s=this.numberOrUndefined(this.latInput?.value??"")!==void 0&&this.numberOrUndefined(this.lngInput?.value??"")!==void 0;this.referenceAddMenu.setKinds([{value:"address",label:e},{value:"file",label:t},{value:"street",label:i,...s?{}:{disabledReason:this.messages?.referenceStreetNoPlace??""}}])}addReferenceOfKind(e){switch(e){case"file":this.addReferenceFromFile();break;case"street":this.searchStreetPictures();break;default:this.addReferenceFromAddress()}}async searchStreetPictures(){const e=tt(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 s=300;this.referenceStatus.textContent=this.messages.referenceStreetSearching,this.addReferenceButton.disabled=!0;try{this.streetPictures$??=new(await Q(async()=>{const{PanoramaxPictures:r}=await import("./PanoramaxPictures-CELY3Ecc.js");return{PanoramaxPictures:r}},[],import.meta.url)).PanoramaxPictures,this.streetPictures=await this.streetPictures$.nearby(t,i,s)}catch{this.streetPictures=[],this.referenceStatus.textContent=this.messages.referenceStreetFailed,this.addReferenceButton.disabled=!1;return}this.addReferenceButton.disabled=!1,this.referenceStreetSelect.innerHTML="";for(const[r,a]of this.streetPictures.entries()){const o=document.createElement("option");o.value=String(r),o.textContent=this.streetPictureLabel(a,this.messages.referenceStreetItem),this.referenceStreetSelect.appendChild(o)}const n=this.streetPictures.length>0;this.referenceStreetSelect.hidden=!n,this.referenceStreetAddButton.hidden=!n,this.referenceStatus.textContent=n?"":this.messages.referenceStreetNone.replace("{m}",String(s))}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:jm}})}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;gn.showPresence(this.shadow.getElementById("trace-row"),this.shadow.getElementById("trace-item"),t);for(const i of[this.traceSelect,this.deleteTraceButton,this.traceTitleInput,this.traceSourceInput])i.disabled=!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(s=>s.id!==this.currentTraceId?s:{...s,title:this.said.write(s.title,this.traceTitleInput.value,this.writingLanguage),source:this.said.write(s.source,this.traceSourceInput.value,this.writingLanguage)});const t=Array.from(this.traceSelect.options).find(s=>s.value===this.currentTraceId),i=e.traces.find(s=>s.id===this.currentTraceId);t&&i&&(t.textContent=this.traceLabel(i)),this.ufoElement.refresh()}async addTraces(e){const t=e.file?.name??decodeURIComponent(e.url.split("/").pop()??e.url);let i;try{const{KmlImport:h}=await Q(async()=>{const{KmlImport:d}=await import("./KmlImport-B9mAzJwr.js");return{KmlImport:d}},[],import.meta.url);i=await h.fromBytes(await lM.bytesOf(e))}catch{this.traceStatus.textContent=this.messages.traceFailed;return}if(i.traces.length===0){this.traceStatus.textContent=this.messages.traceNone;return}const s=this.ufoElement.sighting,n=new Set(s.traces.map(h=>h.id));let r=1;const a=this.said.write(void 0,i.documentName??t,this.writingLanguage),o=i.traces.map(h=>{for(;n.has(`trace-${r}`);)r++;const d=`trace-${r}`;return n.add(d),{...h,id:d,title:h.title===void 0?void 0:this.said.write(void 0,h.title,this.writingLanguage),source:a}});s.traces=[...s.traces,...o],this.currentTraceId=o[0].id,this.refreshTraceList();const c=i.skipped.length>0?` ${this.messages.traceSkipped.replace("{what}",i.skipped.join(", "))}`:"";this.traceStatus.textContent=this.messages.traceImported.replace("{n}",String(o.length)).replace("{name}",t)+c,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 s_){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(),xU)}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=sw(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 Wu(e),this.scheduleWeatherLookup()}onWeatherProviderChosen(){const e=this.weatherProviderSelect.value===xe.FILE_SOURCE;if(!e){const t=zi(La,this.weatherProviderSelect.value);t.id!==this.chosenSourceId.get("weather")&&(this.chosenSourceId.set("weather",t.id),this.weatherInference=new Wu(t.create()),this.scheduleWeatherLookup(!0),this.syncWeatherProvider())}if(this.setWeatherFromFile(e),this.weatherInferredInput.checked!==!e){this.weatherInferredInput.checked=!e,this.keepWeatherSource=e;try{this.weatherInferredInput.dispatchEvent(new Event("change"))}finally{this.keepWeatherSource=!1}}}keepWeatherSource=!1;setWeatherFromFile(e){const t=this.ufoElement.sighting;if(Yt.fromFile(t.snapshots,"weather")===e)return;const i={...t.snapshots??{}};e?i.weather={...i.weather??{},live:void 0}:delete i.weather,i.weather&&i.weather.live===void 0&&delete i.weather.live,t.snapshots=os.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}followWeatherRecord(){const e=La.find(i=>i.id===this.ufoElement.sighting.weatherSource?.id),t=this.chosenSourceId.get("weather");if(e&&e.id!==zi(La,t).id){if(this.weatherLookupPending)return;this.chosenSourceId.set("weather",e.id),this.weatherInference=new Wu(e.create())}else!e&&t!==void 0&&!La.some(i=>i.id===t)&&(this.chosenSourceId.delete("weather"),this.weatherInference=new Wu(zi(La,void 0).create()))}fillWeatherProvider(){this.weatherProviderSelect.replaceChildren(...La.map(e=>{const t=new Option(e.name,e.id);return t.title=e.credit,t}),new Option(this.messages.sourceFile,xe.FILE_SOURCE)),this.syncWeatherProvider()}syncWeatherProvider(){const e=!this.weatherInferredInput.checked,t=this.ufoElement.sighting.weatherSource,i=!e&&t!==void 0&&!Jm(t)?t:void 0;if(this.weatherProviderSelect.querySelector("option[data-stated]")?.remove(),i){const r=new Option(i.name??i.id,i.id);r.dataset.stated="",this.weatherProviderSelect.add(r,this.weatherProviderSelect.options.length-1)}this.weatherProviderSelect.value=e?xe.FILE_SOURCE:i?i.id:zi(La,this.chosenSourceId.get("weather")).id,this.weatherProviderSelect.disabled=this.weatherInferredInput.disabled,this.weatherProviderSelect.title=this.weatherInferredInput.title;const s=zi(La,this.chosenSourceId.get("weather")),n=this.shadow.getElementById("weather-credit");n.hidden=e||i!==void 0,n.href=s.creditUrl,n.textContent=s.credit,this.weatherFileLink.hidden=!e,e&&(this.weatherFileLink.textContent=this.weatherFileItemLabel(),this.weatherFileLink.title=this.sectionFilePanel?.where("weather")??"")}onWeatherInferredToggled(){this.weatherFromRecords=this.weatherInferredInput.checked,this.setWeatherFromFile(!this.weatherFromRecords),this.weatherFromRecords?this.scheduleWeatherLookup(!0):(this.cancelWeatherLookup(),this.keepWeatherSource||(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&&!Jm(t)||(clearTimeout(this.weatherLookupTimer),this.weatherLookupTimer=setTimeout(()=>void this.inferWeather(),SA))}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||!Jm(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=this.fieldHints.get(a.id)??"");const i=this.weatherInference.canInfer(this.ufoElement.sighting)&&!this.startDateHalfEntered();if(!i&&e!==void 0&&Jm(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 s=i?this.messages.weatherInferredTitle:this.messages.weatherNeedsDateAndPlace;this.weatherInferredInput.title=s,this.labelWeatherInferred.title=s,this.syncWeatherProvider();const n=t&&e!==void 0;if(this.weatherSourceLink.hidden=!n,n){this.weatherSourceRow.hidden=!1,this.weatherSourceText.textContent="",this.weatherSourceLink.href=e.url,this.weatherSourceLink.textContent=[e.name,this.observationInstantLabel()].filter(Boolean).join(", ");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&&mn(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.followWeatherRecord(),this.weatherFromRecords=!Yt.fromFile(e.snapshots,"weather")&&(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=qm[0].create();lightPollutionTimer;lightPollutionToken=0;lightPollutionLookup;lightPollutionFromRecord(){const e=this.ufoElement.sighting;if(this.sectionFromFile("lightPollution"))return!1;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(),SA)}async lookUpLightPollution(){if(!this.lightPollutionFromRecord())return;const e=this.ufoElement.sighting,t=e.event.place?.[0],i=++this.lightPollutionToken,s=this.lightPollutionProvider,n=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||n===void 0){this.lightPollutionLookup=void 0,this.syncLightPollutionStatus();return}if(n<s.year){r(),this.lightPollutionLookup={status:"too-early",year:n},this.syncLightPollutionStatus();return}this.lightPollutionLookup={status:"pending"},this.syncLightPollutionStatus();const a=await s.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:`${s.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=Qc(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=r5(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;we.show(this.playPauseButton,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[s,n]of[[this.previousMarkButton,this.messages.previousKeyframe],[this.nextMarkButton,this.messages.nextKeyframe]])s.title=n,s.setAttribute("aria-label",n);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,s]of[[this.timeStartLabel,this.messages.currentPosition],[this.timeEndLabel,this.messages.duration]])i.title=e?`${s} — ${t}`:s,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(sn.opensPrecise(e.time)),this.endDate.setPrecise(sn.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),s=e!==void 0&&i!==void 0&&Math.abs(e-i)>TU;this.utcOffsetInput.classList.toggle("invalid",s),this.utcOffsetInput.title=s?this.messages.utcOffsetImplausible.replace("{solar}",i>=0?`+${i}`:String(i)):"",this.showTimeZoneConsistency(s)}showTimeZoneConsistency(e){const t=this.ufoElement.sighting.event,i=this.placeZone&&t.time?.year!==void 0?this.timeZones.offsetHoursAt(this.placeZone,t.time):void 0,s=t.utcOffsetHours??(t.timeZone?this.timeZones.offsetHoursAt(t.timeZone,this.timeZoneReference()):void 0),n=i!==void 0&&s!==void 0&&s!==i;this.timeZoneSelect.classList.toggle("inconsistent",n&&this.timeZoneSelect.value!==""),this.utcOffsetInput.classList.toggle("inconsistent",n&&!e),this.timeZoneWarning.hidden=!n,this.timeZoneWarning.textContent=n?this.messages.utcOffsetInconsistent.replace("{zone}",this.placeZone).replace("{offset}",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),EU))}isSamePlace(e,t,i){return Math.abs(e.lat-t)<Zh&&Math.abs(e.lng-i)<Zh}async applyGroundElevation(e,t){const i=++this.groundElevationToken,s=zi(Km,this.chosenSourceId.get("elevation")),n=await new cM(s.create()).at(e,t);if(i!==this.groundElevationToken||n===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(n),this.syncElevationField(r)}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||Math.round(e)===0?"":this.messages.groundAt.replace("{m}",String(t))}syncGroundElevationField(){this.groundElevationToken++,clearTimeout(this.groundElevationTimer),this.groundElevationM=void 0,this.groundElevationFor=void 0,this.syncElevationField(tt(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(){this.witnessErrorView?.refresh();const e=this.ufoElement.sighting;this.observerIdInput.value=e.observer?.id??"",this.observerTitleInput.value=this.said.read(e.observer?.title)??"",this.observerLastNameInput.value=e.observer?.lastName??"",this.observerFirstNamesInput.value=e.observer?.firstNames?.join(", ")??"",this.observerList.rename(xe.OBSERVER_PRINCIPAL,this.principalObserverLabel()),this.sightingIdInput.value=e.id??"",this.observerAgeInput.value=e.account?.observerAgeYears?.toString()??"",this.birthDate.setPrecise(sn.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.evaluationFields.show(e.account),this.descriptionInput.value=this.said.read(e.event.description)??"",this.showTags(),this.instrumentSelect.value=e.instrument.id,this.swayInput.value=e.sway?.toString()??"";const t=e.lens;this.lensGlassSelect.value=t?.glass??"",this.lensDropsInput.value=t?.drops?.toString()??"",this.lensCondensationInput.value=t?.condensation?.toString()??"",this.lensDirtInput.value=t?.dirt?.toString()??"",this.lensShelteredInput.checked=t?.sheltered===!0,this.lightPollutionInput.value=e.lightPollution?.toString()??""}syncWeatherFromTimeline(){if(this.cloudEditor?.sync(),this.ufoElement.playbackState==="playing")return;const e=ys(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??y0)),t!==this.rareIceCrystalsInput&&(this.rareIceCrystalsInput.value=String(e.rareIceCrystals??CA)),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],s=this.shadow.activeElement;s!==this.latInput&&(this.latInput.value=t?.lat!==void 0?String(t.lat):i?String(i.lat):""),s!==this.lngInput&&(this.lngInput.value=t?.lng!==void 0?String(t.lng):i?String(i.lng):""),this.syncObserverPosition(),s!==this.headingInput&&(this.headingInput.value=t?.headingDeg!==void 0?String(this.rounded(t.headingDeg)):""),this.refreshHeadingPoint(),s!==this.pitchInput&&(this.pitchInput.value=String(this.rounded(t?.pitchDeg??0)),this.rollInput.value=String(this.rounded(t?.rollDeg??0))),s!==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.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,s=this.ufoElement.currentTime,n=i.getInterpolatedShapeAt(s,this.currentSourceId),r=this.buildAppearanceShape(e??n?.bounds??this.defaultBounds(),n,t);this.commitShapes(s,[{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 s=xM(e,this.currentAppearance);return t?{...s,angle:t.angle,title:t.title,selected:t.selected}:s}isGroupOpen(e){return e.getAttribute("aria-expanded")==="true"}toggleGroup(e,t){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();for(const[i,s]of this.groupTabs.entries()){const n=s===e&&t;s.setAttribute("aria-expanded",String(n)),this.groupPanels[i].hidden=!n}if(t){const i=e.parentElement.getBoundingClientRect(),s=e.getBoundingClientRect();(s.left<i.left||s.right>i.right)&&(e.parentElement.scrollLeft+=s.left-i.left-(i.width-s.width)/2)}if(t&&e.getAttribute("aria-controls")==="group-decor"){const i=this.decorList.value;i!==""&&i!==this.currentDecorId&&this.selectDecor(i)}t&&e.getAttribute("aria-controls")==="group-observer"&&this.observerShown!==xe.OBSERVER_PRINCIPAL&&this.selectDecor(this.observerShown),t&&e.getAttribute("aria-controls")==="group-weather"&&this.syncSkyParts(),t&&e.getAttribute("aria-controls")==="group-shape"&&this.showPhenomenonPartWithContent(),t&&e.getAttribute("aria-controls")==="group-observation"&&this.candidatesView?.refresh(),this.placeDecorItem(),this.syncCanvasMode(),this.refreshTimelineMarks(),t&&this.sectionFolds.refresh(),t&&e.getAttribute("aria-controls")==="group-file"&&this.loadFileEditor().then(()=>{this.syncFileEditor(!1),this.showFileItem(this.fileItemSelect.value)},()=>this.showFileNote(this.messages.importError,"error"))}loadFileEditor(){return this.fileEditorLoading??=(async()=>{this.showFileNote(this.messages.fileLoading);try{const{SightingFileEditor:e}=await Q(async()=>{const{SightingFileEditor:t}=await import("./SightingFileEditor-bXm0nVE4.js");return{SightingFileEditor:t}},__vite__mapDeps([23,3,24]),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 s=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(s!==void 0){this.fileFocus="shape",this.selectUnit(s.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(s=>s.id===e);return i>=0?["interpretation","bodies",i]:void 0}catch{return}}shapePath(e){const t=this.ufoElement.sighting.timeline.allKeyframes;for(const[i,s]of t.entries()){const n=s.shapes.findIndex(r=>r.sourceId===e);if(n>=0)return["timeline","keyframes",i,"shapes",n]}}showFileNote(e,t="info"){Ht.show(this.fileNote,e,t)}fileText(){return this.writtenText(this.ownJson(this.sightingData))}ownJson(e){const t={...e};for(const i of Yt.NAMES)this.ufoElement.sighting.snapshots?.[i]?.src!==void 0&&Yt.strip(i,t);return t}withAnnexed(e){const t=e.snapshots,i=this.sightingData;for(const s of Yt.NAMES){const n=Yt.taken(s,e);t?.[s]?.src===void 0||Object.values(n).some(r=>!Array.isArray(r)||r.length>0)||Yt.put(s,e,Yt.taken(s,i))}return e}writtenText(e){const t=this.keyframesWritten();return wx.of(e,t,t==="thin"?Ti.derivable(this.ufoElement.sighting):void 0)}keyframesWritten(){return this.wholeKeyframesInput.checked?"whole":"thin"}static WHOLE_KEYFRAMES_STORAGE="rr0-sighting-editor.whole-keyframes";setKeyframesWritten(){try{this.wholeKeyframesInput.checked?localStorage.setItem(xe.WHOLE_KEYFRAMES_STORAGE,"true"):localStorage.removeItem(xe.WHOLE_KEYFRAMES_STORAGE)}catch{}if(this.baseline){const e=Mw(JSON.parse(this.baseline)),t=this.keyframesWritten();this.baseline=wx.of(this.ownJson(P0(e)),t,t==="thin"?Ti.derivable(e):void 0),this.savedFileText=this.baseline}this.resetHistory()}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){if(t.edited)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))return;const s=JSON.stringify(i.weatherTrack);if(i=this.withAnnexed(i),!t&&JSON.stringify(i)===JSON.stringify(this.sightingData))return;const n=this.ufoElement.currentTime,r=!t&&this.fileTextApplied!==void 0&&s!==JSON.stringify(xe.weatherOf(this.fileTextApplied)),a={track:this.sightingData.weatherTrack,source:this.sightingData.weatherSource};this.applyingFileText=!0;try{if(this.sightingData=i,this.touched=!0,this.ufoElement.currentTime=n,r&&!this.restoringWeather&&this.weatherFromRecords){const o=this.ufoElement.sighting.weatherSource;o===void 0?(this.weatherFromRecords=!1,this.cancelWeatherLookup(),this.syncWeatherSourceState()):La.some(c=>c.id===o.id)&&this.askAboutWeather(a,o.name??o.id)}this.showFileNote(void 0),this.historySnapshot=this.fileText()}catch(o){this.showFileNote(o instanceof Sp?o.said(this.messages.formatVersionError):this.messages.importErrorMalformed,"error"),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))}static SCENE_LINKED=["heading","pitch","focalLength","apparentWidth","realWidth","objectDistance","color","haloScale","cloudCover","windDirection","windSpeed","referenceOpacity"];setActiveSceneField(e){e!==this.activeSceneField&&(this.activeSceneField=e,e==="referenceOpacity"&&!this.ufoElement.referencesShown?(this.ufoElement.toggleReferences(),this.referencesShownForField=!0):e!=="referenceOpacity"&&this.referencesShownForField&&(this.ufoElement.referencesShown&&this.ufoElement.toggleReferences(),this.referencesShownForField=!1),this.refreshSceneField())}refreshSceneField(){const e=this.sceneFieldOverlay;if(!e)return;const t=this.activeSceneField,i=this.ufoElement.sighting,s=this.ufoElement.currentTime,n=this.ufoElement.canvasElement,r=this.messages,a=c=>this.numberOrUndefined(c.value),o=(c,h=1)=>c===void 0?"?":c.toLocaleString(this.language,{maximumFractionDigits:h});if(t==="pitch"){const c=a(this.pitchInput)??0,h=br.of(i.instrument,n.height,Ti.fovOf(i,s)),d=Math.sign(c)*h.angleDegToRadiusPx(Math.min(89,Math.abs(c))),u=Math.min(1,Math.max(0,(n.height/2+d)/n.height));e.horizon(u,r.overlayHorizon.replaceAll("{deg}",o(c)))}else if(t==="focalLength"){const c=Ti.fovOf(i,s),d=2*br.of(i.instrument,n.height,c).halfWidthAngleDeg(n.width/n.height);e.frame(r.overlayFov.replaceAll("{v}",o(c)).replaceAll("{h}",o(d)))}else if(t==="apparentWidth"||t==="realWidth"||t==="objectDistance"){const c=i.timeline.getInterpolatedShapeAt(s,this.currentSourceId);if(!c){e.hide();return}const h=c.bounds,u=[[a(this.apparentWidthInput),"°",1],[a(this.realWidthInput)," m",1],[a(this.objectDistanceInput)," m",0]].filter(([p])=>p!==void 0).map(([p,f,m])=>`${o(p,m)}${f}`).join(" · ");e.measure((h.x+h.width/2)/n.width,(h.y+h.height/2)/n.height,Math.max(h.width,h.height)*1.3/n.width,u)}else if(t==="windDirection"||t==="windSpeed"){const c=a(this.windDirectionInput)??0,h=c-(a(this.headingInput)??0);e.wind(h,r.overlayWind.replaceAll("{point}",this.naming.point(c)).replaceAll("{speed}",o(a(this.windSpeedInput))))}else e.hide()}attachWitnessErrors(){const e=this,t=()=>this.ufoElement.sighting,i=()=>this.ufoElement.currentTime,s=this.shadow.querySelector('rr0-date-input[name="obs-time"]');this.witnessErrorView.attach({kind:"time",label:s.closest("label"),input:s,path:()=>t().event.time?"time":void 0,value:()=>t().event.time?.hour!==void 0?0:void 0}),this.witnessErrorView.attach({kind:"duration",label:this.durationElement.closest("label"),input:this.durationElement,path:()=>t().event.durationSeconds!==void 0?"durationSeconds":void 0,value:()=>t().event.durationSeconds});const n=c=>{let h=-1;return c.forEach((d,u)=>{d<=i()&&(h=u)}),h===-1&&c.length>0?0:h};this.witnessErrorView.attach({kind:"heading",label:this.headingInput.closest("label"),input:this.headingInput,path:()=>{const c=n(t().observerTrack.allKeyframes.map(h=>h.t));return c===-1||this.headingInput.value===""?void 0:`observerTrack.keyframes.${c}.pose.headingDeg`},value:()=>this.numberOrUndefined(this.headingInput.value)}),this.witnessErrorView.attach({kind:"angularSize",label:this.apparentWidthInput.closest("label"),input:this.apparentWidthInput,path:()=>{const c=t().timeline.allKeyframes,h=n(c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId)).map(f=>f.t));if(h===-1||this.apparentWidthInput.value==="")return;const d=c.filter(f=>f.shapes.some(m=>m.sourceId===this.currentSourceId))[h],u=c.indexOf(d),p=d.shapes.findIndex(f=>f.sourceId===this.currentSourceId);return`timeline.keyframes.${u}.shapes.${p}.shape.angular`},value:()=>this.numberOrUndefined(this.apparentWidthInput.value)});const r=this.shadow.getElementById("observerPerception").closest(".form-section");this.witnessErrorView.placeObserverSections(r);const a=document.createElement("div");a.className="form-section candidates-section",this.shadow.getElementById("group-observation").append(a);const o=c=>c?.closest("label")??void 0;this.candidatesView=new Tn({get sighting(){return e.ufoElement.sighting},messages:()=>this.messages.witnessError,model:()=>this.witnessErrorView.errorModel,conditions:()=>this.ufoElement.sighting.account?.conditions,start:()=>{const c=this.ufoElement.sighting.event,h=c.place?.[0];if(!h||c.time?.year===void 0||c.time.hour===void 0)return;const d=mn(c.time,h.lng,c.utcOffsetHours);return d?{date:d,observer:{lat:h.lat,lng:h.lng,elevationM:this.groundElevationM??0}}:void 0},limitAt:c=>$a(c,this.instrumentGain()),fieldLabels:()=>({time:o(s),heading:o(this.headingInput),size:o(this.apparentWidthInput),duration:o(this.durationInput)}),sceneCard:()=>this.shadow.querySelector(".scene-card"),poher:c=>{const h=`${c}/${this.language}`;return this.poherMatrix?.key!==h&&(this.poherMatrix={key:h,loaded:jl.load(c,this.language,d=>Ma.json(d))}),this.poherMatrix.loaded},facts:()=>this.poherFacts(),satellites:()=>{const c=(this.ufoElement.sighting.event.durationSeconds??0)*1e3||this.ufoElement.seekableDuration,h=this.sceneElement.satellitePassesDuring(c);return h.length>0?{passes:h,positionsAt:d=>this.sceneElement.satellitePositionsAt(d)}:void 0},burning:()=>this.sceneElement.burningCandidates(),traffic:()=>this.sceneElement.trafficCandidates(),interpretations:()=>{const c=this.ufoElement.sighting.interpretation;return[...c&&c.bodies.length>0?[{id:"own",label:this.said.read(c.title)??this.principalObserverLabel(),interpretation:c}]:[],...this.readings]},starName:c=>this.naming.star({name:c}),projectionAt:(c,h)=>this.sceneElement.bodyProjectionAt(c,h),variants:()=>this.ufoElement.sighting.variants,keep:c=>this.editVariants(h=>[...h,c]),remove:c=>this.editVariants(h=>h.filter((d,u)=>u!==c))},a)}readings=[];editVariants(e){this.touch(),this.armHistory(),this.ufoElement.sighting.variants=e(this.ufoElement.sighting.variants),this.scheduleHistoryRecord()}poherMatrix;poherFacts(){const e=this.ufoElement.sighting,t={},i=e.event,s=i.place?.[0];if(s&&i.time?.year!==void 0&&i.time.hour!==void 0){const h=mn(i.time,s.lng,i.utcOffsetHours);h&&(t.sunAltitudeDeg=Hi("Sun",h,{lat:s.lat,lng:s.lng,elevationM:this.groundElevationM??0}).altitudeDeg)}if(i.durationSeconds!==void 0&&(t.durationSeconds=i.durationSeconds),e.weatherTrack.allKeyframes.length>0){const h=ys(e,0);t.cloudCover=h.cloudCover,t.lightning=h.storm,t.lowVisibility=h.precipitationType!=="none"&&h.precipitationIntensity>.3}const n=e.timeline,r=n.sourceIds[0];if(r){const h=n.allKeyframes.filter(p=>p.shapes.some(f=>f.sourceId===r)),d=h.map(p=>({t:p.t,shape:n.getShapeAt(p.t,r)})).filter(p=>p.shape?.aim),u=n.getInterpolatedShapeAt(h[0]?.t??0,r);if(u?.aim&&(t.elevationDeg=u.aim.altitudeDeg),u?.angular){t.widthDeg=u.angular.widthDeg;const p=u.angular.heightDeg>0?u.angular.widthDeg/u.angular.heightDeg:1;t.round=u.kind==="oval"&&p>.8&&p<1.25}if(u?.brightness!==void 0&&(t.brightness=u.brightness),d.length>1){const p=(g,b)=>{const w=Math.PI/180,y=Math.sin(g.altitudeDeg*w)*Math.sin(b.altitudeDeg*w)+Math.cos(g.altitudeDeg*w)*Math.cos(b.altitudeDeg*w)*Math.cos((g.azimuthDeg-b.azimuthDeg)*w);return Math.acos(Math.max(-1,Math.min(1,y)))/w},f=d.slice(1).map((g,b)=>({deg:p(d[b].shape.aim,g.shape.aim),s:(g.t-d[b].t)/1e3}));t.sweepDeg=p(d[0].shape.aim,d[d.length-1].shape.aim);const m=f.reduce((g,b)=>g+b.deg,0);t.straysDeg=Math.max(0,m-t.sweepDeg)/2;const v=(d[d.length-1].t-d[0].t)/1e3;if(v>0){t.speedDegPerS=m/v;const g=Math.max(...f.filter(b=>b.s>0).map(b=>b.deg/b.s));t.speedVariation=t.speedDegPerS>0?g/t.speedDegPerS:0}}}const a=new Set(n.sourceIds.map(h=>n.groupMembers(h)?.[0]??h));a.size>0&&(t.count=a.size);const o=[...a].map(h=>n.getInterpolatedShapeAt(0,h)?.aim).filter(h=>h!==void 0);if(o.length>=3){const h=Math.PI/180,d=o.map(m=>({x:(((m.azimuthDeg-o[0].azimuthDeg)%360+540)%360-180)*Math.cos(m.altitudeDeg*h),y:m.altitudeDeg}));let[u,p]=[d[0],d[1]];for(const m of d)for(const v of d)Math.hypot(m.x-v.x,m.y-v.y)>Math.hypot(u.x-p.x,u.y-p.y)&&([u,p]=[m,v]);const f=Math.hypot(u.x-p.x,u.y-p.y);t.aligned=f>0&&d.every(m=>Math.abs((p.x-u.x)*(u.y-m.y)-(u.x-m.x)*(p.y-u.y))/f<=Math.max(.5,f*.1))}const c=new Set([...a].map(h=>n.getInterpolatedShapeAt(0,h)?.color).filter(h=>h!==void 0));return c.size>0&&(t.colors=[...c]),t.observers=e.observerCount,e.instrument.category==="eye"&&(t.nakedEye=!0),e.soundTrack.allKeyframes.some(h=>h.sound.kind!=="none")&&(t.sound=!0),t}candidatesTimer;refreshCandidatesSoon(){clearTimeout(this.candidatesTimer),this.isGroupIdOpen("group-observation")&&(this.candidatesTimer=setTimeout(()=>this.candidatesView?.refresh(),150))}showOverlays(){const e=this.shadow.querySelector(".scene-card");e.dataset.shown="",clearTimeout(this.overlayTimer),this.overlayTimer=setTimeout(()=>delete e.dataset.shown,3500)}static SCENE_HEIGHT_KEY="rr0-editor-scene-height";resizeScene(e){const t=this.shadow.querySelector(".app"),i=this.sceneElement,s=n=>{n===void 0?t.style.removeProperty("--rr0-scene-max-height"):t.style.setProperty("--rr0-scene-max-height",`${Math.round(Math.min(window.innerHeight*.85,Math.max(120,n)))}px`);try{n===void 0?localStorage.removeItem(xe.SCENE_HEIGHT_KEY):localStorage.setItem(xe.SCENE_HEIGHT_KEY,t.style.getPropertyValue("--rr0-scene-max-height"))}catch{}};try{const n=localStorage.getItem(xe.SCENE_HEIGHT_KEY);n&&/^\d+px$/.test(n)&&t.style.setProperty("--rr0-scene-max-height",n)}catch{}e.addEventListener("pointerdown",n=>{n.preventDefault();const r=n.clientY,a=i.getBoundingClientRect().height;e.setPointerCapture?.(n.pointerId),e.classList.add("dragging");const o=h=>s(a+h.clientY-r),c=()=>{e.classList.remove("dragging"),e.removeEventListener("pointermove",o),e.removeEventListener("pointerup",c),e.removeEventListener("pointercancel",c)};e.addEventListener("pointermove",o),e.addEventListener("pointerup",c),e.addEventListener("pointercancel",c)}),e.addEventListener("keydown",n=>{n.key!=="ArrowUp"&&n.key!=="ArrowDown"||(n.preventDefault(),s(i.getBoundingClientRect().height+(n.key==="ArrowUp"?-20:20)))}),e.addEventListener("dblclick",()=>s(void 0))}setTracksShown(e){this.shadow.querySelector(".scene-card").toggleAttribute("data-tracks",e),this.shadow.getElementById("timeline-tracks").hidden=!e,this.tracksToggle.setAttribute("aria-expanded",String(e));const i=e?this.messages.collapseTracks:this.messages.expandTracks;this.tracksToggle.title=i,this.tracksToggle.setAttribute("aria-label",i),this.refreshTracks()}flash(e){e&&(e.classList.add("flash"),setTimeout(()=>e.classList.remove("flash"),1800))}refreshTracks(){if(!this.timelineTracks||this.tracksToggle.getAttribute("aria-expanded")!=="true")return;const e=this.ufoElement.sighting,t=this.messages,i=a=>{const o=this.groupTabs.find(c=>c.getAttribute("aria-controls")===a);o&&this.toggleGroup(o,!0)},s=a=>()=>{this.touch(),this.armHistory(),a(),this.scheduleHistoryRecord(),this.refreshTimelineMarks()},r=[this.showsBodies?{id:"bodies",label:t.bodiesTrack,color:"#f5c451",...this.eventMarks("bodies"),open:()=>this.chooseAccountView(!0),selected:this.pickedEvent(this.bodiesEventsPanel),select:a=>this.pickEvent(Number(a)),add:()=>this.bodyEditor?s(()=>this.bodyEditor.keyframeHere())():this.chooseAccountView(!0)}:{id:"shapes",label:t.shapesTrack,color:"#f5c451",...this.eventMarks("phenomenon"),open:()=>this.revealShapePanel(),selected:this.pickedEvent(this.phenomenonEventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>{e.timeline.sourceIds.includes(this.currentSourceId)&&this.applyAppearanceAtPlayhead(void 0,!1)})},{id:"observer",label:t.observerTrack,color:"#7fd4ff",...this.eventMarks("observer"),open:()=>i("group-location"),selected:this.pickedEvent(this.eventsPanel),select:a=>this.pickEvent(Number(a)),add:s(()=>this.updateObserver())},{id:"weather",label:t.weatherTrack,color:"#b9c8d8",times:e.weatherTrack.allKeyframes.map(a=>a.t),open:()=>i("group-weather"),add:s(()=>this.applyWeatherAtPlayhead())},{id:"sound",label:t.soundTrack,color:"#9fd9a8",times:e.soundTrack.allKeyframes.map(a=>a.t),open:()=>i("group-sound"),add:s(()=>this.applySoundAtPlayhead())}];this.timelineTracks.show(r,this.ufoElement.seekableDuration,this.ufoElement.currentTime)}eventMarks(e){const t=this.ufoElement.sighting;if(e==="bodies")return this.bodyMarks();const i=e==="observer"?ht.observerTrackIsExpanded(t):ht.timelineIsExpanded(t),s=e==="observer"?t.observerTrack.allKeyframes:t.timeline.allKeyframes;if(!i)return{times:s.map(h=>h.t)};const n=this.ufoElement.seekableDuration,r=h=>e==="observer"?Vt.isObserver(t,h):Vt.isPhenomenon(t,h),a=(t.events??[]).map((h,d)=>({event:h,index:d})).filter(({event:h})=>r(h)),o=new Set(a.map(({event:h})=>h.who)).size>1,c=a.map(({event:h,index:d})=>{const u=this.messages.events.kinds[h.eventType]??h.eventType;return{id:String(d),t:h.t,until:h.until??n,label:e==="phenomenon"&&o?`${this.shapesLabel(h.who??"")} · ${u}`:u}});return{times:[],spans:c}}bodyMarks(){const e=this.ufoElement.sighting,t=e.interpretation?.bodies??[],i=new Set(t.map(o=>o.id)),s=o=>Vt.partOf(o)?.element??o??"",n=(e.events??[]).map((o,c)=>({event:o,index:c})).filter(({event:o})=>i.has(s(o.who)));if(n.length===0||!ht.bodiesAreExpanded(e))return{times:[...new Set(t.flatMap(o=>o.track.map(c=>c.t)))].sort((o,c)=>o-c)};const r=this.ufoElement.seekableDuration,a=n.map(({event:o,index:c})=>{const h=t.find(f=>f.id===s(o.who)),d=Vt.partOf(o.who)?.part,u=this.messages.events.kinds[o.eventType]??o.eventType,p=[...t.length>1?[this.said.read(h?.title)??s(o.who)]:[],...d?[d]:[]];return{id:String(c),t:o.t,until:o.until??r,label:[...p,u].join(" · ")}});return{times:[],spans:a}}pickedEvent(e){const t=e?.pickedIndex,i=e===this.eventsPanel?"events-section":e===this.phenomenonEventsPanel?"phenomenon-events-section":"bodies-events-section",s=this.shadow.getElementById(i);return t===void 0||!s||s.closest("[hidden]")?void 0:String(t)}pickEvent(e){const t=this.ufoElement.sighting,i=t.events?.[e];if(!i)return;const s=i.who??Vt.observerId(t);if(Vt.isObserver(t,i)){const n=this.groupTabs.find(r=>r.getAttribute("aria-controls")==="group-location");n&&this.toggleGroup(n,!0),this.eventsPanel.pick(e)}else Vt.isPhenomenon(t,i)?(this.revealShapePanel(),this.phenomenonEventsPanel.pick(e)):(this.chooseAccountView(!0),this.loadBodyEditor().then(n=>{n.show(Vt.partOf(s)?.element??s),this.bodiesEventsPanel.pick(e),this.refreshTracks()}));this.goToMark(i.t),this.refreshTracks()}shapesLabel(e){const t=this.ufoElement.sighting,i=t.timeline.groupOf(e);if(i)return this.said.read(i.title)??e;const s=t.timeline.allKeyframes.map(n=>n.shapes.find(r=>r.sourceId===e)?.shape.title).find(n=>n!==void 0);return this.said.read(s)??e}get showsBodies(){return this.accountViewSelect.value==="bodies"}refreshTimelineMarks(){const e=this.ufoElement.sighting,t=(o,c)=>[...c].map(h=>({t:h,kind:"keyframe",label:`${this.messages.keyframeMark} (${o})`})),i=o=>{if(this.showsBodies){const h=this.eventMarks("bodies");return h.spans?h.spans.map(d=>({t:d.t,kind:"event",label:d.label})):t(this.messages.bodiesTrack,h.times)}const{spans:c}=this.eventMarks("phenomenon");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.shapesTrack,e.timeline.allKeyframes.filter(h=>!o||h.shapes.some(d=>this.selectedSourceIds.has(d.sourceId))).map(h=>h.t))},s=()=>{const{times:o,spans:c}=this.eventMarks("observer");return c?c.map(h=>({t:h.t,kind:"event",label:h.label})):t(this.messages.observerTrack,o)},n=()=>t(this.messages.weatherTrack,e.weatherTrack.allKeyframes.map(o=>o.t)),r=()=>t(this.messages.soundTrack,e.soundTrack.allKeyframes.map(o=>o.t)),a=this.isGroupIdOpen("group-shape")?i(!0):this.isGroupIdOpen("group-observer")||this.isGroupIdOpen("group-location")?s():this.isGroupIdOpen("group-weather")?n():this.isGroupIdOpen("group-sound")?r():[...i(!1),...s(),...n(),...r()];for(const o of e.milestones)a.push({t:o.t,kind:"milestone",label:this.said.read(o.label)??""});this.timelineMarks.show(a,this.ufoElement.seekableDuration),this.refreshTracks(),this.eventsPanel?.sync(),this.phenomenonEventsPanel?.sync(),this.bodiesEventsPanel?.sync(),this.witnessErrorView?.refreshFields(),this.activeSceneField&&this.refreshSceneField()}seekTo(e){this.goToMark(e*1e3)}set passages(e){const t=this.shadow.getElementById("moment-passages");t.replaceChildren(...(e??[]).map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.className="at",n.innerHTML=st.PLAY,n.append(i.clock),n.addEventListener("click",()=>this.seekTo(i.at));const r=document.createElement("button");return r.type="button",r.className="excerpt",r.textContent=i.said,r.title=i.where,r.addEventListener("click",()=>i.open()),s.append(n,r),s})),t.hidden=t.childElementCount===0}openSection(e){const t=this.groupTabs.find(i=>i.getAttribute("aria-controls")===e);t&&this.toggleGroup(t,!0)}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-weather")&&this.openSkyParts().some(e=>e.category==="skyEvent")?"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",s=e!==this.lastCanvasMode;this.lastCanvasMode=e,this.ufoElement.selectionShown=e==="shape",t&&this.currentReference()&&this.loadPictureRegistration(),this.ufoElement.overlayPainter=t?this.paintPictureOverlay:e==="body"?this.paintBodyOverlay:e==="decor"?this.paintDecorOverlay:void 0,s&&this.ufoElement.repaintOverlay(),t!==i&&this.setCanvasCursor(t?"pan":this.hoverCursor),!t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark();const n=this.currentReference();n&&this.syncReferenceStatus(n),this.syncStreetSearchAvailability(),this.syncBodiesShown()}skyOf(e){const t=Zc.kinds();if(Zn.computes(e,t))return this.skyPart?.of!==e&&(this.skyPart={of:e,sky:{bodies:[],...Zn.computedPart(e,t)}}),this.skyPart.sky}skyPart;syncBodiesShown(){const t=!(this.isGroupIdOpen("group-shape")&&this.shadow.getElementById("shape-shapes")?.hidden===!1)||this.isReading,i=this.ufoElement.sighting.interpretation,s=t?i:this.skyOf(i);this.sceneElement.compareAccount=t&&s!==void 0&&this.accountCompareInput.checked,this.sceneElement.interpretation!==s&&(this.sceneElement.interpretation=s);const n=t&&s!==void 0?"bodies":"shapes",r=this.accountViewSelect.value!==n;this.accountViewSelect.value=n,r&&this.refreshTimelineMarks(),this.syncSkyParts(),this.shadow.getElementById("account-view-row").hidden=this.isReading,this.shadow.getElementById("account-compare-row").hidden=this.isReading||n!=="bodies"}syncSkyParts(){if(this.isGroupIdOpen("group-weather"))for(const e of this.openSkyParts())this.loadSkyPartEditor(e)?.then(t=>t.refresh())}chooseAccountView(e){const t=this.groupTabs.find(s=>s.getAttribute("aria-controls")==="group-shape");t&&this.toggleGroup(t,!0);const i=this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===(e?"shape-bodies":"shape-shapes"));i&&this.openSubgroup(i)}openSubgroup(e){this.sectionChosen=!0,this.opensMostLacking=!1,this.cloudEditor?.stopManipulation();const t=e.parentElement;for(const s of this.subgroupTabs){if(s.parentElement!==t)continue;const n=s===e;s.setAttribute("aria-expanded",String(n)),this.shadow.getElementById(s.getAttribute("aria-controls")).hidden=!n}e.getAttribute("aria-controls")==="shape-bodies"&&this.loadBodyEditor().then(s=>s.sync());const i=[...this.skyParts.values()].find(s=>s.tab===e);i&&this.loadSkyPartEditor(i)?.then(s=>s.sync()),this.syncCanvasMode()}showPhenomenonPartWithContent(){const e=this.ufoElement.sighting,t=e.timeline.sourceIds.length>0,i=(e.interpretation?.bodies?.length??0)>0,n=this.shadow.getElementById("shape-bodies")?.hidden===!1?!i&&t?"shape-shapes":void 0:!t&&i?"shape-bodies":void 0,r=n&&this.subgroupTabs.find(c=>c.getAttribute("aria-controls")===n);if(!r)return;const{sectionChosen:a,opensMostLacking:o}=this;this.openSubgroup(r),this.sectionChosen=a,this.opensMostLacking=o}revealSubgroupOf(e){const t=e.closest(".subgroup-panel"),i=t&&this.subgroupTabs.find(s=>s.getAttribute("aria-controls")===t.id);i&&this.openSubgroup(i)}panelOf(e){return(e.getAttribute("aria-controls")??"").replace(/^group-/,"")}panelIndex(e){return this.groupTabs.findIndex(t=>this.panelOf(t)===e)}refreshParamSummary(){if(!this.paramSummaryBuilder)return;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("|"),s=JSON.stringify(this.ufoElement.sighting.account??null);if(i===this.paramSummarySignature){s!==this.assessedAccount?(this.assessedAccount=s,this.assessSoon()):this.assessmentsOwed&&this.ufoElement.playbackState!=="playing"&&this.assessSoon();return}this.assessedAccount=s,this.paramSummarySignature=i,this.paramChips=t,this.renderParamSummary(),this.assessSoon()}assessmentsOwed=!1;assessSoon(){if(this.ufoElement.playbackState==="playing"){this.assessmentsOwed=!0;return}this.assessmentsOwed=!1,this.runAssessments()}paramChips=[];renderParamSummary(){this.saveButton&&this.refreshEditorTitle();const e=xe.NESTED_GROUPS,t=[];let i;for(const s of[...this.paramChips,...this.assessmentChips]){if(i&&i.group!==s.group&&(i=void 0),e.includes(s.group)&&!i){const r=document.createElement("span");r.className="param-nest",r.dataset.group=s.group;const a=document.createElement("span");a.className="param-nest-label",a.textContent=s.group==="assessment"?this.messages.assessmentGroup:s.group==="summary"?this.messages.summaryGroup:xe.tabLabel(this.groupTabs[this.summaryPanelIndex(s.group)]),r.append(a),i={group:s.group,element:r},t.push(r)}const n=this.paramChip(s);i?i.element.append(n):t.push(n)}this.paramSummary.replaceChildren(...t),this.shadow.getElementById("label-param-summary").textContent=this.messages.paramSummaryTitle.replace("{n}",String(t.length)),this.syncDescription()}openDescription;syncDescription(){this.openDescription!==void 0&&!this.paramChips.some(e=>e.full===this.openDescription)&&(this.openDescription=void 0),kT.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 this.panelIndex(e==="phenomenon"?"shape":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"]},"bg-information":{panel:"observer",fields:["accountSource"]},"bg-occupation":{panel:"observer",fields:["observerOccupationKind"]},"bg-relation":{panel:"observer",fields:["observersRelation"]},"bg-activity":{panel:"observer",fields:["observerActivity"]},"bg-age":{panel:"observer",fields:["observerAge"]},"bg-appearance":{panel:"observer",fields:["strangeness-appearance"]},"bg-movement":{panel:"observer",fields:["strangeness-movement"]},"bg-incongruity":{panel:"observer",fields:["strangeness-incongruity"]},"bg-close":{panel:"observer",fields:["strangeness-close"]},"bg-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-traces":{panel:"observer",fields:["strangeness-traces"]},"poher-occupants":{panel:"observer",fields:["strangeness-beings"]}};assessmentChips=[];assessmentToken=0;assessedAccount="";async runAssessments(){const e=++this.assessmentToken,t=await new ww(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.openMostLackingGroup(),this.renderParamSummary())}opensMostLacking=!1;sectionChosen=!1;openMostLackingGroup(){if(!this.opensMostLacking)return;this.opensMostLacking=!1;const e=s=>{const n=s.querySelector(".tab-badge");return n&&!n.hidden?Number(n.textContent):0},t=this.groupTabs.find(s=>this.isGroupOpen(s));let i=t&&e(t)>0?t:void 0;for(const s of this.groupTabs)e(s)>(i?e(i):0)&&(i=s);i&&i!==t&&(this.toggleGroup(i,!0),this.sectionChosen=!1)}fitGroupTabs(){const e=this.groupTabs[0]?.parentElement;e&&(e.classList.add("measuring"),e.classList.remove("compact"),e.classList.toggle("compact",e.scrollWidth>e.clientWidth),e.offsetWidth,e.classList.remove("measuring"))}static titleGroupTab(e){e.title=[e.dataset.intro,e.dataset.unanswered].filter(Boolean).join(`
|
|
11755
11755
|
`)}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 n of e){const r=xe.QUESTION_FIELDS[n];if(r&&!r.fields.some(a=>this.shadow.getElementById(a)?.classList.contains("missing-required")))for(const a of r.fields){const o=this.shadow.getElementById(a);o&&!o.hidden&&o.value===""&&t.add(a)}}for(const[n,r]of Object.entries(xe.QUESTION_FIELDS))for(const a of xe.QUESTION_FIELDS[n].fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=t.has(a)&&!o.classList.contains("missing-required");o.classList.toggle("wanted",c),(c||o.title===this.messages.questionUnanswered)&&(o.title=c?this.messages.questionUnanswered:this.fieldHints.get(a)??"")}const i=new Map;let s;for(const[n,r]of Object.entries(xe.QUESTION_FIELDS))for(const a of r.fields){const o=this.shadow.getElementById(a);if(!o)continue;const c=o.classList.contains("missing-required");!c&&!o.classList.contains("wanted")||(c&&(s=r.panel),i.set(r.panel,(i.get(r.panel)??0)+1))}for(const n of this.groupTabs){const r=this.panelOf(n),a=i.get(r)??0,o=r===s,c=xe.badgeOn(n);c.hidden=a===0,c.textContent=String(a),c.classList.toggle("optional",!o);const h=a===0?void 0:o?this.messages.durationRequired:this.messages.questionsUnanswered.replace("{count}",String(a));h?n.dataset.unanswered=h:delete n.dataset.unanswered,xe.titleGroupTab(n)}}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,e.detail&&(t.title=e.detail);const i=document.createElement("span");if(i.className="param-chip-label",i.textContent=`${e.label} `,t.append(i),e.color!==void 0){const n=document.createElement("span");n.className="param-chip-swatch",n.style.background=e.color,t.append(n)}const s=document.createElement("span");return s.className="param-chip-value",s.textContent=e.unit===""?e.value:`${e.value} ${e.unit}`,t.append(s),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 s=this.groupPanels[i];this.toggleGroup(this.groupTabs[i],!0);const n=t.dataset.field;if(n.startsWith("shape:")){this.selectedSourceIds=new Set([n.slice(6)]),this.revealShapePanel(),this.ufoElement.refresh();return}if(n.startsWith("body:")){const a=this.subgroupTabs.find(o=>o.getAttribute("aria-controls")==="shape-bodies");a&&this.openSubgroup(a),this.loadBodyEditor().then(o=>o.show(n.slice(5)));return}if(n.startsWith("decor:")){this.currentDecorId=n.slice(6),this.refreshDecorList(),this.decorList.focus();return}const r=this.shadow.getElementById(n);r===null||!s.contains(r)||(this.revealSubgroupOf(r),this.sectionFolds.reveal(r),r.focus(),r instanceof HTMLInputElement&&r.type!=="checkbox"&&r.type!=="color"&&r.type!=="range"&&r.select(),r.scrollIntoView?.({block:"center"}))}onSelectionOrTimeChanged(){this.showAircraftFlights(),this.shadow.getElementById("shape-bodies")?.hidden===!1&&this.bodyEditor?.syncKeyframe();for(const i of this.openSkyParts())i.editor?.setTime?.(this.ufoElement.currentTime);for(const i of[this.eventsPanel,this.phenomenonEventsPanel,this.bodiesEventsPanel])i?.setTime(this.ufoElement.currentTime);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.samplingRateInput!==this.shadow.activeElement&&(this.samplingRateInput.value=this.ufoElement.sighting.sampleMs===void 0?"":String(this.ufoElement.sighting.sampleMs)),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.getElementById("shape-row");t&&gn.showPresence(t,this.shadow.getElementById("shape-item")??void 0,!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.shapeRotationInput])i.disabled=e,i.title=e?t:this.fieldHints.get(i.id)??""}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:NU(e),color:e.color,transparency:e.transparency,haloScale:e.haloScale,blur:e.blur??0,brightness:e.brightness??0},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.shadow.activeElement!==this.shapeRotationInput&&(this.shapeRotationInput.value=String(xe.rotationDeg(e.angle))),this.refreshApparentSize())}static rotationDeg(e){const t=(e*180/Math.PI%360+540)%360-180;return Math.round((t===-180?180:t)*10)/10}updateShapeRotation(){const e=this.numberOrUndefined(this.shapeRotationInput.value);if(e===void 0)return;const t=this.ufoElement.sighting.timeline,i=this.ufoElement.currentTime,s=t.getInterpolatedShapeAt(i,this.currentSourceId);s&&(this.commitShapes(i,[{sourceId:this.currentSourceId,shape:{...s,angle:e*Math.PI/180}}]),this.ufoElement.refresh())}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,Pt.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,Pt.distanceMAt(e,i)),this.refreshDepth());return}const t=this.currentDistanceM();t!==void 0&&t>0&&this.applyApparentWidth(Pt.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(Pt.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,s=t.getInterpolatedShapeAt(i,this.currentSourceId);if(!s)return;const n=this.currentProjection(),r=n.degToPx(e),a=s.bounds.height*(s.bounds.width===0?1:r/s.bounds.width),o={x:s.bounds.x+(s.bounds.width-r)/2,y:s.bounds.y+(s.bounds.height-a)/2,width:r,height:a},c=n.ofBounds(o),h=s.kind==="oval"?{...s,bounds:o,angular:c}:{...s,bounds:o,angular:c,points:this.scalePoints(s,o)};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,s=e.bounds.height===0?1:t.height/e.bounds.height;return e.points.map(n=>({x:n.x*i,y:n.y*s}))}refreshFilterOptions(){const e={[ji.NONE.id]:this.messages.filterNone,[ji.SOLAR_VISUAL.id]:this.messages.filterSolarVisual,[ji.SOLAR_PHOTO.id]:this.messages.filterSolarPhoto},t=n=>e[n.id]??n.name,i=[...this.filterSelect.options].map(n=>n.textContent);if(i.length!==ji.ALL.length||ji.ALL.some((n,r)=>i[r]!==t(n))){const n=this.filterSelect.value||ji.NONE.id;this.filterSelect.replaceChildren();for(const r of ji.ALL){const a=document.createElement("option");a.value=r.id,a.textContent=t(r),this.filterSelect.appendChild(a)}this.filterSelect.value=n}const s=this.ufoElement?.sighting?.instrument;for(const n of this.filterSelect.options){const r=!s||ji.usableWith(ji.byId(n.value),s);n.disabled=!r,n.title=r?"":this.messages.filterNotForInstrument}}refreshInstrumentOptions(){const e=this.ufoElement.sighting,t=e.event.time?.year,i=e.instrument,s={eye:this.messages.instrumentCategoryEye,camera:this.messages.instrumentCategoryCamera,dslr:this.messages.instrumentCategoryDslr,phone:this.messages.instrumentCategoryPhone,video:this.messages.instrumentCategoryVideo,binoculars:this.messages.instrumentCategoryBinoculars,telescope:this.messages.instrumentCategoryTelescope},n=r=>{const a=this.naming.instrument(r),o=Qt.unavailability(r,t);if(!o)return{id:r.id,label:a};const c=(o.kind==="before"?this.messages.instrumentNotYetOnSale:this.messages.instrumentNoLongerOnSale).replace("{year}",String(t)).replace("{from}",String(o.from)).replace("{to}",String(o.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=Qt.CATEGORIES.map(r=>({label:s[r],children:Ku.filter(a=>a.category===r).map(n)})).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=xe.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 n=Number(i[1]),r=Number(i[2]);return r>0?n/r:void 0}const s=Number(t);return Number.isFinite(s)&&s>0?s:void 0}syncOpticsFromInstrument(){const e=this.ufoElement.sighting,t=e.instrument,i=tt(e,this.ufoElement.currentTime),s=t.frame,n=i?.fovDeg??Qt.fieldOfViewDeg(t),r=s?Qt.focalLengthMmFor(t,n):n;this.focalLengthInput!==this.shadow.activeElement&&(this.focalLengthInput.value=r===void 0?"":String(Math.round(r*10)/10)),this.unitFocalLength.textContent=s?this.messages.unitMillimetres:this.messages.unitDegrees,this.labelFocalLength.textContent=s?this.messages.focalLength:this.messages.fieldOfView,this.focalLengthInput.disabled=s!==void 0&&s.focalRangeMm===void 0,this.focalLengthInput.min=String(s?s.focalRangeMm?.minMm??1:1),this.focalLengthInput.max=String(s?s.focalRangeMm?.maxMm??2e3:179),fn.fit(this.focalLengthInput.parentElement??this.shadow),this.focalFovOutput.textContent=s&&n!==void 0?this.messages.fieldOfViewReadout.replace("{deg}",this.plain(n,n<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 o=e.exposure;this.exposureInput!==this.shadow.activeElement&&(this.exposureInput.value=o===void 0?"":xe.exposureText(o)),this.setRowVisible(this.exposureInput,t.exposureSeconds!==void 0);for(const d of[this.lensGlassSelect,this.lensDropsInput,this.lensCondensationInput,this.lensDirtInput,this.lensShelteredInput])this.setRowVisible(d,xi.records(t));this.exposureInput.disabled=t.exposureRangeSeconds===void 0;const c=t.medium;this.isoInput!==this.shadow.activeElement&&(this.isoInput.value=e.iso===void 0?"":String(e.iso)),this.syncFilmStocks(e,t);const h=Wo.byId(e.film);this.isoInput.placeholder=c?c.autoExposure?"auto":String(h?.iso??c.iso):"",this.setRowVisible(this.isoInput,c!==void 0),this.meteringSelect.value=e.metering??"",this.setRowVisible(this.meteringSelect,c?.autoExposure===!0),this.meteringSelect.disabled=e.iso!==void 0,this.focusDistanceInput!==this.shadow.activeElement&&(this.focusDistanceInput.value=i?.focusDistanceM===void 0?"":String(i.focusDistanceM)),this.setRowVisible(this.focusDistanceInput,s!==void 0&&t.fNumber!==void 0),this.filterSelect!==this.shadow.activeElement&&(this.filterSelect.value=ji.byId(i?.filter).id),this.ufoElement.playbackState!=="playing"&&this.sectionFolds?.refresh()}retuneFieldOfView(e){const t=this.ufoElement.sighting,i=Qt.fieldOfViewDeg(e),s=Qt.fieldOfViewDeg(t.instrument);for(const n of[...t.observerTrack.allKeyframes])Math.abs(n.pose.fovDeg-i)>DU||t.observerTrack.addKeyframe(n.t,{...n.pose,fovDeg:s})}retuneExposure(e){const t=this.ufoElement.sighting,i=t.exposureSeconds,s=t.instrument.exposureRangeSeconds;if(i===void 0||i===e.exposureSeconds||!s){t.exposureSeconds=void 0;return}t.exposureSeconds=Math.min(s.max,Math.max(s.min,i))}currentFovDeg(){const e=this.ufoElement.sighting;return tt(e,this.ufoElement.currentTime)?.fovDeg??Qt.fieldOfViewDeg(e.instrument)}currentProjection(){return br.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=Pt.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 s=tt(this.ufoElement.sighting,this.ufoElement.currentTime),n=s?.focusDistanceM;if(n!==void 0){this.blurBoundOutput.textContent=this.messages.blurBoundNotAtInfinity.replace("{focus}",this.meters(n));return}const r=(s?Qt.focalLengthMmFor(t,s.fovDeg):void 0)??i.focalLengthMm,a=s?.fNumber??t.fNumber;if(a===void 0||r<=0){this.blurBoundOutput.textContent="";return}const o=this.ufoElement.canvasElement.height;if(o<=0)return;const c=2*Eb*e/o*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 s=this.numberOrUndefined(this.realWidthInput.value),n=s!==void 0&&(t!==void 0&&s<t||i!==void 0&&s>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+n;return}this.realSizeOutput.textContent=(t!==void 0?this.messages.realSizeAtLeast.replace("{min}",this.meters(t)):this.messages.realSizeAtMost.replace("{max}",this.meters(i)))+n}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),s=(m,v)=>Number(m.toFixed(v)),n=i?.aim??{azimuthDeg:Number(this.headingInput.value)||0,altitudeDeg:Number(this.pitchInput.value)||0},r=(i?this.sceneElement.depthOf(e)?.distanceM:void 0)??SU,a=this.sceneElement.groundAlong(n.azimuthDeg,n.altitudeDeg,t),o=a!==void 0&&a<r,c=s(r,1),h=i?.angular?.widthDeg,d=i?.angular?.heightDeg,u=h!==void 0&&d!==void 0&&h>0&&d>0?{widthM:s(Pt.sizeMAt(c,h),2),lengthM:s(Pt.sizeMAt(c,h),2),heightM:s(Pt.sizeMAt(c,d),2)}:void 0,p={azimuthDeg:s(n.azimuthDeg,2),altitudeDeg:s(n.altitudeDeg,2)},f={t,...p,distanceM:c,...o?{onGround:!0}:{},...u?{sizeM:u}:{}};return i?{sourceId:e,label:this.shapeLabel(e),keyframe:f}:{keyframe:f}}loadBodyEditor(){return this.bodyEditorLoading??=Q(async()=>{const{BodyEditor:e}=await import("./BodyEditor-CamqX5Xg.js");return{BodyEditor:e}},[],import.meta.url).then(({BodyEditor:e})=>(this.bodyEditor=new e(this.shadow.getElementById("body-editor"),{sighting:()=>this.ufoElement.sighting,bodySelected:()=>this.bodiesEventsPanel.render(),said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),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},duration:()=>this.ufoElement.seekableDuration,readingOf:(t,i)=>this.sceneElement.bodyReading(t,i),groundAlong:(t,i,s)=>this.sceneElement.groundAlong(t,i,s)},this.language),this.bodyEditor)),this.bodyEditorLoading}openSkyParts(){return[...this.skyParts.values()].filter(e=>!e.panel.hidden)}wantedSkyParts(){const e=Zc.kinds().filter(i=>i.editor).map(i=>({key:`interpretation:${i.key}`,id:`interpretation-${i.key}`,category:"interpretation",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),shapes:()=>this.bodyShapeIds().map(r=>({id:r,label:this.shapeLabel(r)})),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.syncBodiesShown()}},this.language))})),t=Qp.map(i=>Or.of(i)).filter(i=>i.editor).map(i=>({key:`skyEvent:${i.key}`,id:`sky-event-${i.key}`,category:"skyEvent",kind:i,titles:i.messages,create:()=>i.editor().then(s=>n=>s(n,{sighting:()=>this.ufoElement.sighting,said:()=>this.said,writingLanguage:()=>this.writingLanguage,positionPlace:()=>this.framePlace(),currentTime:()=>this.ufoElement.currentTime,duration:()=>this.ufoElement.seekableDuration,seekTo:r=>this.goToMark(r),changed:()=>{this.ufoElement.refresh(),this.refreshParamSummary(),this.sceneElement.redrawSky()}},this.language))}));return[...e,...t]}buildSkyParts(){const e=this.shadow.getElementById("weather-tabs"),t=this.shadow.getElementById("sky-event-parts");if(!e||!t)return;const i=this.wantedSkyParts();for(const[s,n]of this.skyParts)if(!i.some(r=>r.key===s&&r.kind===n.kind)){if(n.tab.getAttribute("aria-expanded")==="true"){const r=this.subgroupTabs.find(a=>a.parentElement===e&&a!==n.tab);r&&this.openSubgroup(r)}n.tab.remove(),n.panel.remove(),this.subgroupTabs.splice(this.subgroupTabs.indexOf(n.tab),1),this.skyParts.delete(s)}for(const s of i){if(this.skyParts.has(s.key))continue;const n=document.createElement("button");n.className="subgroup-tab",n.type="button",n.setAttribute("aria-controls",s.id),n.setAttribute("aria-expanded","false");const r=document.createElement("span");r.id=`label-${s.id}`,this.nameSkyPart(r,s.titles),n.append(r),n.addEventListener("click",()=>this.openSubgroup(n)),e.append(n),this.subgroupTabs.push(n);const a=document.createElement("section");a.className="subgroup-panel",a.id=s.id,a.hidden=!0,a.setAttribute("aria-labelledby",r.id);const o=document.createElement("div");o.className="toolbar";const c=document.createElement("div");c.id=`${s.id}-editor`,o.append(c),a.append(o),t.before(a),this.skyParts.set(s.key,{...s,tab:n,label:r,panel:a})}for(const s of i){const n=this.skyParts.get(s.key);e.append(n.tab),t.before(n.panel)}}applyPerceptionLabels(){const e=this.decidedLanguage;if(e===void 0)return;const t=[...new Set(ya.ALL.map(i=>i.messages))];Promise.all(t.map(i=>i.load(e))).then(i=>{this.decidedLanguage===e&&(this.perceptionSettings.labels=Object.assign({},...i))},()=>{})}nameSkyPart(e,t){const i=this.decidedLanguage;i!==void 0&&t.load(i).then(s=>{this.decidedLanguage===i&&(e.textContent=s.title)},()=>{})}loadSkyPartEditor(e){return e.loading??=e.create().then(t=>(e.editor=t(e.panel.querySelector(`#${e.id}-editor`)),e.editor)),e.loading}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 n=i===void 0||i<=0?void 0:Pt.sizeMAt(e.distanceM,i);this.realWidthInput.value=n===void 0?"":this.plain(n,n<1?2:n<10?1:0)}this.clearDistanceHypothesisButton.hidden=e.basis!=="hypothesis";const s={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=s.replace("{m}",t)}commitShapes(e,t){const i=this.ufoElement.sighting,s=br.of(i.instrument,Pt.CANVAS_HEIGHT_PX,Ti.fovOf(i,e)),n=this.ufoElement.seekableDuration;n>i.timeline.duration&&i.timeline.setSpan(n),i.timeline.addKeyframe(e,t.map(r=>{const a=Ti.aimOf(i,e,r.shape.bounds),o=s.ofBounds(r.shape.bounds),{aim:c,...h}=r.shape;return{...r,shape:a?{...h,aim:a,angular:o}:{...h,angular:o}}}))}meters(e){const t=e<1?2:e<10?1:0;return e.toLocaleString(void 0,{maximumFractionDigits:t})}updateShapeTitleValidity(){const e=this.selectedSourceIds.size===1&&this.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 s=/^ufo-(\d+)$/.exec(e);return s?`${this.messages.shape} ${s[1]}`:e}addShape(){if(this.isRecording)return;const e=this.ufoElement.sighting.timeline;this.currentSourceId=this.newSourceIds(1)[0],this.selectedSourceIds=new Set([this.currentSourceId]),this.applyAppearanceAtPlayhead(this.offsetDefaultBounds(e.sourceIds.length)),this.shapeTitleInput.value=this.shapeLabel(this.currentSourceId),this.updateShapeTitle()}newSourceIds(e){const t=this.ufoElement.sighting.timeline,i=[];t.sourceIds.length===0&&this.currentSourceId!==void 0&&i.push(this.currentSourceId);const s=new Set([...t.sourceIds,this.currentSourceId]);let n=s.size+1;for(;i.length<e;){for(;s.has(`ufo-${n}`);)n++;i.push(`ufo-${n}`),s.add(`ufo-${n}`)}return i}shapeAddKinds(){const e=this.messages,t={triangle:e.modelTriangle,saucer:e.modelSaucer,cigar:e.modelCigar,chevron:e.modelChevron,light:e.modelLight};return[{value:"oval",label:e.oval},{value:"polygon",label:e.polygon},...Co.ALL.map(i=>({value:i.id,label:t[i.id]}))]}addModel(e){if(this.isRecording||this.ufoElement.playbackState==="playing")return;const t=this.ufoElement.sighting.timeline,i=e.boundsAt(this.offsetDefaultBounds(t.sourceIds.length)),s=e.shapesIn(i,this.currentAppearance),n=this.newSourceIds(s.length),r=this.shapeAddKinds().find(h=>h.value===e.id).label,a=/^ufo-(\d+)$/.exec(n[0])?.[1]??"",o={disc:this.messages.modelPartDisc,dome:this.messages.modelPartDome},c=s.map((h,d)=>{const u=e.partNames[d],p=u?`${r} ${a}, ${o[u]}`:`${r} ${a}`;return{sourceId:n[d],shape:{...h,title:this.said.write(void 0,p,this.writingLanguage)}}});this.commitShapes(this.ufoElement.currentTime,c),n.length>1&&t.group(n),this.currentSourceId=n[n.length-1],this.selectedSourceIds=new Set(n),this.refreshSourceList(),this.ufoElement.refresh()}duplicateSelected(){if(this.hideContextMenu(),this.isRecording||this.ufoElement.playbackState==="playing")return;const e=this.ufoElement.sighting.timeline,t=e.sourceIds.filter(r=>this.selectedSourceIds.has(r));if(t.length===0)return;const i=this.newSourceIds(t.length),s=24;for(const r of e.allKeyframes){const a=r.shapes.filter(o=>t.includes(o.sourceId)).map(o=>{const{bounds:c}=o.shape;return{sourceId:i[t.indexOf(o.sourceId)],shape:{...o.shape,bounds:{...c,x:c.x+s,y:c.y+s}}}});a.length>0&&this.commitShapes(r.t,a)}const n=e.groupMembers(t[0]);t.length>1&&n?.length===t.length&&t.every(r=>n.includes(r))&&e.group(i),this.currentSourceId=i[i.length-1],this.selectedSourceIds=new Set(i),this.refreshSourceList(),this.ufoElement.refresh()}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]??$u,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 s=document.createElement("option");s.value=i,s.textContent=this.shapeLabel(i),this.sourceSelect.appendChild(s)}this.sourceSelect.value=this.currentSourceId}decorLabel(e){const t=this.said.read(e.title);if(t)return t;const s=this.ufoElement.sighting.decor.filter(r=>r.kind===e.kind).indexOf(e)+1;return`${this.decorList.kindLabel(e.kind)} ${s}`}addDecor(e=this.decorList.pickedKind??"building"){this.observerAdded=e==="observer";const t=this.ufoElement.sighting,s={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==="trafficlight"?{lights:Zd.byId("traffic-signal")?.create()}:{},...e==="roadsign"?{sign:{face:"stop"}}:{},...e==="building"?{floors:Jd}:{},windows:ET(e)};t.decor=[...t.decor,s],this.currentDecorId=s.id,this.refreshDecorList(),this.ufoElement.refresh(),e!=="building"&&this.adoptDefaultModel(s.id,e)}readSceneryChoice(){try{return localStorage.getItem(xe.SCENERY_STORAGE)??void 0}catch{return}}readSceneryRadius(){try{const e=Number(localStorage.getItem(xe.SCENERY_RADIUS_STORAGE));if(Number.isFinite(e)&&e>=20&&e<=3e3)return String(e)}catch{}return"100"}writeSceneryRadius(e){try{localStorage.setItem(xe.SCENERY_RADIUS_STORAGE,e)}catch{}}writeSceneryChoice(e){try{localStorage.setItem(xe.SCENERY_STORAGE,e)}catch{}}async fillScenerySources(){const e=await Q(()=>import("./surroundingsSources-DXpzMDPy.js"),[],import.meta.url).catch(()=>{});if(!e)return;const{SURROUNDINGS_SOURCES:t,SurroundingsSources:i}=e;if(!this.isConnected)return;const s=document.createElement("option");s.value=xe.NO_SCENERY,s.id="option-scenery-none",s.textContent=this.messages.surveySourceNone;const n=t.map(a=>{const o=document.createElement("option");return o.value=a.id,o.textContent=a.name,o.title=a.credit,o}),r=new Option(this.messages.sourceFile,xe.FILE_SOURCE);r.id="option-scenery-file",this.scenerySource.replaceChildren(s,...n,r),this.surveyIds=t.map(a=>a.id),this.defaultSurveyId=i.DEFAULT_ID,this.syncSceneryPicker()}surveyIds;defaultSurveyId;sceneryAsked(){return this.sceneryChoice!==xe.NO_SCENERY&&!this.sectionFromFile("decor")}syncSceneryPicker(){const e=this.sectionFromFile("decor");this.surveyIds&&(this.scenerySource.value=e?xe.FILE_SOURCE:this.sceneryChoice===xe.NO_SCENERY?xe.NO_SCENERY:this.surveyIds.includes(this.sceneryChoice??"")?this.sceneryChoice:this.defaultSurveyId??this.surveyIds[0]),this.surroundings.setEnabled(this.sceneryAsked()),this.shadow.getElementById("scenery-radius-row").hidden=e||this.sceneryChoice===xe.NO_SCENERY;const t=this.shadow.getElementById("scenery-file-link");t.hidden=!e,e&&(t.textContent=this.sectionFilePanel.itemLabel("decor"),t.title=this.sectionFilePanel.where("decor"))}setDecorFromFile(e){const t=this.ufoElement.sighting;if(this.sectionFromFile("decor")===e)return;const i={...t.snapshots??{}};e?i.decor=i.decor??{}:delete i.decor,t.snapshots=os.isEmpty(i)?void 0:i,this.touch(),this.scheduleFileSync(),this.refreshFileItems()}plantingCentre(){const e=this.ufoElement.sighting,t=e.observerTrack.getInterpolatedPoseAt(0),i=e.event.place?.[0],s=t?.lat??i?.lat,n=t?.lng??i?.lng;return typeof s=="number"&&typeof n=="number"?{lat:s,lng:n}: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?k0.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 s=this.ufoElement.sighting.decor.find(n=>n.id===e);!s||s.model||s.sizeM||(this.ufoElement.sighting.decor=this.ufoElement.sighting.decor.map(n=>n.id===e?{...n,model:{id:i.id},sizeM:i.sizeM}:n),this.currentDecorId===e&&this.syncDecorVisibility(),this.refreshDecorList(),this.ufoElement.refresh(),this.scheduleModuleNaming())}defaultAircraft(){const e=2*eb,t=Math.round(e/RU*1e3);return{lights:Zd.byId("airliner")?.create(),track:[{t:0,eastM:-eb,northM:1e3,altitudeM:1500,headingDeg:90},{t,eastM:eb,northM:1e3,altitudeM:1500,headingDeg:90}]}}nextDecorLabel(e){const t=this.ufoElement.sighting.decor.filter(s=>s.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=ef(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(s=>{this.drawnEntryAsked!==i||!s||(this.drawnEntry=s,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 s=this.ufoElement.sighting.decor.find(r=>r.id===this.currentDecorId),n=i!==""?i:s?R0[s.kind]?.id:void 0;return n!==void 0?this.decorModelProvider.entry(n).then(r=>r&&{url:r.url,headingOffsetDeg:r.headingOffsetDeg}):s===void 0?void 0:{decorKind:s.kind}},{current:()=>{const i=this.ufoElement.sighting.decor.find(s=>s.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(s=>{const n=this.stringOrUndefined(i.title),r=this.stringOrUndefined(i.license);s.model={url:i.url,credit:n!==void 0&&r!==void 0?{title:n,license:r,author:this.stringOrUndefined(i.author),sourceUrl:this.stringOrUndefined(i.source)}:void 0}},"model")}))}async adoptCatalogueSize(e,t){const[i,s]=await Promise.all([e.model?.id?this.decorModelProvider.entry(e.model.id).catch(()=>{}):void 0,t?this.decorModelProvider.entry(t).catch(()=>{}):void 0]),n=this.ufoElement.sighting.decor.find(o=>o.id===e.id);if(!n||n.model?.id!==t||!s?.sizeM)return;const r=n.sizeM!==void 0&&i?.sizeM!==void 0&&n.sizeM.widthM===i.sizeM.widthM&&n.sizeM.lengthM===i.sizeM.lengthM&&n.sizeM.heightM===i.sizeM.heightM;if(n.sizeM&&!r)return;const a={...n.sizeM,...Object.fromEntries(Object.entries(s.sizeM).filter(([,o])=>o!==void 0).map(([o,c])=>[o,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(s=>s.t===e)||(t.milestones=$c([...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(s=>s.t===e);i&&(t.milestones=t.milestones.filter(s=>s.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=$c(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;gn.showPresence(this.shadow.getElementById("milestone-row"),this.shadow.getElementById("milestone-item"),t);for(const i of[this.milestoneSelect,this.goToMilestoneButton,this.deleteMilestoneButton])i.disabled=!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.filter(e=>e.kind!=="observer").map(e=>({id:e.id,label:this.decorLabel(e)})),this.currentDecorId),this.syncDecorFields(),this.syncCanvasMode(),this.refreshSceneryWarning(),this.refreshObserverList()}refreshObserverList(){const e=xe.OBSERVER_PRINCIPAL,t=this.ufoElement.sighting.decor.filter(s=>s.kind==="observer");this.currentDecorId!==void 0&&t.some(s=>s.id===this.currentDecorId)&&this.observerAdded&&(this.observerShown=this.currentDecorId),this.observerAdded=!1,t.some(s=>s.id===this.observerShown)||(this.observerShown=e),this.observerList.setItems([{id:e,label:this.principalObserverLabel()},...t.map(s=>({id:s.id,label:this.decorLabel(s)}))],this.observerShown);const i=this.observerShown!==e;this.observerList.setRemoveEnabled(i),this.observerList.setActionEnabled("look-at-observer",i),this.placeDecorItem()}principalObserverLabel(){const e=[this.observerTitleInput.value,this.observerFirstNamesInput.value,this.observerLastNameInput.value].map(t=>t.trim()).filter(Boolean).join(" ");return e===""?this.messages.principalObserver:`${e} (${this.messages.principalObserver.toLowerCase()})`}observerAdded=!1;selectObserver(e){this.observerShown=e,e!==xe.OBSERVER_PRINCIPAL&&this.selectDecor(e),this.refreshObserverList()}placeDecorItem(){const e=this.shadow.getElementById("decor-item"),t=this.shadow.getElementById("observer-decor-host"),i=this.shadow.getElementById("observer-principal");if(!e||!t||!i)return;const s=this.observerShown!==xe.OBSERVER_PRINCIPAL;if(i.hidden=s,s&&this.isGroupIdOpen("group-observer")){e.parentElement!==t&&t.append(e),e.hidden=!1;return}e.parentElement===t&&this.shadow.getElementById("decor-list-header").after(e),e.hidden=this.decorList.value===""}syncDecorFields(){this.syncDecorVisibility()}async findGhosts(){const e=this.currentReference();if(e?.src){this.searchingGhosts=!0,this.syncFindGhosts(e);try{const{GhostSearchView:t}=await Q(async()=>{const{GhostSearchView:r}=await import("./GhostSearchView-Dlhj3xWa.js");return{GhostSearchView:r}},__vite__mapDeps([27,18]),import.meta.url),i=this.messages,s={searching:i.referenceGhostsSearching,found:i.referenceGhostsFound,foundScaled:i.referenceGhostsFoundScaled,low:i.referenceGhostsLow,none:i.referenceGhostsNone,cropped:i.referenceGhostsCropped},n=await new t(this.ghostsStatus,s).search(e.src);this.ghostFinding=n&&n.pairs.length>0?{referenceId:e.id,src:e.src,search:n}:void 0,this.ghostsShown=!0,this.syncGhostsShown(),this.ufoElement.refresh()}finally{this.searchingGhosts=!1,this.syncFindGhosts(this.currentReference())}}}syncGhostsShown(){this.ghostsShownButton.hidden=!this.ghostFinding,this.ghostsShownButton.setAttribute("aria-pressed",String(this.ghostsShown)),this.ghostsShownButton.textContent=this.ghostsShown?this.messages.referenceGhostsHide:this.messages.referenceGhostsShow}syncFindGhosts(e){const t=!e?.src||this.sceneElement.referenceFailure(e.src)!==void 0;this.findGhostsButton.disabled=this.searchingGhosts||t||e?.kind==="video",this.addReferenceLandmarkButton.disabled=t,t&&(this.armingLandmark||this.pendingLandmark)&&this.disarmLandmark()}syncFilmStocks(e,t){const i=Wo.forInstrument(t);this.setRowVisible(this.filmStockSelect,i.length>0);const s=e.event.time?.year??void 0,n=`${t.id}|${s}|${e.film}|${this.messages.filmStockAny}`;if(this.filmStockKey===n)return;this.filmStockKey=n,this.filmStockSelect.innerHTML="";const r=(o,c,h=!1)=>{const d=document.createElement("option");d.value=o,d.textContent=c,d.disabled=h,this.filmStockSelect.appendChild(d)};r("",this.messages.filmStockAny);const a=i.map(o=>({stock:o,gap:Wo.gap(o,t,s)}));for(const{stock:o}of a.filter(c=>!c.gap))r(o.id,o.name);for(const{stock:o,gap:c}of a.filter(h=>h.gap)){const h=c.kind==="before"?this.messages.filmStockNotYet.replace("{from}",String(c.from)):this.messages.filmStockNoLonger.replace("{to}",String(c.to));r(o.id,`${o.name} (${h})`,o.id!==e.film)}this.filmStockSelect.value=e.film??""}filmStockKey;updateExposureSettings(){const e=this.ufoElement.sighting;e.iso=this.numberOrUndefined(this.isoInput.value),e.film=this.filmStockSelect.value||void 0,this.isoInput.placeholder=String(Wo.byId(e.film)?.iso??e.instrument.medium?.iso??"");const t=this.meteringSelect.value;e.metering=t==="average"||t==="highlights"?t:void 0,this.meteringSelect.disabled=e.iso!==void 0,this.ufoElement.refresh()}updateLens(){const e=this.lensGlassSelect.value,t={...e?{glass:e}:{},drops:this.numberOrUndefined(this.lensDropsInput.value),condensation:this.numberOrUndefined(this.lensCondensationInput.value),dirt:this.numberOrUndefined(this.lensDirtInput.value),...this.lensShelteredInput.checked?{sheltered:!0}:{}};for(const i of["drops","condensation","dirt"])t[i]===void 0&&delete t[i];this.ufoElement.sighting.lens=Object.keys(t).length>0?t:void 0,this.ufoElement.refresh()}label(e,t){const i=this.shadow.getElementById(e);i&&(i.textContent=t)}setRowVisible(e,t){const i=e.closest("label")??e;i.hidden=!t}decorBaseShownFor;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,this.decorBaseShownFor=void 0;return}const t=this.decorBaseShownFor!==e.id;if(this.decorBaseShownFor=e.id,this.decorBaseShown){this.decorBaseForm.sync(t),this.decorStateForm.sync(t);return}this.decorBaseShown=!0;const i=()=>new Ql(()=>{const s=this.ufoElement.sighting.decor.find(n=>n.id===this.currentDecorId);return s?va.viewOf(s,this.ufoElement.currentTime,this.sceneElement.sunAltitudeDeg):void 0},(s,n)=>this.commitDecorBase(s,n.key),()=>this.decorBaseContext(),this.decorPositionPlace());this.decorBaseForm.show(Ko.resolve(Dr.BASE,this.decorParameterTexts),i(),()=>{}),this.decorStateForm.show(Ko.resolve(Dr.STATE,this.decorParameterTexts),i(),()=>{})}decorPositionPlace(){const e=()=>{const t=this.ufoElement.sighting.decor.findIndex(i=>i.id===this.currentDecorId);return t<0?[]:[`decor.${t}.eastM`,`decor.${t}.northM`]};return{frame:()=>this.positionFrame(this.currentDecorId),messages:()=>this.messages,basis:{read:()=>this.ufoElement.sighting.provenance.at(e()[0]??"")?.basis,write:(t,i)=>this.writePositionBasis(e(),i)}}}framePlace(){return{frame:()=>this.positionFrame(),messages:()=>this.messages}}positionFrame(e){const t=this.ufoElement.currentTime,i=[{label:this.messages.positionObserver,eastM:0,northM:0}];for(const s of this.ufoElement.sighting.decor){if(s.id===e)continue;const{eastM:n,northM:r}=Pr(s,t);i.push({id:s.id,label:this.decorLabel(s),eastM:n,northM:r})}return{origin:this.plantingCentre(),references:i}}syncObserverPosition(){const e=this.ufoElement.sighting,t=this.ufoElement.currentTime;this.observerSaid=e.observerTrack.getLatestPoseAt(t)?.saidPosition;const i=this.positionFrame();this.observerPosition.frame={...i,references:i.references.filter(n=>n.id!==void 0)};const s=JSON.stringify(this.observerSaid??null);s!==this.observerSaidShown&&(this.observerSaidShown=s,this.observerPosition.said=this.observerSaid),this.observerPosition.basis=e.provenance.at(this.observerPositionPaths()[0]??"")?.basis}observerPositionPaths(){const e=this.ufoElement.currentTime,t=this.ufoElement.sighting.observerTrack.toJSON().keyframes.findIndex(i=>i.t===e);return t<0?[]:[`observerTrack.keyframes.${t}.pose.lat`,`observerTrack.keyframes.${t}.pose.lng`]}writeObserverBasis(e){this.observerPositionPaths().length===0&&this.updateObserver(),this.writePositionBasis(this.observerPositionPaths(),e)}writePositionBasis(e,t){const i=this.ufoElement.sighting.provenance;for(const s of e)t===void 0||t==="stated"?i.clear(s):i.set(s,{basis:t});this.dispatchEvent(new CustomEvent("sightingchange"))}decorBaseContext(){const e=this.ufoElement.sighting.decor.find(i=>i.id===this.currentDecorId);if(!e)return;const t=Gc.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:Gc.rigsFor(e.kind,this.publishedParametersOf(e)).map(i=>({value:i.id,label:this.naming.lightRig(i)})),seats:Dr.seatsFor(e.kind),models:(this.decorModelEntries?.kind===e.kind?this.decorModelEntries.entries:[]).map(i=>({value:i.id,label:i.name})),defaultModelId:R0[e.kind]?.id}}placedByAuthor(e){if(!e.lamp?.supposed)return e;const t=this.sceneElement.decorDrawnOffset(e.id),{supposed:i,...s}=e.lamp,n={...e,eastM:e.eastM+(t?.eastM??0),northM:e.northM+(t?.northM??0),...Object.keys(s).length>0?{lamp:s}:{}};Object.keys(s).length===0&&delete n.lamp;const r=this.ufoElement.sighting;return r.decor=r.decor.map(a=>a.id===e.id?n:a),n}commitDecorBase(e,t){const i=this.ufoElement.sighting.decor.find(c=>c.id===this.currentDecorId);if(!i)return;const s=t==="eastM"||t==="northM"?this.placedByAuthor(i):i;if((t==="lit"||t==="headlights")&&this.ufoElement.playbackState==="playing")return;const n=this.ufoElement.currentTime,r=va.viewOf(s,n,this.sceneElement.sunAltitudeDeg);e(r);const a=this.ufoElement.sighting;a.decor=a.decor.map(c=>c.id===s.id?va.apply(c,r,t,n):c),t==="model.id"&&this.adoptCatalogueSize(s,r.model?.id);const o=a.decor.find(c=>c.id===s.id);t==="title"&&this.decorList.rename(o.id,this.decorLabel(o)),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?yi.of(e,this.publishedParametersOf(e)):void 0,i=t&&Ko.resolve(t,this.decorParameterTexts);if(!e||!i){this.decorParametersShownFor=void 0,this.decorParameterForm.clear(),this.decorParametersHost.hidden=!0;return}this.decorParametersHost.hidden=!1;const s=`${e.id}|${i.kind}|${i.parameters.map(a=>a.key).join(",")}`;if(s===this.decorParametersShownFor){this.decorParameterForm.sync();return}this.decorParametersShownFor=s;const n=e.id,r=new Ql(()=>this.ufoElement.sighting.decor.find(a=>a.id===n),a=>{const o=this.ufoElement.sighting;o.decor=o.decor.map(c=>{if(c.id!==n)return c;const h=structuredClone(c);return a(h),h})});this.decorParameterForm.show(i,r,()=>{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++,this.meteorMagnitudeLimit());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,this.meteorMagnitudeLimit()),t=e?`${e.t}`:"";t!==this.meteorRankFor&&(this.meteorRankFor=t,this.meteorRank=0)}meteorRankFor;meteorMagnitudeLimit(){const e=this.ufoElement.sighting,t=this.observerAtStart(),i=e.event.time?.year!==void 0?mn(e.event.time,t.lng,e.event.utcOffsetHours):void 0;if(!i)return Number.POSITIVE_INFINITY;const s=Hi("Sun",i,t).altitudeDeg;return $a(s,this.instrumentGain(),this.skyLossAt(i,t))}skyCandidatesKey;static reentryArchive=new dr;reentries;meteorRank=0;showerLanguage(){return this.language}naming=new mg;static LANGUAGE_NAMES=new Intl.DisplayNames(["en"],{type:"language"});said=new bn(["en"]);tagNames=new Ab({});get writingLanguage(){return this.showerLanguage()}refreshSkyCandidates(){if(!this.worded)return;this.resetMeteorRankIfSkyChanged();const e=this.ufoElement.sighting,t=e.event.place?.[0],i=e.event.time,s=t&&t.lat!==void 0&&t.lng!==void 0&&i?.year!==void 0?mn(i,t.lng,e.event.utcOffsetHours):void 0,n=JSON.stringify([s?.getTime(),t?.lat,t?.lng,this.groundElevationM,e.instrumentId,e.exposureSeconds,e.lightPollution,ys(e,0),this.messages.skyLine,this.meteorRankFor,this.sceneElement.satelliteState.status,this.satelliteSpanMs(),this.sceneElement.fireballState.status,this.sceneElement.groundKey]);if(n===this.skyCandidatesKey)return;if(this.skyCandidatesKey=n,!s||!t||t.lat===void 0||t.lng===void 0){this.showMeteorButton.disabled=!0,this.showCometButton.disabled=!0,this.showNovaButton.disabled=!0,this.showSatelliteButton.disabled=!0,this.showFireballButton.disabled=!0,this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",this.messages.skyUnknown),this.labelSkyButtons();return}const r={lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0},a=[this.starsClause(s,r),this.showerClause(s,r),this.cometClause(s,r),this.novaClause(s,r),this.eclipseClause(s,r),this.moonClause(s,r),this.satelliteClause(s,r),this.reentryClause(s,r),this.fireballClause(s,r),this.opticsClause(s,r),this.rainbowClause(s,r),this.glowClause(s,r)].filter(o=>o!==void 0);this.skyCandidatesOutput.textContent=this.messages.skyLine.replace("{parts}",a.join(" · ")),this.labelSkyButtons()}labelSkyButtons(){const e=this.messages,t=[[this.showMeteorButton,e.showMeteor,e.noMeteor],[this.showCometButton,e.showComet,e.noComet],[this.showNovaButton,e.showNova,e.noNova],[this.showSatelliteButton,e.showSatellite,e.noSatellite],[this.showFireballButton,e.showFireball,e.noFireball]];for(const[i,s,n]of t){const r=i.disabled?n:s;i.title=r,i.setAttribute("aria-label",r)}}instrumentGain(){const e=this.ufoElement.sighting;return en.gainFor(e.instrument,{fNumber:tt(e,0)?.fNumber,fieldOfViewDeg:Ti.fovOf(e,0),exposureSeconds:e.exposure})}starsClause(e,t){const i=Hi("Sun",e,t).altitudeDeg,s=this.instrumentGain(),n=this.skyLossAt(e,t),r=$a(i,s,n),a=h=>h.toLocaleString(void 0,{maximumFractionDigits:1});if(r<AU)return this.messages.skyStarsNone;const o=this.ufoElement.sighting.instrument,c=Math.abs(s)<.1?this.messages.skyStarsEye.replace("{limit}",a(r)):(s>0?this.messages.skyStarsDeeper:this.messages.skyStarsShallower).replace("{limit}",a(r)).replace("{device}",this.naming.instrument(o)).replace("{gain}",a(Math.abs(s))).replace("{eye}",a($a(i,0,n)));return r<=bp?c:c+this.messages.skyStarsCatalogue.replace("{catalogue}",a(bp))}showerClause(e,t){const i=ns.observedRatePerHour(ns.apexPosition(e,t).altitudeDeg).toLocaleString(void 0,{maximumFractionDigits:1}),s=zd.activeAt(e);if(s.length===0)return this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyNothingActive.replace("{sporadic}",i);const n=s.map(r=>{const a=zd.radiantPosition(r.shower,e,t);return{entry:r,position:a,rate:zd.observedRatePerHour(r.zhr,a.altitudeDeg,r.shower.populationIndex)}}).sort((r,a)=>a.rate-r.rate)[0];return n.rate<=0?(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerBelowHorizon.replace("{name}",this.naming.shower(n.entry.shower))):(this.showMeteorButton.disabled=!this.sceneElement.meteorByRank(0,this.meteorMagnitudeLimit()),this.messages.skyShowerActive.replace("{name}",this.naming.shower(n.entry.shower)).replace("{altitude}",String(Math.round(n.position.altitudeDeg))).replace("{bearing}",this.naming.towards(n.position.azimuthDeg)).replace("{rate}",n.rate.toLocaleString(void 0,{maximumFractionDigits:n.rate<10?1:0})).replace("{sporadic}",i))}cometClause(e,t){const i=b0.brightestAt(e,t);if(!i||i.magnitude>au){this.showCometButton.disabled=!0;return}return this.showCometButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.cometText(i)}novaClause(e,t){const i=gg.brightestAt(e,t);if(!i||i.magnitude>au){this.showNovaButton.disabled=!0;return}return this.showNovaButton.disabled=this.sceneElement.groundHides(i.position.altitudeDeg,i.position.azimuthDeg),this.novaText(i)}eclipseClause(e,t){const i=bs.around(e,t);if(!i||i.peakAltitudeDeg<=0)return;const s=Hi("Sun",i.peak,t),n=r=>r.replace("{altitude}",String(Math.round(s.altitudeDeg))).replace("{bearing}",this.naming.towards(s.azimuthDeg));if(i.totality){const r=Math.floor(i.totality.seconds/60),a=Math.round(i.totality.seconds%60);return n(this.messages.skyEclipseTotal).replace("{time}",this.observerClock(i.totality.begin)).replace("{duration}",`${r} min ${a} s`)}return n(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=Hi("Moon",e,t);if(i.altitudeDeg<=0||Ec(e).illuminatedFraction<.97)return;const s=[],n=Ln.distanceKm(e,t),r=Ln.relativeToMean(Ln.radiusAtKm(n)),a=n<=Ln.SUPERMOON_DISTANCE_KM?this.messages.skySupermoon:n>=Ln.MICROMOON_DISTANCE_KM?this.messages.skyMicromoon:void 0;return a&&s.push(a.replace("{distance}",(Math.round(n/100)*100).toLocaleString(this.showerLanguage())).replace("{diameter}",this.decimal(Ln.radiusAtKm(n)*2,3)).replace("{percent}",String(Math.round(Math.abs(r)*100)))),wg.isIn(e)&&s.push(this.messages.skyRedMoon.replace("{altitude}",String(Math.round(i.altitudeDeg))).replace("{bearing}",this.naming.towards(i.azimuthDeg))),s.length>0?s.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=ua.visibilityAt(e,t),s=this.realSatelliteClause(i.lowOrbitLit||i.sunAltitudeDeg>=0);if(s!==void 0)return s;if(this.showSatelliteButton.disabled=!0,!i.anythingInOrbit)return i.sunAltitudeDeg<0?this.messages.skySatellitesNotYet:void 0;const n=$a(i.sunAltitudeDeg,this.instrumentGain(),this.skyLossAt(e,t)),r=i.classes.filter(d=>d.peakMagnitude<=n),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 o=Math.round(i.shadowHeightKm).toLocaleString(),c=(i.trackedObjects??0).toLocaleString(),h=d=>d.replace("{height}",o).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(),s=i+this.satelliteSpanMs(),n=[i,s,t.lat.toFixed(3),t.lng.toFixed(3)].join();if(this.reentries?.key!==n){const c={key:n,status:"loading"};this.reentries=c,xe.reentryArchive.candidates(i,s,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=ua.visibilityAt(e,t).sunAltitudeDeg<-6,a=(this.reentries.candidates??[]).filter(c=>c.record.precision==="minute"||r);if(a.length===0)return;const o=a.slice(0,3).map(c=>this.reentryText(c));return a.length>3&&o.push(this.messages.skyReentriesMore.replace("{count}",String(a.length-3))),this.messages.skyReentries.replace("{list}",o.join("; "))}reentryText(e){const{record:t}=e,i=t.cosparId?`${t.name} (${t.cosparId})`:t.name,s=new Date(e.timeMs);if(t.precision==="day"){const a=s.toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skyReentryDay.replace("{name}",i).replace("{date}",a)}const n=this.observerClock(s).replace(/:\d\d$/,"");if(t.precision==="hours")return this.messages.skyReentryPredicted.replace("{name}",i).replace("{time}",n).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}",n).replace("{place}",t.seenFrom).replace("{distance}",String(Math.round(e.seenKm/10)*10))+r:this.messages.skyReentryObserved.replace("{name}",i).replace("{time}",n)+r}realSatelliteClause(e){const t=this.sceneElement.satelliteState;if(t.status!=="ready")return;if(t.coverage?.every(c=>c.status!=="covered"))return this.showSatelliteButton.disabled=!0,t.coverage.some(c=>c.status==="gap")?this.messages.skySatelliteElementsGap:void 0;const i=this.visibleSatellitePasses();if(this.showSatelliteButton.disabled=this.aimableSatellitePasses(i).length===0,i.length===0)return e?this.messages.skySatellitePassesNone:void 0;const n=i[0].peak,a=(i.length===1?this.messages.skySatellitePassesOne:this.messages.skySatellitePasses).replace("{count}",String(i.length)).replace("{name}",n.object.name).replace("{magnitude}",n.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{altitude}",String(Math.round(n.altitudeDeg))).replace("{bearing}",this.naming.towards(n.azimuthDeg)).replace("{time}",this.observerClock(n.date)),o=this.starlinkTrain(i);return o?`${a}, ${o}`:a}visibleSatellitePasses(){const e=this.instrumentGain(),t=this.observerAtStart();return this.sceneElement.satellitePassesDuring(this.satelliteSpanMs()).filter(i=>{const s=i.peak.magnitude;if(s===void 0)return!1;const n=Hi("Sun",i.peak.date,t);return s<=$a(n.altitudeDeg,e,this.skyLossAt(i.peak.date,t))}).sort((i,s)=>i.peak.magnitude-s.peak.magnitude)}aimableSatellitePasses(e){return e.filter(t=>this.passTimelineMs(t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(t.peak.altitudeDeg,t.peak.azimuthDeg))}starlinkTrain(e){const t=new Map;for(const r of e){const{kind:a,launch:o}=r.peak.object;a!=="starlink"||!o||(r.peak.date.getTime()-Date.parse(`${o}T00:00:00Z`))/864e5>60||t.set(o,(t.get(o)??0)+1)}const[i,s]=[...t.entries()].sort((r,a)=>a[1]-r[1])[0]??[];if(!i||!s||s<3)return;const n=new Date(`${i}T00:00:00Z`).toLocaleDateString(this.showerLanguage(),{day:"numeric",month:"long",year:"numeric",timeZone:"UTC"});return this.messages.skySatelliteTrain.replace("{count}",String(s)).replace("{date}",n)}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=tt(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=mn(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.aimableSatellitePasses(this.visibleSatellitePasses());if(e.length===0)return;const t=e.map(s=>`${s.object.norad}@${s.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=>qr.seenFrom(i,{lat:t.lat,lng:t.lng,heightM:t.elevationM})).filter(i=>i!==void 0&&i.magnitude<=qr.STRIKING_MAGNITUDE).filter(i=>i.record.t>=e.getTime()).sort((i,s)=>i.magnitude-s.magnitude)}aimableFireballs(e,t){return e.filter(i=>this.fireballTimelineMs(i,t)<=this.ufoElement.seekableDuration&&!this.sceneElement.groundHides(i.peak.altitudeDeg,i.peak.azimuthDeg))}fireballTimelineMs(e,t){const{record:i}=e,s=i.from[2]-i.to[2],n=Math.abs(s)<1e-6?.5:Math.min(1,Math.max(0,(i.from[2]-i.peakHeightKm)/s));return i.t-t.getTime()+n*i.durationS*1e3}fireballClause(e,t){const i=this.sceneElement.fireballState.status==="ready"?this.strikingFireballs(e,t):[];if(this.showFireballButton.disabled=this.aimableFireballs(i,e).length===0,i.length===0)return;const s=i[0];return(i.length===1?this.messages.skyFireballsOne:this.messages.skyFireballs).replace("{count}",String(i.length)).replace("{magnitude}",s.magnitude.toLocaleString(this.showerLanguage(),{maximumFractionDigits:1})).replace("{time}",this.observerClock(new Date(s.record.t))).replace("{altitude}",String(Math.round(s.peak.altitudeDeg))).replace("{bearing}",this.naming.towards(s.peak.azimuthDeg)).replace("{distance}",String(Math.round(s.peak.distanceKm/10)*10)).replace("{stations}",String(s.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 s=mn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=this.aimableFireballs(this.strikingFireballs(s,this.observerAtStart()),s);if(n.length===0)return;const r=n[this.fireballRank++%n.length];this.ufoElement.playbackState==="playing"&&this.ufoElement.togglePlayPause(),this.ufoElement.currentTime=this.fireballTimelineMs(r,s),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=ys(this.ufoElement.sighting,0),s=Hi("Sun",e,t),n=Hi("Moon",e,t),r=Mt.deckLitUntilDeg(Mt.DECK_HEIGHT_M),a=s.altitudeDeg>-r,o=a?s:n;if(o.altitudeDeg<=-r)return;const c=i.highCloudCover;if(c===void 0||c<=0)return this.messages.skyOpticsNoIce;if(Mt.strength(c,i.lowerCloudCover??i.cloudCover,o.altitudeDeg,r)<=0)return this.messages.skyOpticsHidden;const h=a?this.messages.skyOpticsSun:this.messages.skyOpticsMoon,d=this.listed(Mt.formsAt(o.altitudeDeg,r).map(p=>this.opticsFormName(p))),u=i.iceCrystalAlignment??y0;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=ys(this.ufoElement.sighting,0);if(i.precipitationType!=="rain"||i.precipitationIntensity<=0)return;const s=Hi("Sun",e,t),n=Hi("Moon",e,t),r=s.altitudeDeg>0,a=r?s:n;if(a.altitudeDeg<=0)return this.messages.skyBowNoSource;const o=i.lowerCloudCover??i.cloudCover;if(Dn.strength(i.precipitationIntensity,o,a.altitudeDeg)<=0)return this.messages.skyBowHidden;const c=Dn.formsAt(a.altitudeDeg);if(c.length===0)return this.messages.skyBowSourceTooHigh.replace("{altitude}",String(Math.round(a.altitudeDeg))).replace("{radius}",String(Math.round(Dn.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(Ec(e).illuminatedFraction*100);return this.messages.skyBowMoon.replace("{forms}",h).replace("{lit}",String(d))}glowClause(e,t){const i=Hi("Sun",e,t);if(i.altitudeDeg>FU)return;const s=this.glows.assess(e,t,this.ufoElement.sighting.lightPollution),n=[];if(s.milkyWay&&n.push(this.messages.skyGlowBand.replace("{contrast}",this.decimal(s.milkyWay.contrast,1)).replace("{altitude}",String(Math.round(s.milkyWay.altitudeDeg))).replace("{bearing}",this.naming.towards(s.milkyWay.azimuthDeg))),s.zodiacal){const p=s.zodiacal.sunSeparationDeg<=Zt.CONE_SEPARATION_DEG;n.push((p?this.messages.skyGlowCone:this.messages.skyGlowZodiacalBand).replace("{contrast}",this.decimal(s.zodiacal.contrast,1)).replace("{altitude}",String(Math.round(s.zodiacal.altitudeDeg))).replace("{bearing}",this.naming.towards(s.zodiacal.azimuthDeg)).replace("{elongation}",String(Math.round(s.zodiacal.sunSeparationDeg))))}if(n.length>0)return this.listed(n);const r=this.decimal(s.darkestSkyMagPerArcsec2,1),a=Hi("Moon",e,t),o=s.darkestSkyMagPerArcsec2<UU,c=this.ufoElement.sighting.lightPollution,h=pe.scatteringAt(90-a.altitudeDeg)*pe.moonOutput(pe.phaseAngleOf(Ec(e).illuminatedFraction),a.altitudeDeg)*pe.scatteredFraction(90),d=pe.artificialZenithNanolamberts(c)>h;if(o&&a.altitudeDeg>0&&!d){const p=Math.round(Ec(e).illuminatedFraction*100);return this.messages.skyGlowMoon.replace("{lit}",String(p)).replace("{sky}",r)}const u=pe.artificialZenithNanolamberts(c)>pe.twilightExcessNanolamberts(i.altitudeDeg);return o&&d&&u?this.messages.skyGlowTowns.replace("{sky}",r):o?this.messages.skyGlowTwilight.replace("{sky}",r):this.messages.skyGlowNothingUp.replace("{sky}",r)}skyLossAt(e,t){const i=Hi("Sun",e,t),s=Hi("Moon",e,t);return pe.starLossMagnitudes(i.altitudeDeg,{phaseAngleDeg:pe.phaseAngleOf(Ec(e).illuminatedFraction),altitudeDeg:s.altitudeDeg},this.ufoElement.sighting.lightPollution)}glows=new Zt;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<b0.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 s=mn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=b0.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.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 s=mn(i,t.lng,e.event.utcOffsetHours);if(!s)return;const n=gg.brightestAt(s,{lat:t.lat,lng:t.lng,elevationM:this.groundElevationM??0});!n||this.sceneElement.groundHides(n.position.altitudeDeg,n.position.azimuthDeg)||(this.headingInput.value=String(this.rounded(n.position.azimuthDeg)),this.pitchInput.value=String(this.rounded(n.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(o=>o.id===this.currentDecorId);if(!e)return;const{eastM:t,northM:i,altitudeM:s}=Pr(e,this.ufoElement.currentTime),n=Math.hypot(t,i);if(n===0&&s===0)return;const r=Math.atan2(t,i)*180/Math.PI,a=Math.atan2(s-kU,n)*180/Math.PI;this.headingInput.value=String(Math.round(r*10)/10),this.pitchInput.value=String(Math.round(a*10)/10),this.updateObserver()}static DEFAULT_SAMPLE_MS=100;get samplingRate(){return this.ufoElement.sighting.sampleMs??xe.DEFAULT_SAMPLE_MS}buildPrototype(e=this.defaultBounds()){return xM(e,this.currentAppearance)}defaultBounds(){const e=this.ufoElement.canvasElement;return{x:e.width/2-jh.width/2,y:e.height/2-jh.height/2,width:jh.width,height:jh.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 oM(this.ufoElement.sighting.timeline,new NF(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){const t=e?this.messages.stop:this.messages.record;this.recordButton.title=t,this.recordButton.setAttribute("aria-label",t),this.recordButton.querySelector(".record-label")||this.recordButton.replaceChildren(Object.assign(document.createElement("span"),{className:"record-icon"}),Object.assign(document.createElement("span"),{className:"record-label"})),we.show(this.recordButton.querySelector(".record-icon"),e?"⏹":"⏺"),this.recordButton.querySelector(".record-label").textContent=t}async loadLocaleMessages(){const e=++this.localeToken,t=yr.preferencesFor(this);this.preferences=t;const i=jd(t,qd),s=this.decidedLanguage===void 0;if(this.decidedLanguage=i,s){for(const d of this.skyParts.values())this.nameSkyPart(d.label,d.titles);this.applyPerceptionLabels()}const n=this.narrativeProvider.localize?.(i),[r,a,o,c]=await Promise.all([nw.load(i),i==="en"?{}:p5(i),VA(i),tk.load(i)]);if(await n,e!==this.localeToken)return;const h=i!==this.language;this.language=i,this.decorParameterTexts=c,this.naming=new mg(o),this.said=new bn(t),this.tagNames=new Ab(a),r!==this.messages?this.applyMessages(r):(this.paramSummaryBuilder=new _l(r,this.naming,this.said,this.tagNames,{messages:r,locale:this.language},this.decorParameterTexts),this.refreshParamSummary()),h?this.showSaidTexts():this.showTags()}preferences=[];decidedLanguage;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.worded=!0,this.currentSourceId===$u&&this.shapeTitleInput.value===`${this.messages.shape} 1`?(this.messages=e,this.shapeTitleInput.value=`${this.messages.shape} 1`,this.updateShapeTitle()):this.messages=e,this.sayLoadError(),this.shapeAddMenu.setKinds(this.shapeAddKinds()),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.sourceSelect.setAttribute("aria-label",e.shape),this.shadow.getElementById("shape-empty").textContent=e.emptyShapes,this.labelShapeTitle.textContent=e.shapeTitle,this.labelUtcOffset.textContent=e.utcOffset,this.utcOffsetInput.placeholder=e.utcOffsetPlaceholder;const t=(n,r,a)=>{this.shadow.getElementById(n).setAttribute(r,a),r==="title"&&this.fieldHints.set(n,a)};t("observerAge","placeholder",e.observerAgeUnit),t("observerOccupation","placeholder",e.observerOccupationExample),t("roll","title",e.rollHint),t("utcOffsetHours","title",e.utcOffsetHint),t("highCloudCover","title",e.highCloudCoverHint),t("cloudBase","title",e.cloudBaseHint),t("windDirection","title",e.windDirectionHint),t("soundPitch","title",e.soundPitchHint),t("brightness","title",e.brightnessHint),t("blur","title",e.blurHint),t("apparentWidth","title",e.apparentWidthHint),t("realWidth","title",e.realWidthHint),t("objectDistance","title",e.objectDistanceHint),t("sizeLock","title",e.sizeLockHint),this.labelApparentWidth.textContent=e.apparentWidth,this.labelRealWidth.textContent=e.realWidth,this.labelObjectDistance.textContent=e.distance,this.shadow.getElementById("label-shape-rotation").textContent=e.shapeRotation,this.shapeRotationInput.title=e.shapeRotationTitle,this.labelSizeLock.textContent=e.sizeLock;for(const[n,r]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=r;this.clearDistanceHypothesisButton.textContent=e.clearDistanceHypothesis,this.clearDistanceHypothesisButton.title=e.clearDistanceHypothesisTitle,this.refreshApparentSize(),this.labelSamplingRate.textContent=e.samplingRate,this.samplingRateInput.placeholder=String(xe.DEFAULT_SAMPLE_MS),this.samplingRateInput.title=e.samplingRateHint.replace("{n}",String(xe.DEFAULT_SAMPLE_MS)),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.shadow.getElementById("label-account-compare").textContent=e.accountCompare,this.shadow.getElementById("account-compare-row").title=e.accountCompareHint;const i=this.shadow.getElementById("scene-resize");i&&(i.title=e.resizeScene,i.setAttribute("aria-label",e.resizeScene)),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.contextDuplicateButton.textContent=e.duplicate,this.contextBringToFrontButton.textContent=e.bringToFront,this.contextSendToBackButton.textContent=e.sendToBack,this.contextDeleteButton.textContent=e.contextMenuDelete,this.exportButton.textContent=e.export,this.snapshotsPanel.localize(e),this.sectionFilePanel.localize(e),this.eventsPanel.localize(e.events),this.phenomenonEventsPanel.localize(e.events),this.bodiesEventsPanel.localize(e.events),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.shadow.getElementById("label-whole-keyframes").textContent=e.wholeKeyframes,this.wholeKeyframesInput.closest("label").title=e.wholeKeyframesHint,this.importInput.placeholder=e.importUrlPlaceholder;for(const n of this.shadow.querySelectorAll(gf))n.messages=e;this.labelObserverAge.textContent=e.observerAge,this.labelObserverBirth.textContent=e.observerBirth,this.applyPerceptionLabels(),this.labelObserverOccupation.textContent=e.observerOccupation,this.labelAccountSource.textContent=e.accountSource,Jn.say(this.labelAccountUrl,e.accountUrl,e.accountUrlHint),this.labelAccountFollowedUp.textContent=e.accountFollowedUp,this.evaluationFields.messages=e.accountEvaluation;for(const[n,r]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 a=this.shadow.getElementById(n);a&&(a.textContent=r)}this.labelNarrativeSource.textContent=e.narrativeSource,this.renderNarrativeSettings(),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.labelPosition.textContent=e.positionLabel,this.observerPosition.messages=e,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.label("label-iso",e.iso),this.label("label-film-stock",e.filmStock),this.filmStockKey=void 0,this.isoInput.title=e.isoTitle,this.label("label-metering",e.metering),this.meteringSelect.title=e.meteringTitle,this.label("metering-device",e.meteringDevice),this.label("metering-average",e.meteringAverage),this.label("metering-highlights",e.meteringHighlights),this.label("label-lens-glass",e.lensGlass),this.label("label-reference-ghosts",e.referenceGhosts),this.findGhostsButton.textContent=e.referenceFindGhosts,this.syncGhostsShown(),this.label("lens-glass-none",e.lensGlassNone),this.label("lens-glass-filter",e.lensGlassFilter),this.label("lens-glass-window",e.lensGlassWindow),this.label("lens-glass-windscreen",e.lensGlassWindscreen),this.label("label-lens-drops",e.lensDrops),this.lensDropsInput.title=e.lensDropsTitle,this.label("label-lens-condensation",e.lensCondensation),this.lensCondensationInput.title=e.lensCondensationTitle,this.label("label-lens-dirt",e.lensDirt),this.lensDirtInput.title=e.lensDirtTitle,this.label("label-lens-sheltered",e.lensSheltered),this.lensShelteredInput.title=e.lensShelteredTitle,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.shapeAddMenu.panel.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:"trafficlight",label:e.decorTrafficLight},{value:"crossing",label:e.decorCrossing},{value:"roadsign",label:e.decorRoadSign},{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,empty:e.emptyDecor,actions:{"look-at-decor":e.lookAtDecor}}),this.labelSkyButtons(),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.observerList.setLabels({list:e.observerGroup,remove:e.deleteObserver,add:e.addObserver,actions:{"look-at-observer":e.lookAtDecor}}),this.refreshObserverList(),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 s=this.shadow.getElementById("option-scenery-none");s&&(s.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,this.shadow.getElementById("milestone-empty").textContent=e.emptyMilestones;for(const[n,r]of[[this.addMilestoneButton,e.addMilestone],[this.goToMilestoneButton,e.goToMilestone],[this.deleteMilestoneButton,e.deleteMilestone]])n.title=r,n.setAttribute("aria-label",r);this.decorParameterForm.setLanguage(this.language),this.decorBaseForm.setLanguage(this.language),this.decorStateForm.setLanguage(this.language),this.decorBaseShownFor=void 0,this.decorBaseShown=!1,this.decorParametersShownFor=void 0,this.isConnected&&this.syncDecorVisibility(),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;for(const n of this.skyParts.values())this.nameSkyPart(n.label,n.titles);for(const n of["location","decor","weather"]){const r=this.shadow.getElementById(`${n}-settings-button`);r?.setAttribute("title",e.dataSources),r?.setAttribute("aria-label",e.dataSources);const a=this.shadow.getElementById(`label-${n}-settings`);a&&(a.textContent=e.dataSources)}this.bodyEditor?.setLanguage(this.language);for(const n of this.skyParts.values())n.editor?.setLanguage(this.language);this.modulesPanel?.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.observerTab,this.labelWeatherGroup.textContent=e.sky,this.fitGroupTabs(),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.decorParameterTexts),this.refreshParamSummary(),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.shadow.getElementById("label-aircraft-group").textContent=e.aircraftGroup,this.aircraftFlights.show(this.sceneElement.aircraftFlights,e,!0),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.referenceSelect.setAttribute("aria-label",e.reference),this.shadow.getElementById("reference-empty").textContent=e.emptyReferences,this.shadow.getElementById("reference-landmark-empty").textContent=e.emptyReferenceLandmarks,this.shadow.getElementById("trace-empty").textContent=e.emptyTraces,this.labelReferenceTitle.textContent=e.referenceTitle,this.labelReferenceSrc.textContent=e.referenceSrc,this.referenceSourceInput.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.referenceKindSelect.querySelector("#reference-kind-video").textContent=e.referenceVideo,this.shadow.getElementById("label-reference-video-from").textContent=e.referenceVideoFrom,this.shadow.getElementById("label-reference-video-to").textContent=e.referenceVideoTo,this.shadow.getElementById("label-reference-video-rate").textContent=e.referenceVideoRate,this.referenceRemoveKeyButton.textContent=e.referenceRemoveKey,this.labelReferenceCredit.textContent=e.referenceCredit,this.labelReferenceCreditUrl.textContent=e.referenceCreditUrl,this.labelReferenceT.textContent=this.currentReference()?.kind==="video"?e.referenceVideoT: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.setReferenceAddKinds(e.addReferenceUrl,e.addReferenceFile,e.referenceStreetSearch),this.addReferenceButton.title=e.addReference,this.addReferenceButton.setAttribute("aria-label",e.addReference),this.referenceAddMenu.panel.setAttribute("aria-label",e.addReference),this.deleteReferenceButton.title=e.deleteReference,this.deleteReferenceButton.setAttribute("aria-label",e.deleteReference),this.labelReferenceLandmarks.textContent=e.referenceLandmarks,this.addReferenceLandmarkButton.title=e.addReferenceLandmark,this.addReferenceLandmarkButton.setAttribute("aria-label",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,Jn.say(this.labelTraceImport,e.traceImport,e.traceImportHint),this.traceSelect.setAttribute("aria-label",e.trace),this.addTraceButton.title=`${e.traceImport} (${e.traceImportHint})`,this.addTraceButton.setAttribute("aria-label",e.traceImport),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,r]of this.soundKindOptions)r.textContent=this.soundKindLabel(n,e);this.labelInstrument.textContent=e.instrument,this.labelFilter.textContent=e.filter,this.refreshFilterOptions(),this.setRecordButtonLabel(this.isRecording),this.syncPlaybackControls(),this.labelPanels(e),this.refreshFileItems(),this.refreshSkyCandidates()}labelPanels(e){const t={identity:e.sectionIdentity,profile:e.sectionProfile,testimony:e.sectionTestimony,vision:e.sectionVision,perception:e.sectionPerception,coordinates:e.sectionCoordinates,gaze:e.sectionGaze,"night-sky":e.sectionNightSky,period:e.sectionPeriod,survey:e.sectionSurvey,heard:e.sectionHeard,"sound-recording":e.sectionSoundRecording,picture:e.sectionPicture,pose:e.sectionPose,appearance:e.sectionAppearance,size:e.sectionSize,path:e.sectionPath};for(const[s,n]of Object.entries(t))this.shadow.getElementById(`label-section-${s}`).textContent=n;this.sectionFolds.setMessages(e),this.candidatesView?.languageChanged(),this.witnessErrorView.refresh(),this.timelineTracks.setMessages(e),this.tracksToggle&&this.setTracksShown(this.tracksToggle.getAttribute("aria-expanded")==="true");for(const s of["location-settings","decor-settings","weather-settings"])er.popover(this.shadow.getElementById(s),e.close);er.dialog(this.identityAsk,e.close,()=>this.closeIdentityAsk()),er.dialog(this.fileAsk,e.close,()=>this.keepReadingWeather()),er.button(this.contextMenu,e.close,()=>this.hideContextMenu()),er.button(this.decorContextMenu,e.close,()=>this.hideDecorContextMenu()),this.shadow.getElementById("label-editor-kicker").textContent=e.editorKicker,this.shadow.getElementById("label-save").textContent=e.save,this.shareDialog.useLanguage(this.language).then(s=>{s&&(this.shareMessages=s,this.shadow.getElementById("label-share").textContent=s.share,this.refreshEditorHead())});const i={observation:e.panelIntroObservation,observer:e.panelIntroObserver,location:e.panelIntroLocation,temporal:e.panelIntroTemporal,decor:e.panelIntroDecor,weather:e.panelIntroWeather,shape:e.panelIntroShape,sound:e.panelIntroSound,reference:e.panelIntroReference,file:e.panelIntroFile};for(const[s,n]of Object.entries(i)){const r=this.shadow.querySelector(`[aria-controls="group-${s}"]`);r.dataset.intro=n,xe.titleGroupTab(r)}this.refreshEditorHead()}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 s=this.decorMoveAxis(e);if(i==="decor"&&s&&this.ufoElement.playbackState!=="playing"&&this.beginDecorDrag(e,t,s))return;const n=this.ufoElement.sighting.timeline,r=this.ufoElement.currentTime,a=this.ufoElement.playbackState==="playing",o=i==="shape";if(o)if(this.selectedSourceIds.size>1){const d=new pv(this.selectedMembers()),u=Jt.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=n.getInterpolatedShapeAt(r,this.currentSourceId),u=d?.kind==="polygon"?Jt.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&&Jt.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,Qm);if(!c){const d=s==="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(),this.flash(this.shapeTitleInput.closest("label")),e.shiftKey?this.toggleUnitSelection(c.sourceId):this.selectedSourceIds.has(c.sourceId)||this.selectUnit(c.sourceId),a||!o)return;const h=[...this.selectedSourceIds].map(d=>({sourceId:d,original:d===c.sourceId?c.shape:n.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(n=>this.selectedSourceIds.has(n))){if(i.length>=this.selectedSourceIds.size)return;for(const n of i)this.selectedSourceIds.delete(n);if(!this.selectedSourceIds.has(this.currentSourceId)){const n=t.sourceIds;this.currentSourceId=[...this.selectedSourceIds].sort((r,a)=>n.indexOf(r)-n.indexOf(a)).pop()}}else{for(const n of i)this.selectedSourceIds.add(n);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,s=this.ufoElement.currentTime,n=this.selectedSourceIds.size===1?i.getInterpolatedShapeAt(s,this.currentSourceId):void 0,a=n?.kind==="polygon"&&Jt.hitTestVertex(n,t)!==void 0?{sourceId:this.currentSourceId}:this.ufoElement.shapeAt(t.x,t.y,Qm);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 o=this.pickDecorAt(e),c=o?this.ufoElement.sighting.decor.find(h=>h.id===o):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 s=(e.clientX-i.left)/i.width*2-1,n=-((e.clientY-i.top)/i.height*2-1);return this.sceneElement.pickDecorAt(s,n)}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,s=i.filter(p=>this.selectedSourceIds.has(p)),n=i.length<=s.length,r=s.length>0&&i.slice(i.length-s.length).every(p=>this.selectedSourceIds.has(p)),a=s.length>0&&i.slice(0,s.length).every(p=>this.selectedSourceIds.has(p));this.contextBringToFrontButton.disabled=n||r,this.contextSendToBackButton.disabled=n||a,this.contextBringToFrontButton.title=n?this.messages.onlyOneShape:r?this.messages.alreadyAtFront:"",this.contextSendToBackButton.title=n?this.messages.onlyOneShape:a?this.messages.alreadyAtBack:"",this.contextGroupButton.disabled=this.selectedSourceIds.size<2,this.contextGroupButton.title=this.contextGroupButton.disabled?this.messages.needTwoShapesToGroup:"";const o=this.ufoElement.sighting.timeline.groupMembers(this.currentSourceId)!==void 0;this.contextUngroupButton.disabled=!o,this.contextUngroupButton.title=o?"":this.messages.notGrouped,this.contextDuplicateButton.disabled=this.deleteShapeButton.disabled,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?Jt.hitTestVertex(c,this.contextMenuPoint):void 0,u=h&&c.points.length<=DT;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 s=document.createElement("span");s.className="submenu-empty",s.textContent=this.messages.masksNone,this.contextMasksSubmenu.appendChild(s)}for(const s of t){const n=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=e.occludesSourceIds?.includes(s)??!1,r.addEventListener("change",()=>this.updateDecorOccludesShape(e.id,s,r.checked)),n.appendChild(r),n.appendChild(document.createTextNode(this.shapeLabel(s))),this.contextMasksSubmenu.appendChild(n)}for(const s of i){const n=this.sceneElement.bodyMaskedBy(s.id,e.id);if(n===void 0)continue;const r=document.createElement("span");r.className="submenu-empty submenu-fact";const a=this.said.read(s.title)??s.id,o=this.messages;r.textContent=`${a} — ${n>=.995?o.masksBodyFully:n>.005?o.masksBodyPartly.replace("{share}",String(Math.round(n*100))):o.masksBodyNot}`,this.contextMasksSubmenu.appendChild(r)}}updateDecorOccludesShape(e,t,i){const s=this.ufoElement.sighting;s.decor=s.decor.map(n=>{if(n.id!==e)return n;const r=i?[...new Set([...n.occludesSourceIds??[],t])]:(n.occludesSourceIds??[]).filter(a=>a!==t);return{...n,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 s=Jt.insertVertexNear(i,e);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:s}]),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 s=Jt.hitTestVertex(i,e);if(s===void 0)return;const n=Jt.deleteVertex(i,s);this.commitShapes(t,[{sourceId:this.currentSourceId,shape:n}]),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,s,n){this.dragState={kind:e,sourceId:t,original:i,handle:n,startPointer:s},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,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;if(!s||!i)return!1;i.show(s);const n=i.readingNow(),r=this.skyDirectionOf(e);return!n||!r?!1:(this.dragState={kind:"body",pointerAzimuthDeg:r.azimuthDeg,pointerAltitudeDeg:r.altitudeDeg,bodyAzimuthDeg:n.azimuthDeg,bodyAltitudeDeg:n.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 s=(i.azimuthDeg-t.pointerAzimuthDeg+540)%360-180;this.bodyEditor?.dragTo(t.bodyAzimuthDeg+s,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(xA,(e.maxX-e.minX)/2*t.width),s=Math.max(xA,(e.maxY-e.minY)/2*t.height),n=((e.minX+e.maxX)/2+1)/2*t.width,r=(1-(e.minY+e.maxY)/2)/2*t.height;return{x:n-i/2,y:r-s/2,width:i,height:s}}paintBodyOverlay=e=>{const t=this.bodyCanvasBounds();t&&e.paintGroupHandles(t)};beginFrameDrag(e,t){const i=e.bounds(),s=e.reading();if(!i||!s)return!1;const n=Jt.hitTestHandle({bounds:i,angle:0},t);if(!n)return!1;if(n==="rotate")this.dragState={kind:"frame-rotate",target:e,startPointer:t,startAttitude:{...s.attitude}};else{const r={x:i.x+i.width/2,y:i.y+i.height/2};this.dragState={kind:"frame-resize",target:e,handle:n,centre:r,startPointer:t,startSizeM:{...s.sizeM}}}return this.setCanvasCursor(this.cursorForHandle(n,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:s,startPointer:n,startSizeM:r,handle:a}=t,o=(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?o(i.x-s.x,n.x-s.x):h?o(i.y-s.y,n.y-s.y):o(Math.hypot(i.x-s.x,i.y-s.y),Math.hypot(n.x-s.x,n.y-s.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:Q1};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:IU};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:va.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,s=t&&i?this.sceneElement.pickPlacedBodyAt(t.x,t.y):void 0;!s||!i||(e.preventDefault(),i.show(s),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 s=this.pickDecorAt(e);if(s===i.id)return!0;const n=this.decorCanvasBounds();return n!==void 0&&t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+n.height?s===void 0||this.ufoElement.sighting.decor.find(a=>a.id===s)?.kind==="terrace":!1}beginDecorDrag(e,t,i){const s=this.editableDecor();if(!s)return!1;if(this.beginFrameDrag(this.decorFrame,t))return!0;if(this.ufoElement.shapeAt(t.x,t.y,Qm)||!this.grabsDecor(e,t,s))return!1;const n=this.ndcOf(e),r=va.viewOf(this.placedByAuthor(s),this.ufoElement.currentTime),a=n?this.sceneElement.decorGrabHeightAt?.(s.id,n.x,n.y)??0:0,o=n&&this.sceneElement.decorGroundPointAt(s.id,n.x,n.y,a);return!n||!o?!1:(this.dragState={kind:"decor-move",id:s.id,startGround:o,grabHeightM:a,axis:i,startAltitudeM:r.altitudeM,startNdcY:n.y,metresPerNdcY:this.sceneElement.decorMetresPerNdcY?.(s.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 s=this.sceneElement.decorGroundPointAt(t.id,i.x,i.y,t.grabHeightM);!s&&t.axis!=="up"||this.commitDecorBase(n=>{s&&(t.axis==="ground"||t.axis==="east")&&(n.eastM=this.roundedMeters(t.startEastM+s.x-t.startGround.x)),s&&(t.axis==="ground"||t.axis==="north")&&(n.northM=this.roundedMeters(t.startNorthM-(s.z-t.startGround.z))),t.axis==="up"&&(n.altitudeM=this.roundedMeters(t.startAltitudeM+(i.y-t.startNdcY)*t.metresPerNdcY))},"eastM")}beginCameraDrag(e,t,i){const s=this.isObserverInsideDecor();this.cameraDragState={pressedDecorId:t,pressedBodyId:i,moved:!1,startPointer:e,startHeadingDeg:s?this.indoorLookYawDeg:this.numberOrUndefined(this.headingInput.value)??0,startPitchDeg:s?this.indoorLookPitchDeg:this.numberOrUndefined(this.pitchInput.value)??0,insideDecor:s},s||this.sceneElement.setCompassForced(!0),this.setCanvasCursor("panning"),this.startDragListening()}isObserverInsideDecor(){return this.ufoElement.sighting.decor.some(e=>e.observerSide!==void 0&&ic(e.kind))}syncIndoorLookReset(){const e=this.ufoElement.sighting.decor.find(i=>i.observerSide!==void 0&&ic(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:s,startPointer:n}=this.dragState,r=t.x-n.x,a=t.y-n.y,o=s.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,o)}else if(this.dragState.kind==="group-resize"){const{group:s,handle:n}=this.dragState;this.commitShapes(i,s.resize(n,t))}else if(this.dragState.kind==="group-rotate"){const{group:s,startPointer:n}=this.dragState;this.commitShapes(i,s.rotate(t,n))}else if(this.dragState.kind==="vertex"){const{sourceId:s,original:n,vertexIndex:r}=this.dragState,a=Jt.moveVertex(n,r,t);this.commitShapes(i,[{sourceId:s,shape:a}])}else{const{kind:s,sourceId:n,original:r,handle:a}=this.dragState,o=s==="resize"?Jt.resizeShape(r,a,t):Jt.rotateShape(r,t);this.commitShapes(i,[{sourceId:n,shape:o}])}this.ufoElement.refresh()}onCameraDragPointerMove(e){if(!this.cameraDragState)return;const t=this.canvasPointFromEvent(e);if(!t)return;const{startPointer:i,startHeadingDeg:s,startPitchDeg:n,insideDecor:r}=this.cameraDragState;if(!this.cameraDragState.moved){if(Math.hypot(t.x-i.x,t.y-i.y)<_U)return;this.cameraDragState.moved=!0}const a=s+(t.x-i.x)*Q1,o=Math.max(-90,Math.min(90,n-(t.y-i.y)*Q1));if(r){this.indoorLookYawDeg=a,this.indoorLookPitchDeg=o,this.sceneElement.setIndoorLook(a,o),this.ufoElement.refresh();return}this.headingInput.value=String(this.rounded(a)),this.pitchInput.value=String(this.rounded(o)),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))}walkOrTurn(e){if(e.preventDefault(),this.isRecording||this.ufoElement.playbackState==="playing"||this.isObserverInsideDecor())return;const t=e.shiftKey?OU:1,i=this.numberOrUndefined(this.headingInput.value)??0;if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.headingInput.value=String(this.rounded(i+(e.key==="ArrowRight"?1:-1)*LU*t)),this.updateObserver();return}const s=this.numberOrUndefined(this.latInput.value),n=this.numberOrUndefined(this.lngInput.value);if(s===void 0||n===void 0)return;const r=(e.key==="ArrowUp"?1:-1)*CU*t,a=i*Math.PI/180,o=tr(Math.sin(a)*r,-Math.cos(a)*r,s,n);this.latInput.value=o.lat.toFixed(7),this.lngInput.value=o.lng.toFixed(7);const c=this.plantingCentre();this.updateObserver(),this.keepDecorInPlace(c,this.plantingCentre()),this.surroundings.walked(o.lat,o.lng,i)}keepDecorInPlace(e,t){if(!e||!t)return;const i=ot(t.lat,t.lng,e.lat,e.lng),s=i.x,n=-i.z;if(Math.hypot(s,n)<1e-6)return;const r=(o,c)=>Math.round((o-c)*1e3)/1e3,a=this.ufoElement.sighting;a.decor=a.decor.map(o=>({...o,eastM:r(o.eastM,s),northM:r(o.northM,n),...o.track?{track:o.track.map(c=>({...c,eastM:r(c.eastM,s),northM:r(c.northM,n)}))}:{}})),this.ufoElement.refresh()}nudgeBounds(e,t){const i={...e};if(t.shiftKey){switch(t.key){case"ArrowLeft":i.width=Math.max(Wl,i.width-gl);break;case"ArrowRight":i.width+=gl;break;case"ArrowUp":i.height=Math.max(Wl,i.height-gl);break;case"ArrowDown":i.height+=gl;break}i.x-=(i.width-e.width)/2,i.y-=(i.height-e.height)/2}else switch(t.key){case"ArrowLeft":i.x-=gl;break;case"ArrowRight":i.x+=gl;break;case"ArrowUp":i.y-=gl;break;case"ArrowDown":i.y+=gl;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:s,shape:n}=i[0];this.commitShapes(t,[{sourceId:s,shape:{...n,bounds:this.nudgeBounds(n.bounds,e)}}])}else{const s=new pv(i),n=this.nudgeBounds(s.bounds(),e);this.commitShapes(t,s.scaleTo(n))}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(),s=this.ufoElement.sighting.timeline,n=this.ufoElement.currentTime,r=this.ufoElement.playbackState!=="playing";if(i==="picture")return r?"pan":void 0;if(i==="body"){const o=r?this.bodyCanvasBounds():void 0,c=o&&Jt.hitTestHandle({bounds:o,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 o=this.decorCanvasBounds(),c=o&&Jt.hitTestHandle({bounds:o,angle:0},t);if(c)return this.cursorForHandle(c,0);const h=this.editableDecor();if(h&&!this.ufoElement.shapeAt(t.x,t.y,Qm)&&this.grabsDecor(e,t,h))return"move"}const a=i==="shape";if(r&&a)if(this.selectedSourceIds.size>1){const o=Jt.hitTestHandle({bounds:new pv(this.selectedMembers()).bounds(),angle:0},t);if(o)return this.cursorForHandle(o,0)}else{const o=s.getInterpolatedShapeAt(n,this.currentSourceId);if(o?.kind==="polygon"&&Jt.hitTestVertex(o,t)!==void 0)return"vertex";const c=o&&Jt.hitTestHandle(o,t);if(o&&c)return this.cursorForHandle(c,o.angle)}return s.hitTest(n,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-${Jt.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(),s=e.clientX-i.left,n=e.clientY-i.top;this.recorder?.onPointerMove(s,n),this.ufoElement.renderer.clear(t.width,t.height),this.ufoElement.renderer.paintShape(RA(this.buildPrototype({x:0,y:0,width:jh.width,height:jh.height}),s,n))}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 BU={measured:"narrativeStated",stated:"narrativeStated",derived:"narrativeDerived",assumed:"narrativeAssumed"},TA="rr0-sighting-editor";function _I(){WA(),ow(),EI(),HF(),BF(),$F(),Ug(),customElements.get(TA)||customElements.define(TA,xe)}const IA="rr0-case-editor",zU=`
|
|
11756
11756
|
<style>
|
|
11757
11757
|
:host { display: block; }
|