@rr0/ufoathome 0.194.0 → 0.195.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-embed-scene/rr0-scene.mjs +4 -4
- package/dist-embed-sighting/{CaseReportExport-B9iaGKNP.js → CaseReportExport-BeKawC8S.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +8 -8
- package/dist-embed-sighting-editor/{CaseElement-DzwFIDZZ.js → CaseElement-CVi_yfyW.js} +1 -1
- package/dist-embed-sighting-editor/{CaseReportExport-D0GXupCT.js → CaseReportExport-DisXbZ3b.js} +1 -1
- package/dist-embed-sighting-editor/{SightingElement-BfxNhmfn.js → SightingElement-Bdkf99VT.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +17 -16
- package/dist-embed-ufoathome/{AdsbLolArchiveProvider-DXRO-h2K.js → AdsbLolArchiveProvider-veDw9Mxo.js} +1 -1
- package/dist-embed-ufoathome/{BallesterGuaspAssessor-ZSDHMhXN.js → BallesterGuaspAssessor-BVygSN0R.js} +1 -1
- package/dist-embed-ufoathome/{BeamEditor-BvF4J204.js → BeamEditor-eDeeNBE9.js} +1 -1
- package/dist-embed-ufoathome/{BeamSystem-Yg5JRiCT.js → BeamSystem-B5u4ithz.js} +1 -1
- package/dist-embed-ufoathome/{BodyEditor-CRJFVGzZ.js → BodyEditor-23Dua2K5.js} +1 -1
- package/dist-embed-ufoathome/{CaseEditorElement-MwO-zwnP.js → CaseEditorElement-DYMt7oB4.js} +13 -12
- package/dist-embed-ufoathome/{CaseElement-Ch0QzF7-.js → CaseElement-C6KVIESP.js} +3 -3
- package/dist-embed-ufoathome/{CaseReportExport-D9YyGZHP.js → CaseReportExport-Cgs2Y0v3.js} +3 -3
- package/dist-embed-ufoathome/{CaseTimeline-CnP5rqaK.js → CaseTimeline-BwCuVg5N.js} +3 -3
- package/dist-embed-ufoathome/{ContrailSystem-O_yvjart.js → ContrailSystem-CtQPQFyc.js} +1 -1
- package/dist-embed-ufoathome/{ControlPasses-BaglOE-7.js → ControlPasses-B_uf1Wmh.js} +1 -1
- package/dist-embed-ufoathome/{CoverageAssessor-CBh0sDI1.js → CoverageAssessor-JQCFe16i.js} +1 -1
- package/dist-embed-ufoathome/{Flightradar24Provider-C8Uj-qTs.js → Flightradar24Provider-BR8_7wmx.js} +1 -1
- package/dist-embed-ufoathome/{GLTFLoader-B4SVqjkZ.js → GLTFLoader-DrBMau2Y.js} +1 -1
- package/dist-embed-ufoathome/{GeoJsonExport-C-daFhc2.js → GeoJsonExport-wUgEVyel.js} +1 -1
- package/dist-embed-ufoathome/{GeographicFigures-N4WyX3J_.js → GeographicFigures-CpbFopao.js} +1 -1
- package/dist-embed-ufoathome/{HeadlightSystem-7mtgTwud.js → HeadlightSystem-YXD1Zdpn.js} +1 -1
- package/dist-embed-ufoathome/{HynekAssessor-DdoHR-Qt.js → HynekAssessor-BV2nWUx8.js} +1 -1
- package/dist-embed-ufoathome/{InterviewEditorElement-BSXLlt4e.js → InterviewEditorElement-DiT6FZnj.js} +1 -1
- package/dist-embed-ufoathome/{InterviewElement-Dwk9iHNv.js → InterviewElement-DFcCnZtF.js} +1 -1
- package/dist-embed-ufoathome/{KmlExport-CX-tTjIv.js → KmlExport-wWr2S8H-.js} +1 -1
- package/dist-embed-ufoathome/{LaserBeam-DUL1O57g.js → LaserBeam-CejB0H9v.js} +1 -1
- package/dist-embed-ufoathome/{LaunchEditor-X_zWEOTY.js → LaunchEditor-ConcMLIe.js} +1 -1
- package/dist-embed-ufoathome/{LaunchPlume-CcfhClxb.js → LaunchPlume-BQEYjeSf.js} +1 -1
- package/dist-embed-ufoathome/{LaunchSimulation-C9gbGzGM.js → LaunchSimulation-BIiU6D8P.js} +1 -1
- package/dist-embed-ufoathome/{ModelSource-BtuW2Ztg.js → ModelSource-B93j0IA6.js} +1 -1
- package/dist-embed-ufoathome/{ModelThumbnails-CacTTCW4.js → ModelThumbnails-3U8M50_n.js} +1 -1
- package/dist-embed-ufoathome/{ModelViewer-BlFPQJAr.js → ModelViewer-Cnxj0Oi9.js} +1 -1
- package/dist-embed-ufoathome/{ModuleConformance-qYpBoQH9.js → ModuleConformance-BlrRirPF.js} +2 -2
- package/dist-embed-ufoathome/{ModuleSession-D4LhYKvL.js → ModuleSession-Cdilmebx.js} +3 -3
- package/dist-embed-ufoathome/{ModuleThree-DLikU-uy.js → ModuleThree-Dpv5uvYp.js} +1 -1
- package/dist-embed-ufoathome/{ModulesPanelElement-GY7cTQ5t.js → ModulesPanelElement-CwgqBVUI.js} +3 -3
- package/dist-embed-ufoathome/{NearestApproach-4ntSx6IQ.js → NearestApproach-CQ2w9ctm.js} +1 -1
- package/dist-embed-ufoathome/{PictureRegistration-BLs4DkTI.js → PictureRegistration-DOSDjiOf.js} +1 -1
- package/dist-embed-ufoathome/{PoherAssessor-6t5qvmJy.js → PoherAssessor-C8g5YvJi.js} +1 -1
- package/dist-embed-ufoathome/{RailwaySystem-Dm-PbG_D.js → RailwaySystem-D8B965iv.js} +1 -1
- package/dist-embed-ufoathome/{ReentryEditor-C7A3Kh3_.js → ReentryEditor-CEbb0oLd.js} +1 -1
- package/dist-embed-ufoathome/{ReentrySimulation-BlgfVSxb.js → ReentrySimulation-D_JX7wWS.js} +1 -1
- package/dist-embed-ufoathome/{ReferenceSystem-Bv62TprV.js → ReferenceSystem-xm8mzWiT.js} +1 -1
- package/dist-embed-ufoathome/{ShareDialogElement-DLr5u_tk.js → ShareDialogElement-BBMLOqSW.js} +11 -11
- package/dist-embed-ufoathome/{SightingElement-DuNE_Yt0.js → SightingElement-e9ZcWa58.js} +2 -2
- package/dist-embed-ufoathome/{TraceSystem-Cl5kzaIr.js → TraceSystem-BL6qfrHF.js} +1 -1
- package/dist-embed-ufoathome/{VideoButton-DXPI7_Vt.js → VideoButton-DA48Qz2E.js} +1 -1
- package/dist-embed-ufoathome/{WaterSystem-CTGGh-Y-.js → WaterSystem-BLy0L9qC.js} +1 -1
- package/dist-embed-ufoathome/rr0-ufoathome.mjs +2 -2
- package/dist-embed-ufoathome/{surroundingsSources-CVKKb8h6.js → surroundingsSources-Dlyt6moH.js} +1 -1
- package/dist-embed-ufoathome/{trafficRuntime-DvKPyJcx.js → trafficRuntime-B_bwWY8d.js} +1 -1
- package/package.json +1 -1
package/dist-embed-ufoathome/{ShareDialogElement-DLr5u_tk.js → ShareDialogElement-BBMLOqSW.js}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./VideoButton-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./VideoButton-DA48Qz2E.js","./rr0-ufoathome.mjs","./SaidPosition-CWiVNaNW.js","./Sighting-CBpJpdm9.js","./VisualAids-DI-hEL46.js","./Decor-Dn-cvniW.js","./RecordingIssue-BlWT8Xsu.js","./Obstacles-v9SkfBD7.js","./CoverageAssessor-JQCFe16i.js","./HynekAssessor-BV2nWUx8.js","./NearestApproach-CQ2w9ctm.js","./BallesterGuaspAssessor-BVygSN0R.js","./Account-C4jhsVtN.js","./PoherAssessor-C8g5YvJi.js","./RoadMarkings-BsN3rh0W.js","./BeamSystem-B5u4ithz.js","./LaserBeam-CejB0H9v.js","./BeamEditor-eDeeNBE9.js","./SkyEventEditorStyle-CvY_AhbI.js","./ParameterForm-DfpJQGku.js","./TimelineTracks-X_GEZi12.js","./LaunchSimulation-BIiU6D8P.js","./LaunchPlume-BQEYjeSf.js","./LaunchEditor-ConcMLIe.js","./ReentrySimulation-D_JX7wWS.js","./ReentryEditor-CEbb0oLd.js","./ReentryArchive-CeXHrU7L.js","./GLTFLoader-DrBMau2Y.js","./WaterSystem-BLy0L9qC.js","./RailwaySystem-D8B965iv.js","./TraceSystem-BL6qfrHF.js","./ContrailSystem-CtQPQFyc.js","./ContrailGrowth-DwHS8If9.js","./HeadlightSystem-YXD1Zdpn.js","./ControlPasses-B_uf1Wmh.js","./ReferenceSystem-xm8mzWiT.js","./ReferenceTimeline-2kBldQeG.js","./PictureFetch-C3wgf1ZV.js","./AdsbLolArchiveProvider-veDw9Mxo.js","./Flightradar24Provider-BR8_7wmx.js","./trafficRuntime-B_bwWY8d.js","./upperAirSources-BGuLpdwu.js","./ModuleSession-Cdilmebx.js","./GenerativeKit-BmhvjjzB.js","./browser-CltifEM0.js","./VideoExport-B8ZhHNnd.js","./GenerativeKitMessages-BwG7cWZX.js","./ShareCodeEditor-DyEYu_9d.js","./index-C8cdeM8E.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{F as s1,P as Ls,H as Sr,s as zh,U as Bh,x as Qb,_ as Ht,S as dx,z as tS,M as fc,e as rs,h as jd,o as E0,n as Ur,c as eS,A as iS}from"./rr0-ufoathome.mjs";import{a as dv,g as re,S as lu,l as Nn,I as sS,b as Ch,P as nS}from"./SaidPosition-CWiVNaNW.js";import{A as Di,c as Te,I as Ts,H as A0,T as fx,l as px,O as fv,W as pv,n as mv,p as jn,k as al,f as mx,s as gx,o as aS,b as tl,r as vx,F as Ql,h as rS,q as oS,a as cS,t as Mx,u as th}from"./Sighting-CBpJpdm9.js";import{l as pm,i as yx,e as xx,r as ga,c as Hl,h as wx,a as mf,D as gf,f as lS,F as hS,g as uS,j as n1,k as bx,m as dS,b as fS,n as pS,H as mm,p as gv,q as vv}from"./Decor-Dn-cvniW.js";import{R as Mv}from"./RecordingIssue-BlWT8Xsu.js";import{O as yv}from"./Obstacles-v9SkfBD7.js";/**
|
|
3
3
|
@preserve
|
|
4
4
|
|
|
@@ -1565,9 +1565,9 @@ canvas[data-cursor="rotate"] {
|
|
|
1565
1565
|
white-space: nowrap;
|
|
1566
1566
|
}
|
|
1567
1567
|
`;class Pl{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:s,lng:n,headingDeg:a}=i.pose;s===void 0||n===void 0||e.push({t:i.t,lat:s,lng:n,headingDeg:a})}if(e.length===0){const i=t.event.place?.[0];if(!i)return;e.push({t:0,lat:i.lat,lng:i.lng})}return new Pl(e)}static TRAVEL_M=50;get travels(){return this.spanM>Pl.TRAVEL_M}get moved(){return this.spanM>Pl.STATIONARY_M}get spanM(){const t=this.box,e=(t.south+t.north)/2,i=(t.west+t.east)/2;return Math.max(Math.abs(re(e,t.east,e,t.west).x),Math.abs(re(t.north,i,t.south,i).z))}get center(){const t=this.box;return{lat:(t.south+t.north)/2,lng:(t.west+t.east)/2}}boundsAround(t,e){const{lat:i,lng:s}=this.center,n=Math.max(this.spanM*(1+e),t)/2;return{north:Nn(0,-n,i,s).lat,south:Nn(0,n,i,s).lat,east:Nn(n,0,i,s).lng,west:Nn(-n,0,i,s).lng}}get box(){const t=this.points.map(i=>i.lat),e=this.points.map(i=>i.lng);return{south:Math.min(...t),north:Math.max(...t),west:Math.min(...e),east:Math.max(...e)}}}class Kn{constructor(t,e){this.rotationPassed=t,this.scale=e}static SWAY_M=.012;static BREATH_M=.003;static DRIFT_YAW_DEG=.5;static DRIFT_PITCH_DEG=.4;static DRIFT_ROLL_DEG=.3;static GAZE_DRIFT_SHARE=.35;static HAND_HELD_S=.5;static HZ=[.11,.23,.17,.29,.37,.07];static of(t){if(t.instrument.mounted)return;const e=t.event.tags?.includes("paralysis")||(t.exposure??0)>Kn.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new Kn(Math.max(1-(t.instrument.stabilization??0),Kn.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,s=(u,d)=>Math.sin(2*Math.PI*u*e+d),[n,a,r,o,l,h]=Kn.HZ;return{eastM:i*Kn.SWAY_M*(.7*s(n,.3)+.3*s(o,1.9)),northM:i*Kn.SWAY_M*(.6*s(r,2.2)+.4*s(l,.8)),upM:i*Kn.BREATH_M*s(a,0),yawDeg:i*this.rotationPassed*Kn.DRIFT_YAW_DEG*(.6*s(h,1.1)+.4*s(o,2.7)),pitchDeg:i*this.rotationPassed*Kn.DRIFT_PITCH_DEG*(.5*s(a,1.6)+.5*s(r,.4)),rollDeg:i*this.rotationPassed*Kn.DRIFT_ROLL_DEG*s(n,2.9)}}}class ii{constructor(t,e){this.stretches=t,this.rotationPassed=e}static REFERENCE_SPEED_M_PER_S=1.4;static REFERENCE_STEP_HZ=1.9;static CADENCE_EXPONENT=.43;static RISE_M_PER_M_PER_S=.0175;static SWAY_M=.0175;static SLOWEST_WALK_M_PER_S=.2;static FASTEST_WALK_M_PER_S=2.2;static HEAD_ROLL_DEG=1.5;static HEAD_PITCH_DEG=1.25;static HEAD_YAW_DEG=1;static STOP_LURCH_M=.035;static STOP_PITCH_DEG=3;static START_LURCH_M=.015;static START_PITCH_DEG=1.2;static JOLT_HZ=1.4;static JOLT_DECAY_S=.35;static JOLT_LASTS_MS=1500;static STILL=Object.freeze({eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0});static of(t){const e=Pl.of(t);if(!e||e.points.length<2)return;const i=[];let s=0;for(let n=1;n<e.points.length;n++){const a=e.points[n-1],r=e.points[n],o=(r.t-a.t)/1e3;if(o<=0)continue;const l=re(r.lat,r.lng,a.lat,a.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/o,p=ii.stepHzFor(f);i.push({startMs:a.t,endMs:r.t,speedMPerS:f,eastUnit:d>0?h/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:s,rampsIn:!0,rampsOut:!0}),s+=p*o}for(let n=0;n<i.length;n++){const a=i[n-1],r=i[n+1];i[n].rampsIn=a===void 0||a.stepHz===0,i[n].rampsOut=r===void 0||r.stepHz===0}if(i.some(n=>n.stepHz>0))return new ii(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const s=ii.of(t)?.offsetAt(e)??ii.STILL;return i?s:ii.add(s,Kn.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ii.SLOWEST_WALK_M_PER_S||t>ii.FASTEST_WALK_M_PER_S?0:ii.REFERENCE_STEP_HZ*Math.pow(t/ii.REFERENCE_SPEED_M_PER_S,ii.CADENCE_EXPONENT)}offsetAt(t){return ii.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ii.REFERENCE_SPEED_M_PER_S,s=(r,o,l,h)=>{if(r<0||r>ii.JOLT_LASTS_MS)return;const u=r/1e3,d=Math.exp(-u/ii.JOLT_DECAY_S)*Math.sin(2*Math.PI*ii.JOLT_HZ*u),f=h*o*i*d;return{eastM:f*e.eastUnit,northM:f*e.northUnit,upM:-Math.abs(f)*.3,rollDeg:0,pitchDeg:-h*l*i*d*this.rotationPassed,yawDeg:0}},n=e.rampsOut?s(t-e.endMs,ii.STOP_LURCH_M,ii.STOP_PITCH_DEG,1):void 0;if(n)return n;const a=e.rampsIn?s(t-e.startMs,ii.START_LURCH_M,ii.START_PITCH_DEG,-1):void 0;if(a)return a}}static add(t,e){return e?{eastM:t.eastM+e.eastM,northM:t.northM+e.northM,upM:t.upM+e.upM,rollDeg:t.rollDeg+e.rollDeg,pitchDeg:t.pitchDeg+e.pitchDeg,yawDeg:t.yawDeg+e.yawDeg}:t}cycleAt(t){const e=this.stretches.find(o=>t>=o.startMs&&t<=o.endMs);if(!e||e.stepHz===0)return ii.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,s=2*Math.PI*i,n=this.amplitudeAt(e,t),a=ii.SWAY_M*n*Math.cos(s/2),r=n*this.rotationPassed*e.speedMPerS/ii.REFERENCE_SPEED_M_PER_S;return{eastM:a*e.northUnit,northM:-a*e.eastUnit,upM:ii.RISE_M_PER_M_PER_S*e.speedMPerS*n*Math.cos(s),rollDeg:ii.HEAD_ROLL_DEG*r*Math.cos(s/2),pitchDeg:-1.25*r*Math.cos(s),yawDeg:ii.HEAD_YAW_DEG*r*Math.cos(s/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,s=Math.min(i,(t.endMs-t.startMs)/2);if(s<=0)return 1;const n=e-t.startMs,a=t.endMs-e,r=Math.min(t.rampsIn?n/s:1,t.rampsOut?a/s:1,1);return(1-Math.cos(Math.PI*Math.max(r,0)))/2}}class HE{constructor(t,e){this.timeline=t,this.onFrame=e}rafId=null;state="stopped";currentT=0;lastWallTime=0;playbackRate=1;loop=!1;onEnded;durationOverrideMs=0;get seekableDuration(){return Math.max(this.timeline.duration,this.durationOverrideMs)}play(){if(this.state==="playing")return;this.currentT>=this.seekableDuration&&(this.currentT=0,this.resolveFrame(0)),this.state="playing",this.lastWallTime=performance.now();const t=()=>{if(this.state!=="playing")return;const e=performance.now();if(this.currentT+=(e-this.lastWallTime)*this.playbackRate,this.lastWallTime=e,this.currentT>=this.seekableDuration){if(this.loop&&this.seekableDuration>0){this.currentT%=this.seekableDuration,this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t);return}this.currentT=this.seekableDuration,this.stop(),this.resolveFrame(this.currentT),this.onEnded?.();return}this.resolveFrame(this.currentT),this.rafId=requestAnimationFrame(t)};this.rafId=requestAnimationFrame(t)}pause(){this.state==="playing"&&(this.state="paused",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null))}stop(){this.state="stopped",this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}seek(t){this.currentT=Math.max(0,Math.min(t,this.seekableDuration)),this.resolveFrame(this.currentT)}get playbackState(){return this.state}get time(){return this.currentT}resolveFrame(t){const e=new Map;for(const i of this.timeline.sourceIds){const s=this.timeline.getInterpolatedShapeAt(t,i);s&&e.set(i,s)}this.onFrame(t,e)}}const jx=["nw","n","ne","e","se","s","sw","w"],GE=24,ll=8,VE=3,WE=8;function Nh(c,t,e){const i=c.x-t.x,s=c.y-t.y,n=Math.cos(e),a=Math.sin(e);return{x:t.x+i*n-s*a,y:t.y+i*a+s*n}}function Fo(c){return{x:c.x+c.width/2,y:c.y+c.height/2}}const XE={nw:{left:!0,top:!0},n:{top:!0},ne:{right:!0,top:!0},e:{right:!0},se:{right:!0,bottom:!0},s:{bottom:!0},sw:{left:!0,bottom:!0},w:{left:!0}};class cn{static handlePointsFor(t){const{x:e,y:i,width:s,height:n}=t.bounds,a={nw:{x:e,y:i},n:{x:e+s/2,y:i},ne:{x:e+s,y:i},e:{x:e+s,y:i+n/2},se:{x:e+s,y:i+n},s:{x:e+s/2,y:i+n},sw:{x:e,y:i+n},w:{x:e,y:i+n/2},rotate:{x:e+s/2,y:i-GE}},r=Fo(t.bounds),o={};for(const l of Object.keys(a))o[l]=Nh(a[l],r,t.angle);return o}static hitTestHandle(t,e,i=8,s=[...jx,"rotate"]){const n=cn.handlePointsFor(t);for(const a of s)if(Math.hypot(e.x-n[a].x,e.y-n[a].y)<=i)return a}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const s=((cn.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,n=["ew","nwse","ns","nesw"];return n[Math.round(s)%n.length]}static resizeBounds(t,e,i,s){const n=Fo(t),a=Nh(s,n,-e),{x:r,y:o,width:l,height:h}=t,u=XE[i];let d=r,f=o,p=r+l,g=o+h;return u.left&&(d=Math.min(a.x,p-ll)),u.right&&(p=Math.max(a.x,d+ll)),u.top&&(f=Math.min(a.y,g-ll)),u.bottom&&(g=Math.max(a.y,f+ll)),{x:d,y:f,width:p-d,height:g-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:s,height:n}=t.bounds,a=cn.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:a};const r=s===0?1:a.width/s,o=n===0?1:a.height/n;return{...t,bounds:a,points:t.points.map(l=>({x:l.x*r,y:l.y*o}))}}static rotateShape(t,e){const i=Fo(t.bounds),s=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:s}}static groupBoundsFor(t){const e=Math.min(...t.map(a=>a.x)),i=Math.min(...t.map(a=>a.y)),s=Math.max(...t.map(a=>a.x+a.width)),n=Math.max(...t.map(a=>a.y+a.height));return{x:e,y:i,width:s-e,height:n-i}}static vertexPointsFor(t){const e=Fo(t.bounds);return t.points.map(i=>Nh({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=WE){const s=cn.vertexPointsFor(t);let n,a=i;return s.forEach((r,o)=>{const l=Math.hypot(e.x-r.x,e.y-r.y);l<=a&&(a=l,n=o)}),n}static toLocalPoint(t,e){const i=Fo(t.bounds),s=Nh(e,i,-t.angle);return{x:s.x-t.bounds.x,y:s.y-t.bounds.y}}static moveVertex(t,e,i){const s=t.points.map((u,d)=>d===e?cn.toLocalPoint(t,i):u),n=Math.min(...s.map(u=>u.x)),a=Math.min(...s.map(u=>u.y)),r=Math.max(...s.map(u=>u.x)),o=Math.max(...s.map(u=>u.y)),l={x:t.bounds.x+n,y:t.bounds.y+a,width:r-n,height:o-a},h=s.map(u=>({x:u.x-n,y:u.y-a}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=cn.toLocalPoint(t,e),{points:s}=t;let n=s.length-1,a=1/0;for(let o=0;o<s.length;o++){const l=s[o],h=s[(o+1)%s.length],u=cn.distanceToSegment(i,l,h);u<a&&(a=u,n=o)}const r=[...s.slice(0,n+1),i,...s.slice(n+1)];return{...t,points:r}}static distanceToSegment(t,e,i){const s=i.x-e.x,n=i.y-e.y,a=s*s+n*n,r=a===0?0:Math.max(0,Math.min(1,((t.x-e.x)*s+(t.y-e.y)*n)/a)),o=e.x+r*s,l=e.y+r*n;return Math.hypot(t.x-o,t.y-l)}static deleteVertex(t,e){return t.points.length<=VE?t:{...t,points:t.points.filter((i,s)=>s!==e)}}}class kO{constructor(t){this.members=t}bounds(){return cn.groupBoundsFor(this.members.map(t=>t.shape.bounds))}scaleTo(t){const e=this.bounds(),i=e.width===0?1:t.width/e.width,s=e.height===0?1:t.height/e.height;return this.members.map(({sourceId:n,shape:a})=>{const r=Math.max(a.bounds.width*i,ll),o=Math.max(a.bounds.height*s,ll),l=t.x+(a.bounds.x-e.x)*i,h=t.y+(a.bounds.y-e.y)*s,u={x:l,y:h,width:r,height:o};return a.kind==="oval"?{sourceId:n,shape:{...a,bounds:u}}:{sourceId:n,shape:{...a,bounds:u,points:a.points.map(d=>({x:d.x*i,y:d.y*s}))}}})}resize(t,e){return this.scaleTo(cn.resizeBounds(this.bounds(),0,t,e))}rotate(t,e){const i=Fo(this.bounds()),s=a=>Math.atan2(a.y-i.y,a.x-i.x),n=s(t)-s(e);return this.members.map(({sourceId:a,shape:r})=>{const o=Fo(r.bounds),l=Nh(o,i,n),h={x:l.x-r.bounds.width/2,y:l.y-r.bounds.height/2,width:r.bounds.width,height:r.bounds.height};return{sourceId:a,shape:{...r,bounds:h,angle:r.angle+n}}})}}const Lm=6,Bu=Lm/2,Lv=20,Nv=24,kv=9,Fv=6,Uv=7,zv=6,Ea=4;class Gl{constructor(t){this.ctx=t}starPoints=0;roll=0;clear(t,e){this.ctx.clearRect(0,0,t,e)}static paintExtent(t){const{x:e,y:i,width:s,height:n}=t.bounds,a=e+s/2,r=i+n/2,o=t.angle%(2*Math.PI)!==0,l=Math.hypot(s,n)/2,h=o?l:s/2,u=o?l:n/2,d=Math.max(s,n)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+kv*f),zv*f)-d:0,g=f>0?d*(1+Uv*f)-d:0,m=3*Nv*(t.blur??0)+1.5*Lv*t.haloScale,v=Math.max(p,g,0)+m+2;return{x:a-h-v,y:r-u-v,width:2*(h+v),height:2*(u+v)}}paintInto(t,e,i,s=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const n=t.selected?{...t,selected:!1}:t;s?this.paintGhost(n,1.5):this.paintShape(n),this.ctx.restore()}paintShape(t){this.ctx.save(),this.ctx.globalAlpha=1-t.transparency;const e=t.blur??0;e>0&&(this.ctx.filter=`blur(${(Nv*e).toFixed(2)}px)`);const i=t.brightness??0;i>0&&this.paintDazzle(t,i),t.haloScale>0&&this.paintHalo(t),this.paintBase(t),this.ctx.restore(),t.selected&&this.paintSelectionHandles(t)}setStarPoints(t){this.starPoints=Math.max(0,Math.floor(t))}setRoll(t){this.roll=t}paintDazzle(t,e){const{x:i,y:s,width:n,height:a}=t.bounds,r=i+n/2,o=s+a/2,l=Math.max(n,a)/2,h=Math.max(l*(1+kv*e),zv*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(r,o,0,r,o,h);for(let d=0;d<=Fv;d++){const f=d/Fv,p=1/(1+24*f*f);this.ctx.globalAlpha=1,u.addColorStop(f,this.withAlpha(t.color,p*e*.55))}if(this.ctx.fillStyle=u,this.ctx.beginPath(),this.ctx.arc(r,o,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+Uv*e);this.ctx.lineWidth=Math.max(1,l*.12),this.ctx.lineCap="round";for(let f=0;f<this.starPoints;f++){const p=f/this.starPoints*Math.PI*2+this.roll,g=r+Math.cos(p)*d,m=o+Math.sin(p)*d,v=this.ctx.createLinearGradient(r,o,g,m);v.addColorStop(0,this.withAlpha(t.color,e*.55)),v.addColorStop(.35,this.withAlpha(t.color,e*.22)),v.addColorStop(1,this.withAlpha(t.color,0)),this.ctx.strokeStyle=v,this.ctx.beginPath(),this.ctx.moveTo(r,o),this.ctx.lineTo(g,m),this.ctx.stroke()}}this.ctx.restore()}dazzledFill(t,e){if(e<=0)return t.color;const i=/^#([0-9a-f]{6})$/i.exec(t.color.trim());if(!i)return t.color;const s=Number.parseInt(i[1],16),n=a=>Math.round(a+(255-a)*e);return`rgb(${n(s>>16&255)}, ${n(s>>8&255)}, ${n(s&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),s=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!s)return t;const n=Number.parseInt(s[1],16);return`rgba(${n>>16&255}, ${n>>8&255}, ${n&255}, ${i.toFixed(3)})`}paintBase(t){this.ctx.fillStyle=this.dazzledFill(t,t.brightness??0),this.tracePath(t),this.ctx.fill()}paintGhost(t,e){this.ctx.save(),this.tracePath(t),this.ctx.setLineDash([e*3,e*2]),this.ctx.lineWidth=e,this.ctx.strokeStyle=t.color,this.ctx.stroke(),this.ctx.restore()}tracePath(t){if(this.ctx.beginPath(),t.kind==="oval"){const{x:e,y:i,width:s,height:n}=t.bounds,a=s/2,r=n/2;this.ctx.ellipse(e+a,i+r,a,r,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:s,height:n}=t.bounds;this.ctx.save(),this.ctx.translate(e+s/2,i+n/2),this.ctx.rotate(t.angle),this.ctx.translate(-s/2,-n/2),t.points.forEach((a,r)=>{r===0?this.ctx.moveTo(a.x,a.y):this.ctx.lineTo(a.x,a.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=Lv*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(cn.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of cn.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Ea,Ea,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(cn.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const s=this.ctx;if(s.save(),t&&t.length===4){s.strokeStyle="#39f",s.lineWidth=1.5,s.setLineDash([6,4]),s.beginPath(),s.moveTo(t[0].x,t[0].y);for(const n of t.slice(1))s.lineTo(n.x,n.y);s.closePath(),s.stroke(),s.setLineDash([])}for(const n of e){const a=Gl.landmarkColour(n.residualDeg),r=n.selected?3:2;n.selected&&(s.strokeStyle="#fff",s.lineWidth=r+3,s.beginPath(),s.ellipse(n.picture.x,n.picture.y,Ea+2,Ea+2,0,0,2*Math.PI),s.stroke()),n.scene&&(s.strokeStyle=a,s.lineWidth=1,s.beginPath(),s.moveTo(n.picture.x,n.picture.y),s.lineTo(n.scene.x,n.scene.y),s.stroke(),s.fillStyle=a,s.beginPath(),s.ellipse(n.scene.x,n.scene.y,Ea,Ea,0,0,2*Math.PI),s.fill()),s.strokeStyle=a,s.lineWidth=r,s.beginPath(),s.ellipse(n.picture.x,n.picture.y,Ea+2,Ea+2,0,0,2*Math.PI),s.stroke(),this.paintLabel(n.label,n.picture.x+Ea+5,n.picture.y-Ea-2,a)}i&&this.paintLabel(i,8,8,"#fff",13),s.restore()}paintGhosts(t,e,i){const s=this.ctx;s.save();const n=(o,l,h,u=[])=>{s.setLineDash(u),s.lineWidth=h+2,s.strokeStyle="rgba(0, 0, 0, 0.6)",o(),s.lineWidth=h,s.strokeStyle=l,o(),s.setLineDash([])},a=(o,l)=>()=>{s.beginPath(),s.arc(o.x,o.y,l,0,2*Math.PI),s.stroke()},r=(o,l,h)=>()=>{const[u,d]=h?[l,l]:[l,0];s.beginPath(),s.moveTo(o.x-u,o.y-d),s.lineTo(o.x+u,o.y+d),s.moveTo(o.x+d,o.y-u),s.lineTo(o.x-d,o.y+u),s.stroke()};for(const o of t)n(()=>{s.beginPath(),s.moveTo(o.ghost.x,o.ghost.y),s.lineTo(o.light.x,o.light.y),s.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),n(a(o.light,7),"#ffffff",1.5),n(a(o.ghost,Math.max(9,o.ghostRadius)),"#ffd23f",2);e&&n(r(e,8,!1),"#ffd23f",2),i&&n(r(i,5,!0),"rgba(255, 255, 255, 0.7)",1),s.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,s,n=11){const a=this.ctx;a.save(),a.font=`${n}px system-ui, sans-serif`,a.textBaseline="top";const r=a.measureText(t).width;a.fillStyle="rgba(0, 0, 0, 0.6)",a.fillRect(e-3,i-2,r+6,n+4),a.fillStyle=s,a.fillText(t,e,i),a.restore()}paintGroupHandles(t){this.paintHandleFrame(cn.handlePointsFor({bounds:t,angle:0}),{includeRotate:!0})}paintOutline(t){this.ctx.strokeStyle="lightgray",this.ctx.beginPath(),this.ctx.moveTo(t.nw.x,t.nw.y),this.ctx.lineTo(t.ne.x,t.ne.y),this.ctx.lineTo(t.se.x,t.se.y),this.ctx.lineTo(t.sw.x,t.sw.y),this.ctx.closePath(),this.ctx.stroke()}paintHandleFrame(t,{includeRotate:e}){this.paintOutline(t),this.ctx.fillStyle="lightgray";for(const i of jx){const s=t[i];this.ctx.fillRect(s.x-Bu,s.y-Bu,Lm,Lm)}e&&(this.ctx.beginPath(),this.ctx.moveTo(t.n.x,t.n.y),this.ctx.lineTo(t.rotate.x,t.rotate.y),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.ellipse(t.rotate.x,t.rotate.y,Bu+1,Bu+1,0,0,2*Math.PI),this.ctx.fill())}}class Un{static sessionDeclared=!1;static isLive(t){return t!==void 0&&typeof AudioContext<"u"&&t instanceof AudioContext}static unlock(t){if(Un.declarePlayback(),t.state!=="running")try{Promise.resolve(t.resume()).catch(()=>{});const e=t.createBufferSource();e.buffer=t.createBuffer(1,1,22050),e.connect(t.destination),e.start(0)}catch{}}static declarePlayback(){if(!(Un.sessionDeclared||typeof navigator>"u")){Un.sessionDeclared=!0;try{const t=navigator.audioSession;t&&(t.type="playback")}catch{}}}}const Bv=.05,Hv=.08,Gv=2,Vv=3,KE=14,YE=.02;class Wv{context;constructor(t){this.context=t}voice;voiceToken=0;buffers=new Map;noiseBuffer;crackleBuffer;requested;level=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("SightingAudio: Web Audio unavailable, the sighting stays silent:",t);return}}Un.isLive(this.context)&&Un.unlock(this.context)}setSound(t){if(this.requested=t,!this.context)return;const e=this.keyFor(t);if(!e){this.silence();return}if(this.voice?.key!==e){this.stopVoice();const i=++this.voiceToken;e.startsWith("src:")?this.buildRecordedVoice(t.src,e,i):this.voice=this.buildSynthesizedVoice(t,e)}this.applyTo(this.voice,t)}silence(){this.voiceToken++,this.stopVoice()}dispose(){this.silence(),Un.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear(),this.noiseBuffer=void 0,this.crackleBuffer=void 0}keyFor(t){if(!(t.volume<=0))return t.src?`src:${t.src}`:t.kind==="none"?void 0:t.kind}applyTo(t,e){const i=this.context;if(!t||!i)return;const s=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,s,Bv);for(const{param:n,ratio:a}of t.pitch)n.setTargetAtTime(Math.min(e.pitchHz*a,i.sampleRate/2-1),s,Bv)}buildSynthesizedVoice(t,e){const i=this.context;if(i)switch(t.kind){case"hum":return this.buildHum(i,e);case"whistle":return this.buildWhistle(i,e);case"rumble":return this.buildRumble(i,e);case"crackle":return this.buildCrackle(i,e);default:return}}buildHum(t,e){const i=t.createOscillator();i.type="sawtooth";const s=t.createOscillator();s.type="sawtooth";const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=1;const a=t.createGain();return a.gain.value=0,i.connect(n),s.connect(n),n.connect(a).connect(this.output(t)),i.start(),s.start(),{key:e,nodes:[n,a],sources:[i,s],volumeParam:a.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:s.frequency,ratio:1.006},{param:n.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const s=t.createOscillator();s.type="sine",s.frequency.value=5;const n=t.createGain(),a=t.createGain();return a.gain.value=0,s.connect(n).connect(i.frequency),i.connect(a).connect(this.output(t)),i.start(),s.start(),{key:e,nodes:[n,a],sources:[i,s],volumeParam:a.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:n.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=.8;const n=t.createGain();return n.gain.value=0,i.connect(s).connect(n).connect(this.output(t)),i.start(),{key:e,nodes:[s,n],sources:[i],volumeParam:n.gain,gainScale:1.4,pitch:[{param:s.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const s=t.createBiquadFilter();s.type="bandpass",s.Q.value=1.2;const n=t.createGain();n.gain.value=0;const a=t.createBufferSource();a.buffer=this.crackleEnvelope(t),a.loop=!0;const r=t.createGain();return r.gain.value=0,a.connect(r).connect(n.gain),i.connect(s).connect(n).connect(this.output(t)),i.start(),a.start(),{key:e,nodes:[s,n,r],sources:[i,a],volumeParam:r.gain,gainScale:.9,pitch:[{param:s.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const s=this.context;if(!s)return;let n;try{n=await this.getBuffer(t)}catch(o){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",o);return}if(i!==this.voiceToken||!this.context)return;const a=s.createBufferSource();a.buffer=n,a.loop=!0;const r=s.createGain();r.gain.value=0,a.connect(r).connect(this.output(s)),a.start(),this.voice={key:e,nodes:[r],sources:[a],volumeParam:r.gain,gainScale:1,pitch:[]},this.requested&&this.applyTo(this.voice,this.requested)}async getBuffer(t){const e=this.context;if(!e)throw new Error("SightingAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${t}`);return s.arrayBuffer()}).then(s=>e.decodeAudioData(s)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*Gv),t.sampleRate),i=e.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*Gv),t.sampleRate),i=e.getChannelData(0);let s=0,n=0;for(let a=0;a<i.length;a++)s=(s+.02*(Math.random()*2-1))/1.02,i[a]=s,n=Math.max(n,Math.abs(s));if(n>0)for(let a=0;a<i.length;a++)i[a]/=n;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*Vv),t.sampleRate),i=e.getChannelData(0),s=Math.max(1,Math.floor(YE*t.sampleRate)),n=Math.round(Vv*KE);for(let a=0;a<n;a++){const r=Math.floor(Math.random()*i.length),o=.4+Math.random()*.6;for(let l=0;l<s&&r+l<i.length;l++)i[r+l]=Math.max(i[r+l],o*(1-l/s))}this.crackleBuffer=e}return this.crackleBuffer}stopVoice(){const t=this.voice,e=this.context;if(this.voice=void 0,!t||!e)return;const i=e.currentTime;t.volumeParam.cancelScheduledValues(i),t.volumeParam.setTargetAtTime(0,i,Hv/3);const s=i+Hv;for(const n of t.sources){n.onended=()=>{n.disconnect();for(const a of t.nodes)a.disconnect()};try{n.stop(s)}catch{n.disconnect();for(const a of t.nodes)a.disconnect()}}}}class jt{static svg(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor"/></svg>`}static outline(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" stroke-linecap="round"/></svg>`}static solid(t){return`<svg viewBox="0 0 24 24" width="1.5em" height="1.5em" aria-hidden="true" focusable="false"><path d="${t}" fill="currentColor" fill-rule="evenodd"/></svg>`}static BOOKMARK="M6 3.5h12a.5.5 0 0 1 .5.5v16.5L12 16.8l-6.5 3.7V4a.5.5 0 0 1 .5-.5z";static PICTURE="M5 4h14a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z";static PICTURE_HILLS="M4.5 17.5l4.5-6 3 4 2.5-3 5 5z";static PIN="M12 21.5s-6.5-5.7-6.5-10.8a6.5 6.5 0 0 1 13 0c0 5.1-6.5 10.8-6.5 10.8z";static PIN_HOLE="M12 8.4a2.4 2.4 0 1 0 0 4.8 2.4 2.4 0 0 0 0-4.8z";static MILESTONES_OFF=jt.outline(jt.BOOKMARK);static MILESTONES_ON=jt.solid(jt.BOOKMARK);static PICTURES_OFF=jt.outline(`${jt.PICTURE}${jt.PICTURE_HILLS}`);static PICTURES_ON=jt.solid(`${jt.PICTURE}${jt.PICTURE_HILLS}`);static TRACE_LINE="M3 19.5l2.2-2.2 1.4 1.4L4.4 20.9zM8 14.5l2.2-2.2 1.4 1.4-2.2 2.2zM13 9.5l2.2-2.2 1.4 1.4-2.2 2.2z";static TRACE_MARK="M18.5 2.5l3.5 3.5-3.5 3.5-3.5-3.5z";static TRACES_OFF=jt.outline(`${jt.TRACE_LINE}${jt.TRACE_MARK}`);static TRACES_ON=jt.solid(`${jt.TRACE_LINE}${jt.TRACE_MARK}`);static MAP_OFF=jt.outline(`${jt.PIN}${jt.PIN_HOLE}`);static MAP_ON=jt.solid(`${jt.PIN}${jt.PIN_HOLE}`);static SHARE=jt.outline("M14 4l7 7-7 7v-4.2C8.6 13.8 5.4 15.6 3.5 19c.6-5.6 3.4-9.6 10.5-10.8V4z");static VIDEO=jt.outline("M3.5 7h11a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zM15.5 10.5l5-3v9l-5-3z");static FOLDED=jt.svg("M15.4 7.4 14 6l-6 6 6 6 1.4-1.4L10.8 12z");static UNFOLDED=jt.svg("M8.6 16.6 10 18l6-6-6-6-1.4 1.4 4.6 4.6z");static PLAY=jt.svg("M7.4 5v14l11-7z");static PAUSE=jt.svg("M6 5h4v14H6zM14 5h4v14h-4z");static VOLUME=jt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zm12.5 2.5A4 4 0 0 0 12.5 8.5v7A4 4 0 0 0 14.5 12zM12.5 4.2v2.1a6.5 6.5 0 0 1 0 11.4v2.1a8.6 8.6 0 0 0 0-15.6z");static MUTED=jt.svg("M2 9.5v5h3.5l4.5 4.5V5L5.5 9.5H2zM15 9.8l1.4-1.4 2.6 2.6 2.6-2.6 1.4 1.4-2.6 2.6 2.6 2.6-1.4 1.4-2.6-2.6-2.6 2.6-1.4-1.4 2.6-2.6z");static ENTER_FULLSCREEN=jt.svg("M5 5h5v2H7v3H5V5zm9 0h5v5h-2V7h-3V5zM5 14h2v3h3v2H5v-5zm12 0h2v5h-5v-2h3v-3z");static EXIT_FULLSCREEN=jt.svg("M8 5h2v5H5V8h3V5zm6 0h2v3h3v2h-5V5zM5 14h5v5H8v-3H5v-2zm9 0h5v2h-3v3h-2v-5z")}class Yn{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,s){if(!Yn.isObject(t)){s.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:Yn.typeOf(t)});return}for(const[n,a]of Object.entries(t)){const r=i?`${i}.${n}`:n,o=e[n];o?this.field(a,o,r,s):s.push({kind:"unknown-key",path:r})}}field(t,e,i,s){if(Yn.isStated(t)){this.field(t.value,e,i,s);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&s.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(n=>`"${n}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,s):Yn.isObject(t)||s.push({kind:"wrong-type",path:i,expected:"object",found:Yn.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((n,a)=>{const r=Yn.isStated(n)?n.value:n;this.object(r,e.fields,`${i}.${a}`,s)}):s.push({kind:"wrong-type",path:i,expected:"array",found:Yn.typeOf(t)});return;default:typeof t!==e.type?s.push({kind:"wrong-type",path:i,expected:e.type,found:Yn.typeOf(t)}):typeof t=="number"&&(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&s.push({kind:"out-of-range",path:i,expected:`${e.minimum??"−∞"}–${e.maximum??"∞"}`,found:String(t)})}}static STATED_KEYS=new Set(["value","basis","rationale","how","range","source"]);static isObject(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}static isStated(t){return Yn.isObject(t)&&"value"in t&&Object.keys(t).every(e=>Yn.STATED_KEYS.has(e))}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class Xs{static PIXELS_PER_INSTANT=2;static INSTANTS_PER_FLASH=2;static MAX_INSTANTS=512;static windowEndingAt(t,e){const i=Number.isFinite(e)?Math.max(0,e):0,s=Math.max(0,t-i*1e3),n=Math.max(0,t-s);return{fromMs:s,toMs:t,ms:n,seconds:n/1e3}}static instants(t,e,i,s,n){if(!(s>0))return 1;const a=n>0?Xs.travelDegOver(t,e,i,i+s*1e3)/n/Xs.PIXELS_PER_INSTANT:0,r=Xs.flashesOver(t,s)*Xs.INSTANTS_PER_FLASH,o=Math.ceil(Math.max(a,r));return o<2?1:Math.min(Xs.MAX_INSTANTS,o)}static travelDegOver(t,e,i,s){let n=0;for(const a of t){if(!a.track||a.track.length<2)continue;const r=Xs.directionAt(a,e,i),o=Xs.directionAt(a,e,s),l=Math.min(1,Math.max(-1,r.x*o.x+r.y*o.y+r.z*o.z));n=Math.max(n,Math.acos(l)*180/Math.PI)}return n}static flashesOver(t,e){let i=0;for(const s of t)for(const n of s.lights??[])n.pattern.kind==="flash"&&(i=Math.max(i,n.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const s=ga(t,i),n=s.eastM,a=s.altitudeM-e,r=s.northM,o=Math.hypot(n,a,r);return o===0?{x:0,y:1,z:0}:{x:n/o,y:a/o,z:r/o}}static bodyInstants(t,e,i,s,n){if(!(s>i)||!(n>0))return 1;let a=0;for(const o of t){const l=Xs.bodyAt(o,i),h=Xs.bodyAt(o,s);if(!l||!h)continue;const u={x:l.eastM,y:l.upM-e,z:l.northM},d={x:h.eastM,y:h.upM-e,z:h.northM},f=Math.hypot(u.x,u.y,u.z),p=Math.hypot(d.x,d.y,d.z);if(f===0||p===0)continue;const g=Math.min(1,Math.max(-1,(u.x*d.x+u.y*d.y+u.z*d.z)/f/p));let m=Math.acos(g)*180/Math.PI,v=0;for(const M of Object.keys(h.motions))v=Math.max(v,Math.abs(h.motions[M]-(l.motions[M]??h.motions[M])));v>0&&(m+=v*2*(h.halfWidthM/Math.max(p,.001))*180/Math.PI),a=Math.max(a,m)}const r=Math.ceil(a/n/Xs.PIXELS_PER_INSTANT);return r<2?1:Math.min(Xs.MAX_INSTANTS,r)}static bodyAt(t,e){const i=t.track;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let s=0,n=i.length-1;for(;n-s>1;){const d=s+n>>1;i[d].t<=e?s=d:n=d}const a=i[s],r=i[n];if(a.eastM===void 0||a.northM===void 0||r.eastM===void 0||r.northM===void 0)return;const o=r.t>a.t?(e-a.t)/(r.t-a.t):0,l=(d,f)=>d+(f-d)*o,h={};for(const d of Object.keys(r.motions??{})){const f=a.motions?.[d],p=r.motions[d];h[d]=f===void 0?p:l(f,p)}const u=i.find(d=>d.sizeM)?.sizeM?.widthM??1;return{eastM:l(a.eastM,r.eastM),northM:l(a.northM,r.northM),upM:l(a.altitudeM??0,r.altitudeM??0),halfWidthM:u/2,motions:h}}}const Qx=Math.PI/180,$E=180/Math.PI,qE=256,tw=19,ZE=1.25;function ew(c,t){return 156543.03392*Math.cos(c*Qx)/2**t}function iw(c,t){return ew(c,t)*qE}function JE(c,t){let e=0;for(;e<tw&&iw(c,e+1)>=t;)e++;return e}function v1(c,t){return iw(c,t)}function sw(c,t){const e=t*ZE;let i=0;for(;i<tw&&ew(c,i)>e;)i++;return i}function Qd(c){const t=c*Qx;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function nw(c,t,e){const i=2**e;return{x:(c+180)/360*i,y:Qd(t)*i}}function aw(c,t,e){const i=Qd(c.north),s=Qd(c.south);return{x:(t-c.west)/(c.east-c.west),y:(Qd(e)-i)/(s-i)}}function jE(c,t,e){const{x:i,y:s}=nw(c,t,e);return{x:Math.floor(i),y:Math.floor(s),z:e}}function QE(c){const t=2**c.z,e=c.x/t*360-180,i=(c.x+1)/t*360-180,s=Xv(c.y,t);return{south:Xv(c.y+1,t),north:s,west:e,east:i}}function Xv(c,t){const e=c/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*$E}function rw(c,t,e,i){const s=jE(c,t,e),n=Math.floor(i/2),a=[];for(let l=-n;l<=n;l++)for(let h=-n;h<=n;h++)a.push({x:s.x+h,y:s.y+l,z:e});const r=a.map(QE),o={south:Math.min(...r.map(l=>l.south)),north:Math.max(...r.map(l=>l.north)),west:Math.min(...r.map(l=>l.west)),east:Math.max(...r.map(l=>l.east))};return{tiles:a,bounds:o}}const tA="#2ec4ff";class Uo{constructor(t){this.ctx=t}static SCALE_STEPS_M=[5e3,2e3,1e3,500,200,100,50,20,10,5];static MARKER_RADIUS_PX=8.5;static ON_MARKER_M=3;targets=[];hitTest(t,e){let i,s=1/0;for(const n of this.targets){const a=Math.hypot(n.x-t,n.y-e);a>n.radius||a>s||(i=n,s=a)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(t){const{ctx:e}=this;e.save(),this.targets=[],e.clearRect(0,0,this.width,this.height),this.paintGround(t),this.paintNight(t.nightFraction),this.paintPath(t),this.paintTraces(t),t.position?(this.paintCone(t,t.position),this.paintDecor(t),this.paintMarkers(t),this.paintObserver(t,t.position)):(this.paintDecor(t),this.paintMarkers(t)),this.paintNorth(),this.paintFooter(t.bounds,t.attribution),e.restore()}toCanvas(t,e,i){const s=aw(t,i,e);return{x:s.x*this.width,y:s.y*this.height}}paintGround(t){const{ctx:e}=this;e.fillStyle="#1d2321",e.fillRect(0,0,this.width,this.height);const i=t.imagery;if(!i)return;const s=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),n=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,s.x,s.y,n.x-s.x,n.y-s.y)}paintNight(t=0){if(t<=0)return;const{ctx:e}=this;e.save(),e.fillStyle=`rgba(6, 12, 30, ${Math.min(t,1)*.78})`,e.fillRect(0,0,this.width,this.height),e.restore()}paintDecor(t){const{ctx:e}=this;for(const i of t.decor){const s=this.toCanvas(t.bounds,i.lat,i.lng);if(i.label&&this.targets.push({kind:"decor",label:i.label,lat:i.lat,lng:i.lng,x:s.x,y:s.y,radius:7}),e.beginPath(),e.rect(s.x-3.5,s.y-3.5,7,7),e.fillStyle="rgba(120, 220, 255, 0.85)",e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.7)",e.stroke(),i.headingDeg===void 0)continue;const n=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(s.x,s.y),e.lineTo(s.x+Math.cos(n)*10,s.y+Math.sin(n)*10),e.lineWidth=3,e.strokeStyle="rgba(0, 0, 0, 0.6)",e.stroke(),e.lineWidth=1.5,e.strokeStyle="rgba(120, 220, 255, 0.9)",e.stroke()}}paintPath(t){if(!t.path.moved)return;const{ctx:e}=this,i=t.path.points.map(s=>this.toCanvas(t.bounds,s.lat,s.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const s of i.slice(1))e.lineTo(s.x,s.y);e.lineJoin="round",e.lineCap="round",e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=5,e.stroke(),e.strokeStyle="rgba(255, 255, 255, 0.9)",e.lineWidth=2,e.stroke()}paintTraces(t){const{ctx:e}=this;for(const i of t.traces??[]){const s=i.points.map(a=>this.toCanvas(t.bounds,a.lat,a.lng));if(s.length===0)continue;const n=i.color??tA;if(i.kind==="point")e.beginPath(),e.moveTo(s[0].x,s[0].y-6),e.lineTo(s[0].x+6,s[0].y),e.lineTo(s[0].x,s[0].y+6),e.lineTo(s[0].x-6,s[0].y),e.closePath(),e.fillStyle=n,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(s[0].x,s[0].y);for(const a of s.slice(1))e.lineTo(a.x,a.y);i.kind==="polygon"&&e.closePath(),e.lineJoin="round",e.setLineDash([]),e.strokeStyle="rgba(0, 0, 0, 0.65)",e.lineWidth=4.5,e.stroke(),e.setLineDash([9,5]),e.strokeStyle=n,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let a=s[0];if(i.kind==="line"&&t.position){const r=this.toCanvas(t.bounds,t.position.lat,t.position.lng);a=s.reduce((o,l)=>Math.hypot(l.x-r.x,l.y-r.y)>Math.hypot(o.x-r.x,o.y-r.y)?l:o)}this.paintOutlinedText(i.label,a.x+9,a.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:s}=t;if(i===void 0||s===void 0)return;const{ctx:n}=this,a=this.toCanvas(t.bounds,e.lat,e.lng),r=Math.hypot(this.width,this.height),o=(i-90)*Math.PI/180,l=s*Math.PI/180;n.save(),n.beginPath(),n.moveTo(a.x,a.y),n.arc(a.x,a.y,r,o-l,o+l),n.closePath();const h=n.createRadialGradient(a.x,a.y,0,a.x,a.y,r);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(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((s,n)=>Number(s.current)-Number(n.current))){const s=this.toCanvas(t.bounds,i.lat,i.lng);this.targets.push({kind:"milestone",label:i.note?`${i.label} — ${i.note}`:i.label,lat:i.lat,lng:i.lng,t:i.t,x:s.x,y:s.y,radius:Uo.MARKER_RADIUS_PX}),e.beginPath(),e.arc(s.x,s.y,Uo.MARKER_RADIUS_PX,0,Math.PI*2),e.fillStyle=i.current?"rgba(255, 224, 130, 0.95)":"rgba(0, 0, 0, 0.55)",e.fill(),e.lineWidth=2,e.strokeStyle="rgba(255, 255, 255, 0.9)",e.stroke(),e.fillStyle=i.current?"#1d2321":"#fff",e.fillText(i.label,s.x,s.y)}}paintObserver(t,e){const{ctx:i}=this,s=this.toCanvas(t.bounds,e.lat,e.lng);t.observerLabel&&this.targets.push({kind:"observer",label:t.observerLabel,lat:e.lat,lng:e.lng,x:s.x,y:s.y,radius:8});const n=t.markers.some(a=>{if(!a.current)return!1;const r=re(a.lat,a.lng,e.lat,e.lng);return Math.hypot(r.x,r.z)<=Uo.ON_MARKER_M});i.beginPath(),i.arc(s.x,s.y,n?Uo.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:t}=this,e=this.width-14,i=16;t.beginPath(),t.moveTo(e,i-9),t.lineTo(e-4.5,i+5),t.lineTo(e,i+2),t.lineTo(e+4.5,i+5),t.closePath(),t.fillStyle="rgba(255, 255, 255, 0.92)",t.strokeStyle="rgba(0, 0, 0, 0.6)",t.lineWidth=1,t.fill(),t.stroke(),t.font="bold 9px sans-serif",t.textAlign="center",t.textBaseline="top",t.strokeText("N",e,i+6),t.fillText("N",e,i+6)}paintFooter(t,e){const{ctx:i}=this;i.font="9px sans-serif",i.textBaseline="bottom";const s=e?this.wrap(e,this.width-20):[];let n=this.height-4;i.textAlign="right";for(const f of s.slice().reverse())this.paintOutlinedText(f,this.width-6,n),n-=11;const a=(t.south+t.north)/2,o=Math.abs(re(a,t.east,a,t.west).x)/this.width,l=Uo.SCALE_STEPS_M.find(f=>f/o<=this.width/3);if(l===void 0)return;const h=l/o,u=8,d=n-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:s}=this;s.lineWidth=3,s.strokeStyle="rgba(0, 0, 0, 0.75)",s.strokeText(t,e,i),s.fillStyle="#fff",s.fillText(t,e,i)}wrap(t,e){const i=[];let s="";for(const n of t.split(" ")){const a=s?`${s} ${n}`:n;s&&this.ctx.measureText(a).width>e?(i.push(s),s=n):s=a}return s&&i.push(s),i}}class li{static MIN_ZOOM=.25;static MAX_ZOOM=64;static MIN_SPAN_M=400;static MARGIN=.6;static IMAGERY_PX=768;static fitted(t,e){return li.including(t.boundsAround(li.MIN_SPAN_M,li.MARGIN),e)}zoom=1;centerX=.5;centerY=.5;get changed(){return this.zoom!==1||this.centerX!==.5||this.centerY!==.5}get zoomFactor(){return this.zoom}reset(){this.zoom=1,this.centerX=.5,this.centerY=.5}zoomAt(t,e,i){const s=Math.min(li.MAX_ZOOM,Math.max(li.MIN_ZOOM,this.zoom*i)),n=this.centerX+(t-.5)/this.zoom,a=this.centerY+(e-.5)/this.zoom;this.centerX=n-(t-.5)/s,this.centerY=a-(e-.5)/s,this.zoom=s}panBy(t,e){this.centerX-=t/this.zoom,this.centerY-=e/this.zoom}refit(t,e){if(!this.changed)return;const i=this.boundsWithin(t),s=li.mercatorY01(e.north),n=li.mercatorY01(e.south),a=li.mercatorY01(i.north),r=li.mercatorY01(i.south);this.zoom=(e.east-e.west)/(i.east-i.west),this.centerX=((i.west+i.east)/2-e.west)/(e.east-e.west),this.centerY=((a+r)/2-s)/(n-s)}keepInView(t,e,i){if(!this.changed)return!1;const s=this.boundsWithin(t),n=li.mercatorY01(s.north),a=li.mercatorY01(s.south),r=(e.lng-s.west)/(s.east-s.west),o=(li.mercatorY01(e.lat)-n)/(a-n);return r>=i&&r<=1-i&&o>=i&&o<=1-i?!1:(this.panBy(.5-r,.5-o),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=li.mercatorY01(t.north),s=li.mercatorY01(t.south),n=t.east-t.west;return{west:t.west+(this.centerX-e)*n,east:t.west+(this.centerX+e)*n,north:li.latitudeAt(i+(this.centerY-e)*(s-i)),south:li.latitudeAt(i+(this.centerY+e)*(s-i))}}static including(t,e,i=3){const s=(t.north+t.south)/2,n=(t.east+t.west)/2,a=re(s,t.east,s,n).x;let r=a;for(const o of e){const{x:l,z:h}=re(o.lat,o.lng,s,n),u=Math.max(Math.abs(l),Math.abs(h));u<=a*i&&(r=Math.max(r,u*1.15))}return r<=a?t:{north:Nn(0,-r,s,n).lat,south:Nn(0,r,s,n).lat,east:Nn(r,0,s,n).lng,west:Nn(-r,0,s,n).lng}}static expand(t,e){const i=t.east-t.west,s=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-s*e,north:t.north+s*e}}static pointAt(t,e,i){const s=li.mercatorY01(t.north),n=li.mercatorY01(t.south);return{lat:li.latitudeAt(s+i*(n-s)),lng:t.west+e*(t.east-t.west)}}static mercatorY01(t){const e=t*Math.PI/180;return(1-Math.log(Math.tan(e)+1/Math.cos(e))/Math.PI)/2}static latitudeAt(t){return Math.atan(Math.sinh(Math.PI*(1-2*t)))*180/Math.PI}}const Gn=256,eA=3,iA=129,sA=7,nA=32768;class ow{fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"}async getElevationGrid(t,e){const i=(t.south+t.north)/2,s=(t.west+t.east)/2,n=Math.abs(re(i,t.east,i,t.west).x),a=Math.abs(re(t.north,s,t.south,s).z),r=Math.max(n,a);let o=JE(i,r),l=eA;if(e.width>=iA){const g=v=>2*Math.ceil((r/v1(i,v)+1)/2)+1;let m=sw(i,r/(e.width-1)/2);for(;m>o&&g(m)>sA;)m--;m>o&&(o=m,l=g(m))}const{tiles:h}=rw(s,i,o,l),u=l*Gn,d=new Float32Array(u*u),f=h[0];await Promise.all(h.map(g=>this.decodeTileInto(g,f,d,u)));const p=new Float32Array(e.width*e.height);for(let g=0;g<e.height;g++){const m=t.north+(t.south-t.north)*(g/(e.height-1));for(let v=0;v<e.width;v++){const M=t.west+(t.east-t.west)*(v/(e.width-1));p[g*e.width+v]=this.sampleAt(m,M,o,f,d,u)}}return{heights:p,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,s){const n=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),a=await this.fetchImpl(n);if(!a.ok)throw new Error(`Elevation tile fetch failed (${a.status}): ${n}`);const r=await createImageBitmap(await a.blob()),o=document.createElement("canvas");o.width=Gn,o.height=Gn;const l=o.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(r,0,0);const{data:h}=l.getImageData(0,0,Gn,Gn),u=(t.x-e.x)*Gn,d=(t.y-e.y)*Gn;for(let f=0;f<Gn;f++)for(let p=0;p<Gn;p++){const g=(f*Gn+p)*4,m=h[g]*256+h[g+1]+h[g+2]/256-nA,v=u+p,M=d+f;i[M*s+v]=m}}sampleAt(t,e,i,s,n,a){const{x:r,y:o}=nw(e,t,i),l=(r-s.x)*Gn,h=(o-s.y)*Gn,u=Math.max(0,Math.min(a-1,Math.floor(l))),d=Math.max(0,Math.min(a-1,Math.floor(h))),f=Math.min(a-1,u+1),p=Math.min(a-1,d+1),g=l-u,m=h-d,v=n[d*a+u],M=n[d*a+f],x=n[p*a+u],y=n[p*a+f],w=v+(M-v)*g,S=x+(y-x)*g;return w+(S-w)*m}}class h0{constructor(t,e,i,s){this.width=t,this.height=e,this.samples=i,this.values=s}at(t,e,i=0){return this.values[(e*this.width+t)*this.samples+i]}static parse(t){const e=new DataView(t);if(t.byteLength<8||e.getUint16(0)!==18761||e.getUint16(2,!0)!==42)throw new Error("Not a little-endian TIFF");const i=e.getUint32(4,!0),s=e.getUint16(i,!0),n=new Map;for(let v=0;v<s;v++){const M=i+2+v*12;n.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const a=(v,M)=>{const x=n.get(v);if(x===void 0){if(M===void 0)throw new Error(`TIFF without tag ${v}`);return M}return x.type===3?x.value&65535:x.value},r=v=>{const M=n.get(v);if(M===void 0)throw new Error(`TIFF without tag ${v}`);const x=M.type===3?2:4,y=[];if(M.count*x<=4){const w=new DataView(new ArrayBuffer(4));w.setUint32(0,M.value,!0);for(let S=0;S<M.count;S++)y.push(x===2?w.getUint16(S*2,!0):w.getUint32(0,!0))}else for(let w=0;w<M.count;w++)y.push(x===2?e.getUint16(M.value+w*2,!0):e.getUint32(M.value+w*4,!0));return y};if(a(259,1)!==1)throw new Error("Compressed TIFF");if(n.has(322))throw new Error("Tiled TIFF");const o=a(256),l=a(257),h=a(277,1),u=r(258)[0],d=a(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=r(273),p=r(279),g=new Uint8Array(o*l*h*(u/8));let m=0;for(let v=0;v<f.length&&m<g.length;v++){const M=Math.min(p[v],g.length-m);g.set(new Uint8Array(t,f[v],M),m),m+=M}if(m<g.length)throw new Error("Truncated TIFF");return new h0(o,l,h,d?new Float32Array(g.buffer):g)}}class Br extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class aA{constructor(t,e,i,s,n){this.heights=t,this.plants=e,this.buildings=i,this.size=s,this.metresPerPixel=n}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),s=Math.floor(this.size/2-e/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(t,e,i){let s;const n=Math.ceil(i/this.metresPerPixel);for(let a=-n;a<=n;a++)for(let r=-n;r<=n;r++){if(Math.hypot(r,a)*this.metresPerPixel>i)continue;const o=this.structureAt(t+r*this.metresPerPixel,e+a*this.metresPerPixel);o!==void 0&&(s===void 0||o>s)&&(s=o)}return s}}class _t{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(t,e){const[i,s]=t;return{east:(i-e.lng)*_t.METRES_PER_DEGREE*Math.cos(e.lat*Math.PI/180),north:(s-e.lat)*_t.METRES_PER_DEGREE}}static path(t,e){return t.geometry.type!=="LineString"?[]:t.geometry.coordinates.map(i=>_t.toMetres(i,e))}static bearing(t,e){return(Math.atan2(e.east-t.east,e.north-t.north)*180/Math.PI+360)%360}static distanceToSegment(t,e,i){const s=i.east-e.east,n=i.north-e.north,a=s*s+n*n,r=a===0?0:Math.max(0,Math.min(1,((t.east-e.east)*s+(t.north-e.north)*n)/a));return Math.hypot(t.east-(e.east+r*s),t.north-(e.north+r*n))}static bridges(t,e,i,s){const n=t.elevatedRoads.map(o=>({path:_t.path(o,e),properties:o.properties})),a=(t.elevatedRailways??[]).map(o=>_t.path(o,e)),r=[];for(const o of _t.joined(t.bridges.map(l=>_t.path(l,e)))){const l=o[0],h=o[o.length-1],u=Math.hypot(h.east-l.east,h.north-l.north);if(u<_t.MIN_BRIDGE_M)continue;const d={east:(l.east+h.east)/2,north:(l.north+h.north)/2};if(Math.hypot(d.east,d.north)>i+u/2||_t.carriesRailway(l,h,a))continue;const[f,p]=_t.deckReach(l,h,s);r.push({eastM:_t.tenth((f.east+p.east)/2),northM:_t.tenth((f.north+p.north)/2),lengthM:_t.tenth(Math.hypot(p.east-f.east,p.north-f.north)),widthM:_t.roadOf(d,n).width,heightM:_t.tenth(_t.deckHeight(l,h,s)),headingDeg:_t.tenth(_t.bearing(l,h)%180),..._t.roadOf(d,n).name?{name:_t.roadOf(d,n).name}:{}})}return r.sort((o,l)=>Math.hypot(o.eastM,o.northM)-Math.hypot(l.eastM,l.northM)),r}static carriesRailway(t,e,i){const s={east:(t.east+e.east)/2,north:(t.north+e.north)/2},n=_t.bearing(t,e)%180;for(const a of i)for(let r=0;r+1<a.length;r++){if(_t.distanceToSegment(s,a[r],a[r+1])>_t.RAIL_MATCH_M)continue;const o=Math.abs(_t.bearing(a[r],a[r+1])%180-n);if(Math.min(o,180-o)<=_t.JOIN_DEG)return!0}return!1}static joined(t){const e=t.filter(i=>i.length>=2);for(let i=0;i<e.length;i++)for(let s=i+1;s<e.length;s++){const n=_t.join(e[i],e[s]);n!==void 0&&(e[i]=n,e.splice(s,1),s=i)}return e}static join(t,e){for(const i of[t,[...t].reverse()])for(const s of[e,[...e].reverse()]){const n=i[i.length-1],a=s[0];if(Math.hypot(n.east-a.east,n.north-a.north)>_t.JOIN_M)continue;const r=Math.abs(_t.bearing(i[0],n)-_t.bearing(a,s[s.length-1]));if(Math.min(r,360-r)<=_t.JOIN_DEG)return[...i,...s.slice(1)]}}static roadOf(t,e){let i;for(const r of e)for(let o=0;o+1<r.path.length;o++){const l=_t.distanceToSegment(t,r.path[o],r.path[o+1]);(i===void 0||l<i.distance)&&(i={distance:l,properties:r.properties})}if(i===void 0||i.distance>_t.ROAD_MATCH_M)return{width:_t.DEFAULT_DECK_M};const s=[i.properties.nom_voie_ban_gauche,i.properties.nom_voie_ban_droite,i.properties.cpx_toponyme_route_nommee].find(r=>typeof r=="string"&&r.length>0),n=Number(i.properties.largeur_de_chaussee),a=Number.isFinite(n)&&n>0?_t.tenth(n+_t.DECK_MARGIN_M):i.properties.nature==="Sentier"?_t.FOOTBRIDGE_DECK_M:_t.DEFAULT_DECK_M;return s?{width:a,name:s}:{width:a}}static deckReach(t,e,i){const s=Math.hypot(e.east-t.east,e.north-t.north);if(i===void 0||s===0)return[t,e];const n={east:(t.east+e.east)/2,north:(t.north+e.north)/2},a={east:(e.east-t.east)/s,north:(e.north-t.north)/s},r=d=>(i.structureAt(n.east+a.east*d,n.north+a.north*d)??0)>=_t.DECK_SEEN_M,o=d=>i.structureAt(n.east+a.east*d,n.north+a.north*d)??0,l=d=>{let f;for(let g=0;g<=s/2+_t.DECK_REACH_M;g+=_t.DECK_STEP_M)if(r(d*g))f=g;else if(f!==void 0&&g-f>_t.DECK_GAP_M)break;if(f===void 0)return s/2;let p=f;for(;p-f<_t.DECK_REACH_M&&o(d*(p+_t.DECK_STEP_M))>=_t.DECK_MEETS_M;)p+=_t.DECK_STEP_M;return Math.max(s/2,p+_t.DECK_BEARING_M)},h=l(-1),u=l(1);return[{east:n.east-a.east*h,north:n.north-a.north*h},{east:n.east+a.east*u,north:n.north+a.north*u}]}static deckHeight(t,e,i){if(i===void 0)return _t.DEFAULT_DECK_HEIGHT_M;const s=[],n=20;for(let a=4;a<=n-4;a++){const r=i.structureAt(t.east+(e.east-t.east)*a/n,t.north+(e.north-t.north)*a/n);r!==void 0&&r>=1.5&&s.push(r)}return s.length===0?_t.DEFAULT_DECK_HEIGHT_M:(s.sort((a,r)=>a-r),s[Math.floor(s.length/2)])}static lines(t,e,i,s){const n=[];for(const a of t.lines){const r=String(a.properties.voltage??""),o=_t.kilovolts(r);if(o===void 0)continue;const l=_t.BY_VOLTAGE.find(u=>o<=u.upToKv)??_t.BY_VOLTAGE[_t.BY_VOLTAGE.length-1],h=_t.path(a,e);for(let u=0;u+1<h.length;u++){const d=h[u],f=h[u+1],p=Math.hypot(f.east-d.east,f.north-d.north);if(p<5||p>_t.MAX_SPAN_M||_t.distanceToSegment({east:0,north:0},d,f)>i)continue;const g=_t.poleHeight(d,f,s)??l.poleM;n.push({eastM:_t.tenth((d.east+f.east)/2),northM:_t.tenth((d.north+f.north)/2),lengthM:_t.tenth(p),headingDeg:_t.tenth(_t.bearing(d,f)),heightM:_t.tenth(Math.max(4,g-l.dropM)),poleHeightM:_t.tenth(g),acrossM:[-l.spreadM,0,l.spreadM],voltage:r})}}return n.sort((a,r)=>Math.hypot(a.eastM,a.northM)-Math.hypot(r.eastM,r.northM)),n.slice(0,_t.MAX_LINES)}static kilovolts(t){const e=/([\d.,]+)\s*kV/i.exec(t);if(e===null)return;const i=Number(e[1].replace(",","."));return Number.isFinite(i)&&i>0?i:void 0}static poleHeight(t,e,i){if(i===void 0)return;const s=[t,e].map(n=>i.tallestStructureNear(n.east,n.north,3)).filter(n=>n!==void 0&&n>=_t.MIN_POLE_M&&n<=_t.MAX_POLE_M);return s.length===0?void 0:s.reduce((n,a)=>n+a,0)/s.length}static tenth(t){return Math.round(t*10)/10}}class Le{static covers(t,e){return t>=41.2&&t<=51.3&&e>=-5.4&&e<=9.8}static WMS="https://data.geopf.fr/wms-r/wms";static WFS="https://data.geopf.fr/wfs/ows";static HEIGHT_LAYER="IGNF_LIDAR-HD_MNH_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static PHOTO_LAYER="ORTHOIMAGERY.ORTHOPHOTOS";static MAX_PHOTO_PIXELS=1e3;static METRES_PER_PIXEL=.5;static MAX_RADIUS_M=3e3;static MAX_LIDAR_RADIUS_M=150;static NO_DATA=-9999;static METRES_PER_DEGREE=111320;fetchImpl;wms;wfs;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??Le.WMS,this.wfs=t.wfsEndpoint??Le.WFS}static radius(t){return Math.min(t,Le.MAX_RADIUS_M)}static lidarRadius(t){return Math.min(t,Le.MAX_LIDAR_RADIUS_M)}async lidar(t,e){const i=Le.lidarRadius(e),s=Math.ceil(2*i/Le.METRES_PER_PIXEL),[n,a]=await Promise.all([this.raster(t,i,s,Le.HEIGHT_LAYER),this.raster(t,i,s,Le.CLASS_LAYER)]);if(n.samples!==1||a.samples<3)throw new Br("unreachable","The survey answered in a layout this does not read");const r=n.values;if(r.every(u=>u===Le.NO_DATA))throw new Br("no-coverage","No LiDAR HD survey here yet");const o=new Uint8Array(s*s),l=new Uint8Array(s*s);for(let u=0;u<s*s;u++){const d=a.values[u*a.samples],f=a.values[u*a.samples+1],p=a.values[u*a.samples+2];o[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/s;return{size:s,metresPerPixel:h,heights:r,vegetation:o,building:l,structures:new aA(r,o,l,s,h)}}async laserDate(t){return Le.latest(await this.dated("IGNF_LIDAR-HD_METADONNEE:metadata","geom","date_fin_acquisition",t))}async photoDate(t){return Le.latest(await this.dated("ORTHOIMAGERY.ORTHOPHOTOS.GRAPHE-MOSAIQUAGE:graphe_bdortho","geom","date_vol",t))}static latest(t){return t.map(i=>/^\d{4}-\d{2}-\d{2}/.exec(String(i??""))?.[0]).filter(i=>i!==void 0).sort().at(-1)}async dated(t,e,i,s){const a=[s.lng-1e-4,s.lat-1e-4,s.lng+1e-4,s.lat+1e-4].map(r=>r.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${a},'EPSG:4326')`,i,20)).map(r=>r.properties[i])}catch{return[]}}async photo(t,e){const i=Le.radius(e),s=Math.min(Le.MAX_PHOTO_PIXELS,Math.ceil(2*i/Le.METRES_PER_PIXEL)),n=await this.raster(t,i,s,Le.PHOTO_LAYER);if(n.samples<3)throw new Br("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(t,e,i){const s=Le.radius(e),n=s/Le.METRES_PER_DEGREE,a=s/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),o=`BBOX(geometrie,${[t.lng-a,t.lat-n,t.lng+a,t.lat+n].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=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,Le.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",o,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),g=i?await this.wholeWorship(p,f,[t.lng-a,t.lat-n,t.lng+a,t.lat+n]):[],m=[...f,...g];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:m,zones:p,mapDate:Le.latest(m.map(v=>v.properties.date_modification))}}static BUILDING_PROPERTIES="cleabs,nature,usage_1,hauteur,nombre_d_etages,materiaux_des_murs,materiaux_de_la_toiture,date_d_apparition,date_modification,geometrie";static MAX_WHOLE_M=300;async wholeWorship(t,e,i){const[s,n,a,r]=i,o=Le.MAX_WHOLE_M/Le.METRES_PER_DEGREE;let l;for(const u of t){if(u.properties.categorie!=="Religieux")continue;const[d,f,p,g]=Le.extent(u);if(d>=s&&f>=n&&p<=a&&g<=r)continue;const m=[Math.max(d,s-o),Math.max(f,n-o),Math.min(p,a+o),Math.min(g,r+o)];l=l?[Math.min(l[0],m[0]),Math.min(l[1],m[1]),Math.max(l[2],m[2]),Math.max(l[3],m[3])]:m}if(!l)return[];const h=new Set(e.map(u=>u.properties.cleabs));try{return(await this.features("batiment",`BBOX(geometrie,${l.map(d=>d.toFixed(6)).join(",")},'EPSG:4326')`,Le.BUILDING_PROPERTIES,1e3)).filter(d=>!h.has(d.properties.cleabs))}catch{return[]}}static extent(t){let e=1/0,i=1/0,s=-1/0,n=-1/0;const a=r=>{Array.isArray(r)&&typeof r[0]=="number"?(e=Math.min(e,r[0]),s=Math.max(s,r[0]),i=Math.min(i,r[1]),n=Math.max(n,r[1])):Array.isArray(r)&&r.forEach(a)};return a(t.geometry.coordinates),[e,i,s,n]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(n=>n.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),s=[];for(const n of i){const{type:a,coordinates:r}=n.geometry,o=a==="LineString"?[r]:a==="MultiLineString"?r:[];for(const l of o)s.push(l.map(h=>({lat:h[1],lng:h[0]})))}return s}async waterSurfaces(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("surface_hydrographique",`${e} AND position_par_rapport_au_sol='0' AND persistance='Permanent'`,"cleabs,nature,geometrie",500)}async roads(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_route",`${e} AND nature<>'Sentier' AND nature<>'Escalier' AND position_par_rapport_au_sol>='0'`,"cleabs,nature,largeur_de_chaussee,nombre_de_voies,sens_de_circulation,vitesse_moyenne_vl,urbain,nom_voie_ban_gauche,nom_voie_ban_droite,cpx_toponyme_route_nommee,geometrie",3e3)}async railways(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(i=>i.toFixed(6)).join(",")},'EPSG:4326')`;return this.features("troncon_de_voie_ferree",`${e} AND etat_de_l_objet='En service'`,"cleabs,nature,electrifie,largeur,nombre_de_voies,position_par_rapport_au_sol,cpx_toponyme,geometrie",3e3)}async raster(t,e,i,s){const n=e/Le.METRES_PER_DEGREE,a=e/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),r=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:s,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-n,t.lng-a,t.lat+n,t.lng+a].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let o;try{o=await this.fetchImpl(`${this.wms}?${r}`)}catch(l){throw new Br("unreachable",l instanceof Error?l.message:String(l))}if(!o.ok)throw new Br("unreachable",`The survey answered ${o.status}`);try{return h0.parse(await o.arrayBuffer())}catch(l){throw new Br("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,s=200){const n=new URLSearchParams({SERVICE:"WFS",VERSION:"2.0.0",REQUEST:"GetFeature",TYPENAMES:t.includes(":")?t:`BDTOPO_V3:${t}`,SRSNAME:"EPSG:4326",OUTPUTFORMAT:"application/json",COUNT:String(s),CQL_FILTER:e,PROPERTYNAME:i});let a;try{a=await this.fetchImpl(`${this.wfs}?${n}`)}catch(o){throw new Br("unreachable",o instanceof Error?o.message:String(o))}if(!a.ok)throw new Br("unreachable",`The map answered ${a.status}`);return(await a.json()).features??[]}}class Qr{static NEAR_M=15;static ALIGNED_DEG=30;static LONG_ENOUGH_M=15;static SAMPLE_M=5;static follows(t,e){if(t.length<2||e.length<2)return!1;const i=e[0],s=e.map(r=>re(r.lat,r.lng,i.lat,i.lng)),n=t.map(r=>re(r.lat,r.lng,i.lat,i.lng));let a=0;for(let r=0;r<n.length-1;r++){const o=n[r],l=n[r+1],h=Math.hypot(l.x-o.x,l.z-o.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/Qr.SAMPLE_M)),d=Math.atan2(l.x-o.x,-(l.z-o.z));for(let f=0;f<=u;f++){const p=f/u,g=Qr.nearest(s,o.x+(l.x-o.x)*p,o.z+(l.z-o.z)*p);g.distanceM>Qr.NEAR_M||Qr.angleBetween(d,g.heading)<=Qr.ALIGNED_DEG&&(a+=h/u)}}return a>=Qr.LONG_ENOUGH_M}static nearest(t,e,i){let s={distanceM:1/0,heading:0};for(let n=0;n<t.length-1;n++){const a=t[n],r=t[n+1],o=r.x-a.x,l=r.z-a.z,h=o*o+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-a.x)*o+(i-a.z)*l)/h)),d=Math.hypot(e-(a.x+o*u),i-(a.z+l*u));d<s.distanceM&&(s={distanceM:d,heading:Math.atan2(o,-l)})}return s}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class De{static WMS="https://data.geopf.fr/wms-r/wms";static LAYERS=["IGNF_LIDAR-HD_MNT_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93","ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"];static METRES_PER_PIXEL=4;static METRES_PER_DEGREE=111320;static CLASS_LAYER="IGNF_LIDAR-HD_CLASS";static SURFACE_LAYER="IGNF_LIDAR-HD_MNS_ELEVATION.ELEVATIONGRIDCOVERAGE.LAMB93";static DECK=[240,240,0];static NO_CLASS=[0,0,0];static DECK_END_PIXELS=3;static DECK_HALF_WIDTH_M=8;static DECK_APPROACH_M=10;static DECK_STRAIGHT_MAX_M=200;static MIN_PIXELS=8;static MAX_PIXELS=700;static NO_DATA_BELOW=-100;static COARSE_METRES_PER_PIXEL=20;static MESH_FROM_VERTICES=33;static FINE_SPACING_M=7;static MAX_SEGMENTS=256;static MAX_HOLE_SHARE=.05;static DEFAULT_TIMEOUT_MS=12e3;static MAX_WINDOW_M=50;fetchImpl;wms;timeoutMs;maxWindowM;geoplatform;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.wms=t.wmsEndpoint??De.WMS,this.timeoutMs=t.timeoutMs??De.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??De.MAX_WINDOW_M,this.geoplatform=new Le({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const s={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Le.covers(s.lat,s.lng))throw new Error("The IGN's relief covers France only");const n=Math.abs(re(s.lat,t.east,s.lat,t.west).x),a=Math.abs(re(t.north,s.lng,t.south,s.lng).z);e=this.finer(e,n,a);const r={x:n/Math.max(1,e.width-1),y:a/Math.max(1,e.height-1)},o={x:Math.min(r.x,this.maxWindowM),y:Math.min(r.y,this.maxWindowM)},l={south:t.south-o.y/De.METRES_PER_DEGREE,north:t.north+o.y/De.METRES_PER_DEGREE,west:t.west-o.x/(De.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180)),east:t.east+o.x/(De.METRES_PER_DEGREE*Math.cos(s.lat*Math.PI/180))},h=g=>Math.min(De.MAX_PIXELS,Math.max(De.MIN_PIXELS,Math.ceil(g/De.METRES_PER_PIXEL))),u={width:h(n+2*o.x),height:h(a+2*o.y)},d={x:(n+2*o.x)/u.width,y:(a+2*o.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>De.COARSE_METRES_PER_PIXEL;for(const g of p?[...De.LAYERS].reverse():De.LAYERS)try{const m=await this.heights(l,u,g);g===De.LAYERS[0]&&await this.layBridgeDecks(m,l,u,i?.route);const v=this.sample(m,e,t,l,d,r);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${g} does not cover this place`)}catch(m){f=m}throw f}finer(t,e,i){if(t.width<De.MESH_FROM_VERTICES||t.height<De.MESH_FROM_VERTICES)return t;const s=(n,a)=>{const r=Math.ceil(n/De.FINE_SPACING_M),o=Math.max(a-1,Math.min(De.MAX_SEGMENTS,r));return o%2===0?o:o+1};return{width:s(e,t.width)+1,height:s(i,t.height)+1}}async raster(t,e,i){const s=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:i,STYLES:"",CRS:"EPSG:4326",BBOX:[t.south,t.west,t.north,t.east].map(a=>a.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.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 h0.parse(await n.arrayBuffer())}async heights(t,e,i){const s=await this.raster(t,e,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(t,e,i,s){if(!(!s||s.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(n=>n>De.NO_DATA_BELOW)))try{const n=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(r=>Qr.follows(s,r));if(n.length===0)return;const a=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,n),this.layRouteDecks(t,a,e,n)}catch{}}async layClassifiedDecks(t,e,i,s){try{const n=await this.raster(e,i,De.CLASS_LAYER);if(n.samples<3||n.width!==t.width||n.height!==t.height)return;const a=(m,[v,M,x])=>n.values[m*n.samples]===v&&n.values[m*n.samples+1]===M&&n.values[m*n.samples+2]===x,r=t.width,o=t.height,l=new Uint8Array(r*o);let h=!1;for(let m=0;m<l.length;m++)a(m,De.DECK)&&(l[m]=1,h=!0);if(!h)return;const u=De.DECK_END_PIXELS,d=[];for(let m=0;m<l.length;m++){if(l[m]!==1)continue;const v=m%r,M=(m-v)/r;for(let x=-u;x<=u;x++)for(let y=-u;y<=u;y++){const w=v+y,S=M+x;if(w<0||S<0||w>=r||S>=o)continue;const E=S*r+w;l[E]===0&&a(E,De.NO_CLASS)&&d.push(E)}}for(const m of d)l[m]=1;const f=this.paint(s,e,r,o),p=this.touching(l,f,r,o);if(p.every(m=>m===0))return;const g=await this.heights(e,i,De.SURFACE_LAYER);if(g.width!==r||g.height!==o)return;for(let m=0;m<p.length;m++){if(p[m]===0)continue;const v=g.values[m];Number.isFinite(v)&&v>De.NO_DATA_BELOW&&v>t.values[m]&&(t.values[m]=v)}}catch{}}layRouteDecks(t,e,i,s){const{width:n,height:a}=t,r=(i.north+i.south)/2,o=(i.east-i.west)*De.METRES_PER_DEGREE*Math.cos(r*Math.PI/180),l=(i.north-i.south)*De.METRES_PER_DEGREE,h=o/n,u=l/a,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*o,y:(i.north-v.lat)/(i.north-i.south)*l}),f=(v,M)=>{const x=Math.floor(v/h),y=Math.floor(M/u);if(x<0||y<0||x>=n||y>=a)return;const w=e[y*n+x];return Number.isFinite(w)&&w>De.NO_DATA_BELOW?w:void 0},p=De.DECK_HALF_WIDTH_M,g=De.DECK_APPROACH_M,m=(v,M)=>{const x=Math.hypot(v.x-M.x,v.y-M.y)||1,y={x:(v.x-M.x)/x,y:(v.y-M.y)/x},w=[0,g/2,g].map(S=>f(v.x+y.x*S,v.y+y.y*S)).filter(S=>S!==void 0);return w.length>0?Math.max(...w):void 0};for(const v of De.chains(s.map(M=>M.map(d)))){const M=[0];for(let D=1;D<v.length;D++)M.push(M[D-1]+Math.hypot(v[D].x-v[D-1].x,v[D].y-v[D-1].y));const x=M[M.length-1];if(x<1||x>De.DECK_STRAIGHT_MAX_M)continue;const y=m(v[0],v[1]),w=m(v[v.length-1],v[v.length-2]);if(y===void 0||w===void 0)continue;const S=p+g,E=Math.max(0,Math.floor((Math.min(...v.map(D=>D.x))-S)/h)),b=Math.min(n-1,Math.ceil((Math.max(...v.map(D=>D.x))+S)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(D=>D.y))-S)/u)),T=Math.min(a-1,Math.ceil((Math.max(...v.map(D=>D.y))+S)/u));for(let D=A;D<=T;D++)for(let I=E;I<=b;I++){const C=De.nearestAlong(v,M,{x:(I+.5)*h,y:(D+.5)*u});if(C.distance>p||C.s<-g||C.s>x+g)continue;const N=y+(w-y)*Math.min(1,Math.max(0,C.s/x)),O=D*n+I;e[O]>=N||(t.values[O]=N)}}}static chains(t){const e=t.filter(n=>n.length>=2).map(n=>[...n]),i=[],s=(n,a)=>Math.hypot(n.x-a.x,n.y-a.y)<=1;for(;e.length>0;){let n=e.shift(),a=!0;for(;a;){a=!1;for(let r=0;r<e.length;r++){const o=e[r],l=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(l,o[o.length-1]))n=[...o.slice(0,-1),...n];else if(s(l,o[0]))n=[...[...o].reverse().slice(0,-1),...n];else continue;e.splice(r,1),a=!0;break}}i.push(n)}return i}static nearestAlong(t,e,i){let s={s:0,distance:1/0};for(let n=0;n<t.length-1;n++){const a=t[n],r=t[n+1],o=r.x-a.x,l=r.y-a.y,h=o*o+l*l;if(h<1e-9)continue;let u=((i.x-a.x)*o+(i.y-a.y)*l)/h;n>0&&(u=Math.max(0,u)),n<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(a.x+o*u),i.y-(a.y+l*u));d<s.distance&&(s={s:e[n]+u*Math.sqrt(h),distance:d})}return s}paint(t,e,i,s){const n=new Uint8Array(i*s),a=o=>(o-e.west)/(e.east-e.west)*i,r=o=>(e.north-o)/(e.north-e.south)*s;for(const o of t)for(let l=0;l<o.length-1;l++){const h=a(o[l].lng),u=r(o[l].lat),d=a(o[l+1].lng),f=r(o[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let g=0;g<=p;g++){const m=Math.floor(h+(d-h)*g/p),v=Math.floor(u+(f-u)*g/p);for(let M=-1;M<=1;M++)for(let x=-1;x<=1;x++){const y=m+x,w=v+M;y>=0&&w>=0&&y<i&&w<s&&(n[w*i+y]=1)}}}return n}touching(t,e,i,s){const n=new Uint8Array(t.length),a=new Uint8Array(t.length);for(let r=0;r<t.length;r++){if(t[r]===0||a[r]===1)continue;const o=[],l=[r];a[r]=1;let h=!1;for(;l.length>0;){const u=l.pop();o.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let g=-1;g<=1;g++){const m=d+g,v=f+p;if(m<0||v<0||m>=i||v>=s)continue;const M=v*i+m;t[M]===1&&a[M]===0&&(a[M]=1,l.push(M))}}if(h)for(const u of o)n[u]=1}return n}sample(t,e,i,s,n,a){const{width:r,height:o}=e,l=new Float32Array(r*o),h=new Uint8Array(r*o),u=Math.min(a.x,this.maxWindowM)/n.x,d=Math.min(a.y,this.maxWindowM)/n.y;let f=0;for(let p=0;p<o;p++){const g=i.north+(i.south-i.north)*(o===1?.5:p/(o-1)),m=(s.north-g)/(s.north-s.south)*t.height-.5;for(let v=0;v<r;v++){const x=(i.west+(i.east-i.west)*(r===1?.5:v/(r-1))-s.west)/(s.east-s.west)*t.width-.5,y=u>1||d>1?this.tent(t,x,m,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,m),w=p*r+v;y===void 0?f++:(l[w]=y,h[w]=1)}}if(!(f===r*o||f/(r*o)>De.MAX_HOLE_SHARE))return this.fill(l,h,r,o),l}tent(t,e,i,s,n){let a=0,r=0,o=0;const l=Math.max(0,Math.ceil(i-n)),h=Math.min(t.height-1,Math.floor(i+n)),u=Math.max(0,Math.ceil(e-s)),d=Math.min(t.width-1,Math.floor(e+s));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/n;if(!(p<=0))for(let g=u;g<=d;g++){const m=p*(1-Math.abs(g-e)/s);if(m<=0)continue;o+=m;const v=t.at(g,f);!Number.isFinite(v)||v<De.NO_DATA_BELOW||(a+=m*v,r+=m)}}return o>0&&r>=o*.5?a/r:void 0}bilinear(t,e,i){const s=Math.max(0,Math.min(t.width-1,Math.floor(e))),n=Math.max(0,Math.min(t.height-1,Math.floor(i))),a=Math.min(t.width-1,s+1),r=Math.min(t.height-1,n+1),o=Math.max(0,Math.min(1,e-s)),l=Math.max(0,Math.min(1,i-n)),h=t.at(s,n),u=t.at(a,n),d=t.at(s,r),f=t.at(a,r);for(const m of[h,u,d,f])if(!Number.isFinite(m)||m<De.NO_DATA_BELOW)return;const p=h+(u-h)*o,g=d+(f-d)*o;return p+(g-p)*l}fill(t,e,i,s){let n=e.reduce((a,r)=>a+(r?0:1),0);for(;n>0;){const a=[];for(let r=0;r<s;r++)for(let o=0;o<i;o++){const l=r*i+o;if(e[l])continue;let h=0,u=0;for(let d=-1;d<=1;d++)for(let f=-1;f<=1;f++){const p=r+d,g=o+f;p<0||g<0||p>=s||g>=i||!e[p*i+g]||(h+=t[p*i+g],u++)}u>0&&a.push([l,h/u])}if(a.length===0)return;for(const[r,o]of a)t[r]=o,e[r]=1;n-=a.length}}}class rA{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let s=new Error("No source of relief to ask");for(const n of this.providers)try{return await n.getElevationGrid(t,e,i)}catch(a){s=a}throw s}}const tf=256,oA=5;async function cw(c,t,e,i){const s=(c.south+c.north)/2,n=(c.west+c.east)/2,a=Math.abs(re(s,c.east,s,c.west).x),r=Math.abs(re(c.north,n,c.south,n).z),o=Math.max(a,r),{zoom:l,gridSize:h}=cA(s,o,Math.max(t.width,t.height)),{tiles:u,bounds:d}=rw(n,s,l,h),f=h*tf,p=document.createElement("canvas");p.width=f,p.height=f;const g=p.getContext("2d");if(!g)throw new Error("2D canvas context unavailable");const m=u[0];await Promise.all(u.map(async y=>{const w=e(y),S=await i(w);if(!S.ok)throw new Error(`Imagery tile fetch failed (${S.status}): ${w}`);const E=await createImageBitmap(await S.blob());g.drawImage(E,(y.x-m.x)*tf,(y.y-m.y)*tf)}));const v=Math.min(Math.max(t.width,t.height),f);if(v===f)return{source:p,width:f,height:f,bounds:d};const M=document.createElement("canvas");M.width=v,M.height=v;const x=M.getContext("2d");if(!x)throw new Error("2D canvas context unavailable");return x.drawImage(p,0,0,f,f,0,0,v,v),{source:M,width:v,height:v,bounds:d}}function cA(c,t,e){let i=sw(c,t/Math.max(1,e)),s=Kv(c,i,t);for(;s>oA&&i>0;)i--,s=Kv(c,i,t);return{zoom:i,gridSize:s,mPerPixel:v1(c,i)/tf}}function Kv(c,t,e){const i=Math.ceil(e/2/v1(c,t));return Math.max(3,2*i+1)}class lw{attribution="Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community";fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.tileUrlTemplate=t.tileUrlTemplate??"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"}async getImageryTexture(t,e){return cw(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Sn{static ENDPOINTS=["https://overpass-api.de/api/interpreter","https://overpass.kumi.systems/api/interpreter","https://overpass.private.coffee/api/interpreter"];static FRANCE_ENDPOINT="https://overpass.openstreetmap.fr/api/interpreter";static FRANCE={south:41.3,west:-5.2,north:51.1,east:9.6};static endpointsFor(t,e=Sn.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[s,n,a,r]=i.slice(1).map(Number),o=(s+a)/2,l=(n+r)/2,h=Sn.FRANCE;return o>=h.south&&o<=h.north&&l>=h.west&&l<=h.east?[Sn.FRANCE_ENDPOINT,...e.filter(d=>d!==Sn.FRANCE_ENDPOINT)]:[...e]}fetchImpl;endpoints;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.endpoints=t.endpoints}static queue=Promise.resolve();static HANG_MS=4e4;static RETRY_MS=4e3;query(t){return this.queued(()=>this.ask(t))}queued(t){const e=Sn.queue.then(t,t);return Sn.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Sn.endpointsFor(t))for(let s=0;s<2;s++){try{const n=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Sn.HANG_MS)});if(n.ok)return await n.json();if(e=new Error(`${new URL(i).host} refused (${n.status})`),n.status!==429&&n.status!==504)break}catch(n){e=new Error(`${new URL(i).host} unreachable (${String(n)})`);break}await new Promise(n=>setTimeout(n,Sn.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class to{attribution="Roads © OpenStreetMap contributors, as surveyed today";contemporary=!0;static DRIVABLE=["motorway","trunk","primary","secondary","tertiary","unclassified","residential","service","track","motorway_link","trunk_link","primary_link","secondary_link","tertiary_link"];static WIDTH_M={motorway:11,trunk:9,primary:8,secondary:7,tertiary:6.5,unclassified:5.5,residential:5.5,service:4,track:3.5};static DEFAULT_WIDTH_M=5;client;constructor(t={}){this.client=new Sn(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${to.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const s=i.geometry,n=i.tags;!n||!s||s.length<2||e.push({id:`osm-${i.id??e.length}`,name:n.name,surface:to.surfaceOf(n),widthM:to.widthOf(n),...to.paintOf(n),points:s.map(a=>({lat:a.lat,lng:a.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",s=t.oneway,n=s==="yes"||s==="1"||s==="true"||s===void 0&&(e==="motorway"||i),a=s==="-1"||s==="reverse",r=Number.parseInt(t.lanes??"",10),o=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(n||a)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(r)&&r>0?{lanes:r}:{},...s!==void 0||e==="motorway"||i?{direction:a?"backward":n?"forward":"both"}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{}}}static widthOf(t){const e=Number.parseFloat(t.width??t.est_width??"");if(Number.isFinite(e)&&e>0)return e;const i=Number.parseInt(t.lanes??"",10);return Number.isFinite(i)&&i>0?i*3.5:to.WIDTH_M[t.highway]??to.DEFAULT_WIDTH_M}static surfaceOf(t){const e=t.surface;return e==="dirt"||e==="earth"||e==="mud"?"dirt":e==="gravel"||e==="fine_gravel"||e==="compacted"||e==="ground"||e==="sand"||e==="unpaved"?"gravel":e?"paved":t.highway==="track"?"gravel":"paved"}}const I0="https://ufoathome.org/roads/index.json";class hl{attributionRead;contemporaryRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??hl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Roads © OpenStreetMap contributors"}get contemporary(){return this.contemporaryRead??this.fallback?.contemporary??!0}async getRoads(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRoads(t);return this.attributionRead=this.fallback.attribution,this.contemporaryRead=this.fallback.contemporary,i}async held(t){let e;try{e=await this.load()}catch{return}const i=e.find(({entry:s})=>s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.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 t=this.indexUrls.join(`
|
|
1568
|
-
`);let e=hl.shared.get(t);return e||(e=this.fetchFirstAvailable(),hl.shared.set(t,e),e.then(i=>{i.length===0&&hl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.
|
|
1569
|
-
`);let e=ul.shared.get(t);return e||(e=this.fetchFirstAvailable(),ul.shared.set(t,e),e.then(i=>{i.length===0&&ul.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.194.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==P0?[e,P0]:[P0]).map(i=>i+t)}}class mn{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=mn.key(t);let i=mn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),mn.asked.set(e,i),i.catch(()=>mn.asked.delete(e))),structuredClone(await i)}static forget(){mn.asked.clear()}static key(t){return`v${mn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await mn.openCache(),s=mn.request(t);if(i)try{const a=await i.match(s);if(a){const{savedAt:r,surfaces:o}=await a.json();if(Date.now()-r<mn.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(e);return i&&mn.store(i,s,n),n}static async store(t,e,i){try{const s={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const a of n.slice(0,Math.max(0,n.length-mn.MAX_STORED)))await t.delete(a)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(mn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class ao{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,s)=>ao.linesOf(i,s))}static linesOf(t,e){const{type:i,coordinates:s}=t.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],a=ao.BY_NATURE[String(t.properties.nature??"")];if(!a)return[];const r=String(t.properties.cleabs??`ign-rail-${e}`),o=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=ao.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=ao.electrificationOf(a.kind,u,t.properties.electrifie);return n.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>ao.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:n.length>1?`${r}-${p}`:r,...typeof h=="string"&&h.length>0?{name:h}:{},kind:a.kind,...a.service?{service:!0}:{},...a.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(o)&&o>0?o:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Cs{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Sn(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Cs.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cs.ROUTES})$"];out body;`;return Cs.apply(t,await this.client.query(s),e)}static apply(t,e,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Cs.ways(e,s);return n.length===0?[...t]:t.map(a=>{const r=a.points.map(v=>re(v.lat,v.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let u=0;const d=n.filter(v=>v.service===!!a.service);for(const v of Cs.samples(r)){u++;const M=Cs.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&o.set(x.name,(o.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(M.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,x)=>x[1]-M[1])[0]?.[0],p=a.name??f(o),g=a.voltageV??(a.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...a,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Cs.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const a=e.get(n.ref)??new Set;a.add(s),e.set(n.ref,a)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Cs.servicesByWay(t),s=[];for(const n of t.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const a=n.tags??{},r=Cs.voltageOf(a);s.push({service:!!a.service||a.usage==="industrial",...a.name?{name:a.name}:{},...r?{voltageV:r}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>re(o.lat,o.lon,e.lat,e.lng))})}return s}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const s=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(s<1e-6)continue;const n=(t[i+1].x-t[i].x)/s,a=(t[i+1].z-t[i].z)/s;for(let r=Cs.SAMPLE_M/2;r<s;r+=Cs.SAMPLE_M)e.push({x:t[i].x+n*r,z:t[i].z+a*r,dx:n,dz:a})}return e}static waysAt(t,e){const i=Math.cos(Cs.ALIGNED_DEG*Math.PI/180),s=[];for(const n of t){let a;for(let r=0;r<n.path.length-1;r++){const o=n.path[r],l=n.path[r+1],h=l.x-o.x,u=l.z-o.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-o.x)*h+(e.z-o.z)*u)/(d*d))),p=Math.hypot(e.x-(o.x+h*f),e.z-(o.z+u*f));p<=Cs.NEAR_M&&(a===void 0||p<a)&&(a=p)}a!==void 0&&s.push({way:n,distance:a})}return s.sort((n,a)=>n.distance-a.distance).map(({way:n})=>n)}}class dl{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Sn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${dl.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cs.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Cs.servicesByWay(t);for(const s of t.elements??[]){const n=s.geometry,a=s.tags;if(s.type==="relation"||!a||!n||n.length<2)continue;const r=[...i.get(s.id??-1)??[]].sort(),o=Cs.voltageOf(a),l=dl.kindOf(a),h=Number.parseInt((a.gauge??"").split(";")[0],10),u=Number.parseInt(a.tracks??"",10),d=dl.electrificationOf(a.electrified),f=a.highspeed==="yes"||Number.parseInt(a.maxspeed??"",10)>=250;e.push({id:`osm-rail-${s.id??e.length}`,...a.name?{name:a.name}:{},...r.length>0?{services:r}:{},...o?{voltageV:o}:{},kind:l,...a.service||a.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:a.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:dl.levelOf(a),points:n.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class uA{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!ao.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class ts{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=ts.key(t);let i=ts.asked.get(e)??ts.containing(t);if(i===void 0){const s=this.recalled(e,t);i={bounds:t,answer:s},ts.asked.set(e,i),s.catch(()=>ts.asked.delete(e))}return structuredClone(await i.answer)}static forget(){ts.asked.clear(),ts.failedAt=-1/0}static key(t){return`v${ts.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of ts.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await ts.openCache(),s=ts.request(t);let n;if(i)try{const r=await i.match(s);if(r){const{savedAt:o,lines:l}=await r.json();if(Array.isArray(l)){if(this.now()-o<ts.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-ts.failedAt<ts.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let a;try{a=await this.railways.getRailways(e)}catch(r){if(ts.failedAt=this.now(),n)return n;throw r}return i&&ts.store(i,s,{savedAt:this.now(),lines:a}),a}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const n of s.slice(0,Math.max(0,s.length-ts.MAX_STORED)))await t.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(ts.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const C0="https://ufoathome.org/railways/index.json";class fl{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??fl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.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 t=this.indexUrls.join(`
|
|
1570
|
-
`);let e=fl.shared.get(t);return e||(e=this.fetchFirstAvailable(),fl.shared.set(t,e),e.then(i=>{i.length===0&&fl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.194.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==C0?[e,C0]:[C0]).map(i=>i+t)}}function hw(){return{elevation:uw(),imagery:dw(),roads:dA(),water:fA(),railways:pA()}}function uw(){return new rA(new De,new ow)}function dw(){return new lw}function dA(){return new hl({fallback:new lA(new no,new to)})}function fA(){return new ul({fallback:new mn(new hA(new fu,new zo))})}function pA(){return new fl({fallback:new ts(new uA(new ao,new dl))})}const mA=new Set,Cl="show-observer-map",Ol="hide-milestones",Xo="minified";class Ue extends HTMLElement{static get observedAttributes(){return["src",Cl,Ol,Xo]}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 li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];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=px.create();issues=[];issueCheck=0;sightingAudio=new Wv;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new Wv(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}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>Ue.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 t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(n)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ue.setIcon(this.moreButton,t?jt.UNFOLDED:jt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=jt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await Ht(async()=>{const{VideoButton:n}=await import("./VideoButton-DXPI7_Vt.js");return{VideoButton:n}},__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url);if(this.videoElement!==e)return;const s=new i(t,e);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?Uu(this.sighting.milestones,e):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),a=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...a&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(a.left-n.left)/n.width,top:(a.top-n.top)/n.height,width:a.width/n.width,height:a.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),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=`${t.clientX-n.left+12}px`,this.tooltip.style.top=`${t.clientY-n.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ue.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ue.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const s=li.pointAt(e,(t.clientX-i.left)/i.width,(t.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 t=document.createElement("template");t.innerHTML=`<style>${BE}</style>${zE}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gl(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",r=>{r.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 Uo(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.citedMarks=this.shadow.getElementById("cited-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",r=>{r.key!=="Enter"&&r.key!==" "||(r.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),s=r=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((r.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;e.addEventListener("pointerdown",r=>{r.button===0&&(r.stopPropagation(),e.setPointerCapture(r.pointerId),e.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(r))}),e.addEventListener("pointermove",r=>{e.hasPointerCapture(r.pointerId)&&s(r)});const a=r=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(r.pointerId)&&e.releasePointerCapture(r.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a),e.addEventListener("click",r=>r.stopPropagation()),this.miniMuteButton.addEventListener("click",r=>{r.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",r=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(r),this.seekPreview.hidden=!0,this.beginTouchScrub(r)}),this.seekInput.addEventListener("pointerup",r=>{this.seekSnapArmed=!1,this.endTouchScrub(r)}),this.seekInput.addEventListener("pointercancel",r=>this.endTouchScrub(r)),this.seekInput.addEventListener("pointermove",r=>{this.nameMarkUnder(r),this.hoverSeek(r),this.touchScrub(r)}),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 r of["touchend","click"])this.stageElement.addEventListener(r,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",r=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}r.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",r=>{!this.enableClickToPlay||this.minified||(r.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 t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Cl&&this.applyObserverMapDefault(),t===Ol&&this.setMilestonesShown(!this.hasAttribute(Ol)),t===Xo){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Xo)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(pw)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await dx.recording(t)}get sightingData(){return Yx(this.currentSighting)}set sightingData(t){const e=s1.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=g1(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let s=[];try{const{default:n}=await Ht(async()=>{const{default:a}=await import("./sightingSchema-CgwoRMl-.js");return{default:a}},[],import.meta.url);s=new Yn(n).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...s,...e.loadIssues],Mv.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(vA,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=Mv.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=sS.INTERVIEW,i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const s=e.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Ue.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(gA,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of e)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 t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const s=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),s=this.said.read(e.title)??e.id,n=document.createElement("div");n.className="reference-row";const a=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,a.append(r,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),l.disabled=!i.shown,r.addEventListener("change",()=>{i.shown=r.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(a,l),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ue.setIcon(this.referencesButton,i?jt.PICTURES_ON:jt.PICTURES_OFF);const s=e?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)),Ue.setIcon(this.tracesButton,this.tracesShownState?jt.TRACES_ON:jt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Hh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const n=this.said.read(i.label)??"",a=this.said.read(i.note),r=a?`${n} — ${a}`:n;return s.title=r,s.setAttribute("aria-label",r),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const a=this.said.read(i.label)??"",r=this.said.read(i.note);return n.textContent=r?`${a} — ${r}`:a,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(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=t!==void 0&&Number(s.dataset.t)===t.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=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const s=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(a=>a>0&&a<t))].sort((a,r)=>a-r):[],Math.max(t,0)];this.seekSegmentList=[];const n=[];for(let a=0;a<s.length-1;a++){const r=document.createElement("div");r.className="seek-segment",r.style.flexGrow=String(Math.max(s[a+1]-s[a],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",r.append(o,l),n.push(r),this.seekSegmentList.push({start:s[a],end:s[a+1],element:r,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,s=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ue.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),n=s*i,a=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ue.fillOf(f,n),f.element.classList.toggle("hovered",n>=f.start&&(n<f.end||p===a))});const r=this.milestonesShown?this.sighting.milestones:[],o=r.length>0?Uu(r,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||s===0||n===0){t(this.canvasRenderer);return}const a=window.devicePixelRatio||1,r=Math.max(1,Math.round(s*a)),o=Math.max(1,Math.round(n*a));this.chromeCanvas.width!==r&&(this.chromeCanvas.width=r),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,r,o),this.chromeDirty=!1,i&&(e.setTransform(r/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Gl(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const s=Ue.MARK_SNAP_PX/i*e;let n;for(const a of this.milestoneMarks.children){const r=Number(a.dataset.t);Math.abs(r-t)>s||(!n||Math.abs(r-t)<Math.abs(n.t-t))&&(n={t:r,name:a.title})}return n}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=(t.clientX-e.left)/e.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Uu(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const s=this.said.read(e.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(t=this.currentTime){const e=Xs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ue.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ue.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ue.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ue.EXPOSURE_STEP_PX),n=Math.min(Ue.MAX_TRAVEL_STEPS,Math.max(i,s)),a=[];for(let r=0;r<n;r++)a.push(e.fromMs+e.ms*r/(n-1));return a}travelPxOver(t,e){const i=this.shapesAt(t),s=this.shapesAt(t+e);let n=0;for(const[a,r]of i){const o=s.get(a);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(r.bounds.x+r.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(r.bounds.y+r.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(t,e,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,t,e,i);if(n)return n}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);s&&e.set(i,s)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Ts.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:mA;this.canvasRenderer.setStarPoints(Ts.starPointsOf(this.sighting.instrument,Te(this.sighting,t)?.fNumber));const s=(Te(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(t),a=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,a))}for(const[o,l]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,a)));const r=this.selectionShown&&i.size>1?cn.groupBoundsFor([...e].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{r&&o.paintGroupHandles(r),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,a).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(mx(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new HE(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ue.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?jt.PLAY:jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ue.icons.get(t)!==e&&(Ue.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ue.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Ue.setIcon(this.playPauseButton,t?jt.PAUSE:jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Cl),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Ue.setIcon(this.observerMapButton,t?jt.MAP_ON:jt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Pl.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=li.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?li.expand(t,Ue.OBSERVER_MAP_IMAGERY_AHEAD):t,s=li.IMAGERY_PX*(e?1+2*Ue.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,a=n?void 0:dw();try{const r=a?await a.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=(a??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(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,s=this.observerMapView.changed?li.expand(t,Ue.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,a=t.east-t.west>this.observerMapImageryViewWidth/2;return!n||!a}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},s=[this.canvas.width-t.width,this.canvas.width],n=[0,t.width],a=Ue.OBSERVER_MAP_CLEARANCE_PX,r=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",r&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!r&&(o||!i(s[0],s[1],a))&&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 t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,s=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*s,bottom:(t.bottom-e.top)*s}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Te(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Ue.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Uu(this.currentSighting.milestones,t):void 0;for(const a of this.milestonesShown?Hh(this.currentSighting.milestones):[]){const r=Te(this.currentSighting,a.t);r?.lat===void 0||r.lng===void 0||s.push({label:this.said.read(a.label)??"",note:this.said.read(a.note),t:a.t,lat:r.lat,lng:r.lng,current:a===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?$a.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Ts.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(a=>({kind:a.kind,points:a.points,color:a.color,label:this.said.read(a.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Hh(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Ue.setIcon(this.milestonesButton,this.milestonesShown?jt.MILESTONES_ON:jt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=Te(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=ga(i,t),{lat:n,lng:a}=Nn(s.eastM,-s.northM,e.lat,e.lng);return{lat:n,lng:a,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const s=Te(this.currentSighting,this.currentTime),n=$a.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(e),y:n.angleDegToRadiusPx(i)}}gaitAt(t){return ii.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Ue.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ue.setIcon(this.miniMuteButton,this.mutedState?jt.MUTED:jt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ue.setIcon(this.muteButton,jt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ue.setIcon(this.muteButton,this.mutedState?jt.MUTED:jt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ue.setIcon(this.fullscreenButton,t?jt.EXIT_FULLSCREEN:jt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new lu(Sr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=zh(Sr.preferencesFor(this),Bh);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await tS.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.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 t=this.currentSighting.event,e=gx(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?aS(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return Hr(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?$v(Yv(this.realStartMs+i)):Hr(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Hr(t):Hr(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Hr(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return Hr(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Hr(this.currentSighting.timeline.duration):this.canShowClockTime?$v(Yv(this.realStartMs+this.realDurationMs)):Hr(this.realDurationMs)}}function Yv(c){const t=new Date(c);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function $v(c){if(c.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return c.second?`${t(c.hour)}:${t(c.minute??0)}:${t(c.second)}`:`${t(c.hour)}:${t(c.minute??0)}`}function Hr(c){const t=Math.round(c/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Nm="rr0-ufo";function fw(){customElements.get(Nm)||customElements.define(Nm,Ue)}const gA="timechange",vA="recordingissues",pw="minifiedreset";class FO{static sync(t,e,i,s,n){if(t.querySelector(".param-description")?.remove(),e===void 0){t.removeAttribute("data-describing");return}const a=document.createElement("div");a.className="param-description";const r=document.createElement("div");r.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const l=document.createElement("button");l.type="button",l.className="param-description-close",l.textContent="×",l.title=s,l.setAttribute("aria-label",s),l.addEventListener("click",n),r.append(o,l);const h=document.createElement("p");h.className="param-description-text",h.textContent=e,a.append(r,h),a.addEventListener("keydown",u=>{u.key==="Escape"&&n()}),t.setAttribute("data-describing",""),t.append(a),l.focus({preventScroll:!0})}static CSS=`
|
|
1568
|
+
`);let e=hl.shared.get(t);return e||(e=this.fetchFirstAvailable(),hl.shared.set(t,e),e.then(i=>{i.length===0&&hl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==I0?[e,I0]:[I0]).map(i=>i+t)}}class no{attribution="Roads © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Type autoroutier":{surface:"paved",widthM:11},"Route à 2 chaussées":{surface:"paved",widthM:7},"Route à 1 chaussée":{surface:"paved",widthM:5.5},"Rond-point":{surface:"paved",widthM:6},Bretelle:{surface:"paved",widthM:5},"Route empierrée":{surface:"gravel",widthM:3.5},Chemin:{surface:"dirt",widthM:3},"Piste cyclable":{surface:"paved",widthM:2.5}};static DEFAULT={surface:"paved",widthM:5};static KINDS={"Type autoroutier":"motorway","Route à 2 chaussées":"dual","Route à 1 chaussée":"road","Rond-point":"roundabout",Bretelle:"slip"};static DIRECTIONS={"Double sens":"both","Sens direct":"forward","Sens inverse":"backward"};platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRoads(t){return(await this.platform.roads(t)).flatMap((i,s)=>no.wayOf(i,s))}static wayOf(t,e){if(t.geometry.type!=="LineString")return[];const i=t.geometry.coordinates.map(([d,f])=>({lat:f,lng:d}));if(i.length<2)return[];const s=String(t.properties.nature??""),n=no.BY_NATURE[s]??no.DEFAULT,a=Number(t.properties.largeur_de_chaussee),r=Number(t.properties.nombre_de_voies),o=Number(t.properties.vitesse_moyenne_vl),l=no.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=no.KINDS[s],u=[t.properties.cpx_toponyme_route_nommee,t.properties.nom_voie_ban_gauche,t.properties.nom_voie_ban_droite].find(d=>typeof d=="string"&&d.length>0);return[{id:String(t.properties.cleabs??`ign-${e}`),...u?{name:u}:{},surface:n.surface,widthM:Number.isFinite(a)&&a>0?a:n.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(r)&&r>0?{lanes:r}:{},...l?{direction:l}:{},...Number.isFinite(o)&&o>0?{speedKmh:o}:{},points:i}]}}class lA{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Roads © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRoads(t){if(no.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class fu{attribution="Water © IGN, BD TOPO (Licence Ouverte 2.0)";platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getWater(t){return(await this.platform.waterSurfaces(t)).flatMap((i,s)=>fu.surfacesOf(i,s))}static surfacesOf(t,e){const{type:i,coordinates:s}=t.geometry,n=i==="Polygon"?[s]:i==="MultiPolygon"?s:[],a=String(t.properties.cleabs??`ign-water-${e}`);return n.flatMap((r,o)=>{const l=r.map(h=>fu.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:n.length>1?`${a}-${o}`:a,rings:l}]:[]})}static open(t){const e=t[0],i=t[t.length-1];return t.length>1&&e.lat===i.lat&&e.lng===i.lng?t.slice(0,-1):t}}class zo{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Sn(t)}async getWater(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];(way["natural"="water"](${e});way["waterway"="riverbank"](${e});)->.w;(relation["natural"="water"](${e});relation["waterway"="riverbank"](${e});)->.r;.w out geom;.r out body;way(r.r)(${e});out geom;`;return zo.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const a of e)a.type==="way"&&a.id!==void 0&&a.geometry&&i.set(a.id,a.geometry.map(r=>({lat:r.lat,lng:r.lon})));const s=[],n=new Set;for(const a of e){if(a.type!=="relation")continue;const r=l=>(a.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(n.add(h.ref),i.get(h.ref))),o=zo.rings(r("inner"));for(const[l,h]of zo.rings(r("outer")).entries()){const u=o.filter(d=>zo.contains(h,d[0]));s.push({id:`osm-r${a.id}-${l}`,rings:[h,...u]})}}for(const a of e)if(!(a.type!=="way"||!a.tags||a.id===void 0||n.has(a.id))&&!(a.tags.natural!=="water"&&a.tags.waterway!=="riverbank"))for(const r of zo.rings([i.get(a.id)??[]]))s.push({id:`osm-w${a.id}`,rings:[r]});return s}static rings(t){const e=(n,a)=>n.lat===a.lat&&n.lng===a.lng,i=t.filter(n=>n.length>=2).map(n=>[...n]),s=[];for(;i.length>0;){let n=i.pop(),a=!0;for(;!e(n[0],n[n.length-1])&&a;){a=!1;for(let r=0;r<i.length;r++){const o=i[r],l=n[n.length-1];if(e(l,o[0]))n=[...n,...o.slice(1)];else if(e(l,o[o.length-1]))n=[...n,...[...o].reverse().slice(1)];else continue;i.splice(r,1),a=!0;break}}n.length>=4&&e(n[0],n[n.length-1])&&s.push(n.slice(0,-1))}return s}static contains(t,e){let i=!1;for(let s=0,n=t.length-1;s<t.length;n=s++){const a=t[s],r=t[n];a.lat>e.lat!=r.lat>e.lat&&e.lng<(r.lng-a.lng)*(e.lat-a.lat)/(r.lat-a.lat)+a.lng&&(i=!i)}return i}}class hA{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(fu.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const P0="https://ufoathome.org/water/index.json";class ul{attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??ul.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Water © OpenStreetMap contributors"}async getWater(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getWater(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.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 t=this.indexUrls.join(`
|
|
1569
|
+
`);let e=ul.shared.get(t);return e||(e=this.fetchFirstAvailable(),ul.shared.set(t,e),e.then(i=>{i.length===0&&ul.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==P0?[e,P0]:[P0]).map(i=>i+t)}}class mn{constructor(t){this.water=t}static CACHE_NAME="rr0-water";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static asked=new Map;get attribution(){return this.water.attribution}async getWater(t){const e=mn.key(t);let i=mn.asked.get(e);return i===void 0&&(i=this.recalled(e,t),mn.asked.set(e,i),i.catch(()=>mn.asked.delete(e))),structuredClone(await i)}static forget(){mn.asked.clear()}static key(t){return`v${mn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await mn.openCache(),s=mn.request(t);if(i)try{const a=await i.match(s);if(a){const{savedAt:r,surfaces:o}=await a.json();if(Date.now()-r<mn.MAX_AGE_MS&&Array.isArray(o))return o;await i.delete(s)}}catch{}const n=await this.water.getWater(e);return i&&mn.store(i,s,n),n}static async store(t,e,i){try{const s={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}}));const n=await t.keys();for(const a of n.slice(0,Math.max(0,n.length-mn.MAX_STORED)))await t.delete(a)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(mn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class ao{attribution="Railways © IGN, BD TOPO (Licence Ouverte 2.0), as drawn today";contemporary=!0;static BY_NATURE={"Voie ferrée principale":{kind:"rail"},LGV:{kind:"rail",highSpeed:!0},"Voie de service":{kind:"rail",service:!0},Métro:{kind:"subway"},Tramway:{kind:"tram"},"Transport urbain":{kind:"light_rail"},"Funiculaire ou crémaillère":{kind:"funicular"}};static GAUGE_MM={Normale:1435,Etroite:1e3,Étroite:1e3,Large:1668};static NO_ALTITUDE=-1e3;platform;constructor(t={}){this.platform=new Le(t)}static covers(t){return Le.covers((t.south+t.north)/2,(t.west+t.east)/2)}async getRailways(t){return(await this.platform.railways(t)).flatMap((i,s)=>ao.linesOf(i,s))}static linesOf(t,e){const{type:i,coordinates:s}=t.geometry,n=i==="LineString"?[s]:i==="MultiLineString"?s:[],a=ao.BY_NATURE[String(t.properties.nature??"")];if(!a)return[];const r=String(t.properties.cleabs??`ign-rail-${e}`),o=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=ao.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=ao.electrificationOf(a.kind,u,t.properties.electrifie);return n.flatMap((f,p)=>{const g=f.map(m=>({lat:m[1],lng:m[0],...m.length>2&&Number.isFinite(m[2])&&m[2]>ao.NO_ALTITUDE?{altitudeM:m[2]}:{}}));return g.length<2?[]:[{id:n.length>1?`${r}-${p}`:r,...typeof h=="string"&&h.length>0?{name:h}:{},kind:a.kind,...a.service?{service:!0}:{},...a.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(o)&&o>0?o:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:g}]})}static electrificationOf(t,e,i){if(i===!1)return"none";if(i===!0){if(t==="subway")return"third_rail";if(!(t==="funicular"||e<1435))return"overhead"}}}class Cs{static NEAR_M=15;static ALIGNED_DEG=30;static SAMPLE_M=10;static ROUTES="train|subway|light_rail|tram|monorail";static KINDS="rail|light_rail|subway|tram|narrow_gauge|funicular|preserved";client;constructor(t={}){this.client=new Sn(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,s=`[out:json][timeout:120];way["railway"~"^(${Cs.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cs.ROUTES})$"];out body;`;return Cs.apply(t,await this.client.query(s),e)}static apply(t,e,i){const s={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},n=Cs.ways(e,s);return n.length===0?[...t]:t.map(a=>{const r=a.points.map(v=>re(v.lat,v.lng,s.lat,s.lng)),o=new Map,l=new Map,h=new Map;let u=0;const d=n.filter(v=>v.service===!!a.service);for(const v of Cs.samples(r)){u++;const M=Cs.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&o.set(x.name,(o.get(x.name)??0)+1),x.voltageV&&l.set(x.voltageV,(l.get(x.voltageV)??0)+1);for(const y of new Set(M.flatMap(w=>w.services)))h.set(y,(h.get(y)??0)+1)}const f=v=>[...v.entries()].sort((M,x)=>x[1]-M[1])[0]?.[0],p=a.name??f(o),g=a.voltageV??(a.electrification==="none"?void 0:f(l)),m=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...a,...p?{name:p}:{},...g?{voltageV:g}:{},...m.length>0?{services:m}:{}}})}static serviceOf(t){const e=t.name?.split(" : ")[0].replace(/\s*\([^)]*\)\s*$/,"").trim();return e||[t.network,t.ref].filter(Boolean).join(" ")||void 0}static servicesByWay(t){const e=new Map;for(const i of t.elements??[]){if(i.type!=="relation"||!i.tags)continue;const s=Cs.serviceOf(i.tags);if(s)for(const n of i.members??[]){if(n.type!=="way"||n.ref===void 0)continue;const a=e.get(n.ref)??new Set;a.add(s),e.set(n.ref,a)}}return e}static voltageOf(t){const e=Number.parseInt((t.voltage??"").split(";")[0],10);return Number.isFinite(e)&&e>0?e:void 0}static ways(t,e){const i=Cs.servicesByWay(t),s=[];for(const n of t.elements??[]){if(n.type!=="way"||!n.geometry||n.geometry.length<2)continue;const a=n.tags??{},r=Cs.voltageOf(a);s.push({service:!!a.service||a.usage==="industrial",...a.name?{name:a.name}:{},...r?{voltageV:r}:{},services:[...i.get(n.id??-1)??[]],path:n.geometry.map(o=>re(o.lat,o.lon,e.lat,e.lng))})}return s}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const s=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(s<1e-6)continue;const n=(t[i+1].x-t[i].x)/s,a=(t[i+1].z-t[i].z)/s;for(let r=Cs.SAMPLE_M/2;r<s;r+=Cs.SAMPLE_M)e.push({x:t[i].x+n*r,z:t[i].z+a*r,dx:n,dz:a})}return e}static waysAt(t,e){const i=Math.cos(Cs.ALIGNED_DEG*Math.PI/180),s=[];for(const n of t){let a;for(let r=0;r<n.path.length-1;r++){const o=n.path[r],l=n.path[r+1],h=l.x-o.x,u=l.z-o.z,d=Math.hypot(h,u);if(d<1e-6||Math.abs((h*e.dx+u*e.dz)/d)<i)continue;const f=Math.max(0,Math.min(1,((e.x-o.x)*h+(e.z-o.z)*u)/(d*d))),p=Math.hypot(e.x-(o.x+h*f),e.z-(o.z+u*f));p<=Cs.NEAR_M&&(a===void 0||p<a)&&(a=p)}a!==void 0&&s.push({way:n,distance:a})}return s.sort((n,a)=>n.distance-a.distance).map(({way:n})=>n)}}class dl{attribution="Railways © OpenStreetMap contributors, as surveyed today";contemporary=!0;static KINDS=["rail","light_rail","tram","subway","narrow_gauge","funicular","preserved"];client;constructor(t={}){this.client=new Sn(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${dl.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${Cs.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=Cs.servicesByWay(t);for(const s of t.elements??[]){const n=s.geometry,a=s.tags;if(s.type==="relation"||!a||!n||n.length<2)continue;const r=[...i.get(s.id??-1)??[]].sort(),o=Cs.voltageOf(a),l=dl.kindOf(a),h=Number.parseInt((a.gauge??"").split(";")[0],10),u=Number.parseInt(a.tracks??"",10),d=dl.electrificationOf(a.electrified),f=a.highspeed==="yes"||Number.parseInt(a.maxspeed??"",10)>=250;e.push({id:`osm-rail-${s.id??e.length}`,...a.name?{name:a.name}:{},...r.length>0?{services:r}:{},...o?{voltageV:o}:{},kind:l,...a.service||a.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:a.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:dl.levelOf(a),points:n.map(p=>({lat:p.lat,lng:p.lon}))})}return e}static kindOf(t){switch(t.railway){case"tram":return"tram";case"subway":return"subway";case"light_rail":return"light_rail";case"funicular":return"funicular";default:return"rail"}}static electrificationOf(t){if(t!==void 0){if(t==="no")return"none";if(t==="contact_line"||t==="yes")return"overhead";if(t==="rail"||t==="4th_rail"||t==="ground-level_power_supply")return"third_rail"}}static levelOf(t){const e=Number.parseInt(t.layer??"",10);return t.tunnel&&t.tunnel!=="no"?Number.isFinite(e)&&e<0?e:-1:t.covered==="yes"&&t.location==="underground"?-1:t.bridge&&t.bridge!=="no"?Number.isFinite(e)&&e>0?e:1:0}}class uA{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Railways © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere, as drawn today";contemporary=!0;async getRailways(t){if(!ao.covers(t))return this.worldwide.getRailways(t);let e;try{if(e=await this.regional.getRailways(t),e.length>0)return e}catch{}try{return await this.worldwide.getRailways(t)}catch(i){if(e)return e;throw i}}}class ts{constructor(t,e=Date.now){this.railways=t,this.now=e}static CACHE_NAME="rr0-railways";static MAX_AGE_MS=720*3600*1e3;static FORMAT=1;static MAX_STORED=400;static RETRY_AFTER_MS=300*1e3;static asked=new Map;static failedAt=-1/0;get attribution(){return this.railways.attribution}get contemporary(){return this.railways.contemporary}async getRailways(t){const e=ts.key(t);let i=ts.asked.get(e)??ts.containing(t);if(i===void 0){const s=this.recalled(e,t);i={bounds:t,answer:s},ts.asked.set(e,i),s.catch(()=>ts.asked.delete(e))}return structuredClone(await i.answer)}static forget(){ts.asked.clear(),ts.failedAt=-1/0}static key(t){return`v${ts.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of ts.asked.values()){const i=e.bounds;if(i.north>=t.north&&i.south<=t.south&&i.east>=t.east&&i.west<=t.west)return e}}async recalled(t,e){const i=await ts.openCache(),s=ts.request(t);let n;if(i)try{const r=await i.match(s);if(r){const{savedAt:o,lines:l}=await r.json();if(Array.isArray(l)){if(this.now()-o<ts.MAX_AGE_MS)return l;n=l}}}catch{}if(this.now()-ts.failedAt<ts.RETRY_AFTER_MS){if(n)return n;throw new Error("The railway survey failed a moment ago: not asked again yet")}let a;try{a=await this.railways.getRailways(e)}catch(r){if(ts.failedAt=this.now(),n)return n;throw r}return i&&ts.store(i,s,{savedAt:this.now(),lines:a}),a}static async store(t,e,i){try{await t.delete(e),await t.put(e,new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const n of s.slice(0,Math.max(0,s.length-ts.MAX_STORED)))await t.delete(n)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(ts.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const C0="https://ufoathome.org/railways/index.json";class fl{contemporary=!0;attributionRead;fetchImpl;indexUrls;fallback;index;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??fl.defaultIndexUrls(),this.fallback=t.fallback}get attribution(){return this.attributionRead??this.fallback?.attribution??"Railways © OpenStreetMap contributors"}async getRailways(t){const e=await this.held(t);if(e)return e;if(!this.fallback)return[];const i=await this.fallback.getRailways(t);return this.attributionRead=this.fallback.attribution,i}async held(t){const i=(await this.load().catch(()=>[])).find(({entry:s})=>s.north>=t.north&&s.south<=t.south&&s.east>=t.east&&s.west<=t.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 t=this.indexUrls.join(`
|
|
1570
|
+
`);let e=fl.shared.get(t);return e||(e=this.fetchFirstAvailable(),fl.shared.set(t,e),e.then(i=>{i.length===0&&fl.shared.delete(t)})),this.index=e}async fetchFirstAvailable(){for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;const i=await e.json();if(Array.isArray(i?.entries))return i.entries.map(s=>({entry:s,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.195.0")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==C0?[e,C0]:[C0]).map(i=>i+t)}}function hw(){return{elevation:uw(),imagery:dw(),roads:dA(),water:fA(),railways:pA()}}function uw(){return new rA(new De,new ow)}function dw(){return new lw}function dA(){return new hl({fallback:new lA(new no,new to)})}function fA(){return new ul({fallback:new mn(new hA(new fu,new zo))})}function pA(){return new fl({fallback:new ts(new uA(new ao,new dl))})}const mA=new Set,Cl="show-observer-map",Ol="hide-milestones",Xo="minified";class Ue extends HTMLElement{static get observedAttributes(){return["src",Cl,Ol,Xo]}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 li;observerMapDrag;suppressObserverMapClick=!1;observerMapImageryTimer;observerPlacing=!1;seekInput;playbackFlash;milestoneMarks;citedMarks;cited=[];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=px.create();issues=[];issueCheck=0;sightingAudio=new Wv;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new Wv(t)):this.liveSightingAudio&&(this.sightingAudio.dispose(),this.sightingAudio=this.liveSightingAudio,this.liveSightingAudio=void 0)}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>Ue.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 t=this.controlsRow,e=t.classList.contains("more-open"),i=()=>t.scrollWidth>t.clientWidth+1,s=!this.momentsMenu.hidden;if(this.momentsMenu.hidden=!0,t.classList.remove("narrow","more-open","nomoments","compact","tiny"),t.clientWidth>0&&i()){t.classList.add("narrow");for(const n of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(n)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!s,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Ue.setIcon(this.moreButton,t?jt.UNFOLDED:jt.FOLDED);const e=t?this.messages?.fewerControls??"":this.messages?.moreControls??"";this.moreButton.title=e,this.moreButton.setAttribute("aria-label",e),this.moreButton.setAttribute("aria-expanded",String(t))}addControl(t){this.controlsRight.insertBefore(t,this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null),this.fitControls()}videoElement;videoButton;set filmer(t){if(this.videoElement?.remove(),this.videoButton?.panel.remove(),this.videoButton=void 0,this.videoElement=void 0,!t){this.fitControls();return}const e=document.createElement("button");e.type="button",e.id="video-button",e.innerHTML=jt.VIDEO,this.videoElement=e,this.labelVideoButton(),e.addEventListener("click",i=>{i.stopPropagation(),this.loadVideoButton(t,e)},{once:!0}),this.moreButton.after(e),this.fitControls()}async loadVideoButton(t,e){const{VideoButton:i}=await Ht(async()=>{const{VideoButton:n}=await import("./VideoButton-DA48Qz2E.js");return{VideoButton:n}},__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url);if(this.videoElement!==e)return;const s=new i(t,e);this.videoButton=s,this.messages&&(s.messages=this.messages),this.stageElement.append(s.panel),s.open()}labelVideoButton(){const t=this.videoElement;!t||this.videoButton||(t.title=this.messages?.recordVideo??"",t.setAttribute("aria-label",t.title))}get filmDescription(){return this.messages?.videoDescription}get hasObserverMap(){return this.observerPath!==void 0}mapBeforeFilm;filmMap(t){t!==void 0?(this.mapBeforeFilm??=!this.observerMapPanel.hidden,t&&this.observerPath&&this.setObserverMapOpen(!0)):this.mapBeforeFilm!==void 0&&(this.setObserverMapOpen(this.mapBeforeFilm&&this.observerPath!==void 0),this.mapBeforeFilm=void 0)}filmChrome(t){const e=this.currentTime,i=t.caption&&this.sighting.milestones.length>0?Uu(this.sighting.milestones,e):void 0,s=i?this.said.read(i.label)??"":void 0,n=this.canvas.getBoundingClientRect(),a=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:s,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...a&&n.width>0&&n.height>0?{map:{canvas:this.observerMapCanvas,left:(a.left-n.left)/n.width,top:(a.top-n.top)/n.height,width:a.width/n.width,height:a.height/n.height}}:{}}}observerMapResizeObserver=typeof ResizeObserver>"u"?void 0:new ResizeObserver(()=>this.resizeObserverMap());resizeObserverMap(){this.observerMapPanel.hidden||(this.sizeObserverMapCanvas(),this.paintObserverMap(this.currentTime))}simulatedFullscreen=!1;styleBeforeSimulatedFullscreen;bodyOverflowBeforeSimulatedFullscreen;handleSimulatedFullscreenKey=t=>{t.key==="Escape"&&this.exitSimulatedFullscreen()};handlePointerMove=t=>{const e=this.canvasPointFromEvent(t),i=e&&this.shapeAt(e.x,e.y),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=`${t.clientX-n.left+12}px`,this.tooltip.style.top=`${t.clientY-n.top+12}px`};handleObserverMapPointerMove=t=>{if(this.dragObserverMap(t))return;const e=this.observerMapTargetFrom(t);if(!e){if(!this.observerPlacing){this.tooltip.hidden=!0,this.observerMapCanvas.style.cursor="grab";return}this.observerMapCanvas.style.cursor="crosshair",this.showObserverMapTooltip(t,this.messages?.placeObserverHere??"");return}this.observerMapCanvas.style.cursor="pointer",this.showObserverMapTooltip(t,e.label)};showObserverMapTooltip(t,e){this.tooltip.textContent=e,this.tooltip.hidden=!1;const i=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-i.left+12}px`,this.tooltip.style.top=`${t.clientY-i.top+12}px`}handleObserverMapClick=t=>{if(this.suppressObserverMapClick){this.suppressObserverMapClick=!1;return}const e=this.observerMapTargetFrom(t);if(!e){this.observerPlacing&&this.placeObserverFrom(t);return}if(e.kind==="milestone"&&e.t!==void 0){this.player.seek(e.t);return}this.dispatchEvent(new CustomEvent("lookat",{detail:{lat:e.lat,lng:e.lng,kind:e.kind},bubbles:!0,composed:!0}))};observerMapTargetFrom(t){const e=this.observerMapCanvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return this.observerMapRenderer.hitTest((t.clientX-e.left)/e.width*this.observerMapCanvas.width,(t.clientY-e.top)/e.height*this.observerMapCanvas.height)}handlePointerLeave=()=>{this.tooltip.hidden=!0};handleObserverMapPointerDown=t=>{t.button===0&&(this.suppressObserverMapClick=!1,this.observerMapDrag={pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,moved:!1})};handleObserverMapPointerUp=t=>{const e=this.observerMapDrag;!e||e.pointerId!==t.pointerId||(this.observerMapDrag=void 0,this.observerMapCanvas.classList.remove("dragging"),e.moved&&(this.suppressObserverMapClick=!0,this.paintObserverMap(this.currentTime),this.observerMapCanvas.hasPointerCapture?.(t.pointerId)&&this.observerMapCanvas.releasePointerCapture(t.pointerId)))};dragObserverMap(t){const e=this.observerMapDrag;if(!e||e.pointerId!==t.pointerId)return!1;if(!e.moved){if(Math.hypot(t.clientX-e.startX,t.clientY-e.startY)<Ue.OBSERVER_MAP_DRAG_PX)return!1;e.moved=!0,this.tooltip.hidden=!0,this.observerMapCanvas.classList.add("dragging"),this.observerMapCanvas.setPointerCapture?.(t.pointerId)}const i=this.observerMapCanvas.getBoundingClientRect();return i.width>0&&i.height>0&&(this.observerMapView.panBy((t.clientX-e.lastX)/i.width,(t.clientY-e.lastY)/i.height),this.observerMapViewChanged()),e.lastX=t.clientX,e.lastY=t.clientY,!0}static OBSERVER_MAP_DRAG_PX=4;handleObserverMapWheel=t=>{t.preventDefault();const e=this.observerMapCanvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=t.deltaMode===0?t.deltaY:t.deltaY*40;this.zoomObserverMap((t.clientX-e.left)/e.width,(t.clientY-e.top)/e.height,Math.exp(-i*.002))};zoomObserverMap(t,e,i){this.observerMapView.zoomAt(t,e,i),this.observerMapViewChanged()}observerMapViewChanged(){this.mapFitButton.hidden=!this.observerMapView.changed,this.mapZoomInButton.disabled=this.observerMapView.zoomFactor>=li.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=li.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Ue.OBSERVER_MAP_IMAGERY_DELAY_MS))}static OBSERVER_MAP_FOLLOW_MARGIN=.1;static OBSERVER_MAP_IMAGERY_DELAY_MS=300;get observerMapViewBounds(){return this.observerMapBounds&&this.observerMapView.boundsWithin(this.observerMapBounds)}placeObserverFrom(t){const e=this.observerMapViewBounds,i=this.observerMapCanvas.getBoundingClientRect();if(!e||i.width===0||i.height===0)return;const s=li.pointAt(e,(t.clientX-i.left)/i.width,(t.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 t=document.createElement("template");t.innerHTML=`<style>${BE}</style>${zE}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Gl(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",r=>{r.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 Uo(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.citedMarks=this.shadow.getElementById("cited-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",r=>{r.key!=="Enter"&&r.key!==" "||(r.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),s=r=>{const o=i.getBoundingClientRect(),l=this.player.seekableDuration;if(o.width<=0||l<=0)return;const h=Math.min(Math.max((r.clientX-o.left)/o.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let n=!1;e.addEventListener("pointerdown",r=>{r.button===0&&(r.stopPropagation(),e.setPointerCapture(r.pointerId),e.classList.add("scrubbing"),n=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,s(r))}),e.addEventListener("pointermove",r=>{e.hasPointerCapture(r.pointerId)&&s(r)});const a=r=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(r.pointerId)&&e.releasePointerCapture(r.pointerId),this.miniScrubTime.hidden=!0,n&&this.play())};e.addEventListener("pointerup",a),e.addEventListener("pointercancel",a),e.addEventListener("click",r=>r.stopPropagation()),this.miniMuteButton.addEventListener("click",r=>{r.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",r=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(r),this.seekPreview.hidden=!0,this.beginTouchScrub(r)}),this.seekInput.addEventListener("pointerup",r=>{this.seekSnapArmed=!1,this.endTouchScrub(r)}),this.seekInput.addEventListener("pointercancel",r=>this.endTouchScrub(r)),this.seekInput.addEventListener("pointermove",r=>{this.nameMarkUnder(r),this.hoverSeek(r),this.touchScrub(r)}),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 r of["touchend","click"])this.stageElement.addEventListener(r,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",r=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}r.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",r=>{!this.enableClickToPlay||this.minified||(r.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 t=this.getAttribute("src");t&&this.loadFromSrc(t)}disconnectedCallback(){document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("pointerdown",this.handleMomentsDismiss,!0),document.removeEventListener("keydown",this.handleMomentsDismiss,!0),document.removeEventListener("visibilitychange",this.handleVisibility),window.removeEventListener("pagehide",this.handleHidden),document.removeEventListener("pointerup",this.handlePointerRelease,!0),document.removeEventListener("pointercancel",this.handlePointerRelease,!0),window.clearTimeout(this.controlsIdleTimer),this.observerMapResizeObserver?.disconnect(),this.chromeResizeObserver?.disconnect(),this.controlsFitObserver?.disconnect(),this.controlsMutations?.disconnect(),this.exitSimulatedFullscreen(),this.sightingAudio.dispose()}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),t===Cl&&this.applyObserverMapDefault(),t===Ol&&this.setMilestonesShown(!this.hasAttribute(Ol)),t===Xo){const s=this.minified;this.stageElement.classList.toggle("minified",s),s&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Xo)}miniPlayed;miniRemaining;miniMuteButton;handleMinifiedEnter=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!0,this.play())};minifiedHovered=!1;handleMinifiedLeave=t=>{!this.minified||t.pointerType==="touch"||(this.minifiedHovered=!1,this.pause(),this.dispatchEvent(new CustomEvent(pw)))};started=!1;updateStartState(){this.playRequested&&(this.started=!0);const t=!this.started&&this.enableClickToPlay;this.stageElement.classList.toggle("unstarted",t),t&&!this.minified?this.canvas.title=this.messages?.clickToPlay??"":this.canvas.removeAttribute("title")}async loadFromSrc(t){this.sightingData=await dx.recording(t)}get sightingData(){return Yx(this.currentSighting)}set sightingData(t){const e=s1.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=g1(e),this.observerMapSnapshotSource&&(this.observerMapSnapshot=this.observerMapSnapshotSource(this.currentSighting.snapshots)),this.issuesPanel.hidden=!0,this.issuesButton.setAttribute("aria-expanded","false"),this.reportIssues(e,this.currentSighting),this.observerMapView.reset(),this.mapFitButton.hidden=!0,this.observerMapAsked=!1,this.player=this.createPlayer(),this.started=!1,this.syncPlayerTitle(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.refresh(),this.applyObserverMapDefault(),this.minified&&this.minifiedHovered&&this.play()}set playerTitle(t){this.titleOverride=t,this.syncPlayerTitle()}titleOverride;set titleShown(t){this.titleHidden=!t,this.syncPlayerTitle()}get titleShown(){return!this.titleHidden}titleHidden=!1;syncPlayerTitle(){const t=this.said.read(this.titleOverride)??this.said.read(this.currentSighting.observer?.title)??"";this.playerTitleBox.textContent=t,this.playerTitleBox.hidden=t===""||this.titleHidden}get recordingIssues(){return this.issues}async reportIssues(t,e){const i=++this.issueCheck;let s=[];try{const{default:n}=await Ht(async()=>{const{default:a}=await import("./sightingSchema-CgwoRMl-.js");return{default:a}},[],import.meta.url);s=new Yn(n).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...s,...e.loadIssues],Mv.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(vA,{detail:{issues:this.issues},bubbles:!0,composed:!0})))}renderIssues(){if(!this.messages)return;const t=this.issues.length;this.issuesBox.hidden=t===0,this.shadow.getElementById("issues-count").textContent=String(t);const e=(this.messages?.recordingIssues??"").replace("{count}",String(t));this.issuesButton.title=e,this.issuesButton.setAttribute("aria-label",e),this.shadow.getElementById("issues-title").textContent=e,this.shadow.getElementById("issues-list").replaceChildren(...this.issues.map(i=>{const s=document.createElement("li");return s.textContent=Mv.text(i,this.messages.issueTemplates),s}))}get sighting(){return this.currentSighting}previewSound(t){this.soundPreview=t,this.sightingAudio.resume(),this.sightingAudio.setSound(t)}stopSoundPreview(){this.soundPreview=void 0,this.sightingAudio.silence()}get canvasElement(){return this.canvas}get renderer(){return this.canvasRenderer}get currentTime(){return this.player.time}set currentTime(t){this.player.seek(t)}get seekableDuration(){return this.player.seekableDuration}get autoReplayEnabled(){return this.loopEnabled}set autoReplayEnabled(t){t!==this.loopEnabled&&this.toggleLoop()}play(){if(!(this.player.seekableDuration<=0||this.playbackState==="playing")){if(this.clockHeld){this.playAfterHold=!0,this.announcePlayRequest();return}this.togglePlayPause()}}get playRequested(){return this.playbackState==="playing"||this.playAfterHold}announcePlayRequest(){this.announceReveal(),this.dispatchEvent(new CustomEvent("playrequest"))}announceReveal(){this.started=!0,this.updateStartState(),this.dispatchEvent(new CustomEvent("revealrequest"))}clockHeld=!1;playAfterHold=!1;holdClock(t){if(t!==this.clockHeld){if(this.clockHeld=t,t){if(this.playbackState!=="playing")return;this.playAfterHold=!0,this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton();return}this.playAfterHold&&(this.playAfterHold=!1,!(this.player.seekableDuration<=0||this.playbackState==="playing")&&(this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton()))}}pause(){this.playAfterHold=!1,this.playbackState==="playing"&&this.togglePlayPause()}get positionLabel(){return this.timeStartLabel.textContent??""}get durationLabel(){return this.timeEndLabel.textContent??""}get showingClockTime(){return this.canShowClockTime}get canSwitchTimeDisplay(){return this.realStartMs!==void 0}set citedMoments(t){this.cited=[...t],this.refreshCitedMarks()}refreshCitedMarks(){const t=this.player.seekableDuration;this.citedMarks.replaceChildren(...(t>0?this.cited:[]).map(e=>{const i=document.createElement("button");i.type="button",i.className="cited-mark",i.innerHTML=sS.INTERVIEW,i.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const s=e.quote??"";return i.title=s,i.setAttribute("aria-label",s),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Ue.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(gA,{bubbles:!0,composed:!0,detail:{at:t/1e3}})))}toggleTimeDisplay(){this.canSwitchTimeDisplay&&(this.showClockTime=!this.showClockTime,this.updateTimeLabels(),this.updateTimeLabelTitles(),this.dispatchEvent(new CustomEvent("timedisplaychange",{bubbles:!0,composed:!0})))}get canShowClockTime(){return this.realStartMs!==void 0&&this.showClockTime}set showToolbar(t){this.toolbar.classList.toggle("hidden",!t),t?this.controlsRight.appendChild(this.fullscreenButton):this.cornerButtons.appendChild(this.fullscreenButton)}get playbackState(){return this.player.playbackState}get playbackRate(){return this.player.playbackRate}get selectedSourceIds(){return this.highlightedSourceIds}get durationSeconds(){return this.currentSighting.event.durationSeconds}set durationSeconds(t){this.currentSighting.event.durationSeconds=t,this.updateTimeLabels(),this.refresh(),this.updatePlayPauseButton()}set selectedSourceIds(t){const e=new Set(t);e.size===this.highlightedSourceIds.size&&[...e].every(s=>this.highlightedSourceIds.has(s))||(this.highlightedSourceIds=e,this.refresh())}hasVisibleShapeAt(t,e){return this.shapeAt(t,e)!==void 0}refresh(){this.applyFrameFormat(),this.updateMuteButton(),this.updateTimeLabels(),this.seekInput.max=String(this.player.seekableDuration),this.refreshMilestoneMarks(),this.updateMilestonesButton(),this.updateObserverMap(),this.updateReferences(),this.updateTracesButton(),this.player.seek(this.player.time)}repaintOverlay(){this.quietFrame=!0;try{this.player.seek(this.player.time)}finally{this.quietFrame=!1}}quietFrame=!1;hostControls(t){const e=[this.milestonesButton,this.referencesButton,this.referenceOpacityInput,this.tracesButton,this.observerMapButton];if(t)for(const i of e)t.appendChild(i);else{const i=this.fullscreenButton.parentElement===this.controlsRight?this.fullscreenButton:null;for(const s of e)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 t=this.currentSighting.references;if(!this.referenceOpacityTouched&&t.length>0){const e=String(t[0].opacity);this.referenceOpacityInput.value!==e&&(this.referenceOpacityInput.value=e,this.severalReferences||this.dispatchReferenceView())}for(const e of[...this.referenceViews.keys()])t.some(i=>i.id===e)||this.referenceViews.delete(e);this.severalReferences?this.referencesMenu.hidden||this.renderReferencesMenu():this.closeReferencesMenu(),this.updateReferencesButton(),this.severalReferences&&this.dispatchReferenceView()}viewOfReference(t){let e=this.referenceViews.get(t.id);return e||(e={shown:!0,opacity:t.opacity},this.referenceViews.set(t.id,e)),e}toggleReferencesMenu(){this.referencesMenu.hidden?this.openReferencesMenu():this.closeReferencesMenu()}openReferencesMenu(){this.renderReferencesMenu(),this.referencesMenu.hidden=!1,this.placeReferencesMenu(),this.referencesButton.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.addEventListener("keydown",this.handleReferencesMenuKey,!0)}closeReferencesMenu(){this.referencesMenu.hidden||(this.referencesMenu.hidden=!0,this.referencesButton.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this.handleReferencesMenuOutside,!0),document.removeEventListener("keydown",this.handleReferencesMenuKey,!0))}handleReferencesMenuOutside=t=>{const e=t.composedPath();e.includes(this.referencesMenu)||e.includes(this.referencesButton)||this.closeReferencesMenu()};handleReferencesMenuKey=t=>{t.key==="Escape"&&(this.closeReferencesMenu(),this.referencesButton.focus())};placeReferencesMenu(){const t=this.referencesButton.getBoundingClientRect(),e=this.referencesMenu,i=4;e.style.bottom=`${Math.max(i,window.innerHeight-t.top+i)}px`,e.style.top="auto";const s=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-s-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),s=this.said.read(e.title)??e.id,n=document.createElement("div");n.className="reference-row";const a=document.createElement("label"),r=document.createElement("input");r.type="checkbox",r.checked=i.shown;const o=document.createElement("span");o.textContent=s,o.title=s,a.append(r,o);const l=document.createElement("input");return l.type="range",l.min="0",l.max="1",l.step="0.05",l.value=String(i.opacity),l.title=this.messages?.referenceOpacity??"",l.setAttribute("aria-label",`${this.messages?.referenceOpacity??""}: ${s}`),l.disabled=!i.shown,r.addEventListener("change",()=>{i.shown=r.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),n.append(a,l),n});this.referencesMenu.setAttribute("aria-label",this.messages?.referencesMenu??""),this.referencesMenu.replaceChildren(...t)}updateReferencesButton(){const t=this.currentSighting.references.length>0,e=this.severalReferences,i=e?this.currentSighting.references.some(n=>this.viewOfReference(n).shown):this.referencesShownState;this.referencesButton.hidden=!t,this.referenceOpacityInput.hidden=!t||!this.referencesShownState||e,this.referencesButton.setAttribute("aria-pressed",String(i)),e?this.referencesButton.setAttribute("aria-haspopup","true"):this.referencesButton.removeAttribute("aria-haspopup"),Ue.setIcon(this.referencesButton,i?jt.PICTURES_ON:jt.PICTURES_OFF);const s=e?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)),Ue.setIcon(this.tracesButton,this.tracesShownState?jt.TRACES_ON:jt.TRACES_OFF);const t=this.tracesShownState?this.messages?.hideTraces??"":this.messages?.showTraces??"";this.tracesButton.title=t,this.tracesButton.setAttribute("aria-label",t)}dispatchReferenceView(){const t=this.severalReferences?Object.fromEntries(this.currentSighting.references.map(e=>[e.id,{...this.viewOfReference(e)}])):void 0;this.dispatchEvent(new CustomEvent("referenceview",{detail:{shown:this.referencesShown,opacity:this.referenceOpacity,views:t}}))}refreshMilestoneMarks(){const t=this.player.seekableDuration,e=t>0?Hh(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const s=document.createElement("button");s.type="button",s.className="milestone-mark",s.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const n=this.said.read(i.label)??"",a=this.said.read(i.note),r=a?`${n} — ${a}`:n;return s.title=r,s.setAttribute("aria-label",r),s.dataset.t=String(i.t),s.addEventListener("click",()=>this.player.seek(i.t)),s})),this.refreshCitedMarks(),this.refreshSeekSegments(t,e.map(i=>i.t)),this.refreshMomentsPicker(e)}refreshMomentsPicker(t){const e=this.milestonesShown&&t.length>0;this.momentsBox.hidden=!e,this.closeMomentsMenu(),this.momentsMenu.replaceChildren(...t.map(i=>{const s=document.createElement("li"),n=document.createElement("button");n.type="button",n.dataset.t=String(i.t);const a=this.said.read(i.label)??"",r=this.said.read(i.note);return n.textContent=r?`${a} — ${r}`:a,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(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const s of this.momentsMenu.querySelectorAll("button")){const n=t!==void 0&&Number(s.dataset.t)===t.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=t=>{if(!this.momentsMenu.hidden){if(t instanceof KeyboardEvent){t.key==="Escape"&&this.closeMomentsMenu();return}t.composedPath().some(e=>e===this.momentsMenu||e===this.momentsButton)||this.closeMomentsMenu()}};seekSegmentList=[];refreshSeekSegments(t,e){const s=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(a=>a>0&&a<t))].sort((a,r)=>a-r):[],Math.max(t,0)];this.seekSegmentList=[];const n=[];for(let a=0;a<s.length-1;a++){const r=document.createElement("div");r.className="seek-segment",r.style.flexGrow=String(Math.max(s[a+1]-s[a],1));const o=document.createElement("i");o.className="seek-hover";const l=document.createElement("i");l.className="seek-played",r.append(o,l),n.push(r),this.seekSegmentList.push({start:s[a],end:s[a+1],element:r,played:l,hover:o})}this.seekSegments.replaceChildren(...n),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,s=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(s,0),1)*100}%`}paintMiniProgress(t){const e=this.player.seekableDuration,i=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`;this.miniPlayed.style.width=i,this.miniDot.style.left=i,this.miniRemaining.textContent=this.formatRemaining(t)}miniDot;miniScrubTime;paintSeekProgress(t){for(const i of this.seekSegmentList)i.played.style.width=Ue.fillOf(i,t);const e=this.player.seekableDuration;this.seekDot.style.left=`${e>0?Math.min(Math.max(t/e,0),1)*100:0}%`}hoverSeek(t){if(t.buttons!==0){this.seekPreview.hidden=!0;return}const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),n=s*i,a=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Ue.fillOf(f,n),f.element.classList.toggle("hovered",n>=f.start&&(n<f.end||p===a))});const r=this.milestonesShown?this.sighting.milestones:[],o=r.length>0?Uu(r,n):void 0,l=o?this.said.read(o.label)??"":"",h=o?this.said.read(o.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(n),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(s*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(n)}leaveSeek(){for(const t of this.seekSegmentList)t.hover.style.width="0",t.element.classList.remove("hovered");this.seekPreview.hidden=!0}seekPreviewPainter;paintSeekPreview(t){const e=this.seekPreviewPainter;this.seekPreviewCanvas.hidden=e===void 0,e?.(t,this.seekPreviewCanvas)}paintChrome(t){const e=this.chromeCanvas.getContext("2d"),i=this.overlayPainter!==void 0||this.selectionShown;if(!i&&!this.chromeDirty)return;const s=this.chromeCanvas.clientWidth,n=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||s===0||n===0){t(this.canvasRenderer);return}const a=window.devicePixelRatio||1,r=Math.max(1,Math.round(s*a)),o=Math.max(1,Math.round(n*a));this.chromeCanvas.width!==r&&(this.chromeCanvas.width=r),this.chromeCanvas.height!==o&&(this.chromeCanvas.height=o),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,r,o),this.chromeDirty=!1,i&&(e.setTransform(r/this.canvas.width,0,0,o/this.canvas.height,0,0),this.chromeRenderer??=new Gl(e),this.chromeDirty=!0,t(this.chromeRenderer))}chromeDraw;repaintChrome(){this.chromeDraw&&this.overlayPainter&&this.paintChrome(this.chromeDraw)}scrubbingPointer;beginTouchScrub(t){if(t.pointerType!=="mouse"){this.scrubbingPointer=t.pointerId;try{this.seekInput.setPointerCapture(t.pointerId)}catch{}this.seekToPointer(t)}}touchScrub(t){t.pointerId===this.scrubbingPointer&&this.seekToPointer(t)}endTouchScrub(t){t.pointerId===this.scrubbingPointer&&(this.scrubbingPointer=void 0,this.seekToPointer(t))}seekToPointer(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(s*i))}seekSnapArmed=!1;static MARK_SNAP_PX=6;markNear(t){const e=this.player.seekableDuration,i=this.seekInput.getBoundingClientRect().width;if(e<=0||i<=0)return;const s=Ue.MARK_SNAP_PX/i*e;let n;for(const a of this.milestoneMarks.children){const r=Number(a.dataset.t);Math.abs(r-t)>s||(!n||Math.abs(r-t)<Math.abs(n.t-t))&&(n={t:r,name:a.title})}return n}snapSeekToMark(t){return this.seekSnapArmed?(this.seekSnapArmed=!1,this.markNear(t)?.t??t):t}nameMarkUnder(t){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const s=(t.clientX-e.left)/e.width*i,n=this.markNear(s);n?this.seekInput.title=n.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?Uu(this.sighting.milestones,t):void 0;if(this.milestoneCaption.hidden=e===void 0,this.showCurrentMoment(e),!e)return;const i=document.createElement("b");i.textContent=this.said.read(e.label)??"";const s=this.said.read(e.note),n=s?` — ${s}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(n))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(s=>({shapes:this.shapesAt(s),share:i}))}exposureTimes(t=this.currentTime){const e=Xs.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Ue.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Ue.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Ue.SHORTEST_VISIBLE_EXPOSURE_MS))),s=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Ue.EXPOSURE_STEP_PX),n=Math.min(Ue.MAX_TRAVEL_STEPS,Math.max(i,s)),a=[];for(let r=0;r<n;r++)a.push(e.fromMs+e.ms*r/(n-1));return a}travelPxOver(t,e){const i=this.shapesAt(t),s=this.shapesAt(t+e);let n=0;for(const[a,r]of i){const o=s.get(a);if(!o)continue;const l=o.bounds.x+o.bounds.width/2-(r.bounds.x+r.bounds.width/2),h=o.bounds.y+o.bounds.height/2-(r.bounds.y+r.bounds.height/2);n=Math.max(n,Math.hypot(l,h))}return n}shapeAt(t,e,i){if(!this.accountHidden)for(const s of this.exposureTimes()){const n=this.currentSighting.timeline.hitTest(s,t,e,i);if(n)return n}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const s=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);s&&e.set(i,s)}return e}static SHORTEST_VISIBLE_EXPOSURE_MS=20;static MAX_EXPOSURE_STEPS=48;static EXPOSURE_STEP_PX=2;static MAX_TRAVEL_STEPS=320;applyFrameFormat(){const t=Ts.frameWidthPx(this.currentSighting.instrument,this.canvas.height);if(this.canvas.width===t)return;this.canvas.width=t,this.canvas.parentElement?.style.setProperty("--frame-aspect",`${t} / ${this.canvas.height}`)}canvasPointFromEvent(t){const e=this.canvas.getBoundingClientRect();if(!(e.width===0||e.height===0))return{x:(t.clientX-e.left)/e.width*this.canvas.width,y:(t.clientY-e.top)/e.height*this.canvas.height}}timeSaid=Number.NEGATIVE_INFINITY;static TIME_SAID_EVERY_MS=100;onFrame(t,e){this.sayTimeMoved(t),this.canvasRenderer.clear(this.canvas.width,this.canvas.height);const i=this.playbackState!=="playing"?this.highlightedSourceIds:mA;this.canvasRenderer.setStarPoints(Ts.starPointsOf(this.sighting.instrument,Te(this.sighting,t)?.fNumber));const s=(Te(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(s*Math.PI/180);const n=this.exposureInstants(t),a=this.frameShift;if(this.paintsShapes)for(const o of n)for(const[,l]of o.shapes){const h=o.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,a))}for(const[o,l]of n[0].shapes)!this.selectionShown||!i.has(o)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,a)));const r=this.selectionShown&&i.size>1?cn.groupBoundsFor([...e].filter(([o])=>i.has(o)).map(([,o])=>o.bounds)):void 0;this.chromeDraw=o=>{r&&o.paintGroupHandles(r),this.overlayPainter?.(o)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=n.flatMap(o=>[...o.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,a).bounds)),this.keepObserverMapClear(),this.seekInput.value=String(t),this.paintSeekProgress(t),this.minified&&this.paintMiniProgress(t),this.timeStartLabel.textContent=this.formatPosition(t),this.showMilestoneAt(t),this.paintObserverMap(t),this.playbackState==="playing"||this.liveSightingAudio?(this.soundPreview=void 0,this.sightingAudio.setSound(mx(this.currentSighting,t))):this.soundPreview?this.sightingAudio.setSound(this.soundPreview):this.sightingAudio.silence(),this.updatePlayPauseButton(),!this.quietFrame&&this.dispatchEvent(new CustomEvent("timeupdate",{detail:{time:t}}))}shifted(t,e){return e.x===0&&e.y===0?t:{...t,bounds:{...t.bounds,x:t.bounds.x+e.x,y:t.bounds.y+e.y}}}createPlayer(){const t=new HE(this.currentSighting.timeline,(e,i)=>this.onFrame(e,i));return t.loop=this.loopEnabled,t.onEnded=()=>{this.updatePlayPauseButton(),this.dispatchEvent(new CustomEvent("ended",{bubbles:!0,composed:!0}))},t}static SEEK_KEY_STEP_MS=5e3;handleFullscreenKey=t=>{t.key.toLowerCase()!=="f"||t.altKey||t.ctrlKey||t.metaKey||!this.enableClickToPlay||t.composedPath().some(i=>i instanceof HTMLElement&&(i.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(i.tagName)&&i.type!=="range"))||(t.preventDefault(),this.toggleFullscreen())};handleSeekKey=t=>{if(t.altKey||t.ctrlKey||t.metaKey)return;const e=t.key==="ArrowLeft"?-1:t.key==="ArrowRight"?1:0;if(e){t.preventDefault();const i=this.player.seekableDuration;this.player.seek(Math.min(i,Math.max(0,this.player.time+e*Ue.SEEK_KEY_STEP_MS)))}else t.key===" "&&(t.preventDefault(),this.togglePlayPause())};togglePlayPause(){if(!(this.player.seekableDuration<=0)){if(this.player.playbackState==="playing")this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh();else if(this.clockHeld){this.playAfterHold=!this.playAfterHold,this.playAfterHold&&this.announcePlayRequest();return}else this.announcePlayRequest(),this.sightingAudio.resume(),this.player.play();this.updatePlayPauseButton(),this.flashPlayback()}}flashPlayback(){const t=this.playbackFlash;t.innerHTML=this.player.playbackState==="playing"?jt.PLAY:jt.PAUSE,t.classList.remove("flashing"),t.offsetWidth,t.classList.add("flashing")}static icons=new WeakMap;static setIcon(t,e){Ue.icons.get(t)!==e&&(Ue.icons.set(t,e),t.innerHTML=e)}set captionHeld(t){this.stageElement.classList.toggle("caption-held",t)}set controlsHeld(t){this.stageElement.classList.toggle("controls-held",t)}static CONTROLS_IDLE_MS=3e3;controlsIdleTimer;wasPlaying=!1;quietControlsValue=!1;get quietControls(){return this.quietControlsValue}set quietControls(t){this.quietControlsValue=t,this.stageElement.classList.toggle("quiet",t)}tapRevealedOnly=!1;get hoverless(){return typeof matchMedia=="function"&&matchMedia("(hover: none)").matches}touchedStage(){if(!this.hoverless)return;this.player.playbackState==="playing"&&!this.stageElement.classList.contains("touched")&&(this.tapRevealedOnly=!0),this.revealControls()}pointerHeld=!1;handlePointerDown=()=>{this.pointerHeld=!0};resumeAfterScrub=!1;suspendForScrub(){this.player.playbackState==="playing"&&(this.resumeAfterScrub=!0,this.stopPlaying())}stopPlaying(){this.player.pause(),this.soundPreview=void 0,this.sightingAudio.silence(),this.refresh(),this.updatePlayPauseButton()}resumeFromScrub(){this.resumeAfterScrub&&(this.resumeAfterScrub=!1,this.sightingAudio.resume(),this.player.play(),this.updatePlayPauseButton())}handleHidden=()=>{this.player.playbackState==="playing"&&this.stopPlaying(),this.resumeAfterScrub=!1};handleVisibility=()=>{document.visibilityState==="hidden"&&this.handleHidden()};handlePointerRelease=()=>{this.resumeAfterScrub&&window.setTimeout(()=>this.resumeFromScrub(),0),this.pointerHeld&&(this.pointerHeld=!1,this.hoverless&&this.stageElement.classList.contains("touched")&&this.revealControls())};revealControls(){this.stageElement.classList.add("touched"),window.clearTimeout(this.controlsIdleTimer),this.player.playbackState==="playing"&&(this.pointerHeld||!this.momentsMenu.hidden||(this.controlsIdleTimer=window.setTimeout(()=>{this.stageElement.classList.remove("touched"),this.tapRevealedOnly=!1},Ue.CONTROLS_IDLE_MS)))}updatePlayPauseButton(){const t=this.player.playbackState==="playing";this.stageElement.classList.toggle("paused",!t),t!==this.wasPlaying&&t&&this.hoverless&&(!this.quietControlsValue||this.stageElement.classList.contains("touched"))&&this.revealControls(),this.wasPlaying=t,this.updateStartState(),Ue.setIcon(this.playPauseButton,t?jt.PAUSE:jt.PLAY);const e=this.player.seekableDuration>0;this.playPauseButton.disabled=!e;const i=e?t?this.messages?.pause??"":this.messages?.play??"":this.messages?.noDuration??"";this.playPauseButton.title=i,this.playPauseButton.setAttribute("aria-label",i)}toggleLoop(){this.loopEnabled=!this.loopEnabled,this.player.loop=this.loopEnabled}restorePlayback(){const t=this.playbackBeforeClick;t&&(this.currentTime=t.time,t.state==="playing"?this.play():this.pause())}get canUseNativeFullscreen(){return typeof this.fullscreenTarget.requestFullscreen=="function"&&document.fullscreenEnabled}toggleFullscreen(){if(!this.canUseNativeFullscreen){this.simulatedFullscreen?this.exitSimulatedFullscreen():this.enterSimulatedFullscreen();return}document.fullscreenElement?document.exitFullscreen():this.fullscreenTarget.requestFullscreen().catch(t=>{console.error("<rr0-ufo>: requestFullscreen() failed —",t)})}enterSimulatedFullscreen(){const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen=t.getAttribute("style")??"",this.bodyOverflowBeforeSimulatedFullscreen=document.body.style.overflow;const e=t.style;e.setProperty("position","fixed"),e.setProperty("inset","0"),e.setProperty("margin","0"),e.setProperty("max-width","none"),e.setProperty("max-height","none"),e.setProperty("aspect-ratio","auto"),e.setProperty("z-index","2147483647"),e.setProperty("background","#000"),e.setProperty("width","100vw"),e.setProperty("width","100dvw"),e.setProperty("height","100vh"),e.setProperty("height","100dvh"),document.body.style.overflow="hidden",this.simulatedFullscreen=!0,document.addEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}exitSimulatedFullscreen(){if(!this.simulatedFullscreen)return;const t=this.fullscreenTarget;this.styleBeforeSimulatedFullscreen?t.setAttribute("style",this.styleBeforeSimulatedFullscreen):t.removeAttribute("style"),document.body.style.overflow=this.bodyOverflowBeforeSimulatedFullscreen??"",this.simulatedFullscreen=!1,document.removeEventListener("keydown",this.handleSimulatedFullscreenKey),this.updateFullscreenButton(),this.updateMuteButton()}toggleObserverMap(){const t=this.observerMapPanel.hidden;this.observerMapAsked=t,this.setObserverMapOpen(t),this.keepObserverMapClear(),this.dispatchEvent(new CustomEvent("observermapchange",{bubbles:!0,composed:!0,detail:{open:t}}))}get observerMapOpen(){return!this.observerMapPanel.hidden}get milestonesVisible(){return this.milestonesShown}observerMapAsked=!1;applyObserverMapDefault(){const t=this.getAttribute(Cl),e=t===null?this.sighting.observerMap??this.observerPath?.travels===!0:t!=="false";this.setObserverMapOpen(e&&this.observerPath!==void 0)}setObserverMapOpen(t){this.observerMapPanel.hidden=!t,this.observerMapPanel.removeAttribute("title"),this.observerMapButton.setAttribute("aria-pressed",String(t)),this.updateObserverMapButton(),t&&(this.sizeObserverMapCanvas(),this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime))}updateObserverMapButton(){const t=!this.observerMapPanel.hidden;Ue.setIcon(this.observerMapButton,t?jt.MAP_ON:jt.MAP_OFF);const e=t?this.messages?.hideObserverMap??"":this.messages?.showObserverMap??"";this.observerMapButton.title=e,this.observerMapButton.setAttribute("aria-label",e);const i=[[this.mapZoomInButton,this.messages?.zoomMapIn??""],[this.mapZoomOutButton,this.messages?.zoomMapOut??""],[this.mapFitButton,this.messages?.fitMap??""]];for(const[s,n]of i)s.title=n,s.setAttribute("aria-label",n)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=Pl.of(this.currentSighting),this.observerMapButton.hidden=this.observerPath===void 0,!t&&this.observerPath&&this.applyObserverMapDefault(),!this.observerPath){this.setObserverMapOpen(!1),this.observerMapBounds=void 0;return}const e=this.tracesShownState?this.currentSighting.traces.flatMap(s=>s.points):[],i=li.fitted(this.observerPath,e);(!this.observerMapBounds||!this.sameGround(this.observerMapBounds,i))&&(this.observerMapBounds&&this.observerMapView.refit(this.observerMapBounds,i),this.observerMapBounds=i,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||this.loadObserverMapImagery())}sameGround(t,e){const i=Math.abs(t.east-t.west)/20;return Math.abs(t.north-e.north)<i&&Math.abs(t.south-e.south)<i&&Math.abs(t.west-e.west)<i&&Math.abs(t.east-e.east)<i}async loadObserverMapImagery(){const t=this.observerMapViewBounds;if(!t||this.observerMapPanel.hidden||this.observerMapImageryLoading||(this.observerMapSnapshotImagery?this.observerMapImageryBounds!==void 0:!this.observerMapImageryNeededFor(t)))return;const e=this.observerMapView.changed,i=e?li.expand(t,Ue.OBSERVER_MAP_IMAGERY_AHEAD):t,s=li.IMAGERY_PX*(e?1+2*Ue.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const n=this.observerMapSnapshotImagery,a=n?void 0:dw();try{const r=a?await a.getImageryTexture(i,{width:s,height:s}):await n.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=r,this.observerMapImageryCredit=(a??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(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,s=this.observerMapView.changed?li.expand(t,Ue.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,n=s.west>=i.west&&s.east<=i.east&&s.south>=i.south&&s.north<=i.north,a=t.east-t.west>this.observerMapImageryViewWidth/2;return!n||!a}get observerMapCredit(){return this.observerMapImageryCredit}set observerMapSnapshot(t){t!==this.observerMapSnapshotImagery&&(this.observerMapSnapshotImagery=t,this.observerMapImagery=void 0,this.observerMapImageryCredit=void 0,this.observerMapImageryFailed=!1,this.observerMapImageryBounds=void 0,this.observerMapImageryLoading=!1,this.observerMapPanel.hidden||(this.loadObserverMapImagery(),this.paintObserverMap(this.currentTime)))}get observerMapSnapshot(){return this.observerMapSnapshotImagery}observerMapSnapshotImagery;observerMapSnapshotSource;get observerMapFooterLine(){return this.observerMapImageryFailed?this.messages?.mapImageryUnavailable??"":this.creditShownExternally?void 0:this.observerMapImageryCredit}mapShapeBounds=[];mapSceneBounds=[];setMapSubjectBounds(t){this.mapSceneBounds=t.map(e=>({x:e.x*this.canvas.width,y:e.y*this.canvas.height,width:e.width*this.canvas.width,height:e.height*this.canvas.height})),this.keepObserverMapClear()}keepObserverMapClear(){if(this.observerMapPanel.hidden)return;const t=this.observerMapBoxPx;if(!t)return;const e=[...this.mapShapeBounds,...this.mapSceneBounds],i=(l,h,u)=>{for(const d of e)if(!(d.x+d.width<l-u||d.x>h+u)&&!(d.y>t.bottom+u||d.y+d.height<t.top-u))return!0;return!1},s=[this.canvas.width-t.width,this.canvas.width],n=[0,t.width],a=Ue.OBSERVER_MAP_CLEARANCE_PX,r=i(...s,0),o=i(...n,0);if(this.observerMapPanel.classList.toggle("subject-overlap",r&&o&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!r&&(o||!i(s[0],s[1],a))&&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 t=this.observerMapPanel.clientWidth;if(t===0)return;const e=Math.round(t*(globalThis.devicePixelRatio??1));this.measureObserverMapBox(),this.observerMapCanvas.width!==e&&(this.observerMapCanvas.width=e,this.observerMapCanvas.height=e)}measureObserverMapBox(){const t=this.observerMapPanel.getBoundingClientRect(),e=this.canvas.getBoundingClientRect();if(e.width===0||e.height===0)return;const i=this.canvas.width/e.width,s=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*s,bottom:(t.bottom-e.top)*s}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=Te(this.currentSighting,t);e?.lat!==void 0&&e.lng!==void 0&&!this.observerMapDrag?.moved&&this.observerMapView.keepInView(this.observerMapBounds,{lat:e.lat,lng:e.lng},Ue.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,s=[],n=this.currentSighting.milestones.length>0?Uu(this.currentSighting.milestones,t):void 0;for(const a of this.milestonesShown?Hh(this.currentSighting.milestones):[]){const r=Te(this.currentSighting,a.t);r?.lat===void 0||r.lng===void 0||s.push({label:this.said.read(a.label)??"",note:this.said.read(a.note),t:a.t,lat:r.lat,lng:r.lng,current:a===n})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position:e?.lat!==void 0&&e.lng!==void 0?{lat:e.lat,lng:e.lng}:void 0,headingDeg:e?.headingDeg===void 0?void 0:e.headingDeg+this.lookYawDeg,coneHalfAngleDeg:e?$a.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg(Ts.aspectOf(i)):void 0,markers:s,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(a=>({kind:a.kind,points:a.points,color:a.color,label:this.said.read(a.title)})),decor:this.observerMapDecorAt(t),observerLabel:this.said.read(this.currentSighting.observer?.title)??this.messages?.observerHere??"",nightFraction:this.observerMapNightFraction,attribution:this.observerMapFooterLine})}toggleMilestones(){this.setMilestonesShown(!this.milestonesShown)}setMilestonesShown(t){this.milestonesShown=t,this.milestoneMarks.hidden=!t,this.momentsBox.hidden=!t||this.sighting.milestones.length===0,this.refreshSeekSegments(this.player.seekableDuration,Hh(this.sighting.milestones).map(e=>e.t)),this.milestonesButton.setAttribute("aria-pressed",String(t)),this.updateMilestonesButton(),this.showMilestoneAt(this.currentTime),this.paintObserverMap(this.currentTime)}updateMilestonesButton(){this.milestonesButton.hidden=this.currentSighting.milestones.length===0,this.momentsButton.title=this.messages?.moments??"",Ue.setIcon(this.milestonesButton,this.milestonesShown?jt.MILESTONES_ON:jt.MILESTONES_OFF);const t=this.milestonesShown?this.messages?.hideMilestones??"":this.messages?.showMilestones??"";this.milestonesButton.title=t,this.milestonesButton.setAttribute("aria-label",t)}observerMapDecorAt(t){const e=Te(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const s=ga(i,t),{lat:n,lng:a}=Nn(s.eastM,-s.northM,e.lat,e.lng);return{lat:n,lng:a,headingDeg:s.headingDeg,label:this.said.read(i.title)??this.messages?.decorHere??""}})}observerMapNightFraction;setSunAltitude(t){const e=t===void 0?void 0:Math.max(0,Math.min(1,-t/12));e!==this.observerMapNightFraction&&(this.observerMapNightFraction=e,this.paintObserverMap(this.currentTime))}setLookOffset(t,e){t===this.lookYawDeg&&e===this.lookPitchDeg||(this.lookYawDeg=t,this.lookPitchDeg=e,this.refresh())}get frameShiftPx(){return this.frameShift}get frameShift(){const t=this.gaitAt(this.currentTime),e=this.lookYawDeg+t.yawDeg,i=this.lookPitchDeg+t.pitchDeg;if(e===0&&i===0)return{x:0,y:0};const s=Te(this.currentSighting,this.currentTime),n=$a.of(this.currentSighting.instrument,this.canvas.height,s?.fovDeg??60);return{x:-n.angleDegToRadiusPx(e),y:n.angleDegToRadiusPx(i)}}gaitAt(t){return ii.bodyAt(this.currentSighting,t,this.steadyBody)}mutedState=!1;get muted(){return this.mutedState}set muted(t){t!==this.mutedState&&(this.mutedState=t,!t&&this.volumeState===0&&(this.volumeState=Ue.RESTORED_VOLUME),this.applyLevel())}volumeState=1;static RESTORED_VOLUME=.5;get volume(){return this.volumeState}set volume(t){this.setVolume(t)}setVolume(t){this.volumeState=Math.min(Math.max(t,0),1),this.mutedState=this.volumeState===0,this.applyLevel()}get level(){return this.mutedState?0:this.volumeState}applyLevel(){this.sightingAudio.setLevel(this.level),this.updateMuteButton(),this.dispatchEvent(new CustomEvent("mutedchange",{bubbles:!0,composed:!0,detail:{muted:this.mutedState,volume:this.volumeState}}))}toggleMuted(){this.hasSound&&(this.muted=!this.mutedState)}ambientSound;get audible(){return this.hasSound}refreshSoundControls(){this.updateMuteButton()}get hasSound(){return this.currentSighting.soundTrack.allKeyframes.length>0||this.ambientSound?.(this.currentSighting)===!0}updateMuteButton(){const t=!this.hasSound;this.miniMuteButton.hidden=t,this.miniMuteButton.setAttribute("aria-pressed",String(this.mutedState)),Ue.setIcon(this.miniMuteButton,this.mutedState?jt.MUTED:jt.VOLUME);const e=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";if(this.miniMuteButton.title=e,this.miniMuteButton.setAttribute("aria-label",e),this.muteButton.disabled=t,this.volumeInput.hidden=t,t){Ue.setIcon(this.muteButton,jt.MUTED),this.muteButton.title=this.messages?.noSound??"",this.muteButton.setAttribute("aria-label",this.messages?.noSound??""),this.muteButton.setAttribute("aria-pressed","true");return}Ue.setIcon(this.muteButton,this.mutedState?jt.MUTED:jt.VOLUME);const i=this.mutedState?this.messages?.unmute??"":this.messages?.mute??"";this.muteButton.title=i,this.muteButton.setAttribute("aria-label",i),this.muteButton.setAttribute("aria-pressed",String(this.mutedState)),this.volumeInput.value=String(this.level)}updateFullscreenButton(){const t=this.simulatedFullscreen||document.fullscreenElement===this.fullscreenTarget;Ue.setIcon(this.fullscreenButton,t?jt.EXIT_FULLSCREEN:jt.ENTER_FULLSCREEN),this.fullscreenButton.title=t?this.messages?.exitFullscreen??"":this.messages?.fullscreen??"",this.fullscreenButton.setAttribute("aria-label",this.fullscreenButton.title)}get said(){return this.saidTexts??=new lu(Sr.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=zh(Sr.preferencesFor(this),Bh);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await tS.load(t);this.messagesLanguage===t&&this.applyMessages(e)}messagesLanguage;updateTimeLabelTitles(){const t=this.showClockTime?this.messages?.switchToElapsed??"":this.messages?.switchToClockTime??"",e=this.canSwitchTimeDisplay?` — ${t}`:"";this.timeStartLabel.title=(this.messages?.currentPosition??"")+e,this.timeEndLabel.title=(this.messages?.duration??"")+e,this.timePill.classList.toggle("switchable",this.canSwitchTimeDisplay),this.canSwitchTimeDisplay?(this.timePill.setAttribute("role","button"),this.timePill.setAttribute("tabindex","0")):(this.timePill.removeAttribute("role"),this.timePill.removeAttribute("tabindex"))}applyMessages(t){this.messages=t,this.videoButton&&(this.videoButton.messages=t),this.labelVideoButton(),this.volumeInput.title=t.volume,this.volumeInput.setAttribute("aria-label",t.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 t=this.currentSighting.event,e=gx(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?aS(t.time):void 0;const i=this.currentSighting.timeline.duration;this.player.playbackRate=this.realDurationMs!==void 0&&i>0?i/this.realDurationMs:1,this.player.durationOverrideMs=i>0?0:this.realDurationMs??0,this.timeEndLabel.textContent=this.formatEndOfTimeline(),this.timeStartLabel.textContent=this.formatPosition(this.player.time),this.paintMiniProgress(this.player.time),this.updateTimeLabelTitles()}formatPosition(t){if(this.realDurationMs===void 0)return Hr(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?$v(Yv(this.realStartMs+i)):Hr(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?Hr(t):Hr(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return Hr(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return Hr(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?Hr(this.currentSighting.timeline.duration):this.canShowClockTime?$v(Yv(this.realStartMs+this.realDurationMs)):Hr(this.realDurationMs)}}function Yv(c){const t=new Date(c);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function $v(c){if(c.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return c.second?`${t(c.hour)}:${t(c.minute??0)}:${t(c.second)}`:`${t(c.hour)}:${t(c.minute??0)}`}function Hr(c){const t=Math.round(c/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const Nm="rr0-ufo";function fw(){customElements.get(Nm)||customElements.define(Nm,Ue)}const gA="timechange",vA="recordingissues",pw="minifiedreset";class FO{static sync(t,e,i,s,n){if(t.querySelector(".param-description")?.remove(),e===void 0){t.removeAttribute("data-describing");return}const a=document.createElement("div");a.className="param-description";const r=document.createElement("div");r.className="param-description-head";const o=document.createElement("span");o.className="param-nest-label",o.textContent=i;const l=document.createElement("button");l.type="button",l.className="param-description-close",l.textContent="×",l.title=s,l.setAttribute("aria-label",s),l.addEventListener("click",n),r.append(o,l);const h=document.createElement("p");h.className="param-description-text",h.textContent=e,a.append(r,h),a.addEventListener("keydown",u=>{u.key==="Escape"&&n()}),t.setAttribute("data-describing",""),t.append(a),l.focus({preventScroll:!0})}static CSS=`
|
|
1571
1571
|
.param-summary[data-describing] > :not(.param-description) {
|
|
1572
1572
|
display: none;
|
|
1573
1573
|
}
|
|
@@ -5723,7 +5723,7 @@ void main() {
|
|
|
5723
5723
|
|
|
5724
5724
|
}
|
|
5725
5725
|
|
|
5726
|
-
}`;class j4{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new Bw(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new _e({vertexShader:Z4,fragmentShader:J4,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new dt(new tn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Q4 extends bo{constructor(t,e){super();const i=this;let s=null,n=1,a=null,r="local-floor",o=1,l=null,h=null,u=null,d=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",m=new j4,v={},M=e.getContextAttributes();let x=null,y=null;const w=[],S=[],E=new Q;let b=null;const A=new Ns;A.viewport=new Ae;const T=new Ns;T.viewport=new Ae;const D=[A,T],I=new $_;let C=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getTargetRaySpace()},this.getControllerGrip=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getGripSpace()},this.getHand=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getHandSpace()};function O(q){const ot=S.indexOf(q.inputSource);if(ot===-1)return;const st=w[ot];st!==void 0&&(st.update(q.inputSource,q.frame,l||a),st.dispatchEvent({type:q.type,data:q.inputSource}))}function k(){s.removeEventListener("select",O),s.removeEventListener("selectstart",O),s.removeEventListener("selectend",O),s.removeEventListener("squeeze",O),s.removeEventListener("squeezestart",O),s.removeEventListener("squeezeend",O),s.removeEventListener("end",k),s.removeEventListener("inputsourceschange",B);for(let q=0;q<w.length;q++){const ot=S[q];ot!==null&&(S[q]=null,w[q].disconnect(ot))}C=null,N=null,m.reset();for(const q in v)delete v[q];t.setRenderTarget(x),f=null,d=null,u=null,s=null,y=null,Zt.stop(),i.isPresenting=!1,t.setPixelRatio(b),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){n=q,i.isPresenting===!0&&Bt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){r=q,i.isPresenting===!0&&Bt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(q){l=q},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&g&&(u=new XRWebGLBinding(s,e)),u},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(q){if(s=q,s!==null){if(x=t.getRenderTarget(),s.addEventListener("select",O),s.addEventListener("selectstart",O),s.addEventListener("selectend",O),s.addEventListener("squeeze",O),s.addEventListener("squeezestart",O),s.addEventListener("squeezeend",O),s.addEventListener("end",k),s.addEventListener("inputsourceschange",B),M.xrCompatible!==!0&&await e.makeXRCompatible(),b=t.getPixelRatio(),t.getSize(E),g&&"createProjectionLayer"in XRWebGLBinding.prototype){let st=null,G=null,Nt=null;M.depth&&(Nt=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,st=M.stencil?Ko:Cr,G=M.stencil?gu:ea);const Xt={colorFormat:e.RGBA8,depthFormat:Nt,scaleFactor:n};u=this.getBinding(),d=u.createProjectionLayer(Xt),s.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new Ke(d.textureWidth,d.textureHeight,{format:Gi,type:Zs,depthTexture:new xo(d.textureWidth,d.textureHeight,G,void 0,void 0,void 0,void 0,void 0,void 0,st),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const st={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:n};f=new XRWebGLLayer(s,e,st),s.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ke(f.framebufferWidth,f.framebufferHeight,{format:Gi,type:Zs,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,a=await s.requestReferenceSpace(r),Zt.setContext(s),Zt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function B(q){for(let ot=0;ot<q.removed.length;ot++){const st=q.removed[ot],G=S.indexOf(st);G>=0&&(S[G]=null,w[G].disconnect(st))}for(let ot=0;ot<q.added.length;ot++){const st=q.added[ot];let G=S.indexOf(st);if(G===-1){for(let Xt=0;Xt<w.length;Xt++)if(Xt>=S.length){S.push(st),G=Xt;break}else if(S[Xt]===null){S[Xt]=st,G=Xt;break}if(G===-1)break}const Nt=w[G];Nt&&Nt.connect(st)}}const X=new _,J=new _;function $(q,ot,st){X.setFromMatrixPosition(ot.matrixWorld),J.setFromMatrixPosition(st.matrixWorld);const G=X.distanceTo(J),Nt=ot.projectionMatrix.elements,Xt=st.projectionMatrix.elements,kt=Nt[14]/(Nt[10]-1),Tt=Nt[14]/(Nt[10]+1),te=(Nt[9]+1)/Nt[5],ie=(Nt[9]-1)/Nt[5],se=(Nt[8]-1)/Nt[0],je=(Xt[8]+1)/Xt[0],Qe=kt*se,Li=kt*je,Ri=G/(-se+je),Ni=Ri*-se;if(ot.matrixWorld.decompose(q.position,q.quaternion,q.scale),q.translateX(Ni),q.translateZ(Ri),q.matrixWorld.compose(q.position,q.quaternion,q.scale),q.matrixWorldInverse.copy(q.matrixWorld).invert(),Nt[10]===-1)q.projectionMatrix.copy(ot.projectionMatrix),q.projectionMatrixInverse.copy(ot.projectionMatrixInverse);else{const ji=kt+Ri,U=Tt+Ri,pn=Qe-Ni,ti=Li+(G-Ni),L=te*Tt/U*ji,R=ie*Tt/U*ji;q.projectionMatrix.makePerspective(pn,ti,L,R,ji,U),q.projectionMatrixInverse.copy(q.projectionMatrix).invert()}}function it(q,ot){ot===null?q.matrixWorld.copy(q.matrix):q.matrixWorld.multiplyMatrices(ot.matrixWorld,q.matrix),q.matrixWorldInverse.copy(q.matrixWorld).invert()}this.updateCamera=function(q){if(s===null)return;let ot=q.near,st=q.far;m.texture!==null&&(m.depthNear>0&&(ot=m.depthNear),m.depthFar>0&&(st=m.depthFar)),I.near=T.near=A.near=ot,I.far=T.far=A.far=st,(C!==I.near||N!==I.far)&&(s.updateRenderState({depthNear:I.near,depthFar:I.far}),C=I.near,N=I.far),I.layers.mask=q.layers.mask|6,A.layers.mask=I.layers.mask&-5,T.layers.mask=I.layers.mask&-3;const G=q.parent,Nt=I.cameras;it(I,G);for(let Xt=0;Xt<Nt.length;Xt++)it(Nt[Xt],G);Nt.length===2?$(I,A,T):I.projectionMatrix.copy(A.projectionMatrix),rt(q,I,G)};function rt(q,ot,st){st===null?q.matrix.copy(ot.matrixWorld):(q.matrix.copy(st.matrixWorld),q.matrix.invert(),q.matrix.multiply(ot.matrixWorld)),q.matrix.decompose(q.position,q.quaternion,q.scale),q.updateMatrixWorld(!0),q.projectionMatrix.copy(ot.projectionMatrix),q.projectionMatrixInverse.copy(ot.projectionMatrixInverse),q.isPerspectiveCamera&&(q.fov=Kl*2*Math.atan(1/q.projectionMatrix.elements[5]),q.zoom=1)}this.getCamera=function(){return I},this.getFoveation=function(){if(!(d===null&&f===null))return o},this.setFoveation=function(q){o=q,d!==null&&(d.fixedFoveation=q),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=q)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(I)},this.getCameraTexture=function(q){return v[q]};let Lt=null;function qt(q,ot){if(h=ot.getViewerPose(l||a),p=ot,h!==null){const st=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let G=!1;st.length!==I.cameras.length&&(I.cameras.length=0,G=!0);for(let Tt=0;Tt<st.length;Tt++){const te=st[Tt];let ie=null;if(f!==null)ie=f.getViewport(te);else{const je=u.getViewSubImage(d,te);ie=je.viewport,Tt===0&&(t.setRenderTargetTextures(y,je.colorTexture,je.depthStencilTexture),t.setRenderTarget(y))}let se=D[Tt];se===void 0&&(se=new Ns,se.layers.enable(Tt),se.viewport=new Ae,D[Tt]=se),se.matrix.fromArray(te.transform.matrix),se.matrix.decompose(se.position,se.quaternion,se.scale),se.projectionMatrix.fromArray(te.projectionMatrix),se.projectionMatrixInverse.copy(se.projectionMatrix).invert(),se.viewport.set(ie.x,ie.y,ie.width,ie.height),Tt===0&&(I.matrix.copy(se.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale)),G===!0&&I.cameras.push(se)}const Nt=s.enabledFeatures;if(Nt&&Nt.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&g){u=i.getBinding();const Tt=u.getDepthInformation(st[0]);Tt&&Tt.isValid&&Tt.texture&&m.init(Tt,s.renderState)}if(Nt&&Nt.includes("camera-access")&&g){t.state.unbindTexture(),u=i.getBinding();for(let Tt=0;Tt<st.length;Tt++){const te=st[Tt].camera;if(te){let ie=v[te];ie||(ie=new Bw,v[te]=ie);const se=u.getCameraImage(te);ie.sourceTexture=se}}}}for(let st=0;st<w.length;st++){const G=S[st],Nt=w[st];G!==null&&Nt!==void 0&&Nt.update(G,ot,l||a)}Lt&&Lt(q,ot),ot.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ot}),p=null}const Zt=new sb;Zt.setAnimationLoop(qt),this.setAnimationLoop=function(q){Lt=q},this.dispose=function(){}}}const tI=new Gt,lb=new he;lb.set(-1,0,0,0,1,0,0,0,1);function eI(c,t){function e(m,v){m.matrixAutoUpdate===!0&&m.updateMatrix(),v.value.copy(m.matrix)}function i(m,v){v.color.getRGB(m.fogColor.value,qw(c)),v.isFog?(m.fogNear.value=v.near,m.fogFar.value=v.far):v.isFogExp2&&(m.fogDensity.value=v.density)}function s(m,v,M,x,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?n(m,v):v.isMeshLambertMaterial?(n(m,v),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(n(m,v),u(m,v)):v.isMeshPhongMaterial?(n(m,v),h(m,v),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(n(m,v),d(m,v),v.isMeshPhysicalMaterial&&f(m,v,y)):v.isMeshMatcapMaterial?(n(m,v),p(m,v)):v.isMeshDepthMaterial?n(m,v):v.isMeshDistanceMaterial?(n(m,v),g(m,v)):v.isMeshNormalMaterial?n(m,v):v.isLineBasicMaterial?(a(m,v),v.isLineDashedMaterial&&r(m,v)):v.isPointsMaterial?o(m,v,M,x):v.isSpriteMaterial?l(m,v):v.isShadowMaterial?(m.color.value.copy(v.color),m.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function n(m,v){m.opacity.value=v.opacity,v.color&&m.diffuse.value.copy(v.color),v.emissive&&m.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(m.map.value=v.map,e(v.map,m.mapTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.bumpMap&&(m.bumpMap.value=v.bumpMap,e(v.bumpMap,m.bumpMapTransform),m.bumpScale.value=v.bumpScale,v.side===Ai&&(m.bumpScale.value*=-1)),v.normalMap&&(m.normalMap.value=v.normalMap,e(v.normalMap,m.normalMapTransform),m.normalScale.value.copy(v.normalScale),v.side===Ai&&m.normalScale.value.negate()),v.displacementMap&&(m.displacementMap.value=v.displacementMap,e(v.displacementMap,m.displacementMapTransform),m.displacementScale.value=v.displacementScale,m.displacementBias.value=v.displacementBias),v.emissiveMap&&(m.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,m.emissiveMapTransform)),v.specularMap&&(m.specularMap.value=v.specularMap,e(v.specularMap,m.specularMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest);const M=t.get(v),x=M.envMap,y=M.envMapRotation;x&&(m.envMap.value=x,m.envMapRotation.value.setFromMatrix4(tI.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(lb),m.reflectivity.value=v.reflectivity,m.ior.value=v.ior,m.refractionRatio.value=v.refractionRatio),v.lightMap&&(m.lightMap.value=v.lightMap,m.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,m.lightMapTransform)),v.aoMap&&(m.aoMap.value=v.aoMap,m.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,m.aoMapTransform))}function a(m,v){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,v.map&&(m.map.value=v.map,e(v.map,m.mapTransform))}function r(m,v){m.dashSize.value=v.dashSize,m.totalSize.value=v.dashSize+v.gapSize,m.scale.value=v.scale}function o(m,v,M,x){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,m.size.value=v.size*M,m.scale.value=x*.5,v.map&&(m.map.value=v.map,e(v.map,m.uvTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest)}function l(m,v){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,m.rotation.value=v.rotation,v.map&&(m.map.value=v.map,e(v.map,m.mapTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest)}function h(m,v){m.specular.value.copy(v.specular),m.shininess.value=Math.max(v.shininess,1e-4)}function u(m,v){v.gradientMap&&(m.gradientMap.value=v.gradientMap)}function d(m,v){m.metalness.value=v.metalness,v.metalnessMap&&(m.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,m.metalnessMapTransform)),m.roughness.value=v.roughness,v.roughnessMap&&(m.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,m.roughnessMapTransform)),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)}function f(m,v,M){m.ior.value=v.ior,v.sheen>0&&(m.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),m.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(m.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,m.sheenColorMapTransform)),v.sheenRoughnessMap&&(m.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,m.sheenRoughnessMapTransform))),v.clearcoat>0&&(m.clearcoat.value=v.clearcoat,m.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(m.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,m.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(m.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Ai&&m.clearcoatNormalScale.value.negate())),v.dispersion>0&&(m.dispersion.value=v.dispersion),v.iridescence>0&&(m.iridescence.value=v.iridescence,m.iridescenceIOR.value=v.iridescenceIOR,m.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(m.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,m.iridescenceMapTransform)),v.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),v.transmission>0&&(m.transmission.value=v.transmission,m.transmissionSamplerMap.value=M.texture,m.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(m.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,m.transmissionMapTransform)),m.thickness.value=v.thickness,v.thicknessMap&&(m.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=v.attenuationDistance,m.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(m.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(m.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=v.specularIntensity,m.specularColor.value.copy(v.specularColor),v.specularColorMap&&(m.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,m.specularColorMapTransform)),v.specularIntensityMap&&(m.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,m.specularIntensityMapTransform))}function p(m,v){v.matcap&&(m.matcap.value=v.matcap)}function g(m,v){const M=t.get(v).light;m.referencePosition.value.setFromMatrixPosition(M.matrixWorld),m.nearDistance.value=M.shadow.camera.near,m.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function iI(c,t,e,i){let s={},n={},a=[];const r=c.getParameter(c.MAX_UNIFORM_BUFFER_BINDINGS);function o(y,w){const S=w.program;i.uniformBlockBinding(y,S)}function l(y,w){let S=s[y.id];S===void 0&&(m(y),S=h(y),s[y.id]=S,y.addEventListener("dispose",M));const E=w.program;i.updateUBOMapping(y,E);const b=t.render.frame;n[y.id]!==b&&(d(y),n[y.id]=b)}function h(y){const w=u();y.__bindingPointIndex=w;const S=c.createBuffer(),E=y.__size,b=y.usage;return c.bindBuffer(c.UNIFORM_BUFFER,S),c.bufferData(c.UNIFORM_BUFFER,E,b),c.bindBuffer(c.UNIFORM_BUFFER,null),c.bindBufferBase(c.UNIFORM_BUFFER,w,S),S}function u(){for(let y=0;y<r;y++)if(a.indexOf(y)===-1)return a.push(y),y;return oe("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=s[y.id],S=y.uniforms,E=y.__cache;c.bindBuffer(c.UNIFORM_BUFFER,w);for(let b=0,A=S.length;b<A;b++){const T=S[b];if(Array.isArray(T))for(let D=0,I=T.length;D<I;D++)f(T[D],b,D,E);else f(T,b,0,E)}c.bindBuffer(c.UNIFORM_BUFFER,null)}function f(y,w,S,E){if(g(y,w,S,E)===!0){const b=y.__offset,A=y.value;if(Array.isArray(A)){let T=0;for(let D=0;D<A.length;D++){const I=A[D],C=v(I);p(I,y.__data,T),typeof I!="number"&&typeof I!="boolean"&&!I.isMatrix3&&!ArrayBuffer.isView(I)&&(T+=C.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);c.bufferSubData(c.UNIFORM_BUFFER,b,y.__data)}}function p(y,w,S){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,S)}function g(y,w,S,E){const b=y.value,A=w+"_"+S;if(E[A]===void 0)return typeof b=="number"||typeof b=="boolean"?E[A]=b:ArrayBuffer.isView(b)?E[A]=b.slice():E[A]=b.clone(),!0;{const T=E[A];if(typeof b=="number"||typeof b=="boolean"){if(T!==b)return E[A]=b,!0}else{if(ArrayBuffer.isView(b))return!0;if(T.equals(b)===!1)return T.copy(b),!0}}return!1}function m(y){const w=y.uniforms;let S=0;const E=16;for(let A=0,T=w.length;A<T;A++){const D=Array.isArray(w[A])?w[A]:[w[A]];for(let I=0,C=D.length;I<C;I++){const N=D[I],O=Array.isArray(N.value)?N.value:[N.value];for(let k=0,B=O.length;k<B;k++){const X=O[k],J=v(X),$=S%E,it=$%J.boundary,rt=$+it;S+=it,rt!==0&&E-rt<J.storage&&(S+=E-rt),N.__data=new Float32Array(J.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=S,S+=J.storage}}}const b=S%E;return b>0&&(S+=E-b),y.__size=S,y.__cache={},this}function v(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?Bt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):Bt("WebGLRenderer: Unsupported uniform value type.",y),w}function M(y){const w=y.target;w.removeEventListener("dispose",M);const S=a.indexOf(w.__bindingPointIndex);a.splice(S,1),c.deleteBuffer(s[w.id]),delete s[w.id],delete n[w.id]}function x(){for(const y in s)c.deleteBuffer(s[y]);a=[],s={},n={}}return{bind:o,update:l,dispose:x}}const sI=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 _a=null;function nI(){return _a===null&&(_a=new dn(sI,16,16,hc,Be),_a.name="DFG_LUT",_a.minFilter=ge,_a.magFilter=ge,_a.wrapS=Hi,_a.wrapT=Hi,_a.generateMipmaps=!1,_a.needsUpdate=!0),_a}class aI{constructor(t={}){const{canvas:e=QA(),context:i=null,depth:s=!0,stencil:n=!1,alpha:a=!1,antialias:r=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Zs}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=a;const g=f,m=new Set([E1,S1,b1]),v=new Set([Zs,ea,mu,gu,x1,w1]),M=new Uint32Array(4),x=new Int32Array(4),y=new _;let w=null,S=null;const E=[],b=[];let A=null;this.domElement=e,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=tr,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let D=!1,I=null,C=null,N=null,O=null;this._outputColorSpace=Es;let k=0,B=0,X=null,J=-1,$=null;const it=new Ae,rt=new Ae;let Lt=null;const qt=new at(0);let Zt=0,q=e.width,ot=e.height,st=1,G=null,Nt=null;const Xt=new Ae(0,0,q,ot),kt=new Ae(0,0,q,ot);let Tt=!1;const te=new d0;let ie=!1,se=!1;const je=new Gt,Qe=new _,Li=new Ae,Ri={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ni=!1;function ji(){return X===null?st:1}let U=i;function pn(P,z){return e.getContext(P,z)}try{const P={alpha:!0,depth:s,stencil:n,antialias:r,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Ru}`),e.addEventListener("webglcontextlost",ki,!1),e.addEventListener("webglcontextrestored",vi,!1),e.addEventListener("webglcontextcreationerror",wa,!1),U===null){const z="webgl2";if(U=pn(z,P),U===null)throw pn(z)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(P){throw oe("WebGLRenderer: "+P.message),P}let ti,L,R,H,K,Z,lt,ft,j,et,mt,Kt,yt,gt,Qt,ae,be,F,ut,tt,vt,St,nt;function Wt(){ti=new nD(U),ti.init(),vt=new q4(U,ti),L=new ZR(U,ti,t,vt),R=new Y4(U,ti),L.reversedDepthBuffer&&d&&R.buffers.depth.setReversed(!0),C=U.createFramebuffer(),N=U.createFramebuffer(),O=U.createFramebuffer(),H=new oD(U),K=new O4,Z=new $4(U,ti,R,K,L,vt,H),lt=new sD(T),ft=new uT(U),St=new $R(U,ft),j=new aD(U,ft,H,St),et=new lD(U,j,ft,St,H),F=new cD(U,L,Z),Qt=new JR(K),mt=new C4(T,lt,ti,L,St,Qt),Kt=new eI(T,K),yt=new N4,gt=new H4(ti),be=new YR(T,lt,R,et,p,o),ae=new K4(T,et,L),nt=new iI(U,H,L,R),ut=new qR(U,ti,H),tt=new rD(U,ti,H),H.programs=mt.programs,T.capabilities=L,T.extensions=ti,T.properties=K,T.renderLists=yt,T.shadowMap=ae,T.state=R,T.info=H}Wt(),g!==Zs&&(A=new uD(g,e.width,e.height,r,s,n));const Ft=new Q4(T,U);this.xr=Ft,this.getContext=function(){return U},this.getContextAttributes=function(){return U.getContextAttributes()},this.forceContextLoss=function(){const P=ti.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=ti.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return st},this.setPixelRatio=function(P){P!==void 0&&(st=P,this.setSize(q,ot,!1))},this.getSize=function(P){return P.set(q,ot)},this.setSize=function(P,z,Y=!0){if(Ft.isPresenting){Bt("WebGLRenderer: Can't change size while VR device is presenting.");return}q=P,ot=z,e.width=Math.floor(P*st),e.height=Math.floor(z*st),Y===!0&&(e.style.width=P+"px",e.style.height=z+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,P,z)},this.getDrawingBufferSize=function(P){return P.set(q*st,ot*st).floor()},this.setDrawingBufferSize=function(P,z,Y){q=P,ot=z,st=Y,e.width=Math.floor(P*Y),e.height=Math.floor(z*Y),this.setViewport(0,0,P,z)},this.setEffects=function(P){if(g===Zs){oe("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(P){for(let z=0;z<P.length;z++)if(P[z].isOutputPass===!0){Bt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(P||[])},this.getCurrentViewport=function(P){return P.copy(it)},this.getViewport=function(P){return P.copy(Xt)},this.setViewport=function(P,z,Y,V){P.isVector4?Xt.set(P.x,P.y,P.z,P.w):Xt.set(P,z,Y,V),R.viewport(it.copy(Xt).multiplyScalar(st).round())},this.getScissor=function(P){return P.copy(kt)},this.setScissor=function(P,z,Y,V){P.isVector4?kt.set(P.x,P.y,P.z,P.w):kt.set(P,z,Y,V),R.scissor(rt.copy(kt).multiplyScalar(st).round())},this.getScissorTest=function(){return Tt},this.setScissorTest=function(P){R.setScissorTest(Tt=P)},this.setOpaqueSort=function(P){G=P},this.setTransparentSort=function(P){Nt=P},this.getClearColor=function(P){return P.copy(be.getClearColor())},this.setClearColor=function(){be.setClearColor(...arguments)},this.getClearAlpha=function(){return be.getClearAlpha()},this.setClearAlpha=function(){be.setClearAlpha(...arguments)},this.clear=function(P=!0,z=!0,Y=!0){let V=0;if(P){let W=!1;if(X!==null){const bt=X.texture.format;W=m.has(bt)}if(W){const bt=X.texture.type,Rt=v.has(bt),wt=be.getClearColor(),Ut=be.getClearAlpha(),Yt=wt.r,Se=wt.g,Re=wt.b;Rt?(M[0]=Yt,M[1]=Se,M[2]=Re,M[3]=Ut,U.clearBufferuiv(U.COLOR,0,M)):(x[0]=Yt,x[1]=Se,x[2]=Re,x[3]=Ut,U.clearBufferiv(U.COLOR,0,x))}else V|=U.COLOR_BUFFER_BIT}z&&(V|=U.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),Y&&(V|=U.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),V!==0&&U.clear(V)},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(P){P.setRenderer(this),I=P},this.dispose=function(){e.removeEventListener("webglcontextlost",ki,!1),e.removeEventListener("webglcontextrestored",vi,!1),e.removeEventListener("webglcontextcreationerror",wa,!1),be.dispose(),yt.dispose(),gt.dispose(),K.dispose(),lt.dispose(),et.dispose(),St.dispose(),nt.dispose(),mt.dispose(),Ft.dispose(),Ft.removeEventListener("sessionstart",nv),Ft.removeEventListener("sessionend",av),Eo.stop()};function ki(P){P.preventDefault(),Cf("WebGLRenderer: Context Lost."),D=!0}function vi(){Cf("WebGLRenderer: Context Restored."),D=!1;const P=H.autoReset,z=ae.enabled,Y=ae.autoUpdate,V=ae.needsUpdate,W=ae.type;Wt(),H.autoReset=P,ae.enabled=z,ae.autoUpdate=Y,ae.needsUpdate=V,ae.type=W}function wa(P){oe("WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function ba(P){const z=P.target;z.removeEventListener("dispose",ba),Kb(z)}function Kb(P){Yb(P),K.remove(P)}function Yb(P){const z=K.get(P).programs;z!==void 0&&(z.forEach(function(Y){mt.releaseProgram(Y)}),P.isShaderMaterial&&mt.releaseShaderCache(P))}this.renderBufferDirect=function(P,z,Y,V,W,bt){z===null&&(z=Ri);const Rt=W.isMesh&&W.matrixWorld.determinantAffine()<0,wt=Zb(P,z,Y,V,W);R.setMaterial(V,Rt);let Ut=Y.index,Yt=1;if(V.wireframe===!0){if(Ut=j.getWireframeAttribute(Y),Ut===void 0)return;Yt=2}const Se=Y.drawRange,Re=Y.attributes.position;let $t=Se.start*Yt,ci=(Se.start+Se.count)*Yt;bt!==null&&($t=Math.max($t,bt.start*Yt),ci=Math.min(ci,(bt.start+bt.count)*Yt)),Ut!==null?($t=Math.max($t,0),ci=Math.min(ci,Ut.count)):Re!=null&&($t=Math.max($t,0),ci=Math.min(ci,Re.count));const Wi=ci-$t;if(Wi<0||Wi===1/0)return;St.setup(W,V,wt,Y,Ut);let Fi,ui=ut;if(Ut!==null&&(Fi=ft.get(Ut),ui=tt,ui.setIndex(Fi)),W.isMesh)V.wireframe===!0?(R.setLineWidth(V.wireframeLinewidth*ji()),ui.setMode(U.LINES)):ui.setMode(U.TRIANGLES);else if(W.isLine){let Us=V.linewidth;Us===void 0&&(Us=1),R.setLineWidth(Us*ji()),W.isLineSegments?ui.setMode(U.LINES):W.isLineLoop?ui.setMode(U.LINE_LOOP):ui.setMode(U.LINE_STRIP)}else W.isPoints?ui.setMode(U.POINTS):W.isSprite&&ui.setMode(U.TRIANGLES);if(W.isBatchedMesh)if(ti.get("WEBGL_multi_draw"))ui.renderMultiDraw(W._multiDrawStarts,W._multiDrawCounts,W._multiDrawCount);else{const Us=W._multiDrawStarts,At=W._multiDrawCounts,_n=W._multiDrawCount,Ge=Ut?ft.get(Ut).bytesPerElement:1,Hn=K.get(V).currentProgram.getUniforms();for(let Sa=0;Sa<_n;Sa++)Hn.setValue(U,"_gl_DrawID",Sa),ui.render(Us[Sa]/Ge,At[Sa])}else if(W.isInstancedMesh)ui.renderInstances($t,Wi,W.count);else if(Y.isInstancedBufferGeometry){const Us=Y._maxInstanceCount!==void 0?Y._maxInstanceCount:1/0,At=Math.min(Y.instanceCount,Us);ui.renderInstances($t,Wi,At)}else ui.render($t,Wi)};function sv(P,z,Y){P.transparent===!0&&P.side===ds&&P.forceSinglePass===!1?(P.side=Ai,P.needsUpdate=!0,Cu(P,z,Y),P.side=sr,P.needsUpdate=!0,Cu(P,z,Y),P.side=ds):Cu(P,z,Y)}this.compile=function(P,z,Y=null){Y===null&&(Y=P),S=gt.get(Y),S.init(z),b.push(S),Y.traverseVisible(function(W){W.isLight&&W.layers.test(z.layers)&&(S.pushLight(W),W.castShadow&&S.pushShadow(W))}),P!==Y&&P.traverseVisible(function(W){W.isLight&&W.layers.test(z.layers)&&(S.pushLight(W),W.castShadow&&S.pushShadow(W))}),S.setupLights();const V=new Set;return P.traverse(function(W){if(!(W.isMesh||W.isPoints||W.isLine||W.isSprite))return;const bt=W.material;if(bt)if(Array.isArray(bt))for(let Rt=0;Rt<bt.length;Rt++){const wt=bt[Rt];sv(wt,Y,W),V.add(wt)}else sv(bt,Y,W),V.add(bt)}),S=b.pop(),V},this.compileAsync=function(P,z,Y=null){const V=this.compile(P,z,Y);return new Promise(W=>{function bt(){if(V.forEach(function(Rt){K.get(Rt).currentProgram.isReady()&&V.delete(Rt)}),V.size===0){W(P);return}setTimeout(bt,10)}ti.get("KHR_parallel_shader_compile")!==null?bt():setTimeout(bt,10)})};let b0=null;function $b(P){b0&&b0(P)}function nv(){Eo.stop()}function av(){Eo.start()}const Eo=new sb;Eo.setAnimationLoop($b),typeof self<"u"&&Eo.setContext(self),this.setAnimationLoop=function(P){b0=P,Ft.setAnimationLoop(P),P===null?Eo.stop():Eo.start()},Ft.addEventListener("sessionstart",nv),Ft.addEventListener("sessionend",av),this.render=function(P,z){if(z!==void 0&&z.isCamera!==!0){oe("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;I!==null&&I.renderStart(P,z);const Y=Ft.enabled===!0&&Ft.isPresenting===!0,V=A!==null&&(X===null||Y)&&A.begin(T,X);if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),z.parent===null&&z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),Ft.enabled===!0&&Ft.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Ft.cameraAutoUpdate===!0&&Ft.updateCamera(z),z=Ft.getCamera()),P.isScene===!0&&P.onBeforeRender(T,P,z,X),S=gt.get(P,b.length),S.init(z),S.state.textureUnits=Z.getTextureUnits(),b.push(S),je.multiplyMatrices(z.projectionMatrix,z.matrixWorldInverse),te.setFromProjectionMatrix(je,ja,z.reversedDepth),se=this.localClippingEnabled,ie=Qt.init(this.clippingPlanes,se),w=yt.get(P,E.length),w.init(),E.push(w),Ft.enabled===!0&&Ft.isPresenting===!0){const Rt=T.xr.getDepthSensingMesh();Rt!==null&&S0(Rt,z,-1/0,T.sortObjects)}S0(P,z,0,T.sortObjects),w.finish(),T.sortObjects===!0&&w.sort(G,Nt,z.reversedDepth),Ni=Ft.enabled===!1||Ft.isPresenting===!1||Ft.hasDepthSensing()===!1,Ni&&be.addToRenderList(w,P),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Qt.beginShadows();const W=S.state.shadowsArray;if(ae.render(W,P,z),ie===!0&&Qt.endShadows(),(V&&A.hasRenderPass())===!1){const Rt=w.opaque,wt=w.transmissive;if(S.setupLights(),z.isArrayCamera){const Ut=z.cameras;if(wt.length>0)for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt];ov(Rt,wt,P,Re)}Ni&&be.render(P);for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt];rv(w,P,Re,Re.viewport)}}else wt.length>0&&ov(Rt,wt,P,z),Ni&&be.render(P),rv(w,P,z)}X!==null&&B===0&&(Z.updateMultisampleRenderTarget(X),Z.updateRenderTargetMipmap(X)),V&&A.end(T),P.isScene===!0&&P.onAfterRender(T,P,z),St.resetDefaultState(),J=-1,$=null,b.pop(),b.length>0?(S=b[b.length-1],Z.setTextureUnits(S.state.textureUnits),ie===!0&&Qt.setGlobalState(T.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,I!==null&&I.renderEnd()};function S0(P,z,Y,V){if(P.visible===!1)return;if(P.layers.test(z.layers)){if(P.isGroup)Y=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(z);else if(P.isLightProbeGrid)S.pushLightProbeGrid(P);else if(P.isLight)S.pushLight(P),P.castShadow&&S.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||te.intersectsSprite(P)){V&&Li.setFromMatrixPosition(P.matrixWorld).applyMatrix4(je);const Rt=et.update(P),wt=P.material;wt.visible&&w.push(P,Rt,wt,Y,Li.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||te.intersectsObject(P))){const Rt=et.update(P),wt=P.material;if(V&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),Li.copy(P.boundingSphere.center)):(Rt.boundingSphere===null&&Rt.computeBoundingSphere(),Li.copy(Rt.boundingSphere.center)),Li.applyMatrix4(P.matrixWorld).applyMatrix4(je)),Array.isArray(wt)){const Ut=Rt.groups;for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt],$t=wt[Re.materialIndex];$t&&$t.visible&&w.push(P,Rt,$t,Y,Li.z,Re)}}else wt.visible&&w.push(P,Rt,wt,Y,Li.z,null)}}const bt=P.children;for(let Rt=0,wt=bt.length;Rt<wt;Rt++)S0(bt[Rt],z,Y,V)}function rv(P,z,Y,V){const{opaque:W,transmissive:bt,transparent:Rt}=P;S.setupLightsView(Y),ie===!0&&Qt.setGlobalState(T.clippingPlanes,Y),V&&R.viewport(it.copy(V)),W.length>0&&Pu(W,z,Y),bt.length>0&&Pu(bt,z,Y),Rt.length>0&&Pu(Rt,z,Y),R.buffers.depth.setTest(!0),R.buffers.depth.setMask(!0),R.buffers.color.setMask(!0),R.setPolygonOffset(!1)}function ov(P,z,Y,V){if((Y.isScene===!0?Y.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const $t=ti.has("EXT_color_buffer_half_float")||ti.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new Ke(1,1,{generateMipmaps:!0,type:$t?Be:Zs,minFilter:Fn,samples:Math.max(4,L.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ke.workingColorSpace})}const bt=S.state.transmissionRenderTarget[V.id],Rt=V.viewport||it;bt.setSize(Rt.z*T.transmissionResolutionScale,Rt.w*T.transmissionResolutionScale);const wt=T.getRenderTarget(),Ut=T.getActiveCubeFace(),Yt=T.getActiveMipmapLevel();T.setRenderTarget(bt),T.getClearColor(qt),Zt=T.getClearAlpha(),Zt<1&&T.setClearColor(16777215,.5),T.clear(),Ni&&be.render(Y);const Se=T.toneMapping;T.toneMapping=tr;const Re=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),ie===!0&&Qt.setGlobalState(T.clippingPlanes,V),Pu(P,Y,V),Z.updateMultisampleRenderTarget(bt),Z.updateRenderTargetMipmap(bt),ti.has("WEBGL_multisampled_render_to_texture")===!1){let $t=!1;for(let ci=0,Wi=z.length;ci<Wi;ci++){const Fi=z[ci],{object:ui,geometry:Us,material:At,group:_n}=Fi;if(At.side===ds&&ui.layers.test(V.layers)){const Ge=At.side;At.side=Ai,At.needsUpdate=!0,cv(ui,Y,V,Us,At,_n),At.side=Ge,At.needsUpdate=!0,$t=!0}}$t===!0&&(Z.updateMultisampleRenderTarget(bt),Z.updateRenderTargetMipmap(bt))}T.setRenderTarget(wt,Ut,Yt),T.setClearColor(qt,Zt),Re!==void 0&&(V.viewport=Re),T.toneMapping=Se}function Pu(P,z,Y){const V=z.isScene===!0?z.overrideMaterial:null;for(let W=0,bt=P.length;W<bt;W++){const Rt=P[W],{object:wt,geometry:Ut,group:Yt}=Rt;let Se=Rt.material;Se.allowOverride===!0&&V!==null&&(Se=V),wt.layers.test(Y.layers)&&cv(wt,z,Y,Ut,Se,Yt)}}function cv(P,z,Y,V,W,bt){P.onBeforeRender(T,z,Y,V,W,bt),P.modelViewMatrix.multiplyMatrices(Y.matrixWorldInverse,P.matrixWorld),P.normalMatrix.getNormalMatrix(P.modelViewMatrix),W.onBeforeRender(T,z,Y,V,P,bt),W.transparent===!0&&W.side===ds&&W.forceSinglePass===!1?(W.side=Ai,W.needsUpdate=!0,T.renderBufferDirect(Y,z,V,W,P,bt),W.side=sr,W.needsUpdate=!0,T.renderBufferDirect(Y,z,V,W,P,bt),W.side=ds):T.renderBufferDirect(Y,z,V,W,P,bt),P.onAfterRender(T,z,Y,V,W,bt)}function Cu(P,z,Y){z.isScene!==!0&&(z=Ri);const V=K.get(P),W=S.state.lights,bt=S.state.shadowsArray,Rt=W.state.version,wt=mt.getParameters(P,W.state,bt,z,Y,S.state.lightProbeGridArray),Ut=mt.getProgramCacheKey(wt);let Yt=V.programs;V.environment=P.isMeshStandardMaterial||P.isMeshLambertMaterial||P.isMeshPhongMaterial?z.environment:null,V.fog=z.fog;const Se=P.isMeshStandardMaterial||P.isMeshLambertMaterial&&!P.envMap||P.isMeshPhongMaterial&&!P.envMap;V.envMap=lt.get(P.envMap||V.environment,Se),V.envMapRotation=V.environment!==null&&P.envMap===null?z.environmentRotation:P.envMapRotation,Yt===void 0&&(P.addEventListener("dispose",ba),Yt=new Map,V.programs=Yt);let Re=Yt.get(Ut);if(Re!==void 0){if(V.currentProgram===Re&&V.lightsStateVersion===Rt)return hv(P,wt),Re}else wt.uniforms=mt.getUniforms(P),I!==null&&P.isNodeMaterial&&I.build(P,Y,wt),P.onBeforeCompile(wt,T),Re=mt.acquireProgram(wt,Ut),Yt.set(Ut,Re),V.uniforms=wt.uniforms;const $t=V.uniforms;return(!P.isShaderMaterial&&!P.isRawShaderMaterial||P.clipping===!0)&&($t.clippingPlanes=Qt.uniform),hv(P,wt),V.needsLights=jb(P),V.lightsStateVersion=Rt,V.needsLights&&($t.ambientLightColor.value=W.state.ambient,$t.lightProbe.value=W.state.probe,$t.directionalLights.value=W.state.directional,$t.directionalLightShadows.value=W.state.directionalShadow,$t.spotLights.value=W.state.spot,$t.spotLightShadows.value=W.state.spotShadow,$t.rectAreaLights.value=W.state.rectArea,$t.ltc_1.value=W.state.rectAreaLTC1,$t.ltc_2.value=W.state.rectAreaLTC2,$t.pointLights.value=W.state.point,$t.pointLightShadows.value=W.state.pointShadow,$t.hemisphereLights.value=W.state.hemi,$t.directionalShadowMatrix.value=W.state.directionalShadowMatrix,$t.spotLightMatrix.value=W.state.spotLightMatrix,$t.spotLightMap.value=W.state.spotLightMap,$t.pointShadowMatrix.value=W.state.pointShadowMatrix),V.lightProbeGrid=S.state.lightProbeGridArray.length>0,V.currentProgram=Re,V.uniformsList=null,Re}function lv(P){if(P.uniformsList===null){const z=P.currentProgram.getUniforms();P.uniformsList=of.seqWithValue(z.seq,P.uniforms)}return P.uniformsList}function hv(P,z){const Y=K.get(P);Y.outputColorSpace=z.outputColorSpace,Y.batching=z.batching,Y.batchingColor=z.batchingColor,Y.instancing=z.instancing,Y.instancingColor=z.instancingColor,Y.instancingMorph=z.instancingMorph,Y.skinning=z.skinning,Y.morphTargets=z.morphTargets,Y.morphNormals=z.morphNormals,Y.morphColors=z.morphColors,Y.morphTargetsCount=z.morphTargetsCount,Y.numClippingPlanes=z.numClippingPlanes,Y.numIntersection=z.numClipIntersection,Y.vertexAlphas=z.vertexAlphas,Y.vertexTangents=z.vertexTangents,Y.toneMapping=z.toneMapping}function qb(P,z){if(P.length===0)return null;if(P.length===1)return P[0].texture!==null?P[0]:null;y.setFromMatrixPosition(z.matrixWorld);for(let Y=0,V=P.length;Y<V;Y++){const W=P[Y];if(W.texture!==null&&W.boundingBox.containsPoint(y))return W}return null}function Zb(P,z,Y,V,W){z.isScene!==!0&&(z=Ri),Z.resetTextureUnits();const bt=z.fog,Rt=V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial?z.environment:null,wt=X===null?T.outputColorSpace:X.isXRRenderTarget===!0?X.texture.colorSpace:ke.workingColorSpace,Ut=V.isMeshStandardMaterial||V.isMeshLambertMaterial&&!V.envMap||V.isMeshPhongMaterial&&!V.envMap,Yt=lt.get(V.envMap||Rt,Ut),Se=V.vertexColors===!0&&!!Y.attributes.color&&Y.attributes.color.itemSize===4,Re=!!Y.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),$t=!!Y.morphAttributes.position,ci=!!Y.morphAttributes.normal,Wi=!!Y.morphAttributes.color;let Fi=tr;V.toneMapped&&(X===null||X.isXRRenderTarget===!0)&&(Fi=T.toneMapping);const ui=Y.morphAttributes.position||Y.morphAttributes.normal||Y.morphAttributes.color,Us=ui!==void 0?ui.length:0,At=K.get(V),_n=S.state.lights;if(ie===!0&&(se===!0||P!==$)){const Mi=P===$&&V.id===J;Qt.setState(V,P,Mi)}let Ge=!1;V.version===At.__version?(At.needsLights&&At.lightsStateVersion!==_n.state.version||At.outputColorSpace!==wt||W.isBatchedMesh&&At.batching===!1||!W.isBatchedMesh&&At.batching===!0||W.isBatchedMesh&&At.batchingColor===!0&&W.colorTexture===null||W.isBatchedMesh&&At.batchingColor===!1&&W.colorTexture!==null||W.isInstancedMesh&&At.instancing===!1||!W.isInstancedMesh&&At.instancing===!0||W.isSkinnedMesh&&At.skinning===!1||!W.isSkinnedMesh&&At.skinning===!0||W.isInstancedMesh&&At.instancingColor===!0&&W.instanceColor===null||W.isInstancedMesh&&At.instancingColor===!1&&W.instanceColor!==null||W.isInstancedMesh&&At.instancingMorph===!0&&W.morphTexture===null||W.isInstancedMesh&&At.instancingMorph===!1&&W.morphTexture!==null||At.envMap!==Yt||V.fog===!0&&At.fog!==bt||At.numClippingPlanes!==void 0&&(At.numClippingPlanes!==Qt.numPlanes||At.numIntersection!==Qt.numIntersection)||At.vertexAlphas!==Se||At.vertexTangents!==Re||At.morphTargets!==$t||At.morphNormals!==ci||At.morphColors!==Wi||At.toneMapping!==Fi||At.morphTargetsCount!==Us||!!At.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(Ge=!0):(Ge=!0,At.__version=V.version);let Hn=At.currentProgram;Ge===!0&&(Hn=Cu(V,z,W),I&&V.isNodeMaterial&&I.onUpdateProgram(V,Hn,At));let Sa=!1,Nr=!1,mc=!1;const di=Hn.getUniforms(),Xi=At.uniforms;if(R.useProgram(Hn.program)&&(Sa=!0,Nr=!0,mc=!0),V.id!==J&&(J=V.id,Nr=!0),At.needsLights){const Mi=qb(S.state.lightProbeGridArray,W);At.lightProbeGrid!==Mi&&(At.lightProbeGrid=Mi,Nr=!0)}if(Sa||$!==P){R.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),di.setValue(U,"projectionMatrix",P.projectionMatrix),di.setValue(U,"viewMatrix",P.matrixWorldInverse);const Fr=di.map.cameraPosition;Fr!==void 0&&Fr.setValue(U,Qe.setFromMatrixPosition(P.matrixWorld)),L.logarithmicDepthBuffer&&di.setValue(U,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&di.setValue(U,"isOrthographic",P.isOrthographicCamera===!0),$!==P&&($=P,Nr=!0,mc=!0)}if(At.needsLights&&(_n.state.directionalShadowMap.length>0&&di.setValue(U,"directionalShadowMap",_n.state.directionalShadowMap,Z),_n.state.spotShadowMap.length>0&&di.setValue(U,"spotShadowMap",_n.state.spotShadowMap,Z),_n.state.pointShadowMap.length>0&&di.setValue(U,"pointShadowMap",_n.state.pointShadowMap,Z)),W.isSkinnedMesh){di.setOptional(U,W,"bindMatrix"),di.setOptional(U,W,"bindMatrixInverse");const Mi=W.skeleton;Mi&&(Mi.boneTexture===null&&Mi.computeBoneTexture(),di.setValue(U,"boneTexture",Mi.boneTexture,Z))}W.isBatchedMesh&&(di.setOptional(U,W,"batchingTexture"),di.setValue(U,"batchingTexture",W._matricesTexture,Z),di.setOptional(U,W,"batchingIdTexture"),di.setValue(U,"batchingIdTexture",W._indirectTexture,Z),di.setOptional(U,W,"batchingColorTexture"),W._colorsTexture!==null&&di.setValue(U,"batchingColorTexture",W._colorsTexture,Z));const kr=Y.morphAttributes;if((kr.position!==void 0||kr.normal!==void 0||kr.color!==void 0)&&F.update(W,Y,Hn),(Nr||At.receiveShadow!==W.receiveShadow)&&(At.receiveShadow=W.receiveShadow,di.setValue(U,"receiveShadow",W.receiveShadow)),(V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial)&&V.envMap===null&&z.environment!==null&&(Xi.envMapIntensity.value=z.environmentIntensity),Xi.dfgLUT!==void 0&&(Xi.dfgLUT.value=nI()),Nr){if(di.setValue(U,"toneMappingExposure",T.toneMappingExposure),At.needsLights&&Jb(Xi,mc),bt&&V.fog===!0&&Kt.refreshFogUniforms(Xi,bt),Kt.refreshMaterialUniforms(Xi,V,st,ot,S.state.transmissionRenderTarget[P.id]),At.needsLights&&At.lightProbeGrid){const Mi=At.lightProbeGrid;Xi.probesSH.value=Mi.texture,Xi.probesMin.value.copy(Mi.boundingBox.min),Xi.probesMax.value.copy(Mi.boundingBox.max),Xi.probesResolution.value.copy(Mi.resolution)}of.upload(U,lv(At),Xi,Z)}if(V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(of.upload(U,lv(At),Xi,Z),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&di.setValue(U,"center",W.center),di.setValue(U,"modelViewMatrix",W.modelViewMatrix),di.setValue(U,"normalMatrix",W.normalMatrix),di.setValue(U,"modelMatrix",W.matrixWorld),V.uniformsGroups!==void 0){const Mi=V.uniformsGroups;for(let Fr=0,gc=Mi.length;Fr<gc;Fr++){const uv=Mi[Fr];nt.update(uv,Hn),nt.bind(uv,Hn)}}return Hn}function Jb(P,z){P.ambientLightColor.needsUpdate=z,P.lightProbe.needsUpdate=z,P.directionalLights.needsUpdate=z,P.directionalLightShadows.needsUpdate=z,P.pointLights.needsUpdate=z,P.pointLightShadows.needsUpdate=z,P.spotLights.needsUpdate=z,P.spotLightShadows.needsUpdate=z,P.rectAreaLights.needsUpdate=z,P.hemisphereLights.needsUpdate=z}function jb(P){return P.isMeshLambertMaterial||P.isMeshToonMaterial||P.isMeshPhongMaterial||P.isMeshStandardMaterial||P.isShadowMaterial||P.isShaderMaterial&&P.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return B},this.getRenderTarget=function(){return X},this.setRenderTargetTextures=function(P,z,Y){const V=K.get(P);V.__autoAllocateDepthBuffer=P.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),K.get(P.texture).__webglTexture=z,K.get(P.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:Y,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(P,z){const Y=K.get(P);Y.__webglFramebuffer=z,Y.__useDefaultFramebuffer=z===void 0},this.setRenderTarget=function(P,z=0,Y=0){X=P,k=z,B=Y;let V=null,W=!1,bt=!1;if(P){const wt=K.get(P);if(wt.__useDefaultFramebuffer!==void 0){R.bindFramebuffer(U.FRAMEBUFFER,wt.__webglFramebuffer),it.copy(P.viewport),rt.copy(P.scissor),Lt=P.scissorTest,R.viewport(it),R.scissor(rt),R.setScissorTest(Lt),J=-1;return}else if(wt.__webglFramebuffer===void 0)Z.setupRenderTarget(P);else if(wt.__hasExternalTextures)Z.rebindTextures(P,K.get(P.texture).__webglTexture,K.get(P.depthTexture).__webglTexture);else if(P.depthBuffer){const Se=P.depthTexture;if(wt.__boundDepthTexture!==Se){if(Se!==null&&K.has(Se)&&(P.width!==Se.image.width||P.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");Z.setupDepthRenderbuffer(P)}}const Ut=P.texture;(Ut.isData3DTexture||Ut.isDataArrayTexture||Ut.isCompressedArrayTexture)&&(bt=!0);const Yt=K.get(P).__webglFramebuffer;P.isWebGLCubeRenderTarget?(Array.isArray(Yt[z])?V=Yt[z][Y]:V=Yt[z],W=!0):P.samples>0&&Z.useMultisampledRTT(P)===!1?V=K.get(P).__webglMultisampledFramebuffer:Array.isArray(Yt)?V=Yt[Y]:V=Yt,it.copy(P.viewport),rt.copy(P.scissor),Lt=P.scissorTest}else it.copy(Xt).multiplyScalar(st).floor(),rt.copy(kt).multiplyScalar(st).floor(),Lt=Tt;if(Y!==0&&(V=C),R.bindFramebuffer(U.FRAMEBUFFER,V)&&R.drawBuffers(P,V),R.viewport(it),R.scissor(rt),R.setScissorTest(Lt),W){const wt=K.get(P.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+z,wt.__webglTexture,Y)}else if(bt){const wt=z;for(let Ut=0;Ut<P.textures.length;Ut++){const Yt=K.get(P.textures[Ut]);U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0+Ut,Yt.__webglTexture,Y,wt)}}else if(P!==null&&Y!==0){const wt=K.get(P.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,wt.__webglTexture,Y)}J=-1},this.readRenderTargetPixels=function(P,z,Y,V,W,bt,Rt,wt=0){if(!(P&&P.isWebGLRenderTarget)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ut=K.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Rt!==void 0&&(Ut=Ut[Rt]),Ut){R.bindFramebuffer(U.FRAMEBUFFER,Ut);try{const Yt=P.textures[wt],Se=Yt.format,Re=Yt.type;if(P.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+wt),!L.textureFormatReadable(Se)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!L.textureTypeReadable(Re)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}z>=0&&z<=P.width-V&&Y>=0&&Y<=P.height-W&&U.readPixels(z,Y,V,W,vt.convert(Se),vt.convert(Re),bt)}finally{const Yt=X!==null?K.get(X).__webglFramebuffer:null;R.bindFramebuffer(U.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(P,z,Y,V,W,bt,Rt,wt=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ut=K.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Rt!==void 0&&(Ut=Ut[Rt]),Ut)if(z>=0&&z<=P.width-V&&Y>=0&&Y<=P.height-W){R.bindFramebuffer(U.FRAMEBUFFER,Ut);const Yt=P.textures[wt],Se=Yt.format,Re=Yt.type;if(P.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+wt),!L.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!L.textureTypeReadable(Re))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const $t=U.createBuffer();U.bindBuffer(U.PIXEL_PACK_BUFFER,$t),U.bufferData(U.PIXEL_PACK_BUFFER,bt.byteLength,U.STREAM_READ),U.readPixels(z,Y,V,W,vt.convert(Se),vt.convert(Re),0);const ci=X!==null?K.get(X).__webglFramebuffer:null;R.bindFramebuffer(U.FRAMEBUFFER,ci);const Wi=U.fenceSync(U.SYNC_GPU_COMMANDS_COMPLETE,0);return U.flush(),await t3(U,Wi,4),U.bindBuffer(U.PIXEL_PACK_BUFFER,$t),U.getBufferSubData(U.PIXEL_PACK_BUFFER,0,bt),U.deleteBuffer($t),U.deleteSync(Wi),bt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,z=null,Y=0){const V=Math.pow(2,-Y),W=Math.floor(P.image.width*V),bt=Math.floor(P.image.height*V),Rt=z!==null?z.x:0,wt=z!==null?z.y:0;Z.setTexture2D(P,0),U.copyTexSubImage2D(U.TEXTURE_2D,Y,0,0,Rt,wt,W,bt),R.unbindTexture()},this.copyTextureToTexture=function(P,z,Y=null,V=null,W=0,bt=0){let Rt,wt,Ut,Yt,Se,Re,$t,ci,Wi;const Fi=P.isCompressedTexture?P.mipmaps[bt]:P.image;if(Y!==null)Rt=Y.max.x-Y.min.x,wt=Y.max.y-Y.min.y,Ut=Y.isBox3?Y.max.z-Y.min.z:1,Yt=Y.min.x,Se=Y.min.y,Re=Y.isBox3?Y.min.z:0;else{const Xi=Math.pow(2,-W);Rt=Math.floor(Fi.width*Xi),wt=Math.floor(Fi.height*Xi),P.isDataArrayTexture?Ut=Fi.depth:P.isData3DTexture?Ut=Math.floor(Fi.depth*Xi):Ut=1,Yt=0,Se=0,Re=0}V!==null?($t=V.x,ci=V.y,Wi=V.z):($t=0,ci=0,Wi=0);const ui=vt.convert(z.format),Us=vt.convert(z.type);let At;z.isData3DTexture?(Z.setTexture3D(z,0),At=U.TEXTURE_3D):z.isDataArrayTexture||z.isCompressedArrayTexture?(Z.setTexture2DArray(z,0),At=U.TEXTURE_2D_ARRAY):(Z.setTexture2D(z,0),At=U.TEXTURE_2D),R.activeTexture(U.TEXTURE0),R.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,z.flipY),R.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,z.premultiplyAlpha),R.pixelStorei(U.UNPACK_ALIGNMENT,z.unpackAlignment);const _n=R.getParameter(U.UNPACK_ROW_LENGTH),Ge=R.getParameter(U.UNPACK_IMAGE_HEIGHT),Hn=R.getParameter(U.UNPACK_SKIP_PIXELS),Sa=R.getParameter(U.UNPACK_SKIP_ROWS),Nr=R.getParameter(U.UNPACK_SKIP_IMAGES);R.pixelStorei(U.UNPACK_ROW_LENGTH,Fi.width),R.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Fi.height),R.pixelStorei(U.UNPACK_SKIP_PIXELS,Yt),R.pixelStorei(U.UNPACK_SKIP_ROWS,Se),R.pixelStorei(U.UNPACK_SKIP_IMAGES,Re);const mc=P.isDataArrayTexture||P.isData3DTexture,di=z.isDataArrayTexture||z.isData3DTexture;if(P.isDepthTexture){const Xi=K.get(P),kr=K.get(z),Mi=K.get(Xi.__renderTarget),Fr=K.get(kr.__renderTarget);R.bindFramebuffer(U.READ_FRAMEBUFFER,Mi.__webglFramebuffer),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,Fr.__webglFramebuffer);for(let gc=0;gc<Ut;gc++)mc&&(U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,K.get(P).__webglTexture,W,Re+gc),U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,K.get(z).__webglTexture,bt,Wi+gc)),U.blitFramebuffer(Yt,Se,Rt,wt,$t,ci,Rt,wt,U.DEPTH_BUFFER_BIT,U.NEAREST);R.bindFramebuffer(U.READ_FRAMEBUFFER,null),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else if(W!==0||P.isRenderTargetTexture||K.has(P)){const Xi=K.get(P),kr=K.get(z);R.bindFramebuffer(U.READ_FRAMEBUFFER,N),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,O);for(let Mi=0;Mi<Ut;Mi++)mc?U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,Xi.__webglTexture,W,Re+Mi):U.framebufferTexture2D(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,Xi.__webglTexture,W),di?U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,kr.__webglTexture,bt,Wi+Mi):U.framebufferTexture2D(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,kr.__webglTexture,bt),W!==0?U.blitFramebuffer(Yt,Se,Rt,wt,$t,ci,Rt,wt,U.COLOR_BUFFER_BIT,U.NEAREST):di?U.copyTexSubImage3D(At,bt,$t,ci,Wi+Mi,Yt,Se,Rt,wt):U.copyTexSubImage2D(At,bt,$t,ci,Yt,Se,Rt,wt);R.bindFramebuffer(U.READ_FRAMEBUFFER,null),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else di?P.isDataTexture||P.isData3DTexture?U.texSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Us,Fi.data):z.isCompressedArrayTexture?U.compressedTexSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Fi.data):U.texSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Us,Fi):P.isDataTexture?U.texSubImage2D(U.TEXTURE_2D,bt,$t,ci,Rt,wt,ui,Us,Fi.data):P.isCompressedTexture?U.compressedTexSubImage2D(U.TEXTURE_2D,bt,$t,ci,Fi.width,Fi.height,ui,Fi.data):U.texSubImage2D(U.TEXTURE_2D,bt,$t,ci,Rt,wt,ui,Us,Fi);R.pixelStorei(U.UNPACK_ROW_LENGTH,_n),R.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Ge),R.pixelStorei(U.UNPACK_SKIP_PIXELS,Hn),R.pixelStorei(U.UNPACK_SKIP_ROWS,Sa),R.pixelStorei(U.UNPACK_SKIP_IMAGES,Nr),bt===0&&z.generateMipmaps&&U.generateMipmap(At),R.unbindTexture()},this.initRenderTarget=function(P){K.get(P).__webglFramebuffer===void 0&&Z.setupRenderTarget(P)},this.initTexture=function(P){P.isCubeTexture?Z.setTextureCube(P,0):P.isData3DTexture?Z.setTexture3D(P,0):P.isDataArrayTexture||P.isCompressedArrayTexture?Z.setTexture2DArray(P,0):Z.setTexture2D(P,0),R.unbindTexture()},this.resetState=function(){k=0,B=0,X=null,R.reset(),St.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ja}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=ke._getDrawingBufferColorSpace(t),e.unpackColorSpace=ke._getUnpackColorSpace()}}class Yo{constructor(t){this.rateAt=t}static HISTORY_S=20;sums=[0];at(t){if(!(t>0))return 0;const e=Math.floor(t);for(;this.sums.length<=e+1;){const i=this.sums.length-1;this.sums.push(this.sums[i]+(this.rateAt(i)+this.rateAt(i+1))/2)}return this.sums[e]+(this.sums[e+1]-this.sums[e])*(t-e)}stateAt(t){return{impacts:this.at(t),history:Array.from({length:Yo.HISTORY_S},(e,i)=>this.at(t-i-1))}}}class Pe{static NONE={ghosts:[],blades:0,bladeAngleRad:0,scattered:0,drops:0,impacts:0,history:[],still:!1,running:0,reachDeg:30,placed:[]};static PHONE=[{scale:-1,share:5e-5,blur:.006,cause:"sensor",tint:[.41,1,.83]},{scale:-.45,share:5e-6,blur:.02,tint:[.7,1,.8]},{scale:.55,share:375e-8,blur:.035,tint:[1,.75,1]}];static CAMERA=[{scale:-1.4,share:3e-4,blur:.045,tint:[1,.8,1]},{scale:-.8,share:4e-4,blur:.02,tint:[.75,1,.8]},{scale:-.35,share:25e-5,blur:.012,tint:[1,.9,.7]},{scale:.3,share:2e-4,blur:.03,tint:[.8,.9,1]},{scale:.65,share:15e-5,blur:.06,tint:[1,.85,1]}];static FILTER={scale:-1,share:.001,blur:.004,cause:"filter"};static WINDOW={scale:1,share:.0016,blur:.002,offset:[0,.006],cause:"glass"};static WINDSCREEN={scale:1,share:.02,blur:.003,offset:[0,.025],cause:"glass"};static OFF_FRAME_REACH_DEG=30;static offFrameShare(t,e,i=Pe.OFF_FRAME_REACH_DEG){const s=Math.min(Math.max((t-e)/i,0),1);return 1-s*s*(3-2*s)}static REFERENCE_F_NUMBER=4;static of(t){return t.ghosts?t.ghosts:Pe.records(t)?t.category==="phone"?Pe.PHONE:Pe.CAMERA:[]}static records(t){return t.medium!==void 0||t.category==="camera"||t.category==="dslr"||t.category==="phone"}static optics(t,e,i,s,n=0){const a=Pe.of(t);if(a.length===0)return Pe.NONE;const r=t.fNumber??Pe.REFERENCE_F_NUMBER,o=e??r,l=[...a,...i?.ghosts??[]].map(y=>({...y,blur:y.blur*r/o}));i?.glass==="filter"?l.push({...Pe.FILTER}):i?.glass==="window"?l.push({...Pe.WINDOW}):i?.glass==="windscreen"&&l.push({...Pe.WINDSCREEN});const h=Pe.share(i?.condensation),u=Pe.share(i?.dirt),d=Pe.falling(i),f=d?s?.impacts??0:0,p=d?s?.history??[]:[],g=f-(p[Pe.DROP_LIFE_S-1]??0),m=i?.drops!==void 0?Pe.share(i.drops):d?Math.min(1,g):0;h>0&&(l.push({scale:1,share:.25*h,blur:.03,cause:"condensation"}),l.push({scale:1,share:.15*h,blur:.12,cause:"condensation"})),u>0&&(l.push({scale:1,share:.03*u,blur:.04,cause:"dirt"}),l.push({scale:1,share:.02*u,blur:.15,cause:"dirt"})),m>0&&l.push({scale:1,share:.12*m,blur:.025,cause:"drops"});const v=l.filter(y=>Pe.scatters(y)).reduce((y,w)=>y+w.share,0),M=Ts.bladesShowing(t,e)>=.5?t.apertureBlades??0:0,x=i?.glass==="window"||i?.glass==="windscreen"?1:.25;return{ghosts:l,blades:M,bladeAngleRad:.3,scattered:Math.min(.9,v),drops:m,impacts:f,history:p,still:i?.drops!==void 0,running:x,reachDeg:i?.reachDeg??Pe.OFF_FRAME_REACH_DEG,placed:(i?.placedDrops??[]).map(y=>Pe.placedAt(y,n))}}static placedAt(t,e){const i=t.track,s=i.findIndex(o=>o.t>e);if(s===0)return{x:i[0].x,y:i[0].y,radius:t.radius};if(s===-1){const o=i[i.length-1];return{x:o.x,y:o.y,radius:t.radius}}const n=i[s-1],a=i[s],r=(e-n.t)/(a.t-n.t);return{x:n.x+(a.x-n.x)*r,y:n.y+(a.y-n.y)*r,radius:t.radius}}static falling(t){return t?.drops===void 0&&!t?.sheltered}static DROP_LIFE_S=8;static impactRate(t,e,i){const s=Pe.dropsFrom(t);if(s===0)return 0;const n=t.precipitationType==="snow"?1:6.5,a=((i?.windFromDeg??0)+180)*Math.PI/180,r=i?.windSpeedMS??0,o=[Math.sin(a)*r,Math.cos(a)*r,-n],l=(i?.headingDeg??0)*Math.PI/180,h=(e==="window"?0:e==="windscreen"?60:i?.pitchDeg??0)*Math.PI/180,u=[Math.sin(l)*Math.cos(h),Math.cos(l)*Math.cos(h),Math.sin(h)],d=Math.hypot(o[0],o[1],o[2]),f=Math.max(0,-(o[0]*u[0]+o[1]*u[1]+o[2]*u[2])/d);return s*.4*(.02+.98*f)}static scatters(t){return t.cause==="condensation"||t.cause==="dirt"||t.cause==="drops"}static dropsFrom(t){if(!t||t.precipitationType==="none"||t.precipitationType==="hail")return 0;const e=Pe.share(t.precipitationIntensity);return e===0?0:t.precipitationType==="snow"?.5*e:Math.min(1,.3+.7*e)}static positionOf(t,e){return{x:e.x*t.scale+2*(t.offset?.[0]??0),y:e.y*t.scale+2*(t.offset?.[1]??0)}}static sourceOf(t,e){return{x:(e.x-2*(t.offset?.[0]??0))/t.scale,y:(e.y-2*(t.offset?.[1]??0))/t.scale}}static share(t){return Math.max(0,Math.min(1,t??0))}}const xs=Math.PI/180;class ee{constructor(t){this.words=t}static COARSE_DEG=2;static FINE_DEG=.25;findingsOf(t,e){const i=Ls.strip(e).recording,s=i.interpretation?.mechanism;if(!s)return[];const n=ee.settingOf(t,s.explains);if(!n)return[];const a="interpretation.mechanism";switch(s.kind){case"fixed-in-frame":{const r=ee.missOf(n.samples,ee.fixedPoint(n.samples));return[this.finding(this.words.bestFixed,r,n,{},"established",a)]}case"driven-one-way":{const{miss:r,directionDeg:o}=ee.oneWay(n.samples);return[this.finding(this.words.bestOneWay,r,n,{direction:Math.round(o)},"established",a)]}case"lens-ghost":return this.lensGhostFindings(n,i,a);case"stated-ghost":return this.statedGhostFindings(n,i,a);case"ghost-of":return this.ghostOfFindings(n,i,s.of,a);case"real-object":return[this.realObjectFinding(n,i,s.explains,a)]}}ghostOfFindings(t,e,i,s){const n=e.interpretation?.bodies?.find(u=>u.id===i);if(!n)return[];const a=t.samples.map(u=>{const d=ee.bodyDirectionAt(n,u.t);if(!d)return;const f=d.applyQuaternion(u.frame.inverse);return f.z<0?{x:f.x/-f.z,y:f.y/-f.z}:void 0}),r=Pe.of(Ts.byId(e.instrument)).filter(u=>!Pe.scatters(u)).map(u=>u.scale);let o;for(const u of r){const d=a.map(p=>p?{x:u*p.x,y:u*p.y}:void 0),f=ee.missOfTrack(t.samples,d);(!o||f.medianDeg<o.miss.medianDeg)&&(o={miss:f,k:u,track:d})}if(!o)return[];const l=o.track.filter(u=>u!==void 0);let h=0;for(const u of l)for(const d of l)h=Math.max(h,ee.angleDeg(u,d));return[this.finding(this.words.bestGhostOf,o.miss,t,{k:this.number(o.k),ghostTravel:this.number(h)},"established",s)]}realObjectFinding(t,e,i,s){const a=e.interpretation?.bodies?.find(l=>l.explains?.includes(i))?.track[0]?.distanceM??ee.DEFAULT_DISTANCE_M,r=t.samples.map(l=>new _(l.at.x,l.at.y,-1).normalize().applyQuaternion(l.frame.rotation));let o=0;for(let l=0;l<r.length;l++){const h=t.samples.findIndex(u=>u.t>=t.samples[l].t+ee.RATE_WINDOW_MS);if(h<0)break;o=Math.max(o,r[l].angleTo(r[h])/((t.samples[h].t-t.samples[l].t)/1e3))}return{text:this.fill(this.words.bestRealObject,{medianDeg:0,maxDeg:0},t,{distance:Math.round(a),width:this.number(a*t.sizeDeg*xs),speed:Math.round(a*o)}),outcome:"holds",against:"established",path:s}}static bodyDirectionAt(t,e){const i=t.track.filter(l=>l.azimuthDeg!==void 0&&l.altitudeDeg!==void 0);if(i.length===0)return;const s=i.findIndex(l=>l.t>e),n=i[s<=0?s===0?0:i.length-1:s-1],a=s<=0?n:i[s],r=a.t>n.t?(e-n.t)/(a.t-n.t):0,o=((a.azimuthDeg-n.azimuthDeg)%360+540)%360-180;return ee.direction(n.azimuthDeg+o*r,n.altitudeDeg+(a.altitudeDeg-n.altitudeDeg)*r)}static DEFAULT_DISTANCE_M=1e3;static RATE_WINDOW_MS=500;static lays(t){return t?.kind==="fixed-in-frame"||t?.kind==="driven-one-way"||t?.kind==="real-object"}bestSceneOf(t,e){const s=Ls.strip(e).recording.interpretation?.mechanism;if(!ee.lays(s))return;const n=ee.settingOf(t,s.explains);if(!n)return;const a=structuredClone(e);if(s.kind==="fixed-in-frame"||s.kind==="real-object"){const r=a.interpretation??{bodies:[]},o=r.bodies??[],l=o.findIndex(d=>d.explains?.includes(s.explains)),h=l>=0?o[l]:void 0,u=s.kind==="fixed-in-frame"?ee.stillBody(n,s.explains,h):ee.sightLineBody(n,s.explains,h);a.interpretation={...r,bodies:l>=0?o.map((d,f)=>f===l?u:d):[...o,u]}}else{const{track:r}=ee.oneWay(n.samples),o=a.lens?.placedDrops?.[0],l=n.samples[0],h=o?.radius??ee.round(n.sizeDeg/l.frame.fovDeg,4),u=n.samples.map((d,f)=>{const p=Math.tan(d.frame.fovDeg/2*xs);return{t:d.t,x:ee.round(.5+r[f].x/(2*p*n.aspect),4),y:ee.round(.5-r[f].y/(2*p),4)}});a.lens={...a.lens,placedDrops:[{radius:h,track:u}]}}return a}static stillBody(t,e,i){const s=ee.fixedPoint(t.samples),n=t.samples[0].t,a=t.samples[t.samples.length-1].t,r=[...new Set([...t.samples.map(o=>o.t),...t.keyframes.map(o=>o.t).filter(o=>o>n&&o<a)])].sort((o,l)=>o-l);return ee.bodyAlong(t,e,i,r,()=>s)}static sightLineBody(t,e,i){return ee.bodyAlong(t,e,i,t.samples.map(s=>s.t),(s,n)=>t.samples[n].at)}static bodyAlong(t,e,i,s,n){const a=s[s.length-1],r=i?.track[0],o=r?.distanceM??ee.DEFAULT_DISTANCE_M,l=r?.sizeM??(()=>{const f=ee.round(o*t.sizeDeg*xs,4);return{widthM:f,lengthM:f,heightM:f}})(),h=r?.appearance??{color:"#f4f6f5"},u=s.map((f,p)=>{const g=n(f,p),m=new _(g.x,g.y,-1).normalize().applyQuaternion(ee.frameAt(t.keyframes,f).rotation);return{t:f,...p===0?{present:!0,sizeM:l,appearance:h}:{},azimuthDeg:ee.round((Math.atan2(m.x,-m.z)/xs+360)%360,3),altitudeDeg:ee.round(Math.asin(Math.min(1,Math.max(-1,m.y)))/xs,3),distanceM:o}}),d=s.length>1?s[s.length-1]-s[s.length-2]:40;return{...i??{id:e,explains:[e],model:{id:"sphere"}},track:[...u,{t:a+d,present:!1}]}}static round(t,e){return Math.round(t*10**e)/10**e}lensGhostFindings(t,e,i){const s=Pe.of(Ts.byId(e.instrument)).filter(l=>!Pe.scatters(l)).map(l=>l.scale),n=e.lens?.reachDeg??Pe.OFF_FRAME_REACH_DEG,a=l=>{const h=ee.sunTrack(t,l,n);if(!h)return;let u;for(const d of s){const f=ee.missOfTrack(t.samples,h.map(p=>({x:d*p.x,y:d*p.y})));(!u||f.medianDeg<u.miss.medianDeg)&&(u={miss:f,k:d})}return u},r=ee.bestSun(t,!0,a),o=[];if(r?o.push(this.finding(this.words.bestGhost,r.result.miss,t,{...this.sunWords(r.sun),k:this.number(r.result.k)},t.lightingGround,i)):o.push({text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:i}),t.lighting&&(!r||r.result.miss.medianDeg>t.sizeDeg)){const l=ee.bestSun(t,!1,a);l&&(!r||l.result.miss.medianDeg<r.result.miss.medianDeg-1e-6)&&o.push({text:this.fill(this.words.bestGhostNeeds,l.result.miss,t,{...this.sunWords(l.sun),k:this.number(l.result.k)}),outcome:"fails",against:t.lightingGround,path:"lighting"})}return o}statedGhostFindings(t,e,i){const s=e.lens?.reachDeg??Pe.OFF_FRAME_REACH_DEG,n=o=>{const l=ee.sunTrack(t,o,s);if(!l)return;const h=ee.linearFit(l,t.samples.map(d=>d.at)),u=l.map(d=>({x:h.k*d.x+h.offset.x,y:h.k*d.y+h.offset.y}));return{miss:ee.missOfTrack(t.samples,u),...h}},a=ee.bestSun(t,!0,n);if(!a)return[{text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:i}];const r=Math.atan(Math.hypot(a.result.offset.x,a.result.offset.y))/xs;return[this.finding(this.words.bestStatedGhost,a.result.miss,t,{...this.sunWords(a.sun),k:this.number(a.result.k),offset:this.number(r)},t.lightingGround,i)]}finding(t,e,i,s,n,a){return{text:this.fill(t,e,i,s),outcome:e.medianDeg<=i.sizeDeg?"holds":"fails",against:n,path:a}}fill(t,e,i,s){const n={median:this.number(e.medianDeg),max:this.number(e.maxDeg),size:this.number(i.sizeDeg),travel:this.number(i.travelDeg),...s};return t.replace(/\{(\w+)\}/g,(a,r)=>r in n?String(n[r]):a)}sunWords(t){return{bearing:Math.round(t.bearing),altitude:this.number(t.altitudeDeg)}}number(t){const e=Math.abs(t)<1?2:1;return t.toFixed(e).replace(".",this.words.decimal)}static settingOf(t,e){const{recording:i,provenance:s}=Ls.strip(t),n=i.observerTrack?.keyframes??[];if(n.length===0)return;const a=Ts.aspectOf(Ts.byId(i.instrument)),r=[],o=[];for(const d of i.timeline?.keyframes??[])for(const f of d.shapes??[]){const p=f.shape;if(f.sourceId!==e||!p.aim)continue;const g=ee.frameAt(n,d.t),m=ee.direction(p.aim.azimuthDeg,p.aim.altitudeDeg).applyQuaternion(g.inverse);m.z>=0||(r.push({t:d.t,at:{x:m.x/-m.z,y:m.y/-m.z},frame:g}),p.angular?.widthDeg&&o.push(p.angular.widthDeg))}if(r.length===0)return;o.sort((d,f)=>d-f);let l=0;for(const d of r)for(const f of r)l=Math.max(l,ee.angleDeg(d.at,f.at));const h=n[0].pose,u=h.lat??0;return{samples:r,keyframes:n,sizeDeg:o.length>0?o[Math.floor(o.length/2)]:.5,travelDeg:l,aspect:a,headingDeg:h.headingDeg??0,lighting:i.lighting,lightingGround:Ls.free(s.at("lighting"))?"supposed":"established",altitudes:{minDeg:-Math.acos(6371e3/(6371e3+Math.max(h.elevationM??0,0)))/xs,maxDeg:ee.highestSun(i.time,s.at("time")?.range,u,h.lng??0)}}}static highestSun(t,e,i,s){const[n,a]=(typeof e=="string"?e:t??"").split("/"),r=n?jn(n):void 0,o=a?jn(a):r;if(!r||!o)return 90;const l=kn.earliestOf(r),h=kn.latestOf(o),u=864e5;let d=-90;for(let f=Math.floor(l/u)*u;f<=h;f+=u){const p=f+(12-s/15)*36e5;for(let g=-60;g<=60;g+=10)d=Math.max(d,Wo("Sun",new Date(p+g*6e4),{lat:i,lng:s,elevationM:0}).altitudeDeg)}return d}static frameAt(t,e){const i=t.findIndex(u=>u.t>e),s=t[i<=0?i===0?0:t.length-1:i-1],n=i<=0?s:t[i],a=n.t>s.t?(e-s.t)/(n.t-s.t):0,r=(u,d,f)=>(u??f)+((d??u??f)-(u??f))*a,o=(((n.pose.headingDeg??0)-(s.pose.headingDeg??0))%360+540)%360-180,l=(s.pose.headingDeg??0)+o*a,h=new Fs().setFromEuler(new Ma(r(s.pose.pitchDeg,n.pose.pitchDeg,0)*xs,-l*xs,r(s.pose.rollDeg,n.pose.rollDeg,0)*xs,"YXZ"));return{rotation:h,inverse:h.clone().invert(),fovDeg:r(s.pose.fovDeg,n.pose.fovDeg,50)}}static direction(t,e){const i=t*xs,s=e*xs;return new _(Math.sin(i)*Math.cos(s),Math.sin(s),-Math.cos(i)*Math.cos(s))}static angleDeg(t,e){const i=(t.x*e.x+t.y*e.y+1)/Math.sqrt((t.x*t.x+t.y*t.y+1)*(e.x*e.x+e.y*e.y+1));return Math.acos(Math.min(1,Math.max(-1,i)))/xs}static missOf(t,e){return ee.missOfTrack(t,t.map(()=>e))}static missOfTrack(t,e){const i=t.map((s,n)=>e[n]?ee.angleDeg(s.at,e[n]):180).sort((s,n)=>s-n);return{medianDeg:i[Math.floor(i.length/2)],maxDeg:i[i.length-1]}}static fixedPoint(t){let e={x:t.reduce((i,s)=>i+s.at.x,0)/t.length,y:t.reduce((i,s)=>i+s.at.y,0)/t.length};for(let i=0;i<100;i++){let s=0,n=0,a=0;for(const r of t){const o=1/Math.max(Math.hypot(r.at.x-e.x,r.at.y-e.y),1e-9);s+=r.at.x*o,n+=r.at.y*o,a+=o}e={x:s/a,y:n/a}}return e}static oneWay(t){let e;for(let i=0;i<360;i+=5){const s={x:Math.sin(i*xs),y:Math.cos(i*xs)},n={x:s.y,y:-s.x},a=t.map(d=>d.at.x*s.x+d.at.y*s.y),r=t.map(d=>d.at.x*n.x+d.at.y*n.y).sort((d,f)=>d-f),o=r[Math.floor(r.length/2)],h=ee.neverBack(a).map(d=>({x:d*s.x+o*n.x,y:d*s.y+o*n.y})),u=ee.missOfTrack(t,h);(!e||u.medianDeg<e.miss.medianDeg||u.medianDeg===e.miss.medianDeg&&u.maxDeg<e.miss.maxDeg)&&(e={miss:u,directionDeg:i,track:h})}return e}static neverBack(t){const e=[];for(const i of t)for(e.push({sum:i,count:1});e.length>1&&e[e.length-2].sum/e[e.length-2].count>e[e.length-1].sum/e[e.length-1].count;){const s=e.pop();e[e.length-1].sum+=s.sum,e[e.length-1].count+=s.count}return e.flatMap(i=>new Array(i.count).fill(i.sum/i.count))}static sunTrack(t,e,i){const s=ee.direction(t.headingDeg+e.bearing,e.altitudeDeg),n=[];for(const a of t.samples){const r=s.clone().applyQuaternion(a.frame.inverse),o=Math.acos(Math.min(1,Math.max(-1,-r.z)))/xs,l=Math.tan(a.frame.fovDeg/2*xs),h=Math.atan(l*Math.hypot(1,t.aspect))/xs;if(r.z>=0||o>=h+i)return;n.push({x:r.x/-r.z,y:r.y/-r.z})}return n}static linearFit(t,e){const i=t.length,s=h=>({x:h.reduce((u,d)=>u+d.x,0)/i,y:h.reduce((u,d)=>u+d.y,0)/i}),n=s(t),a=s(e);let r=0,o=0;for(let h=0;h<i;h++)r+=(t[h].x-n.x)*(e[h].x-a.x)+(t[h].y-n.y)*(e[h].y-a.y),o+=(t[h].x-n.x)**2+(t[h].y-n.y)**2;const l=o>1e-12?r/o:0;return{k:l,offset:{x:a.x-l*n.x,y:a.y-l*n.y}}}static bestSun(t,e,i){const s=h=>h.altitudeDeg>=t.altitudes.minDeg&&h.altitudeDeg<=t.altitudes.maxDeg&&(!e||!t.lighting||ee.lights(t.lighting,h));let n;const a=h=>{if(!s(h))return;const u=i(h);u&&(!n||u.miss.medianDeg<n.result.miss.medianDeg)&&(n={sun:h,result:u})},{minDeg:r,maxDeg:o}=t.altitudes;for(let h=0;h<360;h+=ee.COARSE_DEG){for(let u=r;u<=o;u+=ee.COARSE_DEG/2)a({bearing:h,altitudeDeg:u});a({bearing:h,altitudeDeg:o})}if(!n)return;const l=n.sun;for(let h=-2;h<=ee.COARSE_DEG;h+=ee.FINE_DEG)for(let u=-2;u<=ee.COARSE_DEG;u+=ee.FINE_DEG)a({bearing:((l.bearing+h)%360+360)%360,altitudeDeg:l.altitudeDeg+u});return n}static lights(t,e){const i=t.sunFromViewDeg,s=i?((e.bearing-i.fromDeg)%360+360)%360:0,n=i?((i.toDeg-i.fromDeg)%360+360)%360:360,a=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return s<=n&&a}}const rI=[{path:"place.locations.0.lat",what:"latitude"},{path:"place.locations.0.lng",what:"longitude"}];class cs{constructor(t){this.words=t,this.bestCases=new ee(t)}bestCases;found=new WeakMap;findingsOf(t,e){const i=Ls.strip(t),s=Ls.strip(e).recording,n=[],a=this.timeFinding(i.recording.time,i.provenance.at("time"),s.time);a&&n.push(a);for(const{path:o,what:l}of rI){const h=this.numberFinding(cs.at(i.recording,o),i.provenance.at(o),cs.at(s,o),this.words[l]);h&&n.push({...h,path:o})}const r=i.recording.lighting;if(r&&cs.movesTheSun(i.recording,s)){const o=this.lightingFinding(r,i.provenance.at("lighting"),s);o&&n.push(o)}return n.push(...this.bestCasesOf(t,e)),n}bestCasesOf(t,e){const i=JSON.stringify([e.interpretation?.mechanism,e.lens,e.instrument]),s=this.found.get(e);if(s&&s.account===t&&s.key===i)return s.findings;const n=this.bestCases.findingsOf(t,e);return this.found.set(e,{account:t,key:i,findings:n}),n}static withinInterval(t,e){const[i,s]=e.split("/"),n=i?jn(i):void 0,a=s?jn(s):void 0;if(!(!n&&!a))return!(n&&t.getTime()<kn.earliestOf(n)||a&&t.getTime()>kn.latestOf(a))}timeFinding(t,e,i){if(t===void 0||i===void 0||t===i)return;const s=jn(i),n=s?xr(s,0,0):void 0;if(typeof e?.range=="string"&&n){const a=cs.withinInterval(n,e.range);if(a===void 0)return;const r=a?this.words.timeWithin:this.words.timeOutside;return{text:cs.fill(r,{time:i,range:e.range}),outcome:a?"holds":"fails",against:"established",path:"time"}}if(!Ls.free(e))return{text:cs.fill(this.words.timeChanged,{from:t,time:i}),outcome:"fails",against:"established",path:"time"}}numberFinding(t,e,i,s){if(!(typeof t!="number"||typeof i!="number"||Math.abs(t-i)<1e-9)){if(Array.isArray(e?.range)){const[n,a]=e.range,r=i>=n&&i<=a;return{text:cs.fill(r?this.words.valueWithin:this.words.valueOutside,{what:s,value:i,min:n,max:a}),outcome:r?"holds":"fails",against:"established"}}if(!Ls.free(e))return{text:cs.fill(this.words.valueChanged,{what:s,from:t,value:i}),outcome:"fails",against:"established"}}}static movesTheSun(t,e){const i=a=>a.observerTrack?.keyframes?.[0]?.pose,s=i(t),n=i(e);return t.time!==e.time||t.utcOffsetHours!==e.utcOffsetHours||JSON.stringify(t.place)!==JSON.stringify(e.place)||s?.lat!==n?.lat||s?.lng!==n?.lng||s?.headingDeg!==n?.headingDeg}lightingFinding(t,e,i){const s=i.time?jn(i.time):void 0,n=s?cs.sunOf(s,i):void 0;if(!n)return;const{bearing:a}=n,{fromDeg:r,toDeg:o}=t.sunFromViewDeg??{fromDeg:0,toDeg:360},{minDeg:l,maxDeg:h}=t.sunAltitudeDeg??{minDeg:-90,maxDeg:90},u=cs.lights(t,n),d=Ls.free(e)?"supposed":"established",f=p=>Math.round(p);return{text:cs.fill(u?this.words.lightingHolds:this.words.lightingFails,{bearing:f(a),altitude:f(n.altitudeDeg),from:r,to:o,altitudes:t.sunAltitudeDeg?cs.fill(this.words.altitudes,{min:l,max:h}):""}),outcome:u?"holds":"fails",against:d,path:"lighting",...e?.rationale?{rationale:e.rationale}:{}}}static standOf(t){const e=Ls.strip(t).recording,i=e.observerTrack?.keyframes?.[0]?.pose,s=e.place?.locations?.[0],n=i?.lat??s?.lat,a=i?.lng??s?.lng;if(!(n===void 0||a===void 0||i?.headingDeg===void 0))return{lat:n,lng:a,elevationM:i.elevationM??0,headingDeg:i.headingDeg,utcOffsetHours:e.utcOffsetHours}}static sunOf(t,e){const i=cs.standOf(e);return i?cs.sunFrom(t,i):void 0}static sunFrom(t,e){if(t.hour===void 0)return;const i=xr(t,e.lng,e.utcOffsetHours);if(!i)return;const s=Wo("Sun",i,e);return{bearing:((s.azimuthDeg-e.headingDeg)%360+360)%360,altitudeDeg:s.altitudeDeg}}static lights(t,e){const i=t.sunFromViewDeg?cs.onArc(e.bearing,t.sunFromViewDeg.fromDeg,t.sunFromViewDeg.toDeg):!0,s=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return i&&s}static nearestLit(t,e,i){const s=u=>({...e,hour:Math.floor(u/60),minute:u%60,second:void 0,raw:void 0}),n=cs.standOf(i);if(!n)return;const a=u=>{const d=cs.sunFrom(s(u),n);return d!==void 0&&cs.lights(t,d)};if(e.hour===void 0)return;const r=e.hour*60+(e.minute??0);if(a(r))return e;const o=5;let l;for(let u=0;u<1440;u+=o)a(u)&&(l===void 0||Math.abs(u-r)<Math.abs(l-r))&&(l=u);if(l===void 0)return;const h=r<l?-1:1;for(;l+h>=0&&l+h<1440&&a(l+h)&&Math.abs(l+h-r)<Math.abs(l-r);)l+=h;return s(l)}static onArc(t,e,i){const s=((i-e)%360+360)%360;return((t-e)%360+360)%360<=s}static at(t,e){return e.split(".").reduce((i,s)=>i?.[s],t)}static fill(t,e){return t.replace(/\{(\w+)\}/g,(i,s)=>s in e?String(e[s]):i)}}const eL=fc.catalog({en:()=>Ht(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(c=>c.readingCheckTexts_en),fr:()=>Ht(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(c=>c.readingCheckTexts_fr),es:()=>Ht(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(c=>c.readingCheckTexts_es),it:()=>Ht(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(c=>c.readingCheckTexts_it)});class iL{static of(t){if(!(!t||t.length===0))return t.some(e=>e.outcome==="fails"&&e.against!=="supposed")?"incompatible":t.some(e=>e.outcome!=="holds")?"unsettled":"compatible"}}class nn{constructor(t,e,i,s="en"){this.parts=t,this.messages=e,this.onChange=i,this.locale=s,e&&this.setMessages(e),t.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),t.picker.addEventListener("change",()=>this.writeFromPicker()),t.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),t.text.addEventListener("blur",()=>this.validate()),t.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";setBounds(t){this.bounds=t;const{picker:e}=this.parts;e.min=t?nn.pickerValueOf(t.min):"",e.max=t?nn.pickerValueOf(t.max):""}bounds;bounded(t){if(!this.bounds)return t;const e=kn.latestOf(t)<kn.earliestOf(this.bounds.min)?this.bounds.min:kn.earliestOf(t)>kn.earliestOf(this.bounds.max)?this.bounds.max:t;return this.bounds.adjust?.(e)??e}get isPrecise(){return this.precise}setMessages(t,e=this.locale){this.messages=t,this.locale=e,t.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=t.edtfPlaceholder),this.parts.mode.title=t.edtfModeTitle,this.parts.mode.setAttribute("aria-label",t.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(t){this.precise=t,this.parts.picker.hidden=!t,this.parts.text.hidden=t,this.parts.mode.textContent=(t?this.messages?.datePrecise:this.messages?.dateEdtf)??"",this.parts.mode.setAttribute("aria-pressed",String(!t)),this.parts.help&&(this.parts.help.hidden=t),this.showDeduction()}set(t){const{text:e,picker:i}=this.parts;e.value=t?al(t):"",i.type!=="date"&&(i.step=nn.stepFor(t)),i.value=i.type==="date"?nn.pickerDateOf(t):nn.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||nn.isPickable(e)&&nn.qualifierOf(al(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||nn.isFullDate(e)&&nn.qualifierOf(al(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!nn.isFullDate(t))return"";const e=(i,s=2)=>String(i).padStart(s,"0");return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}`}static isPickable(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0&&t.hour!==void 0&&t.minute!==void 0}static pickerValueOf(t){if(!nn.isPickable(t))return"";const e=(s,n=2)=>String(s).padStart(n,"0"),i=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${i}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),i=/[~%]/.test(t);return e&&i?"%":e?"?":i?"~":""}describe(t){return this.messages?nn.describeTime(t,this.messages,this.locale):""}static describeTime(t,e,i){const s=al(t),n=nn.qualifierOf(s),a=h=>String(h).padStart(2,"0"),r=[];if(t.season!==void 0){const h={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];r.push(t.year!==void 0?`${h} ${t.year}`:h)}else if(t.year!==void 0){const h=t.day!==void 0?{...t.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:t.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},u=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));r.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(u))}t.hour!==void 0&&r.push(`${a(t.hour)}:${a(t.minute??0)}${t.second!==void 0?`:${a(t.second)}`:""}`);const o=r.join(", "),l=n==="~"?e.timeQualifierApproximate:n==="?"?e.timeQualifierUncertain:n==="%"?e.timeQualifierBoth:"";return l?`${o} — ${l.toLowerCase()}`:o}setHint(t){this.hint=t,this.showDeduction()}showDeduction(){const{text:t}=this.parts,e=t.value.trim();if(this.precise||e===""){t.title=this.hint;return}const i=jn(e);t.title=i?`→ ${this.describe(i)}`:this.messages?.edtfInvalid??""}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=jn(t);if(!e)return;this.clean();const i=this.bounded(e);i!==e&&this.set(i),this.onChange(i)}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:t,text:e}=this.parts;t.value===""&&t.validity.badInput||(e.value=t.value===""?"":t.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:t}=this.parts,e=t.value.trim();e===""||jn(e)||(t.setCustomValidity(this.messages?.edtfInvalid??""),t.classList.add("invalid"))}}const by="#ff2200",Sy="#00ff44",Do="#ffffff",bd="#ffa500",Hc="#ff0000",oI="#2244ff",Pg=[{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:by,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Sy,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:Do,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:Do,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:Do,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:by,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Sy,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:Do,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:Do,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:Do,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:Do,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Hc,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Hc,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:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:bd,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:oI,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Hc,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>fe.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>fe.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 Ff{static forKind(t){return Pg.filter(e=>e.kinds.includes(t))}static byId(t){return Pg.find(e=>e.id===t)}}class fe{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(t){const e=(t%180+180)%180;return e>=45&&e<135?1:0}static vehicleLights(t){const e=t*fe.CYCLE_S/2,i=fe.VEHICLE_HEAD_Y_M,s=fe.LENS_SPACING_M;return[fe.lamp("red",fe.RED,i+s,e+fe.GREEN_S+fe.AMBER_S,fe.CYCLE_S-fe.GREEN_S-fe.AMBER_S,fe.VEHICLE_INTENSITY),fe.lamp("amber",fe.AMBER,i,e+fe.GREEN_S,fe.AMBER_S,fe.VEHICLE_INTENSITY),fe.lamp("green",fe.GREEN,i-s,e,fe.GREEN_S,fe.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*fe.CYCLE_S/2+fe.GREEN_S+fe.AMBER_S+fe.PEDESTRIAN_DELAY_S,i=fe.PEDESTRIAN_HEAD_Y_M,s=fe.LENS_SPACING_M/2;return[fe.lamp("ped-red",fe.RED,i+s,e+fe.PEDESTRIAN_GREEN_S,fe.CYCLE_S-fe.PEDESTRIAN_GREEN_S,fe.PEDESTRIAN_INTENSITY),fe.lamp("ped-green",fe.GREEN,i-s,e,fe.PEDESTRIAN_GREEN_S,fe.PEDESTRIAN_INTENSITY)]}static isPedestrian(t){return t?.some(e=>e.id==="ped-green")??!1}static figureOf(t){return t.id==="ped-red"?"standing":t.id==="ped-green"?"walking":void 0}static lamp(t,e,i,s,n,a){const r=fe.CYCLE_S,o=Math.round(((1-s/r)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:a,radiusM:fe.LENS_RADIUS_M,beamDeg:fe.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/r,dutyCycle:Math.round(n/r*1e6)/1e6,...o?{phase:o}:{}}}}}class qh{static of(t,e){const i=qh.drawnAsModel(t);return{color:e?.color??!i,lit:e?.lit??qh.litByDefault(t.kind,i),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&qh.rigsFor(t.kind,e).length>0,windows:!i&&wx(t.kind),floors:!i&&t.kind==="building",observerSide:Hl(t.kind)}}static rigsFor(t,e){return Ff.forKind(t).filter(i=>e?.lightRigs===void 0||e.lightRigs.includes(i.id))}static drawnAsModel(t){return mf(t)!==void 0&&!(t.observerSide!==void 0&&Hl(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class fi{static sideLabel(t){return fi.SIDE_LABELS[t]}static SIDE_LABELS={front:"front",behind:"behind",left:"left",right:"right","front-left":"frontLeft","front-right":"frontRight","behind-left":"behindLeft","behind-right":"behindRight"};static WINDOWS="windows";static BUILDING="building";static BRIDGE="bridge";static RAILING="railing";static WIRE="overheadLine";static together(t,e){return`${t} ${e}`}static of(t,e){const i=[],s=qh.drawnAsModel(t);if(!s&&t.kind==="building"&&i.push(...fi.floors(),...fi.walls(),...fi.roof()),!s&&wx(t.kind)&&i.push(...fi.windows(t.kind)),t.kind==="vehicle"&&i.push(...fi.engine()),t.kind==="observer"&&i.push(...fi.observerRecording()),t.kind==="aircraft"&&i.push(...fi.aircraftSound(e)),t.kind==="bridge"&&i.push(...fi.bridge()),t.kind==="wire"&&i.push(...fi.wire()),e?.parameters&&i.push(...e.parameters.map(n=>({...n,key:`modelParameters.${n.key}`}))),i.length!==0)return{kind:`decor-${t.kind}`,title:"properties",parameters:i}}static floors(){const t=e=>Ch.read(e,"floors")??gf;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>gf,label:"floors",hint:"upperStoriesAboveTheGround",group:fi.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:"occupiedFloor",hint:"theFloorTheWitnessIs",group:fi.BUILDING}]}static walls(){const t="walls";return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:"wallColour",hint:"theColourOfTheWalls"},{type:"choice",key:"facade.openings",group:t,label:"facade",empty:"aHouseS",hint:"aHouseSAWindowEvery",choices:[{value:"tall",label:"oldBuilding"},{value:"lancet",label:"church"},{value:"plain",label:"bareWall"},{value:"none",label:"noFacade"}]}]}static roof(){const t="roof";return[{type:"choice",key:"roof.shape",group:t,label:"roof",empty:"flat",hint:"flatTheBoxTwoSlopes",choices:[{value:"flat",label:"flat"},{value:"gable",label:"twoSlopes"},{value:"hip",label:"fourSlopes"},{value:"dome",label:"dome"}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:"rise",hint:"howFarTheRidgeStands",visibleWhen:i=>["gable","hip","dome"].includes(String(Ch.read(i,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:"ridgeAlong",empty:"theWidth",choices:[{value:"width",label:"theWidth"},{value:"depth",label:"theDepth"}],visibleWhen:i=>Ch.read(i,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:"roofColour"}]}static windows(t){return lS(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:uS(t,e)?0:hS,max:100,label:fi.SIDE_LABELS[e],summary:fi.together(fi.WINDOWS,fi.SIDE_LABELS[e]),hint:"opacityOfTheWindowOn",group:fi.WINDOWS}))}static engine(){const t="engineSound";return[{type:"choice",key:"engine.kind",group:t,label:"engine",hint:"whetherTheVehicleIsHeard",empty:"silentParked",choices:[{value:"car",label:"car"},{value:"van",label:"van"},{value:"truck",label:"truck"},{value:"motorcycle",label:"motorcycle"},{value:"generic",label:"unknown"}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:"loudness",hint:"againstAnOrdinaryOneOf",visibleWhen:e=>Ch.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:"theirOwnRecordingURL"}]}static aircraftSound(t){return[{type:"choice",key:"aircraftSound",group:"sound",label:"noiseInFlight",hint:"whatItSoundsLikeWhile",empty:t?.sound==="silent"?"silentAsTheModel":"asTheModel",choices:[{value:"airliner-narrow",label:"aircraftNarrowBodyAirliner"},{value:"airliner-wide",label:"aircraftWideBodyAirliner"},{value:"airliner-supersonic",label:"aircraftSupersonicAirliner"},{value:"regional-jet",label:"aircraftRegionalJet"},{value:"regional-turboprop",label:"aircraftTurboprop"},{value:"business-jet",label:"aircraftBusinessJet"},{value:"light-piston",label:"aircraftLightPistonAircraft"},{value:"piston-heavy",label:"aircraftHeavyPistonAircraft"},{value:"helicopter-light",label:"aircraftLightHelicopter"},{value:"helicopter-medium",label:"aircraftMediumHelicopter"},{value:"helicopter-heavy",label:"aircraftHeavyHelicopter"},{value:"military-jet",label:"aircraftMilitaryJet"},{value:"ultralight",label:"aircraftUltralight"},{value:"unmanned",label:"aircraftDrone"},{value:"glider",label:"aircraftGlider"},{value:"silent",label:"aircraftSilent"}]}]}static bridge(){const t=(e,i,s,n,a,r,o,l,h)=>({type:"number",key:e,label:i,min:s,max:n,step:a,unit:r,group:l,hint:h,effective:o===void 0?void 0:()=>o});return[t("bridge.spanM","span",.1,5e3,.1,"m",void 0,fi.BRIDGE,"metresOfOpenSpanUnder"),t("bridge.deckThicknessM","deckThickness",.1,20,.1,"m",1.2,fi.BRIDGE),t("bridge.railing.heightM","height",.1,5,.05,"m",1.05,fi.RAILING),t("bridge.railing.postSpacingM","postSpacing",.2,20,.1,"m",1.5,fi.RAILING),t("bridge.railing.rails","rails",0,8,1,"",2,fi.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:fi.WIRE,label:"poles",hint:"whichEndsStandOnA",choices:[{value:"both",label:"both"},{value:"start",label:"start"},{value:"end",label:"end"},{value:"none",label:"noPoles"}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:fi.WIRE,label:"strandThickness"},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:fi.WIRE,label:"poleHeight",hint:"emptyHalfAMetreOver"}]}}class ma{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[ma.NONE,ma.SOLAR_VISUAL,ma.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return ma.ALL.find(e=>e.id===t)??ma.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class cI{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[i,s]of Object.entries(this.names))if(s.toLowerCase()===e)return i;return t.trim()}}class il{constructor(t,e,i,s=new cI({}),n,a={}){this.labels=t,this.naming=e,this.said=i,this.tags=s,this.timeWords=n,this.decorParameterTexts=a}entriesFor(t,e,i={}){const s=[];return this.addSummary(s,t),this.addObservation(s,t),this.addObserver(s,t,e),this.addLocation(s,t,e,i.groundElevationM,i.roadGradeDeg??0),this.addDecor(s,t,e,i),i.phenomena===!0&&this.addPhenomena(s,t,e),this.addTemporal(s,t),this.addWeather(s,t,e),this.addSound(s,t,e),s}push(t,e,i,s,n,a="",r={}){n===void 0||n===""||t.push({group:e,field:i,label:s,value:String(n),unit:a,color:r.color,fromSource:r.fromSource===!0})}percent(t){return t===void 0?void 0:`${Math.round(t*100)} %`}rounded(t,e=0){return t===void 0?void 0:String(Number(t.toFixed(e)))}shows(t,e=0){return t!==void 0&&Number(t.toFixed(e))!==0}showsPercent(t){return this.shows(t===void 0?void 0:t*100)}percentShown(t){return this.showsPercent(t)?this.percent(t):void 0}roundedShown(t,e=0){return this.shows(t,e)?this.rounded(t,e):void 0}static DESCRIPTION_WORDS=3;addSummary(t,e){const i=this.said.read(e.event.description)?.trim();if(!i)return;const s=i.split(/\s+/),n=s.length>il.DESCRIPTION_WORDS?`${s.slice(0,il.DESCRIPTION_WORDS).join(" ")}…`:i;this.push(t,"summary","description",this.labels.summaryDescription,n),t[t.length-1].full=i}addObservation(t,e){const i=e.event.tags;this.push(t,"observation","tags",this.labels.tags,i&&i.length>0?i.map(s=>this.tags.name(s)).join(", "):void 0)}filterName(t){return t===ma.SOLAR_VISUAL?this.labels.filterSolarVisual:t===ma.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,i){const s=e.observer;this.push(t,"observer","observerId",this.labels.observerId,s?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(s?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,s?.lastName);const n=s?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,n&&n.length>0?n.join(", "):void 0);const a=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(a));const r=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,r===void 0?void 0:r<1?`1/${Math.round(1/r)}`:this.rounded(r,2),"s");const o=Te(e,i);if(o){const l=Ts.focalLengthMmFor(a,o.fovDeg);l===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(o.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(l,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(o.fNumber??a.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(o.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(o.rollDeg),"°");const h=ma.byId(o.filter);h!==ma.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(h))}}degreesMinutesSeconds(t,e,i){if(t===void 0||!Number.isFinite(t))return;const s=Math.round(Math.abs(t)*3600),n=Math.floor(s/3600),a=Math.floor(s%3600/60),r=s%60;return`${n}°${String(a).padStart(2,"0")}′${String(r).padStart(2,"0")}″ ${this.naming.point(t<0?i:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const i=il.SPEED_SPAN_MS/2,s=Math.max(0,e-i),n=Te(t,s),a=Te(t,s+2*i);if(n?.lat===void 0||n.lng===void 0||a?.lat===void 0||a.lng===void 0)return;const r=(a.lat-n.lat)*111320,o=(a.lng-n.lng)*111320*Math.cos(n.lat*Math.PI/180);return Math.hypot(r,o)/(2*i/1e3)*3.6}addLocation(t,e,i,s,n){const a=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,a?.name);const r=Te(e,i);if(!r)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(r.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(r.lng,90,270));const o=this.rounded(r.headingDeg);this.push(t,"location","heading",this.labels.heading,o,r.headingDeg===void 0?"°":`° (${this.naming.point(r.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,r.pitchDeg===void 0?void 0:this.rounded(r.pitchDeg+n),"°");const l=il.speedKmhAt(e,i);l!==void 0&&l>il.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(l),"km/h"),s===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(r.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(s+r.elevationM),"m")}addDecor(t,e,i,s){const n=e.decor.find(h=>h.id===s.decorId);if(!n){if(s.decorPicker===!0)for(const h of e.decor)this.push(t,"decor",`decor:${h.id}`,this.decorLabel(h),this.decorKindName(h.kind));return}this.push(t,"decor","decorBase.title",this.labels.decorTitle,this.said.read(n.title));const a=ga(n,i);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(a.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(a.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(a.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(a.headingDeg),"°"),n1(n,i)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const r=n.lights?.map(h=>h.id).join()??"",o=r===""?void 0:Pg.find(h=>h.create().map(u=>u.id).join()===r);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,o&&this.naming.lightRig(o)),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(n.observerSide));const l=fi.of(n);for(const h of(l&&nS.resolve(l,this.decorParameterTexts))?.parameters??[]){const u=Ch.read(n,h.key);if(u==null)continue;const d=h.type==="choice"?this.said.read(h.choices.find(f=>f.value===u)?.label)??String(u):u;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof d=="boolean"?d?"✓":"":d,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?nn.describeTime(t,this.timeWords.messages,this.timeWords.locale):al(t)}addTemporal(t,e){const i=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,i.time&&this.timeText(i.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,i.endTime&&this.timeText(i.endTime));const s=gx(i);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(s&&s/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,i.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(i.utcOffsetHours,1),"UTC±h")}addWeather(t,e,i){const s=tl(e,i),a={fromSource:e.weatherSource!==void 0},r=this.showsPercent(s.cloudCover)||this.showsPercent(s.lowerCloudCover)||this.showsPercent(s.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(s.cloudCover),"",a),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(s.highCloudCover),"",a),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(s.highCloudCover)?this.percent(s.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(s.highCloudCover)?this.percent(s.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,r?this.percent(s.cloudDarkness):void 0,"",a),this.push(t,"weather","cloudBase",this.labels.cloudBase,r?this.rounded(s.cloudBaseM):void 0,"m",a);const o=s.precipitationType!=="none"&&this.showsPercent(s.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,o?this.precipitationName(s.precipitationType):void 0,"",a),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,o?this.percent(s.precipitationIntensity):void 0,"",a),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(s.windSpeed,2)?this.rounded(s.windDirectionDeg):void 0,"°",a),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(s.windSpeed,2),"m/s",a),s.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",a)}addSound(t,e,i){const s=mx(e,i);s.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(s.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(s.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(s.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,s.src))}addPhenomena(t,e,i){for(const s of e.timeline.sourceIds){const n=e.timeline.getInterpolatedShapeAt(i,s),a=n?.angular,r=a?`${this.rounded(a.widthDeg,2)} × ${this.rounded(a.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${s}`,this.said.read(n?.title)??s,r)}for(const s of e.interpretation?.bodies??[]){const n=s.track.find(r=>r.sizeM?.widthM!==void 0)?.sizeM?.widthM,a=s.model.id??s.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${s.id}`,this.said.read(s.title)??s.id,[a,n!==void 0?`${this.rounded(n,2)} m`:void 0].filter(Boolean).join(", "))}}decorLabel(t){return this.said.read(t.title)??this.decorKindName(t.kind)}decorKindName(t){switch(t){case"building":return this.labels.decorBuilding;case"tree":return this.labels.decorTree;case"shrub":return this.labels.decorShrub;case"bridge":return this.labels.decorBridge;case"wire":return this.labels.decorWire;case"crop":return this.labels.decorCrop;case"terrace":return this.labels.decorTerrace;case"mound":return this.labels.decorMound;case"wall":return this.labels.decorWall;case"streetlight":return this.labels.decorStreetlight;case"trafficlight":return this.labels.decorTrafficLight;case"peak":return this.labels.decorPeak;case"crossing":return this.labels.decorCrossing;case"roadsign":return this.labels.decorRoadSign;case"vehicle":return this.labels.decorVehicle;case"aircraft":return this.labels.decorAircraft;default:return this.labels.decorObserver}}decorSideName(t){switch(t){case"front":return this.labels.decorSideFront;case"behind":return this.labels.decorSideBehind;case"left":return this.labels.decorSideLeft;case"right":return this.labels.decorSideRight;case"front-left":return this.labels.decorSideFrontLeft;case"front-right":return this.labels.decorSideFrontRight;case"behind-left":return this.labels.decorSideBehindLeft;case"behind-right":return this.labels.decorSideBehindRight;default:return}}precipitationName(t){switch(t){case"rain":return this.labels.precipitationRain;case"snow":return this.labels.precipitationSnow;case"hail":return this.labels.precipitationHail;default:return this.labels.precipitationNone}}soundKindName(t){switch(t){case"hum":return this.labels.soundHum;case"whistle":return this.labels.soundWhistle;case"rumble":return this.labels.soundRumble;case"crackle":return this.labels.soundCrackle;default:return this.labels.soundNone}}}const lI="Global Meteor Network",hI="https://globalmeteornetwork.org/data/",uI="“Thunder” by Jerimee",dI="https://creativecommons.org/licenses/by/3.0/",fI="CC BY 3.0";class Hs{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),s=e.currentTerrainAttribution;s&&i(Hs.text(s));const n=e.currentRoadAttribution;n&&i(Hs.text(n));const a=e.currentWaterAttribution;a&&i(Hs.text(a));const r=e.currentRailwayAttribution;r&&i(Hs.text(r));const o=e.ufoElement.observerMapCredit;o&&!s?.includes(o)&&i(Hs.text(o));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(Hs.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Hs.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new lu(Sr.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(Hs.text(p))}const l=e.satelliteState;if(l.status==="ready"&&l.credit){const d=document.createElement("li");d.appendChild(Hs.link(l.creditUrl??"",l.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Hs.link(hI,lI),document.createTextNode(" (CC BY 4.0)")),i(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Hs.link(h.creditUrl,h.credit)),i(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Hs.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(f)}}const u=Hs.text(`${uI} (`);u.append(Hs.link(dI,fI),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const pI=rs.point("assessment").provide(rs.BUILT_IN,[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async c=>{const{CoverageAssessor:t}=await Ht(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-CBh0sDI1.js");return{CoverageAssessor:e}},__vite__mapDeps([8,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async c=>{const{HynekAssessor:t}=await Ht(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-DdoHR-Qt.js");return{HynekAssessor:e}},__vite__mapDeps([9,10,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async c=>{const{BallesterGuaspAssessor:t}=await Ht(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-ZSDHMhXN.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([11,12,2,10,8,1,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async c=>{const{PoherAssessor:t}=await Ht(async()=>{const{PoherAssessor:e}=await import("./PoherAssessor-6t5qvmJy.js");return{PoherAssessor:e}},__vite__mapDeps([13,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})}]);class hb{constructor(t){this.labels=t}async read(t){const e=[],i=new Set;for(const s of pI){let n;try{n=await s.create().assess(t)}catch{continue}for(const r of n.criteria)r.basis===void 0&&!r.unsupported&&i.add(r.id);const a=n.score===void 0?n.verdict===void 0?"":this.verdictName(s.id,n.verdict):`${Math.round(n.score*100)}%`;a!==""&&e.push({group:"assessment",field:s.id,label:this.labels.assessmentNames[s.id]??s.name,value:a,unit:"",fromSource:!1,about:s.create().about,...n.factors?{detail:hb.factorsText(n.factors)}:{}})}return{entries:e,unanswered:i}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([i,s])=>`${e[i]??i} ${s.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}class gl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const s=t.event.place?.[0],n=t.observerTrack;if(!s)return 0;const a=g=>{const m=n.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=re(m.lat,m.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg,aboveM:m.elevationM??0,altitudeM:m.altitudeM}},r=a(e-gl.HALF_SPAN_MS),o=a(e+gl.HALF_SPAN_MS),l=a(e);if(!r||!o||!l)return 0;const h=Math.hypot(o.eastM-r.eastM,o.northM-r.northM),u=2*gl.HALF_SPAN_MS/1e3;if(h/u<gl.MIN_SPEED_MS)return 0;const d=o.altitudeM!==void 0&&r.altitudeM!==void 0?o.altitudeM-r.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(r.eastM,r.northM)-r.aboveM,f=Math.atan2(d,h)*180/Math.PI;if(l.heading===void 0)return f;const p=Math.atan2(o.eastM-r.eastM,o.northM-r.northM)*180/Math.PI;return f*Math.max(0,Math.cos((l.heading-p)*Math.PI/180))}}const mI=.08,Ey=.15,Ay=2,gI=2e3;class _y{context;constructor(t){this.context=t}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(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}Un.isLive(this.context)&&Un.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);Un.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<gI),i=new Set(e.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of e){const n=this.voices.get(s.id)??this.build(t,s.id);this.retarget(t,n,s)}}build(t,e){const i=t.createGain();i.gain.value=0;const s=t.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(t));const n=t.createOscillator();n.type="sawtooth";const a=t.createOscillator();a.type="sine";const r=t.createGain(),o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),a.connect(o),o.connect(r).connect(s);const l=()=>{const w=t.createBufferSource();return w.buffer=this.noise(t),w.loop=!0,w.loopStart=Math.random()*Ay*.5,w},h=l(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();h.connect(u).connect(d).connect(s);const f=l(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const g=t.createGain();f.connect(p).connect(g).connect(s);const m=l(),v=t.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const M=t.createGain();m.connect(v).connect(M).connect(s);const x=[n,a,h,f,m];for(const w of x)w.start();const y={nodes:[i,s,r,o,u,d,p,g,v,M,...x],sources:x,firing:n,crank:a,knock:u,engineGain:r,knockGain:d,roadGain:g,windGain:M,cabin:s,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:s,noise:n,inside:a,windowsOpen:r,distanceM:o}){const l=t.currentTime,h=(M,x)=>M.setTargetAtTime(x,l,mI),u=s.rpm/60,d=u*i.cylinders/2,f=Math.min(1,s.rpm/i.shiftUpRpm),p=Math.min(1.5,s.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,u),h(e.knock.frequency,d*3),h(e.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*f)*.3),h(e.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(e.roadGain.gain,i.roadGain*p**1.5*.8);const g=!a||r;h(e.windGain.gain,p**2*(g?.5:.06));const m=a?r?3500:700:8e3/(1+o/60);h(e.cabin.frequency,m);const v=a?.5:Math.min(1,8/Math.max(o,1));h(e.output.gain,v*n)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,Ey/3),setTimeout(()=>{for(const s of e.sources)try{s.stop()}catch{}for(const s of e.nodes)s.disconnect()},Ey*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*Ay,t.sampleRate),i=e.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Su{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(t){return Su.BY_KIND[t??"generic"]??Su.BY_KIND.generic}}class Os{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(t){return Os.ROAD_KINDS.includes(t)}static roadOf(t){return t&&Os.isRoad(t.kind)?t.kind:void 0}static aircraftOf(t){return t&&!Os.isRoad(t.kind)?t.kind:void 0}static transmission(t){const e=Os.insulationDb(t),i=[3,4,5].map(s=>e[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(t){return t?t.windowsOpen===!0?Os.WINDOWS_OPEN_DB:Os.isRoad(t.kind)?Os.ROAD_CLOSED_DB:Os.CANOPIED.includes(t.kind)?Os.CANOPY_DB:Os.FUSELAGE_DB:Os.OPEN_AIR}}class $o{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,s){const n=$o.SAMPLE_MS,a=[];for(let l=i;l<=s+n/2;l+=n){const h=e(l-n/2),u=e(l+n/2);if(!h||!u)return;a.push(Math.hypot(u.eastM-h.eastM,u.northM-h.northM)/(n/1e3))}const r=[];let o=1;for(let l=0;l<a.length;l++){const h=a[l],u=(a[Math.min(l+1,a.length-1)]-a[Math.max(l-1,0)])/(2*n/1e3);if(h<$o.STANDING_MPS){o=1,r.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=v=>d/t.kmhPer1000Rpm[v-1]*1e3;for(;o<t.kmhPer1000Rpm.length&&f(o)>t.shiftUpRpm;)o++;for(;o>1&&f(o)<t.shiftDownRpm;)o--;const p=Math.max(f(o),t.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=u>.15?Math.min(1,g+u/2.5):u<-.3?.05:g;r.push({speedMps:h,rpm:p,load:m,gear:o})}return new $o(r,i)}at(t){const e=(t-this.startMs)/$o.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],a=Math.min(Math.max(e-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*a,rpm:s.rpm+(n.rpm-s.rpm)*a,load:s.load+(n.load-s.load)*a,gear:a<.5?s.gear:n.gear}}}class Uf{drives=new Map;at(t,e){const i=[],s=t.event.place?.[0],n=h=>{const u=t.observerTrack.getInterpolatedPoseAt(h),d=u?.lat??s?.lat,f=u?.lng??s?.lng;if(d===void 0||f===void 0||!s)return;const p=re(d,f,s.lat,s.lng);return{eastM:p.x,northM:-p.z}},a=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),r=t.vehicle,o=Os.roadOf(r);if(r&&o){const h=Su.of(o),u=this.drive(`observer:${o}`,Uf.trackKey(t),()=>$o.of(h,n,0,a));u&&i.push({id:"observer",profile:h,state:u.at(e),noise:r.noise??1,inside:!0,windowsOpen:r.windowsOpen===!0,distanceM:0})}const l=n(e);for(const h of t.decor){if(!h.engine||!l)continue;const u=Su.of(h.engine.kind),d=m=>{const v=ga(h,m);return{eastM:v.eastM,northM:v.northM}},f=this.drive(`decor:${h.id}`,Uf.decorKey(h,a),()=>$o.of(u,d,0,a));if(!f)continue;const p=ga(h,e),g=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${h.id}`,profile:u,state:f.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:g})}return i}drive(t,e,i){const s=this.drives.get(t);if(s&&s.key===e)return s.drive;const n=i();return this.drives.set(t,{key:e,drive:n}),n}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Ty=864e5,Ry=4e4;function vI(c){const t=Math.floor(c.getTime()/Ty);return{elapsedMs:c.getTime()-t*Ty,shiftM:{x:Dy.unit(t,2654435761)*Ry,z:Dy.unit(t,2246822507)*Ry}}}class Dy{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function Iy(c,t,e,i,s,n,a){const r=i?.lat!==void 0&&i.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?re(s.lat,s.lng,i.lat,i.lng):{x:0,z:0};if(a){const h=t.getInterpolatedWeatherAt(0)??e,u=n===void 0?void 0:h.cloudLayers?.find(p=>p.id===n),d=(u?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??h.windSpeed)*a.elapsedMs/1e3;r.x+=a.shiftM.x-Math.sin(d)*f,r.z+=a.shiftM.z+Math.cos(d)*f}const o=Math.max(0,c),l=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<o),o];for(let h=1;h<l.length;h++){const u=l[h-1],d=l[h]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const g=t.getInterpolatedWeatherAt(u+d*p/f)??e,m=n===void 0?void 0:g.cloudLayers?.find(y=>y.id===n),v=(m?.windDirectionDeg??g.windDirectionDeg)*Math.PI/180,M=p===0||p===f?1:p%2===0?2:4,x=(m?.windSpeed??g.windSpeed)*d/1e3/f/3*M;r.x-=Math.sin(v)*x,r.z+=Math.cos(v)*x}}return r}const MI="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==",yI=`
|
|
5726
|
+
}`;class j4{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e){if(this.texture===null){const i=new Bw(t.texture);(t.depthNear!==e.depthNear||t.depthFar!==e.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(t){if(this.texture!==null&&this.mesh===null){const e=t.cameras[0].viewport,i=new _e({vertexShader:Z4,fragmentShader:J4,uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new dt(new tn(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Q4 extends bo{constructor(t,e){super();const i=this;let s=null,n=1,a=null,r="local-floor",o=1,l=null,h=null,u=null,d=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",m=new j4,v={},M=e.getContextAttributes();let x=null,y=null;const w=[],S=[],E=new Q;let b=null;const A=new Ns;A.viewport=new Ae;const T=new Ns;T.viewport=new Ae;const D=[A,T],I=new $_;let C=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getTargetRaySpace()},this.getControllerGrip=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getGripSpace()},this.getHand=function(q){let ot=w[q];return ot===void 0&&(ot=new G0,w[q]=ot),ot.getHandSpace()};function O(q){const ot=S.indexOf(q.inputSource);if(ot===-1)return;const st=w[ot];st!==void 0&&(st.update(q.inputSource,q.frame,l||a),st.dispatchEvent({type:q.type,data:q.inputSource}))}function k(){s.removeEventListener("select",O),s.removeEventListener("selectstart",O),s.removeEventListener("selectend",O),s.removeEventListener("squeeze",O),s.removeEventListener("squeezestart",O),s.removeEventListener("squeezeend",O),s.removeEventListener("end",k),s.removeEventListener("inputsourceschange",B);for(let q=0;q<w.length;q++){const ot=S[q];ot!==null&&(S[q]=null,w[q].disconnect(ot))}C=null,N=null,m.reset();for(const q in v)delete v[q];t.setRenderTarget(x),f=null,d=null,u=null,s=null,y=null,Zt.stop(),i.isPresenting=!1,t.setPixelRatio(b),t.setSize(E.width,E.height,!1),i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(q){n=q,i.isPresenting===!0&&Bt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(q){r=q,i.isPresenting===!0&&Bt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(q){l=q},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u===null&&g&&(u=new XRWebGLBinding(s,e)),u},this.getFrame=function(){return p},this.getSession=function(){return s},this.setSession=async function(q){if(s=q,s!==null){if(x=t.getRenderTarget(),s.addEventListener("select",O),s.addEventListener("selectstart",O),s.addEventListener("selectend",O),s.addEventListener("squeeze",O),s.addEventListener("squeezestart",O),s.addEventListener("squeezeend",O),s.addEventListener("end",k),s.addEventListener("inputsourceschange",B),M.xrCompatible!==!0&&await e.makeXRCompatible(),b=t.getPixelRatio(),t.getSize(E),g&&"createProjectionLayer"in XRWebGLBinding.prototype){let st=null,G=null,Nt=null;M.depth&&(Nt=M.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,st=M.stencil?Ko:Cr,G=M.stencil?gu:ea);const Xt={colorFormat:e.RGBA8,depthFormat:Nt,scaleFactor:n};u=this.getBinding(),d=u.createProjectionLayer(Xt),s.updateRenderState({layers:[d]}),t.setPixelRatio(1),t.setSize(d.textureWidth,d.textureHeight,!1),y=new Ke(d.textureWidth,d.textureHeight,{format:Gi,type:Zs,depthTexture:new xo(d.textureWidth,d.textureHeight,G,void 0,void 0,void 0,void 0,void 0,void 0,st),stencilBuffer:M.stencil,colorSpace:t.outputColorSpace,samples:M.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const st={antialias:M.antialias,alpha:!0,depth:M.depth,stencil:M.stencil,framebufferScaleFactor:n};f=new XRWebGLLayer(s,e,st),s.updateRenderState({baseLayer:f}),t.setPixelRatio(1),t.setSize(f.framebufferWidth,f.framebufferHeight,!1),y=new Ke(f.framebufferWidth,f.framebufferHeight,{format:Gi,type:Zs,colorSpace:t.outputColorSpace,stencilBuffer:M.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,a=await s.requestReferenceSpace(r),Zt.setContext(s),Zt.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function B(q){for(let ot=0;ot<q.removed.length;ot++){const st=q.removed[ot],G=S.indexOf(st);G>=0&&(S[G]=null,w[G].disconnect(st))}for(let ot=0;ot<q.added.length;ot++){const st=q.added[ot];let G=S.indexOf(st);if(G===-1){for(let Xt=0;Xt<w.length;Xt++)if(Xt>=S.length){S.push(st),G=Xt;break}else if(S[Xt]===null){S[Xt]=st,G=Xt;break}if(G===-1)break}const Nt=w[G];Nt&&Nt.connect(st)}}const X=new _,J=new _;function $(q,ot,st){X.setFromMatrixPosition(ot.matrixWorld),J.setFromMatrixPosition(st.matrixWorld);const G=X.distanceTo(J),Nt=ot.projectionMatrix.elements,Xt=st.projectionMatrix.elements,kt=Nt[14]/(Nt[10]-1),Tt=Nt[14]/(Nt[10]+1),te=(Nt[9]+1)/Nt[5],ie=(Nt[9]-1)/Nt[5],se=(Nt[8]-1)/Nt[0],je=(Xt[8]+1)/Xt[0],Qe=kt*se,Li=kt*je,Ri=G/(-se+je),Ni=Ri*-se;if(ot.matrixWorld.decompose(q.position,q.quaternion,q.scale),q.translateX(Ni),q.translateZ(Ri),q.matrixWorld.compose(q.position,q.quaternion,q.scale),q.matrixWorldInverse.copy(q.matrixWorld).invert(),Nt[10]===-1)q.projectionMatrix.copy(ot.projectionMatrix),q.projectionMatrixInverse.copy(ot.projectionMatrixInverse);else{const ji=kt+Ri,U=Tt+Ri,pn=Qe-Ni,ti=Li+(G-Ni),L=te*Tt/U*ji,R=ie*Tt/U*ji;q.projectionMatrix.makePerspective(pn,ti,L,R,ji,U),q.projectionMatrixInverse.copy(q.projectionMatrix).invert()}}function it(q,ot){ot===null?q.matrixWorld.copy(q.matrix):q.matrixWorld.multiplyMatrices(ot.matrixWorld,q.matrix),q.matrixWorldInverse.copy(q.matrixWorld).invert()}this.updateCamera=function(q){if(s===null)return;let ot=q.near,st=q.far;m.texture!==null&&(m.depthNear>0&&(ot=m.depthNear),m.depthFar>0&&(st=m.depthFar)),I.near=T.near=A.near=ot,I.far=T.far=A.far=st,(C!==I.near||N!==I.far)&&(s.updateRenderState({depthNear:I.near,depthFar:I.far}),C=I.near,N=I.far),I.layers.mask=q.layers.mask|6,A.layers.mask=I.layers.mask&-5,T.layers.mask=I.layers.mask&-3;const G=q.parent,Nt=I.cameras;it(I,G);for(let Xt=0;Xt<Nt.length;Xt++)it(Nt[Xt],G);Nt.length===2?$(I,A,T):I.projectionMatrix.copy(A.projectionMatrix),rt(q,I,G)};function rt(q,ot,st){st===null?q.matrix.copy(ot.matrixWorld):(q.matrix.copy(st.matrixWorld),q.matrix.invert(),q.matrix.multiply(ot.matrixWorld)),q.matrix.decompose(q.position,q.quaternion,q.scale),q.updateMatrixWorld(!0),q.projectionMatrix.copy(ot.projectionMatrix),q.projectionMatrixInverse.copy(ot.projectionMatrixInverse),q.isPerspectiveCamera&&(q.fov=Kl*2*Math.atan(1/q.projectionMatrix.elements[5]),q.zoom=1)}this.getCamera=function(){return I},this.getFoveation=function(){if(!(d===null&&f===null))return o},this.setFoveation=function(q){o=q,d!==null&&(d.fixedFoveation=q),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=q)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(I)},this.getCameraTexture=function(q){return v[q]};let Lt=null;function qt(q,ot){if(h=ot.getViewerPose(l||a),p=ot,h!==null){const st=h.views;f!==null&&(t.setRenderTargetFramebuffer(y,f.framebuffer),t.setRenderTarget(y));let G=!1;st.length!==I.cameras.length&&(I.cameras.length=0,G=!0);for(let Tt=0;Tt<st.length;Tt++){const te=st[Tt];let ie=null;if(f!==null)ie=f.getViewport(te);else{const je=u.getViewSubImage(d,te);ie=je.viewport,Tt===0&&(t.setRenderTargetTextures(y,je.colorTexture,je.depthStencilTexture),t.setRenderTarget(y))}let se=D[Tt];se===void 0&&(se=new Ns,se.layers.enable(Tt),se.viewport=new Ae,D[Tt]=se),se.matrix.fromArray(te.transform.matrix),se.matrix.decompose(se.position,se.quaternion,se.scale),se.projectionMatrix.fromArray(te.projectionMatrix),se.projectionMatrixInverse.copy(se.projectionMatrix).invert(),se.viewport.set(ie.x,ie.y,ie.width,ie.height),Tt===0&&(I.matrix.copy(se.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale)),G===!0&&I.cameras.push(se)}const Nt=s.enabledFeatures;if(Nt&&Nt.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&g){u=i.getBinding();const Tt=u.getDepthInformation(st[0]);Tt&&Tt.isValid&&Tt.texture&&m.init(Tt,s.renderState)}if(Nt&&Nt.includes("camera-access")&&g){t.state.unbindTexture(),u=i.getBinding();for(let Tt=0;Tt<st.length;Tt++){const te=st[Tt].camera;if(te){let ie=v[te];ie||(ie=new Bw,v[te]=ie);const se=u.getCameraImage(te);ie.sourceTexture=se}}}}for(let st=0;st<w.length;st++){const G=S[st],Nt=w[st];G!==null&&Nt!==void 0&&Nt.update(G,ot,l||a)}Lt&&Lt(q,ot),ot.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:ot}),p=null}const Zt=new sb;Zt.setAnimationLoop(qt),this.setAnimationLoop=function(q){Lt=q},this.dispose=function(){}}}const tI=new Gt,lb=new he;lb.set(-1,0,0,0,1,0,0,0,1);function eI(c,t){function e(m,v){m.matrixAutoUpdate===!0&&m.updateMatrix(),v.value.copy(m.matrix)}function i(m,v){v.color.getRGB(m.fogColor.value,qw(c)),v.isFog?(m.fogNear.value=v.near,m.fogFar.value=v.far):v.isFogExp2&&(m.fogDensity.value=v.density)}function s(m,v,M,x,y){v.isNodeMaterial?v.uniformsNeedUpdate=!1:v.isMeshBasicMaterial?n(m,v):v.isMeshLambertMaterial?(n(m,v),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)):v.isMeshToonMaterial?(n(m,v),u(m,v)):v.isMeshPhongMaterial?(n(m,v),h(m,v),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)):v.isMeshStandardMaterial?(n(m,v),d(m,v),v.isMeshPhysicalMaterial&&f(m,v,y)):v.isMeshMatcapMaterial?(n(m,v),p(m,v)):v.isMeshDepthMaterial?n(m,v):v.isMeshDistanceMaterial?(n(m,v),g(m,v)):v.isMeshNormalMaterial?n(m,v):v.isLineBasicMaterial?(a(m,v),v.isLineDashedMaterial&&r(m,v)):v.isPointsMaterial?o(m,v,M,x):v.isSpriteMaterial?l(m,v):v.isShadowMaterial?(m.color.value.copy(v.color),m.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function n(m,v){m.opacity.value=v.opacity,v.color&&m.diffuse.value.copy(v.color),v.emissive&&m.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(m.map.value=v.map,e(v.map,m.mapTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.bumpMap&&(m.bumpMap.value=v.bumpMap,e(v.bumpMap,m.bumpMapTransform),m.bumpScale.value=v.bumpScale,v.side===Ai&&(m.bumpScale.value*=-1)),v.normalMap&&(m.normalMap.value=v.normalMap,e(v.normalMap,m.normalMapTransform),m.normalScale.value.copy(v.normalScale),v.side===Ai&&m.normalScale.value.negate()),v.displacementMap&&(m.displacementMap.value=v.displacementMap,e(v.displacementMap,m.displacementMapTransform),m.displacementScale.value=v.displacementScale,m.displacementBias.value=v.displacementBias),v.emissiveMap&&(m.emissiveMap.value=v.emissiveMap,e(v.emissiveMap,m.emissiveMapTransform)),v.specularMap&&(m.specularMap.value=v.specularMap,e(v.specularMap,m.specularMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest);const M=t.get(v),x=M.envMap,y=M.envMapRotation;x&&(m.envMap.value=x,m.envMapRotation.value.setFromMatrix4(tI.makeRotationFromEuler(y)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(lb),m.reflectivity.value=v.reflectivity,m.ior.value=v.ior,m.refractionRatio.value=v.refractionRatio),v.lightMap&&(m.lightMap.value=v.lightMap,m.lightMapIntensity.value=v.lightMapIntensity,e(v.lightMap,m.lightMapTransform)),v.aoMap&&(m.aoMap.value=v.aoMap,m.aoMapIntensity.value=v.aoMapIntensity,e(v.aoMap,m.aoMapTransform))}function a(m,v){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,v.map&&(m.map.value=v.map,e(v.map,m.mapTransform))}function r(m,v){m.dashSize.value=v.dashSize,m.totalSize.value=v.dashSize+v.gapSize,m.scale.value=v.scale}function o(m,v,M,x){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,m.size.value=v.size*M,m.scale.value=x*.5,v.map&&(m.map.value=v.map,e(v.map,m.uvTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest)}function l(m,v){m.diffuse.value.copy(v.color),m.opacity.value=v.opacity,m.rotation.value=v.rotation,v.map&&(m.map.value=v.map,e(v.map,m.mapTransform)),v.alphaMap&&(m.alphaMap.value=v.alphaMap,e(v.alphaMap,m.alphaMapTransform)),v.alphaTest>0&&(m.alphaTest.value=v.alphaTest)}function h(m,v){m.specular.value.copy(v.specular),m.shininess.value=Math.max(v.shininess,1e-4)}function u(m,v){v.gradientMap&&(m.gradientMap.value=v.gradientMap)}function d(m,v){m.metalness.value=v.metalness,v.metalnessMap&&(m.metalnessMap.value=v.metalnessMap,e(v.metalnessMap,m.metalnessMapTransform)),m.roughness.value=v.roughness,v.roughnessMap&&(m.roughnessMap.value=v.roughnessMap,e(v.roughnessMap,m.roughnessMapTransform)),v.envMap&&(m.envMapIntensity.value=v.envMapIntensity)}function f(m,v,M){m.ior.value=v.ior,v.sheen>0&&(m.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),m.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(m.sheenColorMap.value=v.sheenColorMap,e(v.sheenColorMap,m.sheenColorMapTransform)),v.sheenRoughnessMap&&(m.sheenRoughnessMap.value=v.sheenRoughnessMap,e(v.sheenRoughnessMap,m.sheenRoughnessMapTransform))),v.clearcoat>0&&(m.clearcoat.value=v.clearcoat,m.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(m.clearcoatMap.value=v.clearcoatMap,e(v.clearcoatMap,m.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,e(v.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(m.clearcoatNormalMap.value=v.clearcoatNormalMap,e(v.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===Ai&&m.clearcoatNormalScale.value.negate())),v.dispersion>0&&(m.dispersion.value=v.dispersion),v.iridescence>0&&(m.iridescence.value=v.iridescence,m.iridescenceIOR.value=v.iridescenceIOR,m.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(m.iridescenceMap.value=v.iridescenceMap,e(v.iridescenceMap,m.iridescenceMapTransform)),v.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=v.iridescenceThicknessMap,e(v.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),v.transmission>0&&(m.transmission.value=v.transmission,m.transmissionSamplerMap.value=M.texture,m.transmissionSamplerSize.value.set(M.width,M.height),v.transmissionMap&&(m.transmissionMap.value=v.transmissionMap,e(v.transmissionMap,m.transmissionMapTransform)),m.thickness.value=v.thickness,v.thicknessMap&&(m.thicknessMap.value=v.thicknessMap,e(v.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=v.attenuationDistance,m.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(m.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(m.anisotropyMap.value=v.anisotropyMap,e(v.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=v.specularIntensity,m.specularColor.value.copy(v.specularColor),v.specularColorMap&&(m.specularColorMap.value=v.specularColorMap,e(v.specularColorMap,m.specularColorMapTransform)),v.specularIntensityMap&&(m.specularIntensityMap.value=v.specularIntensityMap,e(v.specularIntensityMap,m.specularIntensityMapTransform))}function p(m,v){v.matcap&&(m.matcap.value=v.matcap)}function g(m,v){const M=t.get(v).light;m.referencePosition.value.setFromMatrixPosition(M.matrixWorld),m.nearDistance.value=M.shadow.camera.near,m.farDistance.value=M.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:s}}function iI(c,t,e,i){let s={},n={},a=[];const r=c.getParameter(c.MAX_UNIFORM_BUFFER_BINDINGS);function o(y,w){const S=w.program;i.uniformBlockBinding(y,S)}function l(y,w){let S=s[y.id];S===void 0&&(m(y),S=h(y),s[y.id]=S,y.addEventListener("dispose",M));const E=w.program;i.updateUBOMapping(y,E);const b=t.render.frame;n[y.id]!==b&&(d(y),n[y.id]=b)}function h(y){const w=u();y.__bindingPointIndex=w;const S=c.createBuffer(),E=y.__size,b=y.usage;return c.bindBuffer(c.UNIFORM_BUFFER,S),c.bufferData(c.UNIFORM_BUFFER,E,b),c.bindBuffer(c.UNIFORM_BUFFER,null),c.bindBufferBase(c.UNIFORM_BUFFER,w,S),S}function u(){for(let y=0;y<r;y++)if(a.indexOf(y)===-1)return a.push(y),y;return oe("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(y){const w=s[y.id],S=y.uniforms,E=y.__cache;c.bindBuffer(c.UNIFORM_BUFFER,w);for(let b=0,A=S.length;b<A;b++){const T=S[b];if(Array.isArray(T))for(let D=0,I=T.length;D<I;D++)f(T[D],b,D,E);else f(T,b,0,E)}c.bindBuffer(c.UNIFORM_BUFFER,null)}function f(y,w,S,E){if(g(y,w,S,E)===!0){const b=y.__offset,A=y.value;if(Array.isArray(A)){let T=0;for(let D=0;D<A.length;D++){const I=A[D],C=v(I);p(I,y.__data,T),typeof I!="number"&&typeof I!="boolean"&&!I.isMatrix3&&!ArrayBuffer.isView(I)&&(T+=C.storage/Float32Array.BYTES_PER_ELEMENT)}}else p(A,y.__data,0);c.bufferSubData(c.UNIFORM_BUFFER,b,y.__data)}}function p(y,w,S){typeof y=="number"||typeof y=="boolean"?w[0]=y:y.isMatrix3?(w[0]=y.elements[0],w[1]=y.elements[1],w[2]=y.elements[2],w[3]=0,w[4]=y.elements[3],w[5]=y.elements[4],w[6]=y.elements[5],w[7]=0,w[8]=y.elements[6],w[9]=y.elements[7],w[10]=y.elements[8],w[11]=0):ArrayBuffer.isView(y)?w.set(new y.constructor(y.buffer,y.byteOffset,w.length)):y.toArray(w,S)}function g(y,w,S,E){const b=y.value,A=w+"_"+S;if(E[A]===void 0)return typeof b=="number"||typeof b=="boolean"?E[A]=b:ArrayBuffer.isView(b)?E[A]=b.slice():E[A]=b.clone(),!0;{const T=E[A];if(typeof b=="number"||typeof b=="boolean"){if(T!==b)return E[A]=b,!0}else{if(ArrayBuffer.isView(b))return!0;if(T.equals(b)===!1)return T.copy(b),!0}}return!1}function m(y){const w=y.uniforms;let S=0;const E=16;for(let A=0,T=w.length;A<T;A++){const D=Array.isArray(w[A])?w[A]:[w[A]];for(let I=0,C=D.length;I<C;I++){const N=D[I],O=Array.isArray(N.value)?N.value:[N.value];for(let k=0,B=O.length;k<B;k++){const X=O[k],J=v(X),$=S%E,it=$%J.boundary,rt=$+it;S+=it,rt!==0&&E-rt<J.storage&&(S+=E-rt),N.__data=new Float32Array(J.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=S,S+=J.storage}}}const b=S%E;return b>0&&(S+=E-b),y.__size=S,y.__cache={},this}function v(y){const w={boundary:0,storage:0};return typeof y=="number"||typeof y=="boolean"?(w.boundary=4,w.storage=4):y.isVector2?(w.boundary=8,w.storage=8):y.isVector3||y.isColor?(w.boundary=16,w.storage=12):y.isVector4?(w.boundary=16,w.storage=16):y.isMatrix3?(w.boundary=48,w.storage=48):y.isMatrix4?(w.boundary=64,w.storage=64):y.isTexture?Bt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(y)?(w.boundary=16,w.storage=y.byteLength):Bt("WebGLRenderer: Unsupported uniform value type.",y),w}function M(y){const w=y.target;w.removeEventListener("dispose",M);const S=a.indexOf(w.__bindingPointIndex);a.splice(S,1),c.deleteBuffer(s[w.id]),delete s[w.id],delete n[w.id]}function x(){for(const y in s)c.deleteBuffer(s[y]);a=[],s={},n={}}return{bind:o,update:l,dispose:x}}const sI=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 _a=null;function nI(){return _a===null&&(_a=new dn(sI,16,16,hc,Be),_a.name="DFG_LUT",_a.minFilter=ge,_a.magFilter=ge,_a.wrapS=Hi,_a.wrapT=Hi,_a.generateMipmaps=!1,_a.needsUpdate=!0),_a}class aI{constructor(t={}){const{canvas:e=QA(),context:i=null,depth:s=!0,stencil:n=!1,alpha:a=!1,antialias:r=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:h="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Zs}=t;this.isWebGLRenderer=!0;let p;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=i.getContextAttributes().alpha}else p=a;const g=f,m=new Set([E1,S1,b1]),v=new Set([Zs,ea,mu,gu,x1,w1]),M=new Uint32Array(4),x=new Int32Array(4),y=new _;let w=null,S=null;const E=[],b=[];let A=null;this.domElement=e,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=tr,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let D=!1,I=null,C=null,N=null,O=null;this._outputColorSpace=Es;let k=0,B=0,X=null,J=-1,$=null;const it=new Ae,rt=new Ae;let Lt=null;const qt=new at(0);let Zt=0,q=e.width,ot=e.height,st=1,G=null,Nt=null;const Xt=new Ae(0,0,q,ot),kt=new Ae(0,0,q,ot);let Tt=!1;const te=new d0;let ie=!1,se=!1;const je=new Gt,Qe=new _,Li=new Ae,Ri={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ni=!1;function ji(){return X===null?st:1}let U=i;function pn(P,z){return e.getContext(P,z)}try{const P={alpha:!0,depth:s,stencil:n,antialias:r,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:h,failIfMajorPerformanceCaveat:u};if("setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Ru}`),e.addEventListener("webglcontextlost",ki,!1),e.addEventListener("webglcontextrestored",vi,!1),e.addEventListener("webglcontextcreationerror",wa,!1),U===null){const z="webgl2";if(U=pn(z,P),U===null)throw pn(z)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}}catch(P){throw oe("WebGLRenderer: "+P.message),P}let ti,L,R,H,K,Z,lt,ft,j,et,mt,Kt,yt,gt,Qt,ae,be,F,ut,tt,vt,St,nt;function Wt(){ti=new nD(U),ti.init(),vt=new q4(U,ti),L=new ZR(U,ti,t,vt),R=new Y4(U,ti),L.reversedDepthBuffer&&d&&R.buffers.depth.setReversed(!0),C=U.createFramebuffer(),N=U.createFramebuffer(),O=U.createFramebuffer(),H=new oD(U),K=new O4,Z=new $4(U,ti,R,K,L,vt,H),lt=new sD(T),ft=new uT(U),St=new $R(U,ft),j=new aD(U,ft,H,St),et=new lD(U,j,ft,St,H),F=new cD(U,L,Z),Qt=new JR(K),mt=new C4(T,lt,ti,L,St,Qt),Kt=new eI(T,K),yt=new N4,gt=new H4(ti),be=new YR(T,lt,R,et,p,o),ae=new K4(T,et,L),nt=new iI(U,H,L,R),ut=new qR(U,ti,H),tt=new rD(U,ti,H),H.programs=mt.programs,T.capabilities=L,T.extensions=ti,T.properties=K,T.renderLists=yt,T.shadowMap=ae,T.state=R,T.info=H}Wt(),g!==Zs&&(A=new uD(g,e.width,e.height,r,s,n));const Ft=new Q4(T,U);this.xr=Ft,this.getContext=function(){return U},this.getContextAttributes=function(){return U.getContextAttributes()},this.forceContextLoss=function(){const P=ti.get("WEBGL_lose_context");P&&P.loseContext()},this.forceContextRestore=function(){const P=ti.get("WEBGL_lose_context");P&&P.restoreContext()},this.getPixelRatio=function(){return st},this.setPixelRatio=function(P){P!==void 0&&(st=P,this.setSize(q,ot,!1))},this.getSize=function(P){return P.set(q,ot)},this.setSize=function(P,z,Y=!0){if(Ft.isPresenting){Bt("WebGLRenderer: Can't change size while VR device is presenting.");return}q=P,ot=z,e.width=Math.floor(P*st),e.height=Math.floor(z*st),Y===!0&&(e.style.width=P+"px",e.style.height=z+"px"),A!==null&&A.setSize(e.width,e.height),this.setViewport(0,0,P,z)},this.getDrawingBufferSize=function(P){return P.set(q*st,ot*st).floor()},this.setDrawingBufferSize=function(P,z,Y){q=P,ot=z,st=Y,e.width=Math.floor(P*Y),e.height=Math.floor(z*Y),this.setViewport(0,0,P,z)},this.setEffects=function(P){if(g===Zs){oe("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(P){for(let z=0;z<P.length;z++)if(P[z].isOutputPass===!0){Bt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}A.setEffects(P||[])},this.getCurrentViewport=function(P){return P.copy(it)},this.getViewport=function(P){return P.copy(Xt)},this.setViewport=function(P,z,Y,V){P.isVector4?Xt.set(P.x,P.y,P.z,P.w):Xt.set(P,z,Y,V),R.viewport(it.copy(Xt).multiplyScalar(st).round())},this.getScissor=function(P){return P.copy(kt)},this.setScissor=function(P,z,Y,V){P.isVector4?kt.set(P.x,P.y,P.z,P.w):kt.set(P,z,Y,V),R.scissor(rt.copy(kt).multiplyScalar(st).round())},this.getScissorTest=function(){return Tt},this.setScissorTest=function(P){R.setScissorTest(Tt=P)},this.setOpaqueSort=function(P){G=P},this.setTransparentSort=function(P){Nt=P},this.getClearColor=function(P){return P.copy(be.getClearColor())},this.setClearColor=function(){be.setClearColor(...arguments)},this.getClearAlpha=function(){return be.getClearAlpha()},this.setClearAlpha=function(){be.setClearAlpha(...arguments)},this.clear=function(P=!0,z=!0,Y=!0){let V=0;if(P){let W=!1;if(X!==null){const bt=X.texture.format;W=m.has(bt)}if(W){const bt=X.texture.type,Rt=v.has(bt),wt=be.getClearColor(),Ut=be.getClearAlpha(),Yt=wt.r,Se=wt.g,Re=wt.b;Rt?(M[0]=Yt,M[1]=Se,M[2]=Re,M[3]=Ut,U.clearBufferuiv(U.COLOR,0,M)):(x[0]=Yt,x[1]=Se,x[2]=Re,x[3]=Ut,U.clearBufferiv(U.COLOR,0,x))}else V|=U.COLOR_BUFFER_BIT}z&&(V|=U.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),Y&&(V|=U.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),V!==0&&U.clear(V)},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(P){P.setRenderer(this),I=P},this.dispose=function(){e.removeEventListener("webglcontextlost",ki,!1),e.removeEventListener("webglcontextrestored",vi,!1),e.removeEventListener("webglcontextcreationerror",wa,!1),be.dispose(),yt.dispose(),gt.dispose(),K.dispose(),lt.dispose(),et.dispose(),St.dispose(),nt.dispose(),mt.dispose(),Ft.dispose(),Ft.removeEventListener("sessionstart",nv),Ft.removeEventListener("sessionend",av),Eo.stop()};function ki(P){P.preventDefault(),Cf("WebGLRenderer: Context Lost."),D=!0}function vi(){Cf("WebGLRenderer: Context Restored."),D=!1;const P=H.autoReset,z=ae.enabled,Y=ae.autoUpdate,V=ae.needsUpdate,W=ae.type;Wt(),H.autoReset=P,ae.enabled=z,ae.autoUpdate=Y,ae.needsUpdate=V,ae.type=W}function wa(P){oe("WebGLRenderer: A WebGL context could not be created. Reason: ",P.statusMessage)}function ba(P){const z=P.target;z.removeEventListener("dispose",ba),Kb(z)}function Kb(P){Yb(P),K.remove(P)}function Yb(P){const z=K.get(P).programs;z!==void 0&&(z.forEach(function(Y){mt.releaseProgram(Y)}),P.isShaderMaterial&&mt.releaseShaderCache(P))}this.renderBufferDirect=function(P,z,Y,V,W,bt){z===null&&(z=Ri);const Rt=W.isMesh&&W.matrixWorld.determinantAffine()<0,wt=Zb(P,z,Y,V,W);R.setMaterial(V,Rt);let Ut=Y.index,Yt=1;if(V.wireframe===!0){if(Ut=j.getWireframeAttribute(Y),Ut===void 0)return;Yt=2}const Se=Y.drawRange,Re=Y.attributes.position;let $t=Se.start*Yt,ci=(Se.start+Se.count)*Yt;bt!==null&&($t=Math.max($t,bt.start*Yt),ci=Math.min(ci,(bt.start+bt.count)*Yt)),Ut!==null?($t=Math.max($t,0),ci=Math.min(ci,Ut.count)):Re!=null&&($t=Math.max($t,0),ci=Math.min(ci,Re.count));const Wi=ci-$t;if(Wi<0||Wi===1/0)return;St.setup(W,V,wt,Y,Ut);let Fi,ui=ut;if(Ut!==null&&(Fi=ft.get(Ut),ui=tt,ui.setIndex(Fi)),W.isMesh)V.wireframe===!0?(R.setLineWidth(V.wireframeLinewidth*ji()),ui.setMode(U.LINES)):ui.setMode(U.TRIANGLES);else if(W.isLine){let Us=V.linewidth;Us===void 0&&(Us=1),R.setLineWidth(Us*ji()),W.isLineSegments?ui.setMode(U.LINES):W.isLineLoop?ui.setMode(U.LINE_LOOP):ui.setMode(U.LINE_STRIP)}else W.isPoints?ui.setMode(U.POINTS):W.isSprite&&ui.setMode(U.TRIANGLES);if(W.isBatchedMesh)if(ti.get("WEBGL_multi_draw"))ui.renderMultiDraw(W._multiDrawStarts,W._multiDrawCounts,W._multiDrawCount);else{const Us=W._multiDrawStarts,At=W._multiDrawCounts,_n=W._multiDrawCount,Ge=Ut?ft.get(Ut).bytesPerElement:1,Hn=K.get(V).currentProgram.getUniforms();for(let Sa=0;Sa<_n;Sa++)Hn.setValue(U,"_gl_DrawID",Sa),ui.render(Us[Sa]/Ge,At[Sa])}else if(W.isInstancedMesh)ui.renderInstances($t,Wi,W.count);else if(Y.isInstancedBufferGeometry){const Us=Y._maxInstanceCount!==void 0?Y._maxInstanceCount:1/0,At=Math.min(Y.instanceCount,Us);ui.renderInstances($t,Wi,At)}else ui.render($t,Wi)};function sv(P,z,Y){P.transparent===!0&&P.side===ds&&P.forceSinglePass===!1?(P.side=Ai,P.needsUpdate=!0,Cu(P,z,Y),P.side=sr,P.needsUpdate=!0,Cu(P,z,Y),P.side=ds):Cu(P,z,Y)}this.compile=function(P,z,Y=null){Y===null&&(Y=P),S=gt.get(Y),S.init(z),b.push(S),Y.traverseVisible(function(W){W.isLight&&W.layers.test(z.layers)&&(S.pushLight(W),W.castShadow&&S.pushShadow(W))}),P!==Y&&P.traverseVisible(function(W){W.isLight&&W.layers.test(z.layers)&&(S.pushLight(W),W.castShadow&&S.pushShadow(W))}),S.setupLights();const V=new Set;return P.traverse(function(W){if(!(W.isMesh||W.isPoints||W.isLine||W.isSprite))return;const bt=W.material;if(bt)if(Array.isArray(bt))for(let Rt=0;Rt<bt.length;Rt++){const wt=bt[Rt];sv(wt,Y,W),V.add(wt)}else sv(bt,Y,W),V.add(bt)}),S=b.pop(),V},this.compileAsync=function(P,z,Y=null){const V=this.compile(P,z,Y);return new Promise(W=>{function bt(){if(V.forEach(function(Rt){K.get(Rt).currentProgram.isReady()&&V.delete(Rt)}),V.size===0){W(P);return}setTimeout(bt,10)}ti.get("KHR_parallel_shader_compile")!==null?bt():setTimeout(bt,10)})};let b0=null;function $b(P){b0&&b0(P)}function nv(){Eo.stop()}function av(){Eo.start()}const Eo=new sb;Eo.setAnimationLoop($b),typeof self<"u"&&Eo.setContext(self),this.setAnimationLoop=function(P){b0=P,Ft.setAnimationLoop(P),P===null?Eo.stop():Eo.start()},Ft.addEventListener("sessionstart",nv),Ft.addEventListener("sessionend",av),this.render=function(P,z){if(z!==void 0&&z.isCamera!==!0){oe("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;I!==null&&I.renderStart(P,z);const Y=Ft.enabled===!0&&Ft.isPresenting===!0,V=A!==null&&(X===null||Y)&&A.begin(T,X);if(P.matrixWorldAutoUpdate===!0&&P.updateMatrixWorld(),z.parent===null&&z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),Ft.enabled===!0&&Ft.isPresenting===!0&&(A===null||A.isCompositing()===!1)&&(Ft.cameraAutoUpdate===!0&&Ft.updateCamera(z),z=Ft.getCamera()),P.isScene===!0&&P.onBeforeRender(T,P,z,X),S=gt.get(P,b.length),S.init(z),S.state.textureUnits=Z.getTextureUnits(),b.push(S),je.multiplyMatrices(z.projectionMatrix,z.matrixWorldInverse),te.setFromProjectionMatrix(je,ja,z.reversedDepth),se=this.localClippingEnabled,ie=Qt.init(this.clippingPlanes,se),w=yt.get(P,E.length),w.init(),E.push(w),Ft.enabled===!0&&Ft.isPresenting===!0){const Rt=T.xr.getDepthSensingMesh();Rt!==null&&S0(Rt,z,-1/0,T.sortObjects)}S0(P,z,0,T.sortObjects),w.finish(),T.sortObjects===!0&&w.sort(G,Nt,z.reversedDepth),Ni=Ft.enabled===!1||Ft.isPresenting===!1||Ft.hasDepthSensing()===!1,Ni&&be.addToRenderList(w,P),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),ie===!0&&Qt.beginShadows();const W=S.state.shadowsArray;if(ae.render(W,P,z),ie===!0&&Qt.endShadows(),(V&&A.hasRenderPass())===!1){const Rt=w.opaque,wt=w.transmissive;if(S.setupLights(),z.isArrayCamera){const Ut=z.cameras;if(wt.length>0)for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt];ov(Rt,wt,P,Re)}Ni&&be.render(P);for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt];rv(w,P,Re,Re.viewport)}}else wt.length>0&&ov(Rt,wt,P,z),Ni&&be.render(P),rv(w,P,z)}X!==null&&B===0&&(Z.updateMultisampleRenderTarget(X),Z.updateRenderTargetMipmap(X)),V&&A.end(T),P.isScene===!0&&P.onAfterRender(T,P,z),St.resetDefaultState(),J=-1,$=null,b.pop(),b.length>0?(S=b[b.length-1],Z.setTextureUnits(S.state.textureUnits),ie===!0&&Qt.setGlobalState(T.clippingPlanes,S.state.camera)):S=null,E.pop(),E.length>0?w=E[E.length-1]:w=null,I!==null&&I.renderEnd()};function S0(P,z,Y,V){if(P.visible===!1)return;if(P.layers.test(z.layers)){if(P.isGroup)Y=P.renderOrder;else if(P.isLOD)P.autoUpdate===!0&&P.update(z);else if(P.isLightProbeGrid)S.pushLightProbeGrid(P);else if(P.isLight)S.pushLight(P),P.castShadow&&S.pushShadow(P);else if(P.isSprite){if(!P.frustumCulled||te.intersectsSprite(P)){V&&Li.setFromMatrixPosition(P.matrixWorld).applyMatrix4(je);const Rt=et.update(P),wt=P.material;wt.visible&&w.push(P,Rt,wt,Y,Li.z,null)}}else if((P.isMesh||P.isLine||P.isPoints)&&(!P.frustumCulled||te.intersectsObject(P))){const Rt=et.update(P),wt=P.material;if(V&&(P.boundingSphere!==void 0?(P.boundingSphere===null&&P.computeBoundingSphere(),Li.copy(P.boundingSphere.center)):(Rt.boundingSphere===null&&Rt.computeBoundingSphere(),Li.copy(Rt.boundingSphere.center)),Li.applyMatrix4(P.matrixWorld).applyMatrix4(je)),Array.isArray(wt)){const Ut=Rt.groups;for(let Yt=0,Se=Ut.length;Yt<Se;Yt++){const Re=Ut[Yt],$t=wt[Re.materialIndex];$t&&$t.visible&&w.push(P,Rt,$t,Y,Li.z,Re)}}else wt.visible&&w.push(P,Rt,wt,Y,Li.z,null)}}const bt=P.children;for(let Rt=0,wt=bt.length;Rt<wt;Rt++)S0(bt[Rt],z,Y,V)}function rv(P,z,Y,V){const{opaque:W,transmissive:bt,transparent:Rt}=P;S.setupLightsView(Y),ie===!0&&Qt.setGlobalState(T.clippingPlanes,Y),V&&R.viewport(it.copy(V)),W.length>0&&Pu(W,z,Y),bt.length>0&&Pu(bt,z,Y),Rt.length>0&&Pu(Rt,z,Y),R.buffers.depth.setTest(!0),R.buffers.depth.setMask(!0),R.buffers.color.setMask(!0),R.setPolygonOffset(!1)}function ov(P,z,Y,V){if((Y.isScene===!0?Y.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const $t=ti.has("EXT_color_buffer_half_float")||ti.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new Ke(1,1,{generateMipmaps:!0,type:$t?Be:Zs,minFilter:Fn,samples:Math.max(4,L.samples),stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ke.workingColorSpace})}const bt=S.state.transmissionRenderTarget[V.id],Rt=V.viewport||it;bt.setSize(Rt.z*T.transmissionResolutionScale,Rt.w*T.transmissionResolutionScale);const wt=T.getRenderTarget(),Ut=T.getActiveCubeFace(),Yt=T.getActiveMipmapLevel();T.setRenderTarget(bt),T.getClearColor(qt),Zt=T.getClearAlpha(),Zt<1&&T.setClearColor(16777215,.5),T.clear(),Ni&&be.render(Y);const Se=T.toneMapping;T.toneMapping=tr;const Re=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),ie===!0&&Qt.setGlobalState(T.clippingPlanes,V),Pu(P,Y,V),Z.updateMultisampleRenderTarget(bt),Z.updateRenderTargetMipmap(bt),ti.has("WEBGL_multisampled_render_to_texture")===!1){let $t=!1;for(let ci=0,Wi=z.length;ci<Wi;ci++){const Fi=z[ci],{object:ui,geometry:Us,material:At,group:_n}=Fi;if(At.side===ds&&ui.layers.test(V.layers)){const Ge=At.side;At.side=Ai,At.needsUpdate=!0,cv(ui,Y,V,Us,At,_n),At.side=Ge,At.needsUpdate=!0,$t=!0}}$t===!0&&(Z.updateMultisampleRenderTarget(bt),Z.updateRenderTargetMipmap(bt))}T.setRenderTarget(wt,Ut,Yt),T.setClearColor(qt,Zt),Re!==void 0&&(V.viewport=Re),T.toneMapping=Se}function Pu(P,z,Y){const V=z.isScene===!0?z.overrideMaterial:null;for(let W=0,bt=P.length;W<bt;W++){const Rt=P[W],{object:wt,geometry:Ut,group:Yt}=Rt;let Se=Rt.material;Se.allowOverride===!0&&V!==null&&(Se=V),wt.layers.test(Y.layers)&&cv(wt,z,Y,Ut,Se,Yt)}}function cv(P,z,Y,V,W,bt){P.onBeforeRender(T,z,Y,V,W,bt),P.modelViewMatrix.multiplyMatrices(Y.matrixWorldInverse,P.matrixWorld),P.normalMatrix.getNormalMatrix(P.modelViewMatrix),W.onBeforeRender(T,z,Y,V,P,bt),W.transparent===!0&&W.side===ds&&W.forceSinglePass===!1?(W.side=Ai,W.needsUpdate=!0,T.renderBufferDirect(Y,z,V,W,P,bt),W.side=sr,W.needsUpdate=!0,T.renderBufferDirect(Y,z,V,W,P,bt),W.side=ds):T.renderBufferDirect(Y,z,V,W,P,bt),P.onAfterRender(T,z,Y,V,W,bt)}function Cu(P,z,Y){z.isScene!==!0&&(z=Ri);const V=K.get(P),W=S.state.lights,bt=S.state.shadowsArray,Rt=W.state.version,wt=mt.getParameters(P,W.state,bt,z,Y,S.state.lightProbeGridArray),Ut=mt.getProgramCacheKey(wt);let Yt=V.programs;V.environment=P.isMeshStandardMaterial||P.isMeshLambertMaterial||P.isMeshPhongMaterial?z.environment:null,V.fog=z.fog;const Se=P.isMeshStandardMaterial||P.isMeshLambertMaterial&&!P.envMap||P.isMeshPhongMaterial&&!P.envMap;V.envMap=lt.get(P.envMap||V.environment,Se),V.envMapRotation=V.environment!==null&&P.envMap===null?z.environmentRotation:P.envMapRotation,Yt===void 0&&(P.addEventListener("dispose",ba),Yt=new Map,V.programs=Yt);let Re=Yt.get(Ut);if(Re!==void 0){if(V.currentProgram===Re&&V.lightsStateVersion===Rt)return hv(P,wt),Re}else wt.uniforms=mt.getUniforms(P),I!==null&&P.isNodeMaterial&&I.build(P,Y,wt),P.onBeforeCompile(wt,T),Re=mt.acquireProgram(wt,Ut),Yt.set(Ut,Re),V.uniforms=wt.uniforms;const $t=V.uniforms;return(!P.isShaderMaterial&&!P.isRawShaderMaterial||P.clipping===!0)&&($t.clippingPlanes=Qt.uniform),hv(P,wt),V.needsLights=jb(P),V.lightsStateVersion=Rt,V.needsLights&&($t.ambientLightColor.value=W.state.ambient,$t.lightProbe.value=W.state.probe,$t.directionalLights.value=W.state.directional,$t.directionalLightShadows.value=W.state.directionalShadow,$t.spotLights.value=W.state.spot,$t.spotLightShadows.value=W.state.spotShadow,$t.rectAreaLights.value=W.state.rectArea,$t.ltc_1.value=W.state.rectAreaLTC1,$t.ltc_2.value=W.state.rectAreaLTC2,$t.pointLights.value=W.state.point,$t.pointLightShadows.value=W.state.pointShadow,$t.hemisphereLights.value=W.state.hemi,$t.directionalShadowMatrix.value=W.state.directionalShadowMatrix,$t.spotLightMatrix.value=W.state.spotLightMatrix,$t.spotLightMap.value=W.state.spotLightMap,$t.pointShadowMatrix.value=W.state.pointShadowMatrix),V.lightProbeGrid=S.state.lightProbeGridArray.length>0,V.currentProgram=Re,V.uniformsList=null,Re}function lv(P){if(P.uniformsList===null){const z=P.currentProgram.getUniforms();P.uniformsList=of.seqWithValue(z.seq,P.uniforms)}return P.uniformsList}function hv(P,z){const Y=K.get(P);Y.outputColorSpace=z.outputColorSpace,Y.batching=z.batching,Y.batchingColor=z.batchingColor,Y.instancing=z.instancing,Y.instancingColor=z.instancingColor,Y.instancingMorph=z.instancingMorph,Y.skinning=z.skinning,Y.morphTargets=z.morphTargets,Y.morphNormals=z.morphNormals,Y.morphColors=z.morphColors,Y.morphTargetsCount=z.morphTargetsCount,Y.numClippingPlanes=z.numClippingPlanes,Y.numIntersection=z.numClipIntersection,Y.vertexAlphas=z.vertexAlphas,Y.vertexTangents=z.vertexTangents,Y.toneMapping=z.toneMapping}function qb(P,z){if(P.length===0)return null;if(P.length===1)return P[0].texture!==null?P[0]:null;y.setFromMatrixPosition(z.matrixWorld);for(let Y=0,V=P.length;Y<V;Y++){const W=P[Y];if(W.texture!==null&&W.boundingBox.containsPoint(y))return W}return null}function Zb(P,z,Y,V,W){z.isScene!==!0&&(z=Ri),Z.resetTextureUnits();const bt=z.fog,Rt=V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial?z.environment:null,wt=X===null?T.outputColorSpace:X.isXRRenderTarget===!0?X.texture.colorSpace:ke.workingColorSpace,Ut=V.isMeshStandardMaterial||V.isMeshLambertMaterial&&!V.envMap||V.isMeshPhongMaterial&&!V.envMap,Yt=lt.get(V.envMap||Rt,Ut),Se=V.vertexColors===!0&&!!Y.attributes.color&&Y.attributes.color.itemSize===4,Re=!!Y.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),$t=!!Y.morphAttributes.position,ci=!!Y.morphAttributes.normal,Wi=!!Y.morphAttributes.color;let Fi=tr;V.toneMapped&&(X===null||X.isXRRenderTarget===!0)&&(Fi=T.toneMapping);const ui=Y.morphAttributes.position||Y.morphAttributes.normal||Y.morphAttributes.color,Us=ui!==void 0?ui.length:0,At=K.get(V),_n=S.state.lights;if(ie===!0&&(se===!0||P!==$)){const Mi=P===$&&V.id===J;Qt.setState(V,P,Mi)}let Ge=!1;V.version===At.__version?(At.needsLights&&At.lightsStateVersion!==_n.state.version||At.outputColorSpace!==wt||W.isBatchedMesh&&At.batching===!1||!W.isBatchedMesh&&At.batching===!0||W.isBatchedMesh&&At.batchingColor===!0&&W.colorTexture===null||W.isBatchedMesh&&At.batchingColor===!1&&W.colorTexture!==null||W.isInstancedMesh&&At.instancing===!1||!W.isInstancedMesh&&At.instancing===!0||W.isSkinnedMesh&&At.skinning===!1||!W.isSkinnedMesh&&At.skinning===!0||W.isInstancedMesh&&At.instancingColor===!0&&W.instanceColor===null||W.isInstancedMesh&&At.instancingColor===!1&&W.instanceColor!==null||W.isInstancedMesh&&At.instancingMorph===!0&&W.morphTexture===null||W.isInstancedMesh&&At.instancingMorph===!1&&W.morphTexture!==null||At.envMap!==Yt||V.fog===!0&&At.fog!==bt||At.numClippingPlanes!==void 0&&(At.numClippingPlanes!==Qt.numPlanes||At.numIntersection!==Qt.numIntersection)||At.vertexAlphas!==Se||At.vertexTangents!==Re||At.morphTargets!==$t||At.morphNormals!==ci||At.morphColors!==Wi||At.toneMapping!==Fi||At.morphTargetsCount!==Us||!!At.lightProbeGrid!=S.state.lightProbeGridArray.length>0)&&(Ge=!0):(Ge=!0,At.__version=V.version);let Hn=At.currentProgram;Ge===!0&&(Hn=Cu(V,z,W),I&&V.isNodeMaterial&&I.onUpdateProgram(V,Hn,At));let Sa=!1,Nr=!1,mc=!1;const di=Hn.getUniforms(),Xi=At.uniforms;if(R.useProgram(Hn.program)&&(Sa=!0,Nr=!0,mc=!0),V.id!==J&&(J=V.id,Nr=!0),At.needsLights){const Mi=qb(S.state.lightProbeGridArray,W);At.lightProbeGrid!==Mi&&(At.lightProbeGrid=Mi,Nr=!0)}if(Sa||$!==P){R.buffers.depth.getReversed()&&P.reversedDepth!==!0&&(P._reversedDepth=!0,P.updateProjectionMatrix()),di.setValue(U,"projectionMatrix",P.projectionMatrix),di.setValue(U,"viewMatrix",P.matrixWorldInverse);const Fr=di.map.cameraPosition;Fr!==void 0&&Fr.setValue(U,Qe.setFromMatrixPosition(P.matrixWorld)),L.logarithmicDepthBuffer&&di.setValue(U,"logDepthBufFC",2/(Math.log(P.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&di.setValue(U,"isOrthographic",P.isOrthographicCamera===!0),$!==P&&($=P,Nr=!0,mc=!0)}if(At.needsLights&&(_n.state.directionalShadowMap.length>0&&di.setValue(U,"directionalShadowMap",_n.state.directionalShadowMap,Z),_n.state.spotShadowMap.length>0&&di.setValue(U,"spotShadowMap",_n.state.spotShadowMap,Z),_n.state.pointShadowMap.length>0&&di.setValue(U,"pointShadowMap",_n.state.pointShadowMap,Z)),W.isSkinnedMesh){di.setOptional(U,W,"bindMatrix"),di.setOptional(U,W,"bindMatrixInverse");const Mi=W.skeleton;Mi&&(Mi.boneTexture===null&&Mi.computeBoneTexture(),di.setValue(U,"boneTexture",Mi.boneTexture,Z))}W.isBatchedMesh&&(di.setOptional(U,W,"batchingTexture"),di.setValue(U,"batchingTexture",W._matricesTexture,Z),di.setOptional(U,W,"batchingIdTexture"),di.setValue(U,"batchingIdTexture",W._indirectTexture,Z),di.setOptional(U,W,"batchingColorTexture"),W._colorsTexture!==null&&di.setValue(U,"batchingColorTexture",W._colorsTexture,Z));const kr=Y.morphAttributes;if((kr.position!==void 0||kr.normal!==void 0||kr.color!==void 0)&&F.update(W,Y,Hn),(Nr||At.receiveShadow!==W.receiveShadow)&&(At.receiveShadow=W.receiveShadow,di.setValue(U,"receiveShadow",W.receiveShadow)),(V.isMeshStandardMaterial||V.isMeshLambertMaterial||V.isMeshPhongMaterial)&&V.envMap===null&&z.environment!==null&&(Xi.envMapIntensity.value=z.environmentIntensity),Xi.dfgLUT!==void 0&&(Xi.dfgLUT.value=nI()),Nr){if(di.setValue(U,"toneMappingExposure",T.toneMappingExposure),At.needsLights&&Jb(Xi,mc),bt&&V.fog===!0&&Kt.refreshFogUniforms(Xi,bt),Kt.refreshMaterialUniforms(Xi,V,st,ot,S.state.transmissionRenderTarget[P.id]),At.needsLights&&At.lightProbeGrid){const Mi=At.lightProbeGrid;Xi.probesSH.value=Mi.texture,Xi.probesMin.value.copy(Mi.boundingBox.min),Xi.probesMax.value.copy(Mi.boundingBox.max),Xi.probesResolution.value.copy(Mi.resolution)}of.upload(U,lv(At),Xi,Z)}if(V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(of.upload(U,lv(At),Xi,Z),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&di.setValue(U,"center",W.center),di.setValue(U,"modelViewMatrix",W.modelViewMatrix),di.setValue(U,"normalMatrix",W.normalMatrix),di.setValue(U,"modelMatrix",W.matrixWorld),V.uniformsGroups!==void 0){const Mi=V.uniformsGroups;for(let Fr=0,gc=Mi.length;Fr<gc;Fr++){const uv=Mi[Fr];nt.update(uv,Hn),nt.bind(uv,Hn)}}return Hn}function Jb(P,z){P.ambientLightColor.needsUpdate=z,P.lightProbe.needsUpdate=z,P.directionalLights.needsUpdate=z,P.directionalLightShadows.needsUpdate=z,P.pointLights.needsUpdate=z,P.pointLightShadows.needsUpdate=z,P.spotLights.needsUpdate=z,P.spotLightShadows.needsUpdate=z,P.rectAreaLights.needsUpdate=z,P.hemisphereLights.needsUpdate=z}function jb(P){return P.isMeshLambertMaterial||P.isMeshToonMaterial||P.isMeshPhongMaterial||P.isMeshStandardMaterial||P.isShadowMaterial||P.isShaderMaterial&&P.lights===!0}this.getActiveCubeFace=function(){return k},this.getActiveMipmapLevel=function(){return B},this.getRenderTarget=function(){return X},this.setRenderTargetTextures=function(P,z,Y){const V=K.get(P);V.__autoAllocateDepthBuffer=P.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),K.get(P.texture).__webglTexture=z,K.get(P.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:Y,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(P,z){const Y=K.get(P);Y.__webglFramebuffer=z,Y.__useDefaultFramebuffer=z===void 0},this.setRenderTarget=function(P,z=0,Y=0){X=P,k=z,B=Y;let V=null,W=!1,bt=!1;if(P){const wt=K.get(P);if(wt.__useDefaultFramebuffer!==void 0){R.bindFramebuffer(U.FRAMEBUFFER,wt.__webglFramebuffer),it.copy(P.viewport),rt.copy(P.scissor),Lt=P.scissorTest,R.viewport(it),R.scissor(rt),R.setScissorTest(Lt),J=-1;return}else if(wt.__webglFramebuffer===void 0)Z.setupRenderTarget(P);else if(wt.__hasExternalTextures)Z.rebindTextures(P,K.get(P.texture).__webglTexture,K.get(P.depthTexture).__webglTexture);else if(P.depthBuffer){const Se=P.depthTexture;if(wt.__boundDepthTexture!==Se){if(Se!==null&&K.has(Se)&&(P.width!==Se.image.width||P.height!==Se.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");Z.setupDepthRenderbuffer(P)}}const Ut=P.texture;(Ut.isData3DTexture||Ut.isDataArrayTexture||Ut.isCompressedArrayTexture)&&(bt=!0);const Yt=K.get(P).__webglFramebuffer;P.isWebGLCubeRenderTarget?(Array.isArray(Yt[z])?V=Yt[z][Y]:V=Yt[z],W=!0):P.samples>0&&Z.useMultisampledRTT(P)===!1?V=K.get(P).__webglMultisampledFramebuffer:Array.isArray(Yt)?V=Yt[Y]:V=Yt,it.copy(P.viewport),rt.copy(P.scissor),Lt=P.scissorTest}else it.copy(Xt).multiplyScalar(st).floor(),rt.copy(kt).multiplyScalar(st).floor(),Lt=Tt;if(Y!==0&&(V=C),R.bindFramebuffer(U.FRAMEBUFFER,V)&&R.drawBuffers(P,V),R.viewport(it),R.scissor(rt),R.setScissorTest(Lt),W){const wt=K.get(P.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_CUBE_MAP_POSITIVE_X+z,wt.__webglTexture,Y)}else if(bt){const wt=z;for(let Ut=0;Ut<P.textures.length;Ut++){const Yt=K.get(P.textures[Ut]);U.framebufferTextureLayer(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0+Ut,Yt.__webglTexture,Y,wt)}}else if(P!==null&&Y!==0){const wt=K.get(P.texture);U.framebufferTexture2D(U.FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,wt.__webglTexture,Y)}J=-1},this.readRenderTargetPixels=function(P,z,Y,V,W,bt,Rt,wt=0){if(!(P&&P.isWebGLRenderTarget)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ut=K.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Rt!==void 0&&(Ut=Ut[Rt]),Ut){R.bindFramebuffer(U.FRAMEBUFFER,Ut);try{const Yt=P.textures[wt],Se=Yt.format,Re=Yt.type;if(P.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+wt),!L.textureFormatReadable(Se)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!L.textureTypeReadable(Re)){oe("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}z>=0&&z<=P.width-V&&Y>=0&&Y<=P.height-W&&U.readPixels(z,Y,V,W,vt.convert(Se),vt.convert(Re),bt)}finally{const Yt=X!==null?K.get(X).__webglFramebuffer:null;R.bindFramebuffer(U.FRAMEBUFFER,Yt)}}},this.readRenderTargetPixelsAsync=async function(P,z,Y,V,W,bt,Rt,wt=0){if(!(P&&P.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ut=K.get(P).__webglFramebuffer;if(P.isWebGLCubeRenderTarget&&Rt!==void 0&&(Ut=Ut[Rt]),Ut)if(z>=0&&z<=P.width-V&&Y>=0&&Y<=P.height-W){R.bindFramebuffer(U.FRAMEBUFFER,Ut);const Yt=P.textures[wt],Se=Yt.format,Re=Yt.type;if(P.textures.length>1&&U.readBuffer(U.COLOR_ATTACHMENT0+wt),!L.textureFormatReadable(Se))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!L.textureTypeReadable(Re))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const $t=U.createBuffer();U.bindBuffer(U.PIXEL_PACK_BUFFER,$t),U.bufferData(U.PIXEL_PACK_BUFFER,bt.byteLength,U.STREAM_READ),U.readPixels(z,Y,V,W,vt.convert(Se),vt.convert(Re),0);const ci=X!==null?K.get(X).__webglFramebuffer:null;R.bindFramebuffer(U.FRAMEBUFFER,ci);const Wi=U.fenceSync(U.SYNC_GPU_COMMANDS_COMPLETE,0);return U.flush(),await t3(U,Wi,4),U.bindBuffer(U.PIXEL_PACK_BUFFER,$t),U.getBufferSubData(U.PIXEL_PACK_BUFFER,0,bt),U.deleteBuffer($t),U.deleteSync(Wi),bt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(P,z=null,Y=0){const V=Math.pow(2,-Y),W=Math.floor(P.image.width*V),bt=Math.floor(P.image.height*V),Rt=z!==null?z.x:0,wt=z!==null?z.y:0;Z.setTexture2D(P,0),U.copyTexSubImage2D(U.TEXTURE_2D,Y,0,0,Rt,wt,W,bt),R.unbindTexture()},this.copyTextureToTexture=function(P,z,Y=null,V=null,W=0,bt=0){let Rt,wt,Ut,Yt,Se,Re,$t,ci,Wi;const Fi=P.isCompressedTexture?P.mipmaps[bt]:P.image;if(Y!==null)Rt=Y.max.x-Y.min.x,wt=Y.max.y-Y.min.y,Ut=Y.isBox3?Y.max.z-Y.min.z:1,Yt=Y.min.x,Se=Y.min.y,Re=Y.isBox3?Y.min.z:0;else{const Xi=Math.pow(2,-W);Rt=Math.floor(Fi.width*Xi),wt=Math.floor(Fi.height*Xi),P.isDataArrayTexture?Ut=Fi.depth:P.isData3DTexture?Ut=Math.floor(Fi.depth*Xi):Ut=1,Yt=0,Se=0,Re=0}V!==null?($t=V.x,ci=V.y,Wi=V.z):($t=0,ci=0,Wi=0);const ui=vt.convert(z.format),Us=vt.convert(z.type);let At;z.isData3DTexture?(Z.setTexture3D(z,0),At=U.TEXTURE_3D):z.isDataArrayTexture||z.isCompressedArrayTexture?(Z.setTexture2DArray(z,0),At=U.TEXTURE_2D_ARRAY):(Z.setTexture2D(z,0),At=U.TEXTURE_2D),R.activeTexture(U.TEXTURE0),R.pixelStorei(U.UNPACK_FLIP_Y_WEBGL,z.flipY),R.pixelStorei(U.UNPACK_PREMULTIPLY_ALPHA_WEBGL,z.premultiplyAlpha),R.pixelStorei(U.UNPACK_ALIGNMENT,z.unpackAlignment);const _n=R.getParameter(U.UNPACK_ROW_LENGTH),Ge=R.getParameter(U.UNPACK_IMAGE_HEIGHT),Hn=R.getParameter(U.UNPACK_SKIP_PIXELS),Sa=R.getParameter(U.UNPACK_SKIP_ROWS),Nr=R.getParameter(U.UNPACK_SKIP_IMAGES);R.pixelStorei(U.UNPACK_ROW_LENGTH,Fi.width),R.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Fi.height),R.pixelStorei(U.UNPACK_SKIP_PIXELS,Yt),R.pixelStorei(U.UNPACK_SKIP_ROWS,Se),R.pixelStorei(U.UNPACK_SKIP_IMAGES,Re);const mc=P.isDataArrayTexture||P.isData3DTexture,di=z.isDataArrayTexture||z.isData3DTexture;if(P.isDepthTexture){const Xi=K.get(P),kr=K.get(z),Mi=K.get(Xi.__renderTarget),Fr=K.get(kr.__renderTarget);R.bindFramebuffer(U.READ_FRAMEBUFFER,Mi.__webglFramebuffer),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,Fr.__webglFramebuffer);for(let gc=0;gc<Ut;gc++)mc&&(U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,K.get(P).__webglTexture,W,Re+gc),U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,K.get(z).__webglTexture,bt,Wi+gc)),U.blitFramebuffer(Yt,Se,Rt,wt,$t,ci,Rt,wt,U.DEPTH_BUFFER_BIT,U.NEAREST);R.bindFramebuffer(U.READ_FRAMEBUFFER,null),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else if(W!==0||P.isRenderTargetTexture||K.has(P)){const Xi=K.get(P),kr=K.get(z);R.bindFramebuffer(U.READ_FRAMEBUFFER,N),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,O);for(let Mi=0;Mi<Ut;Mi++)mc?U.framebufferTextureLayer(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,Xi.__webglTexture,W,Re+Mi):U.framebufferTexture2D(U.READ_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,Xi.__webglTexture,W),di?U.framebufferTextureLayer(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,kr.__webglTexture,bt,Wi+Mi):U.framebufferTexture2D(U.DRAW_FRAMEBUFFER,U.COLOR_ATTACHMENT0,U.TEXTURE_2D,kr.__webglTexture,bt),W!==0?U.blitFramebuffer(Yt,Se,Rt,wt,$t,ci,Rt,wt,U.COLOR_BUFFER_BIT,U.NEAREST):di?U.copyTexSubImage3D(At,bt,$t,ci,Wi+Mi,Yt,Se,Rt,wt):U.copyTexSubImage2D(At,bt,$t,ci,Yt,Se,Rt,wt);R.bindFramebuffer(U.READ_FRAMEBUFFER,null),R.bindFramebuffer(U.DRAW_FRAMEBUFFER,null)}else di?P.isDataTexture||P.isData3DTexture?U.texSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Us,Fi.data):z.isCompressedArrayTexture?U.compressedTexSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Fi.data):U.texSubImage3D(At,bt,$t,ci,Wi,Rt,wt,Ut,ui,Us,Fi):P.isDataTexture?U.texSubImage2D(U.TEXTURE_2D,bt,$t,ci,Rt,wt,ui,Us,Fi.data):P.isCompressedTexture?U.compressedTexSubImage2D(U.TEXTURE_2D,bt,$t,ci,Fi.width,Fi.height,ui,Fi.data):U.texSubImage2D(U.TEXTURE_2D,bt,$t,ci,Rt,wt,ui,Us,Fi);R.pixelStorei(U.UNPACK_ROW_LENGTH,_n),R.pixelStorei(U.UNPACK_IMAGE_HEIGHT,Ge),R.pixelStorei(U.UNPACK_SKIP_PIXELS,Hn),R.pixelStorei(U.UNPACK_SKIP_ROWS,Sa),R.pixelStorei(U.UNPACK_SKIP_IMAGES,Nr),bt===0&&z.generateMipmaps&&U.generateMipmap(At),R.unbindTexture()},this.initRenderTarget=function(P){K.get(P).__webglFramebuffer===void 0&&Z.setupRenderTarget(P)},this.initTexture=function(P){P.isCubeTexture?Z.setTextureCube(P,0):P.isData3DTexture?Z.setTexture3D(P,0):P.isDataArrayTexture||P.isCompressedArrayTexture?Z.setTexture2DArray(P,0):Z.setTexture2D(P,0),R.unbindTexture()},this.resetState=function(){k=0,B=0,X=null,R.reset(),St.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ja}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=ke._getDrawingBufferColorSpace(t),e.unpackColorSpace=ke._getUnpackColorSpace()}}class Yo{constructor(t){this.rateAt=t}static HISTORY_S=20;sums=[0];at(t){if(!(t>0))return 0;const e=Math.floor(t);for(;this.sums.length<=e+1;){const i=this.sums.length-1;this.sums.push(this.sums[i]+(this.rateAt(i)+this.rateAt(i+1))/2)}return this.sums[e]+(this.sums[e+1]-this.sums[e])*(t-e)}stateAt(t){return{impacts:this.at(t),history:Array.from({length:Yo.HISTORY_S},(e,i)=>this.at(t-i-1))}}}class Pe{static NONE={ghosts:[],blades:0,bladeAngleRad:0,scattered:0,drops:0,impacts:0,history:[],still:!1,running:0,reachDeg:30,placed:[]};static PHONE=[{scale:-1,share:5e-5,blur:.006,cause:"sensor",tint:[.41,1,.83]},{scale:-.45,share:5e-6,blur:.02,tint:[.7,1,.8]},{scale:.55,share:375e-8,blur:.035,tint:[1,.75,1]}];static CAMERA=[{scale:-1.4,share:3e-4,blur:.045,tint:[1,.8,1]},{scale:-.8,share:4e-4,blur:.02,tint:[.75,1,.8]},{scale:-.35,share:25e-5,blur:.012,tint:[1,.9,.7]},{scale:.3,share:2e-4,blur:.03,tint:[.8,.9,1]},{scale:.65,share:15e-5,blur:.06,tint:[1,.85,1]}];static FILTER={scale:-1,share:.001,blur:.004,cause:"filter"};static WINDOW={scale:1,share:.0016,blur:.002,offset:[0,.006],cause:"glass"};static WINDSCREEN={scale:1,share:.02,blur:.003,offset:[0,.025],cause:"glass"};static OFF_FRAME_REACH_DEG=30;static offFrameShare(t,e,i=Pe.OFF_FRAME_REACH_DEG){const s=Math.min(Math.max((t-e)/i,0),1);return 1-s*s*(3-2*s)}static REFERENCE_F_NUMBER=4;static of(t){return t.ghosts?t.ghosts:Pe.records(t)?t.category==="phone"?Pe.PHONE:Pe.CAMERA:[]}static records(t){return t.medium!==void 0||t.category==="camera"||t.category==="dslr"||t.category==="phone"}static optics(t,e,i,s,n=0){const a=Pe.of(t);if(a.length===0)return Pe.NONE;const r=t.fNumber??Pe.REFERENCE_F_NUMBER,o=e??r,l=[...a,...i?.ghosts??[]].map(y=>({...y,blur:y.blur*r/o}));i?.glass==="filter"?l.push({...Pe.FILTER}):i?.glass==="window"?l.push({...Pe.WINDOW}):i?.glass==="windscreen"&&l.push({...Pe.WINDSCREEN});const h=Pe.share(i?.condensation),u=Pe.share(i?.dirt),d=Pe.falling(i),f=d?s?.impacts??0:0,p=d?s?.history??[]:[],g=f-(p[Pe.DROP_LIFE_S-1]??0),m=i?.drops!==void 0?Pe.share(i.drops):d?Math.min(1,g):0;h>0&&(l.push({scale:1,share:.25*h,blur:.03,cause:"condensation"}),l.push({scale:1,share:.15*h,blur:.12,cause:"condensation"})),u>0&&(l.push({scale:1,share:.03*u,blur:.04,cause:"dirt"}),l.push({scale:1,share:.02*u,blur:.15,cause:"dirt"})),m>0&&l.push({scale:1,share:.12*m,blur:.025,cause:"drops"});const v=l.filter(y=>Pe.scatters(y)).reduce((y,w)=>y+w.share,0),M=Ts.bladesShowing(t,e)>=.5?t.apertureBlades??0:0,x=i?.glass==="window"||i?.glass==="windscreen"?1:.25;return{ghosts:l,blades:M,bladeAngleRad:.3,scattered:Math.min(.9,v),drops:m,impacts:f,history:p,still:i?.drops!==void 0,running:x,reachDeg:i?.reachDeg??Pe.OFF_FRAME_REACH_DEG,placed:(i?.placedDrops??[]).map(y=>Pe.placedAt(y,n))}}static placedAt(t,e){const i=t.track,s=i.findIndex(o=>o.t>e);if(s===0)return{x:i[0].x,y:i[0].y,radius:t.radius};if(s===-1){const o=i[i.length-1];return{x:o.x,y:o.y,radius:t.radius}}const n=i[s-1],a=i[s],r=(e-n.t)/(a.t-n.t);return{x:n.x+(a.x-n.x)*r,y:n.y+(a.y-n.y)*r,radius:t.radius}}static falling(t){return t?.drops===void 0&&!t?.sheltered}static DROP_LIFE_S=8;static impactRate(t,e,i){const s=Pe.dropsFrom(t);if(s===0)return 0;const n=t.precipitationType==="snow"?1:6.5,a=((i?.windFromDeg??0)+180)*Math.PI/180,r=i?.windSpeedMS??0,o=[Math.sin(a)*r,Math.cos(a)*r,-n],l=(i?.headingDeg??0)*Math.PI/180,h=(e==="window"?0:e==="windscreen"?60:i?.pitchDeg??0)*Math.PI/180,u=[Math.sin(l)*Math.cos(h),Math.cos(l)*Math.cos(h),Math.sin(h)],d=Math.hypot(o[0],o[1],o[2]),f=Math.max(0,-(o[0]*u[0]+o[1]*u[1]+o[2]*u[2])/d);return s*.4*(.02+.98*f)}static scatters(t){return t.cause==="condensation"||t.cause==="dirt"||t.cause==="drops"}static dropsFrom(t){if(!t||t.precipitationType==="none"||t.precipitationType==="hail")return 0;const e=Pe.share(t.precipitationIntensity);return e===0?0:t.precipitationType==="snow"?.5*e:Math.min(1,.3+.7*e)}static positionOf(t,e){return{x:e.x*t.scale+2*(t.offset?.[0]??0),y:e.y*t.scale+2*(t.offset?.[1]??0)}}static sourceOf(t,e){return{x:(e.x-2*(t.offset?.[0]??0))/t.scale,y:(e.y-2*(t.offset?.[1]??0))/t.scale}}static share(t){return Math.max(0,Math.min(1,t??0))}}const xs=Math.PI/180;class ee{constructor(t){this.words=t}static COARSE_DEG=2;static FINE_DEG=.25;findingsOf(t,e){const i=Ls.strip(e).recording,s=i.interpretation?.mechanism;if(!s)return[];const n=ee.settingOf(t,s.explains);if(!n)return[];const a="interpretation.mechanism";switch(s.kind){case"fixed-in-frame":{const r=ee.missOf(n.samples,ee.fixedPoint(n.samples));return[this.finding(this.words.bestFixed,r,n,{},"established",a)]}case"driven-one-way":{const{miss:r,directionDeg:o}=ee.oneWay(n.samples);return[this.finding(this.words.bestOneWay,r,n,{direction:Math.round(o)},"established",a)]}case"lens-ghost":return this.lensGhostFindings(n,i,a);case"stated-ghost":return this.statedGhostFindings(n,i,a);case"ghost-of":return this.ghostOfFindings(n,i,s.of,a);case"real-object":return[this.realObjectFinding(n,i,s.explains,a)]}}ghostOfFindings(t,e,i,s){const n=e.interpretation?.bodies?.find(u=>u.id===i);if(!n)return[];const a=t.samples.map(u=>{const d=ee.bodyDirectionAt(n,u.t);if(!d)return;const f=d.applyQuaternion(u.frame.inverse);return f.z<0?{x:f.x/-f.z,y:f.y/-f.z}:void 0}),r=Pe.of(Ts.byId(e.instrument)).filter(u=>!Pe.scatters(u)).map(u=>u.scale);let o;for(const u of r){const d=a.map(p=>p?{x:u*p.x,y:u*p.y}:void 0),f=ee.missOfTrack(t.samples,d);(!o||f.medianDeg<o.miss.medianDeg)&&(o={miss:f,k:u,track:d})}if(!o)return[];const l=o.track.filter(u=>u!==void 0);let h=0;for(const u of l)for(const d of l)h=Math.max(h,ee.angleDeg(u,d));return[this.finding(this.words.bestGhostOf,o.miss,t,{k:this.number(o.k),ghostTravel:this.number(h)},"established",s)]}realObjectFinding(t,e,i,s){const a=e.interpretation?.bodies?.find(l=>l.explains?.includes(i))?.track[0]?.distanceM??ee.DEFAULT_DISTANCE_M,r=t.samples.map(l=>new _(l.at.x,l.at.y,-1).normalize().applyQuaternion(l.frame.rotation));let o=0;for(let l=0;l<r.length;l++){const h=t.samples.findIndex(u=>u.t>=t.samples[l].t+ee.RATE_WINDOW_MS);if(h<0)break;o=Math.max(o,r[l].angleTo(r[h])/((t.samples[h].t-t.samples[l].t)/1e3))}return{text:this.fill(this.words.bestRealObject,{medianDeg:0,maxDeg:0},t,{distance:Math.round(a),width:this.number(a*t.sizeDeg*xs),speed:Math.round(a*o)}),outcome:"holds",against:"established",path:s}}static bodyDirectionAt(t,e){const i=t.track.filter(l=>l.azimuthDeg!==void 0&&l.altitudeDeg!==void 0);if(i.length===0)return;const s=i.findIndex(l=>l.t>e),n=i[s<=0?s===0?0:i.length-1:s-1],a=s<=0?n:i[s],r=a.t>n.t?(e-n.t)/(a.t-n.t):0,o=((a.azimuthDeg-n.azimuthDeg)%360+540)%360-180;return ee.direction(n.azimuthDeg+o*r,n.altitudeDeg+(a.altitudeDeg-n.altitudeDeg)*r)}static DEFAULT_DISTANCE_M=1e3;static RATE_WINDOW_MS=500;static lays(t){return t?.kind==="fixed-in-frame"||t?.kind==="driven-one-way"||t?.kind==="real-object"}bestSceneOf(t,e){const s=Ls.strip(e).recording.interpretation?.mechanism;if(!ee.lays(s))return;const n=ee.settingOf(t,s.explains);if(!n)return;const a=structuredClone(e);if(s.kind==="fixed-in-frame"||s.kind==="real-object"){const r=a.interpretation??{bodies:[]},o=r.bodies??[],l=o.findIndex(d=>d.explains?.includes(s.explains)),h=l>=0?o[l]:void 0,u=s.kind==="fixed-in-frame"?ee.stillBody(n,s.explains,h):ee.sightLineBody(n,s.explains,h);a.interpretation={...r,bodies:l>=0?o.map((d,f)=>f===l?u:d):[...o,u]}}else{const{track:r}=ee.oneWay(n.samples),o=a.lens?.placedDrops?.[0],l=n.samples[0],h=o?.radius??ee.round(n.sizeDeg/l.frame.fovDeg,4),u=n.samples.map((d,f)=>{const p=Math.tan(d.frame.fovDeg/2*xs);return{t:d.t,x:ee.round(.5+r[f].x/(2*p*n.aspect),4),y:ee.round(.5-r[f].y/(2*p),4)}});a.lens={...a.lens,placedDrops:[{radius:h,track:u}]}}return a}static stillBody(t,e,i){const s=ee.fixedPoint(t.samples),n=t.samples[0].t,a=t.samples[t.samples.length-1].t,r=[...new Set([...t.samples.map(o=>o.t),...t.keyframes.map(o=>o.t).filter(o=>o>n&&o<a)])].sort((o,l)=>o-l);return ee.bodyAlong(t,e,i,r,()=>s)}static sightLineBody(t,e,i){return ee.bodyAlong(t,e,i,t.samples.map(s=>s.t),(s,n)=>t.samples[n].at)}static bodyAlong(t,e,i,s,n){const a=s[s.length-1],r=i?.track[0],o=r?.distanceM??ee.DEFAULT_DISTANCE_M,l=r?.sizeM??(()=>{const f=ee.round(o*t.sizeDeg*xs,4);return{widthM:f,lengthM:f,heightM:f}})(),h=r?.appearance??{color:"#f4f6f5"},u=s.map((f,p)=>{const g=n(f,p),m=new _(g.x,g.y,-1).normalize().applyQuaternion(ee.frameAt(t.keyframes,f).rotation);return{t:f,...p===0?{present:!0,sizeM:l,appearance:h}:{},azimuthDeg:ee.round((Math.atan2(m.x,-m.z)/xs+360)%360,3),altitudeDeg:ee.round(Math.asin(Math.min(1,Math.max(-1,m.y)))/xs,3),distanceM:o}}),d=s.length>1?s[s.length-1]-s[s.length-2]:40;return{...i??{id:e,explains:[e],model:{id:"sphere"}},track:[...u,{t:a+d,present:!1}]}}static round(t,e){return Math.round(t*10**e)/10**e}lensGhostFindings(t,e,i){const s=Pe.of(Ts.byId(e.instrument)).filter(l=>!Pe.scatters(l)).map(l=>l.scale),n=e.lens?.reachDeg??Pe.OFF_FRAME_REACH_DEG,a=l=>{const h=ee.sunTrack(t,l,n);if(!h)return;let u;for(const d of s){const f=ee.missOfTrack(t.samples,h.map(p=>({x:d*p.x,y:d*p.y})));(!u||f.medianDeg<u.miss.medianDeg)&&(u={miss:f,k:d})}return u},r=ee.bestSun(t,!0,a),o=[];if(r?o.push(this.finding(this.words.bestGhost,r.result.miss,t,{...this.sunWords(r.sun),k:this.number(r.result.k)},t.lightingGround,i)):o.push({text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:i}),t.lighting&&(!r||r.result.miss.medianDeg>t.sizeDeg)){const l=ee.bestSun(t,!1,a);l&&(!r||l.result.miss.medianDeg<r.result.miss.medianDeg-1e-6)&&o.push({text:this.fill(this.words.bestGhostNeeds,l.result.miss,t,{...this.sunWords(l.sun),k:this.number(l.result.k)}),outcome:"fails",against:t.lightingGround,path:"lighting"})}return o}statedGhostFindings(t,e,i){const s=e.lens?.reachDeg??Pe.OFF_FRAME_REACH_DEG,n=o=>{const l=ee.sunTrack(t,o,s);if(!l)return;const h=ee.linearFit(l,t.samples.map(d=>d.at)),u=l.map(d=>({x:h.k*d.x+h.offset.x,y:h.k*d.y+h.offset.y}));return{miss:ee.missOfTrack(t.samples,u),...h}},a=ee.bestSun(t,!0,n);if(!a)return[{text:this.words.bestNoGhost,outcome:"fails",against:t.lightingGround,path:i}];const r=Math.atan(Math.hypot(a.result.offset.x,a.result.offset.y))/xs;return[this.finding(this.words.bestStatedGhost,a.result.miss,t,{...this.sunWords(a.sun),k:this.number(a.result.k),offset:this.number(r)},t.lightingGround,i)]}finding(t,e,i,s,n,a){return{text:this.fill(t,e,i,s),outcome:e.medianDeg<=i.sizeDeg?"holds":"fails",against:n,path:a}}fill(t,e,i,s){const n={median:this.number(e.medianDeg),max:this.number(e.maxDeg),size:this.number(i.sizeDeg),travel:this.number(i.travelDeg),...s};return t.replace(/\{(\w+)\}/g,(a,r)=>r in n?String(n[r]):a)}sunWords(t){return{bearing:Math.round(t.bearing),altitude:this.number(t.altitudeDeg)}}number(t){const e=Math.abs(t)<1?2:1;return t.toFixed(e).replace(".",this.words.decimal)}static settingOf(t,e){const{recording:i,provenance:s}=Ls.strip(t),n=i.observerTrack?.keyframes??[];if(n.length===0)return;const a=Ts.aspectOf(Ts.byId(i.instrument)),r=[],o=[];for(const d of i.timeline?.keyframes??[])for(const f of d.shapes??[]){const p=f.shape;if(f.sourceId!==e||!p.aim)continue;const g=ee.frameAt(n,d.t),m=ee.direction(p.aim.azimuthDeg,p.aim.altitudeDeg).applyQuaternion(g.inverse);m.z>=0||(r.push({t:d.t,at:{x:m.x/-m.z,y:m.y/-m.z},frame:g}),p.angular?.widthDeg&&o.push(p.angular.widthDeg))}if(r.length===0)return;o.sort((d,f)=>d-f);let l=0;for(const d of r)for(const f of r)l=Math.max(l,ee.angleDeg(d.at,f.at));const h=n[0].pose,u=h.lat??0;return{samples:r,keyframes:n,sizeDeg:o.length>0?o[Math.floor(o.length/2)]:.5,travelDeg:l,aspect:a,headingDeg:h.headingDeg??0,lighting:i.lighting,lightingGround:Ls.free(s.at("lighting"))?"supposed":"established",altitudes:{minDeg:-Math.acos(6371e3/(6371e3+Math.max(h.elevationM??0,0)))/xs,maxDeg:ee.highestSun(i.time,s.at("time")?.range,u,h.lng??0)}}}static highestSun(t,e,i,s){const[n,a]=(typeof e=="string"?e:t??"").split("/"),r=n?jn(n):void 0,o=a?jn(a):r;if(!r||!o)return 90;const l=kn.earliestOf(r),h=kn.latestOf(o),u=864e5;let d=-90;for(let f=Math.floor(l/u)*u;f<=h;f+=u){const p=f+(12-s/15)*36e5;for(let g=-60;g<=60;g+=10)d=Math.max(d,Wo("Sun",new Date(p+g*6e4),{lat:i,lng:s,elevationM:0}).altitudeDeg)}return d}static frameAt(t,e){const i=t.findIndex(u=>u.t>e),s=t[i<=0?i===0?0:t.length-1:i-1],n=i<=0?s:t[i],a=n.t>s.t?(e-s.t)/(n.t-s.t):0,r=(u,d,f)=>(u??f)+((d??u??f)-(u??f))*a,o=(((n.pose.headingDeg??0)-(s.pose.headingDeg??0))%360+540)%360-180,l=(s.pose.headingDeg??0)+o*a,h=new Fs().setFromEuler(new Ma(r(s.pose.pitchDeg,n.pose.pitchDeg,0)*xs,-l*xs,r(s.pose.rollDeg,n.pose.rollDeg,0)*xs,"YXZ"));return{rotation:h,inverse:h.clone().invert(),fovDeg:r(s.pose.fovDeg,n.pose.fovDeg,50)}}static direction(t,e){const i=t*xs,s=e*xs;return new _(Math.sin(i)*Math.cos(s),Math.sin(s),-Math.cos(i)*Math.cos(s))}static angleDeg(t,e){const i=(t.x*e.x+t.y*e.y+1)/Math.sqrt((t.x*t.x+t.y*t.y+1)*(e.x*e.x+e.y*e.y+1));return Math.acos(Math.min(1,Math.max(-1,i)))/xs}static missOf(t,e){return ee.missOfTrack(t,t.map(()=>e))}static missOfTrack(t,e){const i=t.map((s,n)=>e[n]?ee.angleDeg(s.at,e[n]):180).sort((s,n)=>s-n);return{medianDeg:i[Math.floor(i.length/2)],maxDeg:i[i.length-1]}}static fixedPoint(t){let e={x:t.reduce((i,s)=>i+s.at.x,0)/t.length,y:t.reduce((i,s)=>i+s.at.y,0)/t.length};for(let i=0;i<100;i++){let s=0,n=0,a=0;for(const r of t){const o=1/Math.max(Math.hypot(r.at.x-e.x,r.at.y-e.y),1e-9);s+=r.at.x*o,n+=r.at.y*o,a+=o}e={x:s/a,y:n/a}}return e}static oneWay(t){let e;for(let i=0;i<360;i+=5){const s={x:Math.sin(i*xs),y:Math.cos(i*xs)},n={x:s.y,y:-s.x},a=t.map(d=>d.at.x*s.x+d.at.y*s.y),r=t.map(d=>d.at.x*n.x+d.at.y*n.y).sort((d,f)=>d-f),o=r[Math.floor(r.length/2)],h=ee.neverBack(a).map(d=>({x:d*s.x+o*n.x,y:d*s.y+o*n.y})),u=ee.missOfTrack(t,h);(!e||u.medianDeg<e.miss.medianDeg||u.medianDeg===e.miss.medianDeg&&u.maxDeg<e.miss.maxDeg)&&(e={miss:u,directionDeg:i,track:h})}return e}static neverBack(t){const e=[];for(const i of t)for(e.push({sum:i,count:1});e.length>1&&e[e.length-2].sum/e[e.length-2].count>e[e.length-1].sum/e[e.length-1].count;){const s=e.pop();e[e.length-1].sum+=s.sum,e[e.length-1].count+=s.count}return e.flatMap(i=>new Array(i.count).fill(i.sum/i.count))}static sunTrack(t,e,i){const s=ee.direction(t.headingDeg+e.bearing,e.altitudeDeg),n=[];for(const a of t.samples){const r=s.clone().applyQuaternion(a.frame.inverse),o=Math.acos(Math.min(1,Math.max(-1,-r.z)))/xs,l=Math.tan(a.frame.fovDeg/2*xs),h=Math.atan(l*Math.hypot(1,t.aspect))/xs;if(r.z>=0||o>=h+i)return;n.push({x:r.x/-r.z,y:r.y/-r.z})}return n}static linearFit(t,e){const i=t.length,s=h=>({x:h.reduce((u,d)=>u+d.x,0)/i,y:h.reduce((u,d)=>u+d.y,0)/i}),n=s(t),a=s(e);let r=0,o=0;for(let h=0;h<i;h++)r+=(t[h].x-n.x)*(e[h].x-a.x)+(t[h].y-n.y)*(e[h].y-a.y),o+=(t[h].x-n.x)**2+(t[h].y-n.y)**2;const l=o>1e-12?r/o:0;return{k:l,offset:{x:a.x-l*n.x,y:a.y-l*n.y}}}static bestSun(t,e,i){const s=h=>h.altitudeDeg>=t.altitudes.minDeg&&h.altitudeDeg<=t.altitudes.maxDeg&&(!e||!t.lighting||ee.lights(t.lighting,h));let n;const a=h=>{if(!s(h))return;const u=i(h);u&&(!n||u.miss.medianDeg<n.result.miss.medianDeg)&&(n={sun:h,result:u})},{minDeg:r,maxDeg:o}=t.altitudes;for(let h=0;h<360;h+=ee.COARSE_DEG){for(let u=r;u<=o;u+=ee.COARSE_DEG/2)a({bearing:h,altitudeDeg:u});a({bearing:h,altitudeDeg:o})}if(!n)return;const l=n.sun;for(let h=-2;h<=ee.COARSE_DEG;h+=ee.FINE_DEG)for(let u=-2;u<=ee.COARSE_DEG;u+=ee.FINE_DEG)a({bearing:((l.bearing+h)%360+360)%360,altitudeDeg:l.altitudeDeg+u});return n}static lights(t,e){const i=t.sunFromViewDeg,s=i?((e.bearing-i.fromDeg)%360+360)%360:0,n=i?((i.toDeg-i.fromDeg)%360+360)%360:360,a=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return s<=n&&a}}const rI=[{path:"place.locations.0.lat",what:"latitude"},{path:"place.locations.0.lng",what:"longitude"}];class cs{constructor(t){this.words=t,this.bestCases=new ee(t)}bestCases;found=new WeakMap;findingsOf(t,e){const i=Ls.strip(t),s=Ls.strip(e).recording,n=[],a=this.timeFinding(i.recording.time,i.provenance.at("time"),s.time);a&&n.push(a);for(const{path:o,what:l}of rI){const h=this.numberFinding(cs.at(i.recording,o),i.provenance.at(o),cs.at(s,o),this.words[l]);h&&n.push({...h,path:o})}const r=i.recording.lighting;if(r&&cs.movesTheSun(i.recording,s)){const o=this.lightingFinding(r,i.provenance.at("lighting"),s);o&&n.push(o)}return n.push(...this.bestCasesOf(t,e)),n}bestCasesOf(t,e){const i=JSON.stringify([e.interpretation?.mechanism,e.lens,e.instrument]),s=this.found.get(e);if(s&&s.account===t&&s.key===i)return s.findings;const n=this.bestCases.findingsOf(t,e);return this.found.set(e,{account:t,key:i,findings:n}),n}static withinInterval(t,e){const[i,s]=e.split("/"),n=i?jn(i):void 0,a=s?jn(s):void 0;if(!(!n&&!a))return!(n&&t.getTime()<kn.earliestOf(n)||a&&t.getTime()>kn.latestOf(a))}timeFinding(t,e,i){if(t===void 0||i===void 0||t===i)return;const s=jn(i),n=s?xr(s,0,0):void 0;if(typeof e?.range=="string"&&n){const a=cs.withinInterval(n,e.range);if(a===void 0)return;const r=a?this.words.timeWithin:this.words.timeOutside;return{text:cs.fill(r,{time:i,range:e.range}),outcome:a?"holds":"fails",against:"established",path:"time"}}if(!Ls.free(e))return{text:cs.fill(this.words.timeChanged,{from:t,time:i}),outcome:"fails",against:"established",path:"time"}}numberFinding(t,e,i,s){if(!(typeof t!="number"||typeof i!="number"||Math.abs(t-i)<1e-9)){if(Array.isArray(e?.range)){const[n,a]=e.range,r=i>=n&&i<=a;return{text:cs.fill(r?this.words.valueWithin:this.words.valueOutside,{what:s,value:i,min:n,max:a}),outcome:r?"holds":"fails",against:"established"}}if(!Ls.free(e))return{text:cs.fill(this.words.valueChanged,{what:s,from:t,value:i}),outcome:"fails",against:"established"}}}static movesTheSun(t,e){const i=a=>a.observerTrack?.keyframes?.[0]?.pose,s=i(t),n=i(e);return t.time!==e.time||t.utcOffsetHours!==e.utcOffsetHours||JSON.stringify(t.place)!==JSON.stringify(e.place)||s?.lat!==n?.lat||s?.lng!==n?.lng||s?.headingDeg!==n?.headingDeg}lightingFinding(t,e,i){const s=i.time?jn(i.time):void 0,n=s?cs.sunOf(s,i):void 0;if(!n)return;const{bearing:a}=n,{fromDeg:r,toDeg:o}=t.sunFromViewDeg??{fromDeg:0,toDeg:360},{minDeg:l,maxDeg:h}=t.sunAltitudeDeg??{minDeg:-90,maxDeg:90},u=cs.lights(t,n),d=Ls.free(e)?"supposed":"established",f=p=>Math.round(p);return{text:cs.fill(u?this.words.lightingHolds:this.words.lightingFails,{bearing:f(a),altitude:f(n.altitudeDeg),from:r,to:o,altitudes:t.sunAltitudeDeg?cs.fill(this.words.altitudes,{min:l,max:h}):""}),outcome:u?"holds":"fails",against:d,path:"lighting",...e?.rationale?{rationale:e.rationale}:{}}}static standOf(t){const e=Ls.strip(t).recording,i=e.observerTrack?.keyframes?.[0]?.pose,s=e.place?.locations?.[0],n=i?.lat??s?.lat,a=i?.lng??s?.lng;if(!(n===void 0||a===void 0||i?.headingDeg===void 0))return{lat:n,lng:a,elevationM:i.elevationM??0,headingDeg:i.headingDeg,utcOffsetHours:e.utcOffsetHours}}static sunOf(t,e){const i=cs.standOf(e);return i?cs.sunFrom(t,i):void 0}static sunFrom(t,e){if(t.hour===void 0)return;const i=xr(t,e.lng,e.utcOffsetHours);if(!i)return;const s=Wo("Sun",i,e);return{bearing:((s.azimuthDeg-e.headingDeg)%360+360)%360,altitudeDeg:s.altitudeDeg}}static lights(t,e){const i=t.sunFromViewDeg?cs.onArc(e.bearing,t.sunFromViewDeg.fromDeg,t.sunFromViewDeg.toDeg):!0,s=!t.sunAltitudeDeg||e.altitudeDeg>=t.sunAltitudeDeg.minDeg&&e.altitudeDeg<=t.sunAltitudeDeg.maxDeg;return i&&s}static nearestLit(t,e,i){const s=u=>({...e,hour:Math.floor(u/60),minute:u%60,second:void 0,raw:void 0}),n=cs.standOf(i);if(!n)return;const a=u=>{const d=cs.sunFrom(s(u),n);return d!==void 0&&cs.lights(t,d)};if(e.hour===void 0)return;const r=e.hour*60+(e.minute??0);if(a(r))return e;const o=5;let l;for(let u=0;u<1440;u+=o)a(u)&&(l===void 0||Math.abs(u-r)<Math.abs(l-r))&&(l=u);if(l===void 0)return;const h=r<l?-1:1;for(;l+h>=0&&l+h<1440&&a(l+h)&&Math.abs(l+h-r)<Math.abs(l-r);)l+=h;return s(l)}static onArc(t,e,i){const s=((i-e)%360+360)%360;return((t-e)%360+360)%360<=s}static at(t,e){return e.split(".").reduce((i,s)=>i?.[s],t)}static fill(t,e){return t.replace(/\{(\w+)\}/g,(i,s)=>s in e?String(e[s]):i)}}const eL=fc.catalog({en:()=>Ht(()=>import("./ReadingCheckTexts_en-eq6teExJ.js"),[],import.meta.url).then(c=>c.readingCheckTexts_en),fr:()=>Ht(()=>import("./ReadingCheckTexts_fr-pcDleIvY.js"),[],import.meta.url).then(c=>c.readingCheckTexts_fr),es:()=>Ht(()=>import("./ReadingCheckTexts_es-CR_JJZMV.js"),[],import.meta.url).then(c=>c.readingCheckTexts_es),it:()=>Ht(()=>import("./ReadingCheckTexts_it-MFKeoXnq.js"),[],import.meta.url).then(c=>c.readingCheckTexts_it)});class iL{static of(t){if(!(!t||t.length===0))return t.some(e=>e.outcome==="fails"&&e.against!=="supposed")?"incompatible":t.some(e=>e.outcome!=="holds")?"unsettled":"compatible"}}class nn{constructor(t,e,i,s="en"){this.parts=t,this.messages=e,this.onChange=i,this.locale=s,e&&this.setMessages(e),t.text.addEventListener("input",()=>{this.readText(),this.showDeduction()}),t.picker.addEventListener("change",()=>this.writeFromPicker()),t.mode.addEventListener("click",()=>this.setPrecise(!this.precise)),t.text.addEventListener("blur",()=>this.validate()),t.text.addEventListener("focus",()=>this.showDeduction())}precise=!0;hint="";setBounds(t){this.bounds=t;const{picker:e}=this.parts;e.min=t?nn.pickerValueOf(t.min):"",e.max=t?nn.pickerValueOf(t.max):""}bounds;bounded(t){if(!this.bounds)return t;const e=kn.latestOf(t)<kn.earliestOf(this.bounds.min)?this.bounds.min:kn.earliestOf(t)>kn.earliestOf(this.bounds.max)?this.bounds.max:t;return this.bounds.adjust?.(e)??e}get isPrecise(){return this.precise}setMessages(t,e=this.locale){this.messages=t,this.locale=e,t.edtfPlaceholder!==void 0&&(this.parts.text.placeholder=t.edtfPlaceholder),this.parts.mode.title=t.edtfModeTitle,this.parts.mode.setAttribute("aria-label",t.edtfModeTitle),this.setPrecise(this.precise)}setPrecise(t){this.precise=t,this.parts.picker.hidden=!t,this.parts.text.hidden=t,this.parts.mode.textContent=(t?this.messages?.datePrecise:this.messages?.dateEdtf)??"",this.parts.mode.setAttribute("aria-pressed",String(!t)),this.parts.help&&(this.parts.help.hidden=t),this.showDeduction()}set(t){const{text:e,picker:i}=this.parts;e.value=t?al(t):"",i.type!=="date"&&(i.step=nn.stepFor(t)),i.value=i.type==="date"?nn.pickerDateOf(t):nn.pickerValueOf(t),e.setCustomValidity(""),e.classList.remove("invalid"),this.showDeduction()}static opensPrecise(...t){return t.every(e=>e===void 0||nn.isPickable(e)&&nn.qualifierOf(al(e))==="")}static opensPreciseDate(...t){return t.every(e=>e===void 0||nn.isFullDate(e)&&nn.qualifierOf(al(e))==="")}static isFullDate(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0}static pickerDateOf(t){if(!nn.isFullDate(t))return"";const e=(i,s=2)=>String(i).padStart(s,"0");return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}`}static isPickable(t){return!!t&&t.year!==void 0&&t.month!==void 0&&t.day!==void 0&&t.hour!==void 0&&t.minute!==void 0}static pickerValueOf(t){if(!nn.isPickable(t))return"";const e=(s,n=2)=>String(s).padStart(n,"0"),i=t.second?`:${e(t.second)}`:"";return`${e(t.year,4)}-${e(t.month)}-${e(t.day)}T${e(t.hour)}:${e(t.minute)}${i}`}static stepFor(t){return t?.second?"1":"60"}static qualifierOf(t){const e=/[?%]/.test(t),i=/[~%]/.test(t);return e&&i?"%":e?"?":i?"~":""}describe(t){return this.messages?nn.describeTime(t,this.messages,this.locale):""}static describeTime(t,e,i){const s=al(t),n=nn.qualifierOf(s),a=h=>String(h).padStart(2,"0"),r=[];if(t.season!==void 0){const h={spring:e.timeSeasonSpring,summer:e.timeSeasonSummer,autumn:e.timeSeasonAutumn,winter:e.timeSeasonWinter}[t.season];r.push(t.year!==void 0?`${h} ${t.year}`:h)}else if(t.year!==void 0){const h=t.day!==void 0?{...t.year>=1583?{weekday:"long"}:{},year:"numeric",month:"long",day:"numeric"}:t.month!==void 0?{year:"numeric",month:"long"}:{year:"numeric"},u=new Date(Date.UTC(t.year,(t.month??1)-1,t.day??1));r.push(new Intl.DateTimeFormat(i,{...h,timeZone:"UTC"}).format(u))}t.hour!==void 0&&r.push(`${a(t.hour)}:${a(t.minute??0)}${t.second!==void 0?`:${a(t.second)}`:""}`);const o=r.join(", "),l=n==="~"?e.timeQualifierApproximate:n==="?"?e.timeQualifierUncertain:n==="%"?e.timeQualifierBoth:"";return l?`${o} — ${l.toLowerCase()}`:o}setHint(t){this.hint=t,this.showDeduction()}showDeduction(){const{text:t}=this.parts,e=t.value.trim();if(this.precise||e===""){t.title=this.hint;return}const i=jn(e);t.title=i?`→ ${this.describe(i)}`:this.messages?.edtfInvalid??""}readText(){const t=this.parts.text.value.trim();if(t===""){this.clean(),this.onChange(void 0);return}const e=jn(t);if(!e)return;this.clean();const i=this.bounded(e);i!==e&&this.set(i),this.onChange(i)}clean(){this.parts.text.setCustomValidity(""),this.parts.text.classList.remove("invalid")}writeFromPicker(){const{picker:t,text:e}=this.parts;t.value===""&&t.validity.badInput||(e.value=t.value===""?"":t.value.replace(/\.\d+$/,""),this.readText())}validate(){const{text:t}=this.parts,e=t.value.trim();e===""||jn(e)||(t.setCustomValidity(this.messages?.edtfInvalid??""),t.classList.add("invalid"))}}const by="#ff2200",Sy="#00ff44",Do="#ffffff",bd="#ffa500",Hc="#ff0000",oI="#2244ff",Pg=[{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:by,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:17,y:0,z:0},color:Sy,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-18},color:Do,pattern:{kind:"steady"}},{id:"beacon-top",offsetM:{x:0,y:2,z:0},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"beacon-bottom",offsetM:{x:0,y:-2,z:0},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.18}},{id:"strobe-port",offsetM:{x:-17,y:0,z:-1},color:Do,intensity:20,pattern:{kind:"flash",perMinute:60,dutyCycle:.01}},{id:"strobe-starboard",offsetM:{x:17,y:0,z:-1},color:Do,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:by,pattern:{kind:"steady"}},{id:"nav-starboard",offsetM:{x:5,y:0,z:0},color:Sy,pattern:{kind:"steady"}},{id:"nav-tail",offsetM:{x:0,y:1,z:-7},color:Do,pattern:{kind:"steady"}},{id:"beacon",offsetM:{x:0,y:2,z:-2},color:Hc,intensity:1.5,pattern:{kind:"flash",perMinute:45,dutyCycle:.2}},{id:"strobe",offsetM:{x:0,y:-1,z:0},color:Do,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:Do,intensity:2,pattern:{kind:"steady"}},{id:"head-right",offsetM:{x:.7,y:.6,z:2},color:Do,intensity:2,pattern:{kind:"steady"}},{id:"tail-left",offsetM:{x:-.7,y:.6,z:-2},color:Hc,pattern:{kind:"steady"}},{id:"tail-right",offsetM:{x:.7,y:.6,z:-2},color:Hc,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:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-front-right",offsetM:{x:.8,y:.6,z:2},color:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-left",offsetM:{x:-.8,y:.6,z:-2},color:bd,pattern:{kind:"flash",perMinute:90,dutyCycle:.5}},{id:"hazard-rear-right",offsetM:{x:.8,y:.6,z:-2},color:bd,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:oI,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1}},{id:"beacon-red",offsetM:{x:.4,y:1.6,z:0},color:Hc,intensity:2.5,pattern:{kind:"flash",perMinute:120,dutyCycle:.1,phase:.5}}]},{id:"traffic-signal",name:"Traffic light",kinds:["trafficlight"],create:()=>fe.vehicleLights(0)},{id:"pedestrian-signal",name:"Pedestrian light",kinds:["trafficlight"],create:()=>fe.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 Ff{static forKind(t){return Pg.filter(e=>e.kinds.includes(t))}static byId(t){return Pg.find(e=>e.id===t)}}class fe{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(t){const e=(t%180+180)%180;return e>=45&&e<135?1:0}static vehicleLights(t){const e=t*fe.CYCLE_S/2,i=fe.VEHICLE_HEAD_Y_M,s=fe.LENS_SPACING_M;return[fe.lamp("red",fe.RED,i+s,e+fe.GREEN_S+fe.AMBER_S,fe.CYCLE_S-fe.GREEN_S-fe.AMBER_S,fe.VEHICLE_INTENSITY),fe.lamp("amber",fe.AMBER,i,e+fe.GREEN_S,fe.AMBER_S,fe.VEHICLE_INTENSITY),fe.lamp("green",fe.GREEN,i-s,e,fe.GREEN_S,fe.VEHICLE_INTENSITY)]}static pedestrianLights(t){const e=t*fe.CYCLE_S/2+fe.GREEN_S+fe.AMBER_S+fe.PEDESTRIAN_DELAY_S,i=fe.PEDESTRIAN_HEAD_Y_M,s=fe.LENS_SPACING_M/2;return[fe.lamp("ped-red",fe.RED,i+s,e+fe.PEDESTRIAN_GREEN_S,fe.CYCLE_S-fe.PEDESTRIAN_GREEN_S,fe.PEDESTRIAN_INTENSITY),fe.lamp("ped-green",fe.GREEN,i-s,e,fe.PEDESTRIAN_GREEN_S,fe.PEDESTRIAN_INTENSITY)]}static isPedestrian(t){return t?.some(e=>e.id==="ped-green")??!1}static figureOf(t){return t.id==="ped-red"?"standing":t.id==="ped-green"?"walking":void 0}static lamp(t,e,i,s,n,a){const r=fe.CYCLE_S,o=Math.round(((1-s/r)%1+1)%1*1e6)/1e6;return{id:t,color:e,intensity:a,radiusM:fe.LENS_RADIUS_M,beamDeg:fe.BEAM_DEG,offsetM:{x:0,y:i,z:-.13},pattern:{kind:"flash",perMinute:60/r,dutyCycle:Math.round(n/r*1e6)/1e6,...o?{phase:o}:{}}}}}class qh{static of(t,e){const i=qh.drawnAsModel(t);return{color:e?.color??!i,lit:e?.lit??qh.litByDefault(t.kind,i),headlights:t.kind==="vehicle",lights:(e?.lights??!0)&&qh.rigsFor(t.kind,e).length>0,windows:!i&&wx(t.kind),floors:!i&&t.kind==="building",observerSide:Hl(t.kind)}}static rigsFor(t,e){return Ff.forKind(t).filter(i=>e?.lightRigs===void 0||e.lightRigs.includes(i.id))}static drawnAsModel(t){return mf(t)!==void 0&&!(t.observerSide!==void 0&&Hl(t.kind))}static litByDefault(t,e){return t==="streetlight"||t==="vehicle"&&!e}}class fi{static sideLabel(t){return fi.SIDE_LABELS[t]}static SIDE_LABELS={front:"front",behind:"behind",left:"left",right:"right","front-left":"frontLeft","front-right":"frontRight","behind-left":"behindLeft","behind-right":"behindRight"};static WINDOWS="windows";static BUILDING="building";static BRIDGE="bridge";static RAILING="railing";static WIRE="overheadLine";static together(t,e){return`${t} ${e}`}static of(t,e){const i=[],s=qh.drawnAsModel(t);if(!s&&t.kind==="building"&&i.push(...fi.floors(),...fi.walls(),...fi.roof()),!s&&wx(t.kind)&&i.push(...fi.windows(t.kind)),t.kind==="vehicle"&&i.push(...fi.engine()),t.kind==="observer"&&i.push(...fi.observerRecording()),t.kind==="aircraft"&&i.push(...fi.aircraftSound(e)),t.kind==="bridge"&&i.push(...fi.bridge()),t.kind==="wire"&&i.push(...fi.wire()),e?.parameters&&i.push(...e.parameters.map(n=>({...n,key:`modelParameters.${n.key}`}))),i.length!==0)return{kind:`decor-${t.kind}`,title:"properties",parameters:i}}static floors(){const t=e=>Ch.read(e,"floors")??gf;return[{type:"number",key:"floors",min:0,max:20,step:1,effective:()=>gf,label:"floors",hint:"upperStoriesAboveTheGround",group:fi.BUILDING},{type:"number",key:"occupiedFloor",min:0,max:20,step:1,effective:()=>0,bounds:e=>({max:t(e)}),label:"occupiedFloor",hint:"theFloorTheWitnessIs",group:fi.BUILDING}]}static walls(){const t="walls";return[{type:"colour",key:"facade.color",group:t,fallback:"#d3cab8",label:"wallColour",hint:"theColourOfTheWalls"},{type:"choice",key:"facade.openings",group:t,label:"facade",empty:"aHouseS",hint:"aHouseSAWindowEvery",choices:[{value:"tall",label:"oldBuilding"},{value:"lancet",label:"church"},{value:"plain",label:"bareWall"},{value:"none",label:"noFacade"}]}]}static roof(){const t="roof";return[{type:"choice",key:"roof.shape",group:t,label:"roof",empty:"flat",hint:"flatTheBoxTwoSlopes",choices:[{value:"flat",label:"flat"},{value:"gable",label:"twoSlopes"},{value:"hip",label:"fourSlopes"},{value:"dome",label:"dome"}]},{type:"number",key:"roof.riseM",min:0,max:15,step:.1,unit:"m",group:t,effective:()=>3,label:"rise",hint:"howFarTheRidgeStands",visibleWhen:i=>["gable","hip","dome"].includes(String(Ch.read(i,"roof.shape")))},{type:"choice",key:"roof.ridge",group:t,required:!1,label:"ridgeAlong",empty:"theWidth",choices:[{value:"width",label:"theWidth"},{value:"depth",label:"theDepth"}],visibleWhen:i=>Ch.read(i,"roof.shape")==="gable"},{type:"colour",key:"roof.color",group:t,fallback:"#7a5a4a",label:"roofColour"}]}static windows(t){return lS(t).map(e=>({type:"number",key:`windows.${e}`,step:5,unit:"%",min:uS(t,e)?0:hS,max:100,label:fi.SIDE_LABELS[e],summary:fi.together(fi.WINDOWS,fi.SIDE_LABELS[e]),hint:"opacityOfTheWindowOn",group:fi.WINDOWS}))}static engine(){const t="engineSound";return[{type:"choice",key:"engine.kind",group:t,label:"engine",hint:"whetherTheVehicleIsHeard",empty:"silentParked",choices:[{value:"car",label:"car"},{value:"van",label:"van"},{value:"truck",label:"truck"},{value:"motorcycle",label:"motorcycle"},{value:"generic",label:"unknown"}]},{type:"number",key:"engine.noise",min:.1,max:3,step:.1,group:t,effective:()=>1,label:"loudness",hint:"againstAnOrdinaryOneOf",visibleWhen:e=>Ch.read(e,"engine.kind")!==void 0||e.engine!==void 0}]}static observerRecording(){return[{type:"text",key:"sightingUrl",placeholder:"https://…/sighting.json",label:"theirOwnRecordingURL"}]}static aircraftSound(t){return[{type:"choice",key:"aircraftSound",group:"sound",label:"noiseInFlight",hint:"whatItSoundsLikeWhile",empty:t?.sound==="silent"?"silentAsTheModel":"asTheModel",choices:[{value:"airliner-narrow",label:"aircraftNarrowBodyAirliner"},{value:"airliner-wide",label:"aircraftWideBodyAirliner"},{value:"airliner-supersonic",label:"aircraftSupersonicAirliner"},{value:"regional-jet",label:"aircraftRegionalJet"},{value:"regional-turboprop",label:"aircraftTurboprop"},{value:"business-jet",label:"aircraftBusinessJet"},{value:"light-piston",label:"aircraftLightPistonAircraft"},{value:"piston-heavy",label:"aircraftHeavyPistonAircraft"},{value:"helicopter-light",label:"aircraftLightHelicopter"},{value:"helicopter-medium",label:"aircraftMediumHelicopter"},{value:"helicopter-heavy",label:"aircraftHeavyHelicopter"},{value:"military-jet",label:"aircraftMilitaryJet"},{value:"ultralight",label:"aircraftUltralight"},{value:"unmanned",label:"aircraftDrone"},{value:"glider",label:"aircraftGlider"},{value:"silent",label:"aircraftSilent"}]}]}static bridge(){const t=(e,i,s,n,a,r,o,l,h)=>({type:"number",key:e,label:i,min:s,max:n,step:a,unit:r,group:l,hint:h,effective:o===void 0?void 0:()=>o});return[t("bridge.spanM","span",.1,5e3,.1,"m",void 0,fi.BRIDGE,"metresOfOpenSpanUnder"),t("bridge.deckThicknessM","deckThickness",.1,20,.1,"m",1.2,fi.BRIDGE),t("bridge.railing.heightM","height",.1,5,.05,"m",1.05,fi.RAILING),t("bridge.railing.postSpacingM","postSpacing",.2,20,.1,"m",1.5,fi.RAILING),t("bridge.railing.rails","rails",0,8,1,"",2,fi.RAILING)]}static wire(){return[{type:"choice",key:"wire.poles",group:fi.WIRE,label:"poles",hint:"whichEndsStandOnA",choices:[{value:"both",label:"both"},{value:"start",label:"start"},{value:"end",label:"end"},{value:"none",label:"noPoles"}],effective:()=>"both"},{type:"number",key:"wire.diameterM",min:.001,max:.2,step:.001,unit:"m",effective:()=>.008,group:fi.WIRE,label:"strandThickness"},{type:"number",key:"wire.poleHeightM",min:.5,max:100,step:.1,unit:"m",group:fi.WIRE,label:"poleHeight",hint:"emptyHalfAMetreOver"}]}}class ma{static NONE={id:"none",name:"No filter",opticalDensity:0};static SOLAR_VISUAL={id:"solar-visual",name:"Solar filter for the eye (OD 5)",opticalDensity:5,usableWith:["eye","binoculars","telescope"]};static SOLAR_PHOTO={id:"solar-photo",name:"Solar film for a camera (OD 3.8)",opticalDensity:3.8,usableWith:["camera","dslr","phone","telescope"]};static ALL=[ma.NONE,ma.SOLAR_VISUAL,ma.SOLAR_PHOTO];static usableWith(t,e){return!t.usableWith||t.usableWith.includes(e.category)}static byId(t){return ma.ALL.find(e=>e.id===t)??ma.NONE}static transmittance(t){return 10**-t.opticalDensity}static magnitudes(t){return 2.5*t.opticalDensity}}class cI{constructor(t){this.names=t}name(t){return this.names[t.toLowerCase()]??t}stored(t){const e=t.trim().toLowerCase();for(const[i,s]of Object.entries(this.names))if(s.toLowerCase()===e)return i;return t.trim()}}class il{constructor(t,e,i,s=new cI({}),n,a={}){this.labels=t,this.naming=e,this.said=i,this.tags=s,this.timeWords=n,this.decorParameterTexts=a}entriesFor(t,e,i={}){const s=[];return this.addSummary(s,t),this.addObservation(s,t),this.addObserver(s,t,e),this.addLocation(s,t,e,i.groundElevationM,i.roadGradeDeg??0),this.addDecor(s,t,e,i),i.phenomena===!0&&this.addPhenomena(s,t,e),this.addTemporal(s,t),this.addWeather(s,t,e),this.addSound(s,t,e),s}push(t,e,i,s,n,a="",r={}){n===void 0||n===""||t.push({group:e,field:i,label:s,value:String(n),unit:a,color:r.color,fromSource:r.fromSource===!0})}percent(t){return t===void 0?void 0:`${Math.round(t*100)} %`}rounded(t,e=0){return t===void 0?void 0:String(Number(t.toFixed(e)))}shows(t,e=0){return t!==void 0&&Number(t.toFixed(e))!==0}showsPercent(t){return this.shows(t===void 0?void 0:t*100)}percentShown(t){return this.showsPercent(t)?this.percent(t):void 0}roundedShown(t,e=0){return this.shows(t,e)?this.rounded(t,e):void 0}static DESCRIPTION_WORDS=3;addSummary(t,e){const i=this.said.read(e.event.description)?.trim();if(!i)return;const s=i.split(/\s+/),n=s.length>il.DESCRIPTION_WORDS?`${s.slice(0,il.DESCRIPTION_WORDS).join(" ")}…`:i;this.push(t,"summary","description",this.labels.summaryDescription,n),t[t.length-1].full=i}addObservation(t,e){const i=e.event.tags;this.push(t,"observation","tags",this.labels.tags,i&&i.length>0?i.map(s=>this.tags.name(s)).join(", "):void 0)}filterName(t){return t===ma.SOLAR_VISUAL?this.labels.filterSolarVisual:t===ma.SOLAR_PHOTO?this.labels.filterSolarPhoto:t.name}addObserver(t,e,i){const s=e.observer;this.push(t,"observer","observerId",this.labels.observerId,s?.id),this.push(t,"observer","observerTitle",this.labels.observerTitle,this.said.read(s?.title)),this.push(t,"observer","observerLastName",this.labels.observerLastName,s?.lastName);const n=s?.firstNames;this.push(t,"observer","observerFirstNames",this.labels.observerFirstNames,n&&n.length>0?n.join(", "):void 0);const a=e.instrument;this.push(t,"observer","instrument",this.labels.instrument,this.naming.instrument(a));const r=e.exposure;this.push(t,"observer","exposureSeconds",this.labels.exposure,r===void 0?void 0:r<1?`1/${Math.round(1/r)}`:this.rounded(r,2),"s");const o=Te(e,i);if(o){const l=Ts.focalLengthMmFor(a,o.fovDeg);l===void 0?this.push(t,"observer","focalLength",this.labels.fieldOfView,this.rounded(o.fovDeg,1),"°"):this.push(t,"observer","focalLength",this.labels.focalLength,this.rounded(l,1),"mm"),this.push(t,"observer","fNumber",this.labels.aperture,this.rounded(o.fNumber??a.fNumber,1)),this.push(t,"observer","focusDistance",this.labels.focusDistance,this.rounded(o.focusDistanceM,1),"m"),this.push(t,"observer","roll",this.labels.roll,this.roundedShown(o.rollDeg),"°");const h=ma.byId(o.filter);h!==ma.NONE&&this.push(t,"observer","filter",this.labels.filter,this.filterName(h))}}degreesMinutesSeconds(t,e,i){if(t===void 0||!Number.isFinite(t))return;const s=Math.round(Math.abs(t)*3600),n=Math.floor(s/3600),a=Math.floor(s%3600/60),r=s%60;return`${n}°${String(a).padStart(2,"0")}′${String(r).padStart(2,"0")}″ ${this.naming.point(t<0?i:e)}`}static WALK_KMH=7;static SPEED_SPAN_MS=1e3;static speedKmhAt(t,e){const i=il.SPEED_SPAN_MS/2,s=Math.max(0,e-i),n=Te(t,s),a=Te(t,s+2*i);if(n?.lat===void 0||n.lng===void 0||a?.lat===void 0||a.lng===void 0)return;const r=(a.lat-n.lat)*111320,o=(a.lng-n.lng)*111320*Math.cos(n.lat*Math.PI/180);return Math.hypot(r,o)/(2*i/1e3)*3.6}addLocation(t,e,i,s,n){const a=e.event.place?.[0];this.push(t,"location","placeName",this.labels.placeName,a?.name);const r=Te(e,i);if(!r)return;this.push(t,"location","lat",this.labels.latitude,this.degreesMinutesSeconds(r.lat,0,180)),this.push(t,"location","lng",this.labels.longitude,this.degreesMinutesSeconds(r.lng,90,270));const o=this.rounded(r.headingDeg);this.push(t,"location","heading",this.labels.heading,o,r.headingDeg===void 0?"°":`° (${this.naming.point(r.headingDeg)})`),this.push(t,"location","pitch",this.labels.pitch,r.pitchDeg===void 0?void 0:this.rounded(r.pitchDeg+n),"°");const l=il.speedKmhAt(e,i);l!==void 0&&l>il.WALK_KMH&&this.push(t,"location","speed",this.labels.speed,Math.round(l),"km/h"),s===void 0?this.push(t,"location","elevation",this.labels.heightAboveGround,this.roundedShown(r.elevationM),"m"):this.push(t,"location","elevation",this.labels.elevation,this.rounded(s+r.elevationM),"m")}addDecor(t,e,i,s){const n=e.decor.find(h=>h.id===s.decorId);if(!n){if(s.decorPicker===!0)for(const h of e.decor)this.push(t,"decor",`decor:${h.id}`,this.decorLabel(h),this.decorKindName(h.kind));return}this.push(t,"decor","decorBase.title",this.labels.decorTitle,this.said.read(n.title));const a=ga(n,i);this.push(t,"decor","decorBase.eastM",this.labels.decorEast,this.rounded(a.eastM,1),"m"),this.push(t,"decor","decorBase.northM",this.labels.decorNorth,this.rounded(a.northM,1),"m"),this.push(t,"decor","decorBase.altitudeM",this.labels.decorAltitude,this.roundedShown(a.altitudeM),"m"),this.push(t,"decor","decorBase.headingDeg",this.labels.decorHeading,this.rounded(a.headingDeg),"°"),n1(n,i)&&this.push(t,"decor","decorState.lit",this.labels.decorLit,"✓");const r=n.lights?.map(h=>h.id).join()??"",o=r===""?void 0:Pg.find(h=>h.create().map(u=>u.id).join()===r);this.push(t,"decor","decorState.lightRig",this.labels.decorLights,o&&this.naming.lightRig(o)),this.push(t,"decor","decorState.observerSide",this.labels.decorObserverSide,this.decorSideName(n.observerSide));const l=fi.of(n);for(const h of(l&&nS.resolve(l,this.decorParameterTexts))?.parameters??[]){const u=Ch.read(n,h.key);if(u==null)continue;const d=h.type==="choice"?this.said.read(h.choices.find(f=>f.value===u)?.label)??String(u):u;this.push(t,"decor",`decorParam.${h.key}`,this.said.read(h.summary??h.label)??h.key,typeof d=="boolean"?d?"✓":"":d,h.type==="number"?h.unit:void 0)}}timeText(t){return this.timeWords?nn.describeTime(t,this.timeWords.messages,this.timeWords.locale):al(t)}addTemporal(t,e){const i=e.event;this.push(t,"temporal","obs-time",this.labels.observationTime,i.time&&this.timeText(i.time)),this.push(t,"temporal","obs-end-time",this.labels.observationEndTime,i.endTime&&this.timeText(i.endTime));const s=gx(i);this.push(t,"temporal","durationSeconds",this.labels.duration,this.roundedShown(s&&s/1e3,1),"s"),this.push(t,"temporal","timeZone",this.labels.utcOffset,i.timeZone),this.push(t,"temporal","utcOffsetHours",this.labels.utcOffset,this.rounded(i.utcOffsetHours,1),"UTC±h")}addWeather(t,e,i){const s=tl(e,i),a={fromSource:e.weatherSource!==void 0},r=this.showsPercent(s.cloudCover)||this.showsPercent(s.lowerCloudCover)||this.showsPercent(s.highCloudCover);this.push(t,"weather","cloudCover",this.labels.cloudCover,this.percentShown(s.cloudCover),"",a),this.push(t,"weather","highCloudCover",this.labels.highCloudCover,this.percentShown(s.highCloudCover),"",a),this.push(t,"weather","iceCrystalAlignment",this.labels.iceCrystalAlignment,this.showsPercent(s.highCloudCover)?this.percent(s.iceCrystalAlignment):void 0),this.push(t,"weather","rareIceCrystals",this.labels.rareIceCrystals,this.showsPercent(s.highCloudCover)?this.percent(s.rareIceCrystals):void 0),this.push(t,"weather","cloudDarkness",this.labels.cloudDarkness,r?this.percent(s.cloudDarkness):void 0,"",a),this.push(t,"weather","cloudBase",this.labels.cloudBase,r?this.rounded(s.cloudBaseM):void 0,"m",a);const o=s.precipitationType!=="none"&&this.showsPercent(s.precipitationIntensity);this.push(t,"weather","precipitationType",this.labels.precipitationType,o?this.precipitationName(s.precipitationType):void 0,"",a),this.push(t,"weather","precipitationIntensity",this.labels.precipitationIntensity,o?this.percent(s.precipitationIntensity):void 0,"",a),this.push(t,"weather","windDirection",this.labels.windDirection,this.shows(s.windSpeed,2)?this.rounded(s.windDirectionDeg):void 0,"°",a),this.push(t,"weather","windSpeed",this.labels.windSpeed,this.roundedShown(s.windSpeed,2),"m/s",a),s.storm&&this.push(t,"weather","storm",this.labels.storm,"✓","",a)}addSound(t,e,i){const s=mx(e,i);s.kind!=="none"&&(this.push(t,"sound","soundKind",this.labels.soundKind,this.soundKindName(s.kind)),this.push(t,"sound","soundVolume",this.labels.soundVolume,this.percentShown(s.volume)),this.push(t,"sound","soundPitch",this.labels.soundPitch,this.roundedShown(s.pitchHz),"Hz"),this.push(t,"sound","soundSrc",this.labels.soundSrc,s.src))}addPhenomena(t,e,i){for(const s of e.timeline.sourceIds){const n=e.timeline.getInterpolatedShapeAt(i,s),a=n?.angular,r=a?`${this.rounded(a.widthDeg,2)} × ${this.rounded(a.heightDeg,2)}°`:void 0;this.push(t,"phenomenon",`shape:${s}`,this.said.read(n?.title)??s,r)}for(const s of e.interpretation?.bodies??[]){const n=s.track.find(r=>r.sizeM?.widthM!==void 0)?.sizeM?.widthM,a=s.model.id??s.model.url?.replace(/^.*\//,"");this.push(t,"phenomenon",`body:${s.id}`,this.said.read(s.title)??s.id,[a,n!==void 0?`${this.rounded(n,2)} m`:void 0].filter(Boolean).join(", "))}}decorLabel(t){return this.said.read(t.title)??this.decorKindName(t.kind)}decorKindName(t){switch(t){case"building":return this.labels.decorBuilding;case"tree":return this.labels.decorTree;case"shrub":return this.labels.decorShrub;case"bridge":return this.labels.decorBridge;case"wire":return this.labels.decorWire;case"crop":return this.labels.decorCrop;case"terrace":return this.labels.decorTerrace;case"mound":return this.labels.decorMound;case"wall":return this.labels.decorWall;case"streetlight":return this.labels.decorStreetlight;case"trafficlight":return this.labels.decorTrafficLight;case"peak":return this.labels.decorPeak;case"crossing":return this.labels.decorCrossing;case"roadsign":return this.labels.decorRoadSign;case"vehicle":return this.labels.decorVehicle;case"aircraft":return this.labels.decorAircraft;default:return this.labels.decorObserver}}decorSideName(t){switch(t){case"front":return this.labels.decorSideFront;case"behind":return this.labels.decorSideBehind;case"left":return this.labels.decorSideLeft;case"right":return this.labels.decorSideRight;case"front-left":return this.labels.decorSideFrontLeft;case"front-right":return this.labels.decorSideFrontRight;case"behind-left":return this.labels.decorSideBehindLeft;case"behind-right":return this.labels.decorSideBehindRight;default:return}}precipitationName(t){switch(t){case"rain":return this.labels.precipitationRain;case"snow":return this.labels.precipitationSnow;case"hail":return this.labels.precipitationHail;default:return this.labels.precipitationNone}}soundKindName(t){switch(t){case"hum":return this.labels.soundHum;case"whistle":return this.labels.soundWhistle;case"rumble":return this.labels.soundRumble;case"crackle":return this.labels.soundCrackle;default:return this.labels.soundNone}}}const lI="Global Meteor Network",hI="https://globalmeteornetwork.org/data/",uI="“Thunder” by Jerimee",dI="https://creativecommons.org/licenses/by/3.0/",fI="CC BY 3.0";class Hs{static fill(t,e){t.innerHTML="";const i=d=>t.appendChild(d),s=e.currentTerrainAttribution;s&&i(Hs.text(s));const n=e.currentRoadAttribution;n&&i(Hs.text(n));const a=e.currentWaterAttribution;a&&i(Hs.text(a));const r=e.currentRailwayAttribution;r&&i(Hs.text(r));const o=e.ufoElement.observerMapCredit;o&&!s?.includes(o)&&i(Hs.text(o));for(const d of e.decorModelCredits){const f=d.author?` — ${d.author}`:"",p=document.createElement("li");d.sourceUrl?p.append(Hs.link(d.sourceUrl,d.title),document.createTextNode(`${f} (${d.license})`)):p.textContent=`${d.title}${f} (${d.license})`,i(p)}for(const d of e.ufoElement.sighting.references){if(!d.credit)continue;const f=document.createElement("li");d.creditUrl?f.appendChild(Hs.link(d.creditUrl,d.credit)):f.textContent=d.credit,i(f)}if(e.ufoElement.sighting.traces.length>0){const d=new lu(Sr.preferencesFor(e)),f=new Set(e.ufoElement.sighting.traces.map(p=>d.read(p.source)).filter(p=>!!p));for(const p of f)i(Hs.text(p))}const l=e.satelliteState;if(l.status==="ready"&&l.credit){const d=document.createElement("li");d.appendChild(Hs.link(l.creditUrl??"",l.credit)),i(d)}if(e.fireballState.status==="ready"&&e.fireballState.records.length>0){const d=document.createElement("li");d.append(Hs.link(hI,lI),document.createTextNode(" (CC BY 4.0)")),i(d)}const h=e.aircraftState;if(h.status==="ready"&&h.shown>0){const d=document.createElement("li");if(d.appendChild(Hs.link(h.creditUrl,h.credit)),i(d),h.trailCredit){const f=document.createElement("li");f.appendChild(Hs.link(h.trailCredit.creditUrl,h.trailCredit.credit)),i(f)}}const u=Hs.text(`${uI} (`);u.append(Hs.link(dI,fI),document.createTextNode(")")),i(u)}static text(t){const e=document.createElement("li");return e.textContent=t,e}static link(t,e){const i=document.createElement("a");return i.href=t,i.target="_blank",i.rel="noopener",i.textContent=e,i}}const pI=rs.point("assessment").provide(rs.BUILT_IN,[{id:"coverage",name:"Coverage",credit:"UFO@home",creditUrl:"https://ufoathome.org",create:()=>({about:"observer",assess:async c=>{const{CoverageAssessor:t}=await Ht(async()=>{const{CoverageAssessor:e}=await import("./CoverageAssessor-JQCFe16i.js");return{CoverageAssessor:e}},__vite__mapDeps([8,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"hynek",name:"Hynek",credit:"J. Allen Hynek",creditUrl:"https://rr0.org/science/crypto/ufo/observation/classification/hynek/",create:()=>({about:"temporal",assess:async c=>{const{HynekAssessor:t}=await Ht(async()=>{const{HynekAssessor:e}=await import("./HynekAssessor-BV2nWUx8.js");return{HynekAssessor:e}},__vite__mapDeps([9,10,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"ballester-guasp",name:"Ballester-Guasp",credit:"V.-J. Ballester-Olmos & M. Guasp",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Ballester-Guasp.html",create:()=>({about:"observer",assess:async c=>{const{BallesterGuaspAssessor:t}=await Ht(async()=>{const{BallesterGuaspAssessor:e}=await import("./BallesterGuaspAssessor-BVygSN0R.js");return{BallesterGuaspAssessor:e}},__vite__mapDeps([11,12,2,10,8,1,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})},{id:"poher",name:"Poher",credit:"Claude Poher",creditUrl:"https://rr0.org/science/crypto/ufo/enquete/methode/Poher-Criteres.html",create:()=>({about:"shape",assess:async c=>{const{PoherAssessor:t}=await Ht(async()=>{const{PoherAssessor:e}=await import("./PoherAssessor-C8g5YvJi.js");return{PoherAssessor:e}},__vite__mapDeps([13,1,2,3,4,5,6,7]),import.meta.url);return new t().assess(c)}})}]);class hb{constructor(t){this.labels=t}async read(t){const e=[],i=new Set;for(const s of pI){let n;try{n=await s.create().assess(t)}catch{continue}for(const r of n.criteria)r.basis===void 0&&!r.unsupported&&i.add(r.id);const a=n.score===void 0?n.verdict===void 0?"":this.verdictName(s.id,n.verdict):`${Math.round(n.score*100)}%`;a!==""&&e.push({group:"assessment",field:s.id,label:this.labels.assessmentNames[s.id]??s.name,value:a,unit:"",fromSource:!1,about:s.create().about,...n.factors?{detail:hb.factorsText(n.factors)}:{}})}return{entries:e,unanswered:i}}static factorsText(t){const e={q:"Q",sigma:"Σ",pi:"Π"};return Object.entries(t).map(([i,s])=>`${e[i]??i} ${s.toFixed(2)}`).join(" × ")}verdictName(t,e){return this.labels.assessmentVerdicts[`${t}.${e}`]??e.toUpperCase()}}class gl{static HALF_SPAN_MS=2e3;static MIN_SPEED_MS=1;static at(t,e,i){const s=t.event.place?.[0],n=t.observerTrack;if(!s)return 0;const a=g=>{const m=n.getInterpolatedPoseAt(Math.max(0,g));if(!m||m.lat===void 0||m.lng===void 0)return;const v=re(m.lat,m.lng,s.lat,s.lng);return{eastM:v.x,northM:-v.z,heading:m.headingDeg,aboveM:m.elevationM??0,altitudeM:m.altitudeM}},r=a(e-gl.HALF_SPAN_MS),o=a(e+gl.HALF_SPAN_MS),l=a(e);if(!r||!o||!l)return 0;const h=Math.hypot(o.eastM-r.eastM,o.northM-r.northM),u=2*gl.HALF_SPAN_MS/1e3;if(h/u<gl.MIN_SPEED_MS)return 0;const d=o.altitudeM!==void 0&&r.altitudeM!==void 0?o.altitudeM-r.altitudeM:i.heightAt(o.eastM,o.northM)+o.aboveM-i.heightAt(r.eastM,r.northM)-r.aboveM,f=Math.atan2(d,h)*180/Math.PI;if(l.heading===void 0)return f;const p=Math.atan2(o.eastM-r.eastM,o.northM-r.northM)*180/Math.PI;return f*Math.max(0,Math.cos((l.heading-p)*Math.PI/180))}}const mI=.08,Ey=.15,Ay=2,gI=2e3;class _y{context;constructor(t){this.context=t}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(t){console.warn("VehicleAudio: Web Audio unavailable, vehicles stay silent:",t);return}}Un.isLive(this.context)&&Un.unlock(this.context),this.apply()}setLevel(t){this.level=t,this.master&&(this.master.gain.value=t)}setPaused(t){t!==this.paused&&(this.paused=t,this.apply())}setVoices(t){this.requested=t,this.apply()}dispose(){for(const t of[...this.voices.keys()])this.release(t);Un.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0}masterOf(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.level,this.master.connect(t.destination)),this.master}apply(){const t=this.context;if(!t)return;const e=this.paused?[]:this.requested.filter(s=>s.inside||s.distanceM<gI),i=new Set(e.map(s=>s.id));for(const s of[...this.voices.keys()])i.has(s)||this.release(s);for(const s of e){const n=this.voices.get(s.id)??this.build(t,s.id);this.retarget(t,n,s)}}build(t,e){const i=t.createGain();i.gain.value=0;const s=t.createBiquadFilter();s.type="lowpass",s.connect(i).connect(this.masterOf(t));const n=t.createOscillator();n.type="sawtooth";const a=t.createOscillator();a.type="sine";const r=t.createGain(),o=t.createBiquadFilter();o.type="lowpass",o.frequency.value=900,n.connect(o),a.connect(o),o.connect(r).connect(s);const l=()=>{const w=t.createBufferSource();return w.buffer=this.noise(t),w.loop=!0,w.loopStart=Math.random()*Ay*.5,w},h=l(),u=t.createBiquadFilter();u.type="bandpass",u.Q.value=4;const d=t.createGain();h.connect(u).connect(d).connect(s);const f=l(),p=t.createBiquadFilter();p.type="lowpass",p.frequency.value=600;const g=t.createGain();f.connect(p).connect(g).connect(s);const m=l(),v=t.createBiquadFilter();v.type="bandpass",v.frequency.value=1400,v.Q.value=.7;const M=t.createGain();m.connect(v).connect(M).connect(s);const x=[n,a,h,f,m];for(const w of x)w.start();const y={nodes:[i,s,r,o,u,d,p,g,v,M,...x],sources:x,firing:n,crank:a,knock:u,engineGain:r,knockGain:d,roadGain:g,windGain:M,cabin:s,output:i};return this.voices.set(e,y),y}retarget(t,e,{profile:i,state:s,noise:n,inside:a,windowsOpen:r,distanceM:o}){const l=t.currentTime,h=(M,x)=>M.setTargetAtTime(x,l,mI),u=s.rpm/60,d=u*i.cylinders/2,f=Math.min(1,s.rpm/i.shiftUpRpm),p=Math.min(1.5,s.speedMps/30);h(e.firing.frequency,d),h(e.crank.frequency,u),h(e.knock.frequency,d*3),h(e.engineGain.gain,i.engineGain*(.25+.75*s.load)*(.5+.5*f)*.3),h(e.knockGain.gain,i.roughness*(.2+.8*s.load)*.4),h(e.roadGain.gain,i.roadGain*p**1.5*.8);const g=!a||r;h(e.windGain.gain,p**2*(g?.5:.06));const m=a?r?3500:700:8e3/(1+o/60);h(e.cabin.frequency,m);const v=a?.5:Math.min(1,8/Math.max(o,1));h(e.output.gain,v*n)}release(t){const e=this.voices.get(t);if(!e)return;this.voices.delete(t);const i=this.context;i&&(e.output.gain.setTargetAtTime(0,i.currentTime,Ey/3),setTimeout(()=>{for(const s of e.sources)try{s.stop()}catch{}for(const s of e.nodes)s.disconnect()},Ey*1e3*3))}noise(t){if(this.noiseBuffer)return this.noiseBuffer;const e=t.createBuffer(1,t.sampleRate*Ay,t.sampleRate),i=e.getChannelData(0);for(let s=0;s<i.length;s++)i[s]=Math.random()*2-1;return this.noiseBuffer=e,e}}class Su{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(t){return Su.BY_KIND[t??"generic"]??Su.BY_KIND.generic}}class Os{static ROAD_KINDS=["car","van","truck","motorcycle","generic"];static OPEN_AIR=[0,0,0,0,0,0,0,0];static ROAD_CLOSED_DB=[10,14,18,22,25,28,30,32];static WINDOWS_OPEN_DB=[2,3,4,5,6,7,8,9];static FUSELAGE_DB=[14,18,23,28,32,36,38,40];static CANOPY_DB=[3,4,6,8,10,12,14,16];static CANOPIED=["glider","balloon","ultralight"];static isRoad(t){return Os.ROAD_KINDS.includes(t)}static roadOf(t){return t&&Os.isRoad(t.kind)?t.kind:void 0}static aircraftOf(t){return t&&!Os.isRoad(t.kind)?t.kind:void 0}static transmission(t){const e=Os.insulationDb(t),i=[3,4,5].map(s=>e[s]);return 10**(-(i.reduce((s,n)=>s+n,0)/i.length)/20)}static insulationDb(t){return t?t.windowsOpen===!0?Os.WINDOWS_OPEN_DB:Os.isRoad(t.kind)?Os.ROAD_CLOSED_DB:Os.CANOPIED.includes(t.kind)?Os.CANOPY_DB:Os.FUSELAGE_DB:Os.OPEN_AIR}}class $o{constructor(t,e){this.samples=t,this.startMs=e}static SAMPLE_MS=100;static STANDING_MPS=.3;static of(t,e,i,s){const n=$o.SAMPLE_MS,a=[];for(let l=i;l<=s+n/2;l+=n){const h=e(l-n/2),u=e(l+n/2);if(!h||!u)return;a.push(Math.hypot(u.eastM-h.eastM,u.northM-h.northM)/(n/1e3))}const r=[];let o=1;for(let l=0;l<a.length;l++){const h=a[l],u=(a[Math.min(l+1,a.length-1)]-a[Math.max(l-1,0)])/(2*n/1e3);if(h<$o.STANDING_MPS){o=1,r.push({speedMps:h,rpm:t.idleRpm,load:.1,gear:0});continue}const d=h*3.6,f=v=>d/t.kmhPer1000Rpm[v-1]*1e3;for(;o<t.kmhPer1000Rpm.length&&f(o)>t.shiftUpRpm;)o++;for(;o>1&&f(o)<t.shiftDownRpm;)o--;const p=Math.max(f(o),t.idleRpm*(1+.3*Math.min(1,h/3))),g=.15+.5*Math.min(1,(h/35)**2),m=u>.15?Math.min(1,g+u/2.5):u<-.3?.05:g;r.push({speedMps:h,rpm:p,load:m,gear:o})}return new $o(r,i)}at(t){const e=(t-this.startMs)/$o.SAMPLE_MS,i=Math.min(Math.max(Math.floor(e),0),this.samples.length-1),s=this.samples[i],n=this.samples[Math.min(i+1,this.samples.length-1)],a=Math.min(Math.max(e-i,0),1);return{speedMps:s.speedMps+(n.speedMps-s.speedMps)*a,rpm:s.rpm+(n.rpm-s.rpm)*a,load:s.load+(n.load-s.load)*a,gear:a<.5?s.gear:n.gear}}}class Uf{drives=new Map;at(t,e){const i=[],s=t.event.place?.[0],n=h=>{const u=t.observerTrack.getInterpolatedPoseAt(h),d=u?.lat??s?.lat,f=u?.lng??s?.lng;if(d===void 0||f===void 0||!s)return;const p=re(d,f,s.lat,s.lng);return{eastM:p.x,northM:-p.z}},a=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3),r=t.vehicle,o=Os.roadOf(r);if(r&&o){const h=Su.of(o),u=this.drive(`observer:${o}`,Uf.trackKey(t),()=>$o.of(h,n,0,a));u&&i.push({id:"observer",profile:h,state:u.at(e),noise:r.noise??1,inside:!0,windowsOpen:r.windowsOpen===!0,distanceM:0})}const l=n(e);for(const h of t.decor){if(!h.engine||!l)continue;const u=Su.of(h.engine.kind),d=m=>{const v=ga(h,m);return{eastM:v.eastM,northM:v.northM}},f=this.drive(`decor:${h.id}`,Uf.decorKey(h,a),()=>$o.of(u,d,0,a));if(!f)continue;const p=ga(h,e),g=Math.hypot(p.eastM-l.eastM,p.northM-l.northM,p.altitudeM);i.push({id:`decor:${h.id}`,profile:u,state:f.at(e),noise:h.engine.noise??1,inside:!1,windowsOpen:!0,distanceM:g})}return i}drive(t,e,i){const s=this.drives.get(t);if(s&&s.key===e)return s.drive;const n=i();return this.drives.set(t,{key:e,drive:n}),n}static trackKey(t){return t.observerTrack.allKeyframes.map(i=>`${i.t}:${i.pose.lat}:${i.pose.lng}`).join(";")}static decorKey(t,e){return`${e}|${t.eastM},${t.northM}|`+(t.track??[]).map(i=>`${i.t}:${i.eastM}:${i.northM}`).join(";")}}const Ty=864e5,Ry=4e4;function vI(c){const t=Math.floor(c.getTime()/Ty);return{elapsedMs:c.getTime()-t*Ty,shiftM:{x:Dy.unit(t,2654435761)*Ry,z:Dy.unit(t,2246822507)*Ry}}}class Dy{static unit(t,e){let i=Math.imul(t|0,e)^e;return i=Math.imul(i^i>>>15,739982445),i=Math.imul(i^i>>>12,695872825),i^=i>>>15,(i>>>0)/4294967295*2-1}}function Iy(c,t,e,i,s,n,a){const r=i?.lat!==void 0&&i.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?re(s.lat,s.lng,i.lat,i.lng):{x:0,z:0};if(a){const h=t.getInterpolatedWeatherAt(0)??e,u=n===void 0?void 0:h.cloudLayers?.find(p=>p.id===n),d=(u?.windDirectionDeg??h.windDirectionDeg)*Math.PI/180,f=(u?.windSpeed??h.windSpeed)*a.elapsedMs/1e3;r.x+=a.shiftM.x-Math.sin(d)*f,r.z+=a.shiftM.z+Math.cos(d)*f}const o=Math.max(0,c),l=[0,...t.allKeyframes.map(h=>h.t).filter(h=>h>0&&h<o),o];for(let h=1;h<l.length;h++){const u=l[h-1],d=l[h]-u;if(d===0)continue;const f=32;for(let p=0;p<=f;p++){const g=t.getInterpolatedWeatherAt(u+d*p/f)??e,m=n===void 0?void 0:g.cloudLayers?.find(y=>y.id===n),v=(m?.windDirectionDeg??g.windDirectionDeg)*Math.PI/180,M=p===0||p===f?1:p%2===0?2:4,x=(m?.windSpeed??g.windSpeed)*d/1e3/f/3*M;r.x-=Math.sin(v)*x,r.z+=Math.cos(v)*x}}return r}const MI="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==",yI=`
|
|
5727
5727
|
<div class="stage" id="stage">
|
|
5728
5728
|
<div class="frame" id="frame">
|
|
5729
5729
|
<canvas id="scene-canvas"></canvas>
|
|
@@ -7285,7 +7285,7 @@ float roadNoise(vec2 p) {
|
|
|
7285
7285
|
if (fromEdge < reach) discard;
|
|
7286
7286
|
}
|
|
7287
7287
|
#endif
|
|
7288
|
-
}`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let s=0;s<t.length-1;s++){const n=t[s],a=t[s+1],r=Math.hypot(a.x-n.x,a.z-n.z),o=Math.max(1,Math.ceil(r/this.stepM));for(let l=0;l<o;l++){const h=l/o;e.push({x:n.x+(a.x-n.x)*h,z:n.z+(a.z-n.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Ia{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,s)=>{const n=t[s].widthM/2+.3;for(let a=1;a<i.length;a++){const r=i[a-1].x,o=i[a-1].z,l=i[a].x-r,h=i[a].z-o,u={way:s,ax:r,az:o,dx:l,dz:h,length2:l*l+h*h,reach:n},d=Math.floor((Math.min(r,i[a].x)-n)/Ia.CELL_M),f=Math.floor((Math.max(r,i[a].x)+n)/Ia.CELL_M),p=Math.floor((Math.min(o,i[a].z)-n)/Ia.CELL_M),g=Math.floor((Math.max(o,i[a].z)+n)/Ia.CELL_M);for(let m=d;m<=f;m++)for(let v=p;v<=g;v++){const M=Ia.key(m,v),x=this.cells.get(M);x?x.push(u):this.cells.set(M,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const s=this.cells.get(Ia.key(Math.floor(t/Ia.CELL_M),Math.floor(e/Ia.CELL_M)));if(!s)return!1;for(const n of s){if(n.way===i)continue;const a=n.length2===0?0:Math.max(0,Math.min(1,((t-n.ax)*n.dx+(e-n.az)*n.dz)/n.length2));if(Math.hypot(t-(n.ax+n.dx*a),e-(n.az+n.dz*a))<n.reach)return!0}return!1}}class yi{constructor(t,e=[]){this.lamps=e;for(const i of t){const s=Math.hypot(i.halfAlongM,i.halfAcrossM),n=Math.floor((i.x-s)/yi.CELL_M),a=Math.floor((i.x+s)/yi.CELL_M),r=Math.floor((i.z-s)/yi.CELL_M),o=Math.floor((i.z+s)/yi.CELL_M);for(let l=n;l<=a;l++)for(let h=r;h<=o;h++){const u=yi.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,s){const n=[],a=[];for(const r of yi.SAMPLES_M){const o=t+i*r,l=e+s*r,h=this.wall(o,l,-s,i),u=this.wall(o,l,s,-i);h!==void 0&&n.push(h),u!==void 0&&a.push(u)}return{leftM:yi.agreed(n),rightM:yi.agreed(a)}}lampsAlong(t){const e=[];for(const i of this.lamps){let s;for(let n=1;n<t.length;n++){const a=t[n-1].x,r=t[n-1].z,o=t[n].x-a,l=t[n].z-r,h=o*o+l*l;if(h===0)continue;const u=((i.x-a)*o+(i.z-r)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-a)*-l+(i.z-r)*o)/d;(!s||Math.abs(f)<s.distance)&&(s={distance:Math.abs(f),lateral:f})}s&&s.distance<=yi.REACH_M&&e.push(s.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=yi.REACH_M+Math.max(...yi.SAMPLES_M.map(Math.abs)),i=t.map(n=>n.x),s=t.map(n=>n.z);for(let n=Math.floor((Math.min(...i)-e)/yi.CELL_M);n<=Math.floor((Math.max(...i)+e)/yi.CELL_M);n++)for(let a=Math.floor((Math.min(...s)-e)/yi.CELL_M);a<=Math.floor((Math.max(...s)+e)/yi.CELL_M);a++)if(this.cells.has(yi.key(n,a)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,s){let n;const a=new Set,r=yi.CELL_M/2;for(let o=0;o<=yi.REACH_M+r;o+=r){const l=this.cells.get(yi.key(Math.floor((t+i*o)/yi.CELL_M),Math.floor((e+s*o)/yi.CELL_M)));for(const h of l??[]){if(a.has(h))continue;a.add(h);const u=yi.hit(h,t,e,i,s);u!==void 0&&u<=yi.REACH_M&&(n===void 0||u<n)&&(n=u)}}return n!==void 0&&n>=yi.NEAREST_M?n:void 0}static hit(t,e,i,s,n){const a=e-t.x,r=i-t.z,o=[a*t.alongX+r*t.alongZ,-a*t.alongZ+r*t.alongX],l=[s*t.alongX+n*t.alongZ,-s*t.alongZ+n*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(o[f])>h[f])return;continue}const p=(-h[f]-o[f])/l[f],g=(h[f]-o[f])/l[f];u=Math.max(u,Math.min(p,g)),d=Math.min(d,Math.max(p,g))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const QI=fc.catalog({en:()=>Ht(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(c=>c.beamKindMessages_en),fr:()=>Ht(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(c=>c.beamKindMessages_fr),es:()=>Ht(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(c=>c.beamKindMessages_es),it:()=>Ht(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(c=>c.beamKindMessages_it)}),Fy={key:"beams",messages:QI,pickKind:"beam",simulation:()=>Ht(async()=>{const{BeamSystem:c}=await import("./BeamSystem-Yg5JRiCT.js");return{BeamSystem:c}},__vite__mapDeps([15,16,1,2,3,4,5,6,7]),import.meta.url).then(({BeamSystem:c})=>()=>new c),editor:()=>Ht(async()=>{const{BeamEditor:c}=await import("./BeamEditor-BvF4J204.js");return{BeamEditor:c}},__vite__mapDeps([17,1,2,16,18,19,20,3,4,5,6,7]),import.meta.url).then(({BeamEditor:c})=>(t,e,i)=>new c(t,e,i)),reachM:(c,t)=>le.beamReachFor(c,t),describe:(c,t,{texts:e,name:i,distance:s})=>({name:i,detail:e.detail.replace("{name}",i).replace("{wavelength}",String(c.wavelengthNm)).replace("{power}",c.powerW.toLocaleString()).replace("{distance}",s(t.distanceM??0))})},tP=fc.catalog({en:()=>Ht(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(c=>c.launchKindMessages_en),fr:()=>Ht(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(c=>c.launchKindMessages_fr),es:()=>Ht(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(c=>c.launchKindMessages_es),it:()=>Ht(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(c=>c.launchKindMessages_it)}),Uy={key:"launches",messages:tP,pickKind:"plume",simulation:()=>Ht(async()=>{const{LaunchSimulation:c}=await import("./LaunchSimulation-C9gbGzGM.js");return{LaunchSimulation:c}},__vite__mapDeps([21,22,1,2,3,4,5,6,7]),import.meta.url).then(({LaunchSimulation:c})=>()=>new c),editor:()=>Ht(async()=>{const{LaunchEditor:c}=await import("./LaunchEditor-X_zWEOTY.js");return{LaunchEditor:c}},__vite__mapDeps([23,1,2,18,22,19,20,3,4,5,6,7]),import.meta.url).then(({LaunchEditor:c})=>(t,e,i)=>new c(t,e,i)),describe:(c,t,{said:e,texts:i,distance:s})=>{const n=t.detail,a=e.read(c.title)||c.vehicle?.mission||i.name,r=n.release===void 0||n.release==="burn"?void 0:c.jets?.find((l,h)=>`jet:${l.id??h}`===n.release),o=n.release===void 0||n.release==="burn"?i.ascent:r?.kind==="vent"?i.vent:i.burn;return{name:a,detail:i.detail.replace("{name}",a).replace("{part}",o).replace("{distance}",s(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},eP=fc.catalog({en:()=>Ht(()=>import("./ReentryKindMessages_en-BGZgya17.js"),[],import.meta.url).then(c=>c.reentryKindMessages_en),fr:()=>Ht(()=>import("./ReentryKindMessages_fr-7mer-cdj.js"),[],import.meta.url).then(c=>c.reentryKindMessages_fr),es:()=>Ht(()=>import("./ReentryKindMessages_es--UxzPNfj.js"),[],import.meta.url).then(c=>c.reentryKindMessages_es),it:()=>Ht(()=>import("./ReentryKindMessages_it-BBVQXE1M.js"),[],import.meta.url).then(c=>c.reentryKindMessages_it)}),iP=fc.catalog({en:()=>Ht(()=>import("./ReentryTypeNames_en-CBu890Bd.js"),[],import.meta.url).then(c=>c.reentryTypeNames_en),fr:()=>Ht(()=>import("./ReentryTypeNames_fr-BXq89mrz.js"),[],import.meta.url).then(c=>c.reentryTypeNames_fr),es:()=>Ht(()=>import("./ReentryTypeNames_es-_LnketjJ.js"),[],import.meta.url).then(c=>c.reentryTypeNames_es),it:()=>Ht(()=>import("./ReentryTypeNames_it-Yfq-TDip.js"),[],import.meta.url).then(c=>c.reentryTypeNames_it)}),sP=c=>({load:t=>iP.load(t).then(e=>({name:e[c]}))}),Mh=(c,t,e,i)=>({id:c,name:c,credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>({key:c,nature:e,messages:sP(t),template:i})}),nP=rs.point("reentryTypes").provide(rs.BUILT_IN,[Mh("meteor","meteor","natural",{distanceKm:150,speedKmS:40,durationS:1,fromAltitudeKm:100,toAltitudeKm:85,fragments:[{id:"main",absoluteMagnitude:0,trainS:.3,sheds:[]}]}),Mh("fireball","fireball","natural",{distanceKm:150,speedKmS:30,durationS:3,fromAltitudeKm:100,toAltitudeKm:60,fragments:[{id:"main",absoluteMagnitude:-6}]}),Mh("satellite","satellite","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-3},{id:"piece-2",lagS:2,absoluteMagnitude:-1.5}]}),Mh("rocket-stage","rocketStage","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-4},{id:"piece-2",lagS:1.5,absoluteMagnitude:-2.5},{id:"piece-3",lagS:3,absoluteMagnitude:-1.5}]}),Mh("capsule","capsule","artificial",{distanceKm:300,speedKmS:7.5,durationS:40,fromAltitudeKm:80,toAltitudeKm:55,fragments:[{id:"main",absoluteMagnitude:-5,sheds:[]}]})]);class ha{static built=new WeakMap;static names=new Map;static namesLanguage;static all(){return nP.map(t=>{let e=ha.built.get(t);return e||ha.built.set(t,e=t.create()),e})}static of(t){return t===void 0?void 0:ha.all().find(e=>e.key===t)}static async load(t){const e=ha.all(),i=await Promise.all(e.map(s=>s.messages.load(t).then(n=>n.name,()=>s.key)));ha.names=new Map(e.map((s,n)=>[s.key,i[n]])),ha.namesLanguage=t}static nameOf(t){return ha.names.get(t)??t}static get language(){return ha.namesLanguage}}const zy={key:"reentries",messages:eP,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>Ht(async()=>{const{ReentrySimulation:c}=await import("./ReentrySimulation-BlgfVSxb.js");return{ReentrySimulation:c}},__vite__mapDeps([24,1,2,3,4,5,6,7]),import.meta.url).then(({ReentrySimulation:c})=>()=>new c),editor:()=>Ht(async()=>{const{ReentryEditor:c}=await import("./ReentryEditor-C7A3Kh3_.js");return{ReentryEditor:c}},__vite__mapDeps([25,1,2,18,3,4,19,20,26,5,6,7]),import.meta.url).then(({ReentryEditor:c})=>(t,e,i)=>new c(t,e,i)),describe:(c,t,{said:e,texts:i})=>{const s=t.detail,n=c.type!==void 0&&ha.language!==void 0?ha.nameOf(c.type):"",a=(c.title?e.read(c.title):"")||c.object?.name||n||i.name,r=s.view.head,o=6371,l=Math.sqrt(o**2+r.distanceKm**2+2*o*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-o;return{name:(s.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",a).replace("{mag}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(l).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},zg=rs.point("skyEvents").provide(rs.BUILT_IN,[{id:Uy.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Uy},{id:Fy.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Fy},{id:zy.key,name:"Re-entries",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>zy}]);class Rr{static built=new WeakMap;static of(t){let e=Rr.built.get(t);return e||(e=t.create(),Rr.built.set(t,e)),e}static eventsOf(t,e){const i=t?.[e.key];return Array.isArray(i)?i:[]}}const aP=18,rP=.55,oP=.5,cP=.4,lP=2,hP=`
|
|
7288
|
+
}`)},t.customProgramCacheKey=()=>i?"rr0-road-grain-verge":"rr0-road-grain"}resample(t){const e=[];for(let s=0;s<t.length-1;s++){const n=t[s],a=t[s+1],r=Math.hypot(a.x-n.x,a.z-n.z),o=Math.max(1,Math.ceil(r/this.stepM));for(let l=0;l<o;l++){const h=l/o;e.push({x:n.x+(a.x-n.x)*h,z:n.z+(a.z-n.z)*h})}}const i=t[t.length-1];return i&&e.push({x:i.x,z:i.z}),e}}class Ia{static CELL_M=40;cells=new Map;constructor(t,e){e.forEach((i,s)=>{const n=t[s].widthM/2+.3;for(let a=1;a<i.length;a++){const r=i[a-1].x,o=i[a-1].z,l=i[a].x-r,h=i[a].z-o,u={way:s,ax:r,az:o,dx:l,dz:h,length2:l*l+h*h,reach:n},d=Math.floor((Math.min(r,i[a].x)-n)/Ia.CELL_M),f=Math.floor((Math.max(r,i[a].x)+n)/Ia.CELL_M),p=Math.floor((Math.min(o,i[a].z)-n)/Ia.CELL_M),g=Math.floor((Math.max(o,i[a].z)+n)/Ia.CELL_M);for(let m=d;m<=f;m++)for(let v=p;v<=g;v++){const M=Ia.key(m,v),x=this.cells.get(M);x?x.push(u):this.cells.set(M,[u])}}})}static key(t,e){return(t+5e4)*100003+(e+5e4)}onAnotherCarriageway(t,e,i){const s=this.cells.get(Ia.key(Math.floor(t/Ia.CELL_M),Math.floor(e/Ia.CELL_M)));if(!s)return!1;for(const n of s){if(n.way===i)continue;const a=n.length2===0?0:Math.max(0,Math.min(1,((t-n.ax)*n.dx+(e-n.az)*n.dz)/n.length2));if(Math.hypot(t-(n.ax+n.dx*a),e-(n.az+n.dz*a))<n.reach)return!0}return!1}}class yi{constructor(t,e=[]){this.lamps=e;for(const i of t){const s=Math.hypot(i.halfAlongM,i.halfAcrossM),n=Math.floor((i.x-s)/yi.CELL_M),a=Math.floor((i.x+s)/yi.CELL_M),r=Math.floor((i.z-s)/yi.CELL_M),o=Math.floor((i.z+s)/yi.CELL_M);for(let l=n;l<=a;l++)for(let h=r;h<=o;h++){const u=yi.key(l,h),d=this.cells.get(u);d?d.push(i):this.cells.set(u,[i])}}}static REACH_M=16;static NEAREST_M=1;static SAMPLES_M=[-3,0,3];static CELL_M=32;cells=new Map;across(t,e,i,s){const n=[],a=[];for(const r of yi.SAMPLES_M){const o=t+i*r,l=e+s*r,h=this.wall(o,l,-s,i),u=this.wall(o,l,s,-i);h!==void 0&&n.push(h),u!==void 0&&a.push(u)}return{leftM:yi.agreed(n),rightM:yi.agreed(a)}}lampsAlong(t){const e=[];for(const i of this.lamps){let s;for(let n=1;n<t.length;n++){const a=t[n-1].x,r=t[n-1].z,o=t[n].x-a,l=t[n].z-r,h=o*o+l*l;if(h===0)continue;const u=((i.x-a)*o+(i.z-r)*l)/h;if(u<0||u>1)continue;const d=Math.sqrt(h),f=((i.x-a)*-l+(i.z-r)*o)/d;(!s||Math.abs(f)<s.distance)&&(s={distance:Math.abs(f),lateral:f})}s&&s.distance<=yi.REACH_M&&e.push(s.lateral)}return e}near(t){if(t.length===0)return!1;if(this.lampsAlong(t).length>0)return!0;const e=yi.REACH_M+Math.max(...yi.SAMPLES_M.map(Math.abs)),i=t.map(n=>n.x),s=t.map(n=>n.z);for(let n=Math.floor((Math.min(...i)-e)/yi.CELL_M);n<=Math.floor((Math.max(...i)+e)/yi.CELL_M);n++)for(let a=Math.floor((Math.min(...s)-e)/yi.CELL_M);a<=Math.floor((Math.max(...s)+e)/yi.CELL_M);a++)if(this.cells.has(yi.key(n,a)))return!0;return!1}static agreed(t){if(!(t.length<2))return t.sort((e,i)=>e-i),t[Math.floor((t.length-1)/2)]}wall(t,e,i,s){let n;const a=new Set,r=yi.CELL_M/2;for(let o=0;o<=yi.REACH_M+r;o+=r){const l=this.cells.get(yi.key(Math.floor((t+i*o)/yi.CELL_M),Math.floor((e+s*o)/yi.CELL_M)));for(const h of l??[]){if(a.has(h))continue;a.add(h);const u=yi.hit(h,t,e,i,s);u!==void 0&&u<=yi.REACH_M&&(n===void 0||u<n)&&(n=u)}}return n!==void 0&&n>=yi.NEAREST_M?n:void 0}static hit(t,e,i,s,n){const a=e-t.x,r=i-t.z,o=[a*t.alongX+r*t.alongZ,-a*t.alongZ+r*t.alongX],l=[s*t.alongX+n*t.alongZ,-s*t.alongZ+n*t.alongX],h=[t.halfAlongM,t.halfAcrossM];let u=-1/0,d=1/0;for(let f=0;f<2;f++){if(Math.abs(l[f])<1e-9){if(Math.abs(o[f])>h[f])return;continue}const p=(-h[f]-o[f])/l[f],g=(h[f]-o[f])/l[f];u=Math.max(u,Math.min(p,g)),d=Math.min(d,Math.max(p,g))}if(!(d<u||d<0||u<0))return u}static key(t,e){return(t+5e4)*100003+(e+5e4)}}const QI=fc.catalog({en:()=>Ht(()=>import("./BeamKindMessages_en-5RezNkyz.js"),[],import.meta.url).then(c=>c.beamKindMessages_en),fr:()=>Ht(()=>import("./BeamKindMessages_fr--28-36OI.js"),[],import.meta.url).then(c=>c.beamKindMessages_fr),es:()=>Ht(()=>import("./BeamKindMessages_es-B5vSWVjK.js"),[],import.meta.url).then(c=>c.beamKindMessages_es),it:()=>Ht(()=>import("./BeamKindMessages_it-X53Fuf2U.js"),[],import.meta.url).then(c=>c.beamKindMessages_it)}),Fy={key:"beams",messages:QI,pickKind:"beam",simulation:()=>Ht(async()=>{const{BeamSystem:c}=await import("./BeamSystem-B5u4ithz.js");return{BeamSystem:c}},__vite__mapDeps([15,16,1,2,3,4,5,6,7]),import.meta.url).then(({BeamSystem:c})=>()=>new c),editor:()=>Ht(async()=>{const{BeamEditor:c}=await import("./BeamEditor-eDeeNBE9.js");return{BeamEditor:c}},__vite__mapDeps([17,1,2,16,18,19,20,3,4,5,6,7]),import.meta.url).then(({BeamEditor:c})=>(t,e,i)=>new c(t,e,i)),reachM:(c,t)=>le.beamReachFor(c,t),describe:(c,t,{texts:e,name:i,distance:s})=>({name:i,detail:e.detail.replace("{name}",i).replace("{wavelength}",String(c.wavelengthNm)).replace("{power}",c.powerW.toLocaleString()).replace("{distance}",s(t.distanceM??0))})},tP=fc.catalog({en:()=>Ht(()=>import("./LaunchKindMessages_en-Batvnyw3.js"),[],import.meta.url).then(c=>c.launchKindMessages_en),fr:()=>Ht(()=>import("./LaunchKindMessages_fr-CoojboIk.js"),[],import.meta.url).then(c=>c.launchKindMessages_fr),es:()=>Ht(()=>import("./LaunchKindMessages_es-KYyQ9gbu.js"),[],import.meta.url).then(c=>c.launchKindMessages_es),it:()=>Ht(()=>import("./LaunchKindMessages_it-9HA3cjgP.js"),[],import.meta.url).then(c=>c.launchKindMessages_it)}),Uy={key:"launches",messages:tP,pickKind:"plume",simulation:()=>Ht(async()=>{const{LaunchSimulation:c}=await import("./LaunchSimulation-BIiU6D8P.js");return{LaunchSimulation:c}},__vite__mapDeps([21,22,1,2,3,4,5,6,7]),import.meta.url).then(({LaunchSimulation:c})=>()=>new c),editor:()=>Ht(async()=>{const{LaunchEditor:c}=await import("./LaunchEditor-ConcMLIe.js");return{LaunchEditor:c}},__vite__mapDeps([23,1,2,18,22,19,20,3,4,5,6,7]),import.meta.url).then(({LaunchEditor:c})=>(t,e,i)=>new c(t,e,i)),describe:(c,t,{said:e,texts:i,distance:s})=>{const n=t.detail,a=e.read(c.title)||c.vehicle?.mission||i.name,r=n.release===void 0||n.release==="burn"?void 0:c.jets?.find((l,h)=>`jet:${l.id??h}`===n.release),o=n.release===void 0||n.release==="burn"?i.ascent:r?.kind==="vent"?i.vent:i.burn;return{name:a,detail:i.detail.replace("{name}",a).replace("{part}",o).replace("{distance}",s(n.centre.distanceKm*1e3)).replace("{height}",Math.round(n.heightKm??0).toLocaleString())}}},eP=fc.catalog({en:()=>Ht(()=>import("./ReentryKindMessages_en-BGZgya17.js"),[],import.meta.url).then(c=>c.reentryKindMessages_en),fr:()=>Ht(()=>import("./ReentryKindMessages_fr-7mer-cdj.js"),[],import.meta.url).then(c=>c.reentryKindMessages_fr),es:()=>Ht(()=>import("./ReentryKindMessages_es--UxzPNfj.js"),[],import.meta.url).then(c=>c.reentryKindMessages_es),it:()=>Ht(()=>import("./ReentryKindMessages_it-BBVQXE1M.js"),[],import.meta.url).then(c=>c.reentryKindMessages_it)}),iP=fc.catalog({en:()=>Ht(()=>import("./ReentryTypeNames_en-CBu890Bd.js"),[],import.meta.url).then(c=>c.reentryTypeNames_en),fr:()=>Ht(()=>import("./ReentryTypeNames_fr-BXq89mrz.js"),[],import.meta.url).then(c=>c.reentryTypeNames_fr),es:()=>Ht(()=>import("./ReentryTypeNames_es-_LnketjJ.js"),[],import.meta.url).then(c=>c.reentryTypeNames_es),it:()=>Ht(()=>import("./ReentryTypeNames_it-Yfq-TDip.js"),[],import.meta.url).then(c=>c.reentryTypeNames_it)}),sP=c=>({load:t=>iP.load(t).then(e=>({name:e[c]}))}),Mh=(c,t,e,i)=>({id:c,name:c,credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>({key:c,nature:e,messages:sP(t),template:i})}),nP=rs.point("reentryTypes").provide(rs.BUILT_IN,[Mh("meteor","meteor","natural",{distanceKm:150,speedKmS:40,durationS:1,fromAltitudeKm:100,toAltitudeKm:85,fragments:[{id:"main",absoluteMagnitude:0,trainS:.3,sheds:[]}]}),Mh("fireball","fireball","natural",{distanceKm:150,speedKmS:30,durationS:3,fromAltitudeKm:100,toAltitudeKm:60,fragments:[{id:"main",absoluteMagnitude:-6}]}),Mh("satellite","satellite","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-3},{id:"piece-2",lagS:2,absoluteMagnitude:-1.5}]}),Mh("rocket-stage","rocketStage","artificial",{distanceKm:300,speedKmS:7.5,durationS:60,fromAltitudeKm:82,toAltitudeKm:72,fragments:[{id:"main",absoluteMagnitude:-4},{id:"piece-2",lagS:1.5,absoluteMagnitude:-2.5},{id:"piece-3",lagS:3,absoluteMagnitude:-1.5}]}),Mh("capsule","capsule","artificial",{distanceKm:300,speedKmS:7.5,durationS:40,fromAltitudeKm:80,toAltitudeKm:55,fragments:[{id:"main",absoluteMagnitude:-5,sheds:[]}]})]);class ha{static built=new WeakMap;static names=new Map;static namesLanguage;static all(){return nP.map(t=>{let e=ha.built.get(t);return e||ha.built.set(t,e=t.create()),e})}static of(t){return t===void 0?void 0:ha.all().find(e=>e.key===t)}static async load(t){const e=ha.all(),i=await Promise.all(e.map(s=>s.messages.load(t).then(n=>n.name,()=>s.key)));ha.names=new Map(e.map((s,n)=>[s.key,i[n]])),ha.namesLanguage=t}static nameOf(t){return ha.names.get(t)??t}static get language(){return ha.namesLanguage}}const zy={key:"reentries",messages:eP,pickKind:"reentry",pickedAfterSatellites:!0,simulation:()=>Ht(async()=>{const{ReentrySimulation:c}=await import("./ReentrySimulation-D_JX7wWS.js");return{ReentrySimulation:c}},__vite__mapDeps([24,1,2,3,4,5,6,7]),import.meta.url).then(({ReentrySimulation:c})=>()=>new c),editor:()=>Ht(async()=>{const{ReentryEditor:c}=await import("./ReentryEditor-CEbb0oLd.js");return{ReentryEditor:c}},__vite__mapDeps([25,1,2,18,3,4,19,20,26,5,6,7]),import.meta.url).then(({ReentryEditor:c})=>(t,e,i)=>new c(t,e,i)),describe:(c,t,{said:e,texts:i})=>{const s=t.detail,n=c.type!==void 0&&ha.language!==void 0?ha.nameOf(c.type):"",a=(c.title?e.read(c.title):"")||c.object?.name||n||i.name,r=s.view.head,o=6371,l=Math.sqrt(o**2+r.distanceKm**2+2*o*r.distanceKm*Math.sin(r.altitudeDeg*Math.PI/180))-o;return{name:(s.view.fragmentId.includes(".")?i.fragment:i.piece).replace("{name}",a).replace("{mag}",s.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(l).toLocaleString()).replace("{distance}",Math.round(r.distanceKm).toLocaleString())}}},zg=rs.point("skyEvents").provide(rs.BUILT_IN,[{id:Uy.key,name:"Launches",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Uy},{id:Fy.key,name:"Beams",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>Fy},{id:zy.key,name:"Re-entries",credit:"UFO@home",creditUrl:"https://ufoathome.org/docs/format/",create:()=>zy}]);class Rr{static built=new WeakMap;static of(t){let e=Rr.built.get(t);return e||(e=t.create(),Rr.built.set(t,e)),e}static eventsOf(t,e){const i=t?.[e.key];return Array.isArray(i)?i:[]}}const aP=18,rP=.55,oP=.5,cP=.4,lP=2,hP=`
|
|
7289
7289
|
attribute float aSpeed;
|
|
7290
7290
|
uniform float uTime;
|
|
7291
7291
|
uniform float uOverallSpeed;
|
|
@@ -8347,7 +8347,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
8347
8347
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
8348
8348
|
}
|
|
8349
8349
|
`,transparent:!0,depthWrite:!1,side:ds,fog:!1,blending:oc,blendSrc:cc,blendDst:pu})}static wallReflectance(t,e,i){const s=i(t,1,e);return 2*s/(1+s)}static DISCS={uDiscDirection:{value:[new _(0,1,0),new _(0,1,0)]},uDiscCosRadius:{value:[2,2]},uDiscRadiance:{value:[new _,new _]}};static DISC_INDEX={sun:0,moon:1};static setDisc(t,e){const i=qs.DISC_INDEX[t],s=qs.DISCS;if(!e){s.uDiscCosRadius.value[i]=2,s.uDiscRadiance.value[i].set(0,0,0);return}s.uDiscDirection.value[i].set(...e.direction).normalize(),s.uDiscCosRadius.value[i]=Math.cos(e.radiusRad),s.uDiscRadiance.value[i].set(...e.radiance)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return zt.respond(e*zt.relativeOfResponse(Math.max(t,1e-5)))}}class vn{static SIZE=64;static MOVE_M=.01;holder=new _i;cameras=[];faces=[];target=new Ke(vn.SIZE,vn.SIZE);white=new un({color:new at(1,1,1),side:ds});scene=new zn;cabin;meshes=0;eye=new _;scratch=new _;constructor(){const t=[[new _(1,0,0),new _(0,1,0)],[new _(-1,0,0),new _(0,1,0)],[new _(0,1,0),new _(0,0,1)],[new _(0,-1,0),new _(0,0,-1)],[new _(0,0,1),new _(0,1,0)],[new _(0,0,-1),new _(0,1,0)]];for(const[e,i]of t){const s=new Ns(90,1,.02,20);s.up.copy(i),s.lookAt(e),this.holder.add(s),this.cameras.push(s),this.faces.push(new Uint8Array(vn.SIZE*vn.SIZE*4))}this.scene.background=new at(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const s=this.scratch.copy(i);e.worldToLocal(s);let n=0;e.traverse(a=>{a.isMesh&&n++}),!(e===this.cabin&&n===this.meshes&&s.distanceTo(this.eye)<vn.MOVE_M)&&(this.cabin=e,this.meshes=n,this.eye.copy(s),this.draw(t,e))}hides(t){if(!this.cabin)return!1;this.holder.updateWorldMatrix(!0,!0);for(let e=0;e<6;e++){const i=this.cameras[e],s=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(s.z>=0)continue;const n=s.x/-s.z,a=s.y/-s.z;if(Math.abs(n)>1||Math.abs(a)>1)continue;const r=Math.min(vn.SIZE-1,Math.floor((n+1)/2*vn.SIZE)),o=Math.min(vn.SIZE-1,Math.floor((a+1)/2*vn.SIZE));return this.faces[e][(o*vn.SIZE+r)*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(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(a=>{const r=a;if(!r.isMesh||!r.visible||(Array.isArray(r.material)?r.material:[r.material]).every(h=>h instanceof qs))return;const l=new dt(r.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(r.matrixWorld),l.matrixWorld.copy(r.matrixWorld),i.push(l)});for(const a of i)this.scene.add(a);const s=t.getRenderTarget(),n=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let a=0;a<6;a++){const r=this.cameras[a];r.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,r),Kf.now(t,this.target,0,0,vn.SIZE,vn.SIZE,this.faces[a])}t.setRenderTarget(s),t.shadowMap.autoUpdate=n;for(const a of i)a.removeFromParent()}}const Cp="https://ufoathome.org/models/index.json";class su{attribution="3D models re-hosted by UFO@home, each under its own author's licence";fetchImpl;indexUrls;loading;static shared=new Map;sharing;constructor(t={}){this.sharing=!t.fetchImpl,this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??qP()}async entries(t){const e=await this.load();return t?e.filter(i=>[i.kind].flat().includes(t)):e}async entry(t){return(await this.load()).find(e=>e.id===t)}load(){if(this.loading)return this.loading;if(!this.sharing)return this.loading=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
8350
|
-
`);let e=su.shared.get(t);return e||(e=this.fetchFirstAvailable(),su.shared.set(t,e),e.then(i=>{i.length===0&&su.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,t).href})):void 0}catch{return}}}function qP(){const c=`?v=${encodeURIComponent("0.
|
|
8350
|
+
`);let e=su.shared.get(t);return e||(e=this.fetchFirstAvailable(),su.shared.set(t,e),e.then(i=>{i.length===0&&su.shared.delete(t)})),this.loading=e}async fetchFirstAvailable(){for(const t of this.indexUrls){const e=await this.fetchIndex(t);if(e)return e}return[]}async fetchIndex(t){try{const e=await this.fetchImpl(t);if(!e.ok)return;const i=await e.json();return Array.isArray(i?.models)?i.models.map(({file:s,...n})=>({...n,url:new URL(s,t).href})):void 0}catch{return}}}function qP(){const c=`?v=${encodeURIComponent("0.195.0")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==Cp?[t,Cp]:[Cp]).map(e=>e+c)}const ZP=rs.point("decorModels").provide(rs.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 su}]);class Ib{constructor(t,e=ZP){this.preferredId=t,this.sources=e}attribution="3D models, each under its own author's licence";built=new Map;catalogues(){const t=this.sources.find(i=>i.id===this.preferredId)??this.sources[0];return(t?[t,...this.sources.filter(i=>i!==t)]:[]).map(i=>{let s=this.built.get(i);return s||(s=i.create(),this.built.set(i,s)),s})}entries(t){const e=this.catalogues()[0];return e?e.entries(t):Promise.resolve([])}async entry(t){for(const e of this.catalogues()){const i=await e.entry(t).catch(()=>{});if(i)return i}}async moduleOf(t){const e=rs.point("decorModels");for(const i of this.sources){const s=e.ownerOf(i.id);if(!(s===void 0||s===rs.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return s}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function Op(c){const{GLTFLoader:t}=await Ht(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-DrBMau2Y.js");return{GLTFLoader:i}},__vite__mapDeps([27,1,2,3,4,5,6,7]),import.meta.url),e=new t;return new Promise((i,s)=>{e.load(c,n=>i(Object.assign(n.scene,{animations:n.animations})),void 0,n=>s(new Error(`Could not load 3D model ${c}: ${n instanceof Error?n.message:String(n)}`)))})}class On{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new dt(new tn(2,2),new _e({uniforms:{uColor:{value:new at(0,0,0)},uRadius:{value:1}},vertexShader:On.VERTEX,fragmentShader:On.FRAGMENT,transparent:!0,depthWrite:!1,blending:gs,toneMapped:!1})),this.mesh.name=t,this.mesh.frustumCulled=!1,this.mesh.renderOrder=e,this.mesh.visible=!1}shine(t,e,i){this.mesh.visible=!0,this.mesh.position.set(t.x,t.y,t.z),this.mesh.material.uniforms.uRadius.value=e,this.mesh.material.uniforms.uColor.value.setRGB(i[0],i[1],i[2])}hide(){this.mesh.visible=!1}dispose(){this.mesh.geometry.dispose(),this.mesh.material.dispose()}static spread(t,e,i,s){const n=Math.max(t,s*On.MIN_ANGLE_RAD),a=On.FILL*Math.PI*n*n;return{radiusM:n,luminanceCdM2:i*Math.min(On.MAX_SHARE,e/a)}}static conserving(t){return Math.sqrt(t/(On.MAX_SHARE*On.FILL*Math.PI))}static VERTEX=`
|
|
8351
8351
|
uniform float uRadius;
|
|
8352
8352
|
varying vec2 vOffset;
|
|
8353
8353
|
void main() {
|
|
@@ -8923,7 +8923,7 @@ void main() {`).replace("#include <opaque_fragment>",`
|
|
|
8923
8923
|
vec3 light = texture2D(uMap, vec2((along * (uSteps - 1.0) + 0.5) / uSteps, 0.5)).rgb;
|
|
8924
8924
|
gl_FragColor = vec4(light, 1.0);
|
|
8925
8925
|
}
|
|
8926
|
-
`,transparent:!0,blending:gs,depthWrite:!1,side:Ai,fog:!1});this.object=new dt(new Ji(K1.RADIUS,128,32,0,Math.PI*2,0,Ne.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ne.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=_s.toHalfFloat(Math.min(e[i*3+s],6e4));this.texels[i*4+3]=_s.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class $f{constructor(t){this.generator=t}static SIZE=128;target=new bu($f.SIZE,{type:Be,generateMipmaps:!0,minFilter:Fn,magFilter:ge});camera=new H1(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,s=[]){const n=t.shadowMap.autoUpdate;let a=!1;e.traverse(o=>{const l=o;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(a=!0)}),t.shadowMap.autoUpdate=a?n:!1;const r=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),s.forEach((o,l)=>{o.visible=r[l]}),t.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 Ys{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Ys.install(),this.generator=new Rg(t),this.eye=new $f(this.generator)}static decor;refresh(t,e,i,s,n,a,r,o=[],l,h=Ys.REFRESH_MS){for(const m of[...this.probes.keys()])s.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of s){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new $f(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==r),p=f().filter(({probe:m})=>d-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...n]),Ys.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...n,...o]),l?.(m.probe.sharp),Ys.decor=m.probe.filtered;for(const v of a)Ys.reflectOn(v,m.probe);for(const v of s)v.shiny||Ys.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=r}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(d-m.capturedAtMs))))}scratch=new _;static reflectOn(t,e={filtered:Ys.decor}){t.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof qs?e.sharp&&n.setSurroundings(e.sharp):n instanceof _r&&e.filtered&&n.envMap!==e.filtered&&(n.envMap=e.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Ys.installed)return;Ys.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ne.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ne.lights_fragment_maps=ne.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const Ob=0,QP=1,tC=2,n2=2,Lp=1.25,a2=1,Js=32,fs=Js/4,Lb=65535,uf=Math.pow(2,-24),Y1=Symbol("SKIP_GENERATION"),Nb={strategy:Ob,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Y1]:!1};function Bi(c,t,e){return e.min.x=t[c],e.min.y=t[c+1],e.min.z=t[c+2],e.max.x=t[c+3],e.max.y=t[c+4],e.max.z=t[c+5],e}function Kg(c){let t=-1,e=-1/0;for(let i=0;i<3;i++){const s=c[i+3]-c[i];s>e&&(e=s,t=i)}return t}function r2(c,t){t.set(c)}function o2(c,t,e){let i,s;for(let n=0;n<3;n++){const a=n+3;i=c[n],s=t[n],e[n]=i<s?i:s,i=c[a],s=t[a],e[a]=i>s?i:s}}function Ad(c,t,e){for(let i=0;i<3;i++){const s=t[c+2*i],n=t[c+2*i+1],a=s-n,r=s+n;a<e[i]&&(e[i]=a),r>e[i+3]&&(e[i+3]=r)}}function bh(c){const t=c[3]-c[0],e=c[4]-c[1],i=c[5]-c[2];return 2*(t*e+e*i+i*t)}function qi(c,t){return t[c+15]===Lb}function Rs(c,t){return t[c+6]}function js(c,t){return t[c+14]}function ps(c){return c+fs}function ms(c,t){const e=t[c+6];return c+e*fs}function $1(c,t){return t[c+7]}function Np(c,t,e,i,s){let n=1/0,a=1/0,r=1/0,o=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,g=-1/0,m=-1/0;const v=c.offset||0;for(let M=(t-v)*6,x=(t+e-v)*6;M<x;M+=6){const y=c[M+0],w=c[M+1],S=y-w,E=y+w;S<n&&(n=S),E>o&&(o=E),y<u&&(u=y),y>p&&(p=y);const b=c[M+2],A=c[M+3],T=b-A,D=b+A;T<a&&(a=T),D>l&&(l=D),b<d&&(d=b),b>g&&(g=b);const I=c[M+4],C=c[M+5],N=I-C,O=I+C;N<r&&(r=N),O>h&&(h=O),I<f&&(f=I),I>m&&(m=I)}i[0]=n,i[1]=a,i[2]=r,i[3]=o,i[4]=l,i[5]=h,s[0]=u,s[1]=d,s[2]=f,s[3]=p,s[4]=g,s[5]=m}const Mr=32,eC=(c,t)=>c.candidate-t.candidate,qr=new Array(Mr).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),_d=new Float32Array(6);function iC(c,t,e,i,s,n){let a=-1,r=0;if(n===Ob)a=Kg(t),a!==-1&&(r=(t[a]+t[a+3])/2);else if(n===QP)a=Kg(c),a!==-1&&(r=sC(e,i,s,a));else if(n===tC){const o=bh(c);let l=Lp*s;const h=e.offset||0,u=(i-h)*6,d=(i+s-h)*6;for(let f=0;f<3;f++){const p=t[f],v=(t[f+3]-p)/Mr;if(s<Mr/4){const M=[...qr];M.length=s;let x=0;for(let w=u;w<d;w+=6,x++){const S=M[x];S.candidate=e[w+2*f],S.count=0;const{bounds:E,leftCacheBounds:b,rightCacheBounds:A}=S;for(let T=0;T<3;T++)A[T]=1/0,A[T+3]=-1/0,b[T]=1/0,b[T+3]=-1/0,E[T]=1/0,E[T+3]=-1/0;Ad(w,e,E)}M.sort(eC);let y=s;for(let w=0;w<y;w++){const S=M[w];for(;w+1<y&&M[w+1].candidate===S.candidate;)M.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const S=e[w+2*f];for(let E=0;E<y;E++){const b=M[E];S>=b.candidate?Ad(w,e,b.rightCacheBounds):(Ad(w,e,b.leftCacheBounds),b.count++)}}for(let w=0;w<y;w++){const S=M[w],E=S.count,b=s-S.count,A=S.leftCacheBounds,T=S.rightCacheBounds;let D=0;E!==0&&(D=bh(A)/o);let I=0;b!==0&&(I=bh(T)/o);const C=a2+Lp*(D*E+I*b);C<l&&(a=f,l=C,r=S.candidate)}}else{for(let y=0;y<Mr;y++){const w=qr[y];w.count=0,w.candidate=p+v+y*v;const S=w.bounds;for(let E=0;E<3;E++)S[E]=1/0,S[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=Mr&&(E=Mr-1);const b=qr[E];b.count++,Ad(y,e,b.bounds)}const M=qr[Mr-1];r2(M.bounds,M.rightCacheBounds);for(let y=Mr-2;y>=0;y--){const w=qr[y],S=qr[y+1];o2(w.bounds,S.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Mr-1;y++){const w=qr[y],S=w.count,E=w.bounds,A=qr[y+1].rightCacheBounds;S!==0&&(x===0?r2(E,_d):o2(E,_d,_d)),x+=S;let T=0,D=0;x!==0&&(T=bh(_d)/o);const I=s-x;I!==0&&(D=bh(A)/o);const C=a2+Lp*(T*x+D*I);C<l&&(a=f,l=C,r=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:a,pos:r}}function sC(c,t,e,i){let s=0;const n=c.offset;for(let a=t,r=t+e;a<r;a++)s+=c[(a-n)*6+i*2];return s/e}class kp{constructor(){this.boundingData=new Float32Array(6)}}function nC(c,t,e,i,s,n){let a=i,r=i+s-1;const o=n.pos,l=n.axis*2,h=e.offset||0;for(;;){for(;a<=r&&e[(a-h)*6+l]<o;)a++;for(;a<=r&&e[(r-h)*6+l]>=o;)r--;if(a<r){for(let u=0;u<t;u++){let d=c[a*t+u];c[a*t+u]=c[r*t+u],c[r*t+u]=d}for(let u=0;u<6;u++){const d=a-h,f=r-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}a++,r--}else return a}}let kb,df,Yg,Fb;const aC=Math.pow(2,32);function $g(c){return"count"in c?1:1+$g(c.left)+$g(c.right)}function rC(c,t,e){return kb=new Float32Array(e),df=new Uint32Array(e),Yg=new Uint16Array(e),Fb=new Uint8Array(e),qg(c,t)}function qg(c,t){const e=c/4,i=c/2,s="count"in t,n=t.boundingData;for(let a=0;a<6;a++)kb[e+a]=n[a];if(s)return t.buffer?(Fb.set(new Uint8Array(t.buffer),c),c+t.buffer.byteLength):(df[e+6]=t.offset,Yg[i+14]=t.count,Yg[i+15]=Lb,c+Js);{const{left:a,right:r,splitAxis:o}=t,l=c+Js;let h=qg(l,a);const u=c/Js,f=h/Js-u;if(f>aC)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return df[e+6]=f,df[e+7]=o,qg(h,r)}}function oC(c,t,e,i,s,n){const{maxDepth:a,verbose:r,targetLeafSize:o,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=s,d=c.primitiveBuffer,f=c.primitiveBufferStride,p=new Float32Array(6);let g=!1;const m=new kp;return Np(t,e,i,m.boundingData,p),M(m,e,i,p),m;function v(x){u&&u((x-n.offset)/n.count)}function M(x,y,w,S=null,E=0){!g&&E>=a&&(g=!0,r&&console.warn(`BVH: Max depth of ${a} reached when generating BVH. Consider increasing maxDepth.`));const b=w>l;if(w<=o&&!b||E>=a)return v(y+w),x.offset=y,x.count=w,x;const A=iC(x.boundingData,S,t,y,w,h);let T=A.axis===-1?-1:nC(d,f,t,y,w,A);if(A.axis===-1||T===y||T===y+w){if(!b)return v(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,Kg(x.boundingData)),T=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const D=new kp,I=y,C=T-y;x.left=D,Np(t,I,C,D.boundingData,p),M(D,I,C,p,E+1);const N=new kp,O=T,k=w-C;return x.right=N,Np(t,O,k,N.boundingData,p),M(N,O,k,p,E+1),x}}function cC(c,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=c.getRootRanges(t.range),s=i[0],n=i[i.length-1],a={offset:s.offset,count:n.offset+n.count-s.offset},r=new Float32Array(6*a.count);r.offset=a.offset,c.computePrimitiveBounds(a.offset,a.count,r),c._roots=i.map(o=>{const l=oC(c,r,o.offset,o.count,t,a),h=$g(l),u=new e(Js*h);return rC(0,l,u),u})}class q1{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class lC{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Ti=new lC;let fo,El;const Vc=[],Td=new q1(()=>new ze);function hC(c,t,e,i,s,n){fo=Td.getPrimitive(),El=Td.getPrimitive(),Vc.push(fo,El),Ti.setBuffer(c._roots[t]);const a=Zg(0,c.geometry,e,i,s,n);Ti.clearBuffer(),Td.releasePrimitive(fo),Td.releasePrimitive(El),Vc.pop(),Vc.pop();const r=Vc.length;return r>0&&(El=Vc[r-1],fo=Vc[r-2]),a}function Zg(c,t,e,i,s=null,n=0,a=0){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti;let h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);return Bi(c,r,fo),i(d,f,!1,a,n+c/fs,fo)}else{let T=function(I){const{uint16Array:C,uint32Array:N}=Ti;let O=I*2;for(;!qi(O,C);)I=ps(I),O=I*2;return Rs(I,N)},D=function(I){const{uint16Array:C,uint32Array:N}=Ti;let O=I*2;for(;!qi(O,C);)I=ms(I,N),O=I*2;return Rs(I,N)+js(O,C)};const d=ps(c),f=ms(c,l);let p=d,g=f,m,v,M,x;if(s&&(M=fo,x=El,Bi(p,r,M),Bi(g,r,x),m=s(M),v=s(x),v<m)){p=f,g=d;const I=m;m=v,v=I,M=x}M||(M=fo,Bi(p,r,M));const y=qi(p*2,o),w=e(M,y,m,a+1,n+p/fs);let S;if(w===n2){const I=T(p),N=D(p)-I;S=i(I,N,!0,a+1,n+p/fs,M)}else S=w&&Zg(p,t,e,i,s,n,a+1);if(S)return!0;x=El,Bi(g,r,x);const E=qi(g*2,o),b=e(x,E,v,a+1,n+g/fs);let A;if(b===n2){const I=T(g),N=D(g)-I;A=i(I,N,!0,a+1,n+g/fs,x)}else A=b&&Zg(g,t,e,i,s,n,a+1);return!!A}}const au=new Ti.constructor,qf=new Ti.constructor,so=new q1(()=>new ze),Wc=new ze,Xc=new ze,Fp=new ze,Up=new ze;let zp=!1;function uC(c,t,e,i){if(zp)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");zp=!0;const s=c._roots,n=t._roots;let a,r=0,o=0;const l=new Gt().copy(e).invert();for(let h=0,u=s.length;h<u;h++){au.setBuffer(s[h]),o=0;const d=so.getPrimitive();Bi(0,au.float32Array,d),d.applyMatrix4(l);for(let f=0,p=n.length;f<p&&(qf.setBuffer(n[f]),a=oa(0,0,e,l,i,r,o,0,0,d),qf.clearBuffer(),o+=n[f].byteLength/Js,!a);f++);if(so.releasePrimitive(d),au.clearBuffer(),r+=s[h].byteLength/Js,a)break}return zp=!1,a}function oa(c,t,e,i,s,n=0,a=0,r=0,o=0,l=null,h=!1){let u,d;h?(u=qf,d=au):(u=au,d=qf);const f=u.float32Array,p=u.uint32Array,g=u.uint16Array,m=d.float32Array,v=d.uint32Array,M=d.uint16Array,x=c*2,y=t*2,w=qi(x,g),S=qi(y,M);let E=!1;if(S&&w)h?E=s(Rs(t,v),js(t*2,M),Rs(c,p),js(c*2,g),o,a+t/fs,r,n+c/fs):E=s(Rs(c,p),js(c*2,g),Rs(t,v),js(t*2,M),r,n+c/fs,o,a+t/fs);else if(S){const b=so.getPrimitive();Bi(t,m,b),b.applyMatrix4(e);const A=ps(c),T=ms(c,p);Bi(A,f,Wc),Bi(T,f,Xc);const D=b.intersectsBox(Wc),I=b.intersectsBox(Xc);E=D&&oa(t,A,i,e,s,a,n,o,r+1,b,!h)||I&&oa(t,T,i,e,s,a,n,o,r+1,b,!h),so.releasePrimitive(b)}else{const b=ps(t),A=ms(t,v);Bi(b,m,Fp),Bi(A,m,Up);const T=l.intersectsBox(Fp),D=l.intersectsBox(Up);if(T&&D)E=oa(c,b,e,i,s,n,a,r,o+1,l,h)||oa(c,A,e,i,s,n,a,r,o+1,l,h);else if(T)if(w)E=oa(c,b,e,i,s,n,a,r,o+1,l,h);else{const I=so.getPrimitive();I.copy(Fp).applyMatrix4(e);const C=ps(c),N=ms(c,p);Bi(C,f,Wc),Bi(N,f,Xc);const O=I.intersectsBox(Wc),k=I.intersectsBox(Xc);E=O&&oa(b,C,i,e,s,a,n,o,r+1,I,!h)||k&&oa(b,N,i,e,s,a,n,o,r+1,I,!h),so.releasePrimitive(I)}else if(D)if(w)E=oa(c,A,e,i,s,n,a,r,o+1,l,h);else{const I=so.getPrimitive();I.copy(Up).applyMatrix4(e);const C=ps(c),N=ms(c,p);Bi(C,f,Wc),Bi(N,f,Xc);const O=I.intersectsBox(Wc),k=I.intersectsBox(Xc);E=O&&oa(A,C,i,e,s,a,n,o,r+1,I,!h)||k&&oa(A,N,i,e,s,a,n,o,r+1,I,!h),so.releasePrimitive(I)}}return E}const Bp=new class{constructor(){let c=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,a)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=a,this.buffer=c=n._roots[a],this.uint16Array=e=new Uint16Array(c),this.uint32Array=t=new Uint32Array(c)},this.reset=()=>{this.root=null,this.buffer=c=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=n=>{let a=n*2;for(;!qi(a,e);)n=ps(n),a=n*2;return Rs(n,t)},this.getRangeEnd=n=>{let a=n*2;for(;!qi(a,e);)n=ms(n,t),a=n*2;return Rs(n,t)+js(a,e)};const s=(n,a,r)=>{const o=a*2,l=qi(o,e);if(!n(r,l,a)&&!l){const u=ps(a),d=ms(a,t);s(n,u,r+1),s(n,d,r+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((a,r,o)=>{if(r){const l=o*2,h=t[o+6],u=e[l+14];return n(a,r,new Float32Array(c,o*4,6),h,u)}else{const l=$1(o,t);return n(a,r,new Float32Array(c,o*4,6),l)}})}}},c2=new ze,Kc=new Float32Array(6);class dC{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...Nb,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),cC(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,s){let n=1/0,a=1/0,r=1/0,o=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,Kc,0);const[f,p,g,m,v,M]=Kc;f<n&&(n=f),m>o&&(o=m),p<a&&(a=p),v>l&&(l=v),g<r&&(r=g),M>h&&(h=M)}return i[s+0]=n,i[s+1]=a,i[s+2]=r,i[s+3]=o,i[s+4]=l,i[s+5]=h,i}computePrimitiveBounds(t,e,i){const s=i.offset||0;for(let n=t,a=t+e;n<a;n++){this.writePrimitiveBounds(n,Kc,0);const[r,o,l,h,u,d]=Kc,f=(r+h)/2,p=(o+u)/2,g=(l+d)/2,m=(h-r)/2,v=(u-o)/2,M=(d-l)/2,x=(n-s)*6;i[x+0]=f,i[x+1]=m+(Math.abs(f)+m)*uf,i[x+2]=p,i[x+3]=v+(Math.abs(p)+v)*uf,i[x+4]=g,i[x+5]=M+(Math.abs(g)+M)*uf}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,s=e.length;i<s;i++)e[i]+=t;else{const i=this._roots;for(let s=0;s<i.length;s++){const n=i[s],a=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/Js;for(let l=0;l<o;l++){const h=fs*l,u=2*h;qi(u,r)&&(a[h+6]+=t)}}}}traverse(t,e=0){Bp.setBVH(this,e),Bp.traverse(t),Bp.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const s=t[e],n=new Uint32Array(s),a=new Uint16Array(s),r=new Float32Array(s),o=s.byteLength/Js;for(let l=o-1;l>=0;l--){const h=l*fs,u=h*2;if(qi(u,a)){const f=Rs(h,n),p=js(u,a);this.writePrimitiveRangeBounds(f,p,Kc,0),r.set(Kc,h)}else{const f=ps(h),p=ms(h,n);for(let g=0;g<3;g++){const m=r[f+g],v=r[f+g+3],M=r[p+g],x=r[p+g+3];r[h+g]=m<M?m:M,r[h+g+3]=v>x?v:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Bi(0,new Float32Array(i),c2),t.union(c2)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:n,scratchPrimitive:a,iterate:r}=t;if(s&&n){const u=s;s=(d,f,p,g,m)=>u(d,f,p,g,m)?!0:r(d,f,this,n,p,g,a)}else s||(n?s=(u,d,f,p)=>r(u,d,this,n,f,p,a):s=(u,d,f)=>f);let o=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(o=hC(this,u,i,s,e,l),o)break;l+=f.byteLength/Js}return o}bvhcast(t,e,i){let{intersectsRanges:s}=i;return uC(this,t,e,s)}}function fC(){return typeof SharedArrayBuffer<"u"}function Z1(c){return c.index?c.index.count:c.attributes.position.count}function y0(c){return Z1(c)/3}function pC(c,t=ArrayBuffer){return c>65535?new Uint32Array(new t(4*c)):new Uint16Array(new t(2*c))}function mC(c,t){if(!c.index){const e=c.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=pC(e,i);c.setIndex(new ve(s,1));for(let n=0;n<e;n++)s[n]=n}}function gC(c,t,e){const i=Z1(c)/e,s=t||c.drawRange,n=s.start/e,a=(s.start+s.count)/e,r=Math.max(0,n),o=Math.min(i,a)-r;return{offset:Math.floor(r),count:Math.floor(o)}}function vC(c,t){return c.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function l2(c,t,e){const i=gC(c,t,e),s=vC(c,e);if(!s.length)return[i];const n=[],a=i.offset,r=i.offset+i.count,o=Z1(c)/e,l=[];for(const d of s){const{offset:f,count:p}=d,g=f,m=isFinite(p)?p:o-f,v=f+m;g<r&&v>a&&(l.push({pos:Math.max(a,g),isStart:!0}),l.push({pos:Math.min(r,v),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&n.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return n}function MC(c,t){const e=c[c.length-1],i=e.offset+e.count>2**16,s=c.reduce((l,h)=>l+h.count,0),n=i?4:2,a=t?new SharedArrayBuffer(s*n):new ArrayBuffer(s*n),r=i?new Uint32Array(a):new Uint16Array(a);let o=0;for(let l=0;l<c.length;l++){const{offset:h,count:u}=c[l];for(let d=0;d<u;d++)r[o+d]=h+d;o+=u}return r}class yC extends dC{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!fC())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...Nb,...e},e[Y1]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const s=l2(e,t.range,i),n=MC(s,t.useSharedArrayBuffer);this._indirectBuffer=n}else mC(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ze))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:l2(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Lr{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,s=-1/0;for(let n=0,a=t.length;n<a;n++){const o=t[n][e];i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}setFromPoints(t,e){let i=1/0,s=-1/0;for(let n=0,a=e.length;n<a;n++){const r=e[n],o=t.dot(r);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(t){return this.min>t.max||t.min>this.max}}Lr.prototype.setFromBox=(function(){const c=new _;return function(e,i){const s=i.min,n=i.max;let a=1/0,r=-1/0;for(let o=0;o<=1;o++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){c.x=s.x*o+n.x*(1-o),c.y=s.y*l+n.y*(1-l),c.z=s.z*h+n.z*(1-h);const u=e.dot(c);a=Math.min(u,a),r=Math.max(u,r)}this.min=a,this.max=r}})();const xC=(function(){const c=new _,t=new _,e=new _;return function(s,n,a){const r=s.start,o=c,l=n.start,h=t;e.subVectors(r,l),c.subVectors(s.end,s.start),t.subVectors(n.end,n.start);const u=e.dot(h),d=h.dot(o),f=h.dot(h),p=e.dot(o),m=o.dot(o)*f-d*d;let v,M;m!==0?v=(u*d-p*f)/m:v=0,M=(u+v*d)/f,a.x=v,a.y=M}})(),J1=(function(){const c=new Q,t=new _,e=new _;return function(s,n,a,r){xC(s,n,c);let o=c.x,l=c.y;if(o>=0&&o<=1&&l>=0&&l<=1){s.at(o,a),n.at(l,r);return}else if(o>=0&&o<=1){l<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else if(l>=0&&l<=1){o<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else{let h;o<0?h=s.start:h=s.end;let u;l<0?u=n.start:u=n.end;const d=t,f=e;if(s.closestPointToPoint(u,!0,t),n.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){a.copy(d),r.copy(u);return}else{a.copy(h),r.copy(f);return}}}})(),wC=(function(){const c=new _,t=new _,e=new fa,i=new Or;return function(n,a){const{radius:r,center:o}=n,{a:l,b:h,c:u}=a;if(i.start=l,i.end=h,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r||(i.start=l,i.end=u,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r)||(i.start=h,i.end=u,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r))return!0;const g=a.getPlane(e);if(Math.abs(g.distanceToPoint(o))<=r){const v=g.projectPoint(o,t);if(a.containsPoint(v))return!0}return!1}})(),bC=["x","y","z"],br=1e-15,h2=br*br;function Wn(c){return Math.abs(c)<br}class ya extends As{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new _),this.satBounds=new Array(4).fill().map(()=>new Lr),this.points=[this.a,this.b,this.c],this.plane=new fa,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Or,this.needsUpdate=!0}intersectsSphere(t){return wC(t,this)}update(){const t=this.a,e=this.b,i=this.c,s=this.points,n=this.satAxes,a=this.satBounds,r=n[0],o=a[0];this.getNormal(r),o.setFromPoints(r,s);const l=n[1],h=a[1];l.subVectors(t,e),h.setFromPoints(l,s);const u=n[2],d=a[2];u.subVectors(e,i),d.setFromPoints(u,s);const f=n[3],p=a[3];f.subVectors(i,t),p.setFromPoints(f,s);const g=l.length(),m=u.length(),v=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,g<br?m<br||v<br?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<br?v<br?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<br&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(r,t),this.needsUpdate=!1}}ya.prototype.closestPointToSegment=(function(){const c=new _,t=new _,e=new Or;return function(s,n=null,a=null){const{start:r,end:o}=s,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),J1(e,s,c,t),h=c.distanceToSquared(t),h<u&&(u=h,n&&n.copy(c),a&&a.copy(t))}return this.closestPointToPoint(r,c),h=r.distanceToSquared(c),h<u&&(u=h,n&&n.copy(c),a&&a.copy(r)),this.closestPointToPoint(o,c),h=o.distanceToSquared(c),h<u&&(u=h,n&&n.copy(c),a&&a.copy(o)),Math.sqrt(u)}})();ya.prototype.intersectsTriangle=(function(){const c=new ya,t=new Lr,e=new Lr,i=new _,s=new _,n=new _,a=new _,r=new Or,o=new Or,l=new _,h=new Q,u=new Q;function d(x,y,w,S){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const b=x.satBounds,A=x.satAxes;for(let I=1;I<4;I++){const C=b[I],N=A[I];if(t.setFromPoints(N,y.points),C.isSeparated(t)||(a.copy(E).cross(N),t.setFromPoints(a,x.points),e.setFromPoints(a,y.points),t.isSeparated(e)))return!1}const T=y.satBounds,D=y.satAxes;for(let I=1;I<4;I++){const C=T[I],N=D[I];if(t.setFromPoints(N,x.points),C.isSeparated(t)||(a.crossVectors(E,N),t.setFromPoints(a,x.points),e.setFromPoints(a,y.points),t.isSeparated(e)))return!1}return w&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,S,E,b,A,T,D,I,C){let N=A/(A-T);I.x=S+(E-S)*N,C.start.subVectors(y,x).multiplyScalar(N).add(x),N=A/(A-D),I.y=S+(b-S)*N,C.end.subVectors(w,x).multiplyScalar(N).add(x)}function p(x,y,w,S,E,b,A,T,D,I,C){if(E>0)f(x.c,x.a,x.b,S,y,w,D,A,T,I,C);else if(b>0)f(x.b,x.a,x.c,w,y,S,T,A,D,I,C);else if(T*D>0||A!=0)f(x.a,x.b,x.c,y,w,S,A,T,D,I,C);else if(T!=0)f(x.b,x.a,x.c,w,y,S,T,A,D,I,C);else if(D!=0)f(x.c,x.a,x.b,S,y,w,D,A,T,I,C);else return!0;return!1}function g(x,y,w,S){const E=y.degenerateSegment,b=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return Wn(b)?Wn(A)?d(x,y,w,S):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):Wn(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function m(x,y,w){const S=y.a;return Wn(x.plane.distanceToPoint(S))&&x.containsPoint(S)?(w&&(w.start.copy(S),w.end.copy(S)),!0):!1}function v(x,y,w){const S=x.degenerateSegment,E=y.a;return S.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<h2?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function M(x,y,w,S){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,b=y.degenerateSegment,A=s,T=n;E.delta(A),b.delta(T);const D=i.subVectors(b.start,E.start),I=A.x*T.y-A.y*T.x;if(Wn(I))return!1;const C=(D.x*T.y-D.y*T.x)/I,N=-(A.x*D.y-A.y*D.x)/I;if(C<0||C>1||N<0||N>1)return!1;const O=E.start.z+A.z*C,k=b.start.z+T.z*N;return Wn(O-k)?(w&&(w.start.copy(E.start).addScaledVector(A,C),w.end.copy(E.start).addScaledVector(A,C)),!0):!1}else return y.isDegenerateIntoPoint?v(x,y,w):g(y,x,w,S);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<h2?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?v(y,x,w):m(y,x,w);if(y.isDegenerateIntoPoint)return m(x,y,w);if(y.isDegenerateIntoSegment)return g(x,y,w,S)}}return function(y,w=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(c.copy(y),c.update(),y=c);const E=M(this,y,w,S);if(E!==void 0)return E;const b=this.plane,A=y.plane;let T=A.distanceToPoint(this.a),D=A.distanceToPoint(this.b),I=A.distanceToPoint(this.c);Wn(T)&&(T=0),Wn(D)&&(D=0),Wn(I)&&(I=0);const C=T*D,N=T*I;if(C>0&&N>0)return!1;let O=b.distanceToPoint(y.a),k=b.distanceToPoint(y.b),B=b.distanceToPoint(y.c);Wn(O)&&(O=0),Wn(k)&&(k=0),Wn(B)&&(B=0);const X=O*k,J=O*B;if(X>0&&J>0)return!1;s.copy(b.normal),n.copy(A.normal);const $=s.cross(n);let it=0,rt=Math.abs($.x);const Lt=Math.abs($.y);Lt>rt&&(rt=Lt,it=1),Math.abs($.z)>rt&&(it=2);const Zt=bC[it],q=this.a[Zt],ot=this.b[Zt],st=this.c[Zt],G=y.a[Zt],Nt=y.b[Zt],Xt=y.c[Zt];if(p(this,q,ot,st,C,N,T,D,I,h,r))return d(this,y,w,S);if(p(y,G,Nt,Xt,X,J,O,k,B,u,o))return d(this,y,w,S);if(h.y<h.x){const kt=h.y;h.y=h.x,h.x=kt,l.copy(r.start),r.start.copy(r.end),r.end.copy(l)}if(u.y<u.x){const kt=u.y;u.y=u.x,u.x=kt,l.copy(o.start),o.start.copy(o.end),o.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(o.start):w.start.copy(r.start),u.y<h.y?w.end.copy(o.end):w.end.copy(r.end)),!0)}})();ya.prototype.distanceToPoint=(function(){const c=new _;return function(e){return this.closestPointToPoint(e,c),e.distanceTo(c)}})();ya.prototype.distanceToTriangle=(function(){const c=new _,t=new _,e=["a","b","c"],i=new Or,s=new Or;return function(a,r=null,o=null){const l=r||o?i:null;if(this.intersectsTriangle(a,l,!0))return(r||o)&&(r&&l.getCenter(r),o&&l.getCenter(o)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=a[f];this.closestPointToPoint(p,c),d=p.distanceToSquared(c),d<h&&(h=d,r&&r.copy(c),o&&o.copy(p));const g=this[f];a.closestPointToPoint(g,c),d=g.distanceToSquared(c),d<h&&(h=d,r&&r.copy(g),o&&o.copy(c))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const g=e[p],m=e[(p+1)%3];s.set(a[g],a[m]),J1(i,s,c,t);const v=c.distanceToSquared(t);v<h&&(h=v,r&&r.copy(c),o&&o.copy(t))}}return Math.sqrt(h)}})();class fn{constructor(t,e,i){this.isOrientedBox=!0,this.min=new _,this.max=new _,this.matrix=new Gt,this.invMatrix=new Gt,this.points=new Array(8).fill().map(()=>new _),this.satAxes=new Array(3).fill().map(()=>new _),this.satBounds=new Array(3).fill().map(()=>new Lr),this.alignedSatBounds=new Array(3).fill().map(()=>new Lr),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}fn.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,s=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=s[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const n=this.satBounds,a=this.satAxes,r=s[0];for(let l=0;l<3;l++){const h=a[l],u=n[l],d=1<<l,f=s[d];h.subVectors(r,f),u.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}})();fn.prototype.intersectsBox=(function(){const c=new Lr;return function(e){this.needsUpdate&&this.update();const i=e.min,s=e.max,n=this.satBounds,a=this.satAxes,r=this.alignedSatBounds;if(c.min=i.x,c.max=s.x,r[0].isSeparated(c)||(c.min=i.y,c.max=s.y,r[1].isSeparated(c))||(c.min=i.z,c.max=s.z,r[2].isSeparated(c)))return!1;for(let o=0;o<3;o++){const l=a[o],h=n[o];if(c.setFromBox(l,e),h.isSeparated(c))return!1}return!0}})();fn.prototype.intersectsTriangle=(function(){const c=new ya,t=new Array(3),e=new Lr,i=new Lr,s=new _;return function(a){this.needsUpdate&&this.update(),a.isExtendedTriangle?a.needsUpdate&&a.update():(c.copy(a),c.update(),a=c);const r=this.satBounds,o=this.satAxes;t[0]=a.a,t[1]=a.b,t[2]=a.c;for(let d=0;d<3;d++){const f=r[d],p=o[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=a.satBounds,h=a.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=o[d];for(let p=0;p<4;p++){const g=h[p];if(s.crossVectors(f,g),e.setFromPoints(s,t),i.setFromPoints(s,u),e.isSeparated(i))return!1}}return!0}})();fn.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();fn.prototype.distanceToPoint=(function(){const c=new _;return function(e){return this.closestPointToPoint(e,c),e.distanceTo(c)}})();fn.prototype.distanceToBox=(function(){const c=["x","y","z"],t=new Array(12).fill().map(()=>new Or),e=new Array(12).fill().map(()=>new Or),i=new _,s=new _;return function(a,r=0,o=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(a))return(o||l)&&(a.getCenter(s),this.closestPointToPoint(s,i),a.closestPointToPoint(i,s),o&&o.copy(i),l&&l.copy(s)),0;const h=r*r,u=a.min,d=a.max,f=this.points;let p=1/0;for(let m=0;m<8;m++){const v=f[m];s.copy(v).clamp(u,d);const M=v.distanceToSquared(s);if(M<p&&(p=M,o&&o.copy(v),l&&l.copy(s),M<h))return Math.sqrt(M)}let g=0;for(let m=0;m<3;m++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){const x=(m+1)%3,y=(m+2)%3,w=v<<x|M<<y,S=1<<m|v<<x|M<<y,E=f[w],b=f[S];t[g].set(E,b);const T=c[m],D=c[x],I=c[y],C=e[g],N=C.start,O=C.end;N[T]=u[T],N[D]=v?u[D]:d[D],N[I]=M?u[I]:d[D],O[T]=d[T],O[D]=v?u[D]:d[D],O[I]=M?u[I]:d[D],g++}for(let m=0;m<=1;m++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){s.x=m?d.x:u.x,s.y=v?d.y:u.y,s.z=M?d.z:u.z,this.closestPointToPoint(s,i);const x=s.distanceToSquared(i);if(x<p&&(p=x,o&&o.copy(i),l&&l.copy(s),x<h))return Math.sqrt(x)}for(let m=0;m<12;m++){const v=t[m];for(let M=0;M<12;M++){const x=e[M];J1(v,x,i,s);const y=i.distanceToSquared(s);if(y<p&&(p=y,o&&o.copy(i),l&&l.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class SC extends q1{constructor(){super(()=>new ya)}}const Qn=new SC,Sh=new _,Hp=new _;function EC(c,t,e={},i=0,s=1/0){const n=i*i,a=s*s;let r=1/0,o=null;if(c.shapecast({boundsTraverseOrder:h=>(Sh.copy(t).clamp(h.min,h.max),Sh.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<r&&d<a,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Sh);const d=t.distanceToSquared(Sh);return d<r&&(Hp.copy(Sh),r=d,o=u),d<n}}),r===1/0)return null;const l=Math.sqrt(r);return e.point?e.point.copy(Hp):e.point=Hp.clone(),e.distance=l,e.faceIndex=o,e}const Rd=parseInt(Ru)>=169,AC=parseInt(Ru)<=161,Po=new _,Co=new _,Oo=new _,Dd=new Q,Id=new Q,Pd=new Q,u2=new _,d2=new _,f2=new _,Eh=new _;function _C(c,t,e,i,s,n,a,r){let o;if(n===Ai?o=c.intersectTriangle(i,e,t,!0,s):o=c.intersectTriangle(t,e,i,n!==ds,s),o===null)return null;const l=c.origin.distanceTo(s);return l<a||l>r?null:{distance:l,point:s.clone()}}function p2(c,t,e,i,s,n,a,r,o,l,h){Po.fromBufferAttribute(t,n),Co.fromBufferAttribute(t,a),Oo.fromBufferAttribute(t,r);const u=_C(c,Po,Co,Oo,Eh,o,l,h);if(u){if(i){Dd.fromBufferAttribute(i,n),Id.fromBufferAttribute(i,a),Pd.fromBufferAttribute(i,r),u.uv=new Q;const f=As.getInterpolation(Eh,Po,Co,Oo,Dd,Id,Pd,u.uv);Rd||(u.uv=f)}if(s){Dd.fromBufferAttribute(s,n),Id.fromBufferAttribute(s,a),Pd.fromBufferAttribute(s,r),u.uv1=new Q;const f=As.getInterpolation(Eh,Po,Co,Oo,Dd,Id,Pd,u.uv1);Rd||(u.uv1=f),AC&&(u.uv2=u.uv1)}if(e){u2.fromBufferAttribute(e,n),d2.fromBufferAttribute(e,a),f2.fromBufferAttribute(e,r),u.normal=new _;const f=As.getInterpolation(Eh,Po,Co,Oo,u2,d2,f2,u.normal);u.normal.dot(c.direction)>0&&u.normal.multiplyScalar(-1),Rd||(u.normal=f)}const d={a:n,b:a,c:r,normal:new _,materialIndex:0};if(As.getNormal(Po,Co,Oo,d.normal),u.face=d,u.faceIndex=n,Rd){const f=new _;As.getBarycoord(Eh,Po,Co,Oo,f),u.barycoord=f}}return u}function m2(c){return c&&c.isMaterial?c.side:c}function x0(c,t,e,i,s,n,a){const r=i*3;let o=r+0,l=r+1,h=r+2;const{index:u,groups:d}=c;c.index&&(o=u.getX(o),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:g,uv1:m}=c.attributes;if(Array.isArray(t)){const v=i*3;for(let M=0,x=d.length;M<x;M++){const{start:y,count:w,materialIndex:S}=d[M];if(v>=y&&v<y+w){const E=m2(t[S]),b=p2(e,f,p,g,m,o,l,h,E,n,a);if(b)if(b.faceIndex=i,b.face.materialIndex=S,s)s.push(b);else return b}}}else{const v=m2(t),M=p2(e,f,p,g,m,o,l,h,v,n,a);if(M)if(M.faceIndex=i,M.face.materialIndex=0,s)s.push(M);else return M}return null}function as(c,t,e,i){const s=c.a,n=c.b,a=c.c;let r=t,o=t+1,l=t+2;e&&(r=e.getX(r),o=e.getX(o),l=e.getX(l)),s.x=i.getX(r),s.y=i.getY(r),s.z=i.getZ(r),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),a.x=i.getX(l),a.y=i.getY(l),a.z=i.getZ(l)}function TC(c,t,e,i,s,n,a,r){const{geometry:o,_indirectBuffer:l}=c;for(let h=i,u=i+s;h<u;h++)x0(o,t,e,h,n,a,r)}function RC(c,t,e,i,s,n,a){const{geometry:r,_indirectBuffer:o}=c;let l=1/0,h=null;for(let u=i,d=i+s;u<d;u++){let f;f=x0(r,t,e,u,null,n,a),f&&f.distance<l&&(h=f,l=f.distance)}return h}function DC(c,t,e,i,s,n,a){const{geometry:r}=e,{index:o}=r,l=r.attributes.position;for(let h=c,u=t+c;h<u;h++){let d;if(d=h,as(a,d*3,o,l),a.needsUpdate=!0,i(a,d,s,n))return!0}return!1}function IC(c,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=c.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,a,r,o,l=0;const h=c._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),r=new Uint16Array(n),o=new Float32Array(n),u(0,l),l+=n.byteLength;function u(d,f,p=!1){const g=d*2;if(qi(g,r)){const m=Rs(d,a),v=js(g,r);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=3*m,A=3*(m+v);b<A;b++){let T=i[b];const D=s.getX(T),I=s.getY(T),C=s.getZ(T);D<M&&(M=D),D>w&&(w=D),I<x&&(x=I),I>S&&(S=I),C<y&&(y=C),C>E&&(E=C)}return o[d+0]!==M||o[d+1]!==x||o[d+2]!==y||o[d+3]!==w||o[d+4]!==S||o[d+5]!==E?(o[d+0]=M,o[d+1]=x,o[d+2]=y,o[d+3]=w,o[d+4]=S,o[d+5]=E,!0):!1}else{const m=ps(d),v=ms(d,a);let M=p,x=!1,y=!1;if(t){if(!M){const T=m/fs+f/Js,D=v/fs+f/Js;x=t.has(T),y=t.has(D),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(m,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let T=0;T<3;T++){const D=m+T,I=v+T,C=o[D],N=o[D+3],O=o[I],k=o[I+3];o[d+T]=C<O?C:O,o[d+T+3]=N>k?N:k}return A}}}function wo(c,t,e,i,s){let n,a,r,o,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,g=e.origin.y,m=e.origin.z;let v=t[c],M=t[c+3],x=t[c+1],y=t[c+3+1],w=t[c+2],S=t[c+3+2];return u>=0?(n=(v-p)*u,a=(M-p)*u):(n=(M-p)*u,a=(v-p)*u),d>=0?(r=(x-g)*d,o=(y-g)*d):(r=(y-g)*d,o=(x-g)*d),n>o||r>a||((r>n||isNaN(n))&&(n=r),(o<a||isNaN(a))&&(a=o),f>=0?(l=(w-m)*f,h=(S-m)*f):(l=(S-m)*f,h=(w-m)*f),n>h||l>a)?!1:((l>n||n!==n)&&(n=l),(h<a||a!==a)&&(a=h),n<=s&&a>=i)}function PC(c,t,e,i,s,n,a,r){const{geometry:o,_indirectBuffer:l}=c;for(let h=i,u=i+s;h<u;h++){let d=l?l[h]:h;x0(o,t,e,d,n,a,r)}}function CC(c,t,e,i,s,n,a){const{geometry:r,_indirectBuffer:o}=c;let l=1/0,h=null;for(let u=i,d=i+s;u<d;u++){let f;f=x0(r,t,e,o?o[u]:u,null,n,a),f&&f.distance<l&&(h=f,l=f.distance)}return h}function OC(c,t,e,i,s,n,a){const{geometry:r}=e,{index:o}=r,l=r.attributes.position;for(let h=c,u=t+c;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),as(a,d*3,o,l),a.needsUpdate=!0,i(a,d,s,n))return!0}return!1}function LC(c,t,e,i,s,n,a){Ti.setBuffer(c._roots[t]),Jg(0,c,e,i,s,n,a),Ti.clearBuffer()}function Jg(c,t,e,i,s,n,a){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti,h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);TC(t,e,i,d,f,s,n,a)}else{const d=ps(c);wo(d,r,i,n,a)&&Jg(d,t,e,i,s,n,a);const f=ms(c,l);wo(f,r,i,n,a)&&Jg(f,t,e,i,s,n,a)}}const NC=["x","y","z"];function kC(c,t,e,i,s,n){Ti.setBuffer(c._roots[t]);const a=jg(0,c,e,i,s,n);return Ti.clearBuffer(),a}function jg(c,t,e,i,s,n){const{float32Array:a,uint16Array:r,uint32Array:o}=Ti;let l=c*2;if(qi(l,r)){const u=Rs(c,o),d=js(l,r);return RC(t,e,i,u,d,s,n)}else{const u=$1(c,o),d=NC[u],p=i.direction[d]>=0;let g,m;p?(g=ps(c),m=ms(c,o)):(g=ms(c,o),m=ps(c));const M=wo(g,a,i,s,n)?jg(g,t,e,i,s,n):null;if(M){const w=M.point[d];if(p?w<=a[m+u]:w>=a[m+u+3])return M}const y=wo(m,a,i,s,n)?jg(m,t,e,i,s,n):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Cd=new ze,Yc=new ya,$c=new ya,Ah=new Gt,g2=new fn,Od=new fn;function FC(c,t,e,i){Ti.setBuffer(c._roots[t]);const s=Qg(0,c,e,i);return Ti.clearBuffer(),s}function Qg(c,t,e,i,s=null){const{float32Array:n,uint16Array:a,uint32Array:r}=Ti;let o=c*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),g2.set(e.boundingBox.min,e.boundingBox.max,i),s=g2),qi(o,a)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,g=Rs(c,r),m=js(o,a);if(Ah.copy(i).invert(),e.boundsTree)return Bi(c,n,Od),Od.matrix.copy(Ah),Od.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Od.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=g*3,y=(m+g)*3;x<y;x+=3)if(as($c,x,u,d),$c.needsUpdate=!0,M.intersectsTriangle($c))return!0;return!1}});{const v=y0(e);for(let M=g*3,x=(m+g)*3;M<x;M+=3){as(Yc,M,u,d),Yc.a.applyMatrix4(Ah),Yc.b.applyMatrix4(Ah),Yc.c.applyMatrix4(Ah),Yc.needsUpdate=!0;for(let y=0,w=v*3;y<w;y+=3)if(as($c,y,f,p),$c.needsUpdate=!0,Yc.intersectsTriangle($c))return!0}}}else{const h=ps(c),u=ms(c,r);return Bi(h,n,Cd),!!(s.intersectsBox(Cd)&&Qg(h,t,e,i,s)||(Bi(u,n,Cd),s.intersectsBox(Cd)&&Qg(u,t,e,i,s)))}}const Ld=new Gt,Gp=new fn,_h=new fn,UC=new _,zC=new _,BC=new _,HC=new _;function GC(c,t,e,i={},s={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),Gp.set(t.boundingBox.min,t.boundingBox.max,e),Gp.needsUpdate=!0;const r=c.geometry,o=r.attributes.position,l=r.index,h=t.attributes.position,u=t.index,d=Qn.getPrimitive(),f=Qn.getPrimitive();let p=UC,g=zC,m=null,v=null;s&&(m=BC,v=HC);let M=1/0,x=null,y=null;return Ld.copy(e).invert(),_h.matrix.copy(Ld),c.shapecast({boundsTraverseOrder:w=>Gp.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<a?(S&&(_h.min.copy(w.min),_h.max.copy(w.max),_h.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:b=>_h.distanceToBox(b),intersectsBounds:(b,A,T)=>T<M&&T<a,intersectsRange:(b,A)=>{for(let T=b,D=b+A;T<D;T++){as(f,3*T,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let I=w,C=w+S;I<C;I++){as(d,3*I,l,o),d.needsUpdate=!0;const N=d.distanceToTriangle(f,p,m);if(N<M&&(g.copy(p),v&&v.copy(m),M=N,x=I,y=T),N<n)return!0}}}});{const E=y0(t);for(let b=0,A=E;b<A;b++){as(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=w,D=w+S;T<D;T++){as(d,3*T,l,o),d.needsUpdate=!0;const I=d.distanceToTriangle(f,p,m);if(I<M&&(g.copy(p),v&&v.copy(m),M=I,x=T,y=b),I<n)return!0}}}}}),Qn.releasePrimitive(d),Qn.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=M,i.faceIndex=x,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(Ld),g.applyMatrix4(Ld),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function VC(c,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=c.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,a,r,o,l=0;const h=c._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),r=new Uint16Array(n),o=new Float32Array(n),u(0,l),l+=n.byteLength;function u(d,f,p=!1){const g=d*2;if(qi(g,r)){const m=Rs(d,a),v=js(g,r);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=m,A=m+v;b<A;b++){const T=3*c.resolveTriangleIndex(b);for(let D=0;D<3;D++){let I=T+D;I=i?i[I]:I;const C=s.getX(I),N=s.getY(I),O=s.getZ(I);C<M&&(M=C),C>w&&(w=C),N<x&&(x=N),N>S&&(S=N),O<y&&(y=O),O>E&&(E=O)}}return o[d+0]!==M||o[d+1]!==x||o[d+2]!==y||o[d+3]!==w||o[d+4]!==S||o[d+5]!==E?(o[d+0]=M,o[d+1]=x,o[d+2]=y,o[d+3]=w,o[d+4]=S,o[d+5]=E,!0):!1}else{const m=ps(d),v=ms(d,a);let M=p,x=!1,y=!1;if(t){if(!M){const T=m/fs+f/Js,D=v/fs+f/Js;x=t.has(T),y=t.has(D),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(m,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let T=0;T<3;T++){const D=m+T,I=v+T,C=o[D],N=o[D+3],O=o[I],k=o[I+3];o[d+T]=C<O?C:O,o[d+T+3]=N>k?N:k}return A}}}function WC(c,t,e,i,s,n,a){Ti.setBuffer(c._roots[t]),t1(0,c,e,i,s,n,a),Ti.clearBuffer()}function t1(c,t,e,i,s,n,a){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti,h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);PC(t,e,i,d,f,s,n,a)}else{const d=ps(c);wo(d,r,i,n,a)&&t1(d,t,e,i,s,n,a);const f=ms(c,l);wo(f,r,i,n,a)&&t1(f,t,e,i,s,n,a)}}const XC=["x","y","z"];function KC(c,t,e,i,s,n){Ti.setBuffer(c._roots[t]);const a=e1(0,c,e,i,s,n);return Ti.clearBuffer(),a}function e1(c,t,e,i,s,n){const{float32Array:a,uint16Array:r,uint32Array:o}=Ti;let l=c*2;if(qi(l,r)){const u=Rs(c,o),d=js(l,r);return CC(t,e,i,u,d,s,n)}else{const u=$1(c,o),d=XC[u],p=i.direction[d]>=0;let g,m;p?(g=ps(c),m=ms(c,o)):(g=ms(c,o),m=ps(c));const M=wo(g,a,i,s,n)?e1(g,t,e,i,s,n):null;if(M){const w=M.point[d];if(p?w<=a[m+u]:w>=a[m+u+3])return M}const y=wo(m,a,i,s,n)?e1(m,t,e,i,s,n):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Nd=new ze,qc=new ya,Zc=new ya,Th=new Gt,v2=new fn,kd=new fn;function YC(c,t,e,i){Ti.setBuffer(c._roots[t]);const s=i1(0,c,e,i);return Ti.clearBuffer(),s}function i1(c,t,e,i,s=null){const{float32Array:n,uint16Array:a,uint32Array:r}=Ti;let o=c*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),v2.set(e.boundingBox.min,e.boundingBox.max,i),s=v2),qi(o,a)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,g=Rs(c,r),m=js(o,a);if(Th.copy(i).invert(),e.boundsTree)return Bi(c,n,kd),kd.matrix.copy(Th),kd.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>kd.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=g,y=m+g;x<y;x++)if(as(Zc,3*t.resolveTriangleIndex(x),u,d),Zc.needsUpdate=!0,M.intersectsTriangle(Zc))return!0;return!1}});{const v=y0(e);for(let M=g,x=m+g;M<x;M++){const y=t.resolveTriangleIndex(M);as(qc,3*y,u,d),qc.a.applyMatrix4(Th),qc.b.applyMatrix4(Th),qc.c.applyMatrix4(Th),qc.needsUpdate=!0;for(let w=0,S=v*3;w<S;w+=3)if(as(Zc,w,f,p),Zc.needsUpdate=!0,qc.intersectsTriangle(Zc))return!0}}}else{const h=ps(c),u=ms(c,r);return Bi(h,n,Nd),!!(s.intersectsBox(Nd)&&i1(h,t,e,i,s)||(Bi(u,n,Nd),s.intersectsBox(Nd)&&i1(u,t,e,i,s)))}}const Fd=new Gt,Vp=new fn,Rh=new fn,$C=new _,qC=new _,ZC=new _,JC=new _;function jC(c,t,e,i={},s={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),Vp.set(t.boundingBox.min,t.boundingBox.max,e),Vp.needsUpdate=!0;const r=c.geometry,o=r.attributes.position,l=r.index,h=t.attributes.position,u=t.index,d=Qn.getPrimitive(),f=Qn.getPrimitive();let p=$C,g=qC,m=null,v=null;s&&(m=ZC,v=JC);let M=1/0,x=null,y=null;return Fd.copy(e).invert(),Rh.matrix.copy(Fd),c.shapecast({boundsTraverseOrder:w=>Vp.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<a?(S&&(Rh.min.copy(w.min),Rh.max.copy(w.max),Rh.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:b=>Rh.distanceToBox(b),intersectsBounds:(b,A,T)=>T<M&&T<a,intersectsRange:(b,A)=>{for(let T=b,D=b+A;T<D;T++){const I=E.resolveTriangleIndex(T);as(f,3*I,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let C=w,N=w+S;C<N;C++){const O=c.resolveTriangleIndex(C);as(d,3*O,l,o),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,m);if(k<M&&(g.copy(p),v&&v.copy(m),M=k,x=C,y=T),k<n)return!0}}}})}else{const E=y0(t);for(let b=0,A=E;b<A;b++){as(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=w,D=w+S;T<D;T++){const I=c.resolveTriangleIndex(T);as(d,3*I,l,o),d.needsUpdate=!0;const C=d.distanceToTriangle(f,p,m);if(C<M&&(g.copy(p),v&&v.copy(m),M=C,x=T,y=b),C<n)return!0}}}}}),Qn.releasePrimitive(d),Qn.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=M,i.faceIndex=x,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(Fd),g.applyMatrix4(Fd),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function M2(c,t,e){return c===null?null:(c.point.applyMatrix4(t.matrixWorld),c.distance=c.point.distanceTo(e.ray.origin),c.object=t,c)}const Ud=new fn,zd=new pc,y2=new _,x2=new Gt,w2=new _,Wp=["getX","getY","getZ"];class Zf extends yC{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,s=t._roots,n=t._indirectBuffer,a=i.getIndex(),r={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(r.roots=s.map(o=>o.slice()),r.index=a?a.array.slice():null,r.indirectBuffer=n?n.slice():null):(r.roots=s,r.index=a?a.array:null,r.indirectBuffer=n),r}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:s,roots:n,indirectBuffer:a}=t;t.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 r=new Zf(e,{...i,[Y1]:!0});if(r._roots=n,r._indirectBuffer=a||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new ve(t.index,1,!1);e.setIndex(h)}else l.array!==s&&(l.array.set(s),l.needsUpdate=!0)}return r;function o(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,g=u.byteLength/Js;p<g;p++){const m=fs*p,v=2*m;qi(v,f)||(d[m+6]=d[m+6]/fs-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,a=s.attributes.position,r=s.index?s.index.array:null,l=(n?n[t]:t)*3;let h=l+0,u=l+1,d=l+2;r&&(h=r[h],u=r[u],d=r[d]);for(let f=0;f<3;f++){const p=a[Wp[f]](h),g=a[Wp[f]](u),m=a[Wp[f]](d);let v=p;g<v&&(v=g),m<v&&(v=m);let M=p;g>M&&(M=g),m>M&&(M=m),e[i+f]=v,e[i+f+3]=M}return e}computePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,a=s.attributes.position,r=s.index?s.index.array:null,o=a.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=a.array,h=a.offset||0;let u=3;a.isInterleavedBufferAttribute&&(u=a.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,g=t+e;p<g;p++){const v=(n?n[p]:p)*3,M=(p-f)*6;let x=v+0,y=v+1,w=v+2;r&&(x=r[x],y=r[y],w=r[w]),o||(x=x*u+h,y=y*u+h,w=w*u+h);for(let S=0;S<3;S++){let E,b,A;o?(E=a[d[S]](x),b=a[d[S]](y),A=a[d[S]](w)):(E=l[x+S],b=l[y+S],A=l[w+S]);let T=E;b<T&&(T=b),A<T&&(T=A);let D=E;b>D&&(D=b),A>D&&(D=A);const I=(D-T)/2,C=S*2;i[M+C+0]=T+I,i[M+C+1]=I+(Math.abs(T)+I)*uf}}return i}raycastObject3D(t,e,i=[]){const{material:s}=t;if(s===void 0)return;x2.copy(t.matrixWorld).invert(),zd.copy(e.ray).applyMatrix4(x2),w2.setFromMatrixScale(t.matrixWorld),y2.copy(zd.direction).multiply(w2);const n=y2.length(),a=e.near/n,r=e.far/n;if(e.firstHitOnly===!0){let o=this.raycastFirst(zd,s,a,r);o=M2(o,t,e),o&&i.push(o)}else{const o=this.raycast(zd,s,a,r);for(let l=0,h=o.length;l<h;l++){const u=M2(o[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?VC:IC)(this,t)}raycast(t,e=sr,i=0,s=1/0){const n=this._roots,a=[],r=this.indirect?WC:LC;for(let o=0,l=n.length;o<l;o++)r(this,o,e,t,a,i,s);return a}raycastFirst(t,e=sr,i=0,s=1/0){const n=this._roots;let a=null;const r=this.indirect?KC:kC;for(let o=0,l=n.length;o<l;o++){const h=r(this,o,e,t,i,s);h!=null&&(a==null||h.distance<a.distance)&&(a=h)}return a}intersectsGeometry(t,e){let i=!1;const s=this._roots,n=this.indirect?YC:FC;for(let a=0,r=s.length;a<r&&(i=n(this,a,t,e),!i);a++);return i}shapecast(t){const e=Qn.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?OC:DC});return Qn.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const a=Qn.getPrimitive(),r=this.geometry.index,o=this.geometry.attributes.position,l=this.indirect?p=>{const g=this.resolveTriangleIndex(p);as(a,g*3,r,o)}:p=>{as(a,p*3,r,o)},h=Qn.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const g=t.resolveTriangleIndex(p);as(h,g*3,u,d)}:p=>{as(h,p*3,u,d)};if(n){if(!(t instanceof Zf))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(g,m,v,M,x,y,w,S)=>{for(let E=v,b=v+M;E<b;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=g,T=g+m;A<T;A++)if(l(A),a.needsUpdate=!0,n(a,h,A,E,x,y,w,S))return!0}return!1};if(s){const g=s;s=function(m,v,M,x,y,w,S,E){return g(m,v,M,x,y,w,S,E)?!0:p(m,v,M,x,y,w,S,E)}}else s=p}return super.bvhcast(t,e,{intersectsRanges:s})}intersectsBox(t,e){return Ud.set(t.min,t.max,e),Ud.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Ud.intersectsBox(i),intersectsTriangle:i=>Ud.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},s={},n=0,a=1/0){return(this.indirect?jC:GC)(this,t,e,i,s,n,a)}closestPointToPoint(t,e={},i=0,s=1/0){return EC(this,t,e,i,s)}}class Pa{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ia;static install(){if(Pa.installed)return;Pa.installed=!0;const t=dt.prototype.raycast;dt.prototype.raycast=function(e,i){const s=Pa.treeOf(this,e);s!==null&&(s?s.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,s=i?.attributes.position;if(!(s instanceof ve)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const n=i.index;if((n?n.count:s.count)/3<Pa.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const a=Pa.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(a))return null;const r=Pa.trees.get(i);if(r){if(!r.bvh)return;if(r.position===s&&r.positionVersion===s.version&&r.index===n&&r.indexVersion===(n?.version??0))return r.bvh;Pa.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const o=new Zf(i,{indirect:!0});return Pa.trees.set(i,{bvh:o,position:s,positionVersion:s.version,index:n,indexVersion:n?.version??0}),o}}function QC(c,t){return JSON.stringify(c.cloudLayers)===JSON.stringify(t.cloudLayers)&&c.cloudCover===t.cloudCover&&c.cloudDarkness===t.cloudDarkness&&c.cloudBaseM===t.cloudBaseM&&c.highCloudCover===t.highCloudCover&&c.iceCrystalAlignment===t.iceCrystalAlignment&&c.rareIceCrystals===t.rareIceCrystals&&c.lowerCloudCover===t.lowerCloudCover&&c.relativeHumidity===t.relativeHumidity&&c.visibilityKm===t.visibilityKm&&c.precipitationType===t.precipitationType&&c.precipitationIntensity===t.precipitationIntensity&&c.precipitationAmount===t.precipitationAmount&&c.windDirectionDeg===t.windDirectionDeg&&c.windSpeed===t.windSpeed&&c.storm===t.storm}const Bd=900,Xp=1,b2=4,Kp=5,Hd=.5,Gd=le.GROUND_RADIUS_M;function S2(c){return le.groundRadiusFor(c)}const Yp=.5,$p=850,Vd=.03,t6=.015,Ii=850,Jc=300,dr=120,e6=700,qp=.03,i6=3.5,Wd=20,Zp=.04,s6=.26,E2=4,Jp=1.5,A2=-1,n6=.01,ff=-4,a6=2,r6=20,Xd=2600,o6=.97,c6=.38,Dh=ff,l6=8,h6=2,_2=1500,u6=.7,d6=.3,f6=.32,p6=.65,T2=2.4,m6=.9,g6=400,v6=[0,45,90,135,180,225,270,315],M6=2,y6=16,R2=4e3,D2=880,Kd=40,I2=60,x6=10,P2=1,w6=le.REBUILD_DISTANCE_M,C2=.265,O2=[[0,0],...Array.from({length:8},(c,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*C2,Math.sin(e)*C2]})],jp=700,Qp=250/Mx,b6=12,L2=5,tm=6,Lo=[.92,.92,.95],em=[.15,.15,.19],im={snow:{fallSpeedMPerS:2,size:.3,color:new at(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new at(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},nl=0,sm=0,S6=150,nm=3e3,Ih=20,E6=15,N2=nl,A6=40,k2=1,_6=9;function am(c){return k2+(_6-k2)*c}const F2=new at(.75,.82,.92),T6=10,R6=.5;function U2(c){return Ca(c/T6,R6,1)}const No=200,z2=.18,B2=.32,D6=.35,H2=new at(.85,.9,.98),G2=5,V2=.85,W2=.01;function I6(c,t,e=1){return Math.round(c*(W2+(1-W2)*t)*e)}function P6(c,t){return JSON.stringify(c.cloudLayers)===JSON.stringify(t.cloudLayers)&&c.cloudCover===t.cloudCover&&c.cloudDarkness===t.cloudDarkness&&c.cloudBaseM===t.cloudBaseM&&c.highCloudCover===t.highCloudCover&&c.iceCrystalAlignment===t.iceCrystalAlignment&&c.lowerCloudCover===t.lowerCloudCover}const X2=230,K2=.7,Y2=.05,C6=.6,O6=.7,L6=.15,$2=.35,N6=3,k6=1/12,F6=.5,Ta=new at(.82,.86,1),U6=2500,z6=1.6,rm=15,B6={Venus:new at(1,.96,.85),Mars:new at(1,.55,.4),Jupiter:new at(.95,.87,.72),Saturn:new at(.92,.86,.68)};class ct{renderer;scene=new zn;phenomena=new xn(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new He;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=e===void 0?void 0:setTimeout(s,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(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(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+R2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),R2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new Q;decorModelProvider=new Ib;decorModelToken=0;decorModelCredits=new Map;emitterLights=new an(this.scene,()=>this.relativeScale,{halfExtentM:dr,depthHalfRangeM:Jc,biasM:qp,normalBiasM:Zp,mapSize:1024});bodySystem=new Dt(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??ct.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ct.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 kf(16777215,0);celestialLightTarget=new _i;skyLight=new W_(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new rf;weather=oS;observerElevationM=0;siteElevationM=0;air=new Ks;groundRadius=Gd;terrainRadius=Gd;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new _;cloudFieldOffset=new _;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new _;rainLastVerticalFacing=-1;rainViewportSize=new Q;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new kf(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new _;sunVisible=!1;lensFlareScratch=new _;sunOcclusionRaycaster=new rf;sunOcclusionDirectionScratch=new _;sunOcclusionRightScratch=new _;sunOcclusionUpScratch=new _;ufoOcclusionRaycaster=new rf;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Pe.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Eu;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=hw()){jh.install(),Qh.install(),Pa.install(),this.renderer=new aI({canvas:t,antialias:!0}),this.resolution=new Ze(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Gh,this.camera=new Ns(60,t.width/Math.max(t.height,1),.1,Bd*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-dr,this.celestialLight.shadow.camera.right=dr,this.celestialLight.shadow.camera.top=dr,this.celestialLight.shadow.camera.bottom=-dr,this.celestialLight.shadow.camera.near=Ii-Jc,this.celestialLight.shadow.camera.far=Ii+Jc,this.celestialLight.shadow.bias=-qp/(2*Jc),this.celestialLight.shadow.normalBias=Zp,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Ta),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 ue(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.lastBodies&&this.setBodies(...this.lastBodies),this.render()}lastBodies;setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*Qp,0,t.z*Qp);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Ve,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ve;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ve,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(S2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Gd),this.camera.far=Math.max(Bd*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseStatedElevationM=t.elevationM,this.poseAltitudeM=t.altitudeM,this.poseElevationM=t.altitudeM!==void 0?Math.max(0,t.altitudeM-this.siteElevationM-this.groundYUnder(0,0)):t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.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(t){this.observerRoute=t,this.decorTerrainRadiusM=ct.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return le.decorReachFor(t,e)}placeTerrain(t,e,i,s){const n=(a,r)=>{const o=re(r.lat,r.lng,t,e);a.position.x=o.x-i,a.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 a=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=a}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=P2+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=le.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,s=t.lat+e.distanceM*Math.cos(i)/111320,n=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),a=this.lookPatchAsked;if(a){const l=re(s,n,a.lat,a.lng);if(Math.hypot(l.x,l.z)<a.radiusM*ct.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:s,lng:n,radiusM:e.radiusM};const r=++this.lookPatchToken,o=this.terrainProviders;Ap(s,n,{elevation:o.elevation,imagery:o.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(r!==this.lookPatchToken||this.terrainProviders!==o||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=ct.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:s,lng:n},radiusM:e.radiusM};const u=re(s,n,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const d=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),ct.TERRAIN_PATIENCE_MS)}return}const u=s.nearest(t,e);u&&(t=u.lat,e=u.lng,n=u.radiusM)}const a=n??Math.max(le.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-a)<a*.1){const{x:u,z:d}=re(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<w6*(a/Gd))return}const r=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(re(t,e,o.lat,o.lng).x,re(t,e,o.lat,o.lng).z)<=r||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=a;const h=++this.terrainBuildToken;this.awaitArrival(Ap(t,e,this.terrainProviders,a,{route:this.observerRoute}),ct.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,M=v?re(t,e,v.lat,v.lng):void 0;m&&M&&Math.hypot(M.x,M.z)<=r&&(u.position.y=m.position.y+this.groundYOfPatch(m,M.x,M.z)),m&&v&&M&&Math.hypot(M.x,M.z)<=r?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=P2,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,a),this.buildWater(t,e,a,p,g),this.buildRailways(t,e,a),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,a,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,s,n){s.geometry.computeBoundingBox();const a=s.position.y+(s.geometry.boundingBox?.min.y??0),r=this.camera.position.y-a,o=this.skyEventReachM({lat:t,lng:e}),l=le.farRingRadiusFor(this.weather.visibilityKm);if(!le.needsFarRing(i,r,o,l)){this.dropFarRing();return}if(this.farRing&&this.farRingRadiusM===l){const{x:g,z:m}=re(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(g,m)<i*ct.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,u=h?.farRingOf?.(t,e);if(h&&!u){this.dropFarRing();return}const d=u?.radiusM??l,f=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Ap(t,e,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*ct.FAR_RING_OPEN_SHARE,referenceElevationM:n,gridSize:le.farRingGridFor(d)}),ct.TERRAIN_PATIENCE_MS).then(({mesh:g})=>{if(f!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(g);return}this.dropFarRing(),this.farRingToken=f,g.renderOrder=ct.FAR_RING_RENDER_ORDER,g.position.y=s.position.y-ct.FAR_RING_DROP_M;const m=g.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:g,origin:{lat:t,lng:e}},this.farRingRadiusM=d,this.applyGroundDepthWrite(),this.scene.add(g),g.position.x=s.position.x,g.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},g=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",g))}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(t,e,i){if(this.grassReference){const a=re(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(a.x,a.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const s=re(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const s=t.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),a=()=>{const r=Math.min(1,(performance.now()-n)/ct.TERRAIN_CROSSFADE_MS);if(s.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(a);return}s.polygonOffset=!1,s.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(a)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=le.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const s=this.terrainProviders.roads;if(!s||i>ct.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===t&&n.lng===e&&n.radiusM===i){this.drapeRoads(n.ways,t,e,s.contemporary);return}n&&Math.hypot(re(t,e,n.lat,n.lng).x,re(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,t,e,s.contemporary),this.awaitArrival(s.getRoads(tu(t,e,i)),ct.ROADS_PATIENCE_MS).then(a=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:a},this.drapeRoads(a,t,e,s.contemporary))}).catch(a=>{console.warn("Roads unavailable, drawing none:",a)})}buildWater(t,e,i,s,n){const a=this.terrainProviders.water;if(!a||i>ct.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,t,e,i),ct.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const r=this.waterSurfaces;if(r&&r.lat===t&&r.lng===e&&r.radiusM===i){this.drapeWater(r.surfaces,t,e,i);return}r&&Math.hypot(re(t,e,r.lat,r.lng).x,re(t,e,r.lat,r.lng).z)<=r.radiusM&&this.drapeWater(r.surfaces,t,e,i),this.awaitArrival((n??a.getWater(tu(t,e,i))).then(o=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:o},this.drapeWater(o,t,e,i)}),ct.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(t,e,i,s){if(t.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.set(t,e,i,(r,o)=>this.groundYOfPatch(a,r,o),s,this.patchSpacingM(a)),Ys.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Ht(async()=>{const{WaterSystem:t}=await import("./WaterSystem-CTGGh-Y-.js");return{WaterSystem:t}},__vite__mapDeps([28,2,1,3,4,5,6,7]),import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const s=this.terrainProviders.railways;if(!s||i>ct.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===t&&n.lng===e&&n.radiusM===i){this.drapeRailways(n.lines,t,e,i);return}n&&Math.hypot(re(t,e,n.lat,n.lng).x,re(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,t,e,i),this.awaitArrival(s.getRailways(tu(t,e,i)).then(a=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:a},this.drapeRailways(a,t,e,i)}),ct.ROADS_PATIENCE_MS).catch(a=>{console.warn("Railways unavailable, drawing none:",a)})}async drapeRailways(t,e,i,s){if(!this.railwaySystem&&!t.some(r=>r.level>=0))return;const n=await this.loadRailwaySystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.setGroundSpacing(this.patchSpacingM(a)),n.set(t,e,i,(r,o)=>this.groundYOfPatch(a,r,o),s),Ys.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Ht(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-Dm-PbG_D.js");return{RailwaySystem:t}},__vite__mapDeps([29,2,1,3,4,5,6,7]),import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=Ht(async()=>{const{TraceSystem:t}=await import("./TraceSystem-Cl5kzaIr.js");return{TraceSystem:t}},__vite__mapDeps([30,2,1,3,4,5,6,7]),import.meta.url).then(({TraceSystem:t})=>{const e=new t(Kp);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(s,n)=>this.groundYOfPatch(e,s,n)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ht.naturalSize(s.kind,s.floors),a=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(a),alongZ:-Math.cos(a),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?re(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);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(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,a=i.z-s.northM,r=this.roadSystem.atKerb(n,a);(r.x!==n||r.z!==a)&&this.lampNudges.set(s.id,{eastM:r.x-n,northM:-(r.z-a)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,s)=>{const n=e[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const a=new Set([...Object.keys(i),...Object.keys(n)]);for(const r of a)if(!(r==="eastM"||r==="northM"||r==="track")&&i[r]!==n[r])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const s=this.wallsOf(t,e.lat,e.lng),n=this.roadWalls;n?.lat===e.lat&&n.lng===e.lng&&n.walls.length===s.length&&n.walls.every((r,o)=>r.what===s[o].what&&Math.hypot(r.x-s[o].x,r.z-s[o].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const s=this.decorOriginInRoads(e,i);return t.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(t,e,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(t,e,i,(a,r)=>this.groundYOfPatch(n,a,r),s,this.terrainRadius,new yi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,s=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?hs.LENS_K:hs.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(QC(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!P6(e,t),s=e.precipitationType!==t.precipitationType,n=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;e.visibilityKm!==t.visibilityKm&&this.terrainMesh&&this.terrainMeshOrigin&&le.farRingRadiusFor(t.visibilityKm)!==le.farRingRadiusFor(e.visibilityKm)&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||s||n)&&this.restateHaze(),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=t.storm&&t.cloudDarkness>=F6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(ct.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=ct.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=ct.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ht.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,l6);for(const i of t){const s=ht.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,s,e.indexOf(i)<h6,i.lamp),i.model&&i.id.startsWith(Ye.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=ct.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=Ht(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-O_yvjart.js");return{ContrailSystem:t}},__vite__mapDeps([31,32,1,2,3,4,5,6,7]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,s=ct.CONTRAIL_SCATTERING,n=this.skyLight.color,a=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(e&&i){const r=ln.litFraction(e.sunElevationDeg,e.heightM);if(r>0){const o=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ne.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)a[h]+=s*l*o[h]*r}}return a}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let s=!1;const n=new Set;for(const a of zg){const r=Rr.of(a);n.add(r.key);const o=Rr.eventsOf(t,r);let l=this.skyEventLayers.get(r.key);if(l?.kind!==r&&l&&(this.disposeSkyEventLayer(r.key,l),l=void 0),!(!l&&o.length===0)){if(!l)l={kind:r,events:o},this.skyEventLayers.set(r.key,l);else if(l.events===o)continue;l.events=o,s||=r.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[a,r]of this.skyEventLayers)n.has(a)||(this.disposeSkyEventLayer(a,r),s||=r.kind.reachM!==void 0);s&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,s=new Set;for(const n of e){const a=i+n.key,{x:r,y:o,z:l}=mi(n.position.altitudeDeg,n.position.azimuthDeg,Ii),[h,u,d]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(a,r,o,l,[h*n.fade,u*n.fade,d*n.fade],0,ct.POINT_VEIL_HOLD_DEG),s.add(a)}for(const n of[...this.glareSprites.keys()])n.startsWith(i)&&!s.has(n)&&this.disposeGlare(n)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},s=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):lf(-90,this.instrumentMagnitudeGain);let a;for(const[r,o]of this.skyEventLayers)o.simulation&&(a??={observer:i,date:s,magnitudeLimit:n,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Ve)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Ve)*this.weather.windSpeed}},o.simulation.update(o.events,this.decorTime,{...a,lightFrom:l=>this.skyEventLight(r,l),glareFrom:l=>this.skyEventGlare(r,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?mi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}directionToDecor(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=new ze().setFromObject(e);if(i.isEmpty())return;const s=i.getCenter(new _),n=this.camera.getWorldPosition(new _),a=s.x-n.x,r=n.z-s.z,o=s.y-n.y,l=Math.hypot(a,r);if(!(l===0&&o===0))return{azimuthDeg:(Math.atan2(a,r)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(o,l)*180/Math.PI}}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),s=this.bodyEastScale,n=this.farRing?.mesh??(this.terrainMesh&&this.terrainRadius>le.ROADS_MAX_RADIUS_M?this.terrainMesh:void 0),a=n?(r,o)=>le.curvatureDropM(Math.hypot(r-n.position.x,o-n.position.z)):void 0;return{heightAt:(r,o)=>this.groundYUnder(t+r*s,e-o)-i,...a?{dropAt:(r,o)=>a(t+r*s,e-o)-a(t,e)}:{}}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Ve)/Math.cos(t.lat*Ve)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(a=>a.id),s=[],n){this.lastBodies=[t,e,i,s,n];const{x:a,z:r}=this.bodyOrigin,o=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:a,originZ:r,originGroundY:this.groundYUnder(a,r),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y),daylight:this.daylightOnBodies()},e,o?Object.assign((u,d)=>o.relativeOfLuminance(u,d),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}daylightOnBodies(){const t=this.celestialLight.color,e=this.celestialLight.intensity,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity;return{towardSun:this.lightDirection,sun:[t.r*e,t.g*e,t.b*e],round:[(i.r+s.r)/2*n,(i.g+s.g)/2*n,(i.b+s.b)/2*n],sky:[i.r*n,i.g*n,i.b*n],ground:[s.r*n,s.g*n,s.b*n]}}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity,a=(r,o,l)=>(r*e+(o+l)/2*n)/Math.PI;return[a(t.r,i.r,s.r),a(t.g,i.g,s.g),a(t.b,i.b,s.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,s=t.credit??e?.credit;if(!(!i||!s))return{scene:await Op(i),credit:s,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(mf(t))||!ht.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const s=Pb(i.scene);s.traverse(n=>{n instanceof dt&&(n.userData.sharedModel=!0)}),ht.applyModelParameters(s,t.modelParameters,i.bindings),ht.applyModel(e,t,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(t.id,i.credit)}mirrors=new yn;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const s=i?fS[t.kind]:mf(t);if(!(!s||!ht.usesModel(t)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,a=this.modelUrl(s)??n?.url,r=s.credit??n?.credit;if(!a||!r)return;const o=i||t.kind==="tree"?await this.standInScene(a):await Op(a);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(Dt.glaze(o),Ys.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:r,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${t.id}":`,n)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=Op(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Ys.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const s=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?re(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},n=this.decorObjects.find(p=>p.observerSide!==void 0&&Hl(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.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 a={x:0,z:0};let r=0,o;if(n){const p=ga(n,i),g=ht.occupantView(n,p.headingDeg),m=-(p.headingDeg??0)*Ve,v=g.x*Math.cos(m)+g.z*Math.sin(m),M=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+s.x,y=-p.northM+s.z;a.x=-(x+v),a.z=-(y+M),this.camera.position.y=this.groundYUnder(x,y)+g.eyeY,o=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ve,-(g.headingDeg+this.indoorLookYawDeg)*Ve,0,"YXZ")}this.bodyOrigin={x:s.x+a.x,z:s.z+a.z};const l=this.findCabin(i,s,a);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,s,a);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(g=>g.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseAltitudeM!==void 0&&(this.poseElevationM=Math.max(0,this.poseAltitudeM-this.siteElevationM-this.groundYUnder(0,0))),this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const g=this.decorGroups.get(p.id);if(!g)continue;const m=ga(p,i),v=this.lampNudges.get(p.id),M=m.eastM+(v?.eastM??0)+s.x+a.x,x=-(m.northM+(v?.northM??0))+s.z+a.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${h}`;if(g.userData.footprintKey!==w){if(p.kind==="wire"){const C=ht.wireGround(p,M,x,m.headingDeg,(N,O)=>this.groundYUnder(N,O));g.userData.footprintGroundY=C.startY,ht.shearWire(g,ht.sizeOf(p).lengthM,C.dropM)}else if(p.kind==="crossing"){const C=this.groundYUnder(M,x),N=-(m.headingDeg??0)*Ve,O=Math.cos(N),k=Math.sin(N);g.userData.footprintGroundY=C,Ee.drape(ht.bodyOf(g),(B,X)=>this.groundYUnder(M+B*O+X*k,x-B*k+X*O)-C)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,M,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=w}const E=m.altitudeM>ct.AIRBORNE_M&&Math.hypot(M,x)<ct.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseStatedElevationM:g.userData.footprintGroundY,b=p.id.startsWith(Ye.ID_PREFIX)?ct.trafficHeight(m.altitudeM,g.userData.footprintGroundY):E+m.altitudeM;if(g.position.set(M,b,x),p.kind==="crop"){const C=Math.hypot(M,x);g.visible=C<=S6}const A=this.decorPresence.get(p.id),T=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(g.visible=!T);const D=this.decorSunlight.get(p.id);D&&!T&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*Ve);const I=pS(p,i);if(I!==void 0&&ct.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const C=this.terrainMesh,N=[C?.geometry.uuid,M-(C?.position.x??0),x-(C?.position.z??0),g.position.y-(C?.position.y??0),m.headingDeg,m.altitudeM].map(O=>typeof O=="number"?O.toFixed(4):O).join(":");g.userData.cropGroundKey!==N&&(ht.fitCropToGround(g,(O,k)=>this.groundYUnder(O,k)+m.altitudeM),g.userData.cropGroundKey=N)}if(!T){const C=g.position.distanceTo(this.camera.position);r=Math.max(r,C),C<ct.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(n&&o!==void 0){const p=this.decorGroups.get(n.id);p&&(this.camera.position.y=p.position.y+o)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(Bd*1.2,this.groundRadius*2.5,r*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let s=i;for(const n of this.terraces){const a=t-n.x,r=e-n.z,o=a*n.cos-r*n.sin,l=a*n.sin+r*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(l)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),u=h*h*(3-2*h);s=Math.max(s,u*n.levelY+(1-u)*Math.min(n.levelY,i))}}return s}placeTerraces(t,e,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const a=this.decorGroups.get(n.id);if(!a)continue;const r=ga(n,t),o=r.eastM+e.x+i.x,l=-r.northM+e.z+i.z,h=ht.sizeOf(n),u=-(r.headingDeg??0)*Ve,d=Math.cos(u),f=Math.sin(u),p=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(l-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${r.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;a.position.set(o,0,l),r.headingDeg!==void 0&&(a.rotation.y=u),a.userData.terraceKey!==p&&(a.userData.terraceLevelY=ht.fitTerrace(a,n,(g,m)=>this.terrainYUnder(o+g*d+m*f,l-g*f+m*d)),a.userData.terraceKey=p),this.terraces.push({x:o,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:a.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):sm}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((t%360+360)%360/(360/s))%s;let a=this.horizonByBearing[n];return Number.isNaN(a)&&(a=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),a}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+ct.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=t*Math.PI/180,n=Math.sin(s),a=-Math.cos(s),r=this.farRing?.mesh,o=Math.max(this.terrainRadius,r?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=o;u=Math.max(u+l,u*1.02)){const d=i.x+n*u,f=i.z+a*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):r.position.y+this.groundYOfPatch(r,d-r.position.x,f-r.position.z);h=Math.max(h,Math.atan2(p-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const s=t.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return sm;const a=s.getX(0),r=s.getX(n-1),o=s.getZ(0),l=s.getZ((n-1)*n),h=Ca((e-a)/(r-a)*(n-1),0,n-1),u=Ca((i-o)/(l-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(u))return sm;const d=Math.min(Math.floor(h),n-2),f=Math.min(Math.floor(u),n-2),p=h-d,g=u-f,m=(w,S)=>s.getY(w*n+S),v=m(f,d),M=m(f,d+1),x=m(f+1,d),y=m(f+1,d+1);return p+g<=1?v+(M-v)*p+(x-v)*g:y+(x-y)*(1-p)+(M-y)*(1-g)}groundUnderFootprint(t,e,i,s,n=0){return ht.groundUnderFootprint(t,e,i,s,(a,r)=>this.groundYUnder(a,r),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;poseStatedElevationM=0;poseAltitudeM;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=An.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,s,n){const a=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:s??t.iso,autoExposure:t.autoExposure===!0&&s===void 0,maxIso:t.maxIso,metering:n??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(a)!==JSON.stringify(this.medium)&&(this.medium=a,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?An.NONE:this.perception??An.NONE;if(Si.uColorVision.value.set(...i.colorMatrix),Si.uContrast.value=i.contrastGain,!t){Si.uMedium.value=0;return}const s=t.kind==="sensor"&&t.development==="computational";Si.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:s?4:3;const n=t.autoExposure?this.frameLight:void 0,a=t.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,r=a===void 0?void 0:this.meteredBodies(),o=a===void 0?void 0:a+r.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=o!==void 0&&o>0?1/(e*o):void 0;h!==void 0&&t.metering==="highlights"&&r.brightest>0&&(h=Math.min(h,ct.HIGHLIGHT_KEPT_AT/(.18*e*r.brightest))),h!==void 0&&t.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,ct.ZONE_KEPT_AT/(.18*e*n.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Si.uMediumExposure.value=u,Si.uPhoneStrength.value=s&&o!==void 0&&o>0?la.strengthFor(la.MID_GREY*u*e*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 t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),n=new _;let a=0,r=0;for(const{position:o,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(t),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(a+=l*h,r=Math.max(r,l*Math.min(1,h/(ct.HIGHLIGHT_SHARE*s))**2));return{mean:a/s,brightest:r}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new Q;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ht.setLights(n,s.lights,t,n.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const a=this.decorGroups.get(s.id);if(!a)continue;const r=s.kind==="vehicle"?bx(s,t):void 0,o=r!==void 0?mm.lamps(r):n1(s,t,this.lastAstronomy?.sun.altitudeDeg);ht.setLit(a,s.kind,o,this.relativeScale,s.lamp);const l=this.streetlightLights.get(s.id);l&&(l.visible=o),r!==void 0&&(this.headlightSettings.set(s.id,r),this.aimDecorBeam(s,a,r))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=Ht(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-7mtgTwud.js");return{HeadlightSystem:t}},__vite__mapDeps([33,5,1,2,3,4,6,7]),import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const s=new _(0,0,-1).transformDirection(e.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ht.sizeOf(t).lengthM,a=e.getWorldPosition(new _).addScaledVector(s,n/2-d6);a.y+=u6;const r=ht.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,a,s,r*f6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?mm.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,s=new _(Math.sin(i),0,-Math.cos(i)),n=new _(s.x*T2,this.camera.position.y-m6,s.z*T2);this.headlightSystem.aim("observer",e,n,s,p6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,s){const n=ht.bodyOf(e),a=n.children.find(l=>l.userData.emissive);if(!a)return;const r=_2*ht.lampShare(s),o=new eb(16764006,r*this.relativeScale,g6);s?.colorTemperatureK&&o.color.setRGB(...ht.lampHue(s)),o.userData.candela=r,o.position.copy(a.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,e.add(o),this.streetlightLights.set(t,o)}applyWindowGlow(){const t=this.lastAstronomy;ht.setLitWindowShare(t?Is.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=a=>{const r=En.luminanceOf(a);if(!(r>0))return[0,0,0];const o=zt.relativeOfResponse(r)/r;return[a[0]*o,a[1]*o,a[2]*o]},s=i(t.zenith),n=i(t.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Yi.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,E2,new at(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<ff){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=E2/Ii*(180/Math.PI),s=i/e.sunRadiusDeg,n=mi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),a=mi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),r=Math.acos(Ca(n.x*a.x+n.y*a.y+n.z*a.z,-1,1)),o=r>1e-9?Ca(e.separationDeg*s*Ve/r,0,2):0,l=Math.sin(r),[h,u]=r>1e-9?[Math.sin((1-o)*r)/l,Math.sin(o*r)/l]:[1,0],d={x:n.x*h+a.x*u,y:n.y*h+a.y*u,z:n.z*h+a.z*u},f=e.moonRadiusDeg*s;this.eclipseDiscs={sun:new _(n.x,n.y,n.z).normalize(),moon:new _(d.x,d.y,d.z).normalize(),sunRadiusRad:i*Ve,moonRadiusRad:f*Ve};const p=.01,g=(M,x)=>mi(t.sun.altitudeDeg+M,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:s,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Sl(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??ct.relativeSkyOf(Ug(t.sun.altitudeDeg),this.relativeScale),i=e,s=this.lightUnderClouds(t),n=a=>s?[0,1,2].map(r=>a[r]*s.through+s.radiance[r]*(1-s.through)):[a[0],a[1],a[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(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Vt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const a of this.streetlightLights.values())a.intensity=(a.userData.candela??_2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=(this.hazeOpticalDepth()??Pt.DEFAULT_AEROSOL_OPTICAL_DEPTH)*Pt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),n=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ne.aureoleScale(i,Ne.airMass(t.altitudeDeg))*s,r=Ne.coronaScale(n),o=Ne.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),r.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new K1,this.celestialGroup.add(this.lunarDiffraction.object));const h=Ne.profile(Ne.HAZE_COARSE_MODE),u=Ne.profile(Ne.CLOUD_DROPLETS),d=VI(t.altitudeDeg),f=new Float32Array(Ne.STEPS*3);let p=0;for(let M=0;M<Ne.STEPS;M++){const x=M*3,y=[0,1,2].map(S=>o*d[S]*(a*h[x+S]+r*u[x+S])),w=En.shown(y,En.luminanceOf(y),(S,E)=>e.relativeOfLuminance(S,E));f.set(w,x),p=Math.max(p,En.response(w))}const{x:g,y:m,z:v}=mi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(p>1/200?{x:g,y:m,z:v}:void 0,f)}applyAir(){this.scene.fog instanceof vo||(this.scene.fog=new vo),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+e,Math.hypot(t-s.x,e-s.y,i-s.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}hazeOpticalDepth(){return Ks.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=Ks.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=Zo.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,s]=this.air.transmittance(t,t,ct.UMBRA_PATH_M),n=.2126*e+.7152*i+.0722*s;return n>0?[(.4124*e+.3576*i+.1805*s)/n,1,(.0193*e+.1192*i+.9505*s)/n]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:Yi.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Yi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?y6:M6),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new yP($p),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):lf(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,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")}decorSkyPoint(t){const e=this.decorGroups.get(t);if(!e?.visible)return;const i=new _().copy(e.position).sub(this.camera.position),s=i.length();if(s===0)return;const n=(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,a=Math.asin(i.y/s)*180/Math.PI;return{sky:{azimuthDeg:n,altitudeDeg:a,distanceKm:s/1e3},altitudeM:this.siteElevationM+e.position.y}}flightScreenPoint(t){const e=Ye.declaredIdOf(t);if(e!==void 0){const s=this.decorGroups.get(e);if(!s?.visible)return;const n=new _().copy(s.position).sub(this.camera.position),a=this.screenPointOf(n.clone().normalize());return a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY,n.length())?a:void 0}const i=`${Ye.ID_PREFIX}${t}-`;for(const[s,n]of this.decorGroups){if(!n.visible||!s.startsWith(i))continue;const a=this.screenPointOf(new _().copy(n.position).sub(this.camera.position).normalize());if(a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY))return a}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,s=Math.cos(Vd*this.camera.fov*Math.PI/180);let n,a=s;const r=new _;for(const[o,l]of this.decorGroups){if(!l.visible||!o.startsWith(Ye.ID_PREFIX))continue;r.copy(l.position).sub(this.camera.position).normalize();const h=r.dot(i);h>a&&(a=h,n=o)}return n&&!this.groundHides(t,e)?n:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(Vd*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(t,e)?void 0:s}updateCelestialLight(t,e){const i=this.relativeScale,s=t.sun.altitudeDeg>=Dh,n=!s&&t.moon.altitudeDeg>=Dh,a=s?t.sun:t.moon,r=[0,0,0],o=Math.max(0,Math.sin(Math.max(a.altitudeDeg,0)*Ve)),l=this.siteElevationM+this.observerElevationM;let h=a,u=s||n?s2.directFraction(a.altitudeDeg,l):0;s&&u<=0&&t.moon.altitudeDeg>=Dh&&(h=t.moon,u=s2.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ve)),f=s||n?this.cloudTransmission(a):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(s||n){const S=Ne.illuminanceOf(a.magnitude)*i,E=this.air.transmittanceFromSpace(l,a.altitudeDeg);for(let D=0;D<3;D++)m[D]=S*E[D]*g*o,this.cloudBeam[D]=S*E[D];const{x:b,y:A,z:T}=mi(a.altitudeDeg,a.azimuthDeg,1);if(this.cloudBeamDirection.set(b,A,T),u>0){const D=Ne.illuminanceOf(h.magnitude)*i,I=h===a?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),C=h===a?f:this.cloudTransmission(h);for(let N=0;N<3;N++)r[N]=D*I[N]*C*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),E=e.skyIrradiance,b=[0,1,2].map(T=>E[T]*S+m[T]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const A=Jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(b[0]+r[0]*d),A*(b[1]+r[1]*d),A*(b[2]+r[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[r[0],r[1],r[2]]:[0,0,0],!s&&!n||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:x,z:y}=mi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,x,y),this.celestialLight.shadow.normalBias=Zp*Ca(x/s6,.1,1),this.placeShadowFrustum();const w=Math.max(r[0],r[1],r[2],1e-30);this.celestialLight.color.setRGB(r[0]/w,r[1]/w,r[2]/w),this.celestialLight.intensity=w,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,s=[0,0,0];if(i){const n=ln.litFraction(e.sunElevationDeg,e.heightM);if(n>0){const a=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),r=Ne.illuminanceOf(i.magnitude)*this.relativeScale,o=e.heightM>=ct.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)s[l]=Math.max(0,r*a[l]*n*o-this.sceneSunBeam[l])}}t.traverse(n=>{const a=n.material;if(!(a instanceof sa||a instanceof _r)||n.userData.emissive)return;a.map&&!a.emissiveMap&&(a.emissiveMap=a.map,a.needsUpdate=!0);const r=ct.MEAN_COSINE/Math.PI;a.emissive.setRGB(a.color.r*s[0]*r,a.color.g*s[1]*r,a.color.b*s[2]*r)})}lightDirection=new _(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,s=this.shadowAxisX.crossVectors(this.shadowUp,t);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(t,s).normalize(),a=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),r=l=>{const h=a.dot(l)/i;return(h-Math.round(h))*i},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,r(s)).addScaledVector(n,r(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,s=i6;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=Wd+5,i.near=this.shadowLightDistanceM-Wd,i.far=this.shadowLightDistanceM+Wd,i.updateProjectionMatrix(),e.bias=-.004/(2*Wd),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const a=n;a.isMeshStandardMaterial&&a.envMapIntensity!==ct.CABIN_SKY_SHARE&&(a.envMapIntensity=ct.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(e6,Math.max(dr,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,s=i.camera;s.left=-e,s.right=e,s.top=e,s.bottom=-e;const n=Math.max(Jc,e*(Jc/dr));this.shadowLightDistanceM=Math.max(Ii,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-qp/(2*n);const a=e>2*dr?2048:1024;i.mapSize.x!==a&&(i.mapSize.set(a,a),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=dr;shadowLightDistanceM=Ii;shadowUp=new _(0,1,0);shadowAxisX=new _;shadowAxisY=new _;shadowWorld=new _;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const s=i*Ve,n=Math.sin(s)*Math.cos(s)*2;for(let a=0;a<360;a+=60)t+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:a}),e+=n}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new _(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/zt.semiSaturation(zt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new ws,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:n,y:a,z:r}=mi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new _(n,a,r),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=Ts.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=Et.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return lf(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const s=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,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 t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.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 t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+ct.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const a of t){const r=e.get(a)?.currentProgram;(!r||r.isReady())&&t.delete(a)}t.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.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await Ht(async()=>{const{ControlPasses:e}=await import("./ControlPasses-BaglOE-7.js");return{ControlPasses:e}},__vite__mapDeps([34,1,2,3,4,5,6,7]),import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>ct.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;cabinDecor(){return this.cabinGroups}enclosingDecor(){const t=this.camera.getWorldPosition(this.enclosingEye);return this.decorObjects.filter(e=>e.kind==="aircraft"||e.kind==="vehicle").map(e=>this.decorGroups.get(e.id)).filter(e=>e!==void 0&&this.enclosingBox.setFromObject(e).containsPoint(t))}enclosingEye=new _;enclosingBox=new ze;cabinGroups=[];findCabin(t,e,i){const s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Hl(n.kind))continue;const a=this.decorGroups.get(n.id);if(!a)continue;const r=ga(n,t),o=r.eastM+e.x+i.x,l=-r.northM+e.z+i.z,h=ht.sizeOf(n),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,l)<u&&Math.abs(r.altitudeM-this.poseStatedElevationM-1.6)<u&&s.push(a)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Ys(this.renderer);const e=["sun","moon"].flatMap(l=>this.bodyMeshes.get(l)??[]),i=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...e,...[...this.glareSprites.values()].map(l=>l.mesh),...this.bodySystem.group.children.filter(l=>l.name.startsWith("body-speck:"))],s=[...this.starTiers.map(l=>l.points),...[...this.bodyMeshes.values()].filter(l=>l instanceof Cn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(l=>l!==void 0),...this.cabinDecor(),...this.enclosingDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(l=>l.name.startsWith("body:")),...[this.meteorSystem?.object].filter(l=>l!==void 0),...[...this.skyEventLayers.values()].filter(l=>l.simulation?.hiddenFromEye).map(l=>l.simulation.object)],n=this.relativeScale,a=this.sceneVersion,r=this.recordingTimeMs,o=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,i,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],a,s,l=>this.measureSurroundings(l,n,a,r),t?0:Ys.REFRESH_MS);o===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()}))},o))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,ct.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ml,this.framePhotograph={texture:t,scale:e,atMs:s};const a=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>mi(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,a,r=>{const o=p=>p.map(g=>g/e);if(![...r.up,...r.down,r.logAverage].every(Number.isFinite)){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}const l=this.surroundings,h={up:o(r.up),down:o(r.down)},u=(p,g)=>p.some((m,v)=>Math.abs(m-g[v])>.03*Math.max(Math.abs(m),Math.abs(g[v]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(ct.adaptingLuminance(Math.exp(r.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Dh?t.sun:t.moon.altitudeDeg>=Dh?t.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*s,e.up[1]*s,e.up[2]*s]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new ca;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?mi(e.altitudeDeg,e.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??ct.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,n=>{const a={mean:n.mean/t.scale,brightest:n.brightest/t.scale};if(!Number.isFinite(a.mean)||!Number.isFinite(a.brightest))return;const r=this.frameLight,o=t.atMs,l=r?o-r.atMs:1/0,h=l<0||l>ct.EXPOSURE_JUMP_MS,u=h||l===0&&r?.jumped?1:1-Math.exp(-l/s),d=(g,m)=>g>0&&m>0?g*(m/g)**u:m,f={mean:d(r?.mean??0,a.mean),brightest:d(r?.brightest??0,a.brightest),atMs:o,jumped:h||l===0&&(r?.jumped??!1)};this.frameLight=f;const p=(g,m)=>Math.abs(g-m)>.01*Math.max(g,m);(!r||p(r.mean,f.mean)||p(r.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Si.uRetinaOn.value=0,this.medium)return;const t=[];for(const r of this.emitterLights.farEmitters){const o=this.screenPointOf(r.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||t.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:En.luminanceOf(r.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.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>ce.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new ce,this.retina.replay(0,this.recordingTimeMs,r=>this.historicBleachingAt(r,i),s,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new ce,this.retina.advance(this.recordingTimeMs,t,s)}this.retina.any&&(Si.uRetina.value=this.retina.texture,Si.uRetinaOn.value=1,Si.uRetinaViewport.value.copy(e))}retinaSize=new Q;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*Ve,-(s?.headingDeg??0)*Ve,(s?.rollDeg??0)*Ve,"YXZ")).invert(),a=s?.fovDeg??this.camera.fov,r=[];for(const o of i.views){const l=this.farEmitterOf(o.head,o.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(n),a,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||r.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:En.luminanceOf(l.lux)})}return r}historicQuaternion=new Fs;historicEuler=new Ma;historicDirection=new _;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<ct.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(s=>{s.userData.emissive===!0&&e.push(s)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,k6);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ht.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const a=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...a):this.onMapSubjectBounds(a)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(a,r,o)=>this.directionAtScreenPoint(a,r,o),a=>this.screenPointOf(a)),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?[Xg]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},yn.INTERVAL_MS)),Si.uRodShare.value=this.scatteredSky?.rodShare??0,Si.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina(),this.waterSystem?.reflectBodies(this.renderer,this.scene,this.camera,Wg,this.bodySystem.any,e&&gi.supports(this.camera.fov,this.camera.aspect)?e.sourceFovDeg(this.camera.fov,this.camera.aspect):void 0);const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(a=>a.visible);Si.uHasOverlay.value=s?1:0;const n=s?a=>this.renderOverlayPasses(a):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const a=this.usableDepthOfFieldPass();a?a.render(this.renderer,this.scene,this.camera,n,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,a=>{this.lensFlare&&(this.lensFlare.mesh.visible=a?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Cn&&e.userData.pointSource||e instanceof dt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(n=>n.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Kp),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Wg),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new un({blending:oc,blendSrc:qa,blendDst:qa,blendSrcAlpha:qa,blendDstAlpha:qa,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=Ht(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-Bv62TprV.js");return{ReferenceSystem:s}},__vite__mapDeps([35,36,2,37,1,3,4,5,6,7]),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[r,o]of this.referenceViews)n.setView(r,o);n.setShown(this.referencesShown);const a=this.pendingReferences;return this.pendingReferences=void 0,a&&n.set(a.references,void 0,a.observerAt),this.render(),n})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new _)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.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=e?this.narrowTo(t,e):t,a=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),r=this.phenomena.furthestM;let o=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,a,r);ct.markDecorDepth(h,u),u&&o++}o>0&&(t.layers.set(Xp),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(Xg),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new d0;phenomenaViewProjection=new Gt;occluderSphere=new ia;occluderEye=new _;localBounds=new WeakMap;mayHide(t,e,i,s){let n=0;t.traverse(()=>n++);let a=this.localBounds.get(t);if(!a||a.objects!==n){t.updateMatrixWorld(!0);const o=new ze().setFromObject(t);if(o.isEmpty())return!1;a={sphere:o.getBoundingSphere(new ia).applyMatrix4(new Gt().copy(t.matrixWorld).invert()),objects:n},this.localBounds.set(t,a)}const r=this.occluderSphere.copy(a.sphere).applyMatrix4(t.matrixWorld);return r.center.distanceTo(e.getWorldPosition(this.occluderEye))-r.radius>s?!1:i.intersectsSphere(r)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new Q),s=ct.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-s)),a=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-s)),r=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+s)),l=this.narrowCamera.copy(t);return t.getWorldPosition(l.position),t.getWorldQuaternion(l.quaternion),l.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,r-n),Math.max(1,o-a)),l.updateMatrixWorld(),l}narrowCamera=new Ns;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new un({colorWrite:!1,side:ds});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const s=t.getObjectByName("head");if(!s)return;const n=((i-e)%360+540)%360-180,a=Math.max(-85,Math.min(ct.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-a*Ve}static isSolidSurface(t){if(!(t instanceof dt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==gs}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof dt))return;e&&ct.isSolidSurface(i)?i.layers.enable(Xp):i.layers.disable(Xp)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new Q),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new II(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const s=performance.now()+ct.EXPOSURE_BUDGET_MS,n=ct.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let a=0;do{this.restateAt(t,this.exposureInstantsDone);const r=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((o,l)=>{o.visible=r[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,a++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&a<n);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Si.uRodShare.value=this.scatteredSky?.rodShare??0,Si.uHasOverlay.value=1,Si.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(r=>r.visible))return;const i=new zn,s=new Bn(-1,1,1,-1,0,2),n=Kd/(D2*Math.tan(I2*Ve/2));for(const r of this.compassSprites){if(!r.visible)continue;const o=r.getWorldPosition(new _).sub(this.camera.position).normalize(),l=this.screenPointOf(o);if(!l)continue;const h=new el(r.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const a=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=a}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new ze,i=new _,s=this.camera.getWorldDirection(new _),n=this.decorObjects.filter(r=>r.track?.length||r.kind==="aircraft"||r.kind==="vehicle").map(r=>this.decorGroups.get(r.id)),a=this.bodySystem.reflectors.map(r=>r.holder);for(const r of[...n,...a]){if(!r?.visible||(e.setFromObject(r),e.isEmpty())||e.distanceToPoint(this.camera.position)<ct.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(s)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;o=Math.min(o,m),l=Math.max(l,m),h=Math.min(h,v),u=Math.max(u,v)}o=Math.max(o,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=o&&u>=h&&t.push({x:o,y:h,width:l-o,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}eyeOptics(){if(!this.eyeAsLens)return;const t=Math.max(1e-6,this.scatteredSky?.sceneAdaptation??1e3),e=4.9-3*Math.tanh(.4*Math.log10(t)),i=ct.EYE_FOCAL_MM;return{focalLengthMm:i,fNumber:i/e,focusDistance:0,frameHeightMm:2*i*Math.tan(this.camera.fov*Ve/2)}}static EYE_FOCAL_MM=17;static EYE_LENS_MAX_FOV_DEG=20;get eyeAsLens(){return this.projectionKind==="equidistant"&&!this.lensOptics&&this.camera.fov<=ct.EYE_LENS_MAX_FOV_DEG}usableDepthOfFieldPass(){const t=this.lensOptics??this.eyeOptics();if(!t)return;const e=this.renderer.getDrawingBufferSize(new Q),i=Math.max(1,Math.round(e.x)),s=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new yl(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass.setAir(this.weather.visibilityKm!==void 0?this.weather.visibilityKm*1e3:void 0,this.camera.fov),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Si.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new Q);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new xi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new Q);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new X1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant"||this.eyeAsLens)return;const t=this.renderer.getDrawingBufferSize(new Q);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new gi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,s=>{const n=ct.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(t,e,i){const s=this.projectionKind==="equidistant"&&!this.eyeAsLens?this.equidistantPass:void 0;if(!s){t.setFromCamera(new Q(e,i),this.camera);return}const n=s.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(n.x,n.y,n.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new _)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),s=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,s)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&!this.eyeAsLens&&this.equidistantPass)return gi.ndcFor(t,e,i);if(t.z>=0)return;const s=Math.tan(e/2*Ve);return{ndcX:t.x/-t.z/(i*s),ndcY:t.y/-t.z/s}}screenPointScratch=new _;screenPointQuaternion=new Fs;screenPointSize=new Q;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const s=this.renderer.domElement.width,n=this.renderer.domElement.height;t.uniforms.uResolution.value.set(s,n),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(l=>Math.max(0,l-ct.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=t.uniforms.uLensPosition.value,a=t.uniforms.uTanHalfFov.value,r=this.camera.aspect,o=Pe.offFrameShare(Math.atan(Math.hypot(n.x*r,n.y)*a)*180/Math.PI,Math.atan(Math.hypot(r,1)*a)*180/Math.PI,this.ghostOptics.reachDeg);if(!(o<=0))return{x:n.x,y:n.y,radius:i,flux:[e[0]*s*o,e[1]*s*o,e[2]*s*o]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const s=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(s.x,s.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(b2),this.camera.layers.set(b2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of O2)this.isSunOccluded(e[0],e[1])||t++;return t/O2.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),a=n.length();if(n.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,n,a)||this.cabinMask.hides(n))return!0;const r=this.cabinMask.any?s.filter(l=>!this.cabinGroups.includes(l)):s;if(r.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(r,!0).find(l=>!(l.object.material instanceof qs));return o!==void 0&&o.distance<a}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),s=e.mesh.material.uniforms.uSourceDeg.value,n=s>.05?ct.VEIL_SAMPLES:ct.VEIL_SAMPLES.slice(0,1);let a=0;for(const[r,o]of n)this.isOccludedToward(i,r*s,o*s)||a++;e.share=a/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new vn;veilTargetScratch=new _;groundBlocks(t,e,i,s=0){const n=this.groundMesh;if(n&&e.y<0){const m=(n.position.y-t.y)/e.y;if(m>s&&m<i){const v=t.x+e.x*m-n.position.x,M=t.z+e.z*m-n.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const a=this.terrainMesh;if(!a)return!1;const r=a.geometry.getAttribute("position"),o=Math.round(Math.sqrt(r.count));if(o<2||o*o!==r.count)return!1;const l=[a.position.x+r.getX(0),a.position.x+r.getX(o-1)],h=[a.position.z+r.getZ(0),a.position.z+r.getZ((o-1)*o)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(u>0))return!1;let d=s,f=i;for(const[m,v,M]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(m<x||m>y)return!1;continue}const w=(x-m)/v,S=(y-m)/v;d=Math.max(d,Math.min(w,S)),f=Math.min(f,Math.max(w,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,M=t.x+e.x*v,x=t.y+e.y*v,y=t.z+e.z*v;if(x<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Hd;let s,n;for(const a of this.decorObjects){if(a.kind==="crop")continue;const r=this.decorGroups.get(a.id);if(!r)continue;const o=this.ufoOcclusionRaycaster.intersectObject(r,!0).find(l=>ct.isSolidSurface(l.object));o&&(a.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(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=n6*this.camera.fov*Math.PI/180,a=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new _).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),r=this.eclipseDiscs,o=r?[{key:"sun",direction:r.sun,radiusRad:r.sunRadiusRad},{key:"moon",direction:r.moon,radiusRad:r.moonRadiusRad,inFront:!0}]:[],l=ct.nearestBody(s,[...a.filter(h=>!r||h.key!=="sun"&&h.key!=="moon"),...o],n);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let s,n=1/0,a=1/0,r=!1;for(const o of e){const l=Math.acos(Ca(o.direction.dot(t),-1,1))-o.radiusRad;if(l>i)continue;const h=l<=0,u=n<=0,d=o.inFront===!0;(h!==u?h:h?d!==r?d:o.radiusRad<a:l<n)&&(s=o.key,n=l,a=o.radiusRad,r=d)}return s}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,a=t6*this.camera.fov*Math.PI/180,r=[...this.decorGroups.values()],o=r.length>0?ct.firstSolid(this.raycaster.intersectObjects(r,!0))?.distance:void 0;let l,h=1/0;const u=new ze,d=new _;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new _).length()/2,g=d.clone().sub(n),m=g.length();if(m===0||g.dot(s)<=0||o!==void 0&&o<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(s))),M=Math.atan(p/m);if(M>a){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||o!==void 0&&o<x.distance)continue}else if(v>a)continue;M<h&&(h=M,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,s=Math.cos(Vd*this.camera.fov*Math.PI/180);let n,a=s;for(const r of this.namedStars){const o=r.direction.dot(i);o>a&&(a=o,n={star:r.star,altitudeDeg:r.altitudeDeg})}return n&&this.groundHides(t,e)?void 0:n}groundHides(t,e,i=1/0){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const s=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(s.origin,s.direction,i,Hd)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,s=1/0,n=-1/0,a=-1/0;for(let r=0;r<8;r++){const o=this.bodyCornerScratch.set(r&1?e.max.x:e.min.x,r&2?e.max.y:e.min.y,r&4?e.max.z:e.min.z),l=this.screenPointOf(o.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),n=Math.max(n,l.ndcX),s=Math.min(s,l.ndcY),a=Math.max(a,l.ndcY)}return{minX:i,minY:s,maxX:n,maxY:a}}bodyBoxScratch=new ze;bodyCornerScratch=new _;decorFrameScratch=new Gt;decorPartMatrix=new Gt;decorPartScratch=new ze;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=this.decorFrameScratch.copy(e.matrixWorld).invert(),s=this.bodyBoxScratch.makeEmpty();if(e.traverse(l=>{const h=l.geometry;!h||!l.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&s.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(i,l.matrixWorld))))}),s.isEmpty())return;let n=1/0,a=1/0,r=-1/0,o=-1/0;for(let l=0;l<8;l++){const h=this.bodyCornerScratch.set(l&1?s.max.x:s.min.x,l&2?s.max.y:s.min.y,l&4?s.max.z:s.min.z).applyMatrix4(e.matrixWorld),u=this.screenPointOf(h.sub(this.camera.position).normalize());if(!u)return;n=Math.min(n,u.ndcX),r=Math.max(r,u.ndcX),a=Math.min(a,u.ndcY),o=Math.max(o,u.ndcY)}return{minX:n,minY:a,maxX:r,maxY:o}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,s=0){const n=this.decorGroups.get(t);if(!n)return;this.aimAtScreenPoint(this.raycaster,e,i);const a=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),this.decorHitScratch);return a?{x:a.x,z:a.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ve/2):0}decorGrabHeightAt(t,e,i){const s=this.decorGroups.get(t);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const a=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(a.lengthSq()<1e-6)return 0;a.normalize();const r=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(a,s.position),o=this.raycaster.ray.intersectPlane(r,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new fa;decorHitScratch=new _;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<ct.SEE_THROUGH_BELOW||n instanceof qs))})}static SEE_THROUGH_BELOW=.9;pickPeakAt(t,e){const i=this.renderer.getDrawingBufferSize(new Q),s=this.camera.fov*Ve/Math.max(1,i.y),n=this.camera.getWorldPosition(new _);let a;for(const r of this.decorObjects){if(r.kind!=="peak")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const l=o.getWorldPosition(new _);l.y=this.reliefYAt(l.x,l.z);const h=l.distanceTo(n),u=this.screenPointOf(l.clone().sub(n).normalize());if(!u)continue;const d=(t-u.ndcX)*i.x/2,f=(u.ndcY-e)*i.y/2,p=Math.max(10,(r.sizeM?.widthM??2e3)/2/Math.max(h,1)/s);if(f<-8||f>p*.6)continue;const g=p*Math.max(.15,f/(p*.6));if(Math.abs(d)>Math.max(10,g))continue;const m=Math.abs(d)+Math.abs(f);(!a||m<a.score)&&(a={id:r.id,score:m})}return a?.id}reliefYAt(t,e){const i=this.terrainMesh;if(i&&Math.hypot(t-i.position.x,e-i.position.z)<=this.terrainRadius)return this.terrainYUnder(t,e);const s=this.farRing?.mesh;return s?s.position.y+this.groundYOfPatch(s,t-s.position.x,e-s.position.z):0}pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],s=ct.firstSolid(this.raycaster.intersectObjects(i.map(([,r])=>r),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let a=s.object;for(;a&&!i.some(([,r])=>r===a);)a=a.parent;return i.find(([,r])=>r===a)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new pc().copy(s).applyMatrix4(new Gt().copy(i.group.matrixWorld).invert()),a=i.group.matrixWorld,r=(d,f)=>{const p=new _(d,0,f).applyMatrix4(a);return this.groundYUnder(p.x,p.z)-a.elements[13]};if(!i.mayMeet(n.origin,n.direction,r,ct.RAILWAY_PICK_ABOVE_M))return;const o=ct.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-ct.RAILWAY_GROUND_MARGIN_M,Hd))return;const l=i.group.worldToLocal(o.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:o.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const s=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,a={toleranceRad:ct.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Vd*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let r;for(const l of s){const h=l.simulation.pick(n.origin,n.direction,a);h&&(!r||(h.distanceM??1/0)<(r.distanceM??1/0))&&(r={kind:l.kind.key,...h})}if(!r)return;if(r.distanceM===void 0)return this.groundHides(t,e)?void 0:r;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,r.distanceM-1,Hd))return;const o=ct.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(o&&o.distance<r.distanceM))return r}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=a=>.2126*a[0]+.7152*a[1]+.0722*a[2],s=Math.hypot(t.x,t.y,t.z)||1,n=Math.max(0,Math.min(1,t.y/s));return i(e.horizon)+(i(e.zenith)-i(e.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 t of this.skyEventLayers.values())t.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 t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ht.dispose(t);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 t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const s=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||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(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new _;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<ct.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Ji(Bd,32,16),i=e.attributes.position,s=e.getAttribute("color")??new de(new Float32Array(i.count*3),3);for(let a=0;a<i.count;a++){const{altitudeDeg:r,azimuthDeg:o}=bb(i.getX(a),i.getY(a),i.getZ(a)),l=BI(r,o,t.azimuthDeg,t.altitudeDeg);s.setXYZ(a,l[0],l[1],l[2])}if(s.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",s);const n=new un({vertexColors:!0,side:Ai,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new dt(e,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=S2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new O1(this.groundRadius,48),i=new sa({color:new at(Yp,Yp,Yp),fog:!0});vo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new dt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let s=0;if(i){const a=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<a.count;r++)Math.abs(a.getX(r)+i.position.x)>600||Math.abs(a.getZ(r)+i.position.z)>600||(s=Math.min(s,a.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}const n=this.farRing?.mesh;if(n){const a=n.geometry.getAttribute("position");let r=1/0;for(let o=0;o<a.count;o++)Math.hypot(a.getX(o)+n.position.x,a.getZ(o)+n.position.z)>this.groundRadius||(r=Math.min(r,a.getY(o)+n.position.y));Number.isFinite(r)&&(s=Math.min(s,r-1))}this.groundMesh.position.y=s,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([a,r])=>`${a}=${Math.round(r.x/10)},${Math.round(r.z/10)}`).join(";")+(e?":water":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=mi(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Ce.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*o6);const a=e?0:this.weather.highCloudCover??0;return a>0&&(s*=1-Ce.iceAlphaAt(i,Xd,a,this.cloudFieldOffset)*c6),Math.max(0,Math.min(1,s))}setBodyMesh(t,e,i,s,n){if(e.altitudeDeg<ff){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1,qs.setDisc("sun",void 0));return}const{x:a,y:r,z:o}=mi(e.altitudeDeg,e.azimuthDeg,Ii),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,n,l),u=ct.unitLuminance(s);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/Ii)**2,p=[0,1,2].map(m=>u[m]*h[m]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const g=p.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m));d instanceof dt||(this.disposeMesh(d),d=new dt(new Ji(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(g[0],g[1],g[2]),d.scale.setScalar(i),qs.setDisc("sun",{direction:[a/Ii,r/Ii,o/Ii],radiusRad:Math.atan(i/Ii),radiance:g})}else{if(!(d instanceof Cn)){this.disposeMesh(d);const g=new ye;g.setAttribute("position",new ve(new Float32Array(3),3)),g.setAttribute("color",new ve(new Float32Array(3),3)),d=new Cn(g,Vt.material(Ul[Ul.length-1].size,!1)),Vt.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(a,r,o),this.setHitArea(t,a,r,o,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,a,r,o,h,i/Ii*(180/Math.PI),ct.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(a*f,r*f+this.celestialGroup.position.y,o*f),this.lensFlare||(this.lensFlare=MP(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<ff){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i),qs.setDisc("moon",void 0);return}const{x:s,y:n,z:a}=mi(t.altitudeDeg,t.azimuthDeg,Ii),r=this.cloudTransmission(t),o=this.arrivingIlluminance(t,t.magnitude,r),l=t.radiusDeg??Wa.MEAN_RADIUS_DEG,h=Ii*Math.tan(l*Ve),u=Math.max(Ca(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Ii)**2,d=new at(...o.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m/u))),f=Math.PI*(h/Ii)**2;qs.setDisc("moon",{direction:[s/Ii,n/Ii,a/Ii],radiusRad:l*Ve,radiance:o.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m/f))});const p=`${t.phase.phaseFraction<.5}:${Math.round(Ca(t.phase.illuminatedFraction,0,1)*500)}`;let g=this.bodyMeshes.get(i);g instanceof el?(g.userData.phaseKey!==p&&(g.material.map?.dispose(),g.material.map=Z2(t.phase),g.userData.phaseKey=p),g.material.color.copy(d)):(this.disposeMesh(g),g=new el(new Xh({map:Z2(t.phase),color:d,fog:!1,blending:gs,depthWrite:!1})),g.userData.phaseKey=p,this.celestialGroup.add(g),this.bodyMeshes.set(i,g)),g.scale.set(h*2,h*2,1),g.position.set(s,n,a),this.setHitArea(i,s,n,a,h),this.setGlare(i,s,n,a,o,l)}bentLight(t,e,i=a6){const[s,n,a]=this.arrivingIlluminance(t,e,1),r=Math.max(n,1e-30);return{scale:n/i,tint:[s/r,1,a/r]}}static litBySky(t,e){return ct.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new at;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Vt.CONE_SOLID_ANGLE/e)}pointScratch=new Q;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),n=Ne.illuminanceOf(e)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(t){const e=En.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,s,n){let a=this.hitAreas.get(t);if(!a){const o=new Xh({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});a=new el(o),this.celestialGroup.add(a),this.hitAreas.set(t,a)}a.position.set(e,i,s);const r=n*2;a.scale.set(r,r,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,s,n,a,r=0){if(hs.radiusDeg(hs.K*Math.max(...n))<=Math.max(a,r)){this.disposeGlare(t);return}let o=this.glareSprites.get(t);o||(o=new hs(`veil:${t}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(t,o)),o.shine({x:e,y:i,z:s},n,a,r)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const s=vl(t.magnitude,e),n=Sp(s);this.cometKey=i,this.setBodyMesh(i,t.position,Jp*(.5+.5*s),new at(n,n,n),t.magnitude),this.cometTail||(this.cometTail=new Pn(Ii),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,s)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Ui,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:Xd},0);return}const n=this.lowerCloudCover(),a=we.deckLitUntilDeg(we.DECK_HEIGHT_M),r=t.altitudeDeg>-a?t:e,o=this.bentLight(r,r===t?ue.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,n,r.altitudeDeg,a)*o.scale,{x:h,y:u,z:d}=mi(r.altitudeDeg,r.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},r.altitudeDeg,l,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??Xd},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??cS,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new qo,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=t.altitudeDeg>0,n=s?t:e,a=this.lowerCloudCover(),r=this.bentLight(n,s?ue.SUN_MAGNITUDE:e.magnitude,r6),o=In.strength(i,a,n.altitudeDeg)*r.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=mi(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},o,r.tint,s)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new eo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=t.frame,n=ua.galactic(i,s),a=ct.directionOf(n.centre),r=ct.directionOf(n.rotation),o=ct.directionOf(n.pole),l=new he().set(a.x,a.y,a.z,r.x,r.y,r.z,o.x,o.y,o.z),h=ct.directionOf(ua.eclipticPole(i,s)),u=ct.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:ct.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new _(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:s}=mi(t.altitudeDeg,t.azimuthDeg,1);return new _(e,i,s).normalize()}buildNovae(t,e){const i=new Set;for(const s of t){if(s.magnitude>e)continue;const n=`nova:${s.id}`;i.add(n);const a=vl(s.magnitude,e),r=Sp(a);this.setBodyMesh(n,s.position,Jp*(.5+.5*a),new at(r,r,r),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(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const s of t){if(s.magnitude>e)continue;i.add(s.body);const n=vl(s.magnitude,e),a=Sp(n),r=B6[s.body]??new at(1,1,1),o=new at(r.r*a,r.g*a,r.b*a),l=Jp*(.5+.5*n);this.setBodyMesh(s.body,s.position,l,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(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=t,a=new da(s,n),r=om(1337),o=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=a.position(i.ra[h],i.dec[h]);if(d<A2)continue;const{x:p,y:g,z:m}=mi(d,f,$p);o.push({x:p,y:g,z:m,brightness:vl(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ne.illuminanceOf(u)),phase:r()*Math.PI*2,speedFactor:.7+r()*.6})}for(const h of WI){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=a.position(h.raHours,h.decDeg);if(u<A2)continue;const{x:f,y:p,z:g}=mi(u,d,$p);this.namedStars.push({star:h,direction:new _(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Ul.map((h,u)=>{const d=o.filter(w=>W1(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((w,S)=>{f[S*3]=w.x,f[S*3+1]=w.y,f[S*3+2]=w.z,p[S]=w.brightness,g.set(w.illuminance,S*3),m[S]=w.phase,v[S]=w.speedFactor});const M=new ye;M.setAttribute("position",new ve(f,3)),M.setAttribute("seed",new ve(m.map(w=>w/(2*Math.PI)),1));const x=new ve(new Float32Array(d.length*3),3);M.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new Cn(M,Vt.material(h.size)),Vt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Vt.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;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]*e,s[n*3+1]=i.illuminance[n*3+1]*e,s[n*3+2]=i.illuminance[n*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Fl(this.celestialGroup,jp,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new at(Lo[0]+(em[0]-Lo[0])*e,Lo[1]+(em[1]-Lo[1])*e,Lo[2]+(em[2]-Lo[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:s,uniforms:n}=Og(i,t,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 a=Lg(jp);this.cloudMesh=new dt(a,s),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Og(new at(...Lo),t,Xd,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new dt(Lg(jp*1.04),e),this.cirrusMesh.renderOrder=L2-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Fl.deckOrder(!0,0,1):L2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??Mx)-this.observerElevationM)*Qp;return Math.sign(e||1)*Math.max(Math.abs(e),b6)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,a,r]=this.cloudBeam.map(u=>u/Math.PI),o=this.lightningLevel*rm*this.relativeScale/Math.PI,l=new at(e[0]+Ta.r*o,e[1]+Ta.g*o,e[2]+Ta.b*o);this.layeredClouds?.setLighting(s.clone(),new at(n,a,r),l,l);const h=Math.max(0,s.y);for(const u of i)u.sunDir.value.copy(s),u.sunColor.value.setRGB(n*h,a*h,r*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return I6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,nm],[this.rainSplashSystem?.points,No],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:im[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=U2(am(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=im[t],i=e.poolSize,s=om(9001),n=new Float32Array(i*3),a=new Float32Array(i),r=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const y=s()*Math.PI*2,w=s()*e.radiusM;n[x*3]=Math.cos(y)*w,n[x*3+1]=nl+s()*(e.topYM-nl),n[x*3+2]=Math.sin(y)*w,a[x]=s()*Math.PI*2,r[x]=.7+s()*.6,o[x]=.6+s()*.8,l[x]=.4+s()*1.2}const g=new ye;g.setAttribute("position",new ve(n,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new at(...this.baseFogColor)},uTexture:{value:H6(t)},uNearFocusDistance:{value:G2},uHazeDistance:{value:e.radiusM*V2}},v=new _e({uniforms:m,vertexShader:Y6,fragmentShader:$6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const M=new Cn(g,v);M.renderOrder=tm,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=n,this.precipitationPhase=a,this.precipitationSpeedJitter=r,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const s=im[i];if(this.precipitationUniforms?.uColor.value.copy(ct.litBySky(s.color,this.baseFogColor)),e<=0)return;const n=this.weather.windDirectionDeg*Ve,a=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,r=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let y=0,w=0;y<o.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(b)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(b)*A,f[w]=0}else{const b=1-f[w]/g[w];o[y+1]=nl+Math.sin(Math.PI*b)*p[w],o[y]=Yd(o[y]+(a+m[w])*e,s.radiusM),o[y+2]=Yd(o[y+2]+(r+v[w])*e,s.radiusM)}continue}let S=0,E=0;if(M){const b=C6*u[w],A=O6*d[w];S=Math.sin(t*b*Math.PI*2+l[w])*A,E=Math.sin(t*b*Math.PI*2+l[w]+Math.PI/2)*A}if(o[y]+=(a+S)*e,o[y+1]-=s.fallSpeedMPerS*h[w]*e,o[y+2]+=(r+E)*e,o[y]=Yd(o[y],s.radiusM),o[y+2]=Yd(o[y+2],s.radiusM),o[y+1]<nl){if(x){p[w]=$2*(.2+Math.random()*1.6),g[w]=L6*(.5+Math.random()),f[w]=g[w];const T=Math.random()*Math.PI*2,D=N6*(p[w]/$2);m[w]=Math.cos(T)*D,v[w]=Math.sin(T)*D,o[y+1]=nl;continue}const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(b)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(b)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=am(this.weather.precipitationIntensity);this.rainSystem=mP({count:nm,radiusM:Ih,heightM:E6,bottomYM:N2,overallSpeed:A6,color:F2.clone(),opacity:.85,visibleCount:this.precipitationCount(nm),speedStreak:U2(t),pixelSize:X2,seed:9001,nearFocusDistanceM:G2,hazeDistanceM:Ih*V2,hazeColor:new at(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=tm,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=om(4242),e=new Float32Array(No*3),i=new Float32Array(No),s=new Float32Array(No),n=new Float32Array(No);for(let h=0;h<No;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Ih;e[h*3]=Math.cos(u)*d,e[h*3+1]=N2,e[h*3+2]=Math.sin(u)*d,s[h]=q2(z2,B2),i[h]=t()*s[h],n[h]=i[h]/s[h]}const a=new ye;a.setAttribute("position",new ve(e,3));const r=new ve(n,1);a.setAttribute("aLife",r),a.setDrawRange(0,this.precipitationCount(No));const o=new _e({uniforms:{uMaxSize:{value:D6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:H2.clone()},uTexture:{value:W6()}},vertexShader:X6,fragmentShader:K6,transparent:!0,depthWrite:!1}),l=new Cn(a,o);l.renderOrder=tm,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:s,lifeAttribute:r}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Ve;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-am(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(ct.litBySky(F2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ct.litBySky(H2,this.baseFogColor));const s=this.weather.windDirectionDeg*Ve,n=Math.sin(s)*this.weather.windSpeed,a=-Math.cos(s)*this.weather.windSpeed,r=Ih,o=h=>(h%(r*2)+r*3)%(r*2)-r;e.uniforms.uWindOffset.value.set(o(e.uniforms.uWindOffset.value.x+n*t),o(e.uniforms.uWindOffset.value.y+a*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=K2+(1-K2)*(1-l),u=Y2+(1-Y2)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=X2*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:a}=e,r=a.array;for(let o=0,l=0;o<i.length;o+=3,l++){if(s[l]+=t,s[l]>=n[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Ih;i[o]=Math.cos(h)*u,i[o+2]=Math.sin(h)*u,n[l]=q2(z2,B2),s[l]=0}r[l]=s[l]/n[l]}e.points.geometry.attributes.position.needsUpdate=!0,a.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>t)break;const l=is.brightnessAt(o,t);l>i&&(e=o,i=l)}const s=e?Math.min(1,Math.max(.1,(U6/e.distanceM)**2)):0,n=i*s*(e?.cloudToGround?1:.6);if(n===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,l=n*rm*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Ta.r*l,this.airlight[1]+Ta.g*l,this.airlight[2]+Ta.b*l)}const a=this.skyMesh?.material?.color;if(a){const o=n*z6;a.setRGB(1+o*Ta.r,1+o*Ta.g,1+o*Ta.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*rm*this.relativeScale,e){const{x:o,y:l,z:h}=mi(25,e.azimuthDeg,Ii);this.lightningLight.position.set(o,l,h)}this.lightningBolt||(this.lightningBolt=new io(Ii*.95),this.celestialGroup.add(this.lightningBolt.object));const r=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,r),this.render()}buildCompassLabels(){this.compassSprites=v6.map(t=>{const e=sc.point(t,this.compassPoints),i=new Xh({map:q6(e),depthTest:!1,fog:!1}),s=new el(i),{x:n,y:a,z:r}=mi(0,t,D2);return s.position.set(n,a,r),s.scale.set(Kd,Kd,1),s.renderOrder=x6,s.layers.set(Kp),s.visible=this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=I2*Math.PI/360,i=Kd*Math.tan(t)/Math.tan(e);for(const s of this.compassSprites)s.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const s=i.map;s&&s.dispose(),i.dispose()}}}const Ve=Math.PI/180;function Ca(c,t,e){return Math.max(t,Math.min(e,c))}function q2(c,t){return c+Math.random()*(t-c)}function Yd(c,t){return(c%(t*2)+t*3)%(t*2)-t}let $d,qd;function H6(c){switch(c){case"snow":return G6();case"hail":return V6()}}function G6(){if($d)return $d;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),$d=new So(t),$d}function V6(){if(qd)return qd;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),qd=new So(t),qd}let Zd;function W6(){if(Zd)return Zd;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),Zd=new So(t),Zd}const X6=`
|
|
8926
|
+
`,transparent:!0,blending:gs,depthWrite:!1,side:Ai,fog:!1});this.object=new dt(new Ji(K1.RADIUS,128,32,0,Math.PI*2,0,Ne.MAX_ANGLE_RAD),e),this.object.renderOrder=-1,this.object.frustumCulled=!1,this.object.visible=!1}show(t,e){if(!t||!e){this.object.visible=!1;return}this.towards.set(t.x,t.y,t.z).normalize(),this.object.quaternion.setFromUnitVectors(this.up,this.towards),this.object.material.uniforms.uSource.value.copy(this.towards);for(let i=0;i<Ne.STEPS;i++){for(let s=0;s<3;s++)this.texels[i*4+s]=_s.toHalfFloat(Math.min(e[i*3+s],6e4));this.texels[i*4+3]=_s.toHalfFloat(1)}this.texture.needsUpdate=!0,this.object.visible=!0}dispose(){this.object.geometry.dispose(),this.object.material.dispose(),this.texture.dispose()}}class $f{constructor(t){this.generator=t}static SIZE=128;target=new bu($f.SIZE,{type:Be,generateMipmaps:!0,minFilter:Fn,magFilter:ge});camera=new H1(.1,2e5,this.target);filteredTarget;capturedAtMs=-1/0;capturedVersion;get sharp(){return this.target.texture}get filtered(){return this.filteredTarget?.texture}capture(t,e,i,s=[]){const n=t.shadowMap.autoUpdate;let a=!1;e.traverse(o=>{const l=o;l.isLight&&l.castShadow&&l.shadow&&!l.shadow.map&&(a=!0)}),t.shadowMap.autoUpdate=a?n:!1;const r=s.map(o=>o.visible);for(const o of s)o.visible=!1;this.camera.position.copy(i),this.camera.update(t,e),s.forEach((o,l)=>{o.visible=r[l]}),t.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 Ys{static REFRESH_MS=250;generator;eye;probes=new Map;constructor(t){Ys.install(),this.generator=new Rg(t),this.eye=new $f(this.generator)}static decor;refresh(t,e,i,s,n,a,r,o=[],l,h=Ys.REFRESH_MS){for(const m of[...this.probes.keys()])s.some(v=>v.id===m&&v.shiny)||(this.probes.get(m).dispose(),this.probes.delete(m));const u=[{probe:this.eye}];for(const m of s){if(!m.shiny)continue;let v=this.probes.get(m.id);v||(v=new $f(this.generator),this.probes.set(m.id,v)),u.push({probe:v,reflector:m})}const d=performance.now(),f=()=>u.filter(({probe:m})=>m.capturedVersion!==r),p=f().filter(({probe:m})=>d-m.capturedAtMs>=h);if(p.length>0){const m=p.reduce((v,M)=>M.probe.capturedAtMs<v.probe.capturedAtMs?M:v);if(m.reflector){const v=m.reflector.holder.getWorldPosition(this.scratch);m.probe.capture(t,e,v,[m.reflector.holder,...n]),Ys.reflectOn(m.reflector.holder,m.probe)}else{m.probe.capture(t,e,i,[...n,...o]),l?.(m.probe.sharp),Ys.decor=m.probe.filtered;for(const v of a)Ys.reflectOn(v,m.probe);for(const v of s)v.shiny||Ys.reflectOn(v.holder,m.probe)}m.probe.capturedVersion=r}const g=f();if(g.length!==0)return Math.max(16,Math.min(...g.map(({probe:m})=>h-(d-m.capturedAtMs))))}scratch=new _;static reflectOn(t,e={filtered:Ys.decor}){t.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[])n instanceof qs?e.sharp&&n.setSurroundings(e.sharp):n instanceof _r&&e.filtered&&n.envMap!==e.filtered&&(n.envMap=e.filtered,n.needsUpdate=!0)})}dispose(){this.eye.dispose();for(const t of this.probes.values())t.dispose();this.generator.dispose()}static installed=!1;static install(){if(Ys.installed)return;Ys.installed=!0;const t="iblIrradiance += getIBLIrradiance( geometryNormal );";if(!ne.lights_fragment_maps.includes(t)){console.warn("Reflections: three's lights_fragment_maps changed; the environment will light diffusely too");return}ne.lights_fragment_maps=ne.lights_fragment_maps.replace(t,"// The sky's diffuse light is the hemisphere light's (see Reflections).")}}const Ob=0,QP=1,tC=2,n2=2,Lp=1.25,a2=1,Js=32,fs=Js/4,Lb=65535,uf=Math.pow(2,-24),Y1=Symbol("SKIP_GENERATION"),Nb={strategy:Ob,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Y1]:!1};function Bi(c,t,e){return e.min.x=t[c],e.min.y=t[c+1],e.min.z=t[c+2],e.max.x=t[c+3],e.max.y=t[c+4],e.max.z=t[c+5],e}function Kg(c){let t=-1,e=-1/0;for(let i=0;i<3;i++){const s=c[i+3]-c[i];s>e&&(e=s,t=i)}return t}function r2(c,t){t.set(c)}function o2(c,t,e){let i,s;for(let n=0;n<3;n++){const a=n+3;i=c[n],s=t[n],e[n]=i<s?i:s,i=c[a],s=t[a],e[a]=i>s?i:s}}function Ad(c,t,e){for(let i=0;i<3;i++){const s=t[c+2*i],n=t[c+2*i+1],a=s-n,r=s+n;a<e[i]&&(e[i]=a),r>e[i+3]&&(e[i+3]=r)}}function bh(c){const t=c[3]-c[0],e=c[4]-c[1],i=c[5]-c[2];return 2*(t*e+e*i+i*t)}function qi(c,t){return t[c+15]===Lb}function Rs(c,t){return t[c+6]}function js(c,t){return t[c+14]}function ps(c){return c+fs}function ms(c,t){const e=t[c+6];return c+e*fs}function $1(c,t){return t[c+7]}function Np(c,t,e,i,s){let n=1/0,a=1/0,r=1/0,o=-1/0,l=-1/0,h=-1/0,u=1/0,d=1/0,f=1/0,p=-1/0,g=-1/0,m=-1/0;const v=c.offset||0;for(let M=(t-v)*6,x=(t+e-v)*6;M<x;M+=6){const y=c[M+0],w=c[M+1],S=y-w,E=y+w;S<n&&(n=S),E>o&&(o=E),y<u&&(u=y),y>p&&(p=y);const b=c[M+2],A=c[M+3],T=b-A,D=b+A;T<a&&(a=T),D>l&&(l=D),b<d&&(d=b),b>g&&(g=b);const I=c[M+4],C=c[M+5],N=I-C,O=I+C;N<r&&(r=N),O>h&&(h=O),I<f&&(f=I),I>m&&(m=I)}i[0]=n,i[1]=a,i[2]=r,i[3]=o,i[4]=l,i[5]=h,s[0]=u,s[1]=d,s[2]=f,s[3]=p,s[4]=g,s[5]=m}const Mr=32,eC=(c,t)=>c.candidate-t.candidate,qr=new Array(Mr).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),_d=new Float32Array(6);function iC(c,t,e,i,s,n){let a=-1,r=0;if(n===Ob)a=Kg(t),a!==-1&&(r=(t[a]+t[a+3])/2);else if(n===QP)a=Kg(c),a!==-1&&(r=sC(e,i,s,a));else if(n===tC){const o=bh(c);let l=Lp*s;const h=e.offset||0,u=(i-h)*6,d=(i+s-h)*6;for(let f=0;f<3;f++){const p=t[f],v=(t[f+3]-p)/Mr;if(s<Mr/4){const M=[...qr];M.length=s;let x=0;for(let w=u;w<d;w+=6,x++){const S=M[x];S.candidate=e[w+2*f],S.count=0;const{bounds:E,leftCacheBounds:b,rightCacheBounds:A}=S;for(let T=0;T<3;T++)A[T]=1/0,A[T+3]=-1/0,b[T]=1/0,b[T+3]=-1/0,E[T]=1/0,E[T+3]=-1/0;Ad(w,e,E)}M.sort(eC);let y=s;for(let w=0;w<y;w++){const S=M[w];for(;w+1<y&&M[w+1].candidate===S.candidate;)M.splice(w+1,1),y--}for(let w=u;w<d;w+=6){const S=e[w+2*f];for(let E=0;E<y;E++){const b=M[E];S>=b.candidate?Ad(w,e,b.rightCacheBounds):(Ad(w,e,b.leftCacheBounds),b.count++)}}for(let w=0;w<y;w++){const S=M[w],E=S.count,b=s-S.count,A=S.leftCacheBounds,T=S.rightCacheBounds;let D=0;E!==0&&(D=bh(A)/o);let I=0;b!==0&&(I=bh(T)/o);const C=a2+Lp*(D*E+I*b);C<l&&(a=f,l=C,r=S.candidate)}}else{for(let y=0;y<Mr;y++){const w=qr[y];w.count=0,w.candidate=p+v+y*v;const S=w.bounds;for(let E=0;E<3;E++)S[E]=1/0,S[E+3]=-1/0}for(let y=u;y<d;y+=6){let E=~~((e[y+2*f]-p)/v);E>=Mr&&(E=Mr-1);const b=qr[E];b.count++,Ad(y,e,b.bounds)}const M=qr[Mr-1];r2(M.bounds,M.rightCacheBounds);for(let y=Mr-2;y>=0;y--){const w=qr[y],S=qr[y+1];o2(w.bounds,S.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let y=0;y<Mr-1;y++){const w=qr[y],S=w.count,E=w.bounds,A=qr[y+1].rightCacheBounds;S!==0&&(x===0?r2(E,_d):o2(E,_d,_d)),x+=S;let T=0,D=0;x!==0&&(T=bh(_d)/o);const I=s-x;I!==0&&(D=bh(A)/o);const C=a2+Lp*(T*x+D*I);C<l&&(a=f,l=C,r=w.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:a,pos:r}}function sC(c,t,e,i){let s=0;const n=c.offset;for(let a=t,r=t+e;a<r;a++)s+=c[(a-n)*6+i*2];return s/e}class kp{constructor(){this.boundingData=new Float32Array(6)}}function nC(c,t,e,i,s,n){let a=i,r=i+s-1;const o=n.pos,l=n.axis*2,h=e.offset||0;for(;;){for(;a<=r&&e[(a-h)*6+l]<o;)a++;for(;a<=r&&e[(r-h)*6+l]>=o;)r--;if(a<r){for(let u=0;u<t;u++){let d=c[a*t+u];c[a*t+u]=c[r*t+u],c[r*t+u]=d}for(let u=0;u<6;u++){const d=a-h,f=r-h,p=e[d*6+u];e[d*6+u]=e[f*6+u],e[f*6+u]=p}a++,r--}else return a}}let kb,df,Yg,Fb;const aC=Math.pow(2,32);function $g(c){return"count"in c?1:1+$g(c.left)+$g(c.right)}function rC(c,t,e){return kb=new Float32Array(e),df=new Uint32Array(e),Yg=new Uint16Array(e),Fb=new Uint8Array(e),qg(c,t)}function qg(c,t){const e=c/4,i=c/2,s="count"in t,n=t.boundingData;for(let a=0;a<6;a++)kb[e+a]=n[a];if(s)return t.buffer?(Fb.set(new Uint8Array(t.buffer),c),c+t.buffer.byteLength):(df[e+6]=t.offset,Yg[i+14]=t.count,Yg[i+15]=Lb,c+Js);{const{left:a,right:r,splitAxis:o}=t,l=c+Js;let h=qg(l,a);const u=c/Js,f=h/Js-u;if(f>aC)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return df[e+6]=f,df[e+7]=o,qg(h,r)}}function oC(c,t,e,i,s,n){const{maxDepth:a,verbose:r,targetLeafSize:o,_strictLeafSize:l=1/0,strategy:h,onProgress:u}=s,d=c.primitiveBuffer,f=c.primitiveBufferStride,p=new Float32Array(6);let g=!1;const m=new kp;return Np(t,e,i,m.boundingData,p),M(m,e,i,p),m;function v(x){u&&u((x-n.offset)/n.count)}function M(x,y,w,S=null,E=0){!g&&E>=a&&(g=!0,r&&console.warn(`BVH: Max depth of ${a} reached when generating BVH. Consider increasing maxDepth.`));const b=w>l;if(w<=o&&!b||E>=a)return v(y+w),x.offset=y,x.count=w,x;const A=iC(x.boundingData,S,t,y,w,h);let T=A.axis===-1?-1:nC(d,f,t,y,w,A);if(A.axis===-1||T===y||T===y+w){if(!b)return v(y+w),x.offset=y,x.count=w,x;A.axis=Math.max(0,Kg(x.boundingData)),T=y+Math.max(1,Math.floor(w/2))}x.splitAxis=A.axis;const D=new kp,I=y,C=T-y;x.left=D,Np(t,I,C,D.boundingData,p),M(D,I,C,p,E+1);const N=new kp,O=T,k=w-C;return x.right=N,Np(t,O,k,N.boundingData,p),M(N,O,k,p,E+1),x}}function cC(c,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=c.getRootRanges(t.range),s=i[0],n=i[i.length-1],a={offset:s.offset,count:n.offset+n.count-s.offset},r=new Float32Array(6*a.count);r.offset=a.offset,c.computePrimitiveBounds(a.offset,a.count,r),c._roots=i.map(o=>{const l=oC(c,r,o.offset,o.count,t,a),h=$g(l),u=new e(Js*h);return rC(0,l,u),u})}class q1{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class lC{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const Ti=new lC;let fo,El;const Vc=[],Td=new q1(()=>new ze);function hC(c,t,e,i,s,n){fo=Td.getPrimitive(),El=Td.getPrimitive(),Vc.push(fo,El),Ti.setBuffer(c._roots[t]);const a=Zg(0,c.geometry,e,i,s,n);Ti.clearBuffer(),Td.releasePrimitive(fo),Td.releasePrimitive(El),Vc.pop(),Vc.pop();const r=Vc.length;return r>0&&(El=Vc[r-1],fo=Vc[r-2]),a}function Zg(c,t,e,i,s=null,n=0,a=0){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti;let h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);return Bi(c,r,fo),i(d,f,!1,a,n+c/fs,fo)}else{let T=function(I){const{uint16Array:C,uint32Array:N}=Ti;let O=I*2;for(;!qi(O,C);)I=ps(I),O=I*2;return Rs(I,N)},D=function(I){const{uint16Array:C,uint32Array:N}=Ti;let O=I*2;for(;!qi(O,C);)I=ms(I,N),O=I*2;return Rs(I,N)+js(O,C)};const d=ps(c),f=ms(c,l);let p=d,g=f,m,v,M,x;if(s&&(M=fo,x=El,Bi(p,r,M),Bi(g,r,x),m=s(M),v=s(x),v<m)){p=f,g=d;const I=m;m=v,v=I,M=x}M||(M=fo,Bi(p,r,M));const y=qi(p*2,o),w=e(M,y,m,a+1,n+p/fs);let S;if(w===n2){const I=T(p),N=D(p)-I;S=i(I,N,!0,a+1,n+p/fs,M)}else S=w&&Zg(p,t,e,i,s,n,a+1);if(S)return!0;x=El,Bi(g,r,x);const E=qi(g*2,o),b=e(x,E,v,a+1,n+g/fs);let A;if(b===n2){const I=T(g),N=D(g)-I;A=i(I,N,!0,a+1,n+g/fs,x)}else A=b&&Zg(g,t,e,i,s,n,a+1);return!!A}}const au=new Ti.constructor,qf=new Ti.constructor,so=new q1(()=>new ze),Wc=new ze,Xc=new ze,Fp=new ze,Up=new ze;let zp=!1;function uC(c,t,e,i){if(zp)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");zp=!0;const s=c._roots,n=t._roots;let a,r=0,o=0;const l=new Gt().copy(e).invert();for(let h=0,u=s.length;h<u;h++){au.setBuffer(s[h]),o=0;const d=so.getPrimitive();Bi(0,au.float32Array,d),d.applyMatrix4(l);for(let f=0,p=n.length;f<p&&(qf.setBuffer(n[f]),a=oa(0,0,e,l,i,r,o,0,0,d),qf.clearBuffer(),o+=n[f].byteLength/Js,!a);f++);if(so.releasePrimitive(d),au.clearBuffer(),r+=s[h].byteLength/Js,a)break}return zp=!1,a}function oa(c,t,e,i,s,n=0,a=0,r=0,o=0,l=null,h=!1){let u,d;h?(u=qf,d=au):(u=au,d=qf);const f=u.float32Array,p=u.uint32Array,g=u.uint16Array,m=d.float32Array,v=d.uint32Array,M=d.uint16Array,x=c*2,y=t*2,w=qi(x,g),S=qi(y,M);let E=!1;if(S&&w)h?E=s(Rs(t,v),js(t*2,M),Rs(c,p),js(c*2,g),o,a+t/fs,r,n+c/fs):E=s(Rs(c,p),js(c*2,g),Rs(t,v),js(t*2,M),r,n+c/fs,o,a+t/fs);else if(S){const b=so.getPrimitive();Bi(t,m,b),b.applyMatrix4(e);const A=ps(c),T=ms(c,p);Bi(A,f,Wc),Bi(T,f,Xc);const D=b.intersectsBox(Wc),I=b.intersectsBox(Xc);E=D&&oa(t,A,i,e,s,a,n,o,r+1,b,!h)||I&&oa(t,T,i,e,s,a,n,o,r+1,b,!h),so.releasePrimitive(b)}else{const b=ps(t),A=ms(t,v);Bi(b,m,Fp),Bi(A,m,Up);const T=l.intersectsBox(Fp),D=l.intersectsBox(Up);if(T&&D)E=oa(c,b,e,i,s,n,a,r,o+1,l,h)||oa(c,A,e,i,s,n,a,r,o+1,l,h);else if(T)if(w)E=oa(c,b,e,i,s,n,a,r,o+1,l,h);else{const I=so.getPrimitive();I.copy(Fp).applyMatrix4(e);const C=ps(c),N=ms(c,p);Bi(C,f,Wc),Bi(N,f,Xc);const O=I.intersectsBox(Wc),k=I.intersectsBox(Xc);E=O&&oa(b,C,i,e,s,a,n,o,r+1,I,!h)||k&&oa(b,N,i,e,s,a,n,o,r+1,I,!h),so.releasePrimitive(I)}else if(D)if(w)E=oa(c,A,e,i,s,n,a,r,o+1,l,h);else{const I=so.getPrimitive();I.copy(Up).applyMatrix4(e);const C=ps(c),N=ms(c,p);Bi(C,f,Wc),Bi(N,f,Xc);const O=I.intersectsBox(Wc),k=I.intersectsBox(Xc);E=O&&oa(A,C,i,e,s,a,n,o,r+1,I,!h)||k&&oa(A,N,i,e,s,a,n,o,r+1,I,!h),so.releasePrimitive(I)}}return E}const Bp=new class{constructor(){let c=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,a)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=a,this.buffer=c=n._roots[a],this.uint16Array=e=new Uint16Array(c),this.uint32Array=t=new Uint32Array(c)},this.reset=()=>{this.root=null,this.buffer=c=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=n=>{let a=n*2;for(;!qi(a,e);)n=ps(n),a=n*2;return Rs(n,t)},this.getRangeEnd=n=>{let a=n*2;for(;!qi(a,e);)n=ms(n,t),a=n*2;return Rs(n,t)+js(a,e)};const s=(n,a,r)=>{const o=a*2,l=qi(o,e);if(!n(r,l,a)&&!l){const u=ps(a),d=ms(a,t);s(n,u,r+1),s(n,d,r+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((a,r,o)=>{if(r){const l=o*2,h=t[o+6],u=e[l+14];return n(a,r,new Float32Array(c,o*4,6),h,u)}else{const l=$1(o,t);return n(a,r,new Float32Array(c,o*4,6),l)}})}}},c2=new ze,Kc=new Float32Array(6);class dC{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...Nb,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),cC(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,s){let n=1/0,a=1/0,r=1/0,o=-1/0,l=-1/0,h=-1/0;for(let u=t,d=t+e;u<d;u++){this.writePrimitiveBounds(u,Kc,0);const[f,p,g,m,v,M]=Kc;f<n&&(n=f),m>o&&(o=m),p<a&&(a=p),v>l&&(l=v),g<r&&(r=g),M>h&&(h=M)}return i[s+0]=n,i[s+1]=a,i[s+2]=r,i[s+3]=o,i[s+4]=l,i[s+5]=h,i}computePrimitiveBounds(t,e,i){const s=i.offset||0;for(let n=t,a=t+e;n<a;n++){this.writePrimitiveBounds(n,Kc,0);const[r,o,l,h,u,d]=Kc,f=(r+h)/2,p=(o+u)/2,g=(l+d)/2,m=(h-r)/2,v=(u-o)/2,M=(d-l)/2,x=(n-s)*6;i[x+0]=f,i[x+1]=m+(Math.abs(f)+m)*uf,i[x+2]=p,i[x+3]=v+(Math.abs(p)+v)*uf,i[x+4]=g,i[x+5]=M+(Math.abs(g)+M)*uf}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,s=e.length;i<s;i++)e[i]+=t;else{const i=this._roots;for(let s=0;s<i.length;s++){const n=i[s],a=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/Js;for(let l=0;l<o;l++){const h=fs*l,u=2*h;qi(u,r)&&(a[h+6]+=t)}}}}traverse(t,e=0){Bp.setBVH(this,e),Bp.traverse(t),Bp.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const s=t[e],n=new Uint32Array(s),a=new Uint16Array(s),r=new Float32Array(s),o=s.byteLength/Js;for(let l=o-1;l>=0;l--){const h=l*fs,u=h*2;if(qi(u,a)){const f=Rs(h,n),p=js(u,a);this.writePrimitiveRangeBounds(f,p,Kc,0),r.set(Kc,h)}else{const f=ps(h),p=ms(h,n);for(let g=0;g<3;g++){const m=r[f+g],v=r[f+g+3],M=r[p+g],x=r[p+g+3];r[h+g]=m<M?m:M,r[h+g+3]=v>x?v:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{Bi(0,new Float32Array(i),c2),t.union(c2)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:n,scratchPrimitive:a,iterate:r}=t;if(s&&n){const u=s;s=(d,f,p,g,m)=>u(d,f,p,g,m)?!0:r(d,f,this,n,p,g,a)}else s||(n?s=(u,d,f,p)=>r(u,d,this,n,f,p,a):s=(u,d,f)=>f);let o=!1,l=0;const h=this._roots;for(let u=0,d=h.length;u<d;u++){const f=h[u];if(o=hC(this,u,i,s,e,l),o)break;l+=f.byteLength/Js}return o}bvhcast(t,e,i){let{intersectsRanges:s}=i;return uC(this,t,e,s)}}function fC(){return typeof SharedArrayBuffer<"u"}function Z1(c){return c.index?c.index.count:c.attributes.position.count}function y0(c){return Z1(c)/3}function pC(c,t=ArrayBuffer){return c>65535?new Uint32Array(new t(4*c)):new Uint16Array(new t(2*c))}function mC(c,t){if(!c.index){const e=c.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=pC(e,i);c.setIndex(new ve(s,1));for(let n=0;n<e;n++)s[n]=n}}function gC(c,t,e){const i=Z1(c)/e,s=t||c.drawRange,n=s.start/e,a=(s.start+s.count)/e,r=Math.max(0,n),o=Math.min(i,a)-r;return{offset:Math.floor(r),count:Math.floor(o)}}function vC(c,t){return c.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function l2(c,t,e){const i=gC(c,t,e),s=vC(c,e);if(!s.length)return[i];const n=[],a=i.offset,r=i.offset+i.count,o=Z1(c)/e,l=[];for(const d of s){const{offset:f,count:p}=d,g=f,m=isFinite(p)?p:o-f,v=f+m;g<r&&v>a&&(l.push({pos:Math.max(a,g),isStart:!0}),l.push({pos:Math.min(r,v),isStart:!1}))}l.sort((d,f)=>d.pos!==f.pos?d.pos-f.pos:d.type==="end"?-1:1);let h=0,u=null;for(const d of l){const f=d.pos;h!==0&&f!==u&&n.push({offset:u,count:f-u}),h+=d.isStart?1:-1,u=f}return n}function MC(c,t){const e=c[c.length-1],i=e.offset+e.count>2**16,s=c.reduce((l,h)=>l+h.count,0),n=i?4:2,a=t?new SharedArrayBuffer(s*n):new ArrayBuffer(s*n),r=i?new Uint32Array(a):new Uint16Array(a);let o=0;for(let l=0;l<c.length;l++){const{offset:h,count:u}=c[l];for(let d=0;d<u;d++)r[o+d]=h+d;o+=u}return r}class yC extends dC{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!fC())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...Nb,...e},e[Y1]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const s=l2(e,t.range,i),n=MC(s,t.useSharedArrayBuffer);this._indirectBuffer=n}else mC(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new ze))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:l2(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Lr{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,s=-1/0;for(let n=0,a=t.length;n<a;n++){const o=t[n][e];i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}setFromPoints(t,e){let i=1/0,s=-1/0;for(let n=0,a=e.length;n<a;n++){const r=e[n],o=t.dot(r);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(t){return this.min>t.max||t.min>this.max}}Lr.prototype.setFromBox=(function(){const c=new _;return function(e,i){const s=i.min,n=i.max;let a=1/0,r=-1/0;for(let o=0;o<=1;o++)for(let l=0;l<=1;l++)for(let h=0;h<=1;h++){c.x=s.x*o+n.x*(1-o),c.y=s.y*l+n.y*(1-l),c.z=s.z*h+n.z*(1-h);const u=e.dot(c);a=Math.min(u,a),r=Math.max(u,r)}this.min=a,this.max=r}})();const xC=(function(){const c=new _,t=new _,e=new _;return function(s,n,a){const r=s.start,o=c,l=n.start,h=t;e.subVectors(r,l),c.subVectors(s.end,s.start),t.subVectors(n.end,n.start);const u=e.dot(h),d=h.dot(o),f=h.dot(h),p=e.dot(o),m=o.dot(o)*f-d*d;let v,M;m!==0?v=(u*d-p*f)/m:v=0,M=(u+v*d)/f,a.x=v,a.y=M}})(),J1=(function(){const c=new Q,t=new _,e=new _;return function(s,n,a,r){xC(s,n,c);let o=c.x,l=c.y;if(o>=0&&o<=1&&l>=0&&l<=1){s.at(o,a),n.at(l,r);return}else if(o>=0&&o<=1){l<0?n.at(0,r):n.at(1,r),s.closestPointToPoint(r,!0,a);return}else if(l>=0&&l<=1){o<0?s.at(0,a):s.at(1,a),n.closestPointToPoint(a,!0,r);return}else{let h;o<0?h=s.start:h=s.end;let u;l<0?u=n.start:u=n.end;const d=t,f=e;if(s.closestPointToPoint(u,!0,t),n.closestPointToPoint(h,!0,e),d.distanceToSquared(u)<=f.distanceToSquared(h)){a.copy(d),r.copy(u);return}else{a.copy(h),r.copy(f);return}}}})(),wC=(function(){const c=new _,t=new _,e=new fa,i=new Or;return function(n,a){const{radius:r,center:o}=n,{a:l,b:h,c:u}=a;if(i.start=l,i.end=h,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r||(i.start=l,i.end=u,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r)||(i.start=h,i.end=u,i.closestPointToPoint(o,!0,c).distanceTo(o)<=r))return!0;const g=a.getPlane(e);if(Math.abs(g.distanceToPoint(o))<=r){const v=g.projectPoint(o,t);if(a.containsPoint(v))return!0}return!1}})(),bC=["x","y","z"],br=1e-15,h2=br*br;function Wn(c){return Math.abs(c)<br}class ya extends As{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new _),this.satBounds=new Array(4).fill().map(()=>new Lr),this.points=[this.a,this.b,this.c],this.plane=new fa,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Or,this.needsUpdate=!0}intersectsSphere(t){return wC(t,this)}update(){const t=this.a,e=this.b,i=this.c,s=this.points,n=this.satAxes,a=this.satBounds,r=n[0],o=a[0];this.getNormal(r),o.setFromPoints(r,s);const l=n[1],h=a[1];l.subVectors(t,e),h.setFromPoints(l,s);const u=n[2],d=a[2];u.subVectors(e,i),d.setFromPoints(u,s);const f=n[3],p=a[3];f.subVectors(i,t),p.setFromPoints(f,s);const g=l.length(),m=u.length(),v=f.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,g<br?m<br||v<br?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<br?v<br?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):v<br&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(r,t),this.needsUpdate=!1}}ya.prototype.closestPointToSegment=(function(){const c=new _,t=new _,e=new Or;return function(s,n=null,a=null){const{start:r,end:o}=s,l=this.points;let h,u=1/0;for(let d=0;d<3;d++){const f=(d+1)%3;e.start.copy(l[d]),e.end.copy(l[f]),J1(e,s,c,t),h=c.distanceToSquared(t),h<u&&(u=h,n&&n.copy(c),a&&a.copy(t))}return this.closestPointToPoint(r,c),h=r.distanceToSquared(c),h<u&&(u=h,n&&n.copy(c),a&&a.copy(r)),this.closestPointToPoint(o,c),h=o.distanceToSquared(c),h<u&&(u=h,n&&n.copy(c),a&&a.copy(o)),Math.sqrt(u)}})();ya.prototype.intersectsTriangle=(function(){const c=new ya,t=new Lr,e=new Lr,i=new _,s=new _,n=new _,a=new _,r=new Or,o=new Or,l=new _,h=new Q,u=new Q;function d(x,y,w,S){const E=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?E.copy(x.plane.normal):E.copy(y.plane.normal);const b=x.satBounds,A=x.satAxes;for(let I=1;I<4;I++){const C=b[I],N=A[I];if(t.setFromPoints(N,y.points),C.isSeparated(t)||(a.copy(E).cross(N),t.setFromPoints(a,x.points),e.setFromPoints(a,y.points),t.isSeparated(e)))return!1}const T=y.satBounds,D=y.satAxes;for(let I=1;I<4;I++){const C=T[I],N=D[I];if(t.setFromPoints(N,x.points),C.isSeparated(t)||(a.crossVectors(E,N),t.setFromPoints(a,x.points),e.setFromPoints(a,y.points),t.isSeparated(e)))return!1}return w&&(S||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function f(x,y,w,S,E,b,A,T,D,I,C){let N=A/(A-T);I.x=S+(E-S)*N,C.start.subVectors(y,x).multiplyScalar(N).add(x),N=A/(A-D),I.y=S+(b-S)*N,C.end.subVectors(w,x).multiplyScalar(N).add(x)}function p(x,y,w,S,E,b,A,T,D,I,C){if(E>0)f(x.c,x.a,x.b,S,y,w,D,A,T,I,C);else if(b>0)f(x.b,x.a,x.c,w,y,S,T,A,D,I,C);else if(T*D>0||A!=0)f(x.a,x.b,x.c,y,w,S,A,T,D,I,C);else if(T!=0)f(x.b,x.a,x.c,w,y,S,T,A,D,I,C);else if(D!=0)f(x.c,x.a,x.b,S,y,w,D,A,T,I,C);else return!0;return!1}function g(x,y,w,S){const E=y.degenerateSegment,b=x.plane.distanceToPoint(E.start),A=x.plane.distanceToPoint(E.end);return Wn(b)?Wn(A)?d(x,y,w,S):(w&&(w.start.copy(E.start),w.end.copy(E.start)),x.containsPoint(E.start)):Wn(A)?(w&&(w.start.copy(E.end),w.end.copy(E.end)),x.containsPoint(E.end)):x.plane.intersectLine(E,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function m(x,y,w){const S=y.a;return Wn(x.plane.distanceToPoint(S))&&x.containsPoint(S)?(w&&(w.start.copy(S),w.end.copy(S)),!0):!1}function v(x,y,w){const S=x.degenerateSegment,E=y.a;return S.closestPointToPoint(E,!0,i),E.distanceToSquared(i)<h2?(w&&(w.start.copy(E),w.end.copy(E)),!0):!1}function M(x,y,w,S){if(x.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const E=x.degenerateSegment,b=y.degenerateSegment,A=s,T=n;E.delta(A),b.delta(T);const D=i.subVectors(b.start,E.start),I=A.x*T.y-A.y*T.x;if(Wn(I))return!1;const C=(D.x*T.y-D.y*T.x)/I,N=-(A.x*D.y-A.y*D.x)/I;if(C<0||C>1||N<0||N>1)return!1;const O=E.start.z+A.z*C,k=b.start.z+T.z*N;return Wn(O-k)?(w&&(w.start.copy(E.start).addScaledVector(A,C),w.end.copy(E.start).addScaledVector(A,C)),!0):!1}else return y.isDegenerateIntoPoint?v(x,y,w):g(y,x,w,S);else{if(x.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(x.a)<h2?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:y.isDegenerateIntoSegment?v(y,x,w):m(y,x,w);if(y.isDegenerateIntoPoint)return m(x,y,w);if(y.isDegenerateIntoSegment)return g(x,y,w,S)}}return function(y,w=null,S=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(c.copy(y),c.update(),y=c);const E=M(this,y,w,S);if(E!==void 0)return E;const b=this.plane,A=y.plane;let T=A.distanceToPoint(this.a),D=A.distanceToPoint(this.b),I=A.distanceToPoint(this.c);Wn(T)&&(T=0),Wn(D)&&(D=0),Wn(I)&&(I=0);const C=T*D,N=T*I;if(C>0&&N>0)return!1;let O=b.distanceToPoint(y.a),k=b.distanceToPoint(y.b),B=b.distanceToPoint(y.c);Wn(O)&&(O=0),Wn(k)&&(k=0),Wn(B)&&(B=0);const X=O*k,J=O*B;if(X>0&&J>0)return!1;s.copy(b.normal),n.copy(A.normal);const $=s.cross(n);let it=0,rt=Math.abs($.x);const Lt=Math.abs($.y);Lt>rt&&(rt=Lt,it=1),Math.abs($.z)>rt&&(it=2);const Zt=bC[it],q=this.a[Zt],ot=this.b[Zt],st=this.c[Zt],G=y.a[Zt],Nt=y.b[Zt],Xt=y.c[Zt];if(p(this,q,ot,st,C,N,T,D,I,h,r))return d(this,y,w,S);if(p(y,G,Nt,Xt,X,J,O,k,B,u,o))return d(this,y,w,S);if(h.y<h.x){const kt=h.y;h.y=h.x,h.x=kt,l.copy(r.start),r.start.copy(r.end),r.end.copy(l)}if(u.y<u.x){const kt=u.y;u.y=u.x,u.x=kt,l.copy(o.start),o.start.copy(o.end),o.end.copy(l)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(o.start):w.start.copy(r.start),u.y<h.y?w.end.copy(o.end):w.end.copy(r.end)),!0)}})();ya.prototype.distanceToPoint=(function(){const c=new _;return function(e){return this.closestPointToPoint(e,c),e.distanceTo(c)}})();ya.prototype.distanceToTriangle=(function(){const c=new _,t=new _,e=["a","b","c"],i=new Or,s=new Or;return function(a,r=null,o=null){const l=r||o?i:null;if(this.intersectsTriangle(a,l,!0))return(r||o)&&(r&&l.getCenter(r),o&&l.getCenter(o)),0;let h=1/0;for(let u=0;u<3;u++){let d;const f=e[u],p=a[f];this.closestPointToPoint(p,c),d=p.distanceToSquared(c),d<h&&(h=d,r&&r.copy(c),o&&o.copy(p));const g=this[f];a.closestPointToPoint(g,c),d=g.distanceToSquared(c),d<h&&(h=d,r&&r.copy(g),o&&o.copy(c))}for(let u=0;u<3;u++){const d=e[u],f=e[(u+1)%3];i.set(this[d],this[f]);for(let p=0;p<3;p++){const g=e[p],m=e[(p+1)%3];s.set(a[g],a[m]),J1(i,s,c,t);const v=c.distanceToSquared(t);v<h&&(h=v,r&&r.copy(c),o&&o.copy(t))}}return Math.sqrt(h)}})();class fn{constructor(t,e,i){this.isOrientedBox=!0,this.min=new _,this.max=new _,this.matrix=new Gt,this.invMatrix=new Gt,this.points=new Array(8).fill().map(()=>new _),this.satAxes=new Array(3).fill().map(()=>new _),this.satBounds=new Array(3).fill().map(()=>new Lr),this.alignedSatBounds=new Array(3).fill().map(()=>new Lr),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}fn.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,s=this.points;for(let l=0;l<=1;l++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const d=1*l|2*h|4*u,f=s[d];f.x=l?i.x:e.x,f.y=h?i.y:e.y,f.z=u?i.z:e.z,f.applyMatrix4(t)}const n=this.satBounds,a=this.satAxes,r=s[0];for(let l=0;l<3;l++){const h=a[l],u=n[l],d=1<<l,f=s[d];h.subVectors(r,f),u.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}})();fn.prototype.intersectsBox=(function(){const c=new Lr;return function(e){this.needsUpdate&&this.update();const i=e.min,s=e.max,n=this.satBounds,a=this.satAxes,r=this.alignedSatBounds;if(c.min=i.x,c.max=s.x,r[0].isSeparated(c)||(c.min=i.y,c.max=s.y,r[1].isSeparated(c))||(c.min=i.z,c.max=s.z,r[2].isSeparated(c)))return!1;for(let o=0;o<3;o++){const l=a[o],h=n[o];if(c.setFromBox(l,e),h.isSeparated(c))return!1}return!0}})();fn.prototype.intersectsTriangle=(function(){const c=new ya,t=new Array(3),e=new Lr,i=new Lr,s=new _;return function(a){this.needsUpdate&&this.update(),a.isExtendedTriangle?a.needsUpdate&&a.update():(c.copy(a),c.update(),a=c);const r=this.satBounds,o=this.satAxes;t[0]=a.a,t[1]=a.b,t[2]=a.c;for(let d=0;d<3;d++){const f=r[d],p=o[d];if(e.setFromPoints(p,t),f.isSeparated(e))return!1}const l=a.satBounds,h=a.satAxes,u=this.points;for(let d=0;d<3;d++){const f=l[d],p=h[d];if(e.setFromPoints(p,u),f.isSeparated(e))return!1}for(let d=0;d<3;d++){const f=o[d];for(let p=0;p<4;p++){const g=h[p];if(s.crossVectors(f,g),e.setFromPoints(s,t),i.setFromPoints(s,u),e.isSeparated(i))return!1}}return!0}})();fn.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})();fn.prototype.distanceToPoint=(function(){const c=new _;return function(e){return this.closestPointToPoint(e,c),e.distanceTo(c)}})();fn.prototype.distanceToBox=(function(){const c=["x","y","z"],t=new Array(12).fill().map(()=>new Or),e=new Array(12).fill().map(()=>new Or),i=new _,s=new _;return function(a,r=0,o=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(a))return(o||l)&&(a.getCenter(s),this.closestPointToPoint(s,i),a.closestPointToPoint(i,s),o&&o.copy(i),l&&l.copy(s)),0;const h=r*r,u=a.min,d=a.max,f=this.points;let p=1/0;for(let m=0;m<8;m++){const v=f[m];s.copy(v).clamp(u,d);const M=v.distanceToSquared(s);if(M<p&&(p=M,o&&o.copy(v),l&&l.copy(s),M<h))return Math.sqrt(M)}let g=0;for(let m=0;m<3;m++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){const x=(m+1)%3,y=(m+2)%3,w=v<<x|M<<y,S=1<<m|v<<x|M<<y,E=f[w],b=f[S];t[g].set(E,b);const T=c[m],D=c[x],I=c[y],C=e[g],N=C.start,O=C.end;N[T]=u[T],N[D]=v?u[D]:d[D],N[I]=M?u[I]:d[D],O[T]=d[T],O[D]=v?u[D]:d[D],O[I]=M?u[I]:d[D],g++}for(let m=0;m<=1;m++)for(let v=0;v<=1;v++)for(let M=0;M<=1;M++){s.x=m?d.x:u.x,s.y=v?d.y:u.y,s.z=M?d.z:u.z,this.closestPointToPoint(s,i);const x=s.distanceToSquared(i);if(x<p&&(p=x,o&&o.copy(i),l&&l.copy(s),x<h))return Math.sqrt(x)}for(let m=0;m<12;m++){const v=t[m];for(let M=0;M<12;M++){const x=e[M];J1(v,x,i,s);const y=i.distanceToSquared(s);if(y<p&&(p=y,o&&o.copy(i),l&&l.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class SC extends q1{constructor(){super(()=>new ya)}}const Qn=new SC,Sh=new _,Hp=new _;function EC(c,t,e={},i=0,s=1/0){const n=i*i,a=s*s;let r=1/0,o=null;if(c.shapecast({boundsTraverseOrder:h=>(Sh.copy(t).clamp(h.min,h.max),Sh.distanceToSquared(t)),intersectsBounds:(h,u,d)=>d<r&&d<a,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Sh);const d=t.distanceToSquared(Sh);return d<r&&(Hp.copy(Sh),r=d,o=u),d<n}}),r===1/0)return null;const l=Math.sqrt(r);return e.point?e.point.copy(Hp):e.point=Hp.clone(),e.distance=l,e.faceIndex=o,e}const Rd=parseInt(Ru)>=169,AC=parseInt(Ru)<=161,Po=new _,Co=new _,Oo=new _,Dd=new Q,Id=new Q,Pd=new Q,u2=new _,d2=new _,f2=new _,Eh=new _;function _C(c,t,e,i,s,n,a,r){let o;if(n===Ai?o=c.intersectTriangle(i,e,t,!0,s):o=c.intersectTriangle(t,e,i,n!==ds,s),o===null)return null;const l=c.origin.distanceTo(s);return l<a||l>r?null:{distance:l,point:s.clone()}}function p2(c,t,e,i,s,n,a,r,o,l,h){Po.fromBufferAttribute(t,n),Co.fromBufferAttribute(t,a),Oo.fromBufferAttribute(t,r);const u=_C(c,Po,Co,Oo,Eh,o,l,h);if(u){if(i){Dd.fromBufferAttribute(i,n),Id.fromBufferAttribute(i,a),Pd.fromBufferAttribute(i,r),u.uv=new Q;const f=As.getInterpolation(Eh,Po,Co,Oo,Dd,Id,Pd,u.uv);Rd||(u.uv=f)}if(s){Dd.fromBufferAttribute(s,n),Id.fromBufferAttribute(s,a),Pd.fromBufferAttribute(s,r),u.uv1=new Q;const f=As.getInterpolation(Eh,Po,Co,Oo,Dd,Id,Pd,u.uv1);Rd||(u.uv1=f),AC&&(u.uv2=u.uv1)}if(e){u2.fromBufferAttribute(e,n),d2.fromBufferAttribute(e,a),f2.fromBufferAttribute(e,r),u.normal=new _;const f=As.getInterpolation(Eh,Po,Co,Oo,u2,d2,f2,u.normal);u.normal.dot(c.direction)>0&&u.normal.multiplyScalar(-1),Rd||(u.normal=f)}const d={a:n,b:a,c:r,normal:new _,materialIndex:0};if(As.getNormal(Po,Co,Oo,d.normal),u.face=d,u.faceIndex=n,Rd){const f=new _;As.getBarycoord(Eh,Po,Co,Oo,f),u.barycoord=f}}return u}function m2(c){return c&&c.isMaterial?c.side:c}function x0(c,t,e,i,s,n,a){const r=i*3;let o=r+0,l=r+1,h=r+2;const{index:u,groups:d}=c;c.index&&(o=u.getX(o),l=u.getX(l),h=u.getX(h));const{position:f,normal:p,uv:g,uv1:m}=c.attributes;if(Array.isArray(t)){const v=i*3;for(let M=0,x=d.length;M<x;M++){const{start:y,count:w,materialIndex:S}=d[M];if(v>=y&&v<y+w){const E=m2(t[S]),b=p2(e,f,p,g,m,o,l,h,E,n,a);if(b)if(b.faceIndex=i,b.face.materialIndex=S,s)s.push(b);else return b}}}else{const v=m2(t),M=p2(e,f,p,g,m,o,l,h,v,n,a);if(M)if(M.faceIndex=i,M.face.materialIndex=0,s)s.push(M);else return M}return null}function as(c,t,e,i){const s=c.a,n=c.b,a=c.c;let r=t,o=t+1,l=t+2;e&&(r=e.getX(r),o=e.getX(o),l=e.getX(l)),s.x=i.getX(r),s.y=i.getY(r),s.z=i.getZ(r),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),a.x=i.getX(l),a.y=i.getY(l),a.z=i.getZ(l)}function TC(c,t,e,i,s,n,a,r){const{geometry:o,_indirectBuffer:l}=c;for(let h=i,u=i+s;h<u;h++)x0(o,t,e,h,n,a,r)}function RC(c,t,e,i,s,n,a){const{geometry:r,_indirectBuffer:o}=c;let l=1/0,h=null;for(let u=i,d=i+s;u<d;u++){let f;f=x0(r,t,e,u,null,n,a),f&&f.distance<l&&(h=f,l=f.distance)}return h}function DC(c,t,e,i,s,n,a){const{geometry:r}=e,{index:o}=r,l=r.attributes.position;for(let h=c,u=t+c;h<u;h++){let d;if(d=h,as(a,d*3,o,l),a.needsUpdate=!0,i(a,d,s,n))return!0}return!1}function IC(c,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=c.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,a,r,o,l=0;const h=c._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),r=new Uint16Array(n),o=new Float32Array(n),u(0,l),l+=n.byteLength;function u(d,f,p=!1){const g=d*2;if(qi(g,r)){const m=Rs(d,a),v=js(g,r);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=3*m,A=3*(m+v);b<A;b++){let T=i[b];const D=s.getX(T),I=s.getY(T),C=s.getZ(T);D<M&&(M=D),D>w&&(w=D),I<x&&(x=I),I>S&&(S=I),C<y&&(y=C),C>E&&(E=C)}return o[d+0]!==M||o[d+1]!==x||o[d+2]!==y||o[d+3]!==w||o[d+4]!==S||o[d+5]!==E?(o[d+0]=M,o[d+1]=x,o[d+2]=y,o[d+3]=w,o[d+4]=S,o[d+5]=E,!0):!1}else{const m=ps(d),v=ms(d,a);let M=p,x=!1,y=!1;if(t){if(!M){const T=m/fs+f/Js,D=v/fs+f/Js;x=t.has(T),y=t.has(D),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(m,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let T=0;T<3;T++){const D=m+T,I=v+T,C=o[D],N=o[D+3],O=o[I],k=o[I+3];o[d+T]=C<O?C:O,o[d+T+3]=N>k?N:k}return A}}}function wo(c,t,e,i,s){let n,a,r,o,l,h;const u=1/e.direction.x,d=1/e.direction.y,f=1/e.direction.z,p=e.origin.x,g=e.origin.y,m=e.origin.z;let v=t[c],M=t[c+3],x=t[c+1],y=t[c+3+1],w=t[c+2],S=t[c+3+2];return u>=0?(n=(v-p)*u,a=(M-p)*u):(n=(M-p)*u,a=(v-p)*u),d>=0?(r=(x-g)*d,o=(y-g)*d):(r=(y-g)*d,o=(x-g)*d),n>o||r>a||((r>n||isNaN(n))&&(n=r),(o<a||isNaN(a))&&(a=o),f>=0?(l=(w-m)*f,h=(S-m)*f):(l=(S-m)*f,h=(w-m)*f),n>h||l>a)?!1:((l>n||n!==n)&&(n=l),(h<a||a!==a)&&(a=h),n<=s&&a>=i)}function PC(c,t,e,i,s,n,a,r){const{geometry:o,_indirectBuffer:l}=c;for(let h=i,u=i+s;h<u;h++){let d=l?l[h]:h;x0(o,t,e,d,n,a,r)}}function CC(c,t,e,i,s,n,a){const{geometry:r,_indirectBuffer:o}=c;let l=1/0,h=null;for(let u=i,d=i+s;u<d;u++){let f;f=x0(r,t,e,o?o[u]:u,null,n,a),f&&f.distance<l&&(h=f,l=f.distance)}return h}function OC(c,t,e,i,s,n,a){const{geometry:r}=e,{index:o}=r,l=r.attributes.position;for(let h=c,u=t+c;h<u;h++){let d;if(d=e.resolveTriangleIndex(h),as(a,d*3,o,l),a.needsUpdate=!0,i(a,d,s,n))return!0}return!1}function LC(c,t,e,i,s,n,a){Ti.setBuffer(c._roots[t]),Jg(0,c,e,i,s,n,a),Ti.clearBuffer()}function Jg(c,t,e,i,s,n,a){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti,h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);TC(t,e,i,d,f,s,n,a)}else{const d=ps(c);wo(d,r,i,n,a)&&Jg(d,t,e,i,s,n,a);const f=ms(c,l);wo(f,r,i,n,a)&&Jg(f,t,e,i,s,n,a)}}const NC=["x","y","z"];function kC(c,t,e,i,s,n){Ti.setBuffer(c._roots[t]);const a=jg(0,c,e,i,s,n);return Ti.clearBuffer(),a}function jg(c,t,e,i,s,n){const{float32Array:a,uint16Array:r,uint32Array:o}=Ti;let l=c*2;if(qi(l,r)){const u=Rs(c,o),d=js(l,r);return RC(t,e,i,u,d,s,n)}else{const u=$1(c,o),d=NC[u],p=i.direction[d]>=0;let g,m;p?(g=ps(c),m=ms(c,o)):(g=ms(c,o),m=ps(c));const M=wo(g,a,i,s,n)?jg(g,t,e,i,s,n):null;if(M){const w=M.point[d];if(p?w<=a[m+u]:w>=a[m+u+3])return M}const y=wo(m,a,i,s,n)?jg(m,t,e,i,s,n):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Cd=new ze,Yc=new ya,$c=new ya,Ah=new Gt,g2=new fn,Od=new fn;function FC(c,t,e,i){Ti.setBuffer(c._roots[t]);const s=Qg(0,c,e,i);return Ti.clearBuffer(),s}function Qg(c,t,e,i,s=null){const{float32Array:n,uint16Array:a,uint32Array:r}=Ti;let o=c*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),g2.set(e.boundingBox.min,e.boundingBox.max,i),s=g2),qi(o,a)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,g=Rs(c,r),m=js(o,a);if(Ah.copy(i).invert(),e.boundsTree)return Bi(c,n,Od),Od.matrix.copy(Ah),Od.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>Od.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=g*3,y=(m+g)*3;x<y;x+=3)if(as($c,x,u,d),$c.needsUpdate=!0,M.intersectsTriangle($c))return!0;return!1}});{const v=y0(e);for(let M=g*3,x=(m+g)*3;M<x;M+=3){as(Yc,M,u,d),Yc.a.applyMatrix4(Ah),Yc.b.applyMatrix4(Ah),Yc.c.applyMatrix4(Ah),Yc.needsUpdate=!0;for(let y=0,w=v*3;y<w;y+=3)if(as($c,y,f,p),$c.needsUpdate=!0,Yc.intersectsTriangle($c))return!0}}}else{const h=ps(c),u=ms(c,r);return Bi(h,n,Cd),!!(s.intersectsBox(Cd)&&Qg(h,t,e,i,s)||(Bi(u,n,Cd),s.intersectsBox(Cd)&&Qg(u,t,e,i,s)))}}const Ld=new Gt,Gp=new fn,_h=new fn,UC=new _,zC=new _,BC=new _,HC=new _;function GC(c,t,e,i={},s={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),Gp.set(t.boundingBox.min,t.boundingBox.max,e),Gp.needsUpdate=!0;const r=c.geometry,o=r.attributes.position,l=r.index,h=t.attributes.position,u=t.index,d=Qn.getPrimitive(),f=Qn.getPrimitive();let p=UC,g=zC,m=null,v=null;s&&(m=BC,v=HC);let M=1/0,x=null,y=null;return Ld.copy(e).invert(),_h.matrix.copy(Ld),c.shapecast({boundsTraverseOrder:w=>Gp.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<a?(S&&(_h.min.copy(w.min),_h.max.copy(w.max),_h.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:b=>_h.distanceToBox(b),intersectsBounds:(b,A,T)=>T<M&&T<a,intersectsRange:(b,A)=>{for(let T=b,D=b+A;T<D;T++){as(f,3*T,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let I=w,C=w+S;I<C;I++){as(d,3*I,l,o),d.needsUpdate=!0;const N=d.distanceToTriangle(f,p,m);if(N<M&&(g.copy(p),v&&v.copy(m),M=N,x=I,y=T),N<n)return!0}}}});{const E=y0(t);for(let b=0,A=E;b<A;b++){as(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=w,D=w+S;T<D;T++){as(d,3*T,l,o),d.needsUpdate=!0;const I=d.distanceToTriangle(f,p,m);if(I<M&&(g.copy(p),v&&v.copy(m),M=I,x=T,y=b),I<n)return!0}}}}}),Qn.releasePrimitive(d),Qn.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=M,i.faceIndex=x,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(Ld),g.applyMatrix4(Ld),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function VC(c,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=c.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,a,r,o,l=0;const h=c._roots;for(let d=0,f=h.length;d<f;d++)n=h[d],a=new Uint32Array(n),r=new Uint16Array(n),o=new Float32Array(n),u(0,l),l+=n.byteLength;function u(d,f,p=!1){const g=d*2;if(qi(g,r)){const m=Rs(d,a),v=js(g,r);let M=1/0,x=1/0,y=1/0,w=-1/0,S=-1/0,E=-1/0;for(let b=m,A=m+v;b<A;b++){const T=3*c.resolveTriangleIndex(b);for(let D=0;D<3;D++){let I=T+D;I=i?i[I]:I;const C=s.getX(I),N=s.getY(I),O=s.getZ(I);C<M&&(M=C),C>w&&(w=C),N<x&&(x=N),N>S&&(S=N),O<y&&(y=O),O>E&&(E=O)}}return o[d+0]!==M||o[d+1]!==x||o[d+2]!==y||o[d+3]!==w||o[d+4]!==S||o[d+5]!==E?(o[d+0]=M,o[d+1]=x,o[d+2]=y,o[d+3]=w,o[d+4]=S,o[d+5]=E,!0):!1}else{const m=ps(d),v=ms(d,a);let M=p,x=!1,y=!1;if(t){if(!M){const T=m/fs+f/Js,D=v/fs+f/Js;x=t.has(T),y=t.has(D),M=!x&&!y}}else x=!0,y=!0;const w=M||x,S=M||y;let E=!1;w&&(E=u(m,f,M));let b=!1;S&&(b=u(v,f,M));const A=E||b;if(A)for(let T=0;T<3;T++){const D=m+T,I=v+T,C=o[D],N=o[D+3],O=o[I],k=o[I+3];o[d+T]=C<O?C:O,o[d+T+3]=N>k?N:k}return A}}}function WC(c,t,e,i,s,n,a){Ti.setBuffer(c._roots[t]),t1(0,c,e,i,s,n,a),Ti.clearBuffer()}function t1(c,t,e,i,s,n,a){const{float32Array:r,uint16Array:o,uint32Array:l}=Ti,h=c*2;if(qi(h,o)){const d=Rs(c,l),f=js(h,o);PC(t,e,i,d,f,s,n,a)}else{const d=ps(c);wo(d,r,i,n,a)&&t1(d,t,e,i,s,n,a);const f=ms(c,l);wo(f,r,i,n,a)&&t1(f,t,e,i,s,n,a)}}const XC=["x","y","z"];function KC(c,t,e,i,s,n){Ti.setBuffer(c._roots[t]);const a=e1(0,c,e,i,s,n);return Ti.clearBuffer(),a}function e1(c,t,e,i,s,n){const{float32Array:a,uint16Array:r,uint32Array:o}=Ti;let l=c*2;if(qi(l,r)){const u=Rs(c,o),d=js(l,r);return CC(t,e,i,u,d,s,n)}else{const u=$1(c,o),d=XC[u],p=i.direction[d]>=0;let g,m;p?(g=ps(c),m=ms(c,o)):(g=ms(c,o),m=ps(c));const M=wo(g,a,i,s,n)?e1(g,t,e,i,s,n):null;if(M){const w=M.point[d];if(p?w<=a[m+u]:w>=a[m+u+3])return M}const y=wo(m,a,i,s,n)?e1(m,t,e,i,s,n):null;return M&&y?M.distance<=y.distance?M:y:M||y||null}}const Nd=new ze,qc=new ya,Zc=new ya,Th=new Gt,v2=new fn,kd=new fn;function YC(c,t,e,i){Ti.setBuffer(c._roots[t]);const s=i1(0,c,e,i);return Ti.clearBuffer(),s}function i1(c,t,e,i,s=null){const{float32Array:n,uint16Array:a,uint32Array:r}=Ti;let o=c*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),v2.set(e.boundingBox.min,e.boundingBox.max,i),s=v2),qi(o,a)){const h=t.geometry,u=h.index,d=h.attributes.position,f=e.index,p=e.attributes.position,g=Rs(c,r),m=js(o,a);if(Th.copy(i).invert(),e.boundsTree)return Bi(c,n,kd),kd.matrix.copy(Th),kd.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:M=>kd.intersectsBox(M),intersectsTriangle:M=>{M.a.applyMatrix4(i),M.b.applyMatrix4(i),M.c.applyMatrix4(i),M.needsUpdate=!0;for(let x=g,y=m+g;x<y;x++)if(as(Zc,3*t.resolveTriangleIndex(x),u,d),Zc.needsUpdate=!0,M.intersectsTriangle(Zc))return!0;return!1}});{const v=y0(e);for(let M=g,x=m+g;M<x;M++){const y=t.resolveTriangleIndex(M);as(qc,3*y,u,d),qc.a.applyMatrix4(Th),qc.b.applyMatrix4(Th),qc.c.applyMatrix4(Th),qc.needsUpdate=!0;for(let w=0,S=v*3;w<S;w+=3)if(as(Zc,w,f,p),Zc.needsUpdate=!0,qc.intersectsTriangle(Zc))return!0}}}else{const h=ps(c),u=ms(c,r);return Bi(h,n,Nd),!!(s.intersectsBox(Nd)&&i1(h,t,e,i,s)||(Bi(u,n,Nd),s.intersectsBox(Nd)&&i1(u,t,e,i,s)))}}const Fd=new Gt,Vp=new fn,Rh=new fn,$C=new _,qC=new _,ZC=new _,JC=new _;function jC(c,t,e,i={},s={},n=0,a=1/0){t.boundingBox||t.computeBoundingBox(),Vp.set(t.boundingBox.min,t.boundingBox.max,e),Vp.needsUpdate=!0;const r=c.geometry,o=r.attributes.position,l=r.index,h=t.attributes.position,u=t.index,d=Qn.getPrimitive(),f=Qn.getPrimitive();let p=$C,g=qC,m=null,v=null;s&&(m=ZC,v=JC);let M=1/0,x=null,y=null;return Fd.copy(e).invert(),Rh.matrix.copy(Fd),c.shapecast({boundsTraverseOrder:w=>Vp.distanceToBox(w),intersectsBounds:(w,S,E)=>E<M&&E<a?(S&&(Rh.min.copy(w.min),Rh.max.copy(w.max),Rh.needsUpdate=!0),!0):!1,intersectsRange:(w,S)=>{if(t.boundsTree){const E=t.boundsTree;return E.shapecast({boundsTraverseOrder:b=>Rh.distanceToBox(b),intersectsBounds:(b,A,T)=>T<M&&T<a,intersectsRange:(b,A)=>{for(let T=b,D=b+A;T<D;T++){const I=E.resolveTriangleIndex(T);as(f,3*I,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let C=w,N=w+S;C<N;C++){const O=c.resolveTriangleIndex(C);as(d,3*O,l,o),d.needsUpdate=!0;const k=d.distanceToTriangle(f,p,m);if(k<M&&(g.copy(p),v&&v.copy(m),M=k,x=C,y=T),k<n)return!0}}}})}else{const E=y0(t);for(let b=0,A=E;b<A;b++){as(f,3*b,u,h),f.a.applyMatrix4(e),f.b.applyMatrix4(e),f.c.applyMatrix4(e),f.needsUpdate=!0;for(let T=w,D=w+S;T<D;T++){const I=c.resolveTriangleIndex(T);as(d,3*I,l,o),d.needsUpdate=!0;const C=d.distanceToTriangle(f,p,m);if(C<M&&(g.copy(p),v&&v.copy(m),M=C,x=T,y=b),C<n)return!0}}}}}),Qn.releasePrimitive(d),Qn.releasePrimitive(f),M===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=M,i.faceIndex=x,s&&(s.point?s.point.copy(v):s.point=v.clone(),s.point.applyMatrix4(Fd),g.applyMatrix4(Fd),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function M2(c,t,e){return c===null?null:(c.point.applyMatrix4(t.matrixWorld),c.distance=c.point.distanceTo(e.ray.origin),c.object=t,c)}const Ud=new fn,zd=new pc,y2=new _,x2=new Gt,w2=new _,Wp=["getX","getY","getZ"];class Zf extends yC{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,s=t._roots,n=t._indirectBuffer,a=i.getIndex(),r={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(r.roots=s.map(o=>o.slice()),r.index=a?a.array.slice():null,r.indirectBuffer=n?n.slice():null):(r.roots=s,r.index=a?a.array:null,r.indirectBuffer=n),r}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:s,roots:n,indirectBuffer:a}=t;t.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 r=new Zf(e,{...i,[Y1]:!0});if(r._roots=n,r._indirectBuffer=a||null,i.setIndex){const l=e.getIndex();if(l===null){const h=new ve(t.index,1,!1);e.setIndex(h)}else l.array!==s&&(l.array.set(s),l.needsUpdate=!0)}return r;function o(l){for(let h=0;h<l.length;h++){const u=l[h],d=new Uint32Array(u),f=new Uint16Array(u);for(let p=0,g=u.byteLength/Js;p<g;p++){const m=fs*p,v=2*m;qi(v,f)||(d[m+6]=d[m+6]/fs-p)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,a=s.attributes.position,r=s.index?s.index.array:null,l=(n?n[t]:t)*3;let h=l+0,u=l+1,d=l+2;r&&(h=r[h],u=r[u],d=r[d]);for(let f=0;f<3;f++){const p=a[Wp[f]](h),g=a[Wp[f]](u),m=a[Wp[f]](d);let v=p;g<v&&(v=g),m<v&&(v=m);let M=p;g>M&&(M=g),m>M&&(M=m),e[i+f]=v,e[i+f+3]=M}return e}computePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,a=s.attributes.position,r=s.index?s.index.array:null,o=a.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=a.array,h=a.offset||0;let u=3;a.isInterleavedBufferAttribute&&(u=a.data.stride);const d=["getX","getY","getZ"],f=i.offset;for(let p=t,g=t+e;p<g;p++){const v=(n?n[p]:p)*3,M=(p-f)*6;let x=v+0,y=v+1,w=v+2;r&&(x=r[x],y=r[y],w=r[w]),o||(x=x*u+h,y=y*u+h,w=w*u+h);for(let S=0;S<3;S++){let E,b,A;o?(E=a[d[S]](x),b=a[d[S]](y),A=a[d[S]](w)):(E=l[x+S],b=l[y+S],A=l[w+S]);let T=E;b<T&&(T=b),A<T&&(T=A);let D=E;b>D&&(D=b),A>D&&(D=A);const I=(D-T)/2,C=S*2;i[M+C+0]=T+I,i[M+C+1]=I+(Math.abs(T)+I)*uf}}return i}raycastObject3D(t,e,i=[]){const{material:s}=t;if(s===void 0)return;x2.copy(t.matrixWorld).invert(),zd.copy(e.ray).applyMatrix4(x2),w2.setFromMatrixScale(t.matrixWorld),y2.copy(zd.direction).multiply(w2);const n=y2.length(),a=e.near/n,r=e.far/n;if(e.firstHitOnly===!0){let o=this.raycastFirst(zd,s,a,r);o=M2(o,t,e),o&&i.push(o)}else{const o=this.raycast(zd,s,a,r);for(let l=0,h=o.length;l<h;l++){const u=M2(o[l],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?VC:IC)(this,t)}raycast(t,e=sr,i=0,s=1/0){const n=this._roots,a=[],r=this.indirect?WC:LC;for(let o=0,l=n.length;o<l;o++)r(this,o,e,t,a,i,s);return a}raycastFirst(t,e=sr,i=0,s=1/0){const n=this._roots;let a=null;const r=this.indirect?KC:kC;for(let o=0,l=n.length;o<l;o++){const h=r(this,o,e,t,i,s);h!=null&&(a==null||h.distance<a.distance)&&(a=h)}return a}intersectsGeometry(t,e){let i=!1;const s=this._roots,n=this.indirect?YC:FC;for(let a=0,r=s.length;a<r&&(i=n(this,a,t,e),!i);a++);return i}shapecast(t){const e=Qn.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?OC:DC});return Qn.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const a=Qn.getPrimitive(),r=this.geometry.index,o=this.geometry.attributes.position,l=this.indirect?p=>{const g=this.resolveTriangleIndex(p);as(a,g*3,r,o)}:p=>{as(a,p*3,r,o)},h=Qn.getPrimitive(),u=t.geometry.index,d=t.geometry.attributes.position,f=t.indirect?p=>{const g=t.resolveTriangleIndex(p);as(h,g*3,u,d)}:p=>{as(h,p*3,u,d)};if(n){if(!(t instanceof Zf))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const p=(g,m,v,M,x,y,w,S)=>{for(let E=v,b=v+M;E<b;E++){f(E),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let A=g,T=g+m;A<T;A++)if(l(A),a.needsUpdate=!0,n(a,h,A,E,x,y,w,S))return!0}return!1};if(s){const g=s;s=function(m,v,M,x,y,w,S,E){return g(m,v,M,x,y,w,S,E)?!0:p(m,v,M,x,y,w,S,E)}}else s=p}return super.bvhcast(t,e,{intersectsRanges:s})}intersectsBox(t,e){return Ud.set(t.min,t.max,e),Ud.needsUpdate=!0,this.shapecast({intersectsBounds:i=>Ud.intersectsBox(i),intersectsTriangle:i=>Ud.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},s={},n=0,a=1/0){return(this.indirect?jC:GC)(this,t,e,i,s,n,a)}closestPointToPoint(t,e={},i=0,s=1/0){return EC(this,t,e,i,s)}}class Pa{static MIN_TRIANGLES=512;static installed=!1;static trees=new WeakMap;static sphere=new ia;static install(){if(Pa.installed)return;Pa.installed=!0;const t=dt.prototype.raycast;dt.prototype.raycast=function(e,i){const s=Pa.treeOf(this,e);s!==null&&(s?s.raycastObject3D(this,e,i):t.call(this,e,i))}}static treeOf(t,e){const i=t.geometry,s=i?.attributes.position;if(!(s instanceof ve)||t.material===void 0||t.isSkinnedMesh||t.isInstancedMesh||t.isBatchedMesh||i.morphAttributes.position)return;const n=i.index;if((n?n.count:s.count)/3<Pa.MIN_TRIANGLES||i.drawRange.start!==0||i.drawRange.count!==1/0)return;i.boundingSphere===null&&i.computeBoundingSphere();const a=Pa.sphere.copy(i.boundingSphere).applyMatrix4(t.matrixWorld);if(!e.ray.intersectsSphere(a))return null;const r=Pa.trees.get(i);if(r){if(!r.bvh)return;if(r.position===s&&r.positionVersion===s.version&&r.index===n&&r.indexVersion===(n?.version??0))return r.bvh;Pa.trees.set(i,{positionVersion:-1,index:null,indexVersion:-1});return}const o=new Zf(i,{indirect:!0});return Pa.trees.set(i,{bvh:o,position:s,positionVersion:s.version,index:n,indexVersion:n?.version??0}),o}}function QC(c,t){return JSON.stringify(c.cloudLayers)===JSON.stringify(t.cloudLayers)&&c.cloudCover===t.cloudCover&&c.cloudDarkness===t.cloudDarkness&&c.cloudBaseM===t.cloudBaseM&&c.highCloudCover===t.highCloudCover&&c.iceCrystalAlignment===t.iceCrystalAlignment&&c.rareIceCrystals===t.rareIceCrystals&&c.lowerCloudCover===t.lowerCloudCover&&c.relativeHumidity===t.relativeHumidity&&c.visibilityKm===t.visibilityKm&&c.precipitationType===t.precipitationType&&c.precipitationIntensity===t.precipitationIntensity&&c.precipitationAmount===t.precipitationAmount&&c.windDirectionDeg===t.windDirectionDeg&&c.windSpeed===t.windSpeed&&c.storm===t.storm}const Bd=900,Xp=1,b2=4,Kp=5,Hd=.5,Gd=le.GROUND_RADIUS_M;function S2(c){return le.groundRadiusFor(c)}const Yp=.5,$p=850,Vd=.03,t6=.015,Ii=850,Jc=300,dr=120,e6=700,qp=.03,i6=3.5,Wd=20,Zp=.04,s6=.26,E2=4,Jp=1.5,A2=-1,n6=.01,ff=-4,a6=2,r6=20,Xd=2600,o6=.97,c6=.38,Dh=ff,l6=8,h6=2,_2=1500,u6=.7,d6=.3,f6=.32,p6=.65,T2=2.4,m6=.9,g6=400,v6=[0,45,90,135,180,225,270,315],M6=2,y6=16,R2=4e3,D2=880,Kd=40,I2=60,x6=10,P2=1,w6=le.REBUILD_DISTANCE_M,C2=.265,O2=[[0,0],...Array.from({length:8},(c,t)=>{const e=t*Math.PI/4;return[Math.cos(e)*C2,Math.sin(e)*C2]})],jp=700,Qp=250/Mx,b6=12,L2=5,tm=6,Lo=[.92,.92,.95],em=[.15,.15,.19],im={snow:{fallSpeedMPerS:2,size:.3,color:new at(1,1,1),driftSensitivity:1,radiusM:25,topYM:20,opacity:.75,poolSize:2400},hail:{fallSpeedMPerS:14,size:.5,color:new at(.95,.98,1),driftSensitivity:.25,radiusM:25,topYM:10,opacity:.95,poolSize:1200}},nl=0,sm=0,S6=150,nm=3e3,Ih=20,E6=15,N2=nl,A6=40,k2=1,_6=9;function am(c){return k2+(_6-k2)*c}const F2=new at(.75,.82,.92),T6=10,R6=.5;function U2(c){return Ca(c/T6,R6,1)}const No=200,z2=.18,B2=.32,D6=.35,H2=new at(.85,.9,.98),G2=5,V2=.85,W2=.01;function I6(c,t,e=1){return Math.round(c*(W2+(1-W2)*t)*e)}function P6(c,t){return JSON.stringify(c.cloudLayers)===JSON.stringify(t.cloudLayers)&&c.cloudCover===t.cloudCover&&c.cloudDarkness===t.cloudDarkness&&c.cloudBaseM===t.cloudBaseM&&c.highCloudCover===t.highCloudCover&&c.iceCrystalAlignment===t.iceCrystalAlignment&&c.lowerCloudCover===t.lowerCloudCover}const X2=230,K2=.7,Y2=.05,C6=.6,O6=.7,L6=.15,$2=.35,N6=3,k6=1/12,F6=.5,Ta=new at(.82,.86,1),U6=2500,z6=1.6,rm=15,B6={Venus:new at(1,.96,.85),Mars:new at(1,.55,.4),Jupiter:new at(.95,.87,.72),Saturn:new at(.92,.86,.68)};class ct{renderer;scene=new zn;phenomena=new xn(this.scene);references;referencesLoading;referencesShown=!0;referenceViews=new Map;pendingReferences;referenceClock;onReferencesSettled;camera;celestialGroup=new He;skyMesh;skyGradientMaterial;scatteredSky;lastAstronomy;get sunAltitudeDeg(){return this.lastAstronomy?.sun.altitudeDeg}skyColoursStale=!1;scatteredSkyFrameId=null;skyHoldUntilMs=void 0;onFirstFrameHold;firstFrameReady(){return(!this.scatteredSky||this.scatteredSky.ambient!==void 0)&&!this.iceHalos?.awaitingFirstDisplay}sceneSettled(){return this.firstFrameReady()&&this.arrivalsPending===0&&this.eyeSettledVersion>=this.lastArrivalVersion}arrivalsPending=0;eyeSettledVersion=-1;lastArrivalVersion=0;awaitArrival(t,e){if(this.skyHoldUntilMs===null)return t;this.arrivalsPending++;let i=!0;const s=()=>{i&&(i=!1,this.arrivalsPending--,this.lastArrivalVersion=this.sceneVersion,this.skyHoldUntilMs&&this.redrawHeld())},n=e===void 0?void 0:setTimeout(s,e);return e!==void 0&&(this.arrivalDeadlineMs=Math.max(this.arrivalDeadlineMs,performance.now()+e),this.skyHoldUntilMs&&this.arrivalDeadlineMs>this.skyHoldUntilMs&&(this.skyHoldUntilMs=this.arrivalDeadlineMs,setTimeout(()=>this.render(),e+20))),t.finally(()=>{clearTimeout(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(t){this.surroundings=void 0,this.scatteredSky?.resetSurroundings(),this.startHold(),t&&this.awaitArrival(t).catch(()=>{})}startHold(){this.skyHoldUntilMs=Math.max(performance.now()+R2,this.arrivalDeadlineMs),this.eyeSettledVersion=-1,this.lastArrivalVersion=this.sceneVersion+1,this.iceHalos?.setUrgent(!0),this.skyGlow?.setWithheld(!0),this.onFirstFrameHold?.(!0),setTimeout(()=>this.render(),R2+20)}groundMesh;terrainMesh;terrainProviders;terrainOrigin;terrainMeshOrigin;terrainBuildToken=0;terrainAttribution;roadSystem=new Me;roadAttribution;roadWays;waterSystem;waterSystemLoading;waterAttribution;waterSurfaces;railwaySystem;railwaySystemLoading;railwayAttribution;railwayLines;statedRoads=[];traces=[];traceLabels=new Map;tracesShown=!0;traceSystem;traceSystemLoading;traceResolution=new Q;decorModelProvider=new Ib;decorModelToken=0;decorModelCredits=new Map;emitterLights=new an(this.scene,()=>this.relativeScale,{halfExtentM:dr,depthHalfRangeM:Jc,biasM:qp,normalBiasM:Zp,mapSize:1024});bodySystem=new Dt(t=>this.awaitArrival(this.loadBodyModel(t)),()=>this.render(),()=>this.relativeScale,t=>this.emitterLights.set("bodies",t));bodyOrigin={x:0,z:0};starTiers=[];bodyMeshes=new Map;hitAreas=new Map;glareSprites=new Map;decorObjects=[];terraces=[];decorGroups=new Map;decorPresence=new Map;decorSunlight=new Map;static TRAFFIC_MODEL_RANGE_PER_METRE=133;static TRAFFIC_MODEL_DEFAULT_LENGTH_M=37.6;static trafficModelRangeM(t){return(t.sizeM?.lengthM??ct.TRAFFIC_MODEL_DEFAULT_LENGTH_M)*ct.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 kf(16777215,0);celestialLightTarget=new _i;skyLight=new W_(16777215,0,0);streetlightLights=new Map;headlightSystem;headlightLoading;headlightSettings=new Map;observerHeadlights;compassSprites=[];showCompass=!1;compassForced=!1;animationFrameId=null;resolution;cssSize={width:1,height:1};frameDirty=!1;flushFrameId=null;framesDriven=!1;lastFrameTimeMs;raycaster=new rf;weather=oS;observerElevationM=0;siteElevationM=0;air=new Ks;groundRadius=Gd;terrainRadius=Gd;cloudRendering="volume";layeredClouds;cloudLayerOffsetsM={};cloudOffsetM=new _;cloudFieldOffset=new _;cloudMesh;cirrusMesh;cirrusMaterial;cirrusUniforms;cloudMaterial;cloudUniforms;precipitationPoints;precipitationPositions;precipitationPhase;precipitationSpeedJitter;precipitationWobbleFreqJitter;precipitationWobbleAmpJitter;precipitationBounceRemaining;precipitationBounceHeight;precipitationBounceDuration;precipitationBounceVelX;precipitationBounceVelZ;precipitationUniforms;rainSystem;rainSplashSystem;rainCameraDirection=new _;rainLastVerticalFacing=-1;rainViewportSize=new Q;lightningArmed=!1;lightningFlashes=[];lightningLevel=0;lightningBolt;lightningLight=new kf(16777215,0);baseFogColor=[0,0,0];lastSunPosition;lensFlare;sunUnhiddenFraction=1;sunWorldPosition=new _;sunVisible=!1;lensFlareScratch=new _;sunOcclusionRaycaster=new rf;sunOcclusionDirectionScratch=new _;sunOcclusionRightScratch=new _;sunOcclusionUpScratch=new _;ufoOcclusionRaycaster=new rf;projectionKind="rectilinear";starPoints=0;namedStars=[];equidistantPass;depthOfFieldPass;finishPass;ghostPass;ghostOptics=Pe.NONE;exposureAccumulation;exposureInstants=1;get developingExposure(){return this.exposureInstants>1&&this.exposureInstantAt!==void 0}static EXPOSURE_BUDGET_MS=12;static exposureInstantsPerFrame(t){return Math.max(3,Math.round(6e6/Math.max(1,t)))}exposureFrameId=null;exposureInstantsDone=0;exposureInstantAt;restatingExposure=!1;lensOptics;instrumentMagnitudeGain=0;lightPollution;meteorSystem;cometTail;satelliteField;iceHalos;lunarDiffraction;eclipsedSun=new Eu;eclipseDiscs;solarCorona;sunBeamFraction=1;sunDiscRadiance=[0,0,0];lunarDiffractionKey="";rainbow;skyGlow;cometKey;novaKeys=new Set;constructor(t,e=hw()){jh.install(),Qh.install(),Pa.install(),this.renderer=new aI({canvas:t,antialias:!0}),this.resolution=new Ze(Math.min(window.devicePixelRatio||1,2),this.renderer.getContext()),this.renderer.setPixelRatio(this.resolution.pixelRatio),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Gh,this.camera=new Ns(60,t.width/Math.max(t.height,1),.1,Bd*1.2),this.camera.position.set(0,1.6,0),this.terrainProviders=e,this.celestialLight.shadow.mapSize.set(1024,1024),this.celestialLight.shadow.camera.left=-dr,this.celestialLight.shadow.camera.right=dr,this.celestialLight.shadow.camera.top=dr,this.celestialLight.shadow.camera.bottom=-dr,this.celestialLight.shadow.camera.near=Ii-Jc,this.celestialLight.shadow.camera.far=Ii+Jc,this.celestialLight.shadow.bias=-qp/(2*Jc),this.celestialLight.shadow.normalBias=Zp,this.celestialLight.target=this.celestialLightTarget,this.lightningLight.color.copy(Ta),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 ue(this.renderer,()=>{this.skyColoursStale=!0,this.render()});i.supported?this.scatteredSky=i:i.dispose()}get currentTerrainAttribution(){return this.terrainAttribution}get currentRoadAttribution(){return this.roadAttribution}get currentWaterAttribution(){return this.waterAttribution}get currentRailwayAttribution(){return this.railwayAttribution}resize(t,e){this.cssSize.width=t,this.cssSize.height=e,this.renderer.setSize(t,e,!1),this.camera.aspect=t/Math.max(e,1),this.camera.updateProjectionMatrix(),this.lastBodies&&this.setBodies(...this.lastBodies),this.render()}lastBodies;setCloudRendering(t){t!==this.cloudRendering&&(this.cloudTransmissionMemo.clear(),this.cloudRendering=t,this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.buildClouds(),this.buildCirrus(),this.render())}setCloudOffset(t,e={}){this.cloudOffsetM.set(t.x,0,t.z),this.cloudLayerOffsetsM=e,this.layeredClouds?.setOffsets(t,e),this.cloudFieldOffset.set(t.x*Qp,0,t.z*Qp);for(const i of[this.cloudUniforms,this.cirrusUniforms])i?.fieldOffset.value.copy(this.cloudFieldOffset);this.iceHalos?.setCloudOffset(this.layeredClouds?.cirrusMask?.offset??this.cloudFieldOffset)}setObserverPose(t){this.updateLookPatch(t);const e=((t.rollDeg??0)+this.gaitOffset.rollDeg)*Ve,i=(t.pitchDeg+this.lookPitchDeg+this.gaitOffset.pitchDeg)*Ve;t.headingDeg!==void 0?this.camera.rotation.set(i,-(t.headingDeg+this.lookYawDeg+this.gaitOffset.yawDeg)*Ve,e,"YXZ"):this.camera.rotation.set(i,this.camera.rotation.y,e,"YXZ"),t.elevationM!==this.observerElevationM&&(this.observerElevationM=t.elevationM,this.syncCloudLayer(),Math.abs(S2(t.elevationM)-this.groundRadius)>1&&(this.buildGround(),this.celestialGroup.scale.setScalar(this.groundRadius/Gd),this.camera.far=Math.max(Bd*1.2,this.groundRadius*2.5),this.camera.updateProjectionMatrix())),t.lat!==void 0&&t.lng!==void 0&&this.placeTerrain(t.lat,t.lng,0,0),this.poseStatedElevationM=t.elevationM,this.poseAltitudeM=t.altitudeM,this.poseElevationM=t.altitudeM!==void 0?Math.max(0,t.altitudeM-this.siteElevationM-this.groundYUnder(0,0)):t.elevationM,this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY,this.celestialGroup.position.y=this.camera.position.y,this.camera.fov!==t.fovDeg&&(this.camera.fov=t.fovDeg,this.camera.updateProjectionMatrix(),this.updateCompassScale())}setTerrainProviders(t){this.stopTerrainFade(),this.terrainProviders=t,this.disposeMesh(this.terrainMesh),this.terrainMesh=void 0,this.dropFarRing(),this.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(t){this.observerRoute=t,this.decorTerrainRadiusM=ct.terrainReachFor(this.decorObjects,t)}decorTerrainRadiusM=0;static terrainReachFor(t,e){return le.decorReachFor(t,e)}placeTerrain(t,e,i,s){const n=(a,r)=>{const o=re(r.lat,r.lng,t,e);a.position.x=o.x-i,a.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 a=this.farRing.mesh.position.y;n(this.farRing.mesh,this.farRing.origin),this.farRing.mesh.position.y=a}this.lookPatch&&n(this.lookPatch.mesh,this.lookPatch.origin)}lookPatch;lookPatchToken=0;lookPatchAsked;static LOOK_PATCH_KEPT_SHARE=.3;static LOOK_PATCH_RENDER_ORDER=P2+.1;updateLookPatch(t){if(t.lat===void 0||t.lng===void 0||!this.terrainMesh||this.terrainProviders.patches)return;const e=le.lookPatchFor(t.elevationM??0,t.pitchDeg,this.terrainRadius);if(!e){this.lookPatchAsked=void 0,this.lookPatchToken++,this.lookPatch&&(this.disposeMesh(this.lookPatch.mesh),this.lookPatch=void 0,this.render());return}const i=(t.headingDeg??0)*Math.PI/180,s=t.lat+e.distanceM*Math.cos(i)/111320,n=t.lng+e.distanceM*Math.sin(i)/(111320*Math.cos(t.lat*Math.PI/180)),a=this.lookPatchAsked;if(a){const l=re(s,n,a.lat,a.lng);if(Math.hypot(l.x,l.z)<a.radiusM*ct.LOOK_PATCH_KEPT_SHARE)return}this.lookPatchAsked={lat:s,lng:n,radiusM:e.radiusM};const r=++this.lookPatchToken,o=this.terrainProviders;Ap(s,n,{elevation:o.elevation,imagery:o.imagery},e.radiusM,void 0,{innerM:0,referenceElevationM:this.siteElevationM}).then(({mesh:l})=>{if(r!==this.lookPatchToken||this.terrainProviders!==o||!this.terrainMesh){this.disposeMesh(l);return}this.lookPatch&&this.disposeMesh(this.lookPatch.mesh),l.renderOrder=ct.LOOK_PATCH_RENDER_ORDER,l.position.y=this.terrainMesh.position.y;const h=l.material;h.polygonOffset=!0,h.polygonOffsetFactor=-2,h.polygonOffsetUnits=-8,this.lookPatch={mesh:l,origin:{lat:s,lng:n},radiusM:e.radiusM};const u=re(s,n,t.lat,t.lng);l.position.x=u.x,l.position.z=u.z,this.scene.add(l),this.compileNextFrameOffThread(),this.render()},l=>console.warn("No sharp ground under what is looked at:",l))}setTerrainOrigin(t,e,i){if(t===void 0||e===void 0)return;const s=this.terrainProviders.patches;let n;if(s){if(!s.loaded){if(this.patchesAwaitedFor={lat:t,lng:e,onSettled:i},this.patchesAwaited!==s){this.patchesAwaited=s;const d=this.terrainProviders;this.awaitArrival(s.ready.then(()=>{const f=this.patchesAwaitedFor;this.patchesAwaitedFor=void 0,this.terrainProviders===d&&f&&this.setTerrainOrigin(f.lat,f.lng,f.onSettled)}),ct.TERRAIN_PATIENCE_MS)}return}const u=s.nearest(t,e);u&&(t=u.lat,e=u.lng,n=u.radiusM)}const a=n??Math.max(le.patchRadiusFor(this.groundRadius,this.observerElevationM),this.decorTerrainRadiusM);if(this.terrainOrigin&&Math.abs(this.terrainRadius-a)<a*.1){const{x:u,z:d}=re(t,e,this.terrainOrigin.lat,this.terrainOrigin.lng);if(Math.sqrt(u*u+d*d)<w6*(a/Gd))return}const r=this.terrainRadius,o=this.terrainMeshOrigin;o!==void 0&&Math.hypot(re(t,e,o.lat,o.lng).x,re(t,e,o.lat,o.lng).z)<=r||(this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0,this.clearWater(),this.clearRailways()),this.terrainOrigin={lat:t,lng:e},this.terrainRadius=a;const h=++this.terrainBuildToken;this.awaitArrival(Ap(t,e,this.terrainProviders,a,{route:this.observerRoute}),ct.TERRAIN_PATIENCE_MS).then(({mesh:u,attribution:d,originElevationM:f,water:p,waterLater:g})=>{if(h!==this.terrainBuildToken)return;this.setSiteElevation(f??0),this.anchorGrassTo(u,t,e);const m=this.terrainMesh,v=this.terrainMeshOrigin,M=v?re(t,e,v.lat,v.lng):void 0;m&&M&&Math.hypot(M.x,M.z)<=r&&(u.position.y=m.position.y+this.groundYOfPatch(m,M.x,M.z)),m&&v&&M&&Math.hypot(M.x,M.z)<=r?this.crossfadeTerrain(u,m,v):this.disposeMesh(this.terrainMesh),u.renderOrder=P2,this.terrainMesh=u,this.terrainMeshOrigin={lat:t,lng:e},this.compileNextFrameOffThread(),this.terrainAttribution=d,this.scene.add(u),this.applyGroundDepthWrite(),this.decorCurrentPose&&(this.setObserverPose(this.decorCurrentPose),this.updateDecorAnchoring(this.decorReferencePose,this.decorCurrentPose,this.decorTime)),this.buildRoads(t,e,a),this.buildWater(t,e,a,p,g),this.buildRailways(t,e,a),this.drapeStatedRoads(),this.drapeTraces(),this.buildFarRing(t,e,a,u,f),this.render(),i?.()}).catch(u=>{console.warn("Terrain build failed, keeping the flat ground fallback:",u),i?.()})}buildFarRing(t,e,i,s,n){s.geometry.computeBoundingBox();const a=s.position.y+(s.geometry.boundingBox?.min.y??0),r=this.camera.position.y-a,o=this.skyEventReachM({lat:t,lng:e}),l=le.farRingRadiusFor(this.weather.visibilityKm);if(!le.needsFarRing(i,r,o,l)){this.dropFarRing();return}if(this.farRing&&this.farRingRadiusM===l){const{x:g,z:m}=re(t,e,this.farRing.origin.lat,this.farRing.origin.lng);if(Math.hypot(g,m)<i*ct.FAR_RING_KEPT_SHARE)return}const h=this.terrainProviders.patches,u=h?.farRingOf?.(t,e);if(h&&!u){this.dropFarRing();return}const d=u?.radiusM??l,f=++this.farRingToken,p=this.terrainProviders;this.awaitArrival(Ap(t,e,{elevation:p.elevation,imagery:p.imagery},d,void 0,{innerM:i*ct.FAR_RING_OPEN_SHARE,referenceElevationM:n,gridSize:le.farRingGridFor(d)}),ct.TERRAIN_PATIENCE_MS).then(({mesh:g})=>{if(f!==this.farRingToken||this.terrainProviders!==p){this.disposeMesh(g);return}this.dropFarRing(),this.farRingToken=f,g.renderOrder=ct.FAR_RING_RENDER_ORDER,g.position.y=s.position.y-ct.FAR_RING_DROP_M;const m=g.material;m.polygonOffset=!0,m.polygonOffsetFactor=2,m.polygonOffsetUnits=8,m.alphaTest=.5,this.farRing={mesh:g,origin:{lat:t,lng:e}},this.farRingRadiusM=d,this.applyGroundDepthWrite(),this.scene.add(g),g.position.x=s.position.x,g.position.z=s.position.z,this.compileNextFrameOffThread(),this.render()},g=>console.warn("Far ground unavailable, the patch of the place stays the only ground:",g))}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(t,e,i){if(this.grassReference){const a=re(this.grassReference.lat,this.grassReference.lng,e,i);Math.hypot(a.x,a.z)>2e4&&(this.grassReference=void 0)}this.grassReference??={lat:e,lng:i};const s=re(this.grassReference.lat,this.grassReference.lng,e,i);t.material.userData?.grassOrigin?.set(s.x,s.z)}static TERRAIN_CROSSFADE_MS=1200;fadingTerrain;crossfadeTerrain(t,e,i){this.stopTerrainFade();const s=t.material;s.opacity=0,s.polygonOffset=!0,s.polygonOffsetFactor=-1,s.polygonOffsetUnits=-4;const n=performance.now(),a=()=>{const r=Math.min(1,(performance.now()-n)/ct.TERRAIN_CROSSFADE_MS);if(s.opacity=r*r*(3-2*r),this.render(),r<1&&this.fadingTerrain){this.fadingTerrain.frameId=requestAnimationFrame(a);return}s.polygonOffset=!1,s.opacity=1,this.fadingTerrain&&this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0,this.render()};this.fadingTerrain={mesh:e,origin:i,frameId:requestAnimationFrame(a)}}stopTerrainFade(){if(!this.fadingTerrain)return;cancelAnimationFrame(this.fadingTerrain.frameId),this.disposeMesh(this.fadingTerrain.mesh),this.fadingTerrain=void 0;const t=this.terrainMesh?.material;t&&(t.opacity=1,t.polygonOffset=!1)}static ROADS_MAX_RADIUS_M=le.ROADS_MAX_RADIUS_M;buildRoads(t,e,i){const s=this.terrainProviders.roads;if(!s||i>ct.ROADS_MAX_RADIUS_M){this.roadSystem.clear(),this.lampNudges.clear(),this.roadAttribution=void 0;return}const n=this.roadWays;if(n&&n.lat===t&&n.lng===e&&n.radiusM===i){this.drapeRoads(n.ways,t,e,s.contemporary);return}n&&Math.hypot(re(t,e,n.lat,n.lng).x,re(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRoads(n.ways,t,e,s.contemporary),this.awaitArrival(s.getRoads(tu(t,e,i)),ct.ROADS_PATIENCE_MS).then(a=>{this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e||(this.roadWays={lat:t,lng:e,radiusM:i,ways:a},this.drapeRoads(a,t,e,s.contemporary))}).catch(a=>{console.warn("Roads unavailable, drawing none:",a)})}buildWater(t,e,i,s,n){const a=this.terrainProviders.water;if(!a||i>ct.ROADS_MAX_RADIUS_M){this.clearWater();return}if(s){this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:s},this.awaitArrival(this.drapeWater(s,t,e,i),ct.ROADS_PATIENCE_MS).catch(o=>console.warn("Water not drawn:",o));return}const r=this.waterSurfaces;if(r&&r.lat===t&&r.lng===e&&r.radiusM===i){this.drapeWater(r.surfaces,t,e,i);return}r&&Math.hypot(re(t,e,r.lat,r.lng).x,re(t,e,r.lat,r.lng).z)<=r.radiusM&&this.drapeWater(r.surfaces,t,e,i),this.awaitArrival((n??a.getWater(tu(t,e,i))).then(o=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.waterSurfaces={lat:t,lng:e,radiusM:i,surfaces:o},this.drapeWater(o,t,e,i)}),ct.ROADS_PATIENCE_MS).catch(o=>{console.warn("Water unavailable, drawing none:",o)})}async drapeWater(t,e,i,s){if(t.length===0&&!this.waterSystem)return;const n=await this.loadWaterSystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.set(t,e,i,(r,o)=>this.groundYOfPatch(a,r,o),s,this.patchSpacingM(a)),Ys.reflectOn(n.group),this.waterAttribution=n.count>0?this.terrainProviders.water?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadWaterSystem(){return this.waterSystemLoading??=Ht(async()=>{const{WaterSystem:t}=await import("./WaterSystem-BLy0L9qC.js");return{WaterSystem:t}},__vite__mapDeps([28,2,1,3,4,5,6,7]),import.meta.url).then(({WaterSystem:t})=>{const e=new t;return this.scene.add(e.group),this.waterSystem=e,e})}clearWater(){this.waterSystem?.clear(),this.waterAttribution=void 0}buildRailways(t,e,i){const s=this.terrainProviders.railways;if(!s||i>ct.ROADS_MAX_RADIUS_M){this.clearRailways();return}const n=this.railwayLines;if(n&&n.lat===t&&n.lng===e&&n.radiusM===i){this.drapeRailways(n.lines,t,e,i);return}n&&Math.hypot(re(t,e,n.lat,n.lng).x,re(t,e,n.lat,n.lng).z)<=n.radiusM&&this.drapeRailways(n.lines,t,e,i),this.awaitArrival(s.getRailways(tu(t,e,i)).then(a=>{if(!(this.terrainOrigin?.lat!==t||this.terrainOrigin?.lng!==e))return this.railwayLines={lat:t,lng:e,radiusM:i,lines:a},this.drapeRailways(a,t,e,i)}),ct.ROADS_PATIENCE_MS).catch(a=>{console.warn("Railways unavailable, drawing none:",a)})}async drapeRailways(t,e,i,s){if(!this.railwaySystem&&!t.some(r=>r.level>=0))return;const n=await this.loadRailwaySystem(),a=this.terrainMesh;a&&(n.group.position.copy(a.position),n.setGroundSpacing(this.patchSpacingM(a)),n.set(t,e,i,(r,o)=>this.groundYOfPatch(a,r,o),s),Ys.reflectOn(n.group),this.railwayAttribution=n.count>0?this.terrainProviders.railways?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}loadRailwaySystem(){return this.railwaySystemLoading??=Ht(async()=>{const{RailwaySystem:t}=await import("./RailwaySystem-D8B965iv.js");return{RailwaySystem:t}},__vite__mapDeps([29,2,1,3,4,5,6,7]),import.meta.url).then(({RailwaySystem:t})=>{const e=new t;return this.scene.add(e.group),this.railwaySystem=e,e})}clearRailways(){this.railwaySystem?.clear(),this.railwayAttribution=void 0}setStatedRoads(t){t!==this.statedRoads&&(this.statedRoads=t,this.drapeStatedRoads(),this.render())}drapeStatedRoads(){const t=this.terrainMesh;t&&(this.roadSystem.group.position.copy(t.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(t)),this.roadSystem.setStated(this.statedRoads,(e,i)=>this.groundYOfPatch(t,e,i)))}setTraces(t,e=new Map){t===this.traces&&e===this.traceLabels||(this.traces=t,this.traceLabels=e,!(t.length===0&&!this.traceSystem)&&this.loadTraceSystem().then(()=>{this.drapeTraces(),this.render()}))}setTracesShown(t){t!==this.tracesShown&&(this.tracesShown=t,this.drapeTraces(),this.render())}loadTraceSystem(){return this.traceSystemLoading??=Ht(async()=>{const{TraceSystem:t}=await import("./TraceSystem-BL6qfrHF.js");return{TraceSystem:t}},__vite__mapDeps([30,2,1,3,4,5,6,7]),import.meta.url).then(({TraceSystem:t})=>{const e=new t(Kp);this.scene.add(e.group),this.traceSystem=e})}drapeTraces(){const t=this.traceSystem,e=this.terrainMesh,i=this.terrainMeshOrigin;!t||!e||!i||(t.group.position.copy(e.position),t.set(this.tracesShown?this.traces:[],this.traceLabels,i.lat,i.lng,this.siteElevationM,(s,n)=>this.groundYOfPatch(e,s,n)))}buildingFootprints(t,e){const i=this.decorOriginInRoads(t,e);return this.decorObjects.filter(s=>s.kind==="building"&&!s.observerSide&&!s.track).map(s=>{const n=ht.naturalSize(s.kind,s.floors),a=(s.headingDeg??0)*Math.PI/180;return{x:i.x+s.eastM,z:i.z-s.northM,alongX:Math.sin(a),alongZ:-Math.cos(a),halfAlongM:(s.sizeM?.lengthM??n.lengthM)/2,halfAcrossM:(s.sizeM?.widthM??n.widthM)/2}})}decorOriginInRoads(t,e){const i=this.decorReferencePose;return i?.lat!==void 0&&i.lng!==void 0?re(i.lat,i.lng,t,e):{x:0,z:0}}surveyedLamps(t,e){const i=this.decorOriginInRoads(t,e);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(t,e){this.lampNudges.clear();const i=this.decorOriginInRoads(t,e);for(const s of this.decorObjects){if(s.kind!=="streetlight"||!s.lamp?.supposed||s.track)continue;const n=i.x+s.eastM,a=i.z-s.northM,r=this.roadSystem.atKerb(n,a);(r.x!==n||r.z!==a)&&this.lampNudges.set(s.id,{eastM:r.x-n,northM:-(r.z-a)})}}static onlyMoved(t,e){return t.length!==e.length||t.length===0?!1:t.every((i,s)=>{const n=e[s];if(i.id!==n.id||(i.track?.length??-1)!==(n.track?.length??-1))return!1;const a=new Set([...Object.keys(i),...Object.keys(n)]);for(const r of a)if(!(r==="eastM"||r==="northM"||r==="track")&&i[r]!==n[r])return!1;return!0})}layStreetsIfWallsMoved(t){const e=this.roadWays,i=this.terrainProviders.roads;if(!e||!i)return;const s=this.wallsOf(t,e.lat,e.lng),n=this.roadWalls;n?.lat===e.lat&&n.lng===e.lng&&n.walls.length===s.length&&n.walls.every((r,o)=>r.what===s[o].what&&Math.hypot(r.x-s[o].x,r.z-s[o].z)<.1)||this.drapeRoads(e.ways,e.lat,e.lng,i.contemporary)}wallsOf(t,e,i){const s=this.decorOriginInRoads(e,i);return t.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(t,e,i,s){const n=this.terrainMesh;n&&(this.roadSystem.group.position.copy(n.position),this.roadSystem.setGroundSpacing(this.patchSpacingM(n)),this.roadSystem.set(t,e,i,(a,r)=>this.groundYOfPatch(n,a,r),s,this.terrainRadius,new yi(this.buildingFootprints(e,i),this.surveyedLamps(e,i))),this.roadWalls={lat:e,lng:i,walls:this.wallsOf(this.decorObjects,e,i)},this.lampsToKerb(e,i),this.roadAttribution=t.length>0?this.terrainProviders.roads?.attribution:void 0,this.compileNextFrameOffThread(),this.render())}setShowCompass(t){this.showCompass!==t&&(this.showCompass=t,this.disposeCompassLabels(),t&&this.buildCompassLabels(),this.render())}setCompassPoints(t){this.compassPoints!==t&&(this.compassPoints=t,this.showCompass&&(this.disposeCompassLabels(),this.buildCompassLabels(),this.render()))}compassPoints;applyDazzleStrength(){if(!this.lensFlare)return;const[t,e,i]=this.sunArriving,s=Math.max(e,1e-30);this.lensFlare.uniforms.uDazzleColour.value.setRGB(t/s,1,i/s),this.lensFlare.uniforms.uVeilStrength.value=(this.medium?hs.LENS_K:hs.K)*e*this.sunUnhiddenFraction}sunArriving=[0,0,0];setCompassForced(t){this.compassForced!==t&&(this.compassForced=t,this.updateCompassVisibility())}updateCompassVisibility(){const t=this.compassForced;if(this.compassSprites.some(e=>e.visible!==t)){for(const e of this.compassSprites)e.visible=t;this.developingExposure&&!this.framesDriven?this.exposureInstantsDone>0&&this.presentExposure():this.render()}}setWeather(t){if(QC(this.weather,t))return;this.cloudTransmissionMemo.clear();const e=this.weather;this.weather=t;const i=!P6(e,t),s=e.precipitationType!==t.precipitationType,n=e.precipitationIntensity!==t.precipitationIntensity||e.precipitationAmount!==t.precipitationAmount;e.visibilityKm!==t.visibilityKm&&this.terrainMesh&&this.terrainMeshOrigin&&le.farRingRadiusFor(t.visibilityKm)!==le.farRingRadiusFor(e.visibilityKm)&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM),(e.relativeHumidity!==t.relativeHumidity||e.visibilityKm!==t.visibilityKm||s||n)&&this.restateHaze(),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=t.storm&&t.cloudDarkness>=F6,this.syncAnimationLoop(),this.render()}setDecor(t){if(this.decorObjects===t)return;if(ct.onlyMoved(this.decorObjects,t)){this.decorObjects=t,this.decorTerrainRadiusM=ct.terrainReachFor(t,this.observerRoute),this.layStreetsIfWallsMoved(t);return}this.decorObjects=t,this.decorTerrainRadiusM=ct.terrainReachFor(t,this.observerRoute),this.decorModelToken++,this.decorModelCredits.clear(),this.pendingTrafficModels.clear();for(const i of this.decorGroups.values())i.removeFromParent(),ht.dispose(i);this.decorGroups.clear(),this.mirrors.clear(),this.streetlightLights.clear(),this.headlightSystem?.clear(!0),this.headlightSettings.clear();const e=t.filter(i=>i.kind==="streetlight").sort((i,s)=>Math.hypot(i.eastM,i.northM)-Math.hypot(s.eastM,s.northM)).slice(0,l6);for(const i of t){const s=ht.build(i,i.lit??!1);this.scene.add(s),this.decorGroups.set(i.id,s),i.kind==="streetlight"&&e.includes(i)&&this.addStreetlightLight(i.id,s,e.indexOf(i)<h6,i.lamp),i.model&&i.id.startsWith(Ye.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=ct.lampsOf(this.decorGroups.values()),this.layStreetsIfWallsMoved(t),t.some(i=>i.kind==="vehicle")&&this.loadHeadlights(),this.syncHeadlightBeams(),this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any,this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs)}setDecorSunlight(t){this.decorSunlight=t}setContrails(t){t!==this.contrails&&(this.contrails=t,!(t.length===0&&!this.contrailSystem)&&this.loadContrailSystem().then(()=>{this.contrailSystem?.set(this.contrails),this.updateContrails(),this.render()}))}setContrailSunlight(t){this.contrailSunlight=t}loadContrailSystem(){return this.contrailSystemLoading??=Ht(async()=>{const{ContrailSystem:t}=await import("./ContrailSystem-CtQPQFyc.js");return{ContrailSystem:t}},__vite__mapDeps([31,32,1,2,3,4,5,6,7]),import.meta.url).then(({ContrailSystem:t})=>{const e=new t;this.scene.add(e.group),this.contrailSystem=e})}contrailTint(t){const e=this.contrailSunlight.get(t),i=this.lastAstronomy?.sun,s=ct.CONTRAIL_SCATTERING,n=this.skyLight.color,a=[n.r*s*.5,n.g*s*.5,n.b*s*.5];if(e&&i){const r=ln.litFraction(e.sunElevationDeg,e.heightM);if(r>0){const o=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),l=Ne.illuminanceOf(i.magnitude)*this.relativeScale;for(let h=0;h<3;h++)a[h]+=s*l*o[h]*r}}return a}static CONTRAIL_SCATTERING=1/(4*Math.PI);setSkyEvents(t,e=!1,i){if(this.skyEventsStart=i,t===this.skyEventsStated&&!e)return;this.skyEventsStated=t;let s=!1;const n=new Set;for(const a of zg){const r=Rr.of(a);n.add(r.key);const o=Rr.eventsOf(t,r);let l=this.skyEventLayers.get(r.key);if(l?.kind!==r&&l&&(this.disposeSkyEventLayer(r.key,l),l=void 0),!(!l&&o.length===0)){if(!l)l={kind:r,events:o},this.skyEventLayers.set(r.key,l);else if(l.events===o)continue;l.events=o,s||=r.reachM!==void 0,this.loadSkyEventSimulation(l)}}for(const[a,r]of this.skyEventLayers)n.has(a)||(this.disposeSkyEventLayer(a,r),s||=r.kind.reachM!==void 0);s&&this.terrainMesh&&this.terrainMeshOrigin&&this.buildFarRing(this.terrainMeshOrigin.lat,this.terrainMeshOrigin.lng,this.terrainRadius,this.terrainMesh,this.siteElevationM)}loadSkyEventSimulation(t){if(t.simulation){this.updateSkyEvents(),this.render();return}t.loading??=t.kind.simulation().then(e=>{if(this.skyEventLayers.get(t.kind.key)!==t)return;const i=e();(i.inSky?this.celestialGroup:this.scene).add(i.object),t.simulation=i,this.updateSkyEvents(),this.render()},()=>{}),this.holdUntil(t.loading)}disposeSkyEventLayer(t,e){e.simulation?.dispose(),this.skyEventLayers.delete(t),this.skyEventLight(t,[]),this.skyEventGlare(t,[])}skyEventLight(t,e){this.emitterLights.set(`skyEvent:${t}`,[],e.map(i=>this.farEmitterOf(i.position,i.magnitude)).filter(i=>i!==void 0)),this.refreshSkyFlare()}skyEventGlare(t,e){const i=`skyEvent:${t}:`,s=new Set;for(const n of e){const a=i+n.key,{x:r,y:o,z:l}=mi(n.position.altitudeDeg,n.position.azimuthDeg,Ii),[h,u,d]=this.arrivingIlluminance(n.position,n.magnitude,this.cloudTransmission(n.position));this.setGlare(a,r,o,l,[h*n.fade,u*n.fade,d*n.fade],0,ct.POINT_VEIL_HOLD_DEG),s.add(a)}for(const n of[...this.glareSprites.keys()])n.startsWith(i)&&!s.has(n)&&this.disposeGlare(n)}skyEventReachM(t){let e=0;for(const i of this.skyEventLayers.values())i.events.length>0&&i.kind.reachM&&(e=Math.max(e,i.kind.reachM(i.events,t)));return e}skyEventDrawnCount(t){return this.skyEventLayers.get(t)?.simulation?.drawnCount??0}get beamSegmentCount(){return this.skyEventDrawnCount("beams")}updateSkyEvents(){const t=this.decorReferencePose;if(this.skyEventLayers.size===0||t?.lat===void 0||t.lng===void 0)return;const e=this.decorCurrentPose,i={lat:e?.lat??t.lat,lng:e?.lng??t.lng,heightM:this.siteElevationM+(e?.lat!==void 0?e.elevationM??0:t.elevationM??0)},s=this.skyEventsStart?new Date(this.skyEventsStart.getTime()+this.decorTime):void 0,n=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):lf(-90,this.instrumentMagnitudeGain);let a;for(const[r,o]of this.skyEventLayers)o.simulation&&(a??={observer:i,date:s,magnitudeLimit:n,cloudTransmission:l=>this.cloudTransmission(l),arrivingIlluminance:(l,h,u)=>this.arrivingIlluminance(l,h,u),transmittanceFromSpace:l=>this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,l.altitudeDeg),reference:{lat:t.lat,lng:t.lng},origin:this.bodyOrigin,eastScale:this.bodyEastScale,siteElevationM:this.siteElevationM,eye:this.camera.position,pixelRad:this.contrailPixelRad(),relativeScale:this.relativeScale,air:this.air,transmittanceTo:(l,h,u)=>this.transmittanceTo(l,h,u),groundYAt:(l,h)=>this.groundYUnder(l,h),wind:{eastMS:Math.sin(this.weather.windDirectionDeg*Ve)*this.weather.windSpeed,northMS:Math.cos(this.weather.windDirectionDeg*Ve)*this.weather.windSpeed}},o.simulation.update(o.events,this.decorTime,{...a,lightFrom:l=>this.skyEventLight(r,l),glareFrom:l=>this.skyEventGlare(r,l)}));this.render()}updateContrails(){const t=this.lastAstronomy?.sun;this.contrailSystem?.update(this.decorTime,{origin:this.bodyOrigin,eye:this.camera.position,pixelRad:this.contrailPixelRad(),sun:t?mi(t.altitudeDeg,t.azimuthDeg,1):void 0},e=>this.contrailTint(e))}contrailPixelRad(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.lampBloomRadiusRad()??0,this.camera.fov*Math.PI/180/t)}setDecorPresence(t){this.decorPresence=t}entryOfDecorModel(t){return this.decorModelProvider.entry(t).catch(()=>{})}holdUntil(t){this.awaitArrival(t).catch(()=>{})}setDecorModelProvider(t){this.decorModelProvider=t;const e=this.decorObjects;this.decorObjects=[],this.setDecor(e)}get currentDecorModelCredits(){return[...this.decorModelCredits.values(),...this.bodySystem.modelCredits]}directionToDecor(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=new ze().setFromObject(e);if(i.isEmpty())return;const s=i.getCenter(new _),n=this.camera.getWorldPosition(new _),a=s.x-n.x,r=n.z-s.z,o=s.y-n.y,l=Math.hypot(a,r);if(!(l===0&&o===0))return{azimuthDeg:(Math.atan2(a,r)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(o,l)*180/Math.PI}}get bodyGround(){const{x:t,z:e}=this.bodyOrigin,i=this.groundYUnder(t,e),s=this.bodyEastScale,n=this.farRing?.mesh??(this.terrainMesh&&this.terrainRadius>le.ROADS_MAX_RADIUS_M?this.terrainMesh:void 0),a=n?(r,o)=>le.curvatureDropM(Math.hypot(r-n.position.x,o-n.position.z)):void 0;return{heightAt:(r,o)=>this.groundYUnder(t+r*s,e-o)-i,...a?{dropAt:(r,o)=>a(t+r*s,e-o)-a(t,e)}:{}}}get bodyEastScale(){const t=this.decorReferencePose,e=this.decorCurrentPose;return t?.lat===void 0||e?.lat===void 0?1:Math.cos(e.lat*Ve)/Math.cos(t.lat*Ve)}bodyMaskedByDecor(t,e){const i=this.decorGroups.get(e);return i?this.bodySystem.maskedShare(t,i):void 0}setBodies(t,e=0,i=t.map(a=>a.id),s=[],n){this.lastBodies=[t,e,i,s,n];const{x:a,z:r}=this.bodyOrigin,o=this.scatteredSky,l=this.bodyEastScale;Math.abs(l-1)>1e-9&&(t=t.map(u=>({...u,eastM:u.eastM*l}))),this.bodySystem.set(t,{originX:a,originZ:r,originGroundY:this.groundYUnder(a,r),eye:this.camera.position,groundYAt:(u,d)=>this.groundYUnder(u,d),wind:n,light:this.plumeLight(),occluders:[...this.decorGroups.values()],transmittance:(u,d,f)=>this.transmittanceTo(u,d,f),pixelRad:this.camera.fov*Math.PI/180/Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y),daylight:this.daylightOnBodies()},e,o?Object.assign((u,d)=>o.relativeOfLuminance(u,d),{recorded:o.recorded}):void 0,i),this.bodySystem.setSmoke(s,e),this.bodySystem.any&&(this.celestialLight.castShadow=!0),this.fitShadowToBodies();const h=this.bodySystem.furthestFrom(this.camera.position)*1.2;h>this.camera.far&&(this.camera.far=h,this.camera.updateProjectionMatrix())}daylightOnBodies(){const t=this.celestialLight.color,e=this.celestialLight.intensity,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity;return{towardSun:this.lightDirection,sun:[t.r*e,t.g*e,t.b*e],round:[(i.r+s.r)/2*n,(i.g+s.g)/2*n,(i.b+s.b)/2*n],sky:[i.r*n,i.g*n,i.b*n],ground:[s.r*n,s.g*n,s.b*n]}}plumeLight(){const t=this.celestialLight.color,e=this.celestialLight.intensity*.5,i=this.skyLight.color,s=this.skyLight.groundColor,n=this.skyLight.intensity,a=(r,o,l)=>(r*e+(o+l)/2*n)/Math.PI;return[a(t.r,i.r,s.r),a(t.g,i.g,s.g),a(t.b,i.b,s.b)]}bodyOutline(t,e){return this.bodySystem.outlineOf(t,e)}documentUrl;modelUrl(t){return t.url?this.documentRelative(t.url):void 0}documentRelative(t){if(t.startsWith("data:"))return t;const e=this.documentUrl??(typeof location>"u"?void 0:location.href);return e?new URL(t,e).href:t}async loadBodyModel(t){const e=t.url?void 0:t.id?await this.decorModelProvider.entry(t.id):void 0,i=this.modelUrl(t)??e?.url,s=t.credit??e?.credit;if(!(!i||!s))return{scene:await Op(i),credit:s,headingOffsetDeg:t.headingOffsetDeg??e?.headingOffsetDeg,bindings:e?.parameters?.bindings}}loadedDecorModels=new Map;reuseLoadedDecorModel(t,e){const i=this.loadedDecorModels.get(t.id);return!i||i.ref!==JSON.stringify(mf(t))||!ht.usesModel(t)?!1:(this.applyLoadedDecorModel(t,e,i),!0)}applyLoadedDecorModel(t,e,i){const s=Pb(i.scene);s.traverse(n=>{n instanceof dt&&(n.userData.sharedModel=!0)}),ht.applyModelParameters(s,t.modelParameters,i.bindings),ht.applyModel(e,t,s,{headingOffsetDeg:i.headingOffsetDeg,depictedSizeM:i.depictedSizeM}),this.mirrors.adopt(s),this.decorModelCredits.set(t.id,i.credit)}mirrors=new yn;mirrorCatchUp;standInScenes=new Map;async loadDecorModel(t,e,i=!1){const s=i?fS[t.kind]:mf(t);if(!(!s||!ht.usesModel(t)))try{const n=s.url?void 0:s.id?await this.decorModelProvider.entry(s.id):void 0,a=this.modelUrl(s)??n?.url,r=s.credit??n?.credit;if(!a||!r)return;const o=i||t.kind==="tree"?await this.standInScene(a):await Op(a);if(e!==this.decorModelToken||i&&!this.pendingTrafficModels.has(t.id))return;const l=this.decorGroups.get(t.id);if(!l)return;!i&&t.kind!=="tree"&&(Dt.glaze(o),Ys.reflectOn(o));const h={ref:JSON.stringify(s),scene:o,headingOffsetDeg:s.headingOffsetDeg??n?.headingOffsetDeg,depictedSizeM:n?.sizeM,credit:r,bindings:n?.parameters?.bindings};i||this.loadedDecorModels.set(t.id,h),this.applyLoadedDecorModel(t,l,h),this.render()}catch(n){console.warn(`Keeping the built-in shape for decor "${t.id}":`,n)}}standInScene(t){let e=this.standInScenes.get(t);return e||(e=Op(t).then(i=>(/jungle-jim-realistic-trees/.test(t)||Ys.reflectOn(i),i)),this.standInScenes.set(t,e)),e}updateDecorAnchoring(t,e,i=0){this.decorReferencePose=t,this.decorCurrentPose=e,this.decorTime=i;const s=t?.lat!==void 0&&t.lng!==void 0&&e?.lat!==void 0&&e?.lng!==void 0?re(t.lat,t.lng,e.lat,e.lng):{x:0,z:0},n=this.decorObjects.find(p=>p.observerSide!==void 0&&Hl(p.kind));this.terrainMesh&&e?.lat!==void 0&&e.lng!==void 0&&(this.placeTerrain(e.lat,e.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 a={x:0,z:0};let r=0,o;if(n){const p=ga(n,i),g=ht.occupantView(n,p.headingDeg),m=-(p.headingDeg??0)*Ve,v=g.x*Math.cos(m)+g.z*Math.sin(m),M=-g.x*Math.sin(m)+g.z*Math.cos(m),x=p.eastM+s.x,y=-p.northM+s.z;a.x=-(x+v),a.z=-(y+M),this.camera.position.y=this.groundYUnder(x,y)+g.eyeY,o=g.eyeY,this.camera.rotation.set(this.indoorLookPitchDeg*Ve,-(g.headingDeg+this.indoorLookYawDeg)*Ve,0,"YXZ")}this.bodyOrigin={x:s.x+a.x,z:s.z+a.z};const l=this.findCabin(i,s,a);this.fitShadowToCabin(l.length>0),this.dimCabinSky(l),this.placeShadowFrustum(),this.placeTerraces(i,s,a);const h=this.terraces.map(p=>[p.x,p.z,p.cos,p.sin,p.halfWidthM,p.halfLengthM,p.levelY].map(g=>g.toFixed(3)).join(",")).join(";");!n&&this.terraces.length>0&&(this.poseAltitudeM!==void 0&&(this.poseElevationM=Math.max(0,this.poseAltitudeM-this.siteElevationM-this.groundYUnder(0,0))),this.poseCameraY=this.groundYUnder(0,0)+1.6+this.poseElevationM,this.camera.position.y=this.poseCameraY+this.gaitOffset.upM,this.celestialGroup.position.y=this.camera.position.y);for(const p of this.decorObjects){if(p.kind==="terrace")continue;const g=this.decorGroups.get(p.id);if(!g)continue;const m=ga(p,i),v=this.lampNudges.get(p.id),M=m.eastM+(v?.eastM??0)+s.x+a.x,x=-(m.northM+(v?.northM??0))+s.z+a.z,y=this.terrainMesh,w=`${y?.geometry.uuid}:${(M-(y?.position.x??0)).toFixed(3)}:${(x-(y?.position.z??0)).toFixed(3)}:${(y?.position.y??0).toFixed(3)}:${m.headingDeg}:${m.altitudeM}:${h}`;if(g.userData.footprintKey!==w){if(p.kind==="wire"){const C=ht.wireGround(p,M,x,m.headingDeg,(N,O)=>this.groundYUnder(N,O));g.userData.footprintGroundY=C.startY,ht.shearWire(g,ht.sizeOf(p).lengthM,C.dropM)}else if(p.kind==="crossing"){const C=this.groundYUnder(M,x),N=-(m.headingDeg??0)*Ve,O=Math.cos(N),k=Math.sin(N);g.userData.footprintGroundY=C,Ee.drape(ht.bodyOf(g),(B,X)=>this.groundYUnder(M+B*O+X*k,x-B*k+X*O)-C)}else g.userData.footprintGroundY=this.groundUnderFootprint(p,M,x,m.headingDeg,m.altitudeM);g.userData.footprintKey=w}const E=m.altitudeM>ct.AIRBORNE_M&&Math.hypot(M,x)<ct.CABIN_MATE_RANGE_M?this.poseCameraY-1.6-this.poseStatedElevationM:g.userData.footprintGroundY,b=p.id.startsWith(Ye.ID_PREFIX)?ct.trafficHeight(m.altitudeM,g.userData.footprintGroundY):E+m.altitudeM;if(g.position.set(M,b,x),p.kind==="crop"){const C=Math.hypot(M,x);g.visible=C<=S6}const A=this.decorPresence.get(p.id),T=A!==void 0&&(i<A.fromMs||i>A.untilMs);A&&(g.visible=!T);const D=this.decorSunlight.get(p.id);D&&!T&&this.lightFromAbove(g,D),m.headingDeg!==void 0&&(g.rotation.y=-m.headingDeg*Ve);const I=pS(p,i);if(I!==void 0&&ct.turnHead(g,m.headingDeg??0,I),p.kind==="crop"&&g.visible){const C=this.terrainMesh,N=[C?.geometry.uuid,M-(C?.position.x??0),x-(C?.position.z??0),g.position.y-(C?.position.y??0),m.headingDeg,m.altitudeM].map(O=>typeof O=="number"?O.toFixed(4):O).join(":");g.userData.cropGroundKey!==N&&(ht.fitCropToGround(g,(O,k)=>this.groundYUnder(O,k)+m.altitudeM),g.userData.cropGroundKey=N)}if(!T){const C=g.position.distanceTo(this.camera.position);r=Math.max(r,C),C<ct.trafficModelRangeM(p)&&this.pendingTrafficModels.delete(p.id)&&this.loadDecorModel(p,this.decorModelToken)}}if(n&&o!==void 0){const p=this.decorGroups.get(n.id);p&&(this.camera.position.y=p.position.y+o)}this.updateContrails(),this.updateSkyEvents();const u=Math.max(this.terrainMesh?this.terrainRadius:0,this.farRing?this.farRingRadiusM:0)*Math.SQRT2,d=this.terrainMeshOrigin?this.skyEventReachM(this.terrainMeshOrigin):0,f=Math.max(Bd*1.2,this.groundRadius*2.5,r*1.2,u*1.05,d*1.2);Math.abs(this.camera.far-f)>1&&(this.camera.far=f,this.camera.updateProjectionMatrix())}groundYUnder(t,e){const i=this.terrainYUnder(t,e);let s=i;for(const n of this.terraces){const a=t-n.x,r=e-n.z,o=a*n.cos-r*n.sin,l=a*n.sin+r*n.cos;if(Math.abs(o)<=n.halfWidthM&&Math.abs(l)<=n.halfLengthM){const h=Math.min(1,Math.max(0,(n.halfWidthM-Math.abs(o))/n.bankM)),u=h*h*(3-2*h);s=Math.max(s,u*n.levelY+(1-u)*Math.min(n.levelY,i))}}return s}placeTerraces(t,e,i){this.terraces=[];const s=this.terrainMesh;for(const n of this.decorObjects){if(n.kind!=="terrace")continue;const a=this.decorGroups.get(n.id);if(!a)continue;const r=ga(n,t),o=r.eastM+e.x+i.x,l=-r.northM+e.z+i.z,h=ht.sizeOf(n),u=-(r.headingDeg??0)*Ve,d=Math.cos(u),f=Math.sin(u),p=`${s?.geometry.uuid}:${(o-(s?.position.x??0)).toFixed(3)}:${(l-(s?.position.z??0)).toFixed(3)}:${(s?.position.y??0).toFixed(3)}:${r.headingDeg}:${h.widthM}:${h.lengthM}:${h.heightM}`;a.position.set(o,0,l),r.headingDeg!==void 0&&(a.rotation.y=u),a.userData.terraceKey!==p&&(a.userData.terraceLevelY=ht.fitTerrace(a,n,(g,m)=>this.terrainYUnder(o+g*d+m*f,l-g*f+m*d)),a.userData.terraceKey=p),this.terraces.push({x:o,z:l,cos:d,sin:f,halfWidthM:h.widthM/2,halfLengthM:h.lengthM/2,levelY:a.userData.terraceLevelY,bankM:Math.min(10,h.widthM/4)})}}terrainYUnder(t,e){const i=this.terrainMesh;return i?i.position.y+this.groundYOfPatch(i,t-i.position.x,e-i.position.z):sm}horizonAltitudeDeg(t){const e=this.camera.position,i=`${this.terrainMesh?.uuid}|${this.farRing?.mesh.uuid}|${Math.round(e.x)}|${Math.round(e.y*10)}|${Math.round(e.z)}`;i!==this.horizonFor&&(this.horizonFor=i,this.horizonByBearing.fill(Number.NaN));const s=this.horizonByBearing.length,n=Math.round((t%360+360)%360/(360/s))%s;let a=this.horizonByBearing[n];return Number.isNaN(a)&&(a=this.horizonByBearing[n]=this.marchHorizon(n*360/s)),a}groundHidesDirection(t,e){return t<Math.max(0,this.horizonAltitudeDeg(e))+ct.HORIZON_CLEARANCE_DEG}static HORIZON_CLEARANCE_DEG=1;horizonByBearing=new Float32Array(720).fill(Number.NaN);horizonFor;marchHorizon(t){const e=this.terrainMesh;if(!e)return Number.NEGATIVE_INFINITY;const i=this.camera.position,s=t*Math.PI/180,n=Math.sin(s),a=-Math.cos(s),r=this.farRing?.mesh,o=Math.max(this.terrainRadius,r?this.farRingRadiusM:0),l=Math.min(Math.max(this.patchSpacingM(e),1),50);let h=Number.NEGATIVE_INFINITY;for(let u=l;u<=o;u=Math.max(u+l,u*1.02)){const d=i.x+n*u,f=i.z+a*u,p=u<=this.terrainRadius?this.terrainYUnder(d,f):r.position.y+this.groundYOfPatch(r,d-r.position.x,f-r.position.z);h=Math.max(h,Math.atan2(p-i.y,u))}return h*180/Math.PI}get groundKey(){return`${this.terrainMesh?.uuid??""}|${this.farRing?.mesh.uuid??""}`}patchSpacingM(t){const e=t.geometry.getAttribute("position");return e&&e.count>=2?Math.abs(e.getX(1)-e.getX(0)):1/0}groundYOfPatch(t,e,i){const s=t.geometry.getAttribute("position"),n=Math.round(Math.sqrt(s.count));if(n<2||n*n!==s.count)return sm;const a=s.getX(0),r=s.getX(n-1),o=s.getZ(0),l=s.getZ((n-1)*n),h=Ca((e-a)/(r-a)*(n-1),0,n-1),u=Ca((i-o)/(l-o)*(n-1),0,n-1);if(!Number.isFinite(h)||!Number.isFinite(u))return sm;const d=Math.min(Math.floor(h),n-2),f=Math.min(Math.floor(u),n-2),p=h-d,g=u-f,m=(w,S)=>s.getY(w*n+S),v=m(f,d),M=m(f,d+1),x=m(f+1,d),y=m(f+1,d+1);return p+g<=1?v+(M-v)*p+(x-v)*g:y+(x-y)*(1-p)+(M-y)*(1-g)}groundUnderFootprint(t,e,i,s,n=0){return ht.groundUnderFootprint(t,e,i,s,(a,r)=>this.groundYUnder(a,r),n)}lookYawDeg=0;lookPitchDeg=0;poseCameraY=1.6;poseElevationM=0;poseStatedElevationM=0;poseAltitudeM;setGait(t){this.gaitOffset=t}gaitOffset={eastM:0,northM:0,upM:0,rollDeg:0,pitchDeg:0,yawDeg:0};setLookOffset(t,e){this.lookYawDeg=t,this.lookPitchDeg=e}indoorLookYawDeg=0;indoorLookPitchDeg=0;setIndoorLook(t,e){this.indoorLookYawDeg=t,this.indoorLookPitchDeg=e}skyUnknown=!1;setSkyUnknown(t){t!==this.skyUnknown&&(this.skyUnknown=t,this.render())}perception=An.NONE;setPerception(t){JSON.stringify(t)!==JSON.stringify(this.perception)&&(this.perception=t,this.render())}medium;setMedium(t,e,i,s,n){const a=t&&e!==void 0&&e>0&&i!==void 0&&i>0?{kind:t.kind,iso:s??t.iso,autoExposure:t.autoExposure===!0&&s===void 0,maxIso:t.maxIso,metering:n??t.metering??"average",exposureSeconds:e,fNumber:i,development:t.development,exposureFollowMs:t.exposureFollowMs,print:t.print,monochrome:t.monochrome}:void 0;JSON.stringify(a)!==JSON.stringify(this.medium)&&(this.medium=a,this.render())}applyMedium(){const t=this.medium,e=Math.max(this.relativeScale,1e-30),i=t?An.NONE:this.perception??An.NONE;if(Si.uColorVision.value.set(...i.colorMatrix),Si.uContrast.value=i.contrastGain,!t){Si.uMedium.value=0;return}const s=t.kind==="sensor"&&t.development==="computational";Si.uMedium.value=t.kind==="negative"?1:t.kind==="slide"?2:s?4:3;const n=t.autoExposure?this.frameLight:void 0,a=t.autoExposure||this.skyUnknown?n?.mean??this.scatteredSky?.sceneAdaptation:void 0,r=a===void 0?void 0:this.meteredBodies(),o=a===void 0?void 0:a+r.mean,l=d=>.065*t.exposureSeconds*d*this.filterTransmittance/(t.fNumber*t.fNumber*e);let h=o!==void 0&&o>0?1/(e*o):void 0;h!==void 0&&t.metering==="highlights"&&r.brightest>0&&(h=Math.min(h,ct.HIGHLIGHT_KEPT_AT/(.18*e*r.brightest))),h!==void 0&&t.metering==="highlights"&&n&&n.brightest>0&&(h=Math.min(h,ct.ZONE_KEPT_AT/(.18*e*n.brightest)));const u=h!==void 0?Math.min(h,t.maxIso!==void 0?l(t.maxIso):1/0):l(t.iso);Si.uMediumExposure.value=u,Si.uPhoneStrength.value=s&&o!==void 0&&o>0?la.strengthFor(la.MID_GREY*u*e*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 t=this.camera;t.updateMatrixWorld();const e=t.fov*Math.PI/180,i=2*Math.atan(Math.tan(e/2)*t.aspect),s=4*Math.asin(Math.sin(i/2)*Math.sin(e/2)),n=new _;let a=0,r=0;for(const{position:o,luminanceCdM2:l,solidAngleSr:h}of this.bodySystem.metered.values())n.copy(o).project(t),n.z<1&&Math.abs(n.x)<=1&&Math.abs(n.y)<=1&&(a+=l*h,r=Math.max(r,l*Math.min(1,h/(ct.HIGHLIGHT_SHARE*s))**2));return{mean:a/s,brightest:r}}grain;lampBloomRadiusRad(){if(!this.grain)return;const t=this.camera.fov*Math.PI/180,e=this.grain.frameHeightMm/(2*Math.tan(t/2)),i=Math.max(1,this.renderer.getDrawingBufferSize(this.bloomSize).y);return Math.max(this.grain.detailUm*.001/e,t/i)}bloomSize=new Q;lampTransmittance(t){const e=this.siteElevationM+this.camera.position.y,i=this.siteElevationM+t.position.y;return this.air.transmittance(e,i,t.position.distanceTo(this.camera.position))}decorLitAt;updateDecorLitState(t,e=0){this.decorLitAt={t,stepMs:e};const i=this.lampBloomRadiusRad();for(const s of this.decorObjects){const n=this.decorGroups.get(s.id);if(n&&s.lights?.length&&ht.setLights(n,s.lights,t,n.position.distanceTo(this.camera.position),e,this.relativeScale,i,this.lampTransmittance(n),this.camera.position),s.kind!=="streetlight"&&s.kind!=="vehicle")continue;const a=this.decorGroups.get(s.id);if(!a)continue;const r=s.kind==="vehicle"?bx(s,t):void 0,o=r!==void 0?mm.lamps(r):n1(s,t,this.lastAstronomy?.sun.altitudeDeg);ht.setLit(a,s.kind,o,this.relativeScale,s.lamp);const l=this.streetlightLights.get(s.id);l&&(l.visible=o),r!==void 0&&(this.headlightSettings.set(s.id,r),this.aimDecorBeam(s,a,r))}this.aimObserverBeam()}loadHeadlights(){return this.headlightSystem?Promise.resolve():this.headlightLoading??=Ht(async()=>{const{HeadlightSystem:t}=await import("./HeadlightSystem-YXD1Zdpn.js");return{HeadlightSystem:t}},__vite__mapDeps([33,5,1,2,3,4,6,7]),import.meta.url).then(({HeadlightSystem:t})=>{this.headlightSystem??=new t(this.scene),this.syncHeadlightBeams(),this.compileNextFrameOffThread(),this.render()})}syncHeadlightBeams(){const t=this.headlightSystem;if(t){for(const e of this.decorObjects)e.kind==="vehicle"&&t.add(e.id);this.observerHeadlights&&t.add("observer"),this.aimBeams()}}aimBeams(){if(!(!this.headlightSystem||this.headlightSystem.size===0)){for(const t of this.decorObjects){const e=this.headlightSettings.get(t.id),i=this.decorGroups.get(t.id);e!==void 0&&i&&this.aimDecorBeam(t,i,e)}this.aimObserverBeam()}}headlightScatterPerM(){const t=this.siteElevationM+this.camera.position.y,e=200,i=this.air.transmittance(t,t,e)[1];return i>0?-Math.log(Math.min(1,i))/e:.05}aimDecorBeam(t,e,i){if(!this.headlightSystem?.has(t.id))return;e.updateMatrixWorld(!0);const s=new _(0,0,-1).transformDirection(e.matrixWorld);if(s.y=0,s.lengthSq()<1e-9)return;s.normalize();const n=ht.sizeOf(t).lengthM,a=e.getWorldPosition(new _).addScaledVector(s,n/2-d6);a.y+=u6;const r=ht.sizeOf(t).widthM;this.headlightSystem.aim(t.id,i,a,s,r*f6,this.relativeScale,this.headlightScatterPerM())}setObserverHeadlights(t){this.observerHeadlights=t,t&&this.loadHeadlights(),this.headlightSystem&&(t?this.headlightSystem.add("observer"):this.headlightSystem.remove("observer"),this.aimObserverBeam())}aimObserverBeam(){const t=this.observerHeadlights;if(!t||!this.headlightSystem?.has("observer"))return;const e=t.setting==="auto"?this.lastAstronomy?mm.auto(this.lastAstronomy.sun.altitudeDeg):"off":t.setting,i=t.headingDeg*Math.PI/180,s=new _(Math.sin(i),0,-Math.cos(i)),n=new _(s.x*T2,this.camera.position.y-m6,s.z*T2);this.headlightSystem.aim("observer",e,n,s,p6,this.relativeScale,this.headlightScatterPerM())}addStreetlightLight(t,e,i,s){const n=ht.bodyOf(e),a=n.children.find(l=>l.userData.emissive);if(!a)return;const r=_2*ht.lampShare(s),o=new eb(16764006,r*this.relativeScale,g6);s?.colorTemperatureK&&o.color.setRGB(...ht.lampHue(s)),o.userData.candela=r,o.position.copy(a.position).multiply(n.scale),o.castShadow=i,o.shadow.mapSize.set(512,512),o.shadow.bias=-.002,e.add(o),this.streetlightLights.set(t,o)}applyWindowGlow(){const t=this.lastAstronomy;ht.setLitWindowShare(t?Is.share(t.sun.altitudeDeg,t.localHour):0)}setAstronomy(t){(!this.lastAstronomy||Math.abs(this.lastAstronomy.sun.altitudeDeg-t.sun.altitudeDeg)>2)&&(this.surroundings=void 0,this.scatteredSky?.resetSurroundings()),this.lastAstronomy=t,this.applyWindowGlow(),this.scatteredSky?.update(this.scatteredSkyState(t)),this.skyHoldUntilMs===void 0&&this.startHold(),this.pumpScatteredSky(),this.lastSunPosition=t.sun,this.buildSky(t.sun),this.buildGround();const e=this.magnitudeLimitOf(t);this.buildStars(t.stars,e),this.placeBodies(t,e),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.applySkyColours(t),this.syncAnimationLoop(),this.render()}static relativeSkyOf(t,e){const i=a=>{const r=En.luminanceOf(a);if(!(r>0))return[0,0,0];const o=zt.relativeOfResponse(r)/r;return[a[0]*o,a[1]*o,a[2]*o]},s=i(t.zenith),n=i(t.horizon);return{zenith:s,horizon:n,airlight:n,skyIrradiance:[s[0]*Math.PI,s[1]*Math.PI,s[2]*Math.PI],scale:e}}placeBodies(t,e){this.bodiesScale=this.relativeScale,this.sunBeamFraction=Yi.beamFraction(t.eclipse),this.setBodyMesh("sun",t.sun,E2,new at(1,.96,.88),t.sun.magnitude),this.placeEclipse(t),this.setMoonMesh(t.moon,e),this.buildPlanets(t.planets,e),this.buildComet(t.comet,e),this.buildNovae(t.novae??[],e)}placeEclipse(t){const e=t.eclipse;if(!e||t.sun.altitudeDeg<ff){this.eclipsedSun.setMoon(void 0),this.eclipseDiscs=void 0,this.solarCorona?.show(void 0,[0,0,0]);return}const i=E2/Ii*(180/Math.PI),s=i/e.sunRadiusDeg,n=mi(t.sun.altitudeDeg,t.sun.azimuthDeg,1),a=mi(t.moon.altitudeDeg,t.moon.azimuthDeg,1),r=Math.acos(Ca(n.x*a.x+n.y*a.y+n.z*a.z,-1,1)),o=r>1e-9?Ca(e.separationDeg*s*Ve/r,0,2):0,l=Math.sin(r),[h,u]=r>1e-9?[Math.sin((1-o)*r)/l,Math.sin(o*r)/l]:[1,0],d={x:n.x*h+a.x*u,y:n.y*h+a.y*u,z:n.z*h+a.z*u},f=e.moonRadiusDeg*s;this.eclipseDiscs={sun:new _(n.x,n.y,n.z).normalize(),moon:new _(d.x,d.y,d.z).normalize(),sunRadiusRad:i*Ve,moonRadiusRad:f*Ve};const p=.01,g=(M,x)=>mi(t.sun.altitudeDeg+M,t.sun.azimuthDeg+x,1),m={x:g(p,0).x-g(-p,0).x,y:g(p,0).y-g(-p,0).y,z:g(p,0).z-g(-p,0).z},v={x:g(0,p).x-g(0,-p).x,y:g(0,p).y-g(0,-p).y,z:g(0,p).z-g(0,-p).z};if(this.eclipsedSun.setMoon(d,f,e.limb?{profile:e.limb,scale:s,up:m,right:v}:void 0),e.obscuration<.9){this.solarCorona?.show(void 0,[0,0,0]);return}this.solarCorona||(this.solarCorona=new Sl(i*Math.PI/180,this.eclipsedSun.cut),this.celestialGroup.add(this.solarCorona.object)),this.solarCorona.show(n,this.sunDiscRadiance)}bodiesScale=0;applySkyColours(t){this.skyColoursStale=!1,this.bodiesScale!==this.relativeScale&&(this.placeBodies(t,this.magnitudeLimitOf(t)),this.applyDazzleStrength(),this.buildIceHalos(t.sun,t.moon),this.buildRainbow(t.sun,t.moon),this.updateSkyEvents());const e=this.scatteredSky?.ambient??ct.relativeSkyOf(Ug(t.sun.altitudeDeg),this.relativeScale),i=e,s=this.lightUnderClouds(t),n=a=>s?[0,1,2].map(r=>a[r]*s.through+s.radiance[r]*(1-s.through)):[a[0],a[1],a[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(t,e),this.updateCloudLighting(t.sun,this.baseFogColor),Vt.setEye(this.scatteredSky?.rodShare??0,this.relativeScale),this.updateTwinkle(this.twinkleSeconds);for(const a of this.streetlightLights.values())a.intensity=(a.userData.candela??_2)*this.relativeScale;this.decorLitAt&&this.updateDecorLitState(this.decorLitAt.t,this.decorLitAt.stepMs),this.buildSkyGlow(t,i.zenith),this.applyAir(),this.buildLunarDiffraction(t.moon)}reflections;sceneVersion=0;reflectionTimer;buildLunarDiffraction(t){const e=this.scatteredSky?.ready?this.scatteredSky:void 0;if(t.altitudeDeg<-.5||!e){this.lunarDiffraction?.show(void 0),this.lunarDiffractionKey="";return}const i=(this.hazeOpticalDepth()??Pt.DEFAULT_AEROSOL_OPTICAL_DEPTH)*Pt.aerosolDensity(this.siteElevationM+this.observerElevationM),s=this.cloudTransmission(t),n=-Math.log(Math.max(this.cloudTransmission(t,!0),1e-4)),a=Ne.aureoleScale(i,Ne.airMass(t.altitudeDeg))*s,r=Ne.coronaScale(n),o=Ne.illuminanceOf(t.magnitude),l=[t.altitudeDeg.toFixed(1),t.azimuthDeg.toFixed(1),t.magnitude.toFixed(2),a.toExponential(2),r.toExponential(2),Math.log10(Math.max(e.adaptation,1e-12)).toFixed(2)].join(":");if(l===this.lunarDiffractionKey)return;this.lunarDiffractionKey=l,this.lunarDiffraction||(this.lunarDiffraction=new K1,this.celestialGroup.add(this.lunarDiffraction.object));const h=Ne.profile(Ne.HAZE_COARSE_MODE),u=Ne.profile(Ne.CLOUD_DROPLETS),d=VI(t.altitudeDeg),f=new Float32Array(Ne.STEPS*3);let p=0;for(let M=0;M<Ne.STEPS;M++){const x=M*3,y=[0,1,2].map(S=>o*d[S]*(a*h[x+S]+r*u[x+S])),w=En.shown(y,En.luminanceOf(y),(S,E)=>e.relativeOfLuminance(S,E));f.set(w,x),p=Math.max(p,En.response(w))}const{x:g,y:m,z:v}=mi(t.altitudeDeg,t.azimuthDeg,1);this.lunarDiffraction.show(p>1/200?{x:g,y:m,z:v}:void 0,f)}applyAir(){this.scene.fog instanceof vo||(this.scene.fog=new vo),this.scene.fog.setAir(this.air,this.siteElevationM,this.airlight)}airlight=[0,0,0];transmittanceTo(t,e,i){const s=this.camera.position;return this.air.transmittance(this.siteElevationM+s.y,this.siteElevationM+e,Math.hypot(t-s.x,e-s.y,i-s.z))}get groundAltitudeM(){return this.siteElevationM}static trafficHeight(t,e){return Math.max(t,e)}hazeOpticalDepth(){return Ks.aerosolOpticalDepthOf(this.weather,this.siteElevationM)}restateHaze(){this.air=Ks.of(this.weather,this.siteElevationM),this.applyAir();const t=this.hazeOpticalDepth(),e=Zo.OPTICAL_DEPTH_STEP;this.scatteredSky?.setConditions({aerosolOpticalDepth:t===void 0?void 0:Math.round(t/e)*e}),this.pumpScatteredSky()}setSiteElevation(t){Math.abs(t-this.siteElevationM)<1||(this.siteElevationM=t,this.weather.visibilityKm!==void 0&&this.restateHaze(),this.applyAir(),this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}umbraTint(){const t=this.siteElevationM+this.observerElevationM+1.6,[e,i,s]=this.air.transmittance(t,t,ct.UMBRA_PATH_M),n=.2126*e+.7152*i+.0722*s;return n>0?[(.4124*e+.3576*i+.1805*s)/n,1,(.0193*e+.1192*i+.9505*s)/n]:[.9505,1,1.089]}static UMBRA_PATH_M=8e4;umbraOf(t){const e=t.eclipse?.horizonShare;return e&&Math.max(...e)<.1?{share:e,tint:this.umbraTint()}:void 0}scatteredSkyState(t){return{altitudeM:this.siteElevationM+this.observerElevationM+1.6,lightPollution:this.lightPollution,sun:{altitudeDeg:t.sun.altitudeDeg,azimuthDeg:t.sun.azimuthDeg,magnitude:t.sun.magnitude},sunLight:Yi.beamFraction(t.eclipse),zenithFloorCdM2:t.eclipse?Yi.UMBRA_ZENITH_CD_M2:void 0,umbra:this.umbraOf(t),moon:{altitudeDeg:t.moon.altitudeDeg,azimuthDeg:t.moon.azimuthDeg,magnitude:t.moon.magnitude,phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction)},flare:this.skyFlare}}pumpScatteredSky(){const t=this.scatteredSky;!t||t.tables.ready||this.scatteredSkyFrameId!==null||this.contextReleased||this.suspended||(this.scatteredSkyFrameId=requestAnimationFrame(()=>{this.scatteredSkyFrameId=null,!this.contextReleased&&(t.advance(this.skyHoldUntilMs?y6:M6),this.pumpScatteredSky())}))}cancelScatteredSkyPump(){this.scatteredSkyFrameId!==null&&(cancelAnimationFrame(this.scatteredSkyFrameId),this.scatteredSkyFrameId=null)}setSatellites(t){if(t.length===0&&!this.satelliteField?.count)return;this.satelliteField||(this.satelliteField=new yP($p),this.celestialGroup.add(this.satelliteField.object));const e=this.lastAstronomy?this.magnitudeLimitOf(this.lastAstronomy):lf(-90,this.instrumentMagnitudeGain);this.satelliteField.set(t,e,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")}decorSkyPoint(t){const e=this.decorGroups.get(t);if(!e?.visible)return;const i=new _().copy(e.position).sub(this.camera.position),s=i.length();if(s===0)return;const n=(Math.atan2(i.x,-i.z)*180/Math.PI+360)%360,a=Math.asin(i.y/s)*180/Math.PI;return{sky:{azimuthDeg:n,altitudeDeg:a,distanceKm:s/1e3},altitudeM:this.siteElevationM+e.position.y}}flightScreenPoint(t){const e=Ye.declaredIdOf(t);if(e!==void 0){const s=this.decorGroups.get(e);if(!s?.visible)return;const n=new _().copy(s.position).sub(this.camera.position),a=this.screenPointOf(n.clone().normalize());return a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY,n.length())?a:void 0}const i=`${Ye.ID_PREFIX}${t}-`;for(const[s,n]of this.decorGroups){if(!n.visible||!s.startsWith(i))continue;const a=this.screenPointOf(new _().copy(n.position).sub(this.camera.position).normalize());if(a&&Math.abs(a.ndcX)<=1&&Math.abs(a.ndcY)<=1&&!this.groundHides(a.ndcX,a.ndcY))return a}}pickTrafficAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,s=Math.cos(Vd*this.camera.fov*Math.PI/180);let n,a=s;const r=new _;for(const[o,l]of this.decorGroups){if(!l.visible||!o.startsWith(Ye.ID_PREFIX))continue;r.copy(l.position).sub(this.camera.position).normalize();const h=r.dot(i);h>a&&(a=h,n=o)}return n&&!this.groundHides(t,e)?n:void 0}pickSatelliteAt(t,e){if(!this.satelliteField?.count)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=Math.cos(Vd*this.camera.fov*Math.PI/180),s=this.satelliteField.nearest(this.raycaster.ray.direction,i);return s&&this.groundHides(t,e)?void 0:s}updateCelestialLight(t,e){const i=this.relativeScale,s=t.sun.altitudeDeg>=Dh,n=!s&&t.moon.altitudeDeg>=Dh,a=s?t.sun:t.moon,r=[0,0,0],o=Math.max(0,Math.sin(Math.max(a.altitudeDeg,0)*Ve)),l=this.siteElevationM+this.observerElevationM;let h=a,u=s||n?s2.directFraction(a.altitudeDeg,l):0;s&&u<=0&&t.moon.altitudeDeg>=Dh&&(h=t.moon,u=s2.directFraction(h.altitudeDeg,l));const d=Math.max(0,Math.sin(Math.max(h.altitudeDeg,0)*Ve)),f=s||n?this.cloudTransmission(a):1,p=-Math.log(Math.max(f,1e-6)),g=Math.max(0,1/(1+.1125*p)-f),m=[0,0,0];if(s||n){const S=Ne.illuminanceOf(a.magnitude)*i,E=this.air.transmittanceFromSpace(l,a.altitudeDeg);for(let D=0;D<3;D++)m[D]=S*E[D]*g*o,this.cloudBeam[D]=S*E[D];const{x:b,y:A,z:T}=mi(a.altitudeDeg,a.azimuthDeg,1);if(this.cloudBeamDirection.set(b,A,T),u>0){const D=Ne.illuminanceOf(h.magnitude)*i,I=h===a?E:this.air.transmittanceFromSpace(l,h.altitudeDeg),C=h===a?f:this.cloudTransmission(h);for(let N=0;N<3;N++)r[N]=D*I[N]*C*u}}else this.cloudBeam.fill(0);const v=this.surroundings;if(v)this.skyLight.color.setRGB(v.up[0]*i,v.up[1]*i,v.up[2]*i),this.skyLight.groundColor.setRGB(v.down[0]*i,v.down[1]*i,v.down[2]*i);else{const S=this.skyCloudTransmission(),E=e.skyIrradiance,b=[0,1,2].map(T=>E[T]*S+m[T]);this.skyLight.color.setRGB(b[0],b[1],b[2]);const A=Jt.GROUND_ALBEDO;this.skyLight.groundColor.setRGB(A*(b[0]+r[0]*d),A*(b[1]+r[1]*d),A*(b[2]+r[2]*d))}if(this.skyLight.intensity=1,this.sceneSunBeam=h===t.sun?[r[0],r[1],r[2]]:[0,0,0],!s&&!n||u<=0){this.celestialLight.intensity=0;return}const{x:M,y:x,z:y}=mi(h.altitudeDeg,h.azimuthDeg,1);this.lightDirection.set(M,x,y),this.celestialLight.shadow.normalBias=Zp*Ca(x/s6,.1,1),this.placeShadowFrustum();const w=Math.max(r[0],r[1],r[2],1e-30);this.celestialLight.color.setRGB(r[0]/w,r[1]/w,r[2]/w),this.celestialLight.intensity=w,this.celestialLight.castShadow=this.decorGroups.size>0||this.bodySystem.any}static MEAN_COSINE=.5;static ABOVE_CLOUD_M=8e3;lightFromAbove(t,e){const i=this.lastAstronomy?.sun,s=[0,0,0];if(i){const n=ln.litFraction(e.sunElevationDeg,e.heightM);if(n>0){const a=this.air.transmittanceFromSpace(e.heightM,e.sunElevationDeg),r=Ne.illuminanceOf(i.magnitude)*this.relativeScale,o=e.heightM>=ct.ABOVE_CLOUD_M?1:this.cloudTransmission(i);for(let l=0;l<3;l++)s[l]=Math.max(0,r*a[l]*n*o-this.sceneSunBeam[l])}}t.traverse(n=>{const a=n.material;if(!(a instanceof sa||a instanceof _r)||n.userData.emissive)return;a.map&&!a.emissiveMap&&(a.emissiveMap=a.map,a.needsUpdate=!0);const r=ct.MEAN_COSINE/Math.PI;a.emissive.setRGB(a.color.r*s[0]*r,a.color.g*s[1]*r,a.color.b*s[2]*r)})}lightDirection=new _(0,1,0);placeShadowFrustum(){const t=this.lightDirection,e=this.celestialLight.shadow.camera,i=(e.right-e.left)/this.celestialLight.shadow.mapSize.x,s=this.shadowAxisX.crossVectors(this.shadowUp,t);s.lengthSq()<1e-8&&s.set(1,0,0),s.normalize();const n=this.shadowAxisY.crossVectors(t,s).normalize(),a=this.shadowWorld.set(this.bodyOrigin.x,this.cabinShadow?this.camera.position.y:0,this.bodyOrigin.z),r=l=>{const h=a.dot(l)/i;return(h-Math.round(h))*i},o=this.celestialLightTarget.position.set(0,this.cabinShadow?this.camera.position.y:0,0).addScaledVector(s,r(s)).addScaledVector(n,r(n));this.celestialLightTarget.updateMatrixWorld(),this.celestialLight.position.copy(o).addScaledVector(t,this.shadowLightDistanceM)}fitShadowToCabin(t){if(t===this.cabinShadow)return;this.cabinShadow=t;const e=this.celestialLight.shadow;if(!t){this.shadowHalfExtentM=-1;return}const i=e.camera,s=i6;i.left=-s,i.right=s,i.top=s,i.bottom=-s,this.shadowHalfExtentM=s,this.shadowLightDistanceM=Wd+5,i.near=this.shadowLightDistanceM-Wd,i.far=this.shadowLightDistanceM+Wd,i.updateProjectionMatrix(),e.bias=-.004/(2*Wd),e.mapSize.x!==2048&&(e.mapSize.set(2048,2048),e.map?.dispose(),e.map=null)}static CABIN_SKY_SHARE=.3;dimCabinSky(t){for(const e of t)e.traverse(i=>{const s=i.material;for(const n of Array.isArray(s)?s:s?[s]:[]){const a=n;a.isMeshStandardMaterial&&a.envMapIntensity!==ct.CABIN_SKY_SHARE&&(a.envMapIntensity=ct.CABIN_SKY_SHARE)}})}cabinShadow=!1;fitShadowToBodies(){if(this.cabinShadow)return;const t=this.bodySystem.reachFrom(this.camera.position),e=Math.min(e6,Math.max(dr,Math.ceil(t*1.25/20)*20));if(e===this.shadowHalfExtentM)return;this.shadowHalfExtentM=e;const i=this.celestialLight.shadow,s=i.camera;s.left=-e,s.right=e,s.top=e,s.bottom=-e;const n=Math.max(Jc,e*(Jc/dr));this.shadowLightDistanceM=Math.max(Ii,n+10),s.near=this.shadowLightDistanceM-n,s.far=this.shadowLightDistanceM+n,s.updateProjectionMatrix(),i.bias=-qp/(2*n);const a=e>2*dr?2048:1024;i.mapSize.x!==a&&(i.mapSize.set(a,a),i.map?.dispose(),i.map=null),this.placeShadowFrustum()}shadowHalfExtentM=dr;shadowLightDistanceM=Ii;shadowUp=new _(0,1,0);shadowAxisX=new _;shadowAxisY=new _;shadowWorld=new _;skyCloudTransmission(){let t=this.cloudTransmission({altitudeDeg:90,azimuthDeg:0}),e=1;for(const i of[20,45,70]){const s=i*Ve,n=Math.sin(s)*Math.cos(s)*2;for(let a=0;a<360;a+=60)t+=n*this.cloudTransmission({altitudeDeg:i,azimuthDeg:a}),e+=n}return t/e}cloudBeam=[0,0,0];cloudBeamDirection=new _(0,1,0);get relativeScale(){return this.scatteredSky?.relativeScale??1/zt.semiSaturation(zt.DAYLIGHT_ANCHOR_CD_M2)}setMeteorShower(t,e,i){this.meteorSystem||(this.meteorSystem=new ws,this.celestialGroup.add(this.meteorSystem.object)),this.meteorSystem.setShower(t,e,i)}get meteorSchedule(){return this.meteorSystem?.schedule??[]}meteorMidpoint(t){return this.meteorSystem?.midpointOf(t)}updateMeteors(t){this.meteorSystem&&(this.meteorSystem.update(t),this.emitterLights.set("meteors",[],this.meteorSystem.heads.map(e=>this.farEmitterOf(e,e.magnitude)).filter(e=>e!==void 0)),this.refreshSkyFlare())}farEmitterOf(t,e){if(!(t.altitudeDeg>0)||!Number.isFinite(e))return;const i=Math.max(this.relativeScale,1e-30),s=this.arrivingIlluminance(t,e,this.cloudTransmission(t)),{x:n,y:a,z:r}=mi(t.altitudeDeg,t.azimuthDeg,1);return{direction:new _(n,a,r),lux:[s[0]/i,s[1]/i,s[2]/i],sky:{altitudeDeg:t.altitudeDeg,azimuthDeg:t.azimuthDeg,magnitude:e}}}skyFlare;refreshSkyFlare(){const t=this.emitterLights.brightestInSky;t===this.skyFlare||!t&&!this.skyFlare||(this.skyFlare=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrument(t,e){this.projectionKind=t.projection,this.grain=t.detailUm!==void 0&&t.frame?{detailUm:t.detailUm,frameHeightMm:t.frame.heightMm}:void 0;const i=Ts.starPointsOf(t,e);i!==this.starPoints&&(this.starPoints=i,this.lensFlare&&(this.lensFlare.uniforms.uStarPoints.value=i),this.render())}magnitudeLimitOf(t){const e=Et.starLossMagnitudes(t.sun.altitudeDeg,{phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction),altitudeDeg:t.moon.altitudeDeg},this.lightPollution);return lf(t.sun.altitudeDeg,this.instrumentMagnitudeGain,e)}setLightPollution(t){t!==this.lightPollution&&(this.lightPollution=t,this.lastAstronomy&&this.scatteredSky?.update(this.scatteredSkyState(this.lastAstronomy)))}setInstrumentGain(t,e=!1,i=0){const s=Number.isFinite(t)?t:0;this.instrumentMagnitudeGain=s-2.5*i,this.filterTransmittance=10**-i,this.scatteredSky?.setInstrument(e,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 t=this.compileOffThread().then(()=>{this.compiling===t&&(this.compiling=void 0,this.render())});this.compiling=t;return}if(!this.compiling){if(this.skyHoldUntilMs){if(!this.sceneSettled()&&performance.now()<this.skyHoldUntilMs){this.firstFrameReady()&&this.arrivalsPending===0&&this.refreshReflections(!0);return}this.skyHoldUntilMs=null,this.skyGlow?.setWithheld(!1),this.iceHalos?.setUrgent(!1),this.onFirstFrameHold?.(!1),this.skyColoursStale&&this.lastAstronomy&&this.applySkyColours(this.lastAstronomy)}this.frameDirty=!1,this.references?.release(),this.refreshReflections(),this.resolution.beginDrawing();try{const t=this.usableGhostPass();t?(this.exposureSubjectBounds=[],this.renderOnce(t.frame),t.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),t.develop(this.renderer,t.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 t=this.renderer.compile(this.scene,this.camera);if(!this.renderer.extensions.get("KHR_parallel_shader_compile"))return Promise.resolve();const e=this.renderer.properties,i=performance.now()+ct.COMPILE_WAIT_MS;return new Promise(s=>{const n=()=>{if(this.contextReleased)return s();for(const a of t){const r=e.get(a)?.currentProgram;(!r||r.isReady())&&t.delete(a)}t.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.scatteredSky?.invalidate(),this.renderer.forceContextLoss())}restoreContext(){this.contextReleased&&(this.contextReleased=!1,this.renderer.forceContextRestore(),this.scatteredSky?.invalidate(),this.pumpScatteredSky(),this.compileNextFrameOffThread(),this.syncAnimationLoop(),this.render())}suspended=!1;suspend(){this.suspended||(this.suspended=!0,this.stopTwinkle(),this.cancelFlush(),this.cancelExposure(),this.cancelScatteredSkyPump(),clearTimeout(this.reflectionTimer),this.reflectionTimer=void 0)}resume(){this.suspended&&(this.suspended=!1,this.pumpScatteredSky(),this.syncAnimationLoop(),this.render())}cancelFlush(){this.flushFrameId!==null&&(cancelAnimationFrame(this.flushFrameId),this.flushFrameId=null)}frame(t){if(this.animationsRunning){const e=this.lastFrameTimeMs===void 0?0:t-this.lastFrameTimeMs;if(this.lastFrameTimeMs=t,this.hasAnimations()&&this.animate(t,e),!this.pixelRatioHeld){const i=this.resolution.ratioFor(t,e);i!==this.renderer.getPixelRatio()&&this.applyPixelRatio(i)}}this.drawIfDirty()}get maxPixelRatio(){return this.resolution.maximum}pixelRatioHeld=!1;holdPixelRatio(t){this.pixelRatioHeld=t!==void 0;const e=t??this.resolution.maximum;this.renderer.getPixelRatio()!==e&&this.applyPixelRatio(e)}async controlFrame(){await this.loadControlPasses(),this.render();const t=this.drawn;return this.drawIfDirty(),this.drawn===t?void 0:{image:this.renderer.domElement.toDataURL("image/png"),...this.drawControlPasses()}}async loadControlPasses(){if(this.controlPasses)return;const{ControlPasses:t}=await Ht(async()=>{const{ControlPasses:e}=await import("./ControlPasses-B_uf1Wmh.js");return{ControlPasses:e}},__vite__mapDeps([34,1,2,3,4,5,6,7]),import.meta.url);this.controlPasses??=new t}drawControlPasses(){if(!this.controlPasses)throw new Error("The control passes are not loaded: see loadControlPasses");return this.controlPasses.draw({renderer:this.renderer,scene:this.scene,camera:this.camera,equidistant:this.usableEquidistantPass(),sky:[this.celestialGroup,...this.pointLayerHost.clouds(),...this.lensFlare?[this.lensFlare.mesh]:[]],isSolid:t=>ct.isSolidSurface(t),drawPhenomena:t=>this.renderPhenomenaPass(t)})}controlPasses;cabinDecor(){return this.cabinGroups}enclosingDecor(){const t=this.camera.getWorldPosition(this.enclosingEye);return this.decorObjects.filter(e=>e.kind==="aircraft"||e.kind==="vehicle").map(e=>this.decorGroups.get(e.id)).filter(e=>e!==void 0&&this.enclosingBox.setFromObject(e).containsPoint(t))}enclosingEye=new _;enclosingBox=new ze;cabinGroups=[];findCabin(t,e,i){const s=[];for(const n of this.decorObjects){if(n.kind!=="aircraft"&&n.kind!=="vehicle"||n.observerSide!==void 0&&Hl(n.kind))continue;const a=this.decorGroups.get(n.id);if(!a)continue;const r=ga(n,t),o=r.eastM+e.x+i.x,l=-r.northM+e.z+i.z,h=ht.sizeOf(n),u=Math.max(h.widthM,h.lengthM)/2;Math.hypot(o,l)<u&&Math.abs(r.altitudeM-this.poseStatedElevationM-1.6)<u&&s.push(a)}return this.cabinGroups=s,s}static CABIN_MATE_RANGE_M=4;static AIRBORNE_M=100;refreshReflections(t=!1){this.reflections??=new Ys(this.renderer);const e=["sun","moon"].flatMap(l=>this.bodyMeshes.get(l)??[]),i=[...this.compassSprites,...this.lensFlare?[this.lensFlare.mesh]:[],...e,...[...this.glareSprites.values()].map(l=>l.mesh),...this.bodySystem.group.children.filter(l=>l.name.startsWith("body-speck:"))],s=[...this.starTiers.map(l=>l.points),...[...this.bodyMeshes.values()].filter(l=>l instanceof Cn),...[this.rainSystem?.points,this.precipitationPoints,this.rainSplashSystem?.points].filter(l=>l!==void 0),...this.cabinDecor(),...this.enclosingDecor(),...this.decorLamps,...this.bodySystem.group.children.filter(l=>l.name.startsWith("body:")),...[this.meteorSystem?.object].filter(l=>l!==void 0),...[...this.skyEventLayers.values()].filter(l=>l.simulation?.hiddenFromEye).map(l=>l.simulation.object)],n=this.relativeScale,a=this.sceneVersion,r=this.recordingTimeMs,o=this.reflections.refresh(this.renderer,this.scene,this.camera.position,this.bodySystem.reflectors,i,[...this.decorGroups.values(),...this.waterSystem?[this.waterSystem.group]:[],...this.railwaySystem?[this.railwaySystem.group]:[]],a,s,l=>this.measureSurroundings(l,n,a,r),t?0:Ys.REFRESH_MS);o===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()}))},o))}static adaptingLuminance(t,e){const i=(.2126*e[0]+.7152*e[1]+.0722*e[2])/Math.PI;return Math.max(t,ct.GROUND_ADAPTATION_SHARE*i)}static GROUND_ADAPTATION_SHARE=.5;measureSurroundings(t,e,i,s){const n=this.lastAstronomy;if(!n)return;this.probeIrradiance??=new Ml,this.framePhotograph={texture:t,scale:e,atMs:s};const a=[n.sun,n.moon].filter(r=>r.altitudeDeg>-2).map(r=>mi(r.altitudeDeg,r.azimuthDeg,1));this.probeIrradiance.measure(this.renderer,t,a,r=>{const o=p=>p.map(g=>g/e);if(![...r.up,...r.down,r.logAverage].every(Number.isFinite)){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}const l=this.surroundings,h={up:o(r.up),down:o(r.down)},u=(p,g)=>p.some((m,v)=>Math.abs(m-g[v])>.03*Math.max(Math.abs(m),Math.abs(g[v]),1e-12)),d=!l||u(l.up,h.up)||u(l.down,h.down);d&&(this.surroundings=h),this.eyeSettledVersion=-1;const f=this.scatteredSky?.adaptToSurroundings(ct.adaptingLuminance(Math.exp(r.logAverage)/e,h.down))??!1;if(!d&&!f){this.eyeSettledVersion=i,this.skyHoldUntilMs&&this.redrawHeld();return}this.skyColoursStale=!0,this.render()})}lightUnderClouds(t){const e=this.surroundings;if(!e)return;const i=t.sun.altitudeDeg>=Dh?t.sun:t.moon.altitudeDeg>=Dh?t.moon:void 0;if(!i)return;const s=this.relativeScale/Math.PI;return{through:this.cloudTransmission(i),radiance:[e.up[0]*s,e.up[1]*s,e.up[2]*s]}}probeIrradiance;meterFrame(){const t=this.framePhotograph;if(!this.medium?.autoExposure||!t)return;this.frameMeter??=new ca;const e=this.lastAstronomy?.sun,i=e&&e.altitudeDeg>-2?mi(e.altitudeDeg,e.azimuthDeg,1):void 0,s=this.medium.exposureFollowMs??ct.EXPOSURE_FOLLOW_MS;this.frameMeter.measure(this.renderer,t.texture,this.camera,i,n=>{const a={mean:n.mean/t.scale,brightest:n.brightest/t.scale};if(!Number.isFinite(a.mean)||!Number.isFinite(a.brightest))return;const r=this.frameLight,o=t.atMs,l=r?o-r.atMs:1/0,h=l<0||l>ct.EXPOSURE_JUMP_MS,u=h||l===0&&r?.jumped?1:1-Math.exp(-l/s),d=(g,m)=>g>0&&m>0?g*(m/g)**u:m,f={mean:d(r?.mean??0,a.mean),brightest:d(r?.brightest??0,a.brightest),atMs:o,jumped:h||l===0&&(r?.jumped??!1)};this.frameLight=f;const p=(g,m)=>Math.abs(g-m)>.01*Math.max(g,m);(!r||p(r.mean,f.mean)||p(r.brightest,f.brightest))&&this.render()})}static EXPOSURE_FOLLOW_MS=300;static EXPOSURE_JUMP_MS=2e3;retina;bleachRetina(){if(Si.uRetinaOn.value=0,this.medium)return;const t=[];for(const r of this.emitterLights.farEmitters){const o=this.screenPointOf(r.direction);!o||Math.abs(o.ndcX)>1.2||Math.abs(o.ndcY)>1.2||t.push({ndcX:o.ndcX,ndcY:o.ndcY,lux:En.luminanceOf(r.lux)})}const e=this.renderer.getDrawingBufferSize(this.retinaSize),i=e.x/Math.max(e.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>ce.JUMP_MS)&&this.retinaHistory&&this.recordingTimeMs>0)this.retina??=new ce,this.retina.replay(0,this.recordingTimeMs,r=>this.historicBleachingAt(r,i),s,this.retinaHistoryOf);else{if(!this.retina&&t.length===0)return;this.retina??=new ce,this.retina.advance(this.recordingTimeMs,t,s)}this.retina.any&&(Si.uRetina.value=this.retina.texture,Si.uRetinaOn.value=1,Si.uRetinaViewport.value.copy(e))}retinaSize=new Q;retinaHistory;setRetinaHistory(t,e){this.retinaHistory=t,this.retinaHistoryOf=e}retinaHistoryOf;historicBleachingAt(t,e){const i=this.retinaHistory?.(t);if(!i||i.views.length===0)return[];const s=i.pose,n=this.historicQuaternion.setFromEuler(this.historicEuler.set((s?.pitchDeg??0)*Ve,-(s?.headingDeg??0)*Ve,(s?.rollDeg??0)*Ve,"YXZ")).invert(),a=s?.fovDeg??this.camera.fov,r=[];for(const o of i.views){const l=this.farEmitterOf(o.head,o.magnitude);if(!l)continue;const h=this.screenPointIn(this.historicDirection.copy(l.direction).applyQuaternion(n),a,e);!h||Math.abs(h.ndcX)>1.2||Math.abs(h.ndcY)>1.2||r.push({ndcX:h.ndcX,ndcY:h.ndcY,lux:En.luminanceOf(l.lux)})}return r}historicQuaternion=new Fs;historicEuler=new Ma;historicDirection=new _;pickAfterimageAt(t,e){return!this.medium&&this.retina!==void 0&&this.retina.any&&this.retina.leftAt(t,e)<ct.AFTERIMAGE_SEEN_BELOW}static AFTERIMAGE_SEEN_BELOW=.9;recordingTimeMs=0;setRecordingTime(t){this.recordingTimeMs=t}frameMeter;framePhotograph;frameLight;decorLamps=[];static lampsOf(t){const e=[];for(const i of t)i.traverse(s=>{s.userData.emissive===!0&&e.push(s)});return e}surroundings;animate(t,e){const i=Math.min(e/1e3,k6);this.twinkleSeconds=t/1e3,this.updateTwinkle(this.twinkleSeconds),this.updatePrecipitation(t/1e3,i),this.updateRain(i),this.lensFlare&&(this.lensFlare.uniforms.uTime.value=t/1e3),this.developingExposure||(this.frameDirty=!0)}setMaxPixelRatio(t){this.resolution.maximum=t,this.renderer.getPixelRatio()>this.resolution.maximum&&this.applyPixelRatio(this.resolution.maximum)}applyPixelRatio(t){this.renderer.setPixelRatio(t),this.renderer.setSize(this.cssSize.width,this.cssSize.height,!1),this.frameDirty=!0}setExposure(t,e){const i=e?Math.max(1,Math.round(t)):1;if(i===this.exposureInstants&&(i===1||e===this.exposureInstantAt)){this.exposureInstantAt=e;return}this.exposureInstants=i,this.exposureInstantAt=e,i===1&&(this.cancelExposure(),this.exposureAccumulation?.dispose(),this.exposureAccumulation=void 0),this.render()}renderOnce(t){if(this.aimBeams(),ht.setWindowLuminance(this.relativeScale),this.onMapSubjectBounds){const a=this.mapSubjectBounds();t?this.exposureSubjectBounds.push(...a):this.onMapSubjectBounds(a)}const e=this.usableEquidistantPass();this.phenomena.setCloudLayers(this.layeredClouds?.volumes??[]),this.emitterLights.cast(this.camera.position),this.phenomena.place(this.camera,(a,r,o)=>this.directionAtScreenPoint(a,r,o),a=>this.screenPointOf(a)),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?[Xg]:[],!t)&&(this.mirrorCatchUp??=setTimeout(()=>{this.mirrorCatchUp=void 0,this.render()},yn.INTERVAL_MS)),Si.uRodShare.value=this.scatteredSky?.rodShare??0,Si.uRelativeScale.value=this.relativeScale,this.meterFrame(),this.applyMedium(),this.bleachRetina(),this.waterSystem?.reflectBodies(this.renderer,this.scene,this.camera,Wg,this.bodySystem.any,e&&gi.supports(this.camera.fov,this.camera.aspect)?e.sourceFovDeg(this.camera.fov,this.camera.aspect):void 0);const s=!!this.references?.any||this.phenomena.any||this.compassSprites.some(a=>a.visible);Si.uHasOverlay.value=s?1:0;const n=s?a=>this.renderOverlayPasses(a):void 0;if(this.skyGlow?.setDestinationEncoded(!1),!e){this.updateLensFlarePosition();const a=this.usableDepthOfFieldPass();a?a.render(this.renderer,this.scene,this.camera,n,t):this.usableFinishPass().render(this.renderer,this.scene,this.camera,n,void 0,t);return}e.render(this.renderer,this.scene,this.camera,this.camera.fov,()=>this.updateLensFlarePosition(),n,a=>{this.lensFlare&&(this.lensFlare.mesh.visible=a?!1:this.sunVisible)},()=>this.renderDazzleOnResample(),t,this.pointLayerHost)}pointLayerHost={points:()=>{const t=[];return this.celestialGroup.traverse(e=>{(e instanceof Cn&&e.userData.pointSource||e instanceof dt&&e.userData.skyRibbon)&&t.push(e)}),[...t,...this.bodySystem.pointSources]},clouds:()=>[...this.layeredClouds?.meshes??[],...this.cloudMesh?[this.cloudMesh]:[],...this.cirrusMesh?[this.cirrusMesh]:[]],sky:this.celestialGroup};renderOverlayPasses(t=this.camera){this.renderReferencesPass(t),this.renderBodiesOverReferences(t),this.renderPhenomenaPass(t),this.renderHudPass(t)}renderHudPass(t){const e=this.traceSystem?.any&&this.tracesShown;if(!e&&!this.compassSprites.some(n=>n.visible))return;e&&this.traceSystem.setView(this.renderer.getDrawingBufferSize(this.traceResolution),t.fov);const i=this.renderer.autoClear,s=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Kp),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}renderBodiesOverReferences(t){if(!this.references?.any||!this.bodySystem.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(Wg),this.scene.overrideMaterial=this.bodyCutOutMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null,t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}bodyCutOutMaterial=new un({blending:oc,blendSrc:qa,blendDst:qa,blendSrcAlpha:qa,blendDstAlpha:qa,toneMapped:!1});renderReferencesPass(t){if(!this.references?.any)return;const e=this.renderer.autoClear,i=this.renderer.shadowMap.autoUpdate;this.renderer.autoClear=!1,this.renderer.shadowMap.autoUpdate=!1,t.layers.set(this.references.layer),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=e,this.renderer.shadowMap.autoUpdate=i}setReferences(t,e){const i=t.map(s=>{const n=this.documentRelative(s.src);return n===s.src?s:{...s,src:n}});if(this.references){this.references.set(i,void 0,e);return}if(i.length===0){this.pendingReferences=void 0;return}this.pendingReferences={references:i,observerAt:e},this.referencesLoading??=Ht(async()=>{const{ReferenceSystem:s}=await import("./ReferenceSystem-xm8mzWiT.js");return{ReferenceSystem:s}},__vite__mapDeps([35,36,2,37,1,3,4,5,6,7]),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[r,o]of this.referenceViews)n.setView(r,o);n.setShown(this.referencesShown);const a=this.pendingReferences;return this.pendingReferences=void 0,a&&n.set(a.references,void 0,a.observerAt),this.render(),n})}setReferencesTime(t){this.referenceClock=t,this.references?.setTime(t)}referenceAspect(t){return this.references?.aspectOf(t)}directionAt(t,e){return this.directionAtScreenPoint(t,e,new _)}referenceFailure(t){return this.references?.failureOf(this.documentRelative(t))}get areReferencesShown(){return this.referencesShown}setReferencesShown(t){this.referencesShown=t,this.references?.setShown(t),this.render()}setReferenceView(t,e){this.referenceViews.set(t,e),this.references?.setView(t,e),this.render()}renderPhenomenaPass(t){if(!this.phenomena.any)return;t.updateMatrixWorld();const e=this.phenomena.screenBox(t);if(e&&(e.x0>1||e.x1<-1||e.y0>1||e.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=e?this.narrowTo(t,e):t,a=this.phenomenaFrustum.setFromProjectionMatrix(this.phenomenaViewProjection.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse)),r=this.phenomena.furthestM;let o=0;for(const l of this.decorObjects){const h=this.decorGroups.get(l.id);if(!h)continue;const u=l.kind!=="crop"&&this.mayHide(h,t,a,r);ct.markDecorDepth(h,u),u&&o++}o>0&&(t.layers.set(Xp),this.scene.overrideMaterial=this.decorDepthMaterial,this.renderer.render(this.scene,t),this.scene.overrideMaterial=null),t.layers.set(Xg),this.renderer.render(this.scene,t),t.layers.set(0),this.renderer.autoClear=i,this.renderer.shadowMap.autoUpdate=s}phenomenaFrustum=new d0;phenomenaViewProjection=new Gt;occluderSphere=new ia;occluderEye=new _;localBounds=new WeakMap;mayHide(t,e,i,s){let n=0;t.traverse(()=>n++);let a=this.localBounds.get(t);if(!a||a.objects!==n){t.updateMatrixWorld(!0);const o=new ze().setFromObject(t);if(o.isEmpty())return!1;a={sphere:o.getBoundingSphere(new ia).applyMatrix4(new Gt().copy(t.matrixWorld).invert()),objects:n},this.localBounds.set(t,a)}const r=this.occluderSphere.copy(a.sphere).applyMatrix4(t.matrixWorld);return r.center.distanceTo(e.getWorldPosition(this.occluderEye))-r.radius>s?!1:i.intersectsSphere(r)}narrowTo(t,e){const i=this.renderer.getDrawingBufferSize(new Q),s=ct.PHENOMENA_VIEW_MARGIN_PX*this.renderer.getPixelRatio(),n=Math.max(0,Math.floor((Math.max(-1,e.x0)+1)/2*i.x-s)),a=Math.max(0,Math.floor((Math.max(-1,e.y0)+1)/2*i.y-s)),r=Math.min(i.x,Math.ceil((Math.min(1,e.x1)+1)/2*i.x+s)),o=Math.min(i.y,Math.ceil((Math.min(1,e.y1)+1)/2*i.y+s)),l=this.narrowCamera.copy(t);return t.getWorldPosition(l.position),t.getWorldQuaternion(l.quaternion),l.setViewOffset(i.x,i.y,n,i.y-o,Math.max(1,r-n),Math.max(1,o-a)),l.updateMatrixWorld(),l}narrowCamera=new Ns;static PHENOMENA_VIEW_MARGIN_PX=4;decorDepthMaterial=new un({colorWrite:!1,side:ds});static HEAD_TURN_LIMIT_DEG=85;static turnHead(t,e,i){const s=t.getObjectByName("head");if(!s)return;const n=((i-e)%360+540)%360-180,a=Math.max(-85,Math.min(ct.HEAD_TURN_LIMIT_DEG,n));s.rotation.y=-a*Ve}static isSolidSurface(t){if(!(t instanceof dt))return!0;const e=Array.isArray(t.material)?t.material[0]:t.material;return e.depthWrite!==!1&&e.blending!==gs}static markDecorDepth(t,e){t.traverse(i=>{if(!(i instanceof dt))return;e&&ct.isSolidSurface(i)?i.layers.enable(Xp):i.layers.disable(Xp)})}startExposure(){this.cancelExposure(),this.references?.hold(this.camera),this.exposureSubjectBounds=[];const t=this.renderer.getDrawingBufferSize(new Q),e=Math.max(1,Math.round(t.x)),i=Math.max(1,Math.round(t.y));this.exposureAccumulation||(this.exposureAccumulation=new II(e,i)),this.exposureAccumulation.resize(e,i),this.exposureAccumulation.open(this.renderer),this.exposureInstantsDone=0,this.exposureFrameId=requestAnimationFrame(()=>this.developExposure())}developExposure(){this.exposureFrameId=null;const t=this.exposureInstantAt,e=this.exposureAccumulation;if(!t||!e)return;const i=1/this.exposureInstants;this.resolution.beginDrawing();const s=performance.now()+ct.EXPOSURE_BUDGET_MS,n=ct.exposureInstantsPerFrame(e.instantTarget.scene.width*e.instantTarget.scene.height);let a=0;do{this.restateAt(t,this.exposureInstantsDone);const r=this.compassSprites.map(o=>o.visible);for(const o of this.compassSprites)o.visible=!1;try{this.renderOnce(e.instantTarget)}finally{this.compassSprites.forEach((o,l)=>{o.visible=r[l]})}e.add(this.renderer,i),this.exposureInstantsDone++,a++}while(this.exposureInstantsDone<this.exposureInstants&&performance.now()<s&&a<n);this.restateAt(t,0),this.presentExposure(),this.resolution.endDrawing(),this.exposureInstantsDone<this.exposureInstants&&(this.exposureFrameId=requestAnimationFrame(()=>this.developExposure()))}presentExposure(){Si.uRodShare.value=this.scatteredSky?.rodShare??0,Si.uHasOverlay.value=1,Si.uRelativeScale.value=this.relativeScale,this.applyMedium();const t=this.exposureInstants/this.exposureInstantsDone,e=this.usableGhostPass();if(e?.setFilmPrint(this.medium?.print,this.decorTime,this.camera.aspect,this.medium?.monochrome),e&&this.exposureAccumulation?e.develop(this.renderer,this.exposureAccumulation.developed,this.ghostOptics,t,this.sunBeyondPicture()):this.exposureAccumulation?.develop(this.renderer,t),this.onMapSubjectBounds?.(this.exposureSubjectBounds),!this.compassSprites.some(r=>r.visible))return;const i=new zn,s=new Bn(-1,1,1,-1,0,2),n=Kd/(D2*Math.tan(I2*Ve/2));for(const r of this.compassSprites){if(!r.visible)continue;const o=r.getWorldPosition(new _).sub(this.camera.position).normalize(),l=this.screenPointOf(o);if(!l)continue;const h=new el(r.material);h.position.set(l.ndcX,l.ndcY,-1),h.scale.set(n/this.camera.aspect,n,1),i.add(h)}const a=this.renderer.autoClear;this.renderer.autoClear=!1;try{this.renderer.render(i,s)}finally{this.renderer.autoClear=a}}onMapSubjectBounds;exposureSubjectBounds=[];static MAP_SUBJECT_NEAREST_M=8;mapSubjectBounds(){const t=[],e=new ze,i=new _,s=this.camera.getWorldDirection(new _),n=this.decorObjects.filter(r=>r.track?.length||r.kind==="aircraft"||r.kind==="vehicle").map(r=>this.decorGroups.get(r.id)),a=this.bodySystem.reflectors.map(r=>r.holder);for(const r of[...n,...a]){if(!r?.visible||(e.setFromObject(r),e.isEmpty())||e.distanceToPoint(this.camera.position)<ct.MAP_SUBJECT_NEAREST_M)continue;let o=1/0,l=-1/0,h=1/0,u=-1/0;for(const d of[e.min.x,e.max.x])for(const f of[e.min.y,e.max.y])for(const p of[e.min.z,e.max.z]){if(i.set(d,f,p).sub(this.camera.position).normalize(),i.dot(s)<=0)continue;const g=this.screenPointOf(i);if(!g)continue;const m=(g.ndcX+1)/2,v=(1-g.ndcY)/2;o=Math.min(o,m),l=Math.max(l,m),h=Math.min(h,v),u=Math.max(u,v)}o=Math.max(o,0),l=Math.min(l,1),h=Math.max(h,0),u=Math.min(u,1),l>=o&&u>=h&&t.push({x:o,y:h,width:l-o,height:u-h})}return t}restateAt(t,e){this.restatingExposure=!0;try{t(e)}finally{this.restatingExposure=!1}}cancelExposure(){this.exposureFrameId!==null&&(cancelAnimationFrame(this.exposureFrameId),this.exposureFrameId=null)}setLensOptics(t){const e=this.lensOptics;this.lensOptics=t,(e===void 0!=(t===void 0)||e&&t&&(e.focalLengthMm!==t.focalLengthMm||e.fNumber!==t.fNumber||e.focusDistance!==t.focusDistance||e.frameHeightMm!==t.frameHeightMm))&&(t&&this.depthOfFieldPass&&this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.render())}eyeOptics(){if(!this.eyeAsLens)return;const t=Math.max(1e-6,this.scatteredSky?.sceneAdaptation??1e3),e=4.9-3*Math.tanh(.4*Math.log10(t)),i=ct.EYE_FOCAL_MM;return{focalLengthMm:i,fNumber:i/e,focusDistance:0,frameHeightMm:2*i*Math.tan(this.camera.fov*Ve/2)}}static EYE_FOCAL_MM=17;static EYE_LENS_MAX_FOV_DEG=20;get eyeAsLens(){return this.projectionKind==="equidistant"&&!this.lensOptics&&this.camera.fov<=ct.EYE_LENS_MAX_FOV_DEG}usableDepthOfFieldPass(){const t=this.lensOptics??this.eyeOptics();if(!t)return;const e=this.renderer.getDrawingBufferSize(new Q),i=Math.max(1,Math.round(e.x)),s=Math.max(1,Math.round(e.y));return this.depthOfFieldPass||(this.depthOfFieldPass=new yl(i,s)),this.depthOfFieldPass.resize(i,s),this.depthOfFieldPass.setLens(t.focalLengthMm,t.fNumber,t.focusDistance,t.frameHeightMm),this.depthOfFieldPass.setAir(this.weather.visibilityKm!==void 0?this.weather.visibilityKm*1e3:void 0,this.camera.fov),this.depthOfFieldPass}setLensGhosts(t){JSON.stringify(t)!==JSON.stringify(this.ghostOptics)&&(this.ghostOptics=t,t.ghosts.length===0&&(this.ghostPass?.dispose(),this.ghostPass=void 0),this.render())}ghostsReadableAt(t,e){return this.ghostPass?.holdsPictureAt(this.renderer,t,e)??!1}pickGhostAt(t,e){if(!(!this.ghostPass||!this.ghostOptics.ghosts.length))return this.ghostPass.pickAt(this.renderer,t,e,this.ghostOptics,Si.uMediumExposure.value,this.sunBeyondPicture())}pickDropAt(t,e){return!this.ghostPass||this.ghostOptics.impacts<=0&&this.ghostOptics.drops<=0?!1:this.ghostPass.dropAt(this.renderer,t,e)>.5}usableGhostPass(){if(!this.ghostOptics?.ghosts.length)return;const t=this.renderer.getDrawingBufferSize(new Q);return this.ghostPass?this.ghostPass.resize(t.x,t.y):this.ghostPass=new xi(t.x,t.y),this.ghostPass}usableFinishPass(){const t=this.renderer.getDrawingBufferSize(new Q);return this.finishPass?this.finishPass.resize(t.x,t.y):this.finishPass=new X1(t.x,t.y),this.finishPass}usableEquidistantPass(){if(this.projectionKind!=="equidistant"||this.eyeAsLens)return;const t=this.renderer.getDrawingBufferSize(new Q);return this.equidistantPass?this.equidistantPass.resize(t.x,t.y):this.equidistantPass=new gi(t.x,t.y),this.equidistantPass}aimAtScreenPoint(t,e,i){this.aimStraightAtScreenPoint(t,e,i),t===this.raycaster&&this.mirrors.any&&this.mirrors.reflect(t,s=>{const n=ct.firstSolid(t.intersectObjects(this.cabinGroups,!0));return!n||n.distance>=s-.001||this.mirrors.isMirror(n.object)})}aimStraightAtScreenPoint(t,e,i){const s=this.projectionKind==="equidistant"&&!this.eyeAsLens?this.equidistantPass:void 0;if(!s){t.setFromCamera(new Q(e,i),this.camera);return}const n=s.directionFor(e,i,this.camera.fov);this.camera.updateMatrixWorld(),t.ray.origin.setFromMatrixPosition(this.camera.matrixWorld),t.ray.direction.set(n.x,n.y,n.z).applyQuaternion(this.camera.quaternion).normalize(),t.camera=this.camera}pickCloudAt(t,e){return this.layeredClouds?.pickInstance(this.cloudDirectionAt(t,e))}cloudDirectionAt(t,e){return this.directionAtScreenPoint(t,e,new _)}directionAtScreenPoint(t,e,i){return this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),i.copy(this.ufoOcclusionRaycaster.ray.direction)}screenPointOf(t){this.camera.updateMatrixWorld();const e=this.screenPointScratch.copy(t).applyQuaternion(this.screenPointQuaternion.copy(this.camera.quaternion).invert()),i=this.renderer.getDrawingBufferSize(this.screenPointSize),s=i.x/Math.max(i.y,1);return this.screenPointIn(e,this.camera.fov,s)}screenPointIn(t,e,i){if(this.projectionKind==="equidistant"&&!this.eyeAsLens&&this.equidistantPass)return gi.ndcFor(t,e,i);if(t.z>=0)return;const s=Math.tan(e/2*Ve);return{ndcX:t.x/-t.z/(i*s),ndcY:t.y/-t.z/s}}screenPointScratch=new _;screenPointQuaternion=new Fs;screenPointSize=new Q;updateLensFlarePosition(){const t=this.lensFlare;if(!t)return;if(!this.sunVisible){t.mesh.visible=!1;return}if(this.camera.updateMatrixWorld(),this.lensFlareScratch.copy(this.sunWorldPosition).applyMatrix4(this.camera.matrixWorldInverse),this.lensFlareScratch.z>0){t.mesh.visible=!1;return}const e=this.sunVisibleFraction();if(e<=0){t.mesh.visible=!1;return}t.mesh.visible=!0,this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.lensFlareScratch.copy(this.sunWorldPosition).project(this.camera);t.uniforms.uLensPosition.value.set(i.x,i.y);const s=this.renderer.domElement.width,n=this.renderer.domElement.height;t.uniforms.uResolution.value.set(s,n),t.uniforms.uTanHalfFov.value=Math.tan(this.camera.fov*Math.PI/360)}sunBeyondPicture(){const t=this.lensFlare;if(!t||!t.mesh.visible)return;const e=this.sunDiscRadiance.map(l=>Math.max(0,l-ct.BRIGHTEST_RELATIVE)*this.sunUnhiddenFraction);if(e[1]<=0)return;const i=Math.tan(t.uniforms.uSourceRadiusDeg.value*Math.PI/180)/t.uniforms.uTanHalfFov.value/2,s=Math.PI*i*i,n=t.uniforms.uLensPosition.value,a=t.uniforms.uTanHalfFov.value,r=this.camera.aspect,o=Pe.offFrameShare(Math.atan(Math.hypot(n.x*r,n.y)*a)*180/Math.PI,Math.atan(Math.hypot(r,1)*a)*180/Math.PI,this.ghostOptics.reachDeg);if(!(o<=0))return{x:n.x,y:n.y,radius:i,flux:[e[0]*s*o,e[1]*s*o,e[2]*s*o]}}renderDazzleOnResample(){const t=this.lensFlare;if(!t||!this.sunVisible)return;const e=this.sunVisibleFraction();if(e<=0)return;this.sunUnhiddenFraction=e,this.applyDazzleStrength();const i=this.screenPointOf(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position).normalize());if(!i)return;const s=this.renderer.getDrawingBufferSize(this.screenPointSize);t.uniforms.uLensPosition.value.set(i.ndcX,i.ndcY),t.uniforms.uResolution.value.set(s.x,s.y),t.uniforms.uEquidistant.value=1,t.uniforms.uHalfFovRad.value=this.camera.fov*Math.PI/360;const n=this.renderer.autoClear;this.renderer.autoClear=!1,t.mesh.visible=!0,t.mesh.layers.enable(b2),this.camera.layers.set(b2),this.renderer.render(this.scene,this.camera),this.camera.layers.set(0),t.mesh.visible=!1,t.uniforms.uEquidistant.value=0,this.renderer.autoClear=n}sunVisibleFraction(){this.raycastableDecor().length>0&&this.scene.updateMatrixWorld();let t=0;for(const e of O2)this.isSunOccluded(e[0],e[1])||t++;return t/O2.length}raycastableDecor(){const t=[];for(const e of this.decorObjects){if(e.kind==="crop")continue;const i=this.decorGroups.get(e.id);i&&t.push(i)}return t}isSunOccluded(t=0,e=0){return this.isOccludedToward(this.sunWorldPosition,t,e)}isOccludedToward(t,e=0,i=0){const s=this.raycastableDecor();if(!this.groundMesh&&!this.terrainMesh&&s.length===0)return!1;const n=this.sunOcclusionDirectionScratch.copy(t).sub(this.camera.position),a=n.length();if(n.normalize(),e!==0||i!==0){const l=Math.PI/180,h=this.sunOcclusionRightScratch.set(n.z,0,-n.x);h.lengthSq()<1e-9&&h.set(1,0,0),h.normalize();const u=this.sunOcclusionUpScratch.crossVectors(h,n).normalize();n.addScaledVector(h,e*l).addScaledVector(u,i*l).normalize()}if(this.groundBlocks(this.camera.position,n,a)||this.cabinMask.hides(n))return!0;const r=this.cabinMask.any?s.filter(l=>!this.cabinGroups.includes(l)):s;if(r.length===0)return!1;this.sunOcclusionRaycaster.set(this.camera.position,n);const o=this.sunOcclusionRaycaster.intersectObjects(r,!0).find(l=>!(l.object.material instanceof qs));return o!==void 0&&o.distance<a}hideVeilsBehindDecor(){this.cabinMask.update(this.renderer,this.cabinGroups[0],this.camera.position);let t=!1;for(const e of this.glareSprites.values()){if(!e.mesh.visible)continue;t||(this.raycastableDecor().length>0&&this.scene.updateMatrixWorld(),t=!0);const i=e.mesh.getWorldPosition(this.veilTargetScratch),s=e.mesh.material.uniforms.uSourceDeg.value,n=s>.05?ct.VEIL_SAMPLES:ct.VEIL_SAMPLES.slice(0,1);let a=0;for(const[r,o]of n)this.isOccludedToward(i,r*s,o*s)||a++;e.share=a/n.length}}static VEIL_SAMPLES=[[0,0],[1,0],[-1,0],[0,1],[0,-1]];cabinMask=new vn;veilTargetScratch=new _;groundBlocks(t,e,i,s=0){const n=this.groundMesh;if(n&&e.y<0){const m=(n.position.y-t.y)/e.y;if(m>s&&m<i){const v=t.x+e.x*m-n.position.x,M=t.z+e.z*m-n.position.z;if(Math.hypot(v,M)<=this.groundRadius)return!0}}const a=this.terrainMesh;if(!a)return!1;const r=a.geometry.getAttribute("position"),o=Math.round(Math.sqrt(r.count));if(o<2||o*o!==r.count)return!1;const l=[a.position.x+r.getX(0),a.position.x+r.getX(o-1)],h=[a.position.z+r.getZ(0),a.position.z+r.getZ((o-1)*o)],u=Math.min(Math.abs(l[1]-l[0]),Math.abs(h[1]-h[0]))/(o-1);if(!(u>0))return!1;let d=s,f=i;for(const[m,v,M]of[[t.x,e.x,l],[t.z,e.z,h]]){const x=Math.min(M[0],M[1]),y=Math.max(M[0],M[1]);if(Math.abs(v)<1e-12){if(m<x||m>y)return!1;continue}const w=(x-m)/v,S=(y-m)/v;d=Math.max(d,Math.min(w,S)),f=Math.min(f,Math.max(w,S))}if(!(f>d))return!1;const p=Math.hypot(e.x,e.z),g=Math.min(4096,Math.max(8,Math.ceil((f-d)*p/(u/2))));for(let m=0;m<=g;m++){const v=d+(f-d)*m/g,M=t.x+e.x*v,x=t.y+e.y*v,y=t.z+e.z*v;if(x<=this.groundYUnder(M,y))return!0}return!1}setPhenomena(t,e){this.phenomena.set(t,e)}decorDistancesAt(t,e,i){this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e),this.ufoOcclusionRaycaster.near=Hd;let s,n;for(const a of this.decorObjects){if(a.kind==="crop")continue;const r=this.decorGroups.get(a.id);if(!r)continue;const o=this.ufoOcclusionRaycaster.intersectObject(r,!0).find(l=>ct.isSolidSurface(l.object));o&&(a.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(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.origin,s=this.raycaster.ray.direction,n=n6*this.camera.fov*Math.PI/180,a=[...this.hitAreas.entries()].map(([h,u])=>{const d=u.getWorldPosition(new _).sub(i);return{key:h,direction:d.clone().normalize(),radiusRad:Math.atan2(u.scale.x/2,d.length())}}),r=this.eclipseDiscs,o=r?[{key:"sun",direction:r.sun,radiusRad:r.sunRadiusRad},{key:"moon",direction:r.moon,radiusRad:r.moonRadiusRad,inFront:!0}]:[],l=ct.nearestBody(s,[...a.filter(h=>!r||h.key!=="sun"&&h.key!=="moon"),...o],n);if(l)return this.groundHides(t,e)?void 0:l}pickOpticsAt(t,e){if(!this.iceHalos)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.iceHalos.featureAt(this.raycaster.ray.direction);return i&&!this.groundHides(t,e)?i:void 0}static nearestBody(t,e,i){let s,n=1/0,a=1/0,r=!1;for(const o of e){const l=Math.acos(Ca(o.direction.dot(t),-1,1))-o.radiusRad;if(l>i)continue;const h=l<=0,u=n<=0,d=o.inFront===!0;(h!==u?h:h?d!==r?d:o.radiusRad<a:l<n)&&(s=o.key,n=l,a=o.radiusRad,r=d)}return s}pickInterpretationBodyAt(t,e){const i=this.bodySystem.group.children.filter(f=>f.visible&&f.name.startsWith("body:"));if(i.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray.direction,n=this.raycaster.ray.origin,a=t6*this.camera.fov*Math.PI/180,r=[...this.decorGroups.values()],o=r.length>0?ct.firstSolid(this.raycaster.intersectObjects(r,!0))?.distance:void 0;let l,h=1/0;const u=new ze,d=new _;for(const f of i){if(u.setFromObject(f),u.isEmpty())continue;u.getCenter(d);const p=u.getSize(new _).length()/2,g=d.clone().sub(n),m=g.length();if(m===0||g.dot(s)<=0||o!==void 0&&o<m-p)continue;const v=Math.acos(Math.min(1,g.normalize().dot(s))),M=Math.atan(p/m);if(M>a){const x=this.raycaster.intersectObject(f,!0)[0];if(!x||o!==void 0&&o<x.distance)continue}else if(v>a)continue;M<h&&(h=M,l=f.name.slice(5))}return l}pickStarAt(t,e){if(this.namedStars.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const i=this.raycaster.ray.direction,s=Math.cos(Vd*this.camera.fov*Math.PI/180);let n,a=s;for(const r of this.namedStars){const o=r.direction.dot(i);o>a&&(a=o,n={star:r.star,altitudeDeg:r.altitudeDeg})}return n&&this.groundHides(t,e)?void 0:n}groundHides(t,e,i=1/0){if(!this.terrainMesh&&!this.groundMesh)return!1;this.aimAtScreenPoint(this.ufoOcclusionRaycaster,t,e);const s=this.ufoOcclusionRaycaster.ray;return this.groundBlocks(s.origin,s.direction,i,Hd)}bodyScreenBox(t){const e=this.bodySystem.boxOf(t,this.bodyBoxScratch);if(!e)return;let i=1/0,s=1/0,n=-1/0,a=-1/0;for(let r=0;r<8;r++){const o=this.bodyCornerScratch.set(r&1?e.max.x:e.min.x,r&2?e.max.y:e.min.y,r&4?e.max.z:e.min.z),l=this.screenPointOf(o.sub(this.camera.position).normalize());if(!l)return;i=Math.min(i,l.ndcX),n=Math.max(n,l.ndcX),s=Math.min(s,l.ndcY),a=Math.max(a,l.ndcY)}return{minX:i,minY:s,maxX:n,maxY:a}}bodyBoxScratch=new ze;bodyCornerScratch=new _;decorFrameScratch=new Gt;decorPartMatrix=new Gt;decorPartScratch=new ze;pickPlacedBodyAt(t,e){return this.aimAtScreenPoint(this.raycaster,t,e),this.bodySystem.pick(this.raycaster)}decorScreenBox(t){const e=this.decorGroups.get(t);if(!e||!e.visible)return;e.updateWorldMatrix(!0,!0);const i=this.decorFrameScratch.copy(e.matrixWorld).invert(),s=this.bodyBoxScratch.makeEmpty();if(e.traverse(l=>{const h=l.geometry;!h||!l.visible||(h.boundingBox||h.computeBoundingBox(),h.boundingBox&&s.union(this.decorPartScratch.copy(h.boundingBox).applyMatrix4(this.decorPartMatrix.multiplyMatrices(i,l.matrixWorld))))}),s.isEmpty())return;let n=1/0,a=1/0,r=-1/0,o=-1/0;for(let l=0;l<8;l++){const h=this.bodyCornerScratch.set(l&1?s.max.x:s.min.x,l&2?s.max.y:s.min.y,l&4?s.max.z:s.min.z).applyMatrix4(e.matrixWorld),u=this.screenPointOf(h.sub(this.camera.position).normalize());if(!u)return;n=Math.min(n,u.ndcX),r=Math.max(r,u.ndcX),a=Math.min(a,u.ndcY),o=Math.max(o,u.ndcY)}return{minX:n,minY:a,maxX:r,maxY:o}}decorDrawnOffset(t){return this.lampNudges.get(t)}decorGroundPointAt(t,e,i,s=0){const n=this.decorGroups.get(t);if(!n)return;this.aimAtScreenPoint(this.raycaster,e,i);const a=this.raycaster.ray.intersectPlane(this.decorPlaneScratch.setComponents(0,1,0,-(n.position.y+s)),this.decorHitScratch);return a?{x:a.x,z:a.z}:void 0}decorDistanceM(t){const e=this.decorGroups.get(t);return e?Math.hypot(e.position.x-this.camera.position.x,e.position.z-this.camera.position.z):void 0}decorMetresPerNdcY(t){const e=this.decorGroups.get(t);return e?e.position.distanceTo(this.camera.position)*Math.tan(this.camera.fov*Ve/2):0}decorGrabHeightAt(t,e,i){const s=this.decorGroups.get(t);if(!s)return 0;const n=this.bodyBoxScratch.setFromObject(s).max.y-s.position.y;this.aimAtScreenPoint(this.raycaster,e,i);const a=this.decorHitScratch.set(this.camera.position.x-s.position.x,0,this.camera.position.z-s.position.z);if(a.lengthSq()<1e-6)return 0;a.normalize();const r=this.decorPlaneScratch.setFromNormalAndCoplanarPoint(a,s.position),o=this.raycaster.ray.intersectPlane(r,this.decorHitScratch);return o?Math.min(Math.max(o.y-s.position.y,0),Math.max(n,0)):0}decorPlaneScratch=new fa;decorHitScratch=new _;static firstSolid(t){return t.find(e=>{const i=e.object.material;return!(Array.isArray(i)?i:[i]).some(n=>n&&(n.transparent&&n.opacity<ct.SEE_THROUGH_BELOW||n instanceof qs))})}static SEE_THROUGH_BELOW=.9;pickPeakAt(t,e){const i=this.renderer.getDrawingBufferSize(new Q),s=this.camera.fov*Ve/Math.max(1,i.y),n=this.camera.getWorldPosition(new _);let a;for(const r of this.decorObjects){if(r.kind!=="peak")continue;const o=this.decorGroups.get(r.id);if(!o)continue;const l=o.getWorldPosition(new _);l.y=this.reliefYAt(l.x,l.z);const h=l.distanceTo(n),u=this.screenPointOf(l.clone().sub(n).normalize());if(!u)continue;const d=(t-u.ndcX)*i.x/2,f=(u.ndcY-e)*i.y/2,p=Math.max(10,(r.sizeM?.widthM??2e3)/2/Math.max(h,1)/s);if(f<-8||f>p*.6)continue;const g=p*Math.max(.15,f/(p*.6));if(Math.abs(d)>Math.max(10,g))continue;const m=Math.abs(d)+Math.abs(f);(!a||m<a.score)&&(a={id:r.id,score:m})}return a?.id}reliefYAt(t,e){const i=this.terrainMesh;if(i&&Math.hypot(t-i.position.x,e-i.position.z)<=this.terrainRadius)return this.terrainYUnder(t,e);const s=this.farRing?.mesh;return s?s.position.y+this.groundYOfPatch(s,t-s.position.x,e-s.position.z):0}pickDecorAt(t,e){this.aimAtScreenPoint(this.raycaster,t,e);const i=[...this.decorGroups.entries()],s=ct.firstSolid(this.raycaster.intersectObjects(i.map(([,r])=>r),!0));if(!s)return;const n=this.bodySystem.pickHit(this.raycaster);if(n!==void 0&&n.distance<s.distance)return;let a=s.object;for(;a&&!i.some(([,r])=>r===a);)a=a.parent;return i.find(([,r])=>r===a)?.[0]}static RAILWAY_PICK_ABOVE_M=15;pickRailwayAt(t,e){const i=this.railwaySystem;if(!i||i.count===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const s=this.raycaster.ray;i.group.updateMatrixWorld();const n=new pc().copy(s).applyMatrix4(new Gt().copy(i.group.matrixWorld).invert()),a=i.group.matrixWorld,r=(d,f)=>{const p=new _(d,0,f).applyMatrix4(a);return this.groundYUnder(p.x,p.z)-a.elements[13]};if(!i.mayMeet(n.origin,n.direction,r,ct.RAILWAY_PICK_ABOVE_M))return;const o=ct.firstSolid(this.raycaster.intersectObject(i.group,!0));if(!o||this.terrainMesh&&this.groundBlocks(s.origin,s.direction,o.distance-ct.RAILWAY_GROUND_MARGIN_M,Hd))return;const l=i.group.worldToLocal(o.point.clone()),h=i.lineAt(l.x,l.z);if(!h)return;const u=i.contactHeightM(h);return{line:h,distanceM:o.distance,...u!==void 0?{contactM:u}:{}}}pickSkyEventAt(t,e,i=()=>!0){const s=[...this.skyEventLayers.values()].filter(l=>l.simulation?.pick&&l.simulation.drawnCount>0&&i(l.kind,l.simulation));if(s.length===0)return;this.aimAtScreenPoint(this.raycaster,t,e);const n=this.raycaster.ray,a={toleranceRad:ct.BEAM_PICK_PIXELS*this.contrailPixelRad(),nearestCos:Math.cos(Vd*this.camera.fov*Math.PI/180),skyLightTowards:l=>this.skyLightTowards(l)};let r;for(const l of s){const h=l.simulation.pick(n.origin,n.direction,a);h&&(!r||(h.distanceM??1/0)<(r.distanceM??1/0))&&(r={kind:l.kind.key,...h})}if(!r)return;if(r.distanceM===void 0)return this.groundHides(t,e)?void 0:r;if(this.terrainMesh&&this.groundBlocks(n.origin,n.direction,r.distanceM-1,Hd))return;const o=ct.firstSolid(this.raycaster.intersectObjects([...this.decorGroups.values()],!0));if(!(o&&o.distance<r.distanceM))return r}skyLightTowards(t){const e=this.scatteredSky?.ambient;if(!e)return 0;const i=a=>.2126*a[0]+.7152*a[1]+.0722*a[2],s=Math.hypot(t.x,t.y,t.z)||1,n=Math.max(0,Math.min(1,t.y/s));return i(e.horizon)+(i(e.zenith)-i(e.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 t of this.skyEventLayers.values())t.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 t of this.bodyMeshes.values())this.disposeMesh(t);this.bodyMeshes.clear(),this.novaKeys.clear();for(const t of[...this.hitAreas.keys()])this.disposeHitArea(t);for(const t of[...this.glareSprites.keys()])this.disposeGlare(t);this.disposeCompassLabels();for(const t of this.decorGroups.values())ht.dispose(t);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 t=e=>{this.animationFrameId=null,this.frame(e),this.animationFrameId===null&&this.needsAnimationLoop()&&(this.animationFrameId=requestAnimationFrame(t))};this.animationFrameId=requestAnimationFrame(t)}setAnimationsRunning(t,e=!1){const i=t&&e;if(t===this.animationsRunning&&i===this.framesDriven)return;const s=this.animationsRunning;this.animationsRunning=t,this.framesDriven=i,t&&!s&&(this.lastFrameTimeMs=void 0,this.resolution.reset());const n=!t&&this.renderer.getPixelRatio()!==this.resolution.maximum;n&&this.applyPixelRatio(this.resolution.maximum),!t&&this.developingExposure&&this.render(),this.syncAnimationLoop(),(!t||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(t=>t.brightness.length>0)||this.precipitationPoints!==void 0||this.rainSystem!==void 0||this.flareMayShow()}flareAimScratch=new _;flareMayShow(){if(this.lensFlare===void 0||!this.sunVisible)return!1;const t=this.lastAstronomy?.sun;return t!==void 0&&t.altitudeDeg<ct.FLARE_ANIMATION_MIN_ALTITUDE_DEG?!1:(this.camera.getWorldDirection(this.flareAimScratch),this.flareAimScratch.dot(this.lensFlareScratch.copy(this.sunWorldPosition).sub(this.camera.position))>0)}static FLARE_ANIMATION_MIN_ALTITUDE_DEG=-3;syncAnimationLoop(){this.needsAnimationLoop()?this.startTwinkle():this.stopTwinkle()}buildSky(t){const e=this.skyMesh?.geometry??new Ji(Bd,32,16),i=e.attributes.position,s=e.getAttribute("color")??new de(new Float32Array(i.count*3),3);for(let a=0;a<i.count;a++){const{altitudeDeg:r,azimuthDeg:o}=bb(i.getX(a),i.getY(a),i.getZ(a)),l=BI(r,o,t.azimuthDeg,t.altitudeDeg);s.setXYZ(a,l[0],l[1],l[2])}if(s.needsUpdate=!0,this.skyMesh)return;e.setAttribute("color",s);const n=new un({vertexColors:!0,side:Ai,fog:!1,depthWrite:!1});this.skyGradientMaterial=n,this.skyMesh=new dt(e,n),this.skyMesh.renderOrder=-1,this.celestialGroup.add(this.skyMesh)}buildGround(){const t=S2(this.observerElevationM);if(this.groundMesh&&t===this.groundRadius)return;this.disposeMesh(this.groundMesh),this.groundRadius=t;const e=new O1(this.groundRadius,48),i=new sa({color:new at(Yp,Yp,Yp),fog:!0});vo.fadeRim(i,this.groundRadius*.75,this.groundRadius),this.groundMesh=new dt(e,i),this.groundMesh.rotation.x=-Math.PI/2,this.groundMesh.position.y=0,this.groundMesh.receiveShadow=!0,this.scene.add(this.groundMesh),this.applyGroundDepthWrite()}applyGroundDepthWrite(){const t=this.groundMesh?.material;if(!t)return;const e=this.terrainMesh===void 0;t.depthWrite!==e&&(t.depthWrite=e,t.needsUpdate=!0);const i=this.terrainMesh;let s=0;if(i){const a=i.geometry.getAttribute("position");s=1/0;for(let r=0;r<a.count;r++)Math.abs(a.getX(r)+i.position.x)>600||Math.abs(a.getZ(r)+i.position.z)>600||(s=Math.min(s,a.getY(r)+i.position.y));s=Number.isFinite(s)?Math.min(0,s)-1:0}const n=this.farRing?.mesh;if(n){const a=n.geometry.getAttribute("position");let r=1/0;for(let o=0;o<a.count;o++)Math.hypot(a.getX(o)+n.position.x,a.getZ(o)+n.position.z)>this.groundRadius||(r=Math.min(r,a.getY(o)+n.position.y));Number.isFinite(r)&&(s=Math.min(s,r-1))}this.groundMesh.position.y=s,this.groundMesh.renderOrder=0,t.depthTest=!0,t.needsUpdate=!0}cloudTransmission(t,e=!1){const i=`${t.altitudeDeg.toFixed(1)}:${t.azimuthDeg.toFixed(1)}:${Math.round(this.cloudOffsetM.x/10)}:${Math.round(this.cloudOffsetM.z/10)}:${Math.round(this.observerElevationM)}:`+Object.entries(this.cloudLayerOffsetsM).map(([a,r])=>`${a}=${Math.round(r.x/10)},${Math.round(r.z/10)}`).join(";")+(e?":water":""),s=this.cloudTransmissionMemo.get(i);if(s!==void 0)return s;this.cloudTransmissionMemo.size>256&&this.cloudTransmissionMemo.clear();const n=this.computeCloudTransmission(t,e);return this.cloudTransmissionMemo.set(i,n),n}cloudTransmissionMemo=new Map;computeCloudTransmission(t,e=!1){const i=mi(t.altitudeDeg,t.azimuthDeg,1);if(this.layeredClouds)return this.layeredClouds.transmissionAt(i,e);let s=1;const n=this.lowerCloudCover();n>0&&(s*=1-Ce.alphaAt(i,Math.abs(this.cloudLayerOffset()),n,this.cloudFieldOffset)*o6);const a=e?0:this.weather.highCloudCover??0;return a>0&&(s*=1-Ce.iceAlphaAt(i,Xd,a,this.cloudFieldOffset)*c6),Math.max(0,Math.min(1,s))}setBodyMesh(t,e,i,s,n){if(e.altitudeDeg<ff){this.disposeMesh(this.bodyMeshes.get(t)),this.bodyMeshes.delete(t),this.disposeHitArea(t),this.disposeGlare(t),t==="sun"&&(this.sunVisible=!1,qs.setDisc("sun",void 0));return}const{x:a,y:r,z:o}=mi(e.altitudeDeg,e.azimuthDeg,Ii),l=this.cloudTransmission(e),h=this.arrivingIlluminance(e,n,l),u=ct.unitLuminance(s);let d=this.bodyMeshes.get(t);if(t==="sun"){const f=Math.PI*(i/Ii)**2,p=[0,1,2].map(m=>u[m]*h[m]/(this.sunBeamFraction*f));this.sunDiscRadiance=p;const g=p.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m));d instanceof dt||(this.disposeMesh(d),d=new dt(new Ji(1,16,16),this.eclipsedSun.material()),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)),d.material.color.setRGB(g[0],g[1],g[2]),d.scale.setScalar(i),qs.setDisc("sun",{direction:[a/Ii,r/Ii,o/Ii],radiusRad:Math.atan(i/Ii),radiance:g})}else{if(!(d instanceof Cn)){this.disposeMesh(d);const g=new ye;g.setAttribute("position",new ve(new Float32Array(3),3)),g.setAttribute("color",new ve(new Float32Array(3),3)),d=new Cn(g,Vt.material(Ul[Ul.length-1].size,!1)),Vt.track(d),this.celestialGroup.add(d),this.bodyMeshes.set(t,d)}const f=d.geometry.getAttribute("color"),p=t.startsWith("comet:")?this.pointToPixel():1;f.setXYZ(0,u[0]*h[0]*p,u[1]*h[1]*p,u[2]*h[2]*p),f.needsUpdate=!0}if(d.position.set(a,r,o),this.setHitArea(t,a,r,o,i),t==="sun"&&(this.sunArriving=h),t.startsWith("comet:")?this.disposeGlare(t):t!=="sun"&&this.setGlare(t,a,r,o,h,i/Ii*(180/Math.PI),ct.POINT_VEIL_HOLD_DEG),t==="sun"){this.sunVisible=!0;const f=this.celestialGroup.scale.x;this.sunWorldPosition.set(a*f,r*f+this.celestialGroup.position.y,o*f),this.lensFlare||(this.lensFlare=MP(),this.lensFlare.uniforms.uStarPoints.value=this.starPoints,this.scene.add(this.lensFlare.mesh)),this.applyDazzleStrength()}}setMoonMesh(t,e){const i="moon";if(t.magnitude>e||t.altitudeDeg<ff){this.disposeMesh(this.bodyMeshes.get(i)),this.bodyMeshes.delete(i),this.disposeHitArea(i),this.disposeGlare(i),qs.setDisc("moon",void 0);return}const{x:s,y:n,z:a}=mi(t.altitudeDeg,t.azimuthDeg,Ii),r=this.cloudTransmission(t),o=this.arrivingIlluminance(t,t.magnitude,r),l=t.radiusDeg??Wa.MEAN_RADIUS_DEG,h=Ii*Math.tan(l*Ve),u=Math.max(Ca(t.phase.illuminatedFraction,0,1),.01)*Math.PI*(h/Ii)**2,d=new at(...o.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m/u))),f=Math.PI*(h/Ii)**2;qs.setDisc("moon",{direction:[s/Ii,n/Ii,a/Ii],radiusRad:l*Ve,radiance:o.map(m=>Math.min(ct.BRIGHTEST_RELATIVE,m/f))});const p=`${t.phase.phaseFraction<.5}:${Math.round(Ca(t.phase.illuminatedFraction,0,1)*500)}`;let g=this.bodyMeshes.get(i);g instanceof el?(g.userData.phaseKey!==p&&(g.material.map?.dispose(),g.material.map=Z2(t.phase),g.userData.phaseKey=p),g.material.color.copy(d)):(this.disposeMesh(g),g=new el(new Xh({map:Z2(t.phase),color:d,fog:!1,blending:gs,depthWrite:!1})),g.userData.phaseKey=p,this.celestialGroup.add(g),this.bodyMeshes.set(i,g)),g.scale.set(h*2,h*2,1),g.position.set(s,n,a),this.setHitArea(i,s,n,a,h),this.setGlare(i,s,n,a,o,l)}bentLight(t,e,i=a6){const[s,n,a]=this.arrivingIlluminance(t,e,1),r=Math.max(n,1e-30);return{scale:n/i,tint:[s/r,1,a/r]}}static litBySky(t,e){return ct.litScratch.setRGB(t.r*e[0],t.g*e[1],t.b*e[2])}static litScratch=new at;pointToPixel(){const t=Math.max(1,this.renderer.getDrawingBufferSize(this.pointScratch).y),e=(this.camera.fov*Math.PI/180/t)**2;return Math.min(1,Vt.CONE_SOLID_ANGLE/e)}pointScratch=new Q;static POINT_VEIL_HOLD_DEG=.25;static BRIGHTEST_RELATIVE=6e4;arrivingIlluminance(t,e,i){const s=this.air.transmittanceFromSpace(this.siteElevationM+this.observerElevationM,t.altitudeDeg),n=Ne.illuminanceOf(e)*i*this.relativeScale;return[s[0]*n,s[1]*n,s[2]*n]}static unitLuminance(t){const e=En.luminanceOf([t.r,t.g,t.b]);return e>0?[t.r/e,t.g/e,t.b/e]:[1,1,1]}setHitArea(t,e,i,s,n){let a=this.hitAreas.get(t);if(!a){const o=new Xh({transparent:!0,opacity:0,depthTest:!1,depthWrite:!1,fog:!1});a=new el(o),this.celestialGroup.add(a),this.hitAreas.set(t,a)}a.position.set(e,i,s);const r=n*2;a.scale.set(r,r,1)}disposeHitArea(t){const e=this.hitAreas.get(t);e&&(e.removeFromParent(),e.material.dispose(),this.hitAreas.delete(t))}setGlare(t,e,i,s,n,a,r=0){if(hs.radiusDeg(hs.K*Math.max(...n))<=Math.max(a,r)){this.disposeGlare(t);return}let o=this.glareSprites.get(t);o||(o=new hs(`veil:${t}`),this.celestialGroup.add(o.mesh),this.glareSprites.set(t,o)),o.shine({x:e,y:i,z:s},n,a,r)}disposeGlare(t){const e=this.glareSprites.get(t);e&&(e.mesh.removeFromParent(),e.dispose(),this.glareSprites.delete(t))}buildComet(t,e){const i=t&&`comet:${t.id}`;if(!t||!i||t.magnitude>e){this.disposeComet();return}this.cometKey&&this.cometKey!==i&&this.disposeComet();const s=vl(t.magnitude,e),n=Sp(s);this.cometKey=i,this.setBodyMesh(i,t.position,Jp*(.5+.5*s),new at(n,n,n),t.magnitude),this.cometTail||(this.cometTail=new Pn(Ii),this.celestialGroup.add(this.cometTail.object)),this.cometTail.set(t.position,t.tailEnd,s)}buildIceHalos(t,e){this.iceHalos||(this.iceHalos=new Ui,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:Xd},0);return}const n=this.lowerCloudCover(),a=we.deckLitUntilDeg(we.DECK_HEIGHT_M),r=t.altitudeDeg>-a?t:e,o=this.bentLight(r,r===t?ue.SUN_MAGNITUDE:e.magnitude),l=we.strength(i,n,r.altitudeDeg,a)*o.scale,{x:h,y:u,z:d}=mi(r.altitudeDeg,r.azimuthDeg,1);this.iceHalos.update({x:h,y:u,z:d},r.altitudeDeg,l,o.tint,{cover:s?.cover??i,layerHeight:s?.layerHeight??Xd},s?.iceCrystalAlignment??this.weather.iceCrystalAlignment??cS,this.weather.rareIceCrystals)}buildRainbow(t,e){this.rainbow||(this.rainbow=new qo,this.celestialGroup.add(this.rainbow.object));const i=this.weather.precipitationType==="rain"?this.weather.precipitationIntensity*(this.weather.precipitationAmount??1):0,s=t.altitudeDeg>0,n=s?t:e,a=this.lowerCloudCover(),r=this.bentLight(n,s?ue.SUN_MAGNITUDE:e.magnitude,r6),o=In.strength(i,a,n.altitudeDeg)*r.scale;if(o<=0){this.rainbow.update({x:0,y:1,z:0},0,[1,1,1],!0);return}const{x:l,y:h,z:u}=mi(n.altitudeDeg,n.azimuthDeg,1);this.rainbow.update({x:l,y:h,z:u},o,r.tint,s)}buildSkyGlow(t,e){if(!t.frame){this.skyGlow?.hide();return}this.skyGlow||(this.skyGlow=new eo,this.skyGlow.setWithheld(!!this.skyHoldUntilMs),this.skyGlow.onReady=()=>this.render(),this.celestialGroup.add(this.skyGlow.object));const{date:i,observer:s}=t.frame,n=ua.galactic(i,s),a=ct.directionOf(n.centre),r=ct.directionOf(n.rotation),o=ct.directionOf(n.pole),l=new he().set(a.x,a.y,a.z,r.x,r.y,r.z,o.x,o.y,o.z),h=ct.directionOf(ua.eclipticPole(i,s)),u=ct.directionOf(t.sun),d=u.clone().addScaledVector(h,-u.dot(h)).normalize();this.skyGlow.update({galactic:l,eclipticPole:h,sunLongitude:d,sunDirection:u,sunAltitudeDeg:t.sun.altitudeDeg,moon:{direction:ct.directionOf(t.moon),altitudeDeg:t.moon.altitudeDeg,phaseAngleDeg:Et.phaseAngleOf(t.moon.phase.illuminatedFraction)},lightPollution:this.lightPollution,skyColor:new _(e[0],e[1],e[2])})}static directionOf(t){const{x:e,y:i,z:s}=mi(t.altitudeDeg,t.azimuthDeg,1);return new _(e,i,s).normalize()}buildNovae(t,e){const i=new Set;for(const s of t){if(s.magnitude>e)continue;const n=`nova:${s.id}`;i.add(n);const a=vl(s.magnitude,e),r=Sp(a);this.setBodyMesh(n,s.position,Jp*(.5+.5*a),new at(r,r,r),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(t,e){const i=new Set(["sun","moon",...this.cometKey?[this.cometKey]:[],...this.novaKeys]);for(const s of t){if(s.magnitude>e)continue;i.add(s.body);const n=vl(s.magnitude,e),a=Sp(n),r=B6[s.body]??new at(1,1,1),o=new at(r.r*a,r.g*a,r.b*a),l=Jp*(.5+.5*n);this.setBodyMesh(s.body,s.position,l,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(t,e){if(this.namedStars=[],!t||t.catalog.count===0){this.disposeStarTiers(),this.syncAnimationLoop();return}const{catalog:i,date:s,observer:n}=t,a=new da(s,n),r=om(1337),o=[],l=this.siteElevationM+this.observerElevationM;for(let h=0;h<i.count;h++){const u=i.mag[h];if(u>e)break;const{altitudeDeg:d,azimuthDeg:f}=a.position(i.ra[h],i.dec[h]);if(d<A2)continue;const{x:p,y:g,z:m}=mi(d,f,$p);o.push({x:p,y:g,z:m,brightness:vl(u,e),illuminance:this.air.transmittanceFromSpace(l,d).map(v=>v*Ne.illuminanceOf(u)),phase:r()*Math.PI*2,speedFactor:.7+r()*.6})}for(const h of WI){if(h.mag>e)continue;const{altitudeDeg:u,azimuthDeg:d}=a.position(h.raHours,h.decDeg);if(u<A2)continue;const{x:f,y:p,z:g}=mi(u,d,$p);this.namedStars.push({star:h,direction:new _(f,p,g).normalize(),altitudeDeg:u})}this.starTiers=Ul.map((h,u)=>{const d=o.filter(w=>W1(w.brightness)===u),f=new Float32Array(d.length*3),p=new Float32Array(d.length),g=new Float32Array(d.length*3),m=new Float32Array(d.length),v=new Float32Array(d.length);d.forEach((w,S)=>{f[S*3]=w.x,f[S*3+1]=w.y,f[S*3+2]=w.z,p[S]=w.brightness,g.set(w.illuminance,S*3),m[S]=w.phase,v[S]=w.speedFactor});const M=new ye;M.setAttribute("position",new ve(f,3)),M.setAttribute("seed",new ve(m.map(w=>w/(2*Math.PI)),1));const x=new ve(new Float32Array(d.length*3),3);M.setAttribute("color",x);let y=this.starTiers[u]?.points;return y?(y.geometry.dispose(),y.geometry=M):(y=new Cn(M,Vt.material(h.size)),Vt.track(y),this.celestialGroup.add(y)),{points:y,colorAttribute:x,brightness:p,illuminance:g,phase:m,speedFactor:v}}),this.starColoursRelative=Number.NaN,this.updateTwinkle(this.twinkleSeconds),this.startTwinkle()}twinkleSeconds=0;starColoursRelative=Number.NaN;updateTwinkle(t){Vt.setTime(t);const e=this.relativeScale;if(e!==this.starColoursRelative){this.starColoursRelative=e;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]*e,s[n*3+1]=i.illuminance[n*3+1]*e,s[n*3+2]=i.illuminance[n*3+2]*e;i.colorAttribute.needsUpdate=!0}}}buildClouds(){if(this.cloudRendering==="volume"||this.weather.cloudLayers!==void 0){this.layeredClouds||(this.disposeCloudSystem(),this.layeredClouds=new Fl(this.celestialGroup,jp,this.cloudRendering)),this.disposeCirrus(),this.layeredClouds.hostHalo(this.iceHalos),this.layeredClouds.update(this.weather,this.observerElevationM+1.6),this.layeredClouds.setOffsets(this.cloudOffsetM,this.cloudLayerOffsetsM),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const t=this.lowerCloudCover();if(t<=0){this.disposeCloudSystem();return}const e=this.weather.cloudDarkness,i=new at(Lo[0]+(em[0]-Lo[0])*e,Lo[1]+(em[1]-Lo[1])*e,Lo[2]+(em[2]-Lo[2])*e);if(this.cloudMesh&&this.cloudUniforms){this.cloudUniforms.coverage.value=t,this.cloudUniforms.baseColor.value.copy(i),this.syncCloudLayer(),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}this.disposeCloudSystem();const{material:s,uniforms:n}=Og(i,t,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 a=Lg(jp);this.cloudMesh=new dt(a,s),this.faceCloudDeck(this.cloudMesh,this.cloudLayerOffset()),this.celestialGroup.add(this.cloudMesh)}lowerCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type!=="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.lowerCloudCover??this.weather.cloudCover}highCloudCover(){return this.weather.cloudLayers?1-this.weather.cloudLayers.filter(t=>t.type==="cirrus").reduce((t,e)=>t*(1-e.coverage),1):this.weather.highCloudCover}buildCirrus(){const t=this.weather.highCloudCover??0;if(this.layeredClouds||t<=0){this.disposeCirrus();return}if(this.cirrusMesh&&this.cirrusUniforms){this.cirrusUniforms.coverage.value=t,this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor);return}const{material:e,uniforms:i}=Og(new at(...Lo),t,Xd,1);this.cirrusMaterial=e,this.cirrusUniforms=i,i.fieldOffset.value.copy(this.cloudFieldOffset),this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.cirrusMesh=new dt(Lg(jp*1.04),e),this.cirrusMesh.renderOrder=L2-1,this.celestialGroup.add(this.cirrusMesh)}disposeCirrus(){this.cirrusMesh&&(this.cirrusMesh.removeFromParent(),this.cirrusMesh.geometry.dispose()),this.cirrusMaterial?.dispose(),this.cirrusMesh=void 0,this.cirrusMaterial=void 0,this.cirrusUniforms=void 0}syncCloudLayer(){this.layeredClouds?.update(this.weather,this.observerElevationM+1.6);const t=this.cloudLayerOffset();this.cloudUniforms&&(this.cloudUniforms.layerHeight.value=Math.abs(t)),this.cloudMesh&&this.faceCloudDeck(this.cloudMesh,t)}faceCloudDeck(t,e){const i=e<0;t.scale.y=i?-1:1,t.renderOrder=i?Fl.deckOrder(!0,0,1):L2}cloudLayerOffset(){const e=((this.weather.cloudBaseM??Mx)-this.observerElevationM)*Qp;return Math.sign(e||1)*Math.max(Math.abs(e),b6)}updateCloudLighting(t,e){const i=[this.cloudUniforms,this.cirrusUniforms].filter(u=>u!==void 0);if(i.length===0&&!this.layeredClouds)return;const s=this.cloudBeamDirection,[n,a,r]=this.cloudBeam.map(u=>u/Math.PI),o=this.lightningLevel*rm*this.relativeScale/Math.PI,l=new at(e[0]+Ta.r*o,e[1]+Ta.g*o,e[2]+Ta.b*o);this.layeredClouds?.setLighting(s.clone(),new at(n,a,r),l,l);const h=Math.max(0,s.y);for(const u of i)u.sunDir.value.copy(s),u.sunColor.value.setRGB(n*h,a*h,r*h),u.ambientColor.value.copy(l)}disposeCloudSystem(){this.layeredClouds?.dispose(),this.layeredClouds=void 0,this.cloudMesh&&(this.cloudMesh.removeFromParent(),this.cloudMesh.geometry.dispose()),this.cloudMaterial?.dispose(),this.cloudMesh=void 0,this.cloudMaterial=void 0,this.cloudUniforms=void 0}disposePrecipitationPoints(){this.precipitationPoints&&(this.precipitationPoints.removeFromParent(),this.precipitationPoints.geometry.dispose(),this.precipitationPoints.material.dispose()),this.precipitationPoints=void 0,this.precipitationPositions=void 0,this.precipitationPhase=void 0,this.precipitationSpeedJitter=void 0,this.precipitationWobbleFreqJitter=void 0,this.precipitationWobbleAmpJitter=void 0,this.precipitationBounceRemaining=void 0,this.precipitationBounceHeight=void 0,this.precipitationBounceDuration=void 0,this.precipitationBounceVelX=void 0,this.precipitationBounceVelZ=void 0,this.precipitationUniforms=void 0}precipitationCount(t){return I6(t,this.weather.precipitationIntensity,this.weather.precipitationAmount??1)}updatePrecipitationDensity(){const t=[[this.rainSystem?.points,nm],[this.rainSplashSystem?.points,No],[this.precipitationPoints,this.weather.precipitationType==="none"||this.weather.precipitationType==="rain"?void 0:im[this.weather.precipitationType].poolSize]];for(const[e,i]of t)e&&i!==void 0&&e.geometry.setDrawRange(0,this.precipitationCount(i));this.rainSystem&&(this.rainSystem.uniforms.uSpeedStreak.value=U2(am(this.weather.precipitationIntensity)))}buildPrecipitation(){this.disposePrecipitationPoints(),this.disposeRain();const t=this.weather.precipitationType;if(t==="none")return;if(t==="rain"){this.buildRain();return}const e=im[t],i=e.poolSize,s=om(9001),n=new Float32Array(i*3),a=new Float32Array(i),r=new Float32Array(i),o=new Float32Array(i),l=new Float32Array(i),h=new Float32Array(i),u=new Float32Array(i),d=new Float32Array(i),f=new Float32Array(i),p=new Float32Array(i);for(let x=0;x<i;x++){const y=s()*Math.PI*2,w=s()*e.radiusM;n[x*3]=Math.cos(y)*w,n[x*3+1]=nl+s()*(e.topYM-nl),n[x*3+2]=Math.sin(y)*w,a[x]=s()*Math.PI*2,r[x]=.7+s()*.6,o[x]=.6+s()*.8,l[x]=.4+s()*1.2}const g=new ye;g.setAttribute("position",new ve(n,3)),g.setDrawRange(0,this.precipitationCount(i));const m={uSize:{value:e.size},uScale:{value:.5*this.renderer.domElement.height},uOpacity:{value:e.opacity},uColor:{value:e.color.clone()},uHazeColor:{value:new at(...this.baseFogColor)},uTexture:{value:H6(t)},uNearFocusDistance:{value:G2},uHazeDistance:{value:e.radiusM*V2}},v=new _e({uniforms:m,vertexShader:Y6,fragmentShader:$6,transparent:!0,depthWrite:!1});this.precipitationUniforms=m;const M=new Cn(g,v);M.renderOrder=tm,this.scene.add(M),this.precipitationPoints=M,this.precipitationPositions=n,this.precipitationPhase=a,this.precipitationSpeedJitter=r,this.precipitationWobbleFreqJitter=o,this.precipitationWobbleAmpJitter=l,this.precipitationBounceRemaining=h,this.precipitationBounceHeight=u,this.precipitationBounceDuration=d,this.precipitationBounceVelX=f,this.precipitationBounceVelZ=p}updatePrecipitation(t,e){if(!this.precipitationPoints||!this.precipitationPositions||!this.precipitationPhase||!this.precipitationSpeedJitter)return;this.precipitationUniforms?.uHazeColor.value.setRGB(...this.baseFogColor);const i=this.weather.precipitationType;if(i==="none"||i==="rain")return;const s=im[i];if(this.precipitationUniforms?.uColor.value.copy(ct.litBySky(s.color,this.baseFogColor)),e<=0)return;const n=this.weather.windDirectionDeg*Ve,a=Math.sin(n)*this.weather.windSpeed*s.driftSensitivity,r=-Math.cos(n)*this.weather.windSpeed*s.driftSensitivity,o=this.precipitationPositions,l=this.precipitationPhase,h=this.precipitationSpeedJitter,u=this.precipitationWobbleFreqJitter,d=this.precipitationWobbleAmpJitter,f=this.precipitationBounceRemaining,p=this.precipitationBounceHeight,g=this.precipitationBounceDuration,m=this.precipitationBounceVelX,v=this.precipitationBounceVelZ,M=i==="snow"&&u&&d,x=i==="hail"&&f&&p&&g&&m&&v;for(let y=0,w=0;y<o.length;y+=3,w++){if(x&&f[w]>0){if(f[w]-=e,f[w]<=0){const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(b)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(b)*A,f[w]=0}else{const b=1-f[w]/g[w];o[y+1]=nl+Math.sin(Math.PI*b)*p[w],o[y]=Yd(o[y]+(a+m[w])*e,s.radiusM),o[y+2]=Yd(o[y+2]+(r+v[w])*e,s.radiusM)}continue}let S=0,E=0;if(M){const b=C6*u[w],A=O6*d[w];S=Math.sin(t*b*Math.PI*2+l[w])*A,E=Math.sin(t*b*Math.PI*2+l[w]+Math.PI/2)*A}if(o[y]+=(a+S)*e,o[y+1]-=s.fallSpeedMPerS*h[w]*e,o[y+2]+=(r+E)*e,o[y]=Yd(o[y],s.radiusM),o[y+2]=Yd(o[y+2],s.radiusM),o[y+1]<nl){if(x){p[w]=$2*(.2+Math.random()*1.6),g[w]=L6*(.5+Math.random()),f[w]=g[w];const T=Math.random()*Math.PI*2,D=N6*(p[w]/$2);m[w]=Math.cos(T)*D,v[w]=Math.sin(T)*D,o[y+1]=nl;continue}const b=Math.random()*Math.PI*2,A=Math.sqrt(Math.random())*s.radiusM;o[y]=Math.cos(b)*A,o[y+1]=s.topYM,o[y+2]=Math.sin(b)*A}}this.precipitationPoints.geometry.attributes.position.needsUpdate=!0}buildRain(){const t=am(this.weather.precipitationIntensity);this.rainSystem=mP({count:nm,radiusM:Ih,heightM:E6,bottomYM:N2,overallSpeed:A6,color:F2.clone(),opacity:.85,visibleCount:this.precipitationCount(nm),speedStreak:U2(t),pixelSize:X2,seed:9001,nearFocusDistanceM:G2,hazeDistanceM:Ih*V2,hazeColor:new at(...this.baseFogColor)}),this.rainLastVerticalFacing=-1,this.syncRainSlant(),this.rainSystem.points.renderOrder=tm,this.scene.add(this.rainSystem.points),this.buildRainSplashes()}buildRainSplashes(){const t=om(4242),e=new Float32Array(No*3),i=new Float32Array(No),s=new Float32Array(No),n=new Float32Array(No);for(let h=0;h<No;h++){const u=t()*Math.PI*2,d=Math.sqrt(t())*Ih;e[h*3]=Math.cos(u)*d,e[h*3+1]=N2,e[h*3+2]=Math.sin(u)*d,s[h]=q2(z2,B2),i[h]=t()*s[h],n[h]=i[h]/s[h]}const a=new ye;a.setAttribute("position",new ve(e,3));const r=new ve(n,1);a.setAttribute("aLife",r),a.setDrawRange(0,this.precipitationCount(No));const o=new _e({uniforms:{uMaxSize:{value:D6},uScale:{value:.5*this.renderer.domElement.height},uColor:{value:H2.clone()},uTexture:{value:W6()}},vertexShader:X6,fragmentShader:K6,transparent:!0,depthWrite:!1}),l=new Cn(a,o);l.renderOrder=tm,this.scene.add(l),this.rainSplashSystem={points:l,positions:e,life:i,duration:s,lifeAttribute:r}}disposeRain(){this.rainSystem&&(this.rainSystem.points.removeFromParent(),this.rainSystem.points.geometry.dispose(),this.rainSystem.points.material.dispose()),this.rainSystem=void 0,this.disposeRainSplashes()}disposeRainSplashes(){this.rainSplashSystem&&(this.rainSplashSystem.points.removeFromParent(),this.rainSplashSystem.points.geometry.dispose(),this.rainSplashSystem.points.material.dispose()),this.rainSplashSystem=void 0}syncRainSlant(){const t=this.rainSystem;if(!t)return;const e=this.weather.windDirectionDeg*Ve;t.uniforms.uDropVelocity.value.set(Math.sin(e)*this.weather.windSpeed,-am(this.weather.precipitationIntensity),-Math.cos(e)*this.weather.windSpeed);const i=this.renderer.getSize(this.rainViewportSize);t.uniforms.uAspect.value=i.x/Math.max(i.y,1)}updateRain(t){const e=this.rainSystem;if(!e)return;e.uniforms.uTime.value+=t,e.uniforms.uHazeColor.value.setRGB(...this.baseFogColor),e.uniforms.uColor.value.copy(ct.litBySky(F2,this.baseFogColor));const i=this.rainSplashSystem?.points.material?.uniforms?.uColor;i&&i.value.copy(ct.litBySky(H2,this.baseFogColor));const s=this.weather.windDirectionDeg*Ve,n=Math.sin(s)*this.weather.windSpeed,a=-Math.cos(s)*this.weather.windSpeed,r=Ih,o=h=>(h%(r*2)+r*3)%(r*2)-r;e.uniforms.uWindOffset.value.set(o(e.uniforms.uWindOffset.value.x+n*t),o(e.uniforms.uWindOffset.value.y+a*t)),this.syncRainSlant(),this.camera.getWorldDirection(this.rainCameraDirection);const l=Math.abs(this.rainCameraDirection.y);if(Math.abs(l-this.rainLastVerticalFacing)>.001){this.rainLastVerticalFacing=l;const h=K2+(1-K2)*(1-l),u=Y2+(1-Y2)*(1-l);e.uniforms.uUvSquash.value=u,e.uniforms.uPixelSize.value=X2*h*(.5+.5*u)}this.updateRainSplashes(t)}updateRainSplashes(t){const e=this.rainSplashSystem;if(!e||t<=0)return;const{positions:i,life:s,duration:n,lifeAttribute:a}=e,r=a.array;for(let o=0,l=0;o<i.length;o+=3,l++){if(s[l]+=t,s[l]>=n[l]){const h=Math.random()*Math.PI*2,u=Math.sqrt(Math.random())*Ih;i[o]=Math.cos(h)*u,i[o+2]=Math.sin(h)*u,n[l]=q2(z2,B2),s[l]=0}r[l]=s[l]/n[l]}e.points.geometry.attributes.position.needsUpdate=!0,a.needsUpdate=!0}setLightning(t){this.lightningFlashes=t}updateLightning(t){let e,i=0;if(this.lightningArmed)for(const o of this.lightningFlashes){if(o.t>t)break;const l=is.brightnessAt(o,t);l>i&&(e=o,i=l)}const s=e?Math.min(1,Math.max(.1,(U6/e.distanceM)**2)):0,n=i*s*(e?.cloudToGround?1:.6);if(n===this.lightningLevel&&!e?.cloudToGround)return;if(this.lightningLevel=n,this.scene.fog){const o=this.scene.fog,l=n*rm*this.relativeScale/Math.PI;o.color.setRGB(this.airlight[0]+Ta.r*l,this.airlight[1]+Ta.g*l,this.airlight[2]+Ta.b*l)}const a=this.skyMesh?.material?.color;if(a){const o=n*z6;a.setRGB(1+o*Ta.r,1+o*Ta.g,1+o*Ta.b)}if(this.lastSunPosition&&this.updateCloudLighting(this.lastSunPosition,this.baseFogColor),this.lightningLight.intensity=n*rm*this.relativeScale,e){const{x:o,y:l,z:h}=mi(25,e.azimuthDeg,Ii);this.lightningLight.position.set(o,l,h)}this.lightningBolt||(this.lightningBolt=new io(Ii*.95),this.celestialGroup.add(this.lightningBolt.object));const r=this.weather.cloudBaseM??1500;this.lightningBolt.set(e,i,r),this.render()}buildCompassLabels(){this.compassSprites=v6.map(t=>{const e=sc.point(t,this.compassPoints),i=new Xh({map:q6(e),depthTest:!1,fog:!1}),s=new el(i),{x:n,y:a,z:r}=mi(0,t,D2);return s.position.set(n,a,r),s.scale.set(Kd,Kd,1),s.renderOrder=x6,s.layers.set(Kp),s.visible=this.compassForced,this.celestialGroup.add(s),s}),this.updateCompassScale()}updateCompassScale(){const t=this.camera.fov*Math.PI/360,e=I2*Math.PI/360,i=Kd*Math.tan(t)/Math.tan(e);for(const s of this.compassSprites)s.scale.set(i,i,1)}disposeCompassLabels(){for(const t of this.compassSprites)t.removeFromParent(),t.material.map?.dispose(),t.material.dispose();this.compassSprites=[]}disposeStarTiers(){for(const t of this.starTiers)this.disposeMesh(t.points);this.starTiers=[]}disposeMesh(t){if(!t)return;t.removeFromParent(),"geometry"in t&&t.geometry.dispose();const e=t.material;for(const i of Array.isArray(e)?e:[e]){const s=i.map;s&&s.dispose(),i.dispose()}}}const Ve=Math.PI/180;function Ca(c,t,e){return Math.max(t,Math.min(e,c))}function q2(c,t){return c+Math.random()*(t-c)}function Yd(c,t){return(c%(t*2)+t*3)%(t*2)-t}let $d,qd;function H6(c){switch(c){case"snow":return G6();case"hail":return V6()}}function G6(){if($d)return $d;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,0.95)"),i.addColorStop(.5,"rgba(255,255,255,0.55)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),$d=new So(t),$d}function V6(){if(qd)return qd;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.55,"rgba(255,255,255,0.95)"),i.addColorStop(.8,"rgba(255,255,255,0.4)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),qd=new So(t),qd}let Zd;function W6(){if(Zd)return Zd;const c=64,t=document.createElement("canvas");t.width=c,t.height=c;const e=t.getContext("2d"),i=e.createRadialGradient(c/2,c/2,0,c/2,c/2,c/2);return i.addColorStop(0,"rgba(255,255,255,0)"),i.addColorStop(.4,"rgba(255,255,255,0)"),i.addColorStop(.6,"rgba(255,255,255,0.9)"),i.addColorStop(.8,"rgba(255,255,255,0.25)"),i.addColorStop(1,"rgba(255,255,255,0)"),e.fillStyle=i,e.fillRect(0,0,c,c),Zd=new So(t),Zd}const X6=`
|
|
8927
8927
|
uniform float uMaxSize;
|
|
8928
8928
|
uniform float uScale;
|
|
8929
8929
|
attribute float aLife;
|
|
@@ -8989,7 +8989,7 @@ void main() {
|
|
|
8989
8989
|
gl_FragColor = vec4(color, tex.a * uOpacity * (1.0 - blur * 0.5));
|
|
8990
8990
|
}
|
|
8991
8991
|
`;function Z2(c){const e=document.createElement("canvas");e.width=128,e.height=128;const i=e.getContext("2d"),s=128/2-2,n=128/2,a=128/2,r="#010101",o="#f4f1e2";i.fillStyle=r,i.beginPath(),i.arc(n,a,s,0,Math.PI*2),i.fill();const l=Ca(c.illuminatedFraction,0,1),h=c.phaseFraction<.5,u=s*Math.abs(1-2*l),d=l<.5;return i.save(),i.beginPath(),i.arc(n,a,s,0,Math.PI*2),i.clip(),i.fillStyle=o,i.beginPath(),h?(i.arc(n,a,s,-Math.PI/2,Math.PI/2,!1),i.ellipse(n,a,u,s,0,Math.PI/2,-Math.PI/2,d)):(i.arc(n,a,s,Math.PI/2,-Math.PI/2,!1),i.ellipse(n,a,u,s,0,-Math.PI/2,Math.PI/2,d)),i.fill(),i.restore(),new So(e)}function q6(c){const t=document.createElement("canvas");t.width=128,t.height=128;const e=t.getContext("2d");return e.fillStyle="rgba(0, 0, 0, 0.55)",e.beginPath(),e.arc(64,64,60,0,Math.PI*2),e.fill(),e.fillStyle="#ffffff",e.font="bold 52px sans-serif",e.textAlign="center",e.textBaseline="middle",e.fillText(c,64,68),new So(t)}function om(c){let t=c;return function(){t|=0,t=t+1831565813|0;let i=Math.imul(t^t>>>15,1|t);return i=i+Math.imul(i^i>>>7,61|i)^i,((i^i>>>14)>>>0)/4294967296}}class Jf{constructor(t,e){this.source=t,this.create=e}scene;wanted;pumping=!1;disposed=!1;static PATIENCE_FRAMES=600;static SCENE_WIDTH_PX=480;paint(t,e){this.disposed||(this.wanted={t,canvas:e},this.pumping||this.pump())}recordingChanged(t){this.scene&&(this.scene.sightingData=t)}dispose(){this.disposed=!0,this.scene?.remove(),this.scene=void 0}ensureScene(){if(this.scene)return this.scene;const t=this.create();return t.setAttribute("max-pixel-ratio","1"),t.setAttribute("always-live",""),Object.assign(t.style,{position:"fixed",left:"-10000px",top:"0",width:`${Jf.SCENE_WIDTH_PX}px`,visibility:"hidden",pointerEvents:"none"}),document.body.appendChild(t),t.documentUrl=this.source.documentUrl,t.accountInTheRound=this.source.accountInTheRound,t.sightingData=this.source.sightingData,this.scene=t,t}async pump(){this.pumping=!0;try{for(;this.wanted&&!this.disposed;){const{t,canvas:e}=this.wanted;this.wanted=void 0;const i=this.ensureScene();i.interpretation!==this.source.interpretation&&(i.interpretation=this.source.interpretation),i.compareAccount!==this.source.compareAccount&&(i.compareAccount=this.source.compareAccount),i.showAt(t);for(let s=0;s<Jf.PATIENCE_FRAMES&&!this.wanted&&!this.disposed&&(await new Promise(n=>requestAnimationFrame(()=>n())),!this.wanted);s++)if(i.snapshotTo(e)){e.dataset.ready="true";break}}}finally{this.pumping=!1}}}class hi{static held=new Map;static loaded=new Map;static generation=0;static address(t,e){const i=e??(typeof location>"u"?"http://localhost/":location.href);return new URL(t,i).href}static hold(t,e){hi.held.set(t,e),hi.loaded.delete(t),hi.generation++}static release(){if(hi.held.size!==0){for(const t of hi.held.keys())hi.loaded.delete(t);hi.held.clear(),hi.generation++}}static bytes(t,e=fetch.bind(globalThis)){const i=hi.held.get(t);if(i)return Promise.resolve(i);let s=hi.loaded.get(t);return s||(s=e(t).then(async n=>{if(!n.ok)throw new Error(`Frozen data not found (${n.status}): ${t}`);return new Uint8Array(await n.arrayBuffer())}),hi.loaded.set(t,s),s.catch(()=>hi.loaded.delete(t))),s}static async json(t){return JSON.parse(new TextDecoder().decode(await hi.bytes(t)))}static async zip(t){const e=await hi.bytes(t),{unzipSync:i}=await Ht(async()=>{const{unzipSync:s}=await import("./browser-CltifEM0.js");return{unzipSync:s}},[],import.meta.url);return i(e)}}class er{static SAME_BOUNDS_DEG=1e-9;loaded=!1;ready;list=[];constructor(t){this.ready=t.then(e=>{this.list=e},()=>{}).finally(()=>{this.loaded=!0})}nearest(t,e){let i,s=1/0;for(const n of this.list){if(n.far)continue;const{x:a,z:r}=re(n.lat,n.lng,t,e),o=Math.hypot(a,r);o<s&&(s=o,i=n)}return i}farRingOf(t,e){return this.list.find(i=>i.far&&Math.abs(i.lat-t)<=er.SAME_BOUNDS_DEG&&Math.abs(i.lng-e)<=er.SAME_BOUNDS_DEG)}static boundsOf(t){return tu(t.lat,t.lng,t.radiusM)}static sameBounds(t,e){const i=(s,n)=>Math.abs(s-n)<=er.SAME_BOUNDS_DEG;return i(t.north,e.north)&&i(t.south,e.south)&&i(t.east,e.east)&&i(t.west,e.west)}static contains(t,e){return t.north>=e.north&&t.south<=e.south&&t.east>=e.east&&t.west<=e.west}static samePatches(t,e){return t.length===e.length&&t.every((i,s)=>i.lat===e[s].lat&&i.lng===e[s].lng&&i.radiusM===e[s].radiusM&&i.far===e[s].far)}}class jf{static async encode(t){const{zipSync:e,strToU8:i}=await Ht(async()=>{const{zipSync:a,strToU8:r}=await import("./browser-CltifEM0.js");return{zipSync:a,strToU8:r}},[],import.meta.url),s={},n={version:1,takenOn:t.takenOn,attribution:t.attribution,patches:t.patches.map((a,r)=>{const o=`${r}.f32`;return s[o]=jf.byPlane(a.grid.heights),{lat:a.lat,lng:a.lng,radiusM:a.radiusM,...a.far?{far:a.far}:{},bounds:a.grid.bounds,width:a.grid.width,height:a.grid.height,file:o}})};return s["index.json"]=i(JSON.stringify(n,null,1)),e(s,{level:9})}static decode(t){const e=t["index.json"];if(!e)throw new Error("A relief annex without its index");const i=JSON.parse(new TextDecoder().decode(e));return{takenOn:i.takenOn,attribution:i.attribution,patches:i.patches.flatMap(s=>{const n=t[s.file];if(!n||n.length!==s.width*s.height*4)return[];const a={heights:jf.fromPlanes(n),width:s.width,height:s.height,bounds:s.bounds};return[{lat:s.lat,lng:s.lng,radiusM:s.radiusM,...s.far?{far:s.far}:{},grid:a}]})}}static byPlane(t){const e=new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i=t.length,s=new Uint8Array(e.length);for(let n=0;n<i;n++)for(let a=0;a<4;a++)s[a*i+n]=e[n*4+a];return s}static fromPlanes(t){const e=t.length/4,i=new Uint8Array(t.length);for(let s=0;s<e;s++)for(let n=0;n<4;n++)i[s*4+n]=t[n*e+s];return new Float32Array(i.buffer)}}class j1{constructor(t){this.annex=t}async getElevationGrid(t,e,i){const{patches:s}=await this.annex,n=s.find(r=>er.sameBounds(er.boundsOf(r),t));if(n)return{...n.grid,heights:new Float32Array(n.grid.heights)};const a=s.find(r=>er.contains(r.grid.bounds,t));if(a)return j1.resample(a.grid,t,e);throw new Error("The snapshots relief does not hold this ground")}static resample(t,e,i){const{width:s,height:n}=i,a=new Float32Array(s*n),r=t.bounds.east-t.bounds.west,o=t.bounds.north-t.bounds.south;for(let l=0;l<n;l++){const h=e.north-(e.north-e.south)*(n>1?l/(n-1):0),u=Math.min(t.height-1,Math.max(0,(t.bounds.north-h)/o*(t.height-1))),d=Math.floor(u),f=Math.min(t.height-1,d+1),p=u-d;for(let g=0;g<s;g++){const m=e.west+(e.east-e.west)*(s>1?g/(s-1):0),v=Math.min(t.width-1,Math.max(0,(m-t.bounds.west)/r*(t.width-1))),M=Math.floor(v),x=Math.min(t.width-1,M+1),y=v-M,w=(b,A)=>t.heights[b*t.width+A],S=w(d,M)*(1-y)+w(d,x)*y,E=w(f,M)*(1-y)+w(f,x)*y;a[l*s+g]=S*(1-p)+E*p}}return{heights:a,width:s,height:n,bounds:e}}}function Ub(c,t){return c.find(e=>e.id===t)??c[0]}class Z6{attribution;fetchImpl;tileUrlTemplate;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis);const e=t.year??2024;this.tileUrlTemplate=`https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-${e}_3857/default/g/{z}/{y}/{x}.jpg`,this.attribution=`EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data ${e})`}async getImageryTexture(t,e){return cw(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}const sL=rs.point("elevation").provide(rs.BUILT_IN,[{id:"ign-mnt",name:"IGN LiDAR HD / RGE ALTI",credit:"Relief © IGN, LiDAR HD and RGE ALTI (Licence Ouverte 2.0) in France; © AWS Open Data (SRTM, ETOPO1) elsewhere",creditUrl:"https://geoservices.ign.fr/lidarhd",create:()=>uw()},{id:"aws-terrarium",name:"AWS Terrain Tiles",credit:"© AWS Open Data (SRTM, ETOPO1)",creditUrl:"https://registry.opendata.aws/terrain-tiles/",create:()=>new ow}]),zb=rs.point("imagery").provide(rs.BUILT_IN,[{id:"esri-world",name:"Esri World Imagery",credit:"Imagery © Esri, Maxar, Earthstar Geographics, and the GIS User Community",creditUrl:"https://www.arcgis.com/home/item.html?id=10df2279f9684e4a9f6a7f08febac2a9",create:c=>new lw({fetchImpl:c})},{id:"eox-s2cloudless",name:"EOX Sentinel-2 cloudless",credit:"EOxCloudless by EOX IT Services GmbH (contains modified Copernicus Sentinel data)",creditUrl:"https://cloudless.eox.at",create:c=>new Z6({fetchImpl:c})}]);class nL{constructor(t=fetch.bind(globalThis)){this.fetchImpl=t}tiles=new Map;fetch=async(t,e)=>{const i=await this.fetchImpl(t,e);if(i.ok){const s=typeof t=="string"?t:t instanceof URL?t.href:t.url,n=new Uint8Array(await i.clone().arrayBuffer());this.tiles.set(s,{bytes:n,type:i.headers.get("content-type")??"image/jpeg"})}return i}}class J2{static async encode(t){const{zipSync:e,strToU8:i}=await Ht(async()=>{const{zipSync:o,strToU8:l}=await import("./browser-CltifEM0.js");return{zipSync:o,strToU8:l}},[],import.meta.url),s={},n={};let a=0;for(const[o,l]of t.tiles){const h=`tiles/${a++}`;s[h]=l.bytes,n[o]={file:h,type:l.type}}const r={version:1,takenOn:t.takenOn,source:t.source,attribution:t.attribution,patches:t.patches,map:t.map,tiles:n};return s["index.json"]=i(JSON.stringify(r,null,1)),e(s,{level:0})}static decode(t){const e=t["index.json"];if(!e)throw new Error("An imagery annex without its index");const i=JSON.parse(new TextDecoder().decode(e)),s=new Map;for(const[n,{file:a,type:r}]of Object.entries(i.tiles)){const o=t[a];o&&s.set(n,{bytes:o,type:r})}return{takenOn:i.takenOn,source:i.source,attribution:i.attribution,patches:i.patches,map:i.map,tiles:s}}}class w0{constructor(t,e=""){this.annex=t,this.attributionStated=e}provider;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}async getImageryTexture(t,e){return(await(this.provider??=this.annex.then(s=>(this.attributionRead=s.attribution,Ub(zb,s.source).create(w0.fetchFrom(s.tiles)))))).getImageryTexture(t,e)}static fetchFrom(t){return async e=>{const i=typeof e=="string"?e:e instanceof URL?e.href:e.url,s=t.get(i);return s?new Response(s.bytes,{status:200,headers:{"content-type":s.type}}):new Response(null,{status:404})}}}class J6{constructor(t,e=""){this.annex=t,this.attributionStated=e}picture;attributionRead;get attribution(){return this.attributionRead??this.attributionStated}getImagery(){return this.picture??=this.annex.then(t=>{if(!t.map)throw new Error("An imagery annex that holds no map");return this.attributionRead=t.attribution,Ub(zb,t.source).create(w0.fetchFrom(t.tiles)).getImageryTexture(t.map.bounds,{width:t.map.pixels,height:t.map.pixels})})}}class Q1{constructor(t){this.annex=t}attributionRead;contemporaryRead;async itemsFor(t){const e=await this.annex;return this.attributionRead=e.attribution,this.contemporaryRead=e.contemporary,e.patches.find(i=>er.sameBounds(er.boundsOf(i),t))?.items??[]}}class j6{constructor(t,e=""){this.attributionStated=e,this.reader=new Q1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRoads(t){return this.reader.itemsFor(t)}}class Q6{constructor(t,e=""){this.attributionStated=e,this.reader=new Q1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}getWater(t){return this.reader.itemsFor(t)}}class tO{constructor(t,e=""){this.attributionStated=e,this.reader=new Q1(t)}reader;get attribution(){return this.reader.attributionRead??this.attributionStated}get contemporary(){return this.reader.contemporaryRead??!0}getRailways(t){return this.reader.itemsFor(t)}}class Qf{static providers(t,e,i){const s=f=>jd.held(t,f),n=s("relief"),a=s("imagery"),r=s("roads"),o=s("water"),l=s("railways");if(!n&&!a&&!r&&!o&&!l)return i;const h=f=>hi.address(f.src,e),u=[],d={...i};if(n){const f=hi.zip(h(n)).then(p=>jf.decode(p));d.elevation=new j1(f),u.push(f.then(p=>p.patches))}if(a){const f=hi.zip(h(a)).then(p=>J2.decode(p));d.imagery=new w0(f,a.attribution),u.push(f.then(p=>p.patches))}if(r){const f=hi.json(h(r));d.roads=new j6(f,r.attribution),u.push(f.then(p=>p.patches))}if(o){const f=hi.json(h(o));d.water=new Q6(f,o.attribution),u.push(f.then(p=>p.patches))}if(l){const f=hi.json(h(l));d.railways=new tO(f,l.attribution),u.push(f.then(p=>p.patches))}return d.patches=new er(Qf.firstRead(u)),d}static map(t,e){const i=hi.zip(hi.address(t.src,e)).then(s=>J2.decode(s));return new J6(i,t.attribution)}static async firstRead(t){for(const e of t)try{const i=await e;if(i.length>0)return i.map(({lat:s,lng:n,radiusM:a,far:r})=>({lat:s,lng:n,radiusM:a,...r?{far:r}:{}}))}catch{}return[]}}const jc="https://en.wikipedia.org/wiki/Kodachrome",ko="https://en.wikipedia.org/wiki/Kodacolor_(still_photography)",eO="https://en.wikipedia.org/wiki/Kodak_Tri-X",Qc="https://en.wikipedia.org/wiki/List_of_discontinued_photographic_films",fr="https://www.kodak.com/en/motion/page/chronology-of-film/",Dn=(c,t)=>[{format:"135",from:c,to:t},{format:"120",from:c,to:t}],pr=(c,t)=>[{format:"35mm-cine",from:c,to:t}],j2=[{id:"kodacolor",name:"Kodacolor",kind:"negative",iso:32,formats:Dn(1942,1963),source:ko},{id:"kodacolor-x",name:"Kodacolor-X",kind:"negative",iso:80,formats:[...Dn(1963,1974),{format:"126",from:1963,to:1974}],source:ko},{id:"kodacolor-ii",name:"Kodacolor II",kind:"negative",iso:100,formats:[...Dn(1973),{format:"126",from:1973}],source:ko},{id:"kodacolor-400",name:"Kodacolor 400",kind:"negative",iso:400,formats:Dn(1977),source:ko},{id:"kodacolor-vr-100",name:"Kodacolor VR 100",kind:"negative",iso:100,formats:Dn(1982,1986),source:ko},{id:"kodacolor-vr-200",name:"Kodacolor VR 200",kind:"negative",iso:200,formats:[...Dn(1982,1986),{format:"126",from:1982,to:1986}],source:ko},{id:"kodacolor-vr-400",name:"Kodacolor VR 400",kind:"negative",iso:400,formats:Dn(1982,1986),source:ko},{id:"agfacolor-cn17",name:"Agfacolor CN17",kind:"negative",iso:40,formats:Dn(1956,1971),source:Qc},{id:"agfacolor-cns",name:"Agfacolor CNS",kind:"negative",iso:80,formats:[...Dn(1968,1975),{format:"126",from:1968,to:1975}],source:Qc},{id:"agfacolor-cns-2",name:"Agfacolor CNS 2",kind:"negative",iso:80,formats:[...Dn(1971,1982),{format:"126",from:1971,to:1982}],source:Qc},{id:"agfacolor-cns-400",name:"Agfacolor CNS 400",kind:"negative",iso:400,formats:Dn(1978,1984),source:Qc},{id:"kodachrome",name:"Kodachrome",kind:"slide",iso:10,formats:[{format:"135",from:1936,to:1962}],source:jc},{id:"kodachrome-ii",name:"Kodachrome II",kind:"slide",iso:25,formats:[{format:"135",from:1961,to:1974}],source:jc},{id:"kodachrome-x",name:"Kodachrome-X",kind:"slide",iso:64,formats:[{format:"135",from:1962,to:1974},{format:"126",from:1963,to:1974}],source:jc},{id:"kodachrome-25",name:"Kodachrome 25",kind:"slide",iso:25,formats:[{format:"135",from:1974,to:2001}],source:jc},{id:"kodachrome-64",name:"Kodachrome 64",kind:"slide",iso:64,formats:[{format:"135",from:1974,to:2009},{format:"126",from:1974,to:1993}],source:jc},{id:"kodachrome-200",name:"Kodachrome 200",kind:"slide",iso:200,formats:[{format:"135",from:1988,to:2007}],source:jc},{id:"agfachrome-ct18",name:"Agfachrome CT18",kind:"slide",iso:50,formats:[...Dn(1958,1984),{format:"126",from:1958,to:1984}],source:Qc},{id:"agfachrome-ct21",name:"Agfachrome CT21",kind:"slide",iso:100,formats:[{format:"135",from:1974,to:1984}],source:Qc},{id:"tri-x",name:"Kodak Tri-X",kind:"negative",monochrome:!0,iso:400,formats:Dn(1954),source:eO},{id:"eastman-5247-1950",name:"Eastman Color Negative 5247 (1950)",kind:"negative",iso:16,formats:pr(1950,1952),source:fr},{id:"eastman-5248-1952",name:"Eastman Color Negative 5248 (1952)",kind:"negative",iso:16,formats:pr(1952,1959),source:fr},{id:"eastman-5250",name:"Eastman Color Negative 5250",kind:"negative",iso:32,formats:pr(1959,1962),source:fr},{id:"eastman-5251",name:"Eastman Color Negative 5251",kind:"negative",iso:50,light:"tungsten",formats:pr(1962,1968),source:fr},{id:"eastman-5254",name:"Eastman Color Negative 5254",kind:"negative",iso:100,light:"tungsten",formats:pr(1968,1976),source:fr},{id:"eastman-5247-1974",name:"Eastman Color Negative II 5247 (1974)",kind:"negative",iso:64,formats:pr(1974,1983),source:fr},{id:"eastman-5294",name:"Eastman High Speed Negative 5294",kind:"negative",iso:400,light:"tungsten",formats:pr(1983),source:fr},{id:"eastman-5297",name:"Eastman High Speed Daylight 5297",kind:"negative",iso:250,formats:pr(1986,1997),source:fr},{id:"eastman-5245",name:"Eastman EXR 50D 5245",kind:"negative",iso:50,formats:pr(1989),source:fr}];class Au{static byId(t){return j2.find(e=>e.id===t)}static forInstrument(t){return j2.filter(e=>e.formats.some(i=>i.format===t.filmFormat))}static gap(t,e,i){const s=t.formats.find(n=>n.format===e.filmFormat);if(!(!s||i===void 0)){if(i<s.from)return{kind:"before",from:s.from};if(s.to!==void 0&&i>s.to)return{kind:"after",to:s.to}}}static possible(t,e){return Au.forInstrument(t).filter(i=>Au.gap(i,t,e)===void 0)}static mediumOf(t,e){return!t||!e?t:{...t,kind:e.kind,iso:e.iso,monochrome:e.monochrome}}}class Al{constructor(t){this.annex=t}static SAME_PLACE_DEG=1e-6;static SAME_TIME_MS=1e3;async between(t,e,i){let s;try{s=await this.annex}catch{return{status:"failed"}}const n=o=>Math.abs(o.lat-t.lat)<=Al.SAME_PLACE_DEG&&Math.abs(o.lng-t.lng)<=Al.SAME_PLACE_DEG,r=s.answers.find(o=>n(o)&&Math.abs(o.startMs-e)<=Al.SAME_TIME_MS&&Math.abs(o.endMs-i)<=Al.SAME_TIME_MS)??s.answers.find(o=>o.startMs<=e&&o.endMs>=i);return r?r.answer:{status:"failed"}}}const cm=7.5,lm=9;class Oa{static cache=new Map;static load(t){let e=Oa.cache.get(t);return e||(e=fetch(t).then(i=>i.arrayBuffer()).then(i=>Oa.parse(i)),Oa.cache.set(t,e)),e}static upTo(t,e){const i=t.filter((a,r)=>r===0||t[r-1].magnitudeLimit<e);if(i.length<=1)return Oa.load(t[0].url);const s=i.map(a=>a.url).join(`
|
|
8992
|
-
`);let n=Oa.cache.get(s);return n||(n=Promise.all(i.map(a=>Oa.load(a.url))).then(a=>a.reduce((r,o)=>Oa.concat(r,o))),Oa.cache.set(s,n)),n}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(s,n)=>{const a=new Float32Array(s.length+n.length);return a.set(s,0),a.set(n,s.length),a};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class ei{constructor(t){if(this.heights=t,t.length!==ei.WIDTH*ei.HEIGHT)throw new Error(`a lunar relief has ${ei.WIDTH*ei.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ei.SAMPLES_PER_DEGREE;static HEIGHT=180*ei.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=ei.SAMPLES_PER_DEGREE,s=(e%360+360)%360*i-.5,n=(90-t)*i-.5,a=Math.floor(s),r=Math.floor(n),o=s-a,l=n-r,h=(f,p)=>{const g=(f%ei.WIDTH+ei.WIDTH)%ei.WIDTH,m=Math.min(ei.HEIGHT-1,Math.max(0,p));return this.heights[m*ei.WIDTH+g]},u=h(a,r)*(1-o)+h(a+1,r)*o,d=h(a,r+1)*(1-o)+h(a+1,r+1)*o;return(u*(1-l)+d*l)*ei.UNIT_KM}static inBand(t,e){const i=Math.PI/180,s=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return s>=ei.BAND_FROM_DEG&&s<=ei.BAND_TO_DEG}static withBump(t,e,i,s=.4){const n=new Int8Array(ei.WIDTH*ei.HEIGHT),a=ei.SAMPLES_PER_DEGREE,r=Math.ceil(s*a),o=Math.floor(e*a),l=Math.floor((90-t)*a);for(let h=-r;h<=r;h++)for(let u=-r;u<=r;u++)Math.hypot(u,h)<=r&&(n[(l+h)*ei.WIDTH+(o+u+ei.WIDTH)%ei.WIDTH]=Math.round(i/ei.UNIT_KM));return new ei(n)}static smooth(){return new ei(new Int8Array(ei.WIDTH*ei.HEIGHT))}}class Zn{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,s=Zn.SAMPLES){const{s:n,u:a,w:r,distanceKm:o}=Zn.frame(t,e),l=Math.PI/180,h=new Float32Array(s),u=ei.REFERENCE_RADIUS_KM;for(let d=0;d<s;d++){const f=d/s*2*Math.PI,p=Math.cos(f),g=Math.sin(f),m=p*a[0]+g*r[0],v=p*a[1]+g*r[1],M=p*a[2]+g*r[2];let x=0;for(let y=Zn.SEARCH_FROM_DEG;y<=Zn.SEARCH_TO_DEG;y+=Zn.SEARCH_STEP_DEG){const w=Math.cos(y*l),S=Math.sin(y*l),E=w*n[0]+S*m,b=w*n[1]+S*v,A=w*n[2]+S*M,T=Math.asin(Math.max(-1,Math.min(1,A)))/l,D=Math.atan2(b,E)/l,I=u+i.heightKm(T,D),C=Math.atan2(I*S,o-I*w);C>x&&(x=C)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/o)/l}}static frame(t,e){const i=new Mo(e.lat,e.lng,e.elevationM),s=Pr(t),n=Sm(t,i,!1),a=new Fe(n.x-s.x,n.y-s.y,n.z-s.z,s.t),r=Math.hypot(a.x,a.y,a.z)*Zn.AU_KM,o=Zn.bodyFixed(t),l=o(a),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=fE(t,i),f=d1(d),p=Dr(d,new Fe(-a.x,-a.y,-a.z,s.t)),g=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),m=Math.atan2(-p.y,p.x),v=new Fe(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),s.t),M=new Fe(-Math.sin(m),-Math.cos(m),0,s.t);return{s:u,u:o(Dr(f,v)),w:o(Dr(f,M)),distanceKm:r}}static surfacePoint(t,e,i,s){const{s:n,u:a,w:r}=Zn.frame(t,e),o=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*o)*a[u]+Math.sin(i*o)*r[u]),h=[0,1,2].map(u=>Math.cos(s*o)*n[u]+Math.sin(s*o)*l[u]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(t,e){const i=t.radiusDeg.length,s=(e/360*i%i+i)%i,n=Math.floor(s),a=s-n;return t.radiusDeg[n]*(1-a)+t.radiusDeg[(n+1)%i]*a}static uncoveredFraction(t,e,i){const s=t.radiusDeg.length,n=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let a=0;for(let r=0;r<s;r++){const o=r/s*2*Math.PI,l=Math.cos(o),h=Math.sin(o),u=l*i.upDeg+h*i.rightDeg,d=u*u-n+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const g=Math.max(0,u-f),m=Math.max(g,t.radiusDeg[r]);p>m&&(a+=.5*(p*p-m*m))}return Math.min(1,Math.max(0,a*(2*Math.PI/s)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=DE(pt.Moon,t),i=Math.PI/180,s=e.ra*15*i,n=e.dec*i,a=e.spin*i,r=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],o=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>r(a,o(Math.PI/2-n,r(Math.PI/2+s,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new Mo(e.lat,e.lng,e.elevationM),s=Pr(t),n=Sm(t,i,!1),a=Zn.bodyFixed(t)(new Fe(n.x-s.x,n.y-s.y,n.z-s.z,s.t)),r=Math.hypot(a[0],a[1],a[2]);return{latDeg:Math.asin(a[2]/r)*180/Math.PI,lonDeg:Math.atan2(a[1],a[0])*180/Math.PI}}}class ru{static cache=new Map;static load(t){let e=ru.cache.get(t);return e||(e=ru.fetchRelief(t).catch(()=>{}),ru.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const s=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(s).arrayBuffer())}return new ei(new Int8Array(i.buffer,i.byteOffset,i.length))}}const tv=fc.catalog({en:()=>Ht(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(c=>c.perceptionMessages_en),fr:()=>Ht(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(c=>c.perceptionMessages_fr),es:()=>Ht(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(c=>c.perceptionMessages_es),it:()=>Ht(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(c=>c.perceptionMessages_it)});class t0{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=t0.ID;messages=tv;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=t0.MATRICES[String(t.type)];if(!e)return An.NONE;const i=Number(t.severity??100),s=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((a,r)=>An.IDENTITY[r]+(a-An.IDENTITY[r])*s),contrastGain:1}}}class ev{static ID="fatigue";id=ev.ID;messages=tv;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return An.NONE}}class Ho{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Ho.ID;messages=tv;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:Ho.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(Ho.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return An.NONE;const s=i/Ho.MEASURED_LEVEL*Ho.MEASURED_LOSS_DB;return{colorMatrix:An.IDENTITY,contrastGain:10**(-s/20)}}}const iO=c=>c.sources[0]??c.id,sO=rs.point("perception").provide(rs.BUILT_IN,[new t0,new Ho,new ev].map(c=>({id:c.id,name:c.id,credit:iO(c),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>c})));class Go{static built=new WeakMap;static get ALL(){return sO.map(t=>{let e=Go.built.get(t);return e||(e=t.create(),Go.built.set(t,e)),e})}static byId(t){return Go.ALL.find(e=>e.id===t)}static perceptionOf(t){return Go.ALL.reduce((e,i)=>An.combine(e,i.perceive(t?.[i.id]??{})),An.NONE)}static compact(t){const e={},i=Go.ALL;for(const[s,n]of Object.entries(t))!i.some(a=>a.id===s)&&Object.keys(n??{}).length>0&&(e[s]=n);for(const s of i){const n=t[s.id]??{},a=Object.fromEntries(s.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(a).length>0&&(e[s.id]=a)}return Object.keys(e).length>0?e:void 0}}class Q2{names;constructor(t){this.names=t??fc.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return sc.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return sc.towards(t,this.loaded?this.names:void 0)}}class ka{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??ka.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,s){const{line:n}=t,a=[];n.name&&a.push(ka.kind(n,e).toLocaleLowerCase(s)),a.push(n.tracks>1?e.tracks.replace("{count}",String(n.tracks)):e.singleTrack);const r=n.voltageV?ka.voltage(n.voltageV,s):void 0;if(t.contactM!==void 0){const o=t.contactM.toLocaleString(s,{minimumFractionDigits:2,maximumFractionDigits:2});a.push((r?e.overheadVoltage.replace("{voltage}",r):e.overhead).replace("{height}",o))}else n.electrification==="third_rail"?a.push(r?e.thirdRailVoltage.replace("{voltage}",r):e.thirdRail):n.electrification==="none"&&a.push(e.notElectrified);return n.gaugeMm===ka.METRE_GAUGE_MM?a.push(e.metreGauge):n.gaugeMm!==ka.STANDARD_GAUGE_MM&&a.push(e.gauge.replace("{mm}",n.gaugeMm.toLocaleString(s))),a.push(e.distance.replace("{distance}",i(t.distanceM))),n.services?.length?`${ka.name(n,e)}; ${a.join(", ")}`:`${ka.name(n,e)} — ${a.join(", ")}`}}class ou{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const s=ou.resolve(t,e);if(this.url=s,!s||!i){this.release();return}this.element.src=s,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===ou.PUBLISHED_ORIGIN&&ou.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}class Ci{static OCTAVES=[63,125,250,500,1e3,2e3,4e3,8e3];static STANDARD={temperatureC:15,relativeHumidity:.7,pressureKPa:101.325};static REFERENCE_PRESSURE_KPA=101.325;static REFERENCE_TEMPERATURE_K=293.15;static TRIPLE_POINT_K=273.16;static speedOfSound(t){return 20.0468*Math.sqrt(t+273.15)}static absorptionDbPerKm(t,e=Ci.STANDARD){const i=e.temperatureC+273.15,s=Ci.REFERENCE_TEMPERATURE_K,n=e.pressureKPa/Ci.REFERENCE_PRESSURE_KPA,a=10**(-6.8346*(Ci.TRIPLE_POINT_K/i)**1.261+4.6151),r=e.relativeHumidity*100*a/n,o=n*(24+40400*r*(.02+r)/(.391+r)),l=n*(i/s)**-.5*(9+280*r*Math.exp(-4.17*((i/s)**(-1/3)-1))),h=t*t;return 8.686*h*(184e-13*(1/n)*Math.sqrt(i/s)+(i/s)**-2.5*(.01275*Math.exp(-2239.1/i)/(o+h/o)+.1068*Math.exp(-3352/i)/(l+h/l)))*1e3}static aWeightingDb(t){const e=t*t,i=12194**2*e*e/((e+20.6**2)*Math.sqrt((e+107.7**2)*(e+737.9**2))*(e+12194**2));return 20*Math.log10(i)+2}static sumDb(t){return 10*Math.log10(t.reduce((e,i)=>e+10**(i/10),0))}}const nO=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,aO=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,tx=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,rO=20,oO=1,cO=7,lO=.35,ex=.4,ix=40,sx=.5,hO=Math.SQRT2;class tc{context;constructor(t){this.context=t}buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};around;aroundRequested={rms:0,shape:[]};level=1;share=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.gain,this.master.connect(t.destination)),this.master}get gain(){return this.level*this.share}setLevel(t){this.level=t,this.master&&(this.master.gain.value=this.gain)}setOutsideHeard(t){this.share=Math.min(1,Math.max(0,t)),this.master&&(this.master.gain.value=this.gain)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Un.isLive(this.context)&&Un.unlock(this.context),this.applyAround()}setAround(t,e){const i=this.aroundRequested;i.rms===Math.max(0,t)&&i.shape.length===e.length&&i.shape.every((s,n)=>s===e[n])||(this.aroundRequested={rms:Math.max(0,t),shape:e},this.applyAround())}applyAround(){const t=this.context;if(!t)return;const{rms:e,shape:i}=this.aroundRequested,s=this.paused?0:e;if(s===0&&!this.around)return;const n=this.around??(this.around=this.buildAround(t)),a=t.currentTime;n.gain.gain.setTargetAtTime(s,a,sx),Ci.OCTAVES.forEach((r,o)=>{const l=Math.sqrt(Math.min(1,1.11*r/(t.sampleRate/2)))/Math.sqrt(3);n.bands[o].gain.setTargetAtTime((i[o]??0)/l,a,sx)})}buildAround(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*cO),t.sampleRate),i=e.getChannelData(0);for(let g=0;g<i.length;g++)i[g]=Math.random()*2-1;const s=t.createBufferSource();s.buffer=e,s.loop=!0;const n=Math.floor(t.sampleRate*ix),a=t.createBuffer(1,n,t.sampleRate),r=Array.from({length:Math.round(ix*ex)},()=>Math.random()*2-1),o=a.getChannelData(0),l=t.sampleRate/ex;for(let g=0;g<n;g++){const m=g/l,v=Math.floor(m),M=m-v,x=M*M*(3-2*M);o[g]=r[v%r.length]*(1-x)+r[(v+1)%r.length]*x}const h=t.createBufferSource();h.buffer=a,h.loop=!0;const u=t.createGain();u.gain.value=lO;const d=t.createGain();d.gain.value=1,h.connect(u).connect(d.gain);const f=t.createGain();f.gain.value=0,d.connect(f).connect(this.output(t));const p=Ci.OCTAVES.map(g=>{const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=g,m.Q.value=hO;const v=t.createGain();return v.gain.value=0,s.connect(m).connect(v).connect(d),v});return s.start(),h.start(),{sources:[s,h],nodes:[u,d,f,...p],bands:p,gain:f}}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const s=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=s==="hail"?Math.min(1,e*1.3+.2):s==="rain"?e:0,s!==this.ambientKey){this.ambientKey=s;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(nO,this.ambientVolume).then(r=>this.applyIfCurrent(r,a,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/rO,1);const n=i>oO;if(n!==this.windActive){this.windActive=n;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(aO,this.windVolume).then(r=>this.applyIfCurrent(r,a,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:s}=this.requested;this.setAmbient(e,i,s),this.applyAround()}playThunder(){!this.context||this.paused||this.playOneShot(tx,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),s=e.createBufferSource();s.buffer=this.crackBuffer(e);const n=e.createBiquadFilter();n.type="lowpass",n.frequency.value=tc.CRACK_CUTOFF_HZ;const a=e.createGain();a.gain.value=i,s.connect(n).connect(a).connect(this.output(e)),s.start(),this.playOneShot(tx,i,tc.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*tc.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),s=i.getChannelData(0);for(let n=0;n<e;n++){const a=n/t.sampleRate;s[n]=(Math.random()*2-1)*Math.min(1,a/.005)*Math.exp(-a/tc.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0;for(const t of this.around?.sources??[])try{t.stop()}catch{}for(const t of this.around?.nodes??[])t.disconnect();this.around=void 0,Un.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,s){if(e!==i()){t?.source.stop();return}s(t)}async startLoop(t,e){const i=this.context;if(i)try{const s=await this.getBuffer(t),n=i.createBufferSource();n.buffer=s,n.loop=!0;const a=i.createGain();return a.gain.value=e,n.connect(a).connect(this.output(i)),n.start(),{source:n,gain:a}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(t,e,i=1){const s=this.context;if(s)try{const n=await this.getBuffer(t),a=s.createBufferSource();a.buffer=n,a.playbackRate.value=i;const r=s.createGain();r.gain.value=e,a.connect(r).connect(this.output(s)),a.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${t}`);return s.arrayBuffer()}).then(s=>e.decodeAudioData(s)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}const uO={rollingA:[83.1,89.2,87.7,93.1,100.1,96.7,86.8,76.2],rollingB:[30,41.5,38.9,25.7,32.5,37.2,39,40],propulsionA:[97.9,92.5,90.7,87.2,84.7,88,84.4,77.1],propulsionB:[-1.3,7.2,7.7,8,8,8,8,8]},dO={rollingA:[91.7,96.2,98.2,104.9,105.1,98.5,91.1,85.6],rollingB:[30,33.5,31.3,25.4,31.8,37.1,38.6,40.6],propulsionA:[108.8,104.2,103.5,102.9,102.6,98.5,93.8,87.5],propulsionB:[0,3,4.6,5,5,5,5,5]},hm=70,fO=55+10*Math.log10(2*Math.PI),um=5,pO=2;class ss{static vehiclePowerDbA(t,e){return Ci.sumDb(ss.vehiclePowerBands(t,e).map((i,s)=>i+Ci.aWeightingDb(Ci.OCTAVES[s])))}static vehiclePowerBands(t,e){const i=t?dO:uO,s=Math.max(e,1);return Ci.OCTAVES.map((n,a)=>{const r=i.rollingA[a]+i.rollingB[a]*Math.log10(s/hm),o=i.propulsionA[a]+i.propulsionB[a]*(s-hm)/hm;return Ci.sumDb([r,o])})}static dbA(t,e=!0){if(!Jr.says(t))return-1/0;const i=t.withinM??Jr.DEFAULT_WITHIN_M,s=Jr.DEFAULT_SPEED_KMH,n=[ss.counted(t.cars,ss.vehiclePowerDbA(!1,s),i,um),ss.counted(t.trucks,ss.vehiclePowerDbA(!0,s),i,um),e?ss.counted(t.talking,fO,i,pO):-1/0,...(t.roads??[]).map(a=>ss.road(a.distanceM,a.vehiclesPerMinute,a.trucksPerMinute??0,a.speedKmh??s))].filter(a=>Number.isFinite(a));return n.length>0?Ci.sumDb(n):-1/0}static vehicleShape(t){if(!Jr.says(t))return;const e=t.withinM??Jr.DEFAULT_WITHIN_M,i=Jr.DEFAULT_SPEED_KMH,s=l=>{const h=ss.counted(l?t.trucks:t.cars,ss.vehiclePowerDbA(l,i),e,um),u=(t.roads??[]).map(f=>{const p=Math.min(f.trucksPerMinute??0,f.vehiclesPerMinute);return l?ss.road(f.distanceM,p,p,f.speedKmh??i):ss.road(f.distanceM,f.vehiclesPerMinute-p,0,f.speedKmh??i)}),d=[h,...u].filter(Number.isFinite);return d.length>0?10**(Ci.sumDb(d)/10):0},n=s(!1),a=s(!0);if(n+a===0)return;const r=Ci.OCTAVES.map(()=>0);for(const[l,h]of[[n,!1],[a,!0]]){if(l===0)continue;const u=ss.vehiclePowerBands(h,i),d=Ci.sumDb(u.map((f,p)=>f+Ci.aWeightingDb(Ci.OCTAVES[p])));u.forEach((f,p)=>r[p]+=l*10**((f-d)/10))}const o=Math.sqrt(r.reduce((l,h)=>l+h,0));return r.map(l=>Math.sqrt(l)/o)}static counted(t,e,i,s){if(!t)return-1/0;const n=Math.min(s,i*.99),a=t*Math.log(i/n)/(Math.PI*(i*i-n*n));return e+10*Math.log10(a)}static road(t,e,i,s){const n=Math.min(i,e),a=(o,l)=>o>0?ss.vehiclePowerDbA(l,s)+10*Math.log10(o/(1e3*Math.max(s,1))):-1/0,r=Ci.sumDb([a((e-n)*60,!1),a(n*60,!0)].filter(Number.isFinite));return Number.isFinite(r)?r-10*Math.log10(Math.PI*Math.max(t,1)):-1/0}}class pi{static BASE_DB_A=30;static OUTDOOR_SHAPE_DB=[-12,-7,-5,-5,-7,-11,-17,-25];static HEADROOM_DB=10.5;static AROUND_BED_PLAYED=!1;static WIND_DB_A=[[0,10],[1,28],[2,36],[3,40],[5,46],[8,52],[12,58],[20,66]];static RAIN_DB_A=[[0,0],[.1,42],[.3,50],[.6,58],[1,65]];static BED_RMS=.2;static MINIMUM_REFERENCE=.008;static WIND_BED_MIN_MS=1;static WIND_BED_FULL_MS=20;static dbA(t,e){const i=[pi.BASE_DB_A,pi.along(pi.WIND_DB_A,t.windSpeed),ss.dbA(e)].filter(Number.isFinite);return(t.precipitationType==="rain"||t.precipitationType==="hail")&&i.push(pi.along(pi.RAIN_DB_A,t.precipitationIntensity)),10*Math.log10(i.filter(s=>s>0).reduce((s,n)=>s+10**(n/10),0))}static bedVolume(t){const e=t.windSpeed>pi.WIND_BED_MIN_MS?Math.min(t.windSpeed/pi.WIND_BED_FULL_MS,1):0,i=t.precipitationType==="hail"?Math.min(1,t.precipitationIntensity*1.3+.2):t.precipitationType==="rain"?t.precipitationIntensity:0;return Math.hypot(e,i)}static referenceAmplitude(t,e){return Math.max(Math.hypot(pi.BED_RMS*pi.bedVolume(t),pi.aroundReference(e)),pi.MINIMUM_REFERENCE)}static aroundReference(t){const e=ss.dbA(t);return!Number.isFinite(e)||e<=pi.BASE_DB_A?0:pi.MINIMUM_REFERENCE*10**((e-pi.BASE_DB_A)/20)}static aroundBedRms(t){if(!pi.AROUND_BED_PLAYED)return 0;const e=ss.dbA(t,!1);return!Number.isFinite(e)||e<=pi.BASE_DB_A?0:Math.min(pi.BED_RMS,pi.MINIMUM_REFERENCE*10**((e-pi.BASE_DB_A-pi.HEADROOM_DB)/20))}static bedPlays(t,e){return pi.bedVolume(t)>0||pi.aroundBedRms(e)>0}static shapeDb(t,e){const i=10**(pi.dbA(t,e)/10),s=ss.dbA(e,!1),n=Number.isFinite(s)?10**(s/10):0,a=Math.max(0,i-n),r=pi.OUTDOOR_SHAPE_DB,o=10**(Ci.sumDb(r)/10),h=ss.vehicleShape(e)?.map((p,g)=>p*p*10**(Ci.aWeightingDb(Ci.OCTAVES[g])/10)),u=h?.reduce((p,g)=>p+g,0)??1,d=Ci.OCTAVES.map((p,g)=>a*10**(r[g]/10)/o+(h?n*h[g]/u:0)),f=d.reduce((p,g)=>p+g,0);return d.map(p=>10*Math.log10(p/f))}static aroundBedShape(t){return ss.vehicleShape(t)}static along(t,e){if(e<=t[0][0])return t[0][1];for(let i=1;i<t.length;i++)if(e<=t[i][0]){const[s,n]=t[i-1],[a,r]=t[i];return n+(r-n)*(e-s)/(a-s)}return t[t.length-1][1]}}class yr{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[s,n]=this.perifocalAxes(),a=Math.sqrt(yr.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(s,i),this.perihelionVelocity=this.scale(n,a),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),s=this.inverseSemiMajorAxis*i*i,n=this.elements.perihelionAu,a=1-i*i/n*yr.stumpffC(s),r=e-i*i*i/Math.sqrt(yr.SUN_GM_AU3_PER_DAY2)*yr.stumpffS(s);return{x:a*this.perihelionPosition.x+r*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+r*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+r*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(yr.SUN_GM_AU3_PER_DAY2)*Math.abs(t),s=r=>{const o=this.inverseSemiMajorAxis*r*r,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*r*r*r*yr.stumpffS(o)+l*r};let n=Math.max(1,i/this.elements.perihelionAu);for(;s(n)<i;)n*=2;let a=0;for(let r=0;r<yr.MAX_ITERATIONS&&n-a>1e-13*Math.max(1,n);r++){const o=(a+n)/2;s(o)<i?a=o:n=o}return e*(a+n)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,s=Math.cos(t),n=Math.sin(t),a=Math.cos(e),r=Math.sin(e),o=Math.cos(i),l=Math.sin(i);return[{x:s*a-n*r*o,y:n*a+s*r*o,z:r*l},{x:-s*r-n*a*o,y:-n*r+s*a*o,z:a*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Bb=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class mO{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Bb.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,s)=>i.magnitude-s.magnitude)[0]}static appearanceOf(t,e,i){const s=oi(e),n=this.earthPositionAt(s),a=this.apparentPositionOf(t,2451545+s.tt,n),r=this.subtract(a,n),o=this.length(a),l=this.length(r),h=this.tailEndAt(t,a,n,o,s,e,i),u=this.horizontalOf(r,s,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:o,earthDistanceAu:l,elongationDeg:this.angleBetween(r,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(t,o,l)}}static magnitudeAt(t,e,i){const s=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(s,t.peakMagnitude)}static tailEndAt(t,e,i,s,n,a,r){if(t.tailLengthAu===void 0)return{};const o=1+t.tailLengthAu/s,l=this.subtract({x:e.x*o,y:e.y*o,z:e.z*o},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,n,a,r),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const s=this.orbitOf(t);let n=s.positionAt(e);for(let a=0;a<2;a++){const r=this.length(this.subtract(n,i))/this.LIGHT_SPEED_AU_PER_DAY;n=s.positionAt(e-r)}return n}static horizontalOf(t,e,i,s){const n=Dr(lE(),new Fe(t.x,t.y,t.z,e)),a=Dr(Gx(e),n),r=Sm(e,new Mo(s.lat,s.lng,s.elevationM),!0),o=new Fe(a.x-r.x,a.y-r.y,a.z-r.z,e),l=l0(o);return m1(l.ra,l.dec,i,s)}static earthPositionAt(t){return Dr(cE(),po(pt.Earth,t))}static julianDayOf(t){return 2451545+oi(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new yr(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const dm=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class nx{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return dm.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),s=[];for(const n of dm){const a=this.magnitudeAt(n,i);a!==void 0&&s.push({outburst:n,position:da.ofJ2000(n.raHours,n.decDeg,t,e),magnitude:a})}return s.sort((n,a)=>n.magnitude-a.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return dm.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,s=e-t.startJd;if(i.length===0||s<i[0][0]||s>i[i.length-1][0])return;let n=1;for(;n<i.length-1&&i[n][0]<s;)n++;const[a,r]=i[n-1]??i[0],[o,l]=i[n]??i[0];if(o===a)return r;const h=Math.min(1,Math.max(0,(s-a)/(o-a)));return r+h*(l-r)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const gO=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],e0=6.5;class fm{static activeAt(t){return gO.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),s=this.dayOfYear(this.asDate(t.start)),n=this.dayOfYear(this.asDate(t.peak)),a=this.dayOfYear(this.asDate(t.end)),r=this.wrappedDelta(i,n),o=this.wrappedDelta(n,s),l=this.wrappedDelta(a,n);return r<0?r<-o?0:1+r/o:r>0?r>l?0:1-r/l:1}static observedRatePerHour(t,e,i,s=e0){if(e<=0)return 0;const n=e0-s;return t*Math.sin(e*Math.PI/180)/Math.pow(i,n)}static radiantPosition(t,e,i){return da.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class zi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=oi(t),s=new a0(0,BS(t).elon-90,1),n=Dr(pE(i),p1(s,i)),a=l0(n);return m1(a.ra,a.dec,t,e)}static observedRatePerHour(t,e=e0){const i=zi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),s=e0-e;return(zi.QUIET_RATE_PER_HOUR+i)/Math.pow(zi.POPULATION_INDEX,s)}static schedule(t){const e=new M0(t.seed^1542469173);return Jn.schedule(t).map(i=>{const s=zi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),n=i.fromRadiantDeg*Math.PI/180,a=zi.turnAround(s,e.between(0,360)),r={x:s.x*Math.cos(n)+a.x*Math.sin(n),y:s.y*Math.cos(n)+a.y*Math.sin(n),z:s.z*Math.cos(n)+a.z*Math.sin(n)};return{...i,radiant:zi.toHorizontal(r),bearingDeg:zi.bearingFrom(r,s)}})}static turnAround(t,e){const[i,s]=zi.basisAround(t),n=e*Math.PI/180;return{x:i.x*Math.cos(n)+s.x*Math.sin(n),y:i.y*Math.cos(n)+s.y*Math.sin(n),z:i.z*Math.cos(n)+s.z*Math.sin(n)}}static bearingFrom(t,e){const[i,s]=zi.basisAround(t),n=t.x*e.x+t.y*e.y+t.z*e.z,a=zi.normalise({x:e.x-t.x*n,y:e.y-t.y*n,z:e.z-t.z*n});return(Math.atan2(a.x*s.x+a.y*s.y+a.z*s.z,a.x*i.x+a.y*i.y+a.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=zi.normalise(zi.cross(t,e));return[i,zi.normalise(zi.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=zi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=zi.turnAround(e,t.bearingDeg),s=t.fromRadiantDeg*Math.PI/180;return zi.toHorizontal({x:e.x*Math.cos(s)+i.x*Math.sin(s),y:e.y*Math.cos(s)+i.y*Math.sin(s),z:e.z*Math.cos(s)+i.z*Math.sin(s)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,s=Math.cos(e);return{x:s*Math.sin(i),y:Math.sin(e),z:-s*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const ax="https://ufoathome.org/tle/index.json";class Vs{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Vs.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(ax)||t.push(ax),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Vs.FIRST_SNAPSHOT}T00:00:00Z`)-Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(s=>t.getTime()>=Date.parse(s.from)-Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS&&t.getTime()<=Date.parse(s.to)+Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:s}=e,n=[],a=[];for(const r of Object.keys(i.kinds)){const o=await this.kindAt(r,t,i,s);n.push(...o),a.push(this.coverageOf(r,t,i,o.length>0))}return{objects:n,coverage:a,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,s){const n=e.getTime(),a=i.binDays*Vs.DAY_MS,r=Math.floor(n/a),o=n-r*a<a/2?r-1:r+1,l=new Set(i.kinds[t].bins),h=[r,o].map(g=>new Date(g*a).toISOString().slice(0,10)).filter(g=>l.has(g));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,s).href),...h.map(g=>this.binary(new URL(`${t}/${g}.bin`,s).href))]),f=new Map;for(const g of d)for(const m of Vs.decode(g,i.recordBytes)){const v=f.get(m.norad);(!v||Math.abs(m.epochMs-n)<Math.abs(v.epochMs-n))&&f.set(m.norad,m)}const p=[];for(const g of f.values()){const m=Math.abs(g.epochMs-n)/Vs.DAY_MS;if(m>Vs.MAX_ELEMENT_AGE_DAYS)continue;const v=u[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>n||p.push({norad:g.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return p}coverageOf(t,e,i,s){const{from:n,to:a}=i.kinds[t],r=e.getTime(),o=Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS,l=s?"covered":r<Date.parse(n)-o?"before":r>Date.parse(a)+o?"after":"gap";return{kind:t,status:l,from:n,to:a}}static decode(t,e){const i=new DataView(t),s=[];for(let n=0;n+e<=t.byteLength;n+=e)s.push({norad:i.getUint32(n,!0),epochMs:i.getFloat64(n+4,!0),bstar:i.getFloat32(n+12,!0),inclinationDeg:i.getFloat32(n+16,!0),raanDeg:i.getFloat32(n+20,!0),eccentricity:i.getFloat32(n+24,!0),argOfPerigeeDeg:i.getFloat32(n+28,!0),meanAnomalyDeg:i.getFloat32(n+32,!0),meanMotion:i.getFloat64(n+36,!0)});return s}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(s=>{if(!s.ok)throw new Error(`${t}: ${s.status}`);return e(s)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class vO{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=Di.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=Di.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:Di.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:Di.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class nc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*nc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=nc.degOver(t)/e;return i<1?1:Math.min(nc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Ps{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return nc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Ps.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,s=e.fNumber??t.fNumber;if(i===void 0||s===void 0||!(i>0)||!(s>0))return Ps.EYE;const n=e.focalLengthMm??t.frame?.focalLengthMm??Ps.UNKNOWN_CAMERA_FOCAL_MM,a=n/s,r=Ps.resolutionArcsec(t,n,a);return{apertureMm:a,exposureSeconds:Math.min(i,Ps.trailLimitedSeconds(r)),resolutionArcsec:r}}static visualAidGrasp(t,e){const i=t.visualAid,s=Ps.EYE,n=e??t.frame?.focalLengthMm,a=i.magnification??(n!==void 0&&i.eyepieceFocalMm?n/i.eyepieceFocalMm:1),r=Math.min(i.apertureMm,s.apertureMm*a);return{apertureMm:Math.max(r,s.apertureMm),exposureSeconds:s.exposureSeconds,resolutionArcsec:s.resolutionArcsec/Math.max(1,Math.min(a,i.apertureMm/s.apertureMm))}}static resolutionArcsec(t,e,i){const n=(t.detailUm??Ps.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Ps.ARCSEC_PER_RADIAN,a=1.22*Ps.WAVELENGTH_M/(i/1e3)*Ps.ARCSEC_PER_RADIAN;return Math.max(n,a)}static trailLimitedSeconds(t){return t/Ps.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Ps.graspOf(t,e),s=Ps.EYE,n=(i.apertureMm/s.apertureMm)**2,a=i.exposureSeconds/s.exposureSeconds,r=(s.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(n*a*r)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Ts.focalLengthMmFor(t,e.fieldOfViewDeg);return Ps.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const rx=111320,Ph=Math.PI/180,MO=1.02,yO=1;class cu{static of(t,e){const i=cu.sightings(t,e);if(i.length<2)return;const s=cu.baseline(i);if(!s)return;const{near:n,far:a,closedM:r}=s,o=Math.tan(a.widthDeg/2*Ph)===0?0:Math.tan(n.widthDeg/2*Ph)/Math.tan(a.widthDeg/2*Ph);if(o<MO)return;const l=r/(o-1),h=Di.sizeMAt(l,n.widthDeg),u=i.map(d=>({t:d.t,m:Di.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:a.t,toT:n.t,closedM:r}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const s=i.shapes.find(r=>r.sourceId===e)?.shape,n=s?.angular?.widthDeg,a=Te(t,i.t);return n===void 0||n<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:i.t,widthDeg:n,lat:a.lat,lng:a.lng,sightAzimuthDeg:s?.aim?.azimuthDeg??a.headingDeg}]}).sort((i,s)=>i.t-s.t)}static baseline(t){let e;for(const i of t)for(const s of t){if(i.t>=s.t)continue;const n=cu.closedAlongSight(i,s),[a,r,o]=n>=0?[s,i,n]:[i,s,-n];o<yO||a.widthDeg<=r.widthDeg||(!e||o>e.closedM)&&(e={near:a,far:r,closedM:o})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*rx,s=(e.lng-t.lng)*rx*Math.cos(t.lat*Ph),n=(t.sightAzimuthDeg??0)*Ph;return i*Math.cos(n)+s*Math.sin(n)}}class rn{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:rn.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:rn.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:rn.atLeastNearest(t.derivedM),basis:"derived"};const e=rn.largest(t.range?.minM,t.crossing?.behindM),i=rn.smallest(t.range?.maxM,t.crossing?.inFrontM),s=e===void 0?void 0:e*rn.MARGIN,n=i===void 0?void 0:i/rn.MARGIN;return s!==void 0&&n!==void 0?{distanceM:rn.atLeastNearest(s<=n?Math.sqrt(s*n):s),basis:"bounded"}:s!==void 0?{distanceM:rn.atLeastNearest(s),basis:"bounded"}:n!==void 0&&n<rn.CONVENTIONAL_M?{distanceM:rn.atLeastNearest(n),basis:"bounded"}:{distanceM:rn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(rn.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class Ct{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[Ct.DEFAULT_CRUMBLING,...Ct.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],i=[];for(let s=1;s<e.length-1;s++){const n=e[s];e[s-1].absoluteMagnitude-n.absoluteMagnitude<Ct.FLARE_MAGNITUDES||e[s+1].absoluteMagnitude-n.absoluteMagnitude<Ct.FLARE_MAGNITUDES||i.push({...Ct.DEFAULT_BURST,fromT:n.t-1e3,untilT:n.t+1500})}return i}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let s=0;for(;s<i.length-2&&i[s+1].t<e;)s++;const n=i[s],a=i[s+1],r=a.t-n.t,o=r>0?(e-n.t)/r:0,[l,h]=Ct.alongGreatCircle(n,a,o);return{lat:l,lng:h,heightM:(n.altitudeKm+(a.altitudeKm-n.altitudeKm)*o)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(s=>s.altitudeKm))),i=5*Math.log10(e/Ct.STANDARD_DISTANCE_KM);return t.fragments.some(s=>Math.min(s.absoluteMagnitude,...(s.lightCurve??[]).map(a=>a.absoluteMagnitude))+i<=Ct.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const i=[];for(const s of t)s.fragments.forEach((n,a)=>{const r=Ct.piecesOf(s).find(l=>l.id===(n.id??String(a)));if(!r)return;const o=(n.lightCurve??[]).filter((l,h,u)=>(h===0||u[h-1].absoluteMagnitude>=l.absoluteMagnitude)&&(h===u.length-1||u[h+1].absoluteMagnitude>l.absoluteMagnitude)).map(l=>({t:l.t,magnitude:l.absoluteMagnitude}));o.push({t:r.untilT,magnitude:r.magnitudeAt(r.untilT)});for(const l of o){if(l.magnitude>Ct.DETONATING_MAGNITUDE||l.t<r.fromT||l.t>r.untilT)continue;const h=Ct.pieceAt(s,r,l.t);if(!h||h.heightM>Ct.AUDIBLE_BELOW_KM*1e3||i.some(d=>d.flashT===l.t&&d.reentryId===s.id))continue;const u=Ct.seenFrom(e,h).distanceKm;i.push({reentryId:s.id,flashT:l.t,t:l.t+u/Ct.SOUND_KM_S*1e3,distanceKm:u,loudness:Math.min(1,(.3+(Ct.DETONATING_MAGNITUDE-l.magnitude)/15)*Math.min(1,30/u))})}});return i.sort((s,n)=>s.t-n.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const i=t.lightCurve;if(!i||i.length===0)return t.absoluteMagnitude;if(e<=i[0].t)return i[0].absoluteMagnitude;for(let s=1;s<i.length;s++){const n=i[s-1],a=i[s];if(e<=a.t)return n.absoluteMagnitude+(a.absoluteMagnitude-n.absoluteMagnitude)*(e-n.t)/Math.max(a.t-n.t,1)}return i[i.length-1].absoluteMagnitude}static viewsAt(t,e,i){const s=[];for(const n of t)for(const a of Ct.piecesOf(n)){if(e<a.fromT||e>a.untilT)continue;const r=Ct.pieceAt(n,a,e);if(!r)continue;const o=Ct.seenFrom(i,r);if(o.altitudeDeg<0)continue;const l=Math.min(Ct.FADE_MS,(a.untilT-a.fromT)/4),h=l>0?Math.min(1,(e-a.fromT)/l,(a.untilT-e)/l):1,u=a.magnitudeAt(e)+5*Math.log10(o.distanceKm/Ct.STANDARD_DISTANCE_KM),d=u+(1-h)*Math.max(0,Ct.FADED_MAGNITUDE-u),f=[o];for(let p=1;p<=Ct.TRAIN_POINTS;p++){const g=Math.min(a.trainMs*p/Ct.TRAIN_POINTS,e-a.fromT),m=Ct.pieceAt(n,a,e-g);if(!m||(f.push(Ct.seenFrom(i,m)),g>=e-a.fromT))break}s.push({reentryId:n.id,fragmentId:a.id,head:o,magnitude:d,fade:h,color:a.color,train:f})}return s}static piecesOf(t){const e=Ct.pieces.get(t);if(e)return e;const i=t.track[0]?.t??0,s=t.track[t.track.length-1]?.t??0,n=[];return t.fragments.forEach((a,r)=>{const o=(a.lagS??0)*1e3,l={id:a.id??String(r),fromT:a.fromT??i,untilT:a.untilT??s,lagMsAt:()=>o,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>Ct.absoluteMagnitudeAt(a,h),color:a.color??Ct.DEFAULT_COLOR,trainMs:(a.trainS??Ct.DEFAULT_TRAIN_S)*1e3};n.push(l),Ct.shedsOf(a).forEach((h,u)=>n.push(...Ct.shedPieces(l,h,u)))}),Ct.pieces.set(t,n),n}static pieces=new WeakMap;static shedPieces(t,e,i=0){const s=e.fromT??t.fromT,n=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||n<=s)return[];const a=Math.floor((n-s)/1e3*e.perS),r=e.spreadKmS??.3,o=e.sinkKmS??.3,l=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let u=0;u<a;u++){const d=E=>Ct.hash(`${t.id}/${i}/${u}/${E}`),f=s+(u+d(1))/e.perS*1e3,p=e.lifeS*(.4+1.2*d(2))*1e3,g=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),m=e.dropBack*(.5+d(4)),v=r*(2*d(5)-1),M=o*(.5+d(6)),x=t.lagMsAt(f),y=t.acrossKmAt(f),w=t.belowKmAt(f),S=E=>Math.max(0,E-f)/1e3;h.push({id:`${t.id}.${i}.${u}`,fromT:f,untilT:Math.min(f+p,Ct.endOf(t)),lagMsAt:E=>x+1e3*Ct.lagOfBraking(2*m,S(E)),acrossKmAt:E=>y+v*S(E),belowKmAt:E=>w+M*S(E),magnitudeAt:E=>t.magnitudeAt(Math.min(E,t.untilT))+g,color:t.color,trainMs:l})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,i){const s=i-e.lagMsAt(i),n=Ct.leadAt(t,s);if(!n)return;const a=e.acrossKmAt(i),r=n.heightM-e.belowKmAt(i)*1e3;if(a===0)return{...n,heightM:r};const o=Ct.leadAt(t,s-1e3)??n;return{...Ct.across(o,n,a),heightM:r}}static across(t,e,i){const s=Ct.DEG,n=t.lat*s,a=e.lat*s,r=(e.lng-t.lng)*s,o=Math.atan2(Math.sin(r)*Math.cos(a),Math.cos(n)*Math.sin(a)-Math.sin(n)*Math.cos(a)*Math.cos(r))+Math.PI/2,l=i/6371,h=Math.asin(Math.sin(a)*Math.cos(l)+Math.cos(a)*Math.sin(l)*Math.cos(o)),u=e.lng*s+Math.atan2(Math.sin(o)*Math.sin(l)*Math.cos(a),Math.cos(l)-Math.sin(a)*Math.sin(h));return{lat:h/s,lng:u/s}}static seenFrom(t,e){const i=Ct.ecef(t),s=Ct.ecef(e),n=s[0]-i[0],a=s[1]-i[1],r=s[2]-i[2],o=t.lat*Ct.DEG,l=t.lng*Ct.DEG,h=-Math.sin(l)*n+Math.cos(l)*a,u=-Math.sin(o)*Math.cos(l)*n-Math.sin(o)*Math.sin(l)*a+Math.cos(o)*r,d=Math.cos(o)*Math.cos(l)*n+Math.cos(o)*Math.sin(l)*a+Math.sin(o)*r,f=Math.hypot(h,u,d);return{altitudeDeg:Math.asin(d/f)/Ct.DEG,azimuthDeg:(Math.atan2(h,u)/Ct.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*Ct.DEG,i=t.lng*Ct.DEG,s=Math.sin(e),n=Ct.A/Math.sqrt(1-Ct.E2*s*s);return[(n+t.heightM)*Math.cos(e)*Math.cos(i),(n+t.heightM)*Math.cos(e)*Math.sin(i),(n*(1-Ct.E2)+t.heightM)*s]}static alongGreatCircle(t,e,i){const s=h=>{const u=h.lat*Ct.DEG,d=h.lng*Ct.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},n=s(t),a=s(e),r=Math.max(-1,Math.min(1,n[0]*a[0]+n[1]*a[1]+n[2]*a[2])),o=Math.acos(r);let l;if(o<1e-12)l=n;else{const h=Math.sin((1-i)*o)/Math.sin(o),u=Math.sin(i*o)/Math.sin(o);l=[n[0]*h+a[0]*u,n[1]*h+a[1]*u,n[2]*h+a[2]*u]}return[Math.atan2(l[2],Math.hypot(l[0],l[1]))/Ct.DEG,Math.atan2(l[1],l[0])/Ct.DEG]}}class _l{static typed=new Map;static of(t){return _l.typed.get(t)}static set(t,e){const i=e.trim();i===""?_l.typed.delete(t):_l.typed.set(t,i)}static forget(){_l.typed.clear()}}class iv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=iv.FIRST_DAY}}class ox{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,s){try{return await(await this.provider()).between(t,e,i,s)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const xO="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",wO="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",cx="flightradar24",bO=rs.point("aircraft").provide(rs.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new ox(xO,c=>iv.mayCover(c),async()=>new(await Ht(async()=>{const{AdsbLolArchiveProvider:c}=await import("./AdsbLolArchiveProvider-DXRO-h2K.js");return{AdsbLolArchiveProvider:c}},__vite__mapDeps([38,1,2,3,4,5,6,7]),import.meta.url)).AdsbLolArchiveProvider)},{id:cx,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new ox(wO,c=>c>=Date.UTC(2016,4,11)&&c<=Date.now(),async()=>new(await Ht(async()=>{const{Flightradar24Provider:c}=await import("./Flightradar24Provider-C8Uj-qTs.js");return{Flightradar24Provider:c}},__vite__mapDeps([39,1,2,3,4,5,6,7]),import.meta.url)).Flightradar24Provider({token:()=>_l.of(cx)}))}]);class Ss{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const s=Ss.positionAt(t,i);if(!s)return;const n=Ct.seenFrom(e,s.geo);if(!(n.altitudeDeg<0))return{track:t,sky:n,altitudeFt:s.altitudeFt,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg,angularRateDegPerS:Ss.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(s=>Ss.seenFrom(s,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,s=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*Ss.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(s)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let s=0;for(;s<i.length-1&&i[s+1].t<=e;)s++;const n=i[s],a=i[s+1]??n,r=a.t-n.t;if(r>Ss.MAX_GAP_S*1e3)return;const o=r>0?(e-n.t)/r:0,l=n.altitudeFt+(a.altitudeFt-n.altitudeFt)*o,h=(a.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(a.lat-n.lat)*o,lng:Ss.wrapLongitude(n.lng+h*o),heightM:l*Ss.FT_TO_M},altitudeFt:l,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(t,e,i){const s=Ss.positionAt(t,i-500),n=Ss.positionAt(t,i+500);if(!s||!n)return;const a=Ss.unit(Ct.seenFrom(e,s.geo)),r=Ss.unit(Ct.seenFrom(e,n.geo)),o=Math.min(1,Math.max(-1,a[0]*r[0]+a[1]*r[1]+a[2]*r[2]));return Math.acos(o)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const lx="https://ufoathome.org/fireballs/index.json";class Xa{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Xa.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(lx)||t.push(lx),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Xa.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Xa.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const s=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...s].some(a=>a>=i.index.from&&a<=i.index.to)?(await Promise.all([...s].filter(a=>i.index.months.includes(a)).map(a=>this.monthOf(a,i.base)))).flat().filter(a=>a.t>=t&&a.t<=e):void 0}static seenFrom(t,e){const i=Xa.peakFraction(t),s={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},n=Ct.seenFrom(e,s);if(!(n.altitudeDeg<0))return{record:t,peak:n,magnitude:t.peakMagnitude+5*Math.log10(n.distanceKm/Ct.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,s=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:s,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Xa.COLOR,trainS:Xa.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(s=>s.ok?s.json():[]).catch(()=>[]),this.months.set(t,i)),i}}fw();const Hb="satellites-change",Gb="fireballs-change",Vb="references-change",Wb="aircraft-change",Xb="rr0-confrontation",hx="comet:",ux="nova:",SO=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,EO=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,AO=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,_O=-18,TO={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Jd={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class me extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Cl,Ol,Xo]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;approaches={key:"",of:new Map};distanceHypotheses=new Map;depths=new Map;directionScratch=new _;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Vs;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Xa;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=bO[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return me.trafficRuntimeLoading??=Ht(()=>import("./trafficRuntime-DvKPyJcx.js"),__vite__mapDeps([40,32,41,1,5,2,3,4,6,7]),import.meta.url).then(t=>me.trafficRuntime=t),me.trafficRuntimeLoading.catch(()=>{me.trafficRuntimeLoading=void 0}),me.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new tc;vehicleAudio=new _y;aircraftAudio;vehicleHearing=new Uf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;decorModelsAsked=new Set;thunderTimeoutId;handleFullscreenChange=()=>{this.resizeToStage(),this.hoverTooltip.hidden=!0;for(const t of[this.hoverTooltip,this.shadow.getElementById("credits-panel")])t&&typeof t.hidePopover=="function"&&t.matches(":popover-open")&&t.hidePopover();this.tooltipOver=document.fullscreenElement};handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const s=(t.clientX-i.left)/i.width*2-1,n=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(s,n)?this.sceneRenderer.pickGhostAt(s,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>me.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;tooltipOver=null;hoverAt(t){if(this.showCompassFor({hovered:!0}),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(t.clientX-i.left)/i.width*e.width,n=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(s,n)){this.hoverTooltip.hidden=!0;return}const a=(t.clientX-i.left)/i.width*2-1,r=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(a,r))return;const o=this.pickAt(a,r,!0,t.altKey);o?this.showHoverTooltip(t,t.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),s=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),n=s(t.from),a=s(t.to),r=s({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,l,h,u]=Array.from(this.ghostPath.children);for(const d of[o,l])d.setAttribute("x1",String(n.x)),d.setAttribute("y1",String(n.y)),d.setAttribute("x2",String(a.x)),d.setAttribute("y2",String(a.y));h.setAttribute("cx",String(r.x)),h.setAttribute("cy",String(r.y)),u.setAttribute("cx",String(a.x)),u.setAttribute("cy",String(a.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,s=!1){const n=this.naming,a=n.names;if(s&&this.sceneRenderer.pickDropAt(t,e)){const S=a.ghostTooltip,E=S.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:E,detail:()=>S.dropDetail.replace("{name}",E)}}const r=this.sceneRenderer.pickBodyAt(t,e);if(r)return{kind:"sky",id:r,name:this.bodyName(r)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=o?this.interpretationShown?.bodies.find(S=>S.id===o):void 0,h=l?this.said.read(l.title)||this.explainedName(l.explains)||this.kindName(l):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const u=this.skyEventPickAt(t,e,(S,E)=>!E.inSky);if(u)return u;const d=i?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const S=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:S.name,detail:()=>S.detail.replace("{name}",S.name)}}const f=this.pickDecorAt(t,e)??this.sceneRenderer.pickPeakAt(t,e),p=f?this.ufoElement.sighting.decor.find(S=>S.id===f):void 0;if(p){const S=this.said.read(p.title)||n.decorKind(p.kind);return{kind:"decor",id:p.id,name:S,detail:()=>this.decorTooltip(p,S)}}const g=this.sceneRenderer.pickRailwayAt(t,e);if(g){const S=a.railwayTooltip;return{kind:"railway",id:g.line.id,name:ka.name(g.line,S),detail:()=>ka.detail(g,S,E=>this.distanceText(E))}}const m=this.trafficTooltipAt(t,e);if(m)return{kind:"traffic",name:m};const v=this.skyEventPickAt(t,e,(S,E)=>E.inSky===!0&&!S.pickedAfterSatellites);if(v)return v;const M=this.sceneRenderer.pickSatelliteAt(t,e);if(M)return{kind:"satellite",name:a.satelliteTooltip.replace("{name}",M.name).replace("{mag}",M.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(M.heightKm).toLocaleString())};const x=this.skyEventPickAt(t,e,(S,E)=>E.inSky===!0&&S.pickedAfterSatellites===!0);if(x)return x;const y=this.sceneRenderer.pickOpticsAt(t,e);if(y){const S=a.opticsTooltips[y.id].replace("{angle}",String(Math.round(y.angleDeg??0)));return{kind:"optics",id:y.id,name:S.split(" — ")[0],detail:()=>S}}const w=this.sceneRenderer.pickStarAt(t,e);if(w){const S=w.star.mag,E=w.altitudeDeg,b=E<0?a.starTooltipBelow:a.starTooltip,A=n.star(w.star);return{kind:"star",name:A,detail:()=>b.replace("{name}",A).replace("{mag}",S.toLocaleString(void 0,{maximumFractionDigits:Math.abs(S)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(E))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,s={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},n=`${Math.round(t/s.x)}:${Math.round(e/s.y)}`,a=performance.now(),r=this.ghostLights.get(n);if(r&&a-r.atMs<me.GHOST_LIGHT_KEPT_MS)return r.light;let o=this.shiningDecorNear(t,e,2*Math.max(s.x,s.y)),l;if(!o)for(const[h,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*s.x,e+u*s.y,!1);if(d?.kind==="star")l??=d;else if(d){o=d;break}}return o??=this.shiningDecorNear(t,e,6*Math.max(s.x,s.y)),o??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:o??null,atMs:a}),o??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const s=this.naming.names.ghostTooltip,n=i.beyond?{kind:"sky",id:"sun",name:this.bodyName("sun")}:this.lightOfGhost(i.source.x,i.source.y)??void 0,a=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??s.unnamed,r=i.ghost,l=(Pe.scatters(r)?s.halo:r.cause==="glass"?s.double:s.ghost).replace("{name}",a),h=r.scale<0?s.opposite:r.scale===1?s.around:s.sameSide;return{kind:"ghost",id:n?.id,name:l,detail:()=>s.detail.replace("{name}",l).replace("{cause}",s.causes[r.cause??"lens"]).replace("{where}",h),path:{from:{x:2*(r.offset?.[0]??0)+r.scale*i.source.x,y:2*(r.offset?.[1]??0)+r.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let s;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const r=this.sceneRenderer.decorScreenBox(n.id);if(!r)continue;const o=Math.hypot(Math.max(r.minX-t,0,t-r.maxX),Math.max(r.minY-e,0,e-r.maxY));if(o>i||s&&o>=s.distance)continue;const l=this.said.read(n.title)||this.naming.decorKind(n.kind);s={distance:o,pick:{kind:"decor",id:n.id,name:l}}}return s?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new Yo(s=>{if(!Pe.records(t.instrument)||!Pe.falling(t.lens))return 0;const n=th(t,s*1e3),a=Te(t,s*1e3);return(n.precipitationAmount??1)*Pe.impactRate(n,t.lens?.glass,a&&{headingDeg:a.headingDeg??0,pitchDeg:a.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,i=this.fireballs?.reentries,s=this.skyEventsMerged;if(s&&s.stated===e&&s.fireballs===i)return s.shown;const n=i?.length?{...e,reentries:[...e?.reentries??[],...i]}:e;return this.skyEventsMerged={stated:e,fireballs:i,shown:n},n}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=zh(Sr.preferencesFor(this),Bh);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const i of t)this.skyEventTexts.has(i)||i.messages.load(e).then(s=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(i,s)},()=>{})}skyEventPickAt(t,e,i){const s=this.skyEventsShown;if(!s)return;const n=this.sceneRenderer.pickSkyEventAt(t,e,i),a=n?zg.map(d=>Rr.of(d)).find(d=>d.key===n.kind):void 0,r=n&&a?Rr.eventsOf(s,a).find(d=>d.id===n.id):void 0;if(!n||!a||!r)return;const o=this.skyEventTexts.get(a);if(!o){this.loadSkyEventTexts([a]);return}const l=this.said.read(r.title)||o.name,h=a.describe?.(r,n,{said:this.said,texts:o,name:l,distance:d=>this.distanceText(d)}),u=h?.detail??(n.distanceM!==void 0?`${l}, ${this.distanceText(n.distanceM)}`:void 0);return{kind:a.pickKind??"skyEvent",id:r.id,name:h?.name??l,...u!==void 0?{detail:()=>u}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),s=ht.sizeOf(t),n=this.sceneRenderer.decorDistanceM(t.id),a=n===void 0?"":this.distanceText(n),o=this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${i(s.widthM)} × ${i(s.lengthM)} × ${i(s.heightM)} m`),l=this.said.read(t.note);return l?`${o.replace("{distance}",a)}. ${l}`:o.replace("{distance}",a)}computedKinds=new Map;computedKindTexts=new Map;bodyModelKinds=new Map;showInterpretation(t){const e=E0.kinds(),i=this.obstaclesOf(this.ufoElement.sighting.decor);this.interpretationObstacles=i;const{interpretation:s,kindOf:n}=Ur.expandWithKinds(t,e,{obstacles:i});if(this.interpretationAsked=t,this.interpretationShown=s,this.computedKinds=n,this.loadComputedKindTexts(),Ur.loaded(t,e))return;const a=Ur.load(t,e);this.sceneRenderer.holdUntil(a),a.then(()=>{this.interpretationAsked!==t||!Ur.loaded(t,e)||(this.showInterpretation(t),this.ufoElement.refreshSoundControls(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())})}interpretationAsked;interpretationObstacles=yv.NONE;obstaclesMadeOf;obstaclesOf(t){return this.obstaclesMadeOf?.decor!==t&&(this.obstaclesMadeOf={decor:t,obstacles:yv.of(t,e=>ht.sizeOf(e))}),this.obstaclesMadeOf.obstacles}recomputeAmongNewDecor(){const t=this.interpretationAsked;!t||!Ur.computes(t,E0.kinds())||this.obstaclesOf(this.ufoElement.sighting.decor).signature!==this.interpretationObstacles.signature&&(this.showInterpretation(t),this.ufoElement.refreshSoundControls())}computedInterpretation(t){const e=E0.kinds(),i=Ur.loaded(t,e)?Promise.resolve():Ur.load(t,e),{interpretation:s,phenomenonOf:n}=Ur.expandWithKinds(t,e,{obstacles:this.obstaclesOf(this.ufoElement.sighting.decor)});return{interpretation:s??t,phenomenonOf:n,loaded:i}}loadComputedKindTexts(){const t=this.namesLanguage;if(t)for(const e of new Set(this.computedKinds.values()))this.computedKindTexts.has(e)||e.messages.load(t).then(i=>{t===this.namesLanguage&&this.computedKindTexts.set(e,i)}).catch(()=>{})}kindName(t){const e=this.computedKinds.get(t.id),i=e?this.computedKindTexts.get(e):void 0;if(i?.name)return i.name;const s=t.model.id;if(s==="figure")return this.naming.decorKind("entity");if(!s||t.model.url!==void 0)return;if(!this.bodyModelKinds.has(s)){this.bodyModelKinds.set(s,void 0),this.sceneRenderer.entryOfDecorModel(s).then(a=>this.bodyModelKinds.set(s,[a?.kind].flat()[0])).catch(()=>{});return}const n=this.bodyModelKinds.get(s);return n&&this.naming.decorKind(n)||void 0}explainedName(t){if(!t?.length)return;const e=this.ufoElement.sighting.timeline.allKeyframes,i=t.map(s=>{for(const n of e){const a=this.said.read(n.shapes.find(r=>r.sourceId===s)?.shape.title);if(a)return a}}).filter(s=>!!s);return i.length?i.join(", "):void 0}bodyName(t){const e=t.startsWith(hx)?t.slice(hx.length):void 0,i=e?Bb.find(n=>n.id===e):void 0;if(i)return this.naming.comet(i);const s=t.startsWith(ux)?nx.byId(t.slice(ux.length)):void 0;return s?this.naming.nova(s):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new Q2;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=zh(Sr.preferencesFor(this),Bh);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await eS(t);t===this.namesLanguage&&(this.applySceneNaming(new Q2(e)),this.computedKindTexts.clear(),this.loadComputedKindTexts())}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const s=(n,a)=>{n.setAttribute("aria-label",a),n.replaceChildren(),a.split(" ").forEach((r,o)=>{o>0&&n.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of r){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}n.append(l),i++})};s(this.loaderNotVideo,t),i+=6,s(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const i=this.hoverTooltip;if(i.textContent=e,i.hidden=!1,typeof i.showPopover=="function"){const u=document.fullscreenElement;i.matches(":popover-open")&&u!==this.tooltipOver&&i.hidePopover(),i.matches(":popover-open")||i.showPopover(),this.tooltipOver=u}const{innerWidth:s,innerHeight:n}=window,a=12,r=4,o=Math.min(t.clientX+a,s-i.offsetWidth-r),l=t.clientY+a,h=l+i.offsetHeight+r>n?t.clientY-a-i.offsetHeight:l;i.style.left=`${Math.max(r,o)}px`,i.style.top=`${Math.max(r,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.showCompassFor({hovered:!1})};hearDetonations(t,e,i,s){const n=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,a=this.detonationsFor;(!a||n!==a.key||t.length!==a.reentries.length||t.some((l,h)=>l!==a.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:n,detonations:t.length?Ct.detonationsOf(t,i):[]});const r=this.detonationsFor.detonations;if(s)return;const o=this.lastDetonationT;if(this.lastDetonationT=e,!(o===void 0||e<o||e-o>me.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of r)l.t>o&&l.t<=e&&this.weatherAudio.playDetonation(l.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=Te(t,0),s=t.event.place?.[0],n=i?.lat??s?.lat,a=i?.lng??s?.lng;return e.length>0&&n!==void 0&&a!==void 0&&Ct.detonationsOf(e,{lat:n,lng:a,heightM:this.altitudeOf(i)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){if(clearTimeout(this.thunderTimeoutId),this.filmSound){this.filmThunderAtMs=this.lastTimeMs+is.thunderDelayMs(t)*this.ufoElement.playbackRate;return}this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),is.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(th(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){if(this.filmSound)return;const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=me.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing",e=t||this.filming;this.sceneRenderer.setAnimationsRunning(e,e);const i=t||this.filmSound!==void 0;this.weatherAudio.setPaused(!i),this.vehicleAudio.setPaused(!i),this.aircraftAudio?.setPaused(!i),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${xI}</style>${yI}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new ct(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(Vb));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new ou(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(Nm),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=n=>this.snapshotMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),s=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",n=>{n.newState==="open"&&Hs.fill(s,this)}),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(pw,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,a)=>this.seekPreviewOf(a).paint(n,a),typeof VideoEncoder<"u"&&typeof OffscreenCanvas<"u"&&(this.ufoElement.filmer={film:(n,a,r)=>this.film(n,a,r),generativeKit:(n,a,r)=>this.generativeKit(n,a,r),fileName:()=>this.filmFileName(),kitFileName:()=>this.filmFileName().replace(/\.mp4$/," - kit.zip"),pictureSize:()=>this.filmPictureSize(),hasMap:()=>this.ufoElement.hasObserverMap,durationS:()=>this.ufoElement.seekableDuration/this.filmRate()/1e3,positionS:()=>this.ufoElement.currentTime/this.filmRate()/1e3}),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(a=>a.engine!==void 0)||n.decor.some(a=>gv.kindOf(a,this.decorModelSounds.get(a.model?.id??""))!==void 0)||this.interpretationShown?.bodies.some(a=>a.sound)===!0||n.weatherTrack.allKeyframes.some(a=>a.weather.precipitationType!=="none"||a.weather.windSpeed>1)||this.detonates(n)||(this.traffic?.audible?.size??0)>0,this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of me.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new lu(Sr.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return!i||!Os.isRoad(i.kind)?void 0:{setting:mm.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}}travelHeadingAt(t,e){const i=Te(t,e);if(!i)return 0;for(const s of[400,-400]){const n=Te(t,e+s);if(!n||i.lat===void 0||i.lng===void 0||n.lat===void 0||n.lng===void 0)break;const a=re(n.lat,n.lng,i.lat,i.lng);if(Math.hypot(a.x,a.z)<.8)continue;return(Math.atan2(a.x,-a.z)*180/Math.PI+(s<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),s=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:s},s}traceLabels(t){const e=Sr.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const s of t){const n=this.said.read(s.title);n&&i.set(s.id,n)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){rs.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of me.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){rs.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of me.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const s=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(s)&&s>0?s:Math.min(window.devicePixelRatio||1,2))}(t===Cl||t===Ol||t===Xo)&&i!==e&&this.forwardPlayerAttributes(),t===Xo&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Cl,Ol,Xo]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.showCompassFor({forced:t})}compassHovered=!1;compassForced=!1;showCompassFor(t){this.compassHovered=t.hovered??this.compassHovered,this.compassForced=t.forced??this.compassForced,this.sceneRenderer.setCompassForced(this.compassForced||this.compassHovered)}lookToward(t){const e=Te(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:s}=re(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,s)<1)return this.setLookOffset(0,0);const n=(Math.atan2(i,-s)*180/Math.PI+360)%360;this.setLookOffset(((n-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setOutsideHeard(Os.transmission(this.ufoElement.sighting.vehicle)),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed);const e=this.ufoElement.sighting.around;this.weatherAudio.setAround(pi.aroundBedRms(e),pi.aroundBedShape(e)??[])}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,s=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,s)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=dx.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=s1.recording(t);this.ufoElement.playerTitle=void 0,this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.showInterpretation(this.inTheRound?this.ufoElement.sighting.interpretation:void 0),this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,i=Ht(async()=>{const{ModuleSession:s}=await import("./ModuleSession-D4LhYKvL.js");return{ModuleSession:s}},__vite__mapDeps([42,1,2,3,4,5,6,7]),import.meta.url).then(({ModuleSession:s})=>s.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new Ib));this.sceneRenderer.holdUntil(i)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new Jf(this,()=>document.createElement(i0))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}filmName;filmFileName(){return`${(this.filmName??"").replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim()||"observation"}.mp4`}filming=!1;async film(t,e,i){const[{VideoExport:s},{FilmChrome:n}]=await Promise.all([Ht(()=>import("./VideoExport-B8ZhHNnd.js").then(r=>r.a),[],import.meta.url),Ht(()=>import("./FilmChrome-DYiyzoB_.js"),[],import.meta.url)]),a=await n.loadLogo();return this.filmScene(t,r=>s.film({...r,frameAt:(o,l,h)=>r.frameAt(o,l,h)?(n.paint(h,this.ufoElement.filmChrome(t),a),!0):!1},e,i))}async generativeKit(t,e,i){const[{GenerativeKit:s},{generativeKitMessages:n},{toSightingJson:a}]=await Promise.all([Ht(()=>import("./GenerativeKit-BmhvjjzB.js"),__vite__mapDeps([43,44,45]),import.meta.url),Ht(()=>import("./GenerativeKitMessages-BwG7cWZX.js"),__vite__mapDeps([46,1]),import.meta.url),Ht(()=>Promise.resolve().then(()=>FE),void 0,import.meta.url)]),r=zh(Sr.preferencesFor(this),Bh),[o]=await Promise.all([n.load(r),this.sceneRenderer.loadControlPasses()]),l=this.sceneRenderer.areReferencesShown;this.sceneRenderer.setReferencesShown(!1);try{return await this.filmScene({...t,caption:!1,time:!1,map:!1},h=>s.make({film:h,drawControlPasses:()=>this.sceneRenderer.drawControlPasses(),recording:a(this.ufoElement.sighting),title:this.filmName??"",source:h.about?.source,language:r},o,e,i))}finally{this.sceneRenderer.setReferencesShown(l)}}async filmScene(t,e){if(this.filming)throw new Error("Already filming");const i=this.ufoElement,s=i.currentTime;i.pause();const n={width:this.sceneCanvas.clientWidth,height:this.sceneCanvas.clientHeight},a=t.height&&n.height>0?t.height/n.height:this.sceneRenderer.maxPixelRatio;this.filming=!0,this.sceneRenderer.holdPixelRatio(a),i.filmMap(t.map),this.syncAnimationsToPlayback();try{const r=t.height??this.sceneCanvas.height,o=t.height&&n.height>0?Math.round(t.height*n.width/n.height):this.sceneCanvas.width,l=this.filmRate(),h=Math.min(i.seekableDuration,t.toS!==void 0?t.toS*1e3*l:i.seekableDuration),u=Math.min(h,Math.max(0,(t.fromS??0)*1e3*l));return await e({fromMs:u,toMs:h,rate:l,width:o,height:r,frameAt:(d,f,p)=>this.filmFrameAt(d,f,p),hearInto:d=>this.hearInto(d),about:{title:this.filmName,description:i.filmDescription,source:this.documentUrl?new URL(this.documentUrl,location.href).href:void 0}})}finally{this.filming=!1,this.sceneRenderer.holdPixelRatio(void 0),i.filmMap(void 0),i.currentTime=s,this.syncAnimationsToPlayback()}}filmRate(){const t=this.ufoElement.playbackRate;return t>0?t:1}filmPictureSize(){const t=this.sceneRenderer.maxPixelRatio;return{width:Math.round(this.sceneCanvas.clientWidth*t),height:Math.round(this.sceneCanvas.clientHeight*t)}}filmSound;liveSound;filmThunderAtMs;hearInto(t){if(t){this.liveSound??={weather:this.weatherAudio,vehicle:this.vehicleAudio,aircraft:this.aircraftAudio},this.filmSound=t,this.weatherAudio=new tc(t),this.vehicleAudio=new _y(t);const e=me.trafficRuntime;this.aircraftAudio=this.liveSound.aircraft&&e?this.newAircraftAudio(e):void 0}else this.liveSound&&(this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.weatherAudio=this.liveSound.weather,this.vehicleAudio=this.liveSound.vehicle,this.aircraftAudio=this.liveSound.aircraft,this.liveSound=void 0,this.filmSound=void 0,this.filmThunderAtMs=void 0);this.ufoElement.hearInto(t),this.syncAnimationsToPlayback()}filmFrameAt(t,e,i){this.ufoElement.currentTime!==t&&(this.ufoElement.currentTime=t),this.filmThunderAtMs!==void 0&&t>=this.filmThunderAtMs&&(this.filmThunderAtMs=void 0,this.weatherAudio.playThunder()),this.sceneRenderer.render();const s=this.sceneRenderer.framesDrawn;return this.sceneRenderer.frame(e),this.sceneRenderer.framesDrawn===s?!1:(i.drawImage(this.sceneCanvas,0,0,i.canvas.width,i.canvas.height),!0)}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}horizonPointAt(t){const e=t*Math.PI/180,i=this.sceneRenderer.screenPointOf(new _(Math.sin(e),0,-Math.cos(e)));return i&&{x:(i.ndcX+1)/2,y:(1-i.ndcY)/2}}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=jd.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
8992
|
+
`);let n=Oa.cache.get(s);return n||(n=Promise.all(i.map(a=>Oa.load(a.url))).then(a=>a.reduce((r,o)=>Oa.concat(r,o))),Oa.cache.set(s,n)),n}static parse(t){const e=t.byteLength/(4*Float32Array.BYTES_PER_ELEMENT),i=e*Float32Array.BYTES_PER_ELEMENT;return{count:e,ra:new Float32Array(t,0*i,e),dec:new Float32Array(t,1*i,e),mag:new Float32Array(t,2*i,e),ci:new Float32Array(t,3*i,e)}}static concat(t,e){const i=(s,n)=>{const a=new Float32Array(s.length+n.length);return a.set(s,0),a.set(n,s.length),a};return{count:t.count+e.count,ra:i(t.ra,e.ra),dec:i(t.dec,e.dec),mag:i(t.mag,e.mag),ci:i(t.ci,e.ci)}}}class ei{constructor(t){if(this.heights=t,t.length!==ei.WIDTH*ei.HEIGHT)throw new Error(`a lunar relief has ${ei.WIDTH*ei.HEIGHT} samples, not ${t.length}`)}static SAMPLES_PER_DEGREE=16;static WIDTH=360*ei.SAMPLES_PER_DEGREE;static HEIGHT=180*ei.SAMPLES_PER_DEGREE;static UNIT_KM=.1;static REFERENCE_RADIUS_KM=1737.4;static BAND_FROM_DEG=74;static BAND_TO_DEG=106;heightKm(t,e){const i=ei.SAMPLES_PER_DEGREE,s=(e%360+360)%360*i-.5,n=(90-t)*i-.5,a=Math.floor(s),r=Math.floor(n),o=s-a,l=n-r,h=(f,p)=>{const g=(f%ei.WIDTH+ei.WIDTH)%ei.WIDTH,m=Math.min(ei.HEIGHT-1,Math.max(0,p));return this.heights[m*ei.WIDTH+g]},u=h(a,r)*(1-o)+h(a+1,r)*o,d=h(a,r+1)*(1-o)+h(a+1,r+1)*o;return(u*(1-l)+d*l)*ei.UNIT_KM}static inBand(t,e){const i=Math.PI/180,s=Math.acos(Math.cos(t*i)*Math.cos(e*i))*180/Math.PI;return s>=ei.BAND_FROM_DEG&&s<=ei.BAND_TO_DEG}static withBump(t,e,i,s=.4){const n=new Int8Array(ei.WIDTH*ei.HEIGHT),a=ei.SAMPLES_PER_DEGREE,r=Math.ceil(s*a),o=Math.floor(e*a),l=Math.floor((90-t)*a);for(let h=-r;h<=r;h++)for(let u=-r;u<=r;u++)Math.hypot(u,h)<=r&&(n[(l+h)*ei.WIDTH+(o+u+ei.WIDTH)%ei.WIDTH]=Math.round(i/ei.UNIT_KM));return new ei(n)}static smooth(){return new ei(new Int8Array(ei.WIDTH*ei.HEIGHT))}}class Zn{static SAMPLES=5760;static SEARCH_FROM_DEG=87;static SEARCH_TO_DEG=90.2;static SEARCH_STEP_DEG=.0625;static profile(t,e,i,s=Zn.SAMPLES){const{s:n,u:a,w:r,distanceKm:o}=Zn.frame(t,e),l=Math.PI/180,h=new Float32Array(s),u=ei.REFERENCE_RADIUS_KM;for(let d=0;d<s;d++){const f=d/s*2*Math.PI,p=Math.cos(f),g=Math.sin(f),m=p*a[0]+g*r[0],v=p*a[1]+g*r[1],M=p*a[2]+g*r[2];let x=0;for(let y=Zn.SEARCH_FROM_DEG;y<=Zn.SEARCH_TO_DEG;y+=Zn.SEARCH_STEP_DEG){const w=Math.cos(y*l),S=Math.sin(y*l),E=w*n[0]+S*m,b=w*n[1]+S*v,A=w*n[2]+S*M,T=Math.asin(Math.max(-1,Math.min(1,A)))/l,D=Math.atan2(b,E)/l,I=u+i.heightKm(T,D),C=Math.atan2(I*S,o-I*w);C>x&&(x=C)}h[d]=x/l}return{radiusDeg:h,meanRadiusDeg:Math.asin(u/o)/l}}static frame(t,e){const i=new Mo(e.lat,e.lng,e.elevationM),s=Pr(t),n=Sm(t,i,!1),a=new Fe(n.x-s.x,n.y-s.y,n.z-s.z,s.t),r=Math.hypot(a.x,a.y,a.z)*Zn.AU_KM,o=Zn.bodyFixed(t),l=o(a),h=Math.hypot(l[0],l[1],l[2]),u=[l[0]/h,l[1]/h,l[2]/h],d=fE(t,i),f=d1(d),p=Dr(d,new Fe(-a.x,-a.y,-a.z,s.t)),g=Math.asin(p.z/Math.hypot(p.x,p.y,p.z)),m=Math.atan2(-p.y,p.x),v=new Fe(-Math.sin(g)*Math.cos(m),Math.sin(g)*Math.sin(m),Math.cos(g),s.t),M=new Fe(-Math.sin(m),-Math.cos(m),0,s.t);return{s:u,u:o(Dr(f,v)),w:o(Dr(f,M)),distanceKm:r}}static surfacePoint(t,e,i,s){const{s:n,u:a,w:r}=Zn.frame(t,e),o=Math.PI/180,l=[0,1,2].map(u=>Math.cos(i*o)*a[u]+Math.sin(i*o)*r[u]),h=[0,1,2].map(u=>Math.cos(s*o)*n[u]+Math.sin(s*o)*l[u]);return{latDeg:Math.asin(h[2])/o,lonDeg:Math.atan2(h[1],h[0])/o}}static radiusAt(t,e){const i=t.radiusDeg.length,s=(e/360*i%i+i)%i,n=Math.floor(s),a=s-n;return t.radiusDeg[n]*(1-a)+t.radiusDeg[(n+1)%i]*a}static uncoveredFraction(t,e,i){const s=t.radiusDeg.length,n=i.upDeg*i.upDeg+i.rightDeg*i.rightDeg;let a=0;for(let r=0;r<s;r++){const o=r/s*2*Math.PI,l=Math.cos(o),h=Math.sin(o),u=l*i.upDeg+h*i.rightDeg,d=u*u-n+e*e;if(d<=0)continue;const f=Math.sqrt(d),p=u+f;if(p<=0)continue;const g=Math.max(0,u-f),m=Math.max(g,t.radiusDeg[r]);p>m&&(a+=.5*(p*p-m*m))}return Math.min(1,Math.max(0,a*(2*Math.PI/s)/(Math.PI*e*e)))}static AU_KM=1495978707e-1;static bodyFixed(t){const e=DE(pt.Moon,t),i=Math.PI/180,s=e.ra*15*i,n=e.dec*i,a=e.spin*i,r=(l,[h,u,d])=>[Math.cos(l)*h+Math.sin(l)*u,-Math.sin(l)*h+Math.cos(l)*u,d],o=(l,[h,u,d])=>[h,Math.cos(l)*u+Math.sin(l)*d,-Math.sin(l)*u+Math.cos(l)*d];return l=>r(a,o(Math.PI/2-n,r(Math.PI/2+s,[l.x,l.y,l.z])))}static subObserverPoint(t,e){const i=new Mo(e.lat,e.lng,e.elevationM),s=Pr(t),n=Sm(t,i,!1),a=Zn.bodyFixed(t)(new Fe(n.x-s.x,n.y-s.y,n.z-s.z,s.t)),r=Math.hypot(a[0],a[1],a[2]);return{latDeg:Math.asin(a[2]/r)*180/Math.PI,lonDeg:Math.atan2(a[1],a[0])*180/Math.PI}}}class ru{static cache=new Map;static load(t){let e=ru.cache.get(t);return e||(e=ru.fetchRelief(t).catch(()=>{}),ru.cache.set(t,e)),e}static async fetchRelief(t){const e=await fetch(t);if(!e.ok)return;let i=new Uint8Array(await e.arrayBuffer());if(i[0]===31&&i[1]===139){if(typeof DecompressionStream>"u")return;const s=new Blob([i]).stream().pipeThrough(new DecompressionStream("gzip"));i=new Uint8Array(await new Response(s).arrayBuffer())}return new ei(new Int8Array(i.buffer,i.byteOffset,i.length))}}const tv=fc.catalog({en:()=>Ht(()=>import("./PerceptionMessages_en-B2O6DR64.js"),[],import.meta.url).then(c=>c.perceptionMessages_en),fr:()=>Ht(()=>import("./PerceptionMessages_fr-B59TnGBC.js"),[],import.meta.url).then(c=>c.perceptionMessages_fr),es:()=>Ht(()=>import("./PerceptionMessages_es-BmkP6OqD.js"),[],import.meta.url).then(c=>c.perceptionMessages_es),it:()=>Ht(()=>import("./PerceptionMessages_it-DPlxRmxu.js"),[],import.meta.url).then(c=>c.perceptionMessages_it)});class t0{static ID="color-vision";static MATRICES={protan:[.152286,1.052583,-.204868,.114503,.786281,.099216,-.003882,-.048116,1.051998],deutan:[.367322,.860646,-.227968,.280085,.672501,.047413,-.01182,.04294,.968881],tritan:[1.255528,-.076749,-.178779,-.078411,.930809,.147602,.004733,.691367,.3039]};id=t0.ID;messages=tv;sources=["Machado, Oliveira, Fernandes, A Physiologically-based Model for Simulation of Color Vision Deficiency, IEEE TVCG 15(6), 2009"];settings=[{id:"type",kind:"choice",default:"normal",choices:[{id:"normal"},{id:"protan"},{id:"deutan"},{id:"tritan"}]},{id:"severity",kind:"number",default:100,min:0,max:100,step:5,unit:"%"}];perceive(t){const e=t0.MATRICES[String(t.type)];if(!e)return An.NONE;const i=Number(t.severity??100),s=Math.max(0,Math.min(100,Number.isFinite(i)?i:100))/100;return{colorMatrix:e.map((a,r)=>An.IDENTITY[r]+(a-An.IDENTITY[r])*s),contrastGain:1}}}class ev{static ID="fatigue";id=ev.ID;messages=tv;sources=["Studies of contrast sensitivity during prolonged sleep deprivation (60 hours, naval officers): no significant change"];settings=[{id:"hoursAwake",kind:"number",default:0,min:0,max:72,step:1,unit:"h"}];perceive(t){return An.NONE}}class Ho{static ID="intoxication";static MEASURED_LEVEL=.08;static MEASURED_LOSS_DB=.9;static MAX_EFFECT_LEVEL=.1;static MAX_LEVEL=.5;id=Ho.ID;messages=tv;sources=["Frontiers in Neuroscience, 2022, doi:10.3389/fnins.2022.873671 (contrast sensitivity at about 0.08 % blood alcohol)"];settings=[{id:"bloodAlcohol",kind:"number",default:0,min:0,max:Ho.MAX_LEVEL,step:.01,unit:"%",also:{unit:"g/L",factor:10,digits:1}}];perceive(t){const e=Number(t.bloodAlcohol??0),i=Math.max(0,Math.min(Ho.MAX_EFFECT_LEVEL,Number.isFinite(e)?e:0));if(i===0)return An.NONE;const s=i/Ho.MEASURED_LEVEL*Ho.MEASURED_LOSS_DB;return{colorMatrix:An.IDENTITY,contrastGain:10**(-s/20)}}}const iO=c=>c.sources[0]??c.id,sO=rs.point("perception").provide(rs.BUILT_IN,[new t0,new Ho,new ev].map(c=>({id:c.id,name:c.id,credit:iO(c),creditUrl:"https://ufoathome.org/docs/sources/",create:()=>c})));class Go{static built=new WeakMap;static get ALL(){return sO.map(t=>{let e=Go.built.get(t);return e||(e=t.create(),Go.built.set(t,e)),e})}static byId(t){return Go.ALL.find(e=>e.id===t)}static perceptionOf(t){return Go.ALL.reduce((e,i)=>An.combine(e,i.perceive(t?.[i.id]??{})),An.NONE)}static compact(t){const e={},i=Go.ALL;for(const[s,n]of Object.entries(t))!i.some(a=>a.id===s)&&Object.keys(n??{}).length>0&&(e[s]=n);for(const s of i){const n=t[s.id]??{},a=Object.fromEntries(s.settings.filter(r=>n[r.id]!==void 0&&n[r.id]!==r.default).map(r=>[r.id,n[r.id]]));Object.keys(a).length>0&&(e[s.id]=a)}return Object.keys(e).length>0?e:void 0}}class Q2{names;constructor(t){this.names=t??fc.blank(),this.loaded=t!==void 0}loaded;body(t){return this.names.bodies[t]??t}star(t){return this.names.stars[t.name]??t.name}comet(t){return this.names.comets[t.id]??t.name}nova(t){return this.names.novae[t.id]??t.name}satelliteClass(t){return this.names.satelliteClasses[t.id]??t.name}shower(t){return this.names.showers[t.id]??t.name}lightRig(t){return this.names.lightRigs[t.id]??t.name}instrument(t){return this.names.instruments[t.id]??t.name}decorKind(t){return this.names.decorKinds[t]}point(t){return sc.point(t,this.loaded?this.names.compassPoints:void 0)}towards(t){return sc.towards(t,this.loaded?this.names:void 0)}}class ka{static STANDARD_GAUGE_MM=1435;static METRE_GAUGE_MM=1e3;static kind(t,e){return t.highSpeed?e.highSpeed:t.service?e.service:e.kinds[t.kind]}static name(t,e){const i=t.name??ka.kind(t,e);return t.services?.length?`${i} — ${t.services.join(", ")}`:i}static voltage(t,e){return t>=1e3?`${(t/1e3).toLocaleString(e,{maximumFractionDigits:1})} kV`:`${t.toLocaleString(e)} V`}static detail(t,e,i,s){const{line:n}=t,a=[];n.name&&a.push(ka.kind(n,e).toLocaleLowerCase(s)),a.push(n.tracks>1?e.tracks.replace("{count}",String(n.tracks)):e.singleTrack);const r=n.voltageV?ka.voltage(n.voltageV,s):void 0;if(t.contactM!==void 0){const o=t.contactM.toLocaleString(s,{minimumFractionDigits:2,maximumFractionDigits:2});a.push((r?e.overheadVoltage.replace("{voltage}",r):e.overhead).replace("{height}",o))}else n.electrification==="third_rail"?a.push(r?e.thirdRailVoltage.replace("{voltage}",r):e.thirdRail):n.electrification==="none"&&a.push(e.notElectrified);return n.gaugeMm===ka.METRE_GAUGE_MM?a.push(e.metreGauge):n.gaugeMm!==ka.STANDARD_GAUGE_MM&&a.push(e.gauge.replace("{mm}",n.gaugeMm.toLocaleString(s))),a.push(e.distance.replace("{distance}",i(t.distanceM))),n.services?.length?`${ka.name(n,e)}; ${a.join(", ")}`:`${ka.name(n,e)} — ${a.join(", ")}`}}class ou{constructor(t,e){this.element=t,this.onChange=e,t.addEventListener("error",()=>{this.url=void 0,this.release()})}shown=!1;url;get up(){return this.shown}show(t,e,i=!0){const s=ou.resolve(t,e);if(this.url=s,!s||!i){this.release();return}this.element.src=s,this.element.hidden=!1;const n=this.shown;this.shown=!0,n||this.onChange()}release(){this.shown&&(this.shown=!1,this.element.hidden=!0,this.element.removeAttribute("src"),this.onChange())}restore(){this.url&&this.show(this.url)}static resolve(t,e){if(!(typeof t!="string"||t.trim()===""))try{const i=new URL(t.trim(),e??location.href);return i.protocol!=="https:"&&i.protocol!=="http:"?void 0:i.origin===ou.PUBLISHED_ORIGIN&&ou.isDevelopmentHost(location.hostname)?location.origin+i.pathname:i.href}catch{return}}static PUBLISHED_ORIGIN="https://ufoathome.org";static isDevelopmentHost(t){return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost")}}class Ci{static OCTAVES=[63,125,250,500,1e3,2e3,4e3,8e3];static STANDARD={temperatureC:15,relativeHumidity:.7,pressureKPa:101.325};static REFERENCE_PRESSURE_KPA=101.325;static REFERENCE_TEMPERATURE_K=293.15;static TRIPLE_POINT_K=273.16;static speedOfSound(t){return 20.0468*Math.sqrt(t+273.15)}static absorptionDbPerKm(t,e=Ci.STANDARD){const i=e.temperatureC+273.15,s=Ci.REFERENCE_TEMPERATURE_K,n=e.pressureKPa/Ci.REFERENCE_PRESSURE_KPA,a=10**(-6.8346*(Ci.TRIPLE_POINT_K/i)**1.261+4.6151),r=e.relativeHumidity*100*a/n,o=n*(24+40400*r*(.02+r)/(.391+r)),l=n*(i/s)**-.5*(9+280*r*Math.exp(-4.17*((i/s)**(-1/3)-1))),h=t*t;return 8.686*h*(184e-13*(1/n)*Math.sqrt(i/s)+(i/s)**-2.5*(.01275*Math.exp(-2239.1/i)/(o+h/o)+.1068*Math.exp(-3352/i)/(l+h/l)))*1e3}static aWeightingDb(t){const e=t*t,i=12194**2*e*e/((e+20.6**2)*Math.sqrt((e+107.7**2)*(e+737.9**2))*(e+12194**2));return 20*Math.log10(i)+2}static sumDb(t){return 10*Math.log10(t.reduce((e,i)=>e+10**(i/10),0))}}const nO=new URL(""+new URL("rain-BvWZrB9h.ogg",import.meta.url).href,import.meta.url).href,aO=new URL(""+new URL("wind-BjklexY7.ogg",import.meta.url).href,import.meta.url).href,tx=new URL(""+new URL("thunder-DA48qs_v.wav",import.meta.url).href,import.meta.url).href,rO=20,oO=1,cO=7,lO=.35,ex=.4,ix=40,sx=.5,hO=Math.SQRT2;class tc{context;constructor(t){this.context=t}buffers=new Map;ambientSource;ambientGain;ambientKey="none";ambientToken=0;ambientVolume=0;windSource;windGain;windActive=!1;windToken=0;windVolume=0;paused=!0;requested={type:"none",intensity:0,windSpeed:0};around;aroundRequested={rms:0,shape:[]};level=1;share=1;master;output(t){return this.master||(this.master=t.createGain(),this.master.gain.value=this.gain,this.master.connect(t.destination)),this.master}get gain(){return this.level*this.share}setLevel(t){this.level=t,this.master&&(this.master.gain.value=this.gain)}setOutsideHeard(t){this.share=Math.min(1,Math.max(0,t)),this.master&&(this.master.gain.value=this.gain)}resume(){if(!this.context){if(typeof AudioContext>"u")return;try{this.context=new AudioContext}catch(t){console.warn("WeatherAudio: Web Audio unavailable, weather sounds disabled:",t);return}}Un.isLive(this.context)&&Un.unlock(this.context),this.applyAround()}setAround(t,e){const i=this.aroundRequested;i.rms===Math.max(0,t)&&i.shape.length===e.length&&i.shape.every((s,n)=>s===e[n])||(this.aroundRequested={rms:Math.max(0,t),shape:e},this.applyAround())}applyAround(){const t=this.context;if(!t)return;const{rms:e,shape:i}=this.aroundRequested,s=this.paused?0:e;if(s===0&&!this.around)return;const n=this.around??(this.around=this.buildAround(t)),a=t.currentTime;n.gain.gain.setTargetAtTime(s,a,sx),Ci.OCTAVES.forEach((r,o)=>{const l=Math.sqrt(Math.min(1,1.11*r/(t.sampleRate/2)))/Math.sqrt(3);n.bands[o].gain.setTargetAtTime((i[o]??0)/l,a,sx)})}buildAround(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*cO),t.sampleRate),i=e.getChannelData(0);for(let g=0;g<i.length;g++)i[g]=Math.random()*2-1;const s=t.createBufferSource();s.buffer=e,s.loop=!0;const n=Math.floor(t.sampleRate*ix),a=t.createBuffer(1,n,t.sampleRate),r=Array.from({length:Math.round(ix*ex)},()=>Math.random()*2-1),o=a.getChannelData(0),l=t.sampleRate/ex;for(let g=0;g<n;g++){const m=g/l,v=Math.floor(m),M=m-v,x=M*M*(3-2*M);o[g]=r[v%r.length]*(1-x)+r[(v+1)%r.length]*x}const h=t.createBufferSource();h.buffer=a,h.loop=!0;const u=t.createGain();u.gain.value=lO;const d=t.createGain();d.gain.value=1,h.connect(u).connect(d.gain);const f=t.createGain();f.gain.value=0,d.connect(f).connect(this.output(t));const p=Ci.OCTAVES.map(g=>{const m=t.createBiquadFilter();m.type="bandpass",m.frequency.value=g,m.Q.value=hO;const v=t.createGain();return v.gain.value=0,s.connect(m).connect(v).connect(d),v});return s.start(),h.start(),{sources:[s,h],nodes:[u,d,f,...p],bands:p,gain:f}}setAmbient(t,e,i){if(this.requested={type:t,intensity:e,windSpeed:i},!this.context)return;this.paused&&(t="none",e=0,i=0);const s=t==="rain"||t==="hail"?t:"none";if(this.ambientVolume=s==="hail"?Math.min(1,e*1.3+.2):s==="rain"?e:0,s!==this.ambientKey){this.ambientKey=s;const a=++this.ambientToken;this.stopSource(this.ambientSource,this.ambientGain),this.ambientSource=void 0,this.ambientGain=void 0,s!=="none"&&this.startLoop(nO,this.ambientVolume).then(r=>this.applyIfCurrent(r,a,()=>this.ambientToken,o=>{this.ambientSource=o?.source,this.ambientGain=o?.gain,o&&(o.gain.gain.value=this.ambientVolume)}))}else this.ambientGain&&(this.ambientGain.gain.value=this.ambientVolume);this.windVolume=Math.min(i/rO,1);const n=i>oO;if(n!==this.windActive){this.windActive=n;const a=++this.windToken;this.stopSource(this.windSource,this.windGain),this.windSource=void 0,this.windGain=void 0,n&&this.startLoop(aO,this.windVolume).then(r=>this.applyIfCurrent(r,a,()=>this.windToken,o=>{this.windSource=o?.source,this.windGain=o?.gain,o&&(o.gain.gain.value=this.windVolume)}))}else this.windGain&&(this.windGain.gain.value=this.windVolume)}setPaused(t){if(t===this.paused)return;this.paused=t;const{type:e,intensity:i,windSpeed:s}=this.requested;this.setAmbient(e,i,s),this.applyAround()}playThunder(){!this.context||this.paused||this.playOneShot(tx,.9)}playDetonation(t){const e=this.context;if(!e||this.paused)return;const i=Math.min(1,Math.max(0,t)),s=e.createBufferSource();s.buffer=this.crackBuffer(e);const n=e.createBiquadFilter();n.type="lowpass",n.frequency.value=tc.CRACK_CUTOFF_HZ;const a=e.createGain();a.gain.value=i,s.connect(n).connect(a).connect(this.output(e)),s.start(),this.playOneShot(tx,i,tc.DETONATION_RATE)}static DETONATION_RATE=.8;static CRACK_CUTOFF_HZ=2500;static CRACK_DECAY_S=.25;crackBuffer(t){if(this.crack?.sampleRate===t.sampleRate)return this.crack;const e=Math.round(t.sampleRate*tc.CRACK_DECAY_S*6),i=t.createBuffer(1,e,t.sampleRate),s=i.getChannelData(0);for(let n=0;n<e;n++){const a=n/t.sampleRate;s[n]=(Math.random()*2-1)*Math.min(1,a/.005)*Math.exp(-a/tc.CRACK_DECAY_S)}return this.crack=i,i}crack;dispose(){this.ambientToken++,this.windToken++,this.stopSource(this.ambientSource,this.ambientGain),this.stopSource(this.windSource,this.windGain),this.ambientSource=void 0,this.ambientGain=void 0,this.windSource=void 0,this.windGain=void 0;for(const t of this.around?.sources??[])try{t.stop()}catch{}for(const t of this.around?.nodes??[])t.disconnect();this.around=void 0,Un.isLive(this.context)&&this.context.close(),this.context=void 0,this.master=void 0,this.buffers.clear()}applyIfCurrent(t,e,i,s){if(e!==i()){t?.source.stop();return}s(t)}async startLoop(t,e){const i=this.context;if(i)try{const s=await this.getBuffer(t),n=i.createBufferSource();n.buffer=s,n.loop=!0;const a=i.createGain();return a.gain.value=e,n.connect(a).connect(this.output(i)),n.start(),{source:n,gain:a}}catch(s){console.warn("Weather ambient sound failed to load, staying silent:",s);return}}async playOneShot(t,e,i=1){const s=this.context;if(s)try{const n=await this.getBuffer(t),a=s.createBufferSource();a.buffer=n,a.playbackRate.value=i;const r=s.createGain();r.gain.value=e,a.connect(r).connect(this.output(s)),a.start()}catch(n){console.warn("Thunder sound failed to load:",n)}}async getBuffer(t){const e=this.context;if(!e)throw new Error("WeatherAudio: AudioContext not ready — resume() must be called first");let i=this.buffers.get(t);return i||(i=fetch(t).then(s=>{if(!s.ok)throw new Error(`Audio fetch failed (${s.status}): ${t}`);return s.arrayBuffer()}).then(s=>e.decodeAudioData(s)),this.buffers.set(t,i)),i}stopSource(t,e){try{t?.stop()}catch{}t?.disconnect(),e?.disconnect()}}const uO={rollingA:[83.1,89.2,87.7,93.1,100.1,96.7,86.8,76.2],rollingB:[30,41.5,38.9,25.7,32.5,37.2,39,40],propulsionA:[97.9,92.5,90.7,87.2,84.7,88,84.4,77.1],propulsionB:[-1.3,7.2,7.7,8,8,8,8,8]},dO={rollingA:[91.7,96.2,98.2,104.9,105.1,98.5,91.1,85.6],rollingB:[30,33.5,31.3,25.4,31.8,37.1,38.6,40.6],propulsionA:[108.8,104.2,103.5,102.9,102.6,98.5,93.8,87.5],propulsionB:[0,3,4.6,5,5,5,5,5]},hm=70,fO=55+10*Math.log10(2*Math.PI),um=5,pO=2;class ss{static vehiclePowerDbA(t,e){return Ci.sumDb(ss.vehiclePowerBands(t,e).map((i,s)=>i+Ci.aWeightingDb(Ci.OCTAVES[s])))}static vehiclePowerBands(t,e){const i=t?dO:uO,s=Math.max(e,1);return Ci.OCTAVES.map((n,a)=>{const r=i.rollingA[a]+i.rollingB[a]*Math.log10(s/hm),o=i.propulsionA[a]+i.propulsionB[a]*(s-hm)/hm;return Ci.sumDb([r,o])})}static dbA(t,e=!0){if(!Jr.says(t))return-1/0;const i=t.withinM??Jr.DEFAULT_WITHIN_M,s=Jr.DEFAULT_SPEED_KMH,n=[ss.counted(t.cars,ss.vehiclePowerDbA(!1,s),i,um),ss.counted(t.trucks,ss.vehiclePowerDbA(!0,s),i,um),e?ss.counted(t.talking,fO,i,pO):-1/0,...(t.roads??[]).map(a=>ss.road(a.distanceM,a.vehiclesPerMinute,a.trucksPerMinute??0,a.speedKmh??s))].filter(a=>Number.isFinite(a));return n.length>0?Ci.sumDb(n):-1/0}static vehicleShape(t){if(!Jr.says(t))return;const e=t.withinM??Jr.DEFAULT_WITHIN_M,i=Jr.DEFAULT_SPEED_KMH,s=l=>{const h=ss.counted(l?t.trucks:t.cars,ss.vehiclePowerDbA(l,i),e,um),u=(t.roads??[]).map(f=>{const p=Math.min(f.trucksPerMinute??0,f.vehiclesPerMinute);return l?ss.road(f.distanceM,p,p,f.speedKmh??i):ss.road(f.distanceM,f.vehiclesPerMinute-p,0,f.speedKmh??i)}),d=[h,...u].filter(Number.isFinite);return d.length>0?10**(Ci.sumDb(d)/10):0},n=s(!1),a=s(!0);if(n+a===0)return;const r=Ci.OCTAVES.map(()=>0);for(const[l,h]of[[n,!1],[a,!0]]){if(l===0)continue;const u=ss.vehiclePowerBands(h,i),d=Ci.sumDb(u.map((f,p)=>f+Ci.aWeightingDb(Ci.OCTAVES[p])));u.forEach((f,p)=>r[p]+=l*10**((f-d)/10))}const o=Math.sqrt(r.reduce((l,h)=>l+h,0));return r.map(l=>Math.sqrt(l)/o)}static counted(t,e,i,s){if(!t)return-1/0;const n=Math.min(s,i*.99),a=t*Math.log(i/n)/(Math.PI*(i*i-n*n));return e+10*Math.log10(a)}static road(t,e,i,s){const n=Math.min(i,e),a=(o,l)=>o>0?ss.vehiclePowerDbA(l,s)+10*Math.log10(o/(1e3*Math.max(s,1))):-1/0,r=Ci.sumDb([a((e-n)*60,!1),a(n*60,!0)].filter(Number.isFinite));return Number.isFinite(r)?r-10*Math.log10(Math.PI*Math.max(t,1)):-1/0}}class pi{static BASE_DB_A=30;static OUTDOOR_SHAPE_DB=[-12,-7,-5,-5,-7,-11,-17,-25];static HEADROOM_DB=10.5;static AROUND_BED_PLAYED=!1;static WIND_DB_A=[[0,10],[1,28],[2,36],[3,40],[5,46],[8,52],[12,58],[20,66]];static RAIN_DB_A=[[0,0],[.1,42],[.3,50],[.6,58],[1,65]];static BED_RMS=.2;static MINIMUM_REFERENCE=.008;static WIND_BED_MIN_MS=1;static WIND_BED_FULL_MS=20;static dbA(t,e){const i=[pi.BASE_DB_A,pi.along(pi.WIND_DB_A,t.windSpeed),ss.dbA(e)].filter(Number.isFinite);return(t.precipitationType==="rain"||t.precipitationType==="hail")&&i.push(pi.along(pi.RAIN_DB_A,t.precipitationIntensity)),10*Math.log10(i.filter(s=>s>0).reduce((s,n)=>s+10**(n/10),0))}static bedVolume(t){const e=t.windSpeed>pi.WIND_BED_MIN_MS?Math.min(t.windSpeed/pi.WIND_BED_FULL_MS,1):0,i=t.precipitationType==="hail"?Math.min(1,t.precipitationIntensity*1.3+.2):t.precipitationType==="rain"?t.precipitationIntensity:0;return Math.hypot(e,i)}static referenceAmplitude(t,e){return Math.max(Math.hypot(pi.BED_RMS*pi.bedVolume(t),pi.aroundReference(e)),pi.MINIMUM_REFERENCE)}static aroundReference(t){const e=ss.dbA(t);return!Number.isFinite(e)||e<=pi.BASE_DB_A?0:pi.MINIMUM_REFERENCE*10**((e-pi.BASE_DB_A)/20)}static aroundBedRms(t){if(!pi.AROUND_BED_PLAYED)return 0;const e=ss.dbA(t,!1);return!Number.isFinite(e)||e<=pi.BASE_DB_A?0:Math.min(pi.BED_RMS,pi.MINIMUM_REFERENCE*10**((e-pi.BASE_DB_A-pi.HEADROOM_DB)/20))}static bedPlays(t,e){return pi.bedVolume(t)>0||pi.aroundBedRms(e)>0}static shapeDb(t,e){const i=10**(pi.dbA(t,e)/10),s=ss.dbA(e,!1),n=Number.isFinite(s)?10**(s/10):0,a=Math.max(0,i-n),r=pi.OUTDOOR_SHAPE_DB,o=10**(Ci.sumDb(r)/10),h=ss.vehicleShape(e)?.map((p,g)=>p*p*10**(Ci.aWeightingDb(Ci.OCTAVES[g])/10)),u=h?.reduce((p,g)=>p+g,0)??1,d=Ci.OCTAVES.map((p,g)=>a*10**(r[g]/10)/o+(h?n*h[g]/u:0)),f=d.reduce((p,g)=>p+g,0);return d.map(p=>10*Math.log10(p/f))}static aroundBedShape(t){return ss.vehicleShape(t)}static along(t,e){if(e<=t[0][0])return t[0][1];for(let i=1;i<t.length;i++)if(e<=t[i][0]){const[s,n]=t[i-1],[a,r]=t[i];return n+(r-n)*(e-s)/(a-s)}return t[t.length-1][1]}}class yr{constructor(t){this.elements=t;const{eccentricity:e,perihelionAu:i}=t,[s,n]=this.perifocalAxes(),a=Math.sqrt(yr.SUN_GM_AU3_PER_DAY2*(1+e)/i);this.perihelionPosition=this.scale(s,i),this.perihelionVelocity=this.scale(n,a),this.inverseSemiMajorAxis=(1-e)/i}static SUN_GM_AU3_PER_DAY2=.0002959122082855911;static MAX_ITERATIONS=200;perihelionPosition;perihelionVelocity;inverseSemiMajorAxis;positionAt(t){const e=t-this.elements.perihelionJd,i=this.universalAnomaly(e),s=this.inverseSemiMajorAxis*i*i,n=this.elements.perihelionAu,a=1-i*i/n*yr.stumpffC(s),r=e-i*i*i/Math.sqrt(yr.SUN_GM_AU3_PER_DAY2)*yr.stumpffS(s);return{x:a*this.perihelionPosition.x+r*this.perihelionVelocity.x,y:a*this.perihelionPosition.y+r*this.perihelionVelocity.y,z:a*this.perihelionPosition.z+r*this.perihelionVelocity.z}}heliocentricDistanceAt(t){const e=this.positionAt(t);return Math.hypot(e.x,e.y,e.z)}universalAnomaly(t){if(t===0)return 0;const e=Math.sign(t),i=Math.sqrt(yr.SUN_GM_AU3_PER_DAY2)*Math.abs(t),s=r=>{const o=this.inverseSemiMajorAxis*r*r,l=this.elements.perihelionAu;return(1-this.inverseSemiMajorAxis*l)*r*r*r*yr.stumpffS(o)+l*r};let n=Math.max(1,i/this.elements.perihelionAu);for(;s(n)<i;)n*=2;let a=0;for(let r=0;r<yr.MAX_ITERATIONS&&n-a>1e-13*Math.max(1,n);r++){const o=(a+n)/2;s(o)<i?a=o:n=o}return e*(a+n)/2}perifocalAxes(){const t=this.elements.ascendingNodeDeg*Math.PI/180,e=this.elements.argumentOfPerihelionDeg*Math.PI/180,i=this.elements.inclinationDeg*Math.PI/180,s=Math.cos(t),n=Math.sin(t),a=Math.cos(e),r=Math.sin(e),o=Math.cos(i),l=Math.sin(i);return[{x:s*a-n*r*o,y:n*a+s*r*o,z:r*l},{x:-s*r-n*a*o,y:-n*r+s*a*o,z:a*l}]}scale(t,e){return{x:t.x*e,y:t.y*e,z:t.z*e}}static stumpffC(t){if(Math.abs(t)<1e-6)return 1/2-t/24+t*t/720;if(t>0)return(1-Math.cos(Math.sqrt(t)))/t;const e=Math.sqrt(-t);return(Math.cosh(e)-1)/-t}static stumpffS(t){if(Math.abs(t)<1e-6)return 1/6-t/120+t*t/5040;if(t>0){const i=Math.sqrt(t);return(i-Math.sin(i))/(i*i*i)}const e=Math.sqrt(-t);return(Math.sinh(e)-e)/(e*e*e)}}const Bb=[{id:"halley-1910",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672960498922706,perihelionAu:.5872100477652511,inclinationDeg:162.218798367122,ascendingNodeDeg:58.56208298700436,argumentOfPerihelionDeg:111.7366940639061,perihelionJd:2.4187816784171113e6},peakMagnitude:0,peakOn:"1910-05-20",absoluteMagnitude:4.72,activityExponent:4,tailLengthDeg:100,tailLengthAu:.1638,note:"Passed 0.15 au from Earth on 20 May 1910, and the Earth crossed the outer tail the day before — the apparition that produced a genuine public panic."},{id:"brooks-1911",designation:"C/1911 O1",name:"Comet Brooks",orbit:{eccentricity:.9876404970138669,perihelionAu:.4898172916113738,inclinationDeg:33.34043866978714,ascendingNodeDeg:293.7022074981857,argumentOfPerihelionDeg:153.5578007321686,perihelionJd:2.4193378856140426e6},peakMagnitude:2,peakOn:"1911-10-25",absoluteMagnitude:5.59,activityExponent:4},{id:"skjellerup-maristany-1927",designation:"C/1927 X1",name:"Comet Skjellerup-Maristany",orbit:{eccentricity:.999839726885059,perihelionAu:.1761569619628186,inclinationDeg:85.1125991950808,ascendingNodeDeg:78.24360172472711,argumentOfPerihelionDeg:47.15877857390136,perihelionJd:2.4252326808989984e6},peakMagnitude:-6,peakOn:"1927-12-15",absoluteMagnitude:1.19,activityExponent:4,note:"One of the few comets of the century seen in full daylight."},{id:"de-kock-paraskevopoulos-1941",designation:"C/1941 B2",name:"Comet de Kock-Paraskevopoulos",orbit:{eccentricity:.9991026715181549,perihelionAu:.7900329662827822,inclinationDeg:168.2039226531089,ascendingNodeDeg:43.10609347214336,argumentOfPerihelionDeg:268.6990344196369,perihelionJd:2430022157765061e-9},peakMagnitude:2,peakOn:"1941-02-05",absoluteMagnitude:5.01,activityExponent:4},{id:"southern-1947",designation:"C/1947 X1",name:"the Southern Comet",orbit:{eccentricity:.9998424430916737,perihelionAu:.1100045955093761,inclinationDeg:138.5113919632757,ascendingNodeDeg:337.3114969669252,argumentOfPerihelionDeg:196.1820121395961,perihelionJd:2.4325220864727003e6},peakMagnitude:-3,peakOn:"1947-12-08",absoluteMagnitude:3.01,activityExponent:4,note:"A bright southern-hemisphere comet of December 1947, the month the American sighting wave of that year was still being argued over."},{id:"eclipse-1948",designation:"C/1948 V1",name:"the Eclipse Comet",orbit:{eccentricity:.9999130678247334,perihelionAu:.1354437057263306,inclinationDeg:23.11668597152911,ascendingNodeDeg:211.0454985994762,argumentOfPerihelionDeg:107.2474157073104,perihelionJd:2.4328519265329437e6},peakMagnitude:-2,peakOn:"1948-11-01",absoluteMagnitude:4.79,activityExponent:4,note:"Found during the total solar eclipse of 1 November 1948, which is how a comet that bright had gone unnoticed: it had been hidden in the Sun's glare."},{id:"arend-roland-1957",designation:"C/1956 R1",name:"Comet Arend-Roland",orbit:{eccentricity:1.0002570255357,perihelionAu:.3160532361485914,inclinationDeg:119.9440863251822,ascendingNodeDeg:215.8548157717755,argumentOfPerihelionDeg:308.775920364167,perihelionJd:2.4359365327396123e6},peakMagnitude:.5,peakOn:"1957-04-25",absoluteMagnitude:3.96,activityExponent:4,note:"Showed a spike pointing back TOWARD the Sun in late April 1957 — a real anti-tail, and much reported at the time."},{id:"mrkos-1957",designation:"C/1957 P1",name:"Comet Mrkos",orbit:{eccentricity:.9993521583504134,perihelionAu:.3549238508212375,inclinationDeg:93.9433042053929,ascendingNodeDeg:68.32441518619923,argumentOfPerihelionDeg:40.31823675802871,perihelionJd:243605193752228e-8},peakMagnitude:1,peakOn:"1957-08-05",absoluteMagnitude:5.07,activityExponent:4,note:"The second bright naked-eye comet of 1957, four months after Arend-Roland."},{id:"seki-lines-1962",designation:"C/1962 C1",name:"Comet Seki-Lines",orbit:{eccentricity:1.000003791331562,perihelionAu:.03139689112215131,inclinationDeg:65.01487186102287,ascendingNodeDeg:304.6776602796538,argumentOfPerihelionDeg:11.47295326312573,perihelionJd:2437756163010178e-9},peakMagnitude:-2.5,peakOn:"1962-04-01",absoluteMagnitude:9.3,activityExponent:4},{id:"ikeya-seki-1965",designation:"C/1965 S1",name:"Comet Ikeya-Seki",orbit:{eccentricity:.9999141178248997,perihelionAu:.007785966366889336,inclinationDeg:141.8642315267051,ascendingNodeDeg:346.9951764632611,argumentOfPerihelionDeg:69.04909813996062,perihelionJd:2.4390546837018197e6},peakMagnitude:-10,peakOn:"1965-10-21",alsoRecordedMagnitude:2,alsoRecordedOn:"1965-10-30",absoluteMagnitude:5.26,activityExponent:4.002,tailLengthDeg:25,tailLengthAu:.5048,note:"A sungrazer that passed 450 000 km above the Sun's surface and was seen beside it in broad daylight — the brightest comet of the twentieth century. It then stood in the dawn sky for a fortnight with a tail some 25 degrees long, which is the second magnitude recorded here."},{id:"bennett-1970",designation:"C/1969 Y1",name:"Comet Bennett",orbit:{eccentricity:.9962979048768408,perihelionAu:.5376209981502136,inclinationDeg:90.03975717147327,ascendingNodeDeg:224.6576652531314,argumentOfPerihelionDeg:354.1494209173161,perihelionJd:2.4406655455270996e6},peakMagnitude:0,peakOn:"1970-03-26",absoluteMagnitude:3.36,activityExponent:4},{id:"white-ortiz-bolelli-1970",designation:"C/1970 K1",name:"Comet White-Ortiz-Bolelli",orbit:{eccentricity:.9999488875801225,perihelionAu:.00884411465256722,inclinationDeg:138.9520738221631,ascendingNodeDeg:336.8194095816687,argumentOfPerihelionDeg:61.10224765396615,perihelionJd:2.4407209807728203e6},peakMagnitude:1,peakOn:"1970-05-22",absoluteMagnitude:4.35,activityExponent:4},{id:"kohoutek-1973",designation:"C/1973 E1",name:"Comet Kohoutek",orbit:{eccentricity:1.000007152175185,perihelionAu:.1424250377812859,inclinationDeg:14.30414984159355,ascendingNodeDeg:258.4893339663974,argumentOfPerihelionDeg:37.79772760699667,perihelionJd:2442044930687027e-9},peakMagnitude:0,peakOn:"1974-01-05",absoluteMagnitude:4.89,activityExponent:4,note:"Announced in advance as the comet of the century and remembered for disappointing: it was an ordinary naked-eye object, not the spectacle the press had promised."},{id:"west-1976",designation:"C/1975 V1",name:"Comet West",orbit:{eccentricity:1.000017859625611,perihelionAu:.1966006188461085,inclinationDeg:43.07319920579427,ascendingNodeDeg:118.9189245655447,argumentOfPerihelionDeg:358.4315101259072,perihelionJd:2442833721841768e-9},peakMagnitude:-3,peakOn:"1976-02-25",absoluteMagnitude:4.41,activityExponent:4,tailLengthDeg:30,tailLengthAu:.4325,note:"Broke into four pieces at perihelion. Barely reported at the time — the press had been burned by Kohoutek two years earlier."},{id:"iras-araki-alcock-1983",designation:"C/1983 H1",name:"Comet IRAS-Araki-Alcock",orbit:{eccentricity:.9898409731606003,perihelionAu:.9913412593828502,inclinationDeg:73.25000846947029,ascendingNodeDeg:49.10235754476374,argumentOfPerihelionDeg:192.8506176754439,perihelionJd:2.4454757545235856e6},peakMagnitude:1.7,peakOn:"1983-05-11",absoluteMagnitude:9.04,activityExponent:4,note:"Passed 0.031 au from Earth on 11 May 1983, one of the closest cometary approaches on record: it crossed a quarter of the sky in a night, which no other comet in this list did."},{id:"halley-1986",designation:"1P/Halley",name:"Halley's Comet",orbit:{eccentricity:.9672792271749998,perihelionAu:.5871034488173393,inclinationDeg:162.2422242700916,ascendingNodeDeg:58.85993640671803,argumentOfPerihelionDeg:111.8655480539208,perihelionJd:2.4464709589610207e6},peakMagnitude:2.1,peakOn:"1986-03-10",absoluteMagnitude:2.71,activityExponent:4,note:"The worst-placed return in two thousand years — famous, expected, and for most observers a faint smudge."},{id:"hyakutake-1996",designation:"C/1996 B2",name:"Comet Hyakutake",orbit:{eccentricity:.9997295133739305,perihelionAu:.2302272039470452,inclinationDeg:124.923592343765,ascendingNodeDeg:188.0454295899424,argumentOfPerihelionDeg:130.1724036582639,perihelionJd:2.4502048946148166e6},peakMagnitude:0,peakOn:"1996-03-25",absoluteMagnitude:4.75,activityExponent:4,tailLengthDeg:80,tailLengthAu:1,note:"Passed 0.10 au from Earth in March 1996, five weeks BEFORE perihelion, with a tail measured at some 80 degrees — the longest of the modern era."},{id:"hale-bopp-1997",designation:"C/1995 O1",name:"Comet Hale-Bopp",orbit:{eccentricity:.9951314746156615,perihelionAu:.9141695067003724,inclinationDeg:89.43017155012492,ascendingNodeDeg:282.470602866853,argumentOfPerihelionDeg:130.5872524854533,perihelionJd:2450539633099368e-9},peakMagnitude:-.8,peakOn:"1997-04-01",absoluteMagnitude:-1.06,activityExponent:4,tailLengthDeg:20,tailLengthAu:.9938,note:"Visible to the naked eye for about eighteen months, longer than any comet on record."},{id:"mcnaught-2007",designation:"C/2006 P1",name:"Comet McNaught",orbit:{eccentricity:1.00001811603225,perihelionAu:.1707325614080681,inclinationDeg:77.83726446452654,ascendingNodeDeg:267.4149080498975,argumentOfPerihelionDeg:155.9756130642756,perihelionJd:2454113298753579e-9},peakMagnitude:-5.5,peakOn:"2007-01-13",absoluteMagnitude:2.53,activityExponent:4,tailLengthDeg:35,tailLengthAu:.5009,note:"The brightest comet since Ikeya-Seki, seen in daylight beside the Sun in January 2007."},{id:"lovejoy-2011",designation:"C/2011 W3",name:"Comet Lovejoy",orbit:{eccentricity:.999915056276912,perihelionAu:.005553783989325053,inclinationDeg:134.3558712062691,ascendingNodeDeg:326.3693517957772,argumentOfPerihelionDeg:53.50991655176601,perihelionJd:2455911511809431e-9},peakMagnitude:-3,peakOn:"2011-12-16",alsoRecordedMagnitude:1.5,alsoRecordedOn:"2011-12-22",absoluteMagnitude:3.51,activityExponent:1.194,note:"A sungrazer that was expected to be destroyed at perihelion and came out the other side, to stand in the southern dawn sky for the rest of December — which is the second magnitude recorded here."},{id:"panstarrs-2013",designation:"C/2011 L4",name:"Comet PANSTARRS",orbit:{eccentricity:1.000032542889696,perihelionAu:.301544229714915,inclinationDeg:84.2081978367921,ascendingNodeDeg:65.66588626213694,argumentOfPerihelionDeg:333.6516444379993,perihelionJd:2456361669960698e-9},peakMagnitude:1,peakOn:"2013-03-10",absoluteMagnitude:5.98,activityExponent:4},{id:"neowise-2020",designation:"C/2020 F3",name:"Comet NEOWISE",orbit:{eccentricity:.9991782081129224,perihelionAu:.2946512466331692,inclinationDeg:128.9375043020912,ascendingNodeDeg:61.01042991771634,argumentOfPerihelionDeg:37.2786526292898,perihelionJd:2.4590341788972816e6},peakMagnitude:.9,peakOn:"2020-07-08",absoluteMagnitude:5.79,activityExponent:4,tailLengthDeg:10,tailLengthAu:.1808,note:"The first comet since Hale-Bopp that ordinary observers in the northern hemisphere saw without being told where to look."},{id:"tsuchinshan-atlas-2024",designation:"C/2023 A3",name:"Comet Tsuchinshan-ATLAS",orbit:{eccentricity:1.000020192843226,perihelionAu:.3914228969475176,inclinationDeg:139.1105462619479,ascendingNodeDeg:21.55945689078845,argumentOfPerihelionDeg:308.4913086299446,perihelionJd:2460581242087108e-9},peakMagnitude:0,peakOn:"2024-10-14",absoluteMagnitude:3.97,activityExponent:4,tailLengthDeg:20,tailLengthAu:.1902,note:"Briefly reported far brighter around 9 October 2024, when it stood almost between the observer and the Sun and forward-scattered the light through its own dust — a geometry this catalog's brightness model does not attempt, so what is stored is the ordinary evening-sky peak a few days later."}];class mO{static WINDOW_DAYS=200;static TWILIGHT_ELONGATION_DEG=15;static LIGHT_SPEED_AU_PER_DAY=173.144632674;static orbits=new Map;static aroundDate(t){const e=this.julianDayOf(t);return Bb.filter(i=>Math.abs(e-i.orbit.perihelionJd)<=this.WINDOW_DAYS)}static brightestAt(t,e){return this.aroundDate(t).map(i=>this.appearanceOf(i,t,e)).sort((i,s)=>i.magnitude-s.magnitude)[0]}static appearanceOf(t,e,i){const s=oi(e),n=this.earthPositionAt(s),a=this.apparentPositionOf(t,2451545+s.tt,n),r=this.subtract(a,n),o=this.length(a),l=this.length(r),h=this.tailEndAt(t,a,n,o,s,e,i),u=this.horizontalOf(r,s,e,i);return{apparition:t,position:u,...h,heliocentricDistanceAu:o,earthDistanceAu:l,elongationDeg:this.angleBetween(r,this.subtract({x:0,y:0,z:0},n)),magnitude:this.magnitudeAt(t,o,l)}}static magnitudeAt(t,e,i){const s=t.absoluteMagnitude+5*Math.log10(i)+2.5*t.activityExponent*Math.log10(e);return Math.max(s,t.peakMagnitude)}static tailEndAt(t,e,i,s,n,a,r){if(t.tailLengthAu===void 0)return{};const o=1+t.tailLengthAu/s,l=this.subtract({x:e.x*o,y:e.y*o,z:e.z*o},i),h=this.subtract(e,i);return{tailEnd:this.horizontalOf(l,n,a,r),tailLengthDeg:this.angleBetween(h,l)}}static apparentPositionOf(t,e,i){const s=this.orbitOf(t);let n=s.positionAt(e);for(let a=0;a<2;a++){const r=this.length(this.subtract(n,i))/this.LIGHT_SPEED_AU_PER_DAY;n=s.positionAt(e-r)}return n}static horizontalOf(t,e,i,s){const n=Dr(lE(),new Fe(t.x,t.y,t.z,e)),a=Dr(Gx(e),n),r=Sm(e,new Mo(s.lat,s.lng,s.elevationM),!0),o=new Fe(a.x-r.x,a.y-r.y,a.z-r.z,e),l=l0(o);return m1(l.ra,l.dec,i,s)}static earthPositionAt(t){return Dr(cE(),po(pt.Earth,t))}static julianDayOf(t){return 2451545+oi(t).tt}static orbitOf(t){const e=this.orbits.get(t.id);if(e)return e;const i=new yr(t.orbit);return this.orbits.set(t.id,i),i}static subtract(t,e){return{x:t.x-e.x,y:t.y-e.y,z:t.z-e.z}}static length(t){return Math.hypot(t.x,t.y,t.z)}static angleBetween(t,e){const i=(t.x*e.x+t.y*e.y+t.z*e.z)/(this.length(t)*this.length(e)||1);return Math.acos(Math.min(1,Math.max(-1,i)))*180/Math.PI}}const dm=[{id:"sn-1006",kind:"supernova",designation:"SN 1006",name:"Supernova of 1006",raHours:15.03947,decDeg:-42.09694,peakMagnitude:-7.5,peakJd:2088620,startJd:2088620,lightCurve:[[0,-7.5],[29,-5.9],[60,-4.9],[106,-3.2],[166,-1.9],[258,-1],[350,.5],[364,.7],[411,1.2],[456,1.8],[484,2.5],[785.5,7]],source:"Winkler, Gupta & Long 2003 (peak); decline borrowed from SN 1572",note:"The brightest stellar event in recorded history, seen in daylight, low in the southern sky from Europe and the Near East. The decline is modelled, not recorded, and falls below the naked eye after about two years where the chronicles speak of three."},{id:"sn-1054",kind:"supernova",designation:"SN 1054",name:"Supernova of 1054",raHours:5.5755,decDeg:22.0175,peakMagnitude:-6,peakJd:2106216,startJd:2106216,lightCurve:[[0,-6],[23,-4],[642,6]],source:"Chinese chronicles (Song huiyao), via Stephenson & Green 2002",note:"The explosion that left the Crab Nebula. Its magnitude is an estimate; the two durations are recorded."},{id:"sn-1181",kind:"supernova",designation:"SN 1181",name:"Supernova of 1181",raHours:.88645,decDeg:67.50067,peakMagnitude:0,peakJd:2152636,startJd:2152636,lightCurve:[[0,0],[185,6]],source:"Chinese and Japanese chronicles, via Stephenson & Green 2002",note:"Circumpolar from Europe and China, so never set. Its peak magnitude is uncertain by at least a magnitude."},{id:"sn-1572",kind:"supernova",designation:"SN 1572",name:"Tycho's Supernova",raHours:.42264,decDeg:64.14083,peakMagnitude:-4,peakJd:2295551,startJd:2295546,lightCurve:[[0,-3],[5,-4],[34,-2.4],[65,-1.4],[111,.3],[171,1.6],[263,2.5],[355,4],[369,4.2],[416,4.7],[461,5.3],[489,6]],source:"Tycho Brahe and contemporaries, reduced by Ruiz-Lapuente 2004",note:"Circumpolar from northern Europe. Tycho showed it had no parallax, so it was not in the air: a new star, beyond the Moon."},{id:"sn-1604",kind:"supernova",designation:"SN 1604",name:"Kepler's Supernova",raHours:17.51125,decDeg:-21.48733,peakMagnitude:-2.95,peakJd:2307210,startJd:2307191,lightCurve:[[0,.23],[3,-1.3],[6,-2.08],[9,-2.17],[19,-2.95],[27,-2.95],[32,-1.95],[36,-1.52],[86,.9],[96,.45],[103,1],[114,1.2],[118,1.55],[133,1.95],[137,2.3],[170,2.25],[185,2.25],[194,2.4],[197,2.9],[308,4.45],[324,4.45],[339,4.95],[364,4.7]],source:"Kepler, Fabricius, Maestlin and the Korean court astronomers, reduced by Ruiz-Lapuente 2017",note:"The last supernova in our Galaxy seen with the naked eye. It went behind the Sun from mid-November 1604 to January 1605, which is the gap in its record."},{id:"t-crb-1866",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1866",raHours:15.99171,decDeg:25.92017,peakMagnitude:2,peakJd:2402734,startJd:2402734,lightCurve:[[0,2],[1.5,3],[2.5,3.11],[6.5,5.18],[8.5,5.75],[10.5,6.85],[11.5,6.8],[12.5,7.5],[16,8.18],[32,9.27],[38,9.2],[40,8.95],[44,9.4],[48,9.07],[54,9.4],[58,9.21],[79,9.44],[107,9.26],[111,9.01],[115,8.21],[119,7.96],[159,7.51],[179,7.57],[183,7.97],[191,7.66],[199,8.2],[207,8.31],[211,8.83],[215,8.65],[223,8.97],[297,8.9],[345,9.25],[377,9.07],[425,9.3],[537,9.3]],source:"Recorded peak (Birmingham); curve borrowed from its 1946 eruption",note:"The first eruption of the recurrent nova T CrB to be seen. The decline is its 1946 one."},{id:"t-aur-1891",kind:"nova",designation:"T Aur",name:"Nova Aurigae 1891",raHours:5.53309,decDeg:30.44583,peakMagnitude:4.49,peakJd:2412083,startJd:2412079,lightCurve:[[0,5.28],[4,4.49],[24,4.58],[40,4.97],[52,4.95],[56,4.5],[60,4.9],[68,4.88],[72,5.25],[76,4.93],[84,5.44],[88,7.23],[96,8.85],[100,10.44]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"gk-per-1901",kind:"nova",designation:"GK Per",name:"Nova Persei 1901",raHours:3.52,decDeg:43.90431,peakMagnitude:.19,peakJd:24154395e-1,startJd:24154377e-1,lightCurve:[[0,2.7],[.8,.86],[1.8,.19],[2.3,.2],[5.8,1.78],[11.8,2.54],[12.8,2.98],[17.8,3.62],[18.8,3.35],[19.8,3.77],[20.8,3.59],[22.8,3.95],[24.8,3.82],[25.6,4.99],[25.9,4.89],[26.6,3.69],[27.6,3.94],[27.9,4.61],[28.6,5.28],[28.9,4.46],[29.9,3.8],[30.9,4.27],[31.6,5.21],[31.9,5.22],[32.9,3.88],[33.9,4.19],[34.6,4.85],[35.6,4.8],[36.6,4.23],[37.6,4.44],[38.9,4.15],[39.7,5.19],[40.6,5.39],[40.9,5.35],[41.9,4.01],[42.6,4.5],[42.9,4.49],[43.6,5.53],[44,5.23],[44.6,5.61],[44.9,5.5],[45.9,4.17],[46.9,4.69],[47.6,5.5],[48.6,5.59],[49.6,5.14],[49.9,4.48],[50.6,4.45],[50.9,4.55],[51.6,5.47],[52.6,5.74],[53.7,5.66],[55.7,4.41],[56.7,5.43],[58.7,5.81],[58.9,5.58],[59.7,5.64],[59.9,4.76],[60.9,4.26],[61.9,5.62],[62.7,5.85],[62.9,5.53],[63.7,5.8],[64.9,4.28],[65.6,5.33],[66.7,5.87],[66.9,5.56],[68.7,5.7],[68.9,5.3],[69.7,4.47],[70.7,5.65],[72.9,5.98],[73.9,5.71],[74.7,4.98],[74.9,4.46],[75.7,4.87],[76.9,6.05],[77.6,5.76],[78,6],[78.7,5.95],[80.7,4.98],[81.9,5.85],[82.7,6.02],[84.7,5.41],[84.9,5.08],[85.7,5.17],[85.9,5.6],[87,6.1],[88.8,6.2],[89.7,4.96],[89.9,4.93],[90.7,5.9],[91.9,6.32],[92.7,5.86],[93.1,6.24],[93.7,5.38],[93.9,6.2],[96.1,6.12],[97.1,6.37],[97.6,5.12],[98,5.85],[99.3,6.35],[101.3,6.12],[101.7,5.25],[102.3,4.95],[102.7,6.12],[103.2,5.83],[104.7,6.37],[105,6.13],[106,6.22],[106.7,4.88],[107.7,6.3],[108.1,6.4],[109,6],[109.7,5.16],[110,5.82],[112.1,5.89],[113.1,5.5],[115.7,5.8],[116,6.11],[118.7,5.68],[119,6.23],[119.7,5.85],[120,6.12],[121,4.62],[121.8,5.9],[123,5.48],[125,6.05],[126,5.89],[130.9,6.11],[146.1,6.02],[155.6,6.26],[180.4,6.09],[190.4,6.39],[245.5,6.87],[266.2,6.77],[301.1,7.16],[321.5,7.07],[346.5,7.87],[375.7,7.86],[385.8,8.09],[389.8,8.55],[406.1,8.33],[416.5,8.59],[445.9,8.62],[472.1,9.24],[565.9,9.74],[571,9.4],[589.8,9.76]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Discovered on 21 February 1901 by Thomas Anderson in Edinburgh, and the brightest nova of the century until V603 Aql."},{id:"dn-gem-1912",kind:"nova",designation:"DN Gem",name:"Nova Geminorum 1912",raHours:6.9151,decDeg:32.14108,peakMagnitude:3.58,peakJd:241947675e-2,startJd:241947275e-2,lightCurve:[[0,11.7],[1,4.5],[4,3.58],[5,4.45],[5.5,5.32],[6,5.53],[6.5,5.11],[8,5.43],[8.5,5.16],[11,5.53],[11.5,5.13],[12,5.18],[13.75,4.5],[15.75,5.3],[18.75,6],[19.75,5.55],[26.75,6],[28.75,5.9],[31.75,6.6],[32.75,6.2],[33.75,6.5],[36.75,6.55],[39.75,6.2],[40.75,6.75],[41.75,7],[44.75,6.75],[52.75,6.75],[54.75,7.23],[58.25,7.5],[62.25,7.3],[64.25,7.47],[66.25,8.1],[70.25,7.5],[72.25,8.1],[78.25,7.55],[80.25,8.2],[86.25,7.2],[90.25,7.3],[92.25,7.8],[152.25,7.2],[160.25,7.4],[166.25,8.2],[168.25,8.2],[170.25,7.3],[180.25,7.4],[182.25,8],[186.25,7.5],[190.25,7.6],[192.25,8],[211.25,7.75],[227.25,8],[275.25,7.78],[315.25,8.6],[331.25,7.79],[339.25,8.27],[363.25,8.61],[443.25,8.93],[451.25,9.2],[535.25,10.3],[567.25,9.9],[615.25,10.8],[631.25,10.63],[647.25,10.88],[679.25,10.8],[695.25,11.07],[727.25,11]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v603-aql-1918",kind:"nova",designation:"V603 Aql",name:"Nova Aquilae 1918",raHours:18.81518,decDeg:.58414,peakMagnitude:-.5,peakJd:242175475e-2,startJd:242174875e-2,lightCurve:[[0,11.3],[2,10.5],[4,6.6],[4.5,1.04],[6,-.5],[6.5,.18],[10,1.1],[10.5,.95],[12.75,1.89],[21.75,3.07],[23.75,3.76],[29.75,3.16],[34.75,3.5],[36.75,3.86],[44.75,3.79],[48.75,4.43],[52.75,3.84],[56.75,3.95],[57.75,4.04],[58.75,4.49],[59.75,4.42],[60.75,4.69],[62.75,4.6],[63.75,4.11],[64.75,3.97],[68.75,4.18],[70.75,4.65],[71.75,4.51],[73.75,4.73],[75.75,4.44],[79.75,4.85],[83.75,4.43],[89.75,4.88],[92.75,4.86],[94.75,4.58],[96.75,4.92],[99.75,5.05],[163.25,5.45],[167.25,5.7],[179.25,5.48],[191.25,5.8],[203.25,5.5],[247.25,5.9],[251.25,6.25],[257.25,5.5],[265.25,6.13],[281.25,6.33],[345.25,6.3],[385.25,6.73],[393.25,6.43],[425.25,6.71],[433.25,6.56],[461.25,7.27],[525.25,7.6],[541.25,7.47],[637.25,8.3],[669.25,8.17],[717.25,8.55],[749.25,8.4],[765.25,8.68],[885.25,8.75],[949.25,9.4],[1013.25,9.19],[1141.25,9.57],[1269.25,9.48],[1333.25,9.95],[1653.25,9.94],[1781.25,10.28],[1909.25,10.34],[2037.25,10.1],[2101.25,10.46],[2165.25,10.51],[2357.25,10.3],[2549.25,10.77],[2741.25,10.46],[2869.25,10.83],[3125.25,10.71],[3317.25,11.22],[3381.25,10.91],[3637.25,11.42],[3829.25,10.96],[3893.25,11.65],[3957.25,11.63],[4085.25,11.14],[4213.25,11.48],[4277.25,10.7],[4341.25,11.42],[4405.25,11.47],[4469.25,11.06],[4533.25,11.08],[4597.25,11.7],[4725.25,11.45],[4789.25,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"The brightest nova of the modern era, at magnitude -0.5 on 9-10 June 1918: as bright as Vega, in a summer evening sky, in wartime."},{id:"v476-cyg-1920",kind:"nova",designation:"V476 Cyg",name:"Nova Cygni 1920",raHours:19.97347,decDeg:53.61858,peakMagnitude:1.94,peakJd:242256025e-2,startJd:242255925e-2,lightCurve:[[0,2.7],[1,1.94],[3,2.07],[4.5,2.95],[8.25,4],[31.75,6.41],[35.75,7.23],[37.75,7.08],[41.75,7.33],[43.75,7.92],[45.75,8.2],[51.75,8.59],[63.75,8.82],[65.75,9.25],[71.75,8.93],[85.75,9.43],[87.75,9.05],[95.75,9.2],[97.75,8.67],[99.75,9.07],[112.75,8.78],[120.75,9.03],[128.75,8.67],[144.75,8.94],[152.75,8.73],[168.75,8.79],[176.75,9.28],[192.75,9],[216.75,9.6],[232.75,9.27],[240.75,9.5],[288.75,9.4],[296.75,9.6],[304.75,9.3],[320.75,9.73],[328.75,9.5],[336.75,9.8],[428.75,9.61],[476.75,10.01],[492.75,9.76],[508.75,9.87],[524.75,9.65],[556.75,9.87],[572.75,9.65],[620.75,10.22],[668.75,10.44],[684.75,10.23],[716.75,10.33],[756.75,10.66],[884.75,10.59],[948.75,10.96],[1108.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rr-pic-1925",kind:"nova",designation:"RR Pic",name:"Nova Pictoris 1925",raHours:6.59335,decDeg:-62.64008,peakMagnitude:.95,peakJd:24243085e-1,startJd:24242995e-1,lightCurve:[[0,2.43],[5,2.35],[6,2.1],[7,2.4],[9,.95],[13,1.8],[14,1.7],[16,2.15],[18,2.2],[19,1.9],[23,3.1],[27,3.05],[31.5,3.58],[43.5,3.08],[47.5,3.15],[57.5,2.3],[59.5,1.65],[63.5,3.03],[65.5,2.84],[67.5,3.16],[69.5,2.4],[71.5,2.04],[73.5,2.05],[75.5,2.55],[79.5,3],[83.5,3.15],[116.5,3.54],[120.5,3.78],[124.5,3.67],[136.5,4.18],[148.5,4.34],[154.5,4.17],[194.5,4.43],[226.5,4.93],[234.5,4.8],[242.5,5.4],[250.5,5.5],[266.5,5.15],[298.5,5.6],[362.5,5.4],[414.5,5.7],[430.5,5.5],[494.5,6.2],[718.5,6.52],[830.5,6.3],[862.5,6.6],[878.5,6.4],[910.5,6.77],[958.5,6.67],[1062.5,7.07],[1318.5,7.35],[1590.5,8.12],[1718.5,8.25],[2486.5,8.59],[2614.5,8.47],[2742.5,8.7],[3382.5,8.6],[3766.5,8.97],[4022.5,8.79],[4150.5,9.22],[6710.5,10.29],[7414.5,11.03],[8438.5,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A slow nova, and a southern one: more than two months within two magnitudes of its peak."},{id:"dq-her-1934",kind:"nova",designation:"DQ Her",name:"Nova Herculis 1934",raHours:18.12507,decDeg:45.85906,peakMagnitude:1.56,peakJd:24277935e-1,startJd:242778675e-2,lightCurve:[[0,3.4],[1.5,2.4],[3,2.67],[5.75,2.01],[6.75,1.56],[7.75,1.59],[11.75,2.97],[12.75,2.31],[14.75,3.07],[15.75,2.56],[16.75,2.51],[19.75,2.68],[23.75,2.53],[24.75,2.27],[26.75,2.58],[30.75,2.24],[31.75,2.63],[32.75,2.66],[34.75,2.11],[39.75,2.71],[41.75,2.31],[43.75,2.37],[46.75,3.64],[47.75,3.21],[50.75,3.23],[52.75,2.66],[55.75,2.56],[58.75,2.97],[60.75,2.77],[61.75,3.36],[63.75,3.43],[64.75,2.89],[65.75,3.22],[68.75,3.52],[69.75,2.95],[70.75,3.06],[71.75,2.7],[76.75,3.65],[79.75,3.74],[81.75,3.21],[83.75,3.75],[87.75,3.69],[92.75,4.04],[94.75,4.8],[97.75,4.24],[98.75,4.52],[100.75,4.08],[101.75,4.43],[105.75,4.58],[106.75,4.33],[107.75,4.73],[108.75,6.57],[109.75,8.08],[110.75,8.15],[111.75,8.56],[113.75,8.45],[114.75,9.15],[115.75,9.15],[116.75,9.59],[117.75,9.43],[118.75,9.8],[122.75,10.5],[123.75,10.28],[124.75,10.93],[127.75,10.83],[129.75,11.87],[131.75,12.42],[135.75,12.5],[137.75,12.9],[138.75,12.77],[139.75,13],[143.75,12],[144.75,12.33],[146.75,12.35],[147.75,11.64],[148.75,11.83],[150.75,10.9],[151.75,10.78],[152.75,11.17],[154.75,10.32],[155.75,10.4],[165.25,9.24],[185.25,7.74],[225.25,6.8],[273.25,6.72],[321.25,6.97],[333.25,6.79],[353.25,7],[357.25,6.82],[377.25,6.88],[401.25,7.29],[409.25,6.8],[413.25,6.8],[419.25,7.1],[435.25,7.09],[451.25,7.4],[475.25,7],[555.25,7.48],[823.25,7.83],[855.25,8.18],[1135.25,8.43],[1823.25,9.98],[1887.25,9.71],[2015.25,10.55],[2335.25,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"Lost about ten magnitudes in a few weeks from April 1935, when dust condensed around it, then came back to naked-eye brightness."},{id:"cp-lac-1936",kind:"nova",designation:"CP Lac",name:"Nova Lacertae 1936",raHours:22.26142,decDeg:55.61703,peakMagnitude:2.02,peakJd:242834025e-2,startJd:242833825e-2,lightCurve:[[0,4.03],[.5,2.9],[1,2.45],[2,2.02],[2.5,2.61],[4,3],[4.5,3.35],[5,3.3],[9.25,4.59],[14.25,5.45],[22.25,6.03],[23.25,6.3],[26.25,6.23],[38.25,6.74],[41.25,6.61],[50.25,7.35],[53.25,7.27],[57.25,7.7],[58.25,7.54],[60.25,7.55],[61.25,7.79],[71.25,7.6],[74.25,7.81],[76.25,8.3],[77.25,7.79],[86.25,8.21],[87.25,8],[88.25,8.25],[92.25,8.17],[94.25,8.47],[102.25,8.27],[103.25,8.7],[104.25,8.4],[110.25,8.66],[116.75,8.55],[122.75,8.83],[126.75,8.7],[140.75,9.06],[154.75,9.01],[164.75,9.36],[170.75,9.18],[174.75,9.48],[186.75,9.42],[188.75,9.73],[192.75,9.53],[200.75,9.74],[202.75,9.5],[204.75,9.77],[208.75,9.6],[214.75,9.75],[216.75,10.05],[222.75,9.7],[232.75,10.03],[236.75,9.82],[250.75,10.1],[254.75,9.9],[260.75,10.1],[264.75,9.8],[266.75,10.15],[268.75,10],[274.75,10.2],[276.75,9.9],[292.75,10.6],[294.75,10.6],[298.75,10.1],[318.75,10.35],[320.75,10.6],[322.75,10.3],[328.75,10.65],[332.75,10.3],[338.75,10.7],[348.75,10.53],[350.75,10.7],[354.75,10.37],[358.75,10.58],[365.75,10.43],[373.75,10.85],[421.75,10.94]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"cp-pup-1942",kind:"nova",designation:"CP Pup",name:"Nova Puppis 1942",raHours:8.19613,decDeg:-35.35139,peakMagnitude:.73,peakJd:243067675e-2,startJd:243067275e-2,lightCurve:[[0,.95],[4,.73],[4.5,1.3],[5.5,1.47],[6,2.01],[7.75,2.88],[8.75,2.97],[10.75,3.5],[11.75,4.02],[13.75,4.4],[14.75,3.8],[17.75,5],[18.75,4.93],[19.75,5.48],[23.75,5.5],[25.75,5.65],[26.75,5.99],[33.25,6.28],[45.25,6.6],[57.25,6.41],[81.25,6.85],[89.25,6.5],[97.25,6.67],[101.25,7],[113.25,6.66],[125.25,7.1],[135.25,6.96],[231.25,7.86],[279.25,7.8],[327.25,8.33],[407.25,8.18],[423.25,8.59],[471.25,8.53],[503.25,8.99],[551.25,8.97],[567.25,8.7],[583.25,9.47],[615.25,8.95],[655.25,9.5],[751.25,9.55],[815.25,10.09],[847.25,10.02],[879.25,10.48],[911.25,10.34],[1023.25,10.79],[1279.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest bright novae: two magnitudes gone in four days."},{id:"t-crb-1946",kind:"nova",designation:"T CrB",name:"Nova Coronae Borealis 1946",raHours:15.99171,decDeg:25.92017,peakMagnitude:2.5,peakJd:2431860,startJd:2431860,lightCurve:[[0,2.5],[1.5,3.5],[2.5,3.61],[6.5,5.68],[8.5,6.25],[10.5,7.35],[11.5,7.3],[12.5,8],[16,8.68],[32,9.77],[38,9.7],[40,9.45],[44,9.9],[48,9.57],[54,9.9],[58,9.71],[79,9.94],[107,9.76],[111,9.51],[115,8.71],[119,8.46],[159,8.01],[179,8.07],[183,8.47],[191,8.16],[199,8.7],[207,8.81],[211,9.33],[215,9.15],[223,9.47],[297,9.4],[345,9.75],[377,9.57],[425,9.8],[537,9.8]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova. It erupted in 1866 and in 1946, and a third eruption was expected from 2024 on."},{id:"v446-her-1960",kind:"nova",designation:"V446 Her",name:"Nova Herculis 1960",raHours:18.956,decDeg:13.24147,peakMagnitude:4.83,peakJd:24370038e-1,startJd:24370033e-1,lightCurve:[[0,5.2],[.5,4.83],[2,4.9],[2.5,5.4],[3,5.05],[3.5,5.57],[4,5.25],[5,5.5],[6.5,5.4],[7.2,5.78],[8.2,5.6],[9.2,5.98],[10.2,5.92],[11.2,6.21],[16.2,6.1],[17.2,6.23],[18.2,7.2],[19.2,6.51],[20.2,6.78],[26.2,6.97],[27.2,7.24],[28.2,7.13],[29.2,7.45],[31.2,7.2],[40.7,7.57],[44.7,8.25],[46.7,7.84],[56.7,8.15],[60.7,8.9],[70.7,8.7],[72.7,8.14],[76.7,8.71],[80.7,8.47],[82.7,8.87],[86.7,8.57],[90.7,8.93],[107.7,9.11],[111.7,8.94],[115.7,9.27],[139.7,9.38],[151.7,9.91],[155.7,9.72],[173.7,10.51],[221.7,10.95]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v533-her-1963",kind:"nova",designation:"V533 Her",name:"Nova Herculis 1963",raHours:18.23902,decDeg:41.85614,peakMagnitude:3,peakJd:24380605e-1,startJd:24380565e-1,lightCurve:[[0,8],[4,3],[4.5,3],[8,4],[13,3.95],[15,4.6],[21,4.53],[24,5.05],[27,5.15],[32,4.76],[34,4.98],[35,5.39],[37,5.43],[41,6.04],[49,6.02],[56.5,6.34],[60.5,6.11],[74.5,6.72],[102.5,6.99],[137.5,7.81],[197.5,8.31],[217.5,8.8],[225.5,8.57],[233.5,9.03],[237.5,8.78],[277.5,9.44],[301.5,9.46],[315.5,9.86],[323.5,9.73],[339.5,10.05],[355.5,10.74],[363.5,10.32],[371.5,10.6],[387.5,10.69],[427.5,10.38],[435.5,10.84],[443.5,10.74],[451.5,11.33],[459.5,10.98],[467.5,11.17],[507.5,11.16],[539.5,11.66],[603.5,11.7],[619.5,12.05],[651.5,12.03],[659.5,11.74],[667.5,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"hr-del-1967",kind:"nova",designation:"HR Del",name:"Nova Delphini 1967",raHours:20.70565,decDeg:19.16092,peakMagnitude:3.58,peakJd:2439838,startJd:2439646,lightCurve:[[0,11.9],[6,11.8],[12,8.8],[16,8.3],[20,6.7],[30,5.8],[36,5.51],[66,5.55],[78,5.35],[86,4.89],[96,5],[108,4.75],[136,5.13],[152,4.83],[182,4.93],[186,4.59],[192,3.58],[202,5],[220,5.46],[226,5.14],[230,5.45],[232,5.14],[236,5],[242,5.08],[244,4.59],[246,4.45],[254,5.3],[256,4.75],[260,5.69],[268,4.8],[274,4.94],[276,5.45],[280,5.2],[282,5.51],[286,5.58],[292,4.95],[294,5.16],[298,4.94],[311,5.09],[335,4.4],[367,5.76],[407,6.16],[423,6.55],[603,7.43],[907,8.32],[1451,9.41],[2347,10.75]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"An exceptionally slow nova: rose over months and stayed near magnitude 4 to 5 for most of 1967 and 1968."},{id:"lv-vul-1968",kind:"nova",designation:"LV Vul",name:"Nova Vulpeculae 1968",raHours:19.80012,decDeg:27.1715,peakMagnitude:4.5,peakJd:243996425e-2,startJd:243996325e-2,lightCurve:[[0,5],[1,4.5],[2,5],[2.5,4.86],[3,5.1],[3.5,4.88],[4,5.1],[5,4.9],[7,5.4],[8,5.23],[10.5,5.42],[12,5.82],[13,5.4],[13.5,5.74],[14,5.7],[14.5,6.08],[15,5.75],[15.5,5.86],[16,5.6],[17,5.8],[18,5.6],[20.5,6.34],[21,6.2],[22.5,6.84],[23,6.57],[24,6.98],[24.5,6.3],[25,7.1],[26,6.65],[34.25,7.48],[35.25,7.23],[39.25,7.32],[44.25,7.76],[45.25,7.49],[46.25,7.78],[50.25,7.84],[51.25,8.1],[53.25,7.9],[54.25,8.13],[56.25,8],[57.75,8.24],[67.75,8.52],[75.75,8.38],[83.75,8.69],[89.75,8.59],[125.75,9.32],[127.75,9.33],[129.75,8.98],[131.75,9.29],[135.75,9.43],[212.75,9.9],[220.75,10.16],[228.75,10.03],[236.75,10.3],[244.75,10.16],[264.75,10.54],[280.75,10.45],[296.75,10.79],[328.75,10.78]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"fh-ser-1970",kind:"nova",designation:"FH Ser",name:"Nova Serpentis 1970",raHours:18.51307,decDeg:2.61444,peakMagnitude:4.5,peakJd:244063425e-2,startJd:244063125e-2,lightCurve:[[0,7],[2,5],[3,4.5],[3.5,5],[4.5,4.6],[5.5,5],[6.5,4.68],[12.25,4.66],[16.25,5.3],[17.25,5.72],[18.25,5.3],[19.25,5.2],[23.25,5.84],[24.25,5.68],[27.25,5.9],[30.25,5.47],[32.25,5.9],[34.25,5.7],[43.25,6.28],[45.25,6.1],[50.25,6.62],[52.25,6.47],[57.25,6.63],[60.25,7.08],[61.25,6.87],[62.25,7.2],[63.25,6.85],[64.25,7.68],[65.25,7.3],[66.25,8.3],[67.25,7.93],[69.25,9.15],[71.25,9.2],[72.25,9.63],[74.25,9.9],[76.25,9.7],[77.25,10.25],[78.25,10.1],[79.25,10.4],[80.25,10.23],[81.25,10.57],[83.25,10.64],[85.25,10.35],[86.25,11.2],[87.25,10.1],[89.25,11.2],[96.25,11.35],[100.25,11.95],[102.25,11.1],[104.25,11.65],[106.25,11.5],[108.25,12.07],[114.75,11.32],[118.75,11.28],[122.75,10.93],[130.75,10.85],[134.75,10.52],[154.75,10.65],[162.75,10.12],[174.75,9.98],[178.75,10.34],[186.75,9.98],[214.75,10.25],[224.75,10.02],[240.75,10.2],[264.75,10],[272.75,10.2],[280.75,10.05],[288.75,10.4],[296.75,10],[348.75,10.7],[396.75,10.3],[444.75,10.73],[460.75,10.59],[540.75,10.94],[556.75,10.82]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1500-cyg-1975",kind:"nova",designation:"V1500 Cyg",name:"Nova Cygni 1975",raHours:21.19349,decDeg:48.15056,peakMagnitude:1.88,peakJd:244265525e-2,startJd:244265425e-2,lightCurve:[[0,2.44],[1,1.88],[1.5,1.88],[2.5,2.41],[3,3.38],[4,4.28],[8.25,5.81],[11.25,6.46],[22.25,7.35],[33.25,7.73],[34.25,7.97],[37.25,7.86],[40.25,8.3],[43.25,8.19],[48.25,8.6],[49.25,8.46],[66.25,9.04],[70.25,8.93],[75.25,9.23],[76.25,9.03],[80.25,9.39],[81.25,9.19],[83.25,9.35],[84.25,9.13],[86.25,9.39],[89.25,9.32],[90.25,9.54],[93.25,9.37],[105.75,9.86],[193.75,10.43],[201.75,10.7],[209.75,10.47],[257.75,10.94],[265.75,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"One of the fastest novae on record: discovered on 29 August 1975, at its peak of magnitude 1.9 within two days, and two magnitudes down again two days later."},{id:"v842-cen-1986",kind:"nova",designation:"V842 Cen",name:"Nova Centauri 1986",raHours:14.59794,decDeg:-57.6265,peakMagnitude:4.9,peakJd:244675975e-2,startJd:244675725e-2,lightCurve:[[0,5.6],[2.5,4.9],[3.5,5.1],[15.5,5.1],[17.5,5.75],[18.5,5.4],[20.5,5.5],[22.5,5.95],[30.5,6.15],[31.5,6.3],[32,7.5],[34.5,7.2],[38.5,7.5],[39,7],[41.5,7.15],[42.5,6.7],[44.5,7.23],[45.5,6.6],[53,9.3]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"sn-1987a",kind:"supernova",designation:"SN 1987A",name:"Supernova 1987A",raHours:5.59111,decDeg:-69.26975,peakMagnitude:2.98,peakJd:24469425e-1,startJd:24468495e-1,lightCurve:[[0,6.36],[1,6.11],[2,4.63],[4,4.45],[32,3.97],[56,3.15],[93,2.98],[105,3.35],[118,4.11],[134,4.43],[504,8.15],[617,10.27]],source:"V photometry compiled by the Open Supernova Catalog (Sternberg catalogue, IAU circulars, CTIO)",note:"In the Large Magellanic Cloud, 160 000 light years away: the nearest supernova since Kepler's, and invisible north of about 20° N."},{id:"v1974-cyg-1992",kind:"nova",designation:"V1974 Cyg",name:"Nova Cygni 1992",raHours:20.50879,decDeg:52.63078,peakMagnitude:4.27,peakJd:24486753e-1,startJd:24486718e-1,lightCurve:[[0,7.2],[1,5.23],[2,4.62],[3.5,4.27],[4.5,4.59],[6,4.5],[7,4.78],[7.5,4.52],[8,4.82],[10.7,5.25],[11.7,5.66],[16.7,5.85],[21.7,6.47],[22.7,6.3],[27.7,6.46],[29.7,6.83],[34.7,6.9],[35.7,7.25],[36.7,7],[37.7,7.16],[39.7,7.03],[43.7,7.41],[45.7,7.26],[50.7,7.45],[57.7,7.78],[58.7,8.13],[61.7,7.92],[64.7,8.19],[65.7,7.99],[71.7,8.22],[76.7,8.01],[128.2,8.72],[176.2,8.89],[192.2,9.15],[216.2,9.28],[232.2,9.07],[236.2,9.3],[390.2,10.99]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v382-vel-1999",kind:"nova",designation:"V382 Vel",name:"Nova Velorum 1999",raHours:10.74678,decDeg:-52.42533,peakMagnitude:2.88,peakJd:245132225e-2,startJd:245132075e-2,lightCurve:[[0,2.99],[1.5,2.88],[2.5,3.46],[4.5,3.98],[5,4.32],[5.5,4.23],[7.5,4.85],[21.75,6.67],[30.25,7.2],[40.25,7.41],[93.25,7.95],[97.25,8.25],[101.25,8],[113.25,7.96],[129.25,8.5],[155.25,8.47],[163.25,9.1],[179.25,9],[187.25,8.7],[195.25,9.15],[211.25,9.23],[235.25,9.8],[243.25,9.71],[299.25,10.42],[383.25,10.52],[415.25,10.81]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v1494-aql-1999",kind:"nova",designation:"V1494 Aql",name:"Nova Aquilae 1999",raHours:19.38482,decDeg:4.9555,peakMagnitude:4.11,peakJd:245151575e-2,startJd:245151425e-2,lightCurve:[[0,5.15],[.5,4.86],[1,4.27],[1.5,4.11],[2.5,4.35],[5,5.48],[10.5,6.26],[14.25,6.28],[20.25,7.43],[24.25,7.25],[25.25,7.63],[27.25,7.7],[29.25,7.42],[33.25,8.08],[35.25,8.03],[36.25,7.6],[37.25,7.6],[46.25,8.5],[54.25,8.28],[56.25,8.63],[58.25,8.4],[61.25,9.53],[62.25,9],[64.25,9.13],[69.25,8.58],[70.25,8.9],[72.25,8.88],[75.25,8.57],[77.25,9],[79.25,8.8],[81.25,9.7],[83.25,9.6],[85.25,9.8],[86.75,9.5],[88.75,9.54],[90.75,8.9],[92.75,8.85],[96.75,9.63],[102.75,9.7],[104.75,8.98],[106.75,8.73],[116.75,9.63],[118.75,9.6],[120.75,9.07],[122.75,9.26],[124.75,9.8],[128.75,9.36],[134.75,9.75],[147.75,9.92],[155.75,9.81],[259.75,10.96]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"v4743-sgr-2002",kind:"nova",designation:"V4743 Sgr",name:"Nova Sagittarii 2002",raHours:19.01926,decDeg:-22.00167,peakMagnitude:5,peakJd:245253775e-2,startJd:245253675e-2,lightCurve:[[0,5.2],[1,5],[2,5.89],[2.5,5.91],[3.5,6.43],[5,6.45],[5.5,6.86],[6,6.59],[7,6.77],[7.5,7.31],[8.5,6.99],[9,7.09],[10.5,7.86],[11,7.58],[11.5,7.89],[15.75,8.33],[17.75,8.18],[18.75,8.58],[19.75,8.44],[22.75,8.83],[23.75,8.6],[24.75,8.85],[27.75,8.83],[30.75,9.4],[31.75,9.09],[36.25,9.08],[38.25,9.34],[62.25,9.75],[66.25,10.1],[70.25,9.7],[74.25,10],[171.25,10.9]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010"},{id:"rs-oph-2006",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2006",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.8,peakJd:2453779,startJd:2453779,lightCurve:[[0,4.8],[1.25,4.97],[2.75,5.78],[3.25,5.7],[3.75,6.24],[4.25,6.05],[4.75,6.38],[5.25,6.3],[8.5,7.25],[14.5,7.95],[24.5,8.55],[29.5,9.08],[48,9.87],[80,10.28],[107,11.54],[119,11.54],[139,11.98],[147,11.83],[163,12.03],[171,11.97],[175,11.65],[183,11.84],[195,11.64],[203,11.8],[207,12.13],[219,11.45],[277,11.68],[325,11],[341,11.53],[357,11.62],[373,11.3],[405,11.5],[421,11.17],[469,10.96],[501,11.22],[549,10.75],[581,11.08],[597,10.98]],source:"AAVSO, binned by Strope, Schaefer & Henden 2010",note:"A recurrent nova, erupting every twenty years or so (1898, 1907, 1933, 1945, 1958, 1967, 1985, 2006, 2021)."},{id:"v1280-sco-2007",kind:"nova",designation:"V1280 Sco",name:"Nova Scorpii 2007",raHours:16.96145,decDeg:-32.34325,peakMagnitude:3.8,peakJd:2454149,startJd:2454136,lightCurve:[[0,9.7],[13,3.8],[34,5.8],[103,15]],source:"AAVSO (discovery, peak, dust minimum); t2 from Das et al. 2008",note:"Faded from sight quickly when dust formed around it, three weeks after its peak."},{id:"v339-del-2013",kind:"nova",designation:"V339 Del",name:"Nova Delphini 2013",raHours:20.39186,decDeg:20.76772,peakMagnitude:4.4,peakJd:24565214e-1,startJd:24565214e-1,lightCurve:[[0,4.4],[11,6.4],[20,7.4]],source:"Gehrz et al. 2015 (peak, t2, t3)",note:"High in the summer evening sky of the northern hemisphere, and widely photographed."},{id:"v1369-cen-2013",kind:"nova",designation:"V1369 Cen",name:"Nova Centauri 2013",raHours:13.9126,decDeg:-59.15114,peakMagnitude:3.48,peakJd:245663965e-2,startJd:24566285e-1,lightCurve:[[0,5.33],[1.57,4.08],[2.75,3.73],[4.57,4.16],[5.96,4.15],[10.26,3.77],[11.15,3.48],[12.14,3.74],[14.17,4.78],[15.46,4.97],[23.16,4.22],[26.25,4.32],[27.31,4.82],[29.56,5.11],[32.66,4.71],[33.84,4.86],[36.05,4.46],[37.15,4.99],[41.42,4.59],[42.37,4.93],[43.37,4.82],[44.54,5.09],[49.95,5.38],[51.99,5.82],[54.21,5.77]],source:"AAVSO, binned by day, as plotted by Izzo 2017 (arXiv:1704.07214, figure 1)",note:"Discovered on 2 December 2013 by John Seach at magnitude 5.5, it flared several times, reaching about 3.3 around 14 December: the brightest nova of the century so far, and a southern one."},{id:"rs-oph-2021",kind:"nova",designation:"RS Oph",name:"Nova Ophiuchi 2021",raHours:17.83699,decDeg:-6.70792,peakMagnitude:4.6,peakJd:2459436,startJd:2459435,lightCurve:[[0,5],[1,4.6],[2.25,4.77],[3.75,5.58],[4.25,5.5],[4.75,6.04],[5.25,5.85],[5.75,6.18],[6.25,6.1],[9.5,7.05],[15.5,7.75],[25.5,8.35],[30.5,8.88],[49,9.67],[81,10.08],[108,11.34],[120,11.34],[140,11.78],[148,11.63],[164,11.83],[172,11.77],[176,11.45],[184,11.64],[196,11.44],[204,11.6],[208,11.93],[220,11.25],[278,11.48],[326,10.8],[342,11.33],[358,11.42],[374,11.1],[406,11.3],[422,10.97],[470,10.76],[502,11.02],[550,10.55],[582,10.88],[598,10.78]],source:"Recorded discovery and peak (8 and 9 August 2021); curve borrowed from its 2006 eruption",note:"RS Oph's latest eruption, discovered on 8 August 2021. The decline is its 2006 one."}];class nx{static UNIX_EPOCH_JD=24405875e-1;static aroundDate(t){const e=this.julianDayOf(t);return dm.filter(i=>this.magnitudeAt(i,e)!==void 0)}static appearancesAt(t,e){const i=this.julianDayOf(t),s=[];for(const n of dm){const a=this.magnitudeAt(n,i);a!==void 0&&s.push({outburst:n,position:da.ofJ2000(n.raHours,n.decDeg,t,e),magnitude:a})}return s.sort((n,a)=>n.magnitude-a.magnitude)}static brightestAt(t,e){return this.appearancesAt(t,e)[0]}static byId(t){return dm.find(e=>e.id===t)}static magnitudeAt(t,e){const i=t.lightCurve,s=e-t.startJd;if(i.length===0||s<i[0][0]||s>i[i.length-1][0])return;let n=1;for(;n<i.length-1&&i[n][0]<s;)n++;const[a,r]=i[n-1]??i[0],[o,l]=i[n]??i[0];if(o===a)return r;const h=Math.min(1,Math.max(0,(s-a)/(o-a)));return r+h*(l-r)}static julianDayOf(t){return t.getTime()/864e5+this.UNIX_EPOCH_JD}}const gO=[{id:"quadrantids",code:"QUA",name:"Quadrantids",radiantRaHours:15.33,radiantDecDeg:49.7,start:{month:12,day:28},peak:{month:1,day:3},end:{month:1,day:12},peakZhr:110,velocityKmS:41,populationIndex:2.1},{id:"lyrids",code:"LYR",name:"April Lyrids",radiantRaHours:18.13,radiantDecDeg:33.3,start:{month:4,day:16},peak:{month:4,day:22},end:{month:4,day:25},peakZhr:18,velocityKmS:49,populationIndex:2.1},{id:"eta-aquariids",code:"ETA",name:"eta Aquariids",radiantRaHours:22.53,radiantDecDeg:-1,start:{month:4,day:19},peak:{month:5,day:6},end:{month:5,day:28},peakZhr:50,velocityKmS:66,populationIndex:2.4},{id:"alpha-capricornids",code:"CAP",name:"alpha Capricornids",radiantRaHours:20.47,radiantDecDeg:-9.2,start:{month:7,day:3},peak:{month:7,day:30},end:{month:8,day:15},peakZhr:5,velocityKmS:23,populationIndex:2.5},{id:"southern-delta-aquariids",code:"SDA",name:"Southern delta Aquariids",radiantRaHours:22.67,radiantDecDeg:-16.4,start:{month:7,day:12},peak:{month:7,day:30},end:{month:8,day:23},peakZhr:25,velocityKmS:41,populationIndex:3.2},{id:"perseids",code:"PER",name:"Perseids",radiantRaHours:3.22,radiantDecDeg:58,start:{month:7,day:17},peak:{month:8,day:12},end:{month:8,day:24},peakZhr:100,velocityKmS:59,populationIndex:2.2},{id:"southern-taurids",code:"STA",name:"Southern Taurids",radiantRaHours:3.47,radiantDecDeg:13,start:{month:9,day:10},peak:{month:10,day:10},end:{month:11,day:20},peakZhr:5,velocityKmS:27,populationIndex:2.3},{id:"draconids",code:"DRA",name:"October Draconids",radiantRaHours:17.47,radiantDecDeg:54,start:{month:10,day:6},peak:{month:10,day:8},end:{month:10,day:10},peakZhr:10,velocityKmS:20,populationIndex:2.6},{id:"orionids",code:"ORI",name:"Orionids",radiantRaHours:6.35,radiantDecDeg:15.6,start:{month:10,day:2},peak:{month:10,day:21},end:{month:11,day:7},peakZhr:20,velocityKmS:66,populationIndex:2.5},{id:"northern-taurids",code:"NTA",name:"Northern Taurids",radiantRaHours:3.87,radiantDecDeg:22,start:{month:10,day:20},peak:{month:11,day:12},end:{month:12,day:10},peakZhr:5,velocityKmS:29,populationIndex:2.3},{id:"leonids",code:"LEO",name:"Leonids",radiantRaHours:10.13,radiantDecDeg:21.6,start:{month:11,day:6},peak:{month:11,day:17},end:{month:11,day:30},peakZhr:15,velocityKmS:71,populationIndex:2.5},{id:"geminids",code:"GEM",name:"Geminids",radiantRaHours:7.47,radiantDecDeg:32.3,start:{month:12,day:4},peak:{month:12,day:14},end:{month:12,day:17},peakZhr:150,velocityKmS:35,populationIndex:2.6},{id:"ursids",code:"URS",name:"Ursids",radiantRaHours:14.47,radiantDecDeg:75.3,start:{month:12,day:17},peak:{month:12,day:22},end:{month:12,day:26},peakZhr:10,velocityKmS:33,populationIndex:3}],e0=6.5;class fm{static activeAt(t){return gO.flatMap(e=>{const i=this.nearness(e,t);return i<=0?[]:[{shower:e,zhr:e.peakZhr*i,nearness:i}]})}static nearness(t,e){const i=this.dayOfYear(e),s=this.dayOfYear(this.asDate(t.start)),n=this.dayOfYear(this.asDate(t.peak)),a=this.dayOfYear(this.asDate(t.end)),r=this.wrappedDelta(i,n),o=this.wrappedDelta(n,s),l=this.wrappedDelta(a,n);return r<0?r<-o?0:1+r/o:r>0?r>l?0:1-r/l:1}static observedRatePerHour(t,e,i,s=e0){if(e<=0)return 0;const n=e0-s;return t*Math.sin(e*Math.PI/180)/Math.pow(i,n)}static radiantPosition(t,e,i){return da.ofJ2000(t.radiantRaHours,t.radiantDecDeg,e,i)}static dayOfYear(t){const e=Date.UTC(t.getUTCFullYear(),0,1);return Math.floor((Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())-e)/864e5)+1}static asDate(t){return new Date(Date.UTC(2001,t.month-1,t.day))}static wrappedDelta(t,e){const i=t-e;return i>182?i-365:i<-182?i+365:i}}class zi{static QUIET_RATE_PER_HOUR=2;static APEX_RATE_PER_HOUR=8;static POPULATION_INDEX=3;static apexPosition(t,e){const i=oi(t),s=new a0(0,BS(t).elon-90,1),n=Dr(pE(i),p1(s,i)),a=l0(n);return m1(a.ra,a.dec,t,e)}static observedRatePerHour(t,e=e0){const i=zi.APEX_RATE_PER_HOUR*Math.max(0,Math.sin(t*Math.PI/180)),s=e0-e;return(zi.QUIET_RATE_PER_HOUR+i)/Math.pow(zi.POPULATION_INDEX,s)}static schedule(t){const e=new M0(t.seed^1542469173);return Jn.schedule(t).map(i=>{const s=zi.toCartesian({altitudeDeg:Math.asin(e.next())*180/Math.PI,azimuthDeg:e.between(0,360)}),n=i.fromRadiantDeg*Math.PI/180,a=zi.turnAround(s,e.between(0,360)),r={x:s.x*Math.cos(n)+a.x*Math.sin(n),y:s.y*Math.cos(n)+a.y*Math.sin(n),z:s.z*Math.cos(n)+a.z*Math.sin(n)};return{...i,radiant:zi.toHorizontal(r),bearingDeg:zi.bearingFrom(r,s)}})}static turnAround(t,e){const[i,s]=zi.basisAround(t),n=e*Math.PI/180;return{x:i.x*Math.cos(n)+s.x*Math.sin(n),y:i.y*Math.cos(n)+s.y*Math.sin(n),z:i.z*Math.cos(n)+s.z*Math.sin(n)}}static bearingFrom(t,e){const[i,s]=zi.basisAround(t),n=t.x*e.x+t.y*e.y+t.z*e.z,a=zi.normalise({x:e.x-t.x*n,y:e.y-t.y*n,z:e.z-t.z*n});return(Math.atan2(a.x*s.x+a.y*s.y+a.z*s.z,a.x*i.x+a.y*i.y+a.z*i.z)*180/Math.PI%360+360)%360}static basisAround(t){const e=Math.abs(t.y)<.9?{x:0,y:1,z:0}:{x:1,y:0,z:0},i=zi.normalise(zi.cross(t,e));return[i,zi.normalise(zi.cross(t,i))]}static toHorizontal(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{altitudeDeg:Math.asin(Math.min(1,Math.max(-1,t.y/e)))*180/Math.PI,azimuthDeg:(Math.atan2(t.x,-t.z)*180/Math.PI%360+360)%360}}static appearanceOf(t){const e=zi.toCartesian(t.radiant??{altitudeDeg:90,azimuthDeg:0}),i=zi.turnAround(e,t.bearingDeg),s=t.fromRadiantDeg*Math.PI/180;return zi.toHorizontal({x:e.x*Math.cos(s)+i.x*Math.sin(s),y:e.y*Math.cos(s)+i.y*Math.sin(s),z:e.z*Math.cos(s)+i.z*Math.sin(s)})}static toCartesian(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180,s=Math.cos(e);return{x:s*Math.sin(i),y:Math.sin(e),z:-s*Math.cos(i)}}static cross(t,e){return{x:t.y*e.z-t.z*e.y,y:t.z*e.x-t.x*e.z,z:t.x*e.y-t.y*e.x}}static normalise(t){const e=Math.hypot(t.x,t.y,t.z)||1;return{x:t.x/e,y:t.y/e,z:t.z/e}}static TYPICAL_VELOCITY_KM_S=40}const ax="https://ufoathome.org/tle/index.json";class Vs{static MAX_ELEMENT_AGE_DAYS=7;static DAY_MS=864e5;fetchImpl;indexUrls;index;files=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Vs.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/tle/index.json",location.href).href),t.includes(ax)||t.push(ax),t}static FIRST_SNAPSHOT="2021-02-22";async covers(t){const e=Date.parse(`${Vs.FIRST_SNAPSHOT}T00:00:00Z`)-Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS;if(t.getTime()<e)return!1;const i=await this.loadIndex();return i?Object.values(i.index.kinds).some(s=>t.getTime()>=Date.parse(s.from)-Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS&&t.getTime()<=Date.parse(s.to)+Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS):!1}async at(t){const e=await this.loadIndex();if(!e)return;const{index:i,base:s}=e,n=[],a=[];for(const r of Object.keys(i.kinds)){const o=await this.kindAt(r,t,i,s);n.push(...o),a.push(this.coverageOf(r,t,i,o.length>0))}return{objects:n,coverage:a,credit:i.credit,creditUrl:i.source}}async kindAt(t,e,i,s){const n=e.getTime(),a=i.binDays*Vs.DAY_MS,r=Math.floor(n/a),o=n-r*a<a/2?r-1:r+1,l=new Set(i.kinds[t].bins),h=[r,o].map(g=>new Date(g*a).toISOString().slice(0,10)).filter(g=>l.has(g));if(h.length===0)return[];const[u,...d]=await Promise.all([this.json(new URL(`objects-${t}.json`,s).href),...h.map(g=>this.binary(new URL(`${t}/${g}.bin`,s).href))]),f=new Map;for(const g of d)for(const m of Vs.decode(g,i.recordBytes)){const v=f.get(m.norad);(!v||Math.abs(m.epochMs-n)<Math.abs(v.epochMs-n))&&f.set(m.norad,m)}const p=[];for(const g of f.values()){const m=Math.abs(g.epochMs-n)/Vs.DAY_MS;if(m>Vs.MAX_ELEMENT_AGE_DAYS)continue;const v=u[g.norad]??{name:String(g.norad)};v.launch&&Date.parse(`${v.launch}T00:00:00Z`)>n||p.push({norad:g.norad,name:v.name,kind:t,launch:v.launch,stdMag:v.stdMag,elements:g,ageDays:m})}return p}coverageOf(t,e,i,s){const{from:n,to:a}=i.kinds[t],r=e.getTime(),o=Vs.MAX_ELEMENT_AGE_DAYS*Vs.DAY_MS,l=s?"covered":r<Date.parse(n)-o?"before":r>Date.parse(a)+o?"after":"gap";return{kind:t,status:l,from:n,to:a}}static decode(t,e){const i=new DataView(t),s=[];for(let n=0;n+e<=t.byteLength;n+=e)s.push({norad:i.getUint32(n,!0),epochMs:i.getFloat64(n+4,!0),bstar:i.getFloat32(n+12,!0),inclinationDeg:i.getFloat32(n+16,!0),raanDeg:i.getFloat32(n+20,!0),eccentricity:i.getFloat32(n+24,!0),argOfPerigeeDeg:i.getFloat32(n+28,!0),meanAnomalyDeg:i.getFloat32(n+32,!0),meanMotion:i.getFloat64(n+36,!0)});return s}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(!e.ok)continue;return{index:await e.json(),base:t}}catch{}})(),this.index}json(t){return this.cached(t,async e=>e.json())}binary(t){return this.cached(t,async e=>e.arrayBuffer())}cached(t,e){let i=this.files.get(t);return i||(i=this.fetchImpl(t).then(s=>{if(!s.ok)throw new Error(`${t}: ${s.status}`);return e(s)}),i.catch(()=>this.files.delete(t)),this.files.set(t,i)),i}}class vO{lowerM;upperM;add(t,e){if(!(t<=0)){if(e.behindM!==void 0){const i=Di.sizeMAt(e.behindM,t);this.lowerM=this.lowerM===void 0?i:Math.max(this.lowerM,i)}if(e.inFrontM!==void 0){const i=Di.sizeMAt(e.inFrontM,t);this.upperM=this.upperM===void 0?i:Math.min(this.upperM,i)}}}get sizeRange(){return{minM:this.lowerM,maxM:this.upperM}}get empty(){return this.lowerM===void 0&&this.upperM===void 0}get contradictory(){return this.lowerM!==void 0&&this.upperM!==void 0&&this.lowerM>this.upperM}distanceRangeAt(t){return t<=0?{}:{minM:this.lowerM===void 0?void 0:Di.distanceMAt(this.lowerM,t),maxM:this.upperM===void 0?void 0:Di.distanceMAt(this.upperM,t)}}clear(){this.lowerM=void 0,this.upperM=void 0}}class nc{static DEG_PER_SECOND=360/86164.0905;static degOver(t){return Math.max(0,t)*nc.DEG_PER_SECOND}static instants(t,e){if(!(e>0))return 1;const i=nc.degOver(t)/e;return i<1?1:Math.min(nc.MAX_INSTANTS,Math.max(2,Math.ceil(i)))}static MAX_INSTANTS=64}class Ps{static EYE={apertureMm:7,exposureSeconds:.1,resolutionArcsec:60};static WAVELENGTH_M=55e-8;static ARCSEC_PER_RADIAN=180*3600/Math.PI;static UNKNOWN_CAMERA_FOCAL_MM=50;static UNKNOWN_CAMERA_DETAIL_UM=20;static get skyDriftArcsecPerSecond(){return nc.DEG_PER_SECOND*3600}static graspOf(t,e={}){if(t.visualAid)return Ps.visualAidGrasp(t,e.focalLengthMm);const i=e.exposureSeconds??t.exposureSeconds,s=e.fNumber??t.fNumber;if(i===void 0||s===void 0||!(i>0)||!(s>0))return Ps.EYE;const n=e.focalLengthMm??t.frame?.focalLengthMm??Ps.UNKNOWN_CAMERA_FOCAL_MM,a=n/s,r=Ps.resolutionArcsec(t,n,a);return{apertureMm:a,exposureSeconds:Math.min(i,Ps.trailLimitedSeconds(r)),resolutionArcsec:r}}static visualAidGrasp(t,e){const i=t.visualAid,s=Ps.EYE,n=e??t.frame?.focalLengthMm,a=i.magnification??(n!==void 0&&i.eyepieceFocalMm?n/i.eyepieceFocalMm:1),r=Math.min(i.apertureMm,s.apertureMm*a);return{apertureMm:Math.max(r,s.apertureMm),exposureSeconds:s.exposureSeconds,resolutionArcsec:s.resolutionArcsec/Math.max(1,Math.min(a,i.apertureMm/s.apertureMm))}}static resolutionArcsec(t,e,i){const n=(t.detailUm??Ps.UNKNOWN_CAMERA_DETAIL_UM)/1e3/e*Ps.ARCSEC_PER_RADIAN,a=1.22*Ps.WAVELENGTH_M/(i/1e3)*Ps.ARCSEC_PER_RADIAN;return Math.max(n,a)}static trailLimitedSeconds(t){return t/Ps.skyDriftArcsecPerSecond}static gainOverEye(t,e={}){const i=Ps.graspOf(t,e),s=Ps.EYE,n=(i.apertureMm/s.apertureMm)**2,a=i.exposureSeconds/s.exposureSeconds,r=(s.resolutionArcsec/i.resolutionArcsec)**2;return 1.25*Math.log10(n*a*r)}static gainFor(t,e){const i=e.fieldOfViewDeg===void 0?void 0:Ts.focalLengthMmFor(t,e.fieldOfViewDeg);return Ps.gainOverEye(t,{fNumber:e.fNumber,focalLengthMm:i,exposureSeconds:e.exposureSeconds})}}const rx=111320,Ph=Math.PI/180,MO=1.02,yO=1;class cu{static of(t,e){const i=cu.sightings(t,e);if(i.length<2)return;const s=cu.baseline(i);if(!s)return;const{near:n,far:a,closedM:r}=s,o=Math.tan(a.widthDeg/2*Ph)===0?0:Math.tan(n.widthDeg/2*Ph)/Math.tan(a.widthDeg/2*Ph);if(o<MO)return;const l=r/(o-1),h=Di.sizeMAt(l,n.widthDeg),u=i.map(d=>({t:d.t,m:Di.distanceMAt(h,d.widthDeg)}));return{widthM:h,distanceM:u,nearestM:Math.min(...u.map(d=>d.m)),fromT:a.t,toT:n.t,closedM:r}}static sightings(t,e){return t.timeline.allKeyframes.flatMap(i=>{const s=i.shapes.find(r=>r.sourceId===e)?.shape,n=s?.angular?.widthDeg,a=Te(t,i.t);return n===void 0||n<=0||a?.lat===void 0||a.lng===void 0?[]:[{t:i.t,widthDeg:n,lat:a.lat,lng:a.lng,sightAzimuthDeg:s?.aim?.azimuthDeg??a.headingDeg}]}).sort((i,s)=>i.t-s.t)}static baseline(t){let e;for(const i of t)for(const s of t){if(i.t>=s.t)continue;const n=cu.closedAlongSight(i,s),[a,r,o]=n>=0?[s,i,n]:[i,s,-n];o<yO||a.widthDeg<=r.widthDeg||(!e||o>e.closedM)&&(e={near:a,far:r,closedM:o})}return e}static closedAlongSight(t,e){const i=(e.lat-t.lat)*rx,s=(e.lng-t.lng)*rx*Math.cos(t.lat*Ph),n=(t.sightAzimuthDeg??0)*Ph;return i*Math.cos(n)+s*Math.sin(n)}}class rn{static CONVENTIONAL_M=5;static NEAREST_M=.2;static MARGIN=1.1;static resolve(t){if(t.statedM!==void 0&&t.statedM>0)return{distanceM:rn.atLeastNearest(t.statedM),basis:"stated"};if(t.hypothesisM!==void 0&&t.hypothesisM>0)return{distanceM:rn.atLeastNearest(t.hypothesisM),basis:"hypothesis"};if(t.derivedM!==void 0&&t.derivedM>0)return{distanceM:rn.atLeastNearest(t.derivedM),basis:"derived"};const e=rn.largest(t.range?.minM,t.crossing?.behindM),i=rn.smallest(t.range?.maxM,t.crossing?.inFrontM),s=e===void 0?void 0:e*rn.MARGIN,n=i===void 0?void 0:i/rn.MARGIN;return s!==void 0&&n!==void 0?{distanceM:rn.atLeastNearest(s<=n?Math.sqrt(s*n):s),basis:"bounded"}:s!==void 0?{distanceM:rn.atLeastNearest(s),basis:"bounded"}:n!==void 0&&n<rn.CONVENTIONAL_M?{distanceM:rn.atLeastNearest(n),basis:"bounded"}:{distanceM:rn.CONVENTIONAL_M,basis:"conventional"}}static atLeastNearest(t){return Math.max(rn.NEAREST_M,t)}static largest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.max(...e)}static smallest(...t){const e=t.filter(i=>i!==void 0&&i>0);return e.length===0?void 0:Math.min(...e)}}class Ct{static A=6378137;static E2=.00669437999014;static DEG=Math.PI/180;static STANDARD_DISTANCE_KM=100;static DEFAULT_COLOR="#ffb347";static DEFAULT_TRAIN_S=4;static DEFAULT_CRUMBLING={perS:1.2,lifeS:4,magnitudeDrop:3,dropBack:.3,spreadKmS:1,sinkKmS:.6,trainS:2.5};static DEFAULT_BURST={perS:12,lifeS:3.5,magnitudeDrop:3.5,dropBack:.5,spreadKmS:1.5,sinkKmS:.9,trainS:2};static FLARE_MAGNITUDES=.5;static shedsOf(t){return t.sheds?t.sheds:[Ct.DEFAULT_CRUMBLING,...Ct.flareBursts(t)]}static flareBursts(t){const e=t.lightCurve??[],i=[];for(let s=1;s<e.length-1;s++){const n=e[s];e[s-1].absoluteMagnitude-n.absoluteMagnitude<Ct.FLARE_MAGNITUDES||e[s+1].absoluteMagnitude-n.absoluteMagnitude<Ct.FLARE_MAGNITUDES||i.push({...Ct.DEFAULT_BURST,fromT:n.t-1e3,untilT:n.t+1500})}return i}static FADE_MS=1e3;static FADED_MAGNITUDE=8;static TRAIN_POINTS=8;static leadAt(t,e){const i=t.track;if(i.length<2||e<i[0].t||e>i[i.length-1].t)return;let s=0;for(;s<i.length-2&&i[s+1].t<e;)s++;const n=i[s],a=i[s+1],r=a.t-n.t,o=r>0?(e-n.t)/r:0,[l,h]=Ct.alongGreatCircle(n,a,o);return{lat:l,lng:h,heightM:(n.altitudeKm+(a.altitudeKm-n.altitudeKm)*o)*1e3}}static mayDazzle(t){const e=Math.max(1,Math.min(...t.track.map(s=>s.altitudeKm))),i=5*Math.log10(e/Ct.STANDARD_DISTANCE_KM);return t.fragments.some(s=>Math.min(s.absoluteMagnitude,...(s.lightCurve??[]).map(a=>a.absoluteMagnitude))+i<=Ct.DAZZLING_MAGNITUDE)}static detonationsOf(t,e){const i=[];for(const s of t)s.fragments.forEach((n,a)=>{const r=Ct.piecesOf(s).find(l=>l.id===(n.id??String(a)));if(!r)return;const o=(n.lightCurve??[]).filter((l,h,u)=>(h===0||u[h-1].absoluteMagnitude>=l.absoluteMagnitude)&&(h===u.length-1||u[h+1].absoluteMagnitude>l.absoluteMagnitude)).map(l=>({t:l.t,magnitude:l.absoluteMagnitude}));o.push({t:r.untilT,magnitude:r.magnitudeAt(r.untilT)});for(const l of o){if(l.magnitude>Ct.DETONATING_MAGNITUDE||l.t<r.fromT||l.t>r.untilT)continue;const h=Ct.pieceAt(s,r,l.t);if(!h||h.heightM>Ct.AUDIBLE_BELOW_KM*1e3||i.some(d=>d.flashT===l.t&&d.reentryId===s.id))continue;const u=Ct.seenFrom(e,h).distanceKm;i.push({reentryId:s.id,flashT:l.t,t:l.t+u/Ct.SOUND_KM_S*1e3,distanceKm:u,loudness:Math.min(1,(.3+(Ct.DETONATING_MAGNITUDE-l.magnitude)/15)*Math.min(1,30/u))})}});return i.sort((s,n)=>s.t-n.t)}static DETONATING_MAGNITUDE=-12;static AUDIBLE_BELOW_KM=50;static SOUND_KM_S=.31;static DAZZLING_MAGNITUDE=-11;static absoluteMagnitudeAt(t,e){const i=t.lightCurve;if(!i||i.length===0)return t.absoluteMagnitude;if(e<=i[0].t)return i[0].absoluteMagnitude;for(let s=1;s<i.length;s++){const n=i[s-1],a=i[s];if(e<=a.t)return n.absoluteMagnitude+(a.absoluteMagnitude-n.absoluteMagnitude)*(e-n.t)/Math.max(a.t-n.t,1)}return i[i.length-1].absoluteMagnitude}static viewsAt(t,e,i){const s=[];for(const n of t)for(const a of Ct.piecesOf(n)){if(e<a.fromT||e>a.untilT)continue;const r=Ct.pieceAt(n,a,e);if(!r)continue;const o=Ct.seenFrom(i,r);if(o.altitudeDeg<0)continue;const l=Math.min(Ct.FADE_MS,(a.untilT-a.fromT)/4),h=l>0?Math.min(1,(e-a.fromT)/l,(a.untilT-e)/l):1,u=a.magnitudeAt(e)+5*Math.log10(o.distanceKm/Ct.STANDARD_DISTANCE_KM),d=u+(1-h)*Math.max(0,Ct.FADED_MAGNITUDE-u),f=[o];for(let p=1;p<=Ct.TRAIN_POINTS;p++){const g=Math.min(a.trainMs*p/Ct.TRAIN_POINTS,e-a.fromT),m=Ct.pieceAt(n,a,e-g);if(!m||(f.push(Ct.seenFrom(i,m)),g>=e-a.fromT))break}s.push({reentryId:n.id,fragmentId:a.id,head:o,magnitude:d,fade:h,color:a.color,train:f})}return s}static piecesOf(t){const e=Ct.pieces.get(t);if(e)return e;const i=t.track[0]?.t??0,s=t.track[t.track.length-1]?.t??0,n=[];return t.fragments.forEach((a,r)=>{const o=(a.lagS??0)*1e3,l={id:a.id??String(r),fromT:a.fromT??i,untilT:a.untilT??s,lagMsAt:()=>o,acrossKmAt:()=>0,belowKmAt:()=>0,magnitudeAt:h=>Ct.absoluteMagnitudeAt(a,h),color:a.color??Ct.DEFAULT_COLOR,trainMs:(a.trainS??Ct.DEFAULT_TRAIN_S)*1e3};n.push(l),Ct.shedsOf(a).forEach((h,u)=>n.push(...Ct.shedPieces(l,h,u)))}),Ct.pieces.set(t,n),n}static pieces=new WeakMap;static shedPieces(t,e,i=0){const s=e.fromT??t.fromT,n=Math.min(e.untilT??t.untilT,t.untilT);if(!(e.perS>0)||n<=s)return[];const a=Math.floor((n-s)/1e3*e.perS),r=e.spreadKmS??.3,o=e.sinkKmS??.3,l=e.trainS!==void 0?e.trainS*1e3:t.trainMs*(2/3),h=[];for(let u=0;u<a;u++){const d=E=>Ct.hash(`${t.id}/${i}/${u}/${E}`),f=s+(u+d(1))/e.perS*1e3,p=e.lifeS*(.4+1.2*d(2))*1e3,g=e.magnitudeDrop*(.5-.5*Math.log(1-.999*d(3))),m=e.dropBack*(.5+d(4)),v=r*(2*d(5)-1),M=o*(.5+d(6)),x=t.lagMsAt(f),y=t.acrossKmAt(f),w=t.belowKmAt(f),S=E=>Math.max(0,E-f)/1e3;h.push({id:`${t.id}.${i}.${u}`,fromT:f,untilT:Math.min(f+p,Ct.endOf(t)),lagMsAt:E=>x+1e3*Ct.lagOfBraking(2*m,S(E)),acrossKmAt:E=>y+v*S(E),belowKmAt:E=>w+M*S(E),magnitudeAt:E=>t.magnitudeAt(Math.min(E,t.untilT))+g,color:t.color,trainMs:l})}return h}static lagOfBraking(t,e){return t<=0||e<=0?0:e-(1-Math.exp(-t*e))/t}static endOf(t){return t.untilT}static hash(t){let e=2166136261;for(let i=0;i<t.length;i++)e^=t.charCodeAt(i),e=Math.imul(e,16777619);return(e>>>0)/4294967296}static pieceAt(t,e,i){const s=i-e.lagMsAt(i),n=Ct.leadAt(t,s);if(!n)return;const a=e.acrossKmAt(i),r=n.heightM-e.belowKmAt(i)*1e3;if(a===0)return{...n,heightM:r};const o=Ct.leadAt(t,s-1e3)??n;return{...Ct.across(o,n,a),heightM:r}}static across(t,e,i){const s=Ct.DEG,n=t.lat*s,a=e.lat*s,r=(e.lng-t.lng)*s,o=Math.atan2(Math.sin(r)*Math.cos(a),Math.cos(n)*Math.sin(a)-Math.sin(n)*Math.cos(a)*Math.cos(r))+Math.PI/2,l=i/6371,h=Math.asin(Math.sin(a)*Math.cos(l)+Math.cos(a)*Math.sin(l)*Math.cos(o)),u=e.lng*s+Math.atan2(Math.sin(o)*Math.sin(l)*Math.cos(a),Math.cos(l)-Math.sin(a)*Math.sin(h));return{lat:h/s,lng:u/s}}static seenFrom(t,e){const i=Ct.ecef(t),s=Ct.ecef(e),n=s[0]-i[0],a=s[1]-i[1],r=s[2]-i[2],o=t.lat*Ct.DEG,l=t.lng*Ct.DEG,h=-Math.sin(l)*n+Math.cos(l)*a,u=-Math.sin(o)*Math.cos(l)*n-Math.sin(o)*Math.sin(l)*a+Math.cos(o)*r,d=Math.cos(o)*Math.cos(l)*n+Math.cos(o)*Math.sin(l)*a+Math.sin(o)*r,f=Math.hypot(h,u,d);return{altitudeDeg:Math.asin(d/f)/Ct.DEG,azimuthDeg:(Math.atan2(h,u)/Ct.DEG+360)%360,distanceKm:f/1e3}}static ecef(t){const e=t.lat*Ct.DEG,i=t.lng*Ct.DEG,s=Math.sin(e),n=Ct.A/Math.sqrt(1-Ct.E2*s*s);return[(n+t.heightM)*Math.cos(e)*Math.cos(i),(n+t.heightM)*Math.cos(e)*Math.sin(i),(n*(1-Ct.E2)+t.heightM)*s]}static alongGreatCircle(t,e,i){const s=h=>{const u=h.lat*Ct.DEG,d=h.lng*Ct.DEG;return[Math.cos(u)*Math.cos(d),Math.cos(u)*Math.sin(d),Math.sin(u)]},n=s(t),a=s(e),r=Math.max(-1,Math.min(1,n[0]*a[0]+n[1]*a[1]+n[2]*a[2])),o=Math.acos(r);let l;if(o<1e-12)l=n;else{const h=Math.sin((1-i)*o)/Math.sin(o),u=Math.sin(i*o)/Math.sin(o);l=[n[0]*h+a[0]*u,n[1]*h+a[1]*u,n[2]*h+a[2]*u]}return[Math.atan2(l[2],Math.hypot(l[0],l[1]))/Ct.DEG,Math.atan2(l[1],l[0])/Ct.DEG]}}class _l{static typed=new Map;static of(t){return _l.typed.get(t)}static set(t,e){const i=e.trim();i===""?_l.typed.delete(t):_l.typed.set(t,i)}static forget(){_l.typed.clear()}}class iv{static FIRST_DAY="2022-01-01";static mayCover(t){return new Date(t).toISOString().slice(0,10)>=iv.FIRST_DAY}}class ox{constructor(t,e,i){this.citation=t,this.covers=e,this.load=i}loading;mayCover(t){return this.covers(t)}async between(t,e,i,s){try{return await(await this.provider()).between(t,e,i,s)}catch{return{status:"failed"}}}async describe(t,e){try{return await(await this.provider()).describe?.(t,e)}catch{return}}provider(){if(!this.loading){const t=this.load();this.loading=t,t.catch(()=>{this.loading===t&&(this.loading=void 0)})}return this.loading}}const xO="Aircraft positions: adsb.lol feeders and contributors, Open Database License 1.0 (https://www.adsb.lol/docs/open-data/historical/)",wO="Aircraft positions: Flightradar24 API (https://fr24api.flightradar24.com/)",cx="flightradar24",bO=rs.point("aircraft").provide(rs.BUILT_IN,[{id:"adsb-lol",name:"adsb.lol",credit:"adsb.lol feeders and contributors, ODbL 1.0",creditUrl:"https://www.adsb.lol/docs/open-data/historical/",create:()=>new ox(xO,c=>iv.mayCover(c),async()=>new(await Ht(async()=>{const{AdsbLolArchiveProvider:c}=await import("./AdsbLolArchiveProvider-veDw9Mxo.js");return{AdsbLolArchiveProvider:c}},__vite__mapDeps([38,1,2,3,4,5,6,7]),import.meta.url)).AdsbLolArchiveProvider)},{id:cx,name:"Flightradar24",credit:"Flightradar24, on your own subscription",creditUrl:"https://fr24api.flightradar24.com/",keyUrl:"https://fr24api.flightradar24.com/key-management",create:()=>new ox(wO,c=>c>=Date.UTC(2016,4,11)&&c<=Date.now(),async()=>new(await Ht(async()=>{const{Flightradar24Provider:c}=await import("./Flightradar24Provider-BR8_7wmx.js");return{Flightradar24Provider:c}},__vite__mapDeps([39,1,2,3,4,5,6,7]),import.meta.url)).Flightradar24Provider({token:()=>_l.of(cx)}))}]);class Ss{static MAX_GAP_S=60;static FT_TO_M=.3048;static EARTH_RADIUS_KM=6371;static seenFrom(t,e,i){const s=Ss.positionAt(t,i);if(!s)return;const n=Ct.seenFrom(e,s.geo);if(!(n.altitudeDeg<0))return{track:t,sky:n,altitudeFt:s.altitudeFt,groundSpeedKt:s.groundSpeedKt,trackDeg:s.trackDeg,angularRateDegPerS:Ss.angularRate(t,e,i)}}static viewsAt(t,e,i){return t.flatMap(s=>Ss.seenFrom(s,e,i)??[])}static groundDistanceKm(t,e){const i=Math.PI/180,s=Math.sin((e.lat-t.lat)*i/2)**2+Math.cos(t.lat*i)*Math.cos(e.lat*i)*Math.sin((e.lng-t.lng)*i/2)**2;return 2*Ss.EARTH_RADIUS_KM*Math.asin(Math.min(1,Math.sqrt(s)))}static wrapLongitude(t){return((t+180)%360+360)%360-180}static positionAt(t,e){const i=t.points;if(i.length===0||e<i[0].t||e>i[i.length-1].t)return;let s=0;for(;s<i.length-1&&i[s+1].t<=e;)s++;const n=i[s],a=i[s+1]??n,r=a.t-n.t;if(r>Ss.MAX_GAP_S*1e3)return;const o=r>0?(e-n.t)/r:0,l=n.altitudeFt+(a.altitudeFt-n.altitudeFt)*o,h=(a.lng-n.lng+540)%360-180;return{geo:{lat:n.lat+(a.lat-n.lat)*o,lng:Ss.wrapLongitude(n.lng+h*o),heightM:l*Ss.FT_TO_M},altitudeFt:l,groundSpeedKt:n.groundSpeedKt,trackDeg:n.trackDeg}}static angularRate(t,e,i){const s=Ss.positionAt(t,i-500),n=Ss.positionAt(t,i+500);if(!s||!n)return;const a=Ss.unit(Ct.seenFrom(e,s.geo)),r=Ss.unit(Ct.seenFrom(e,n.geo)),o=Math.min(1,Math.max(-1,a[0]*r[0]+a[1]*r[1]+a[2]*r[2]));return Math.acos(o)*180/Math.PI}static unit(t){const e=t.altitudeDeg*Math.PI/180,i=t.azimuthDeg*Math.PI/180;return[Math.cos(e)*Math.sin(i),Math.cos(e)*Math.cos(i),Math.sin(e)]}}const lx="https://ufoathome.org/fireballs/index.json";class Xa{static FIRST_MONTH="2018-12";static STRIKING_MAGNITUDE=-1;static COLOR="#eef2ff";static TRAIN_S=.3;fetchImpl;indexUrls;index;months=new Map;constructor(t={}){this.fetchImpl=t.fetchImpl??fetch.bind(globalThis),this.indexUrls=t.indexUrls??Xa.defaultIndexUrls()}static defaultIndexUrls(){const t=[];return typeof location<"u"&&/^https?:$/.test(location.protocol)&&t.push(new URL("/fireballs/index.json",location.href).href),t.includes(lx)||t.push(lx),t}static mayCover(t){return new Date(t).toISOString().slice(0,7)>=Xa.FIRST_MONTH}async credit(){return(await this.loadIndex())?.index.credit}async between(t,e){if(!Xa.mayCover(e))return;const i=await this.loadIndex();if(!i)return;const s=new Set([new Date(t).toISOString().slice(0,7),new Date(e).toISOString().slice(0,7)]);return[...s].some(a=>a>=i.index.from&&a<=i.index.to)?(await Promise.all([...s].filter(a=>i.index.months.includes(a)).map(a=>this.monthOf(a,i.base)))).flat().filter(a=>a.t>=t&&a.t<=e):void 0}static seenFrom(t,e){const i=Xa.peakFraction(t),s={lat:t.from[0]+(t.to[0]-t.from[0])*i,lng:t.from[1]+(t.to[1]-t.from[1])*i,heightM:t.peakHeightKm*1e3},n=Ct.seenFrom(e,s);if(!(n.altitudeDeg<0))return{record:t,peak:n,magnitude:t.peakMagnitude+5*Math.log10(n.distanceKm/Ct.STANDARD_DISTANCE_KM)}}static asReentry(t,e){const i=t.t-e,s=i+Math.max(t.durationS,.1)*1e3;return{id:`gmn-${t.id}`,track:[{t:i,lat:t.from[0],lng:t.from[1],altitudeKm:t.from[2]},{t:s,lat:t.to[0],lng:t.to[1],altitudeKm:t.to[2]}],fragments:[{absoluteMagnitude:t.peakMagnitude,color:Xa.COLOR,trainS:Xa.TRAIN_S}]}}static peakFraction(t){const e=t.from[2]-t.to[2];return Math.abs(e)<1e-6?.5:Math.min(1,Math.max(0,(t.from[2]-t.peakHeightKm)/e))}loadIndex(){return this.index??=(async()=>{for(const t of this.indexUrls)try{const e=await this.fetchImpl(t);if(e.ok)return{index:await e.json(),base:t}}catch{}})(),this.index}monthOf(t,e){let i=this.months.get(t);return i||(i=this.fetchImpl(new URL(`${t}.json`,e).href).then(s=>s.ok?s.json():[]).catch(()=>[]),this.months.set(t,i)),i}}fw();const Hb="satellites-change",Gb="fireballs-change",Vb="references-change",Wb="aircraft-change",Xb="rr0-confrontation",hx="comet:",ux="nova:",SO=new URL(""+new URL("lunar-relief.bin-ByThqxUn.gz",import.meta.url).href,import.meta.url).href,EO=new URL(""+new URL("stars-mag7.5-B43R6Wvg.bin",import.meta.url).href,import.meta.url).href,AO=new URL(""+new URL("stars-mag7.5-9-BLV2tFmZ.bin",import.meta.url).href,import.meta.url).href,_O=-18,TO={sun:{altitudeDeg:-3,azimuthDeg:180,magnitude:-26.7},moon:{altitudeDeg:-90,azimuthDeg:0,phase:{phaseFraction:0,illuminatedFraction:0},magnitude:-12.7},planets:[]},Jd={lat:0,lng:0,elevationM:0,headingDeg:void 0,pitchDeg:0,fovDeg:60};class me extends HTMLElement{creditsButton;set ownCredits(t){this.creditsButton.hidden=!t}static get observedAttributes(){return["src","star-catalog-src","deep-star-catalog-src","show-compass","max-pixel-ratio",Cl,Ol,Xo]}shadow;stageElement;frameElement;sceneCanvas;busyElement;busyNote;loaderNote;loaderNotVideo;ufoElement;sceneRenderer;hoverTooltip;ghostPath;flightMark;markedFlight;holding=!1;resizeObserver;sizeEstimates=new Map;sizeEstimatesFor;approaches={key:"",of:new Map};distanceHypotheses=new Map;depths=new Map;directionScratch=new _;meteorScheduleFor;lightningScheduleFor;lightningFlashes=[];lastLightningT;lastTimeMs=0;interpretationShown;confrontationReadings=[];confrontationTolerance;confrontationSignature="";comparing=!1;inTheRound=!0;lastSkyKey;starCatalog;starCatalogRequest=0;static tleArchive=new Vs;satellitesFor;satelliteRequest=0;satelliteStatus="none";satellites;satellitePassesMemo;static fireballArchive=new Xa;fireballs;static aircraftProviders=new Map;static SOUND_LOOKBACK_MS=3e5;static TRAIL_LOOKBACK_MS=36e5;static TRAIL_MAX_AIRCRAFT=60;static NO_CONTRAILS=[];static upperAirProviders=new Map;static NO_PRESENCE=new Map;aircraftSource=bO[0];static trafficRuntimeLoading;static trafficRuntime;static loadTrafficRuntime(){return me.trafficRuntimeLoading??=Ht(()=>import("./trafficRuntime-B_bwWY8d.js"),__vite__mapDeps([40,32,41,1,5,2,3,4,6,7]),import.meta.url).then(t=>me.trafficRuntime=t),me.trafficRuntimeLoading.catch(()=>{me.trafficRuntimeLoading=void 0}),me.trafficRuntimeLoading}traffic;lastSun;get sunAltitudeDeg(){return this.sceneRenderer.sunAltitudeDeg??this.lastSun?.altitudeDeg}decorMemo;seatedMemo;starCatalogDepth=0;weatherAudio=new tc;vehicleAudio=new _y;aircraftAudio;vehicleHearing=new Uf;decorAircraftHearing;bodyHearing;decorModelSounds=new Map;decorModelsAsked=new Set;thunderTimeoutId;handleFullscreenChange=()=>{this.resizeToStage(),this.hoverTooltip.hidden=!0;for(const t of[this.hoverTooltip,this.shadow.getElementById("credits-panel")])t&&typeof t.hidePopover=="function"&&t.matches(":popover-open")&&t.hidePopover();this.tooltipOver=document.fullscreenElement};handlePointerMove=t=>{if(this.lastHover={clientX:t.clientX,clientY:t.clientY,altKey:t.altKey},this.ghostMissedSinceMs=void 0,this.hoverFrame!==void 0&&t.altKey===this.hoverAlt){this.hoverPending=!0;return}this.hoverAlt=t.altKey,this.hoverAt(this.lastHover),this.hoverFrame===void 0&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=void 0,this.hoverPending&&this.lastHover&&this.hoverAt(this.lastHover),this.hoverPending=!1}))};ghostMissedSinceMs;static GHOST_KEPT_MS=600;ghostStillUnder(t,e){const i=this.ufoElement.canvasElement.getBoundingClientRect();if(i.width===0||i.height===0)return!0;const s=(t.clientX-i.left)/i.width*2-1,n=1-(t.clientY-i.top)/i.height*2;return this.sceneRenderer.ghostsReadableAt(s,n)?this.sceneRenderer.pickGhostAt(s,n)?(this.ghostMissedSinceMs=void 0,!0):(this.ghostMissedSinceMs??=e,e-this.ghostMissedSinceMs>me.GHOST_KEPT_MS):!1}hoverFrame;hoverPending=!1;hoverAlt=!1;lastPlayingHoverMs=0;static PLAYING_HOVER_MS=150;lastHover;tooltipOver=null;hoverAt(t){if(this.showCompassFor({hovered:!0}),this.holding){this.hoverTooltip.hidden=!0;return}const e=this.ufoElement.canvasElement,i=e.getBoundingClientRect();if(i.width===0||i.height===0)return;const s=(t.clientX-i.left)/i.width*e.width,n=(t.clientY-i.top)/i.height*e.height;if(this.ufoElement.hasVisibleShapeAt(s,n)){this.hoverTooltip.hidden=!0;return}const a=(t.clientX-i.left)/i.width*2-1,r=-((t.clientY-i.top)/i.height*2-1);if(!this.ghostPath.hasAttribute("hidden")&&!this.sceneRenderer.ghostsReadableAt(a,r))return;const o=this.pickAt(a,r,!0,t.altKey);o?this.showHoverTooltip(t,t.altKey&&o.detail?o.detail():o.name):this.hoverTooltip.hidden=!0,this.showGhostPath(o?.path,i)}showGhostPath(t,e){if(!t){this.ghostPath.toggleAttribute("hidden",!0);return}const i=this.stageElement.getBoundingClientRect(),s=d=>({x:e.left-i.left+(d.x+1)/2*e.width,y:e.top-i.top+(1-d.y)/2*e.height}),n=s(t.from),a=s(t.to),r=s({x:0,y:0});this.ghostPath.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`);const[o,l,h,u]=Array.from(this.ghostPath.children);for(const d of[o,l])d.setAttribute("x1",String(n.x)),d.setAttribute("y1",String(n.y)),d.setAttribute("x2",String(a.x)),d.setAttribute("y2",String(a.y));h.setAttribute("cx",String(r.x)),h.setAttribute("cy",String(r.y)),u.setAttribute("cx",String(a.x)),u.setAttribute("cy",String(a.y)),this.ghostPath.toggleAttribute("hidden",!1)}pickAt(t,e,i=!0,s=!1){const n=this.naming,a=n.names;if(s&&this.sceneRenderer.pickDropAt(t,e)){const S=a.ghostTooltip,E=S.drop[this.ufoElement.sighting.lens?.glass??"lens"];return{kind:"drop",name:E,detail:()=>S.dropDetail.replace("{name}",E)}}const r=this.sceneRenderer.pickBodyAt(t,e);if(r)return{kind:"sky",id:r,name:this.bodyName(r)};const o=this.interpretationShown?this.sceneRenderer.pickInterpretationBodyAt(t,e):void 0,l=o?this.interpretationShown?.bodies.find(S=>S.id===o):void 0,h=l?this.said.read(l.title)||this.explainedName(l.explains)||this.kindName(l):void 0;if(o!==void 0&&h)return{kind:"body",id:o,name:h};const u=this.skyEventPickAt(t,e,(S,E)=>!E.inSky);if(u)return u;const d=i?this.ghostPick(t,e):void 0;if(d)return d;if(this.sceneRenderer.pickAfterimageAt(t,e)){const S=this.naming.names.afterimageTooltip;return{kind:"afterimage",name:S.name,detail:()=>S.detail.replace("{name}",S.name)}}const f=this.pickDecorAt(t,e)??this.sceneRenderer.pickPeakAt(t,e),p=f?this.ufoElement.sighting.decor.find(S=>S.id===f):void 0;if(p){const S=this.said.read(p.title)||n.decorKind(p.kind);return{kind:"decor",id:p.id,name:S,detail:()=>this.decorTooltip(p,S)}}const g=this.sceneRenderer.pickRailwayAt(t,e);if(g){const S=a.railwayTooltip;return{kind:"railway",id:g.line.id,name:ka.name(g.line,S),detail:()=>ka.detail(g,S,E=>this.distanceText(E))}}const m=this.trafficTooltipAt(t,e);if(m)return{kind:"traffic",name:m};const v=this.skyEventPickAt(t,e,(S,E)=>E.inSky===!0&&!S.pickedAfterSatellites);if(v)return v;const M=this.sceneRenderer.pickSatelliteAt(t,e);if(M)return{kind:"satellite",name:a.satelliteTooltip.replace("{name}",M.name).replace("{mag}",M.magnitude.toLocaleString(void 0,{maximumFractionDigits:1})).replace("{height}",Math.round(M.heightKm).toLocaleString())};const x=this.skyEventPickAt(t,e,(S,E)=>E.inSky===!0&&S.pickedAfterSatellites===!0);if(x)return x;const y=this.sceneRenderer.pickOpticsAt(t,e);if(y){const S=a.opticsTooltips[y.id].replace("{angle}",String(Math.round(y.angleDeg??0)));return{kind:"optics",id:y.id,name:S.split(" — ")[0],detail:()=>S}}const w=this.sceneRenderer.pickStarAt(t,e);if(w){const S=w.star.mag,E=w.altitudeDeg,b=E<0?a.starTooltipBelow:a.starTooltip,A=n.star(w.star);return{kind:"star",name:A,detail:()=>b.replace("{name}",A).replace("{mag}",S.toLocaleString(void 0,{maximumFractionDigits:Math.abs(S)<1?2:1})).replace("{alt}",String(Math.round(Math.abs(E))))}}}ghostLights=new Map;static GHOST_LIGHT_KEPT_MS=1e3;lightOfGhost(t,e){const i=this.ufoElement.canvasElement,s={x:8/Math.max(1,i.clientWidth),y:8/Math.max(1,i.clientHeight)},n=`${Math.round(t/s.x)}:${Math.round(e/s.y)}`,a=performance.now(),r=this.ghostLights.get(n);if(r&&a-r.atMs<me.GHOST_LIGHT_KEPT_MS)return r.light;let o=this.shiningDecorNear(t,e,2*Math.max(s.x,s.y)),l;if(!o)for(const[h,u]of[[0,0],[1,0],[-1,0],[0,1],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]]){const d=this.pickAt(t+h*s.x,e+u*s.y,!1);if(d?.kind==="star")l??=d;else if(d){o=d;break}}return o??=this.shiningDecorNear(t,e,6*Math.max(s.x,s.y)),o??=l,this.ghostLights.size>256&&this.ghostLights.clear(),this.ghostLights.set(n,{light:o??null,atMs:a}),o??null}ghostPick(t,e){const i=this.sceneRenderer.pickGhostAt(t,e);if(!i)return;const s=this.naming.names.ghostTooltip,n=i.beyond?{kind:"sky",id:"sun",name:this.bodyName("sun")}:this.lightOfGhost(i.source.x,i.source.y)??void 0,a=(n?.kind==="star"?n.name.split(" — ")[0]:n?.name)??s.unnamed,r=i.ghost,l=(Pe.scatters(r)?s.halo:r.cause==="glass"?s.double:s.ghost).replace("{name}",a),h=r.scale<0?s.opposite:r.scale===1?s.around:s.sameSide;return{kind:"ghost",id:n?.id,name:l,detail:()=>s.detail.replace("{name}",l).replace("{cause}",s.causes[r.cause??"lens"]).replace("{where}",h),path:{from:{x:2*(r.offset?.[0]??0)+r.scale*i.source.x,y:2*(r.offset?.[1]??0)+r.scale*i.source.y},to:i.source}}}shiningDecorNear(t,e,i){let s;for(const n of this.ufoElement.sighting.decor){if(!(n.kind==="streetlight"||n.kind==="trafficlight"||(n.lights?.length??0)>0||n.kind==="vehicle"&&n.lit))continue;const r=this.sceneRenderer.decorScreenBox(n.id);if(!r)continue;const o=Math.hypot(Math.max(r.minX-t,0,t-r.maxX),Math.max(r.minY-e,0,e-r.maxY));if(o>i||s&&o>=s.distance)continue;const l=this.said.read(n.title)||this.naming.decorKind(n.kind);s={distance:o,pick:{kind:"decor",id:n.id,name:l}}}return s?.pick}glassWettingOf(t){const e=JSON.stringify([t.lens,t.instrumentId,t.weatherTrack.allKeyframes.map(i=>[i.t,i.weather.precipitationType,i.weather.precipitationIntensity,i.weather.windDirectionDeg,i.weather.windSpeed])]);if(this.glassWetting?.sighting!==t||this.glassWetting.key!==e){const i=new Yo(s=>{if(!Pe.records(t.instrument)||!Pe.falling(t.lens))return 0;const n=th(t,s*1e3),a=Te(t,s*1e3);return(n.precipitationAmount??1)*Pe.impactRate(n,t.lens?.glass,a&&{headingDeg:a.headingDeg??0,pitchDeg:a.pitchDeg,windFromDeg:n.windDirectionDeg,windSpeedMS:n.windSpeed})});this.glassWetting={sighting:t,key:e,wetting:i}}return this.glassWetting.wetting}glassWetting;get skyEventsShown(){return this.skyEventsOf(this.ufoElement.sighting)}skyEventsStartDate;skyEventsMerged;skyEventsOf(t){const e=t.skyEvents,i=this.fireballs?.reentries,s=this.skyEventsMerged;if(s&&s.stated===e&&s.fireballs===i)return s.shown;const n=i?.length?{...e,reentries:[...e?.reentries??[],...i]}:e;return this.skyEventsMerged={stated:e,fireballs:i,shown:n},n}skyEventTexts=new Map;skyEventTextsLanguage;loadSkyEventTexts(t){const e=zh(Sr.preferencesFor(this),Bh);e!==this.skyEventTextsLanguage&&(this.skyEventTexts.clear(),this.skyEventTextsLanguage=e);for(const i of t)this.skyEventTexts.has(i)||i.messages.load(e).then(s=>{this.skyEventTextsLanguage===e&&this.skyEventTexts.set(i,s)},()=>{})}skyEventPickAt(t,e,i){const s=this.skyEventsShown;if(!s)return;const n=this.sceneRenderer.pickSkyEventAt(t,e,i),a=n?zg.map(d=>Rr.of(d)).find(d=>d.key===n.kind):void 0,r=n&&a?Rr.eventsOf(s,a).find(d=>d.id===n.id):void 0;if(!n||!a||!r)return;const o=this.skyEventTexts.get(a);if(!o){this.loadSkyEventTexts([a]);return}const l=this.said.read(r.title)||o.name,h=a.describe?.(r,n,{said:this.said,texts:o,name:l,distance:d=>this.distanceText(d)}),u=h?.detail??(n.distanceM!==void 0?`${l}, ${this.distanceText(n.distanceM)}`:void 0);return{kind:a.pickKind??"skyEvent",id:r.id,name:h?.name??l,...u!==void 0?{detail:()=>u}:{}}}distanceText(t){return t>=1e3?`${(t/1e3).toLocaleString(void 0,{maximumFractionDigits:1})} km`:`${t.toLocaleString(void 0,{maximumFractionDigits:t<10?1:0})} m`}decorTooltip(t,e){const i=h=>h.toLocaleString(void 0,{maximumFractionDigits:h<10?1:0}),s=ht.sizeOf(t),n=this.sceneRenderer.decorDistanceM(t.id),a=n===void 0?"":this.distanceText(n),o=this.naming.names.decorTooltip.replace("{name}",e).replace("{size}",`${i(s.widthM)} × ${i(s.lengthM)} × ${i(s.heightM)} m`),l=this.said.read(t.note);return l?`${o.replace("{distance}",a)}. ${l}`:o.replace("{distance}",a)}computedKinds=new Map;computedKindTexts=new Map;bodyModelKinds=new Map;showInterpretation(t){const e=E0.kinds(),i=this.obstaclesOf(this.ufoElement.sighting.decor);this.interpretationObstacles=i;const{interpretation:s,kindOf:n}=Ur.expandWithKinds(t,e,{obstacles:i});if(this.interpretationAsked=t,this.interpretationShown=s,this.computedKinds=n,this.loadComputedKindTexts(),Ur.loaded(t,e))return;const a=Ur.load(t,e);this.sceneRenderer.holdUntil(a),a.then(()=>{this.interpretationAsked!==t||!Ur.loaded(t,e)||(this.showInterpretation(t),this.ufoElement.refreshSoundControls(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())})}interpretationAsked;interpretationObstacles=yv.NONE;obstaclesMadeOf;obstaclesOf(t){return this.obstaclesMadeOf?.decor!==t&&(this.obstaclesMadeOf={decor:t,obstacles:yv.of(t,e=>ht.sizeOf(e))}),this.obstaclesMadeOf.obstacles}recomputeAmongNewDecor(){const t=this.interpretationAsked;!t||!Ur.computes(t,E0.kinds())||this.obstaclesOf(this.ufoElement.sighting.decor).signature!==this.interpretationObstacles.signature&&(this.showInterpretation(t),this.ufoElement.refreshSoundControls())}computedInterpretation(t){const e=E0.kinds(),i=Ur.loaded(t,e)?Promise.resolve():Ur.load(t,e),{interpretation:s,phenomenonOf:n}=Ur.expandWithKinds(t,e,{obstacles:this.obstaclesOf(this.ufoElement.sighting.decor)});return{interpretation:s??t,phenomenonOf:n,loaded:i}}loadComputedKindTexts(){const t=this.namesLanguage;if(t)for(const e of new Set(this.computedKinds.values()))this.computedKindTexts.has(e)||e.messages.load(t).then(i=>{t===this.namesLanguage&&this.computedKindTexts.set(e,i)}).catch(()=>{})}kindName(t){const e=this.computedKinds.get(t.id),i=e?this.computedKindTexts.get(e):void 0;if(i?.name)return i.name;const s=t.model.id;if(s==="figure")return this.naming.decorKind("entity");if(!s||t.model.url!==void 0)return;if(!this.bodyModelKinds.has(s)){this.bodyModelKinds.set(s,void 0),this.sceneRenderer.entryOfDecorModel(s).then(a=>this.bodyModelKinds.set(s,[a?.kind].flat()[0])).catch(()=>{});return}const n=this.bodyModelKinds.get(s);return n&&this.naming.decorKind(n)||void 0}explainedName(t){if(!t?.length)return;const e=this.ufoElement.sighting.timeline.allKeyframes,i=t.map(s=>{for(const n of e){const a=this.said.read(n.shapes.find(r=>r.sourceId===s)?.shape.title);if(a)return a}}).filter(s=>!!s);return i.length?i.join(", "):void 0}bodyName(t){const e=t.startsWith(hx)?t.slice(hx.length):void 0,i=e?Bb.find(n=>n.id===e):void 0;if(i)return this.naming.comet(i);const s=t.startsWith(ux)?nx.byId(t.slice(ux.length)):void 0;return s?this.naming.nova(s):this.naming.body(t)}get naming(){return this.sceneNaming}sceneNaming=new Q2;namesLanguage;ready=Promise.resolve();async loadSceneNames(){const t=zh(Sr.preferencesFor(this),Bh);if(t===this.namesLanguage)return;this.namesLanguage=t;const e=await eS(t);t===this.namesLanguage&&(this.applySceneNaming(new Q2(e)),this.computedKindTexts.clear(),this.loadComputedKindTexts())}setBusy(t,e=""){this.busyElement.hidden=!t,this.busyNote.textContent=t?e:"",this.busyElement.setAttribute("aria-label",e),this.busyElement.setAttribute("aria-busy",String(t))}renderLoaderText(t,e){let i=0;const s=(n,a)=>{n.setAttribute("aria-label",a),n.replaceChildren(),a.split(" ").forEach((r,o)=>{o>0&&n.append(" ");const l=document.createElement("span");l.className="scene-loader-word",l.setAttribute("aria-hidden","true");for(const h of r){const u=document.createElement("span");u.className="scene-loader-letter",u.style.setProperty("--i",String(i++)),u.textContent=h,l.append(u)}n.append(l),i++})};s(this.loaderNotVideo,t),i+=6,s(this.loaderNote,e)}applySceneNaming(t){this.sceneNaming=t,t.loaded&&(this.creditsButton.title=t.names.credits,this.creditsButton.setAttribute("aria-label",t.names.credits),this.renderLoaderText(t.names.notAVideo,t.names.isASimulation),this.sceneRenderer.setCompassPoints(t.names.compassPoints))}showHoverTooltip(t,e){const i=this.hoverTooltip;if(i.textContent=e,i.hidden=!1,typeof i.showPopover=="function"){const u=document.fullscreenElement;i.matches(":popover-open")&&u!==this.tooltipOver&&i.hidePopover(),i.matches(":popover-open")||i.showPopover(),this.tooltipOver=u}const{innerWidth:s,innerHeight:n}=window,a=12,r=4,o=Math.min(t.clientX+a,s-i.offsetWidth-r),l=t.clientY+a,h=l+i.offsetHeight+r>n?t.clientY-a-i.offsetHeight:l;i.style.left=`${Math.max(r,o)}px`,i.style.top=`${Math.max(r,h)}px`}handlePointerLeave=()=>{this.lastHover=void 0,this.hoverTooltip.hidden=!0,this.ghostPath.toggleAttribute("hidden",!0),this.showCompassFor({hovered:!1})};hearDetonations(t,e,i,s){const n=`${i.lat.toFixed(4)},${i.lng.toFixed(4)}`,a=this.detonationsFor;(!a||n!==a.key||t.length!==a.reentries.length||t.some((l,h)=>l!==a.reentries[h]))&&(this.detonationsFor={reentries:[...t],key:n,detonations:t.length?Ct.detonationsOf(t,i):[]});const r=this.detonationsFor.detonations;if(s)return;const o=this.lastDetonationT;if(this.lastDetonationT=e,!(o===void 0||e<o||e-o>me.DETONATION_JUMP_MS||this.ufoElement.playbackState!=="playing"))for(const l of r)l.t>o&&l.t<=e&&this.weatherAudio.playDetonation(l.loudness)}detonates(t){const e=[...t.skyEvents?.reentries??[],...this.fireballs?.reentries??[]],i=Te(t,0),s=t.event.place?.[0],n=i?.lat??s?.lat,a=i?.lng??s?.lng;return e.length>0&&n!==void 0&&a!==void 0&&Ct.detonationsOf(e,{lat:n,lng:a,heightM:this.altitudeOf(i)}).length>0}detonationsFor;lastDetonationT;static DETONATION_JUMP_MS=2e3;handleLightningFlash(t){if(clearTimeout(this.thunderTimeoutId),this.filmSound){this.filmThunderAtMs=this.lastTimeMs+is.thunderDelayMs(t)*this.ufoElement.playbackRate;return}this.thunderTimeoutId=window.setTimeout(()=>this.weatherAudio.playThunder(),is.thunderDelayMs(t))}handleFirstInteraction=()=>{this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume(),!this.interacted&&(this.interacted=!0,this.setWeather(th(this.ufoElement.sighting,this.lastTimeMs)))};interacted=!1;applyLevel(){if(this.filmSound)return;const t=this.ufoElement.level;this.weatherAudio.setLevel(t),this.vehicleAudio.setLevel(t),this.aircraftAudio?.setLevel(t)}handlePageGesture=()=>{this.ufoElement.playbackState==="playing"&&this.handleFirstInteraction()};unlockIfAlreadyActivated(){this.interacted||navigator.userActivation?.hasBeenActive&&this.handleFirstInteraction()}static GESTURES=["pointerdown","pointerup","touchend","click","keydown"];handleTimeUpdate=t=>{if(this.lastTimeMs=t.detail.time,this.syncAnimationsToPlayback(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.playbackState==="playing"){this.sceneRenderer.frame(performance.now());const e=performance.now();this.lastHover&&!this.ghostPath.hasAttribute("hidden")&&e-this.lastPlayingHoverMs>=me.PLAYING_HOVER_MS&&(this.lastPlayingHoverMs=e,this.ghostStillUnder(this.lastHover,e)&&this.hoverAt(this.lastHover))}this.placeFlightMark(),this.ufoElement.repaintChrome()};syncAnimationsToPlayback(){const t=this.ufoElement.playbackState==="playing",e=t||this.filming;this.sceneRenderer.setAnimationsRunning(e,e);const i=t||this.filmSound!==void 0;this.weatherAudio.setPaused(!i),this.vehicleAudio.setPaused(!i),this.aircraftAudio?.setPaused(!i),t&&this.unlockIfAlreadyActivated(),t||clearTimeout(this.thunderTimeoutId)}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${xI}</style>${yI}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.frameElement=this.shadow.getElementById("frame"),this.sceneCanvas=this.shadow.getElementById("scene-canvas"),this.sceneRenderer=new ct(this.sceneCanvas),this.sceneRenderer.onReferencesSettled=()=>this.dispatchEvent(new CustomEvent(Vb));const e=this.shadow.getElementById("scene-loader");this.loaderNote=this.shadow.getElementById("scene-loader-note"),this.loaderNotVideo=this.shadow.getElementById("scene-loader-not-video"),this.busyElement=this.shadow.getElementById("scene-busy"),this.busyNote=this.shadow.getElementById("scene-busy-note"),this.loader=e,this.poster=new ou(this.shadow.getElementById("scene-poster"),()=>{this.loader.style.animationDelay=!this.poster.up&&this.holding?"0s":"",this.applyHold()}),this.sceneRenderer.onFirstFrameHold=n=>{this.holding=n,this.applyHold()},this.hoverTooltip=this.shadow.getElementById("hover-tooltip"),this.ghostPath=this.shadow.getElementById("ghost-path"),this.flightMark=this.shadow.getElementById("flight-mark"),this.ufoElement=document.createElement(Nm),this.ufoElement.classList.add("ufo-overlay"),this.ufoElement.paintsShapes=!1,this.ufoElement.observerMapSnapshotSource=n=>this.snapshotMapOf(n),this.forwardPlayerAttributes(),this.ufoElement.addEventListener("lookat",n=>this.lookToward(n.detail)),this.ufoElement.style.setProperty("--ufo-canvas-background","transparent"),this.ufoElement.style.setProperty("--ufo-canvas-border","none"),this.ufoElement.fullscreenTarget=this.stageElement,this.shadow.getElementById("ufo-slot").replaceWith(this.ufoElement),this.ufoElement.creditShownExternally=!0,this.creditsButton=this.shadow.getElementById("credits-button");const i=this.shadow.getElementById("credits-panel"),s=this.shadow.getElementById("credits-list");i.addEventListener("beforetoggle",n=>{n.newState==="open"&&Hs.fill(s,this)}),this.sceneRenderer.onMapSubjectBounds=n=>this.ufoElement.setMapSubjectBounds(n),this.ufoElement.addEventListener("timeupdate",this.handleTimeUpdate),this.ufoElement.addEventListener("revealrequest",()=>this.poster.release()),this.ufoElement.addEventListener(pw,()=>this.poster.restore()),this.ufoElement.seekPreviewPainter=(n,a)=>this.seekPreviewOf(a).paint(n,a),typeof VideoEncoder<"u"&&typeof OffscreenCanvas<"u"&&(this.ufoElement.filmer={film:(n,a,r)=>this.film(n,a,r),generativeKit:(n,a,r)=>this.generativeKit(n,a,r),fileName:()=>this.filmFileName(),kitFileName:()=>this.filmFileName().replace(/\.mp4$/," - kit.zip"),pictureSize:()=>this.filmPictureSize(),hasMap:()=>this.ufoElement.hasObserverMap,durationS:()=>this.ufoElement.seekableDuration/this.filmRate()/1e3,positionS:()=>this.ufoElement.currentTime/this.filmRate()/1e3}),this.ufoElement.addEventListener("mutedchange",()=>this.applyLevel()),this.ufoElement.ambientSound=n=>n.vehicle!==void 0||n.decor.some(a=>a.engine!==void 0)||n.decor.some(a=>gv.kindOf(a,this.decorModelSounds.get(a.model?.id??""))!==void 0)||this.interpretationShown?.bodies.some(a=>a.sound)===!0||n.weatherTrack.allKeyframes.some(a=>a.weather.precipitationType!=="none"||a.weather.windSpeed>1)||this.detonates(n)||(this.traffic?.audible?.size??0)>0,this.ufoElement.addEventListener("referenceview",n=>this.applyReferenceView(n.detail)),this.ufoElement.addEventListener("traceview",n=>this.sceneRenderer.setTracesShown(n.detail.shown)),this.ufoElement.canvasElement.addEventListener("pointermove",this.handlePointerMove),this.ufoElement.canvasElement.addEventListener("pointerleave",this.handlePointerLeave);for(const n of me.GESTURES)this.addEventListener(n,this.handleFirstInteraction,!0)}get said(){return this.saidTexts??=new lu(Sr.preferencesFor(this))}saidTexts;traceLabelsFor;observerHeadlightsAt(t,e){const i=t.vehicle;return!i||!Os.isRoad(i.kind)?void 0:{setting:mm.at(i.headlights??"auto",i.headlightKeyframes,e)??"auto",headingDeg:this.travelHeadingAt(t,e)}}travelHeadingAt(t,e){const i=Te(t,e);if(!i)return 0;for(const s of[400,-400]){const n=Te(t,e+s);if(!n||i.lat===void 0||i.lng===void 0||n.lat===void 0||n.lng===void 0)break;const a=re(n.lat,n.lng,i.lat,i.lng);if(Math.hypot(a.x,a.z)<.8)continue;return(Math.atan2(a.x,-a.z)*180/Math.PI+(s<0?180:0)+360)%360}return i.headingDeg??0}routeCache;routeOf(t){const e=t.allKeyframes;if(this.routeCache?.track===t&&this.routeCache.count===e.length)return this.routeCache.route;const i=e.flatMap(n=>n.pose.lat!==void 0&&n.pose.lng!==void 0?[{lat:n.pose.lat,lng:n.pose.lng}]:[]),s=i.length>=2?i:void 0;return this.routeCache={track:t,count:e.length,route:s},s}traceLabels(t){const e=Sr.preferencesFor(this).join();if(this.traceLabelsFor?.traces!==t||this.traceLabelsFor.language!==e){const i=new Map;for(const s of t){const n=this.said.read(s.title);n&&i.set(s.id,n)}this.traceLabelsFor={traces:t,language:e,labels:i}}return this.traceLabelsFor.labels}connectedCallback(){rs.changes.addEventListener("change",this.onModulesChanged),this.saidTexts=void 0,this.ready=this.loadSceneNames(),this.sceneRenderer.restoreContext(),this.resizeToStage(),this.updateAstronomy(this.lastTimeMs),this.loadStars(),this.resizeObserver=new ResizeObserver(()=>this.resizeToStage()),this.resizeObserver.observe(this.frameElement),this.watchVisibility(),document.addEventListener("fullscreenchange",this.handleFullscreenChange);for(const e of me.GESTURES)document.addEventListener(e,this.handlePageGesture,!0);const t=this.getAttribute("src");t&&this.loadFromSrc(t)}watchVisibility(){this.visibilityObserver?.disconnect(),!(typeof IntersectionObserver>"u"||this.hasAttribute("always-live"))&&(this.visibilityObserver=new IntersectionObserver(t=>{if(t[t.length-1].isIntersecting){this.sceneRenderer.resume();return}this.ufoElement.pause(),this.sceneRenderer.suspend()},{rootMargin:"100px"}),this.visibilityObserver.observe(this))}visibilityObserver;disconnectedCallback(){rs.changes.removeEventListener("change",this.onModulesChanged),this.visibilityObserver?.disconnect(),this.resizeObserver?.disconnect(),document.removeEventListener("fullscreenchange",this.handleFullscreenChange);for(const t of me.GESTURES)document.removeEventListener(t,this.handlePageGesture,!0);this.sceneRenderer.stopTwinkle(),clearTimeout(this.thunderTimeoutId),this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.seekPreview?.dispose(),this.seekPreview=void 0,queueMicrotask(()=>{this.isConnected||this.sceneRenderer.releaseContext()})}attributeChangedCallback(t,e,i){if(t==="src"&&i&&i!==e&&this.isConnected&&this.loadFromSrc(i),(t==="star-catalog-src"||t==="deep-star-catalog-src")&&i!==e&&this.isConnected&&this.loadStars(),t==="show-compass"&&i!==e&&this.sceneRenderer.setShowCompass(this.hasAttribute("show-compass")),t==="max-pixel-ratio"&&i!==e){const s=Number(i);this.sceneRenderer.setMaxPixelRatio(Number.isFinite(s)&&s>0?s:Math.min(window.devicePixelRatio||1,2))}(t===Cl||t===Ol||t===Xo)&&i!==e&&this.forwardPlayerAttributes(),t===Xo&&this.stageElement.classList.toggle("minified",i!==null)}forwardPlayerAttributes(){for(const t of[Cl,Ol,Xo]){const e=this.getAttribute(t);e===null?this.ufoElement.removeAttribute(t):this.ufoElement.setAttribute(t,e)}}setCompassForced(t){this.showCompassFor({forced:t})}compassHovered=!1;compassForced=!1;showCompassFor(t){this.compassHovered=t.hovered??this.compassHovered,this.compassForced=t.forced??this.compassForced,this.sceneRenderer.setCompassForced(this.compassForced||this.compassHovered)}lookToward(t){const e=Te(this.ufoElement.sighting,this.lastTimeMs);if(t.kind==="observer"||e?.lat===void 0||e.lng===void 0||e.headingDeg===void 0){this.setLookOffset(0,0);return}const{x:i,z:s}=re(t.lat,t.lng,e.lat,e.lng);if(Math.hypot(i,s)<1)return this.setLookOffset(0,0);const n=(Math.atan2(i,-s)*180/Math.PI+360)%360;this.setLookOffset(((n-e.headingDeg)%360+540)%360-180,-e.pitchDeg)}setLookOffset(t,e){this.sceneRenderer.setLookOffset(t,e),this.ufoElement.setLookOffset(t,e),this.updateAstronomy(this.lastTimeMs)}setIndoorLook(t,e){this.sceneRenderer.setIndoorLook(t,e)}setCloudRendering(t){this.sceneRenderer.setCloudRendering(t)}setWeather(t){this.sceneRenderer.setWeather(t),this.weatherAudio.setOutsideHeard(Os.transmission(this.ufoElement.sighting.vehicle)),this.weatherAudio.setAmbient(t.precipitationType,t.precipitationIntensity*(t.precipitationAmount??1),t.windSpeed);const e=this.ufoElement.sighting.around;this.weatherAudio.setAround(pi.aroundBedRms(e),pi.aroundBedShape(e)??[])}pickCloudAt(t,e){return this.sceneRenderer.pickCloudAt(t,e)}cloudDirectionAt(t,e){return this.sceneRenderer.cloudDirectionAt(t,e)}pickDecorAt(t,e){return this.sceneRenderer.pickDecorAt(t,e)}decorScreenBox(t){return this.sceneRenderer.decorScreenBox(t)}decorDrawnOffset(t){return this.sceneRenderer.decorDrawnOffset(t)}decorGroundPointAt(t,e,i,s=0){return this.sceneRenderer.decorGroundPointAt(t,e,i,s)}decorMetresPerNdcY(t){return this.sceneRenderer.decorMetresPerNdcY(t)}decorGrabHeightAt(t,e,i){return this.sceneRenderer.decorGrabHeightAt(t,e,i)}bodyScreenBox(t){return this.sceneRenderer.bodyScreenBox(t)}pickPlacedBodyAt(t,e){return this.sceneRenderer.pickPlacedBodyAt(t,e)}resumeWeatherAudio(){this.weatherAudio.resume(),this.vehicleAudio.resume(),this.aircraftAudio?.resume()}async loadFromSrc(t){const e=dx.recording(t);this.holdForNewScene(e);const i=await e;this.documentUrl=new URL(t,location.href).href,this.showPoster(i.image,this.documentUrl,!this.ufoElement.playRequested),this.sightingData=i}loader;poster;showPoster(t,e,i=!0){this.poster.show(t,e,i)}applyHold(){const t=this.holding,e=this.poster.up;this.loader.hidden=!t||e,t&&(this.hoverTooltip.hidden=!0),this.ufoElement.captionHeld=t||e,this.ufoElement.controlsHeld=t||e,this.ufoElement.holdClock(t)}holdForNewScene(t){this.sceneRenderer.holdForNewScene(t)}get documentUrl(){return this.sceneRenderer.documentUrl}set documentUrl(t){this.sceneRenderer.documentUrl=t}get sightingData(){return this.ufoElement.sightingData}set sightingData(t){const e=s1.recording(t);this.ufoElement.playerTitle=void 0,this.ufoElement.sightingData=e,this.requireModules(e.modules),this.upperAirHeardLive=void 0,this.seekPreview?.recordingChanged(e),this.showInterpretation(this.inTheRound?this.ufoElement.sighting.interpretation:void 0),this.syncAccountHidden(),this.applyFrameFormat(),this.lastTimeMs=0,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(0)}onModulesChanged=t=>{t.detail==="skyEvents"&&this.sceneRenderer.setSkyEvents(this.skyEventsShown,!0,this.skyEventsStartDate)};requireModules(t){if(!t?.length)return;const e=this.documentUrl,i=Ht(async()=>{const{ModuleSession:s}=await import("./ModuleSession-Cdilmebx.js");return{ModuleSession:s}},__vite__mapDeps([42,1,2,3,4,5,6,7]),import.meta.url).then(({ModuleSession:s})=>s.shared.require(t,e)).then(()=>this.sceneRenderer.setDecorModelProvider(new Ib));this.sceneRenderer.holdUntil(i)}seekPreview;seekPreviewOf(t){const e=this.sceneCanvas.width>0&&this.sceneCanvas.height>0?this.sceneCanvas.width/this.sceneCanvas.height:1.7777777777777777,i=Math.round(t.width/e);return t.height!==i&&(t.height=i),this.seekPreview??=new Jf(this,()=>document.createElement(i0))}showAt(t){this.ufoElement.currentTime=t,this.framesAtAsk=this.sceneRenderer.framesDrawn}framesAtAsk=0;snapshotTo(t){if(this.sceneRenderer.frame(performance.now()),this.sceneRenderer.framesDrawn===this.framesAtAsk)return!1;const e=t.getContext("2d");return e?(e.imageSmoothingQuality="high",e.drawImage(this.sceneCanvas,0,0,t.width,t.height),!0):!1}filmName;filmFileName(){return`${(this.filmName??"").replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim()||"observation"}.mp4`}filming=!1;async film(t,e,i){const[{VideoExport:s},{FilmChrome:n}]=await Promise.all([Ht(()=>import("./VideoExport-B8ZhHNnd.js").then(r=>r.a),[],import.meta.url),Ht(()=>import("./FilmChrome-DYiyzoB_.js"),[],import.meta.url)]),a=await n.loadLogo();return this.filmScene(t,r=>s.film({...r,frameAt:(o,l,h)=>r.frameAt(o,l,h)?(n.paint(h,this.ufoElement.filmChrome(t),a),!0):!1},e,i))}async generativeKit(t,e,i){const[{GenerativeKit:s},{generativeKitMessages:n},{toSightingJson:a}]=await Promise.all([Ht(()=>import("./GenerativeKit-BmhvjjzB.js"),__vite__mapDeps([43,44,45]),import.meta.url),Ht(()=>import("./GenerativeKitMessages-BwG7cWZX.js"),__vite__mapDeps([46,1]),import.meta.url),Ht(()=>Promise.resolve().then(()=>FE),void 0,import.meta.url)]),r=zh(Sr.preferencesFor(this),Bh),[o]=await Promise.all([n.load(r),this.sceneRenderer.loadControlPasses()]),l=this.sceneRenderer.areReferencesShown;this.sceneRenderer.setReferencesShown(!1);try{return await this.filmScene({...t,caption:!1,time:!1,map:!1},h=>s.make({film:h,drawControlPasses:()=>this.sceneRenderer.drawControlPasses(),recording:a(this.ufoElement.sighting),title:this.filmName??"",source:h.about?.source,language:r},o,e,i))}finally{this.sceneRenderer.setReferencesShown(l)}}async filmScene(t,e){if(this.filming)throw new Error("Already filming");const i=this.ufoElement,s=i.currentTime;i.pause();const n={width:this.sceneCanvas.clientWidth,height:this.sceneCanvas.clientHeight},a=t.height&&n.height>0?t.height/n.height:this.sceneRenderer.maxPixelRatio;this.filming=!0,this.sceneRenderer.holdPixelRatio(a),i.filmMap(t.map),this.syncAnimationsToPlayback();try{const r=t.height??this.sceneCanvas.height,o=t.height&&n.height>0?Math.round(t.height*n.width/n.height):this.sceneCanvas.width,l=this.filmRate(),h=Math.min(i.seekableDuration,t.toS!==void 0?t.toS*1e3*l:i.seekableDuration),u=Math.min(h,Math.max(0,(t.fromS??0)*1e3*l));return await e({fromMs:u,toMs:h,rate:l,width:o,height:r,frameAt:(d,f,p)=>this.filmFrameAt(d,f,p),hearInto:d=>this.hearInto(d),about:{title:this.filmName,description:i.filmDescription,source:this.documentUrl?new URL(this.documentUrl,location.href).href:void 0}})}finally{this.filming=!1,this.sceneRenderer.holdPixelRatio(void 0),i.filmMap(void 0),i.currentTime=s,this.syncAnimationsToPlayback()}}filmRate(){const t=this.ufoElement.playbackRate;return t>0?t:1}filmPictureSize(){const t=this.sceneRenderer.maxPixelRatio;return{width:Math.round(this.sceneCanvas.clientWidth*t),height:Math.round(this.sceneCanvas.clientHeight*t)}}filmSound;liveSound;filmThunderAtMs;hearInto(t){if(t){this.liveSound??={weather:this.weatherAudio,vehicle:this.vehicleAudio,aircraft:this.aircraftAudio},this.filmSound=t,this.weatherAudio=new tc(t),this.vehicleAudio=new _y(t);const e=me.trafficRuntime;this.aircraftAudio=this.liveSound.aircraft&&e?this.newAircraftAudio(e):void 0}else this.liveSound&&(this.weatherAudio.dispose(),this.vehicleAudio.dispose(),this.aircraftAudio?.dispose(),this.weatherAudio=this.liveSound.weather,this.vehicleAudio=this.liveSound.vehicle,this.aircraftAudio=this.liveSound.aircraft,this.liveSound=void 0,this.filmSound=void 0,this.filmThunderAtMs=void 0);this.ufoElement.hearInto(t),this.syncAnimationsToPlayback()}filmFrameAt(t,e,i){this.ufoElement.currentTime!==t&&(this.ufoElement.currentTime=t),this.filmThunderAtMs!==void 0&&t>=this.filmThunderAtMs&&(this.filmThunderAtMs=void 0,this.weatherAudio.playThunder()),this.sceneRenderer.render();const s=this.sceneRenderer.framesDrawn;return this.sceneRenderer.frame(e),this.sceneRenderer.framesDrawn===s?!1:(i.drawImage(this.sceneCanvas,0,0,i.canvas.width,i.canvas.height),!0)}referenceAspect(t){return this.sceneRenderer.referenceAspect(t)}screenPointOf(t){return this.sceneRenderer.screenPointOf(t)}horizonPointAt(t){const e=t*Math.PI/180,i=this.sceneRenderer.screenPointOf(new _(Math.sin(e),0,-Math.cos(e)));return i&&{x:(i.ndcX+1)/2,y:(1-i.ndcY)/2}}directionAt(t,e){return this.sceneRenderer.directionAt(t,e)}referenceFailure(t){return this.sceneRenderer.referenceFailure(t)}applyReferenceView(t){this.sceneRenderer.setReferencesShown(t.shown);for(const e of this.ufoElement.sighting.references){const i=t.views?.[e.id];this.sceneRenderer.setReferenceView(e.id,{opacity:i?i.shown?i.opacity:0:t.opacity})}}get currentTerrainAttribution(){return this.sceneRenderer.currentTerrainAttribution}get currentRoadAttribution(){return this.sceneRenderer.currentRoadAttribution}get currentWaterAttribution(){return this.sceneRenderer.currentWaterAttribution}get currentRailwayAttribution(){return this.sceneRenderer.currentRailwayAttribution}setTerrainProviders(t){this.liveTerrainProviders=t,this.snapshotKey=void 0,this.applySnapshots(this.ufoElement.sighting.snapshots)}liveTerrainProviders;snapshotKey="none";applySnapshots(t){const e=jd.isEmpty(t)?"none":`${JSON.stringify(t)}
|
|
8993
8993
|
${this.documentUrl??""}
|
|
8994
8994
|
${hi.generation}`;if(e===this.snapshotKey)return;const i=this.snapshotKey!==void 0&&this.traffic?.set!==void 0;this.snapshotKey=e,this.sceneRenderer.setTerrainProviders(Qf.providers(t,this.documentUrl,this.liveTerrainProviders??hw())),this.ufoElement.observerMapSnapshot=this.snapshotMapOf(t),i&&(this.traffic=void 0,this.decorMemo=void 0)}snapshotMapOf(t){const e=jd.held(t,"map");if(!e)return;const i=`${hi.address(e.src,this.documentUrl)}
|
|
8995
8995
|
${hi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,imagery:Qf.map(e,this.documentUrl)}),this.snapshotMap.imagery}snapshotMap;setDecorModelProvider(t){this.sceneRenderer.setDecorModelProvider(t)}get decorModelCredits(){return[...new Map(this.sceneRenderer.currentDecorModelCredits.map(e=>[`${e.title}|${e.author??""}|${e.license}|${e.sourceUrl??""}`,e])).values()]}applyFrameFormat(){const t=this.ufoElement.sighting.instrument,e=Di.CANVAS_HEIGHT_PX,i=Ts.frameWidthPx(t,e);this.frameElement.style.setProperty("--frame-aspect",`${i} / ${e}`)}resizeToStage(){const t=this.frameElement.getBoundingClientRect(),e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height));this.sceneCanvas.width=e,this.sceneCanvas.height=i,this.sceneRenderer.resize(e,i)}async loadStars(){const t=[{magnitudeLimit:cm,url:this.getAttribute("star-catalog-src")??EO},{magnitudeLimit:lm,url:this.getAttribute("deep-star-catalog-src")??AO}],e=this.instrumentReach(),i=++this.starCatalogRequest;this.starCatalogDepth=e>cm?lm:cm;const s=await Oa.upTo(t,e);i===this.starCatalogRequest&&(this.starCatalog=s,this.sceneRenderer.compileNextFrameOffThread(),this.updateAstronomy(this.lastTimeMs))}ensureStarsDeepEnough(){!this.starCatalog||this.starCatalogDepth>=lm||this.instrumentReach()<=this.starCatalogDepth||this.loadStars()}instrumentReach(){const t=this.ufoElement.sighting,e=Ps.gainFor(t.instrument,{fNumber:Te(t,0)?.fNumber,fieldOfViewDeg:ns.fovOf(t,0),exposureSeconds:t.exposure});return lf(_O,e)}updateAstronomy(t){this.ensureStarsDeepEnough(),this.applySceneAt(t);const e=Xs.windowEndingAt(t,this.exposureSeconds()),i=e.seconds,s=this.degreesPerPixelAt(t),n=nc.instants(i,s),a=Math.max(n,this.ufoElement.exposureTimes(t).length,Xs.instants(this.decorWithTraffic(this.ufoElement.sighting),Te(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,i,s),Xs.bodyInstants(this.interpretationShown?.bodies??[],Te(this.ufoElement.sighting,t)?.elevationM??0,e.fromMs,t,s));if(a<=1){this.sceneRenderer.setExposure(1);return}const r=this.ufoElement.sighting.observerTrack.turnIsViewOnly(e.fromMs,t)?t:void 0;this.sceneRenderer.setExposure(a,o=>this.applySceneAt(e.fromMs+e.ms*o/(a-1),{viewAt:r,sky:Math.floor(o*n/a)!==Math.floor((o-1)*n/a),stepMs:e.ms/a}))}exposureSeconds(){return this.ufoElement.sighting.exposure??0}degreesPerPixelAt(t){const e=this.sceneCanvas.height;return e<=0?0:ns.fovOf(this.ufoElement.sighting,t)/e}roadGradeAt(t,e){return t.observerTrack.allKeyframes.length<2?0:gl.at(t,e,this.sceneRenderer.bodyGround)}get roadGradeDeg(){return this.roadGradeAt(this.ufoElement.sighting,this.ufoElement.currentTime)}applySceneAt(t,e){const i=this.ufoElement.sighting;e||this.sceneRenderer.setRecordingTime(t),this.setWeather(th(i,t)),this.sceneRenderer.setInstrument(i.instrument,Te(i,t)?.fNumber),this.sceneRenderer.setLightPollution(i.lightPollution),e||this.vehicleAudio.setVoices(this.vehicleHearing.at(i,t)),e||this.pushAircraftSound(i,t),this.updateMeteorShower(i,t),this.updateLightning(i,t,e!==void 0),this.sceneRenderer.setDecor(this.seatedDecor(this.decorWithTraffic(i),t)),this.recomputeAmongNewDecor(),this.sceneRenderer.setDecorPresence(this.traffic?.set?.presence??me.NO_PRESENCE),this.sceneRenderer.setDecorSunlight(this.trafficSunlight(t)),this.sceneRenderer.setContrails(this.traffic?.contrails??me.NO_CONTRAILS),this.sceneRenderer.setContrailSunlight(this.contrailSunlight(t));const s=Te(i,t);this.sceneRenderer.setReferences(i.references,s?.lat!==void 0&&s.lng!==void 0?{lat:s.lat,lng:s.lng}:void 0),e||this.sceneRenderer.setReferencesTime({t,playing:this.ufoElement.playbackState==="playing",timeScale:this.ufoElement.playbackRate});const n=Te(i,0),a=tl(i,0),r=xr(i.event.time??{},s?.lng??Jd.lng,i.event.utcOffsetHours),o=i.weatherSource!==void 0&&r?vI(r):void 0,l=Object.fromEntries(vx(tl(i,t)).map(C=>[C.id,Iy(t,i.weatherTrack,a,n,s,C.id,C.instances?.length?void 0:o)]));this.sceneRenderer.setCloudOffset(Iy(t,i.weatherTrack,a,n,s,void 0,o),l);const h=e?.viewAt!==void 0?Te(i,e.viewAt):void 0,u=s&&h?{...s,headingDeg:h.headingDeg,pitchDeg:h.pitchDeg,rollDeg:h.rollDeg,fovDeg:h.fovDeg}:s;this.sceneRenderer.setObserverPose(u?{...u,pitchDeg:u.pitchDeg+this.roadGradeAt(i,e?.viewAt??t)}:Jd),this.sceneRenderer.setLensOptics(this.lensOpticsAt(t)),this.sceneRenderer.setInstrumentGain(Ps.gainFor(i.instrument,{fNumber:s?.fNumber,fieldOfViewDeg:ns.fovOf(i,t),exposureSeconds:i.exposure}),i.instrument.detailUm!==void 0,ma.byId(s?.filter).opticalDensity),this.sceneRenderer.setMedium(Au.mediumOf(i.instrument.medium,Au.byId(i.film)),i.exposure,s?.fNumber??i.instrument.fNumber,i.iso,i.metering),this.sceneRenderer.setLensGhosts(Pe.optics(i.instrument,s?.fNumber??i.instrument.fNumber,i.lens,this.glassWettingOf(i).stateAt(t/1e3),t)),this.sceneRenderer.setPerception(Go.perceptionOf(i.account?.observerPerception)),this.sceneRenderer.setGait(ii.bodyAt(i,t,this.ufoElement.steadyBody)),this.sceneRenderer.updateDecorAnchoring(Te(i,0),s,t),this.placeBodiesAt(t,e===void 0),this.sceneRenderer.updateDecorLitState(t,e?.stepMs??0),this.applySnapshots(i.snapshots),this.sceneRenderer.setObserverRoute(this.routeOf(i.observerTrack)),this.sceneRenderer.setObserverHeadlights(this.observerHeadlightsAt(i,t)),this.sceneRenderer.setTerrainOrigin(s?.lat,s?.lng,()=>{this.placeBodiesAt(this.lastTimeMs,!0),this.sceneRenderer.render()}),this.sceneRenderer.setStatedRoads(i.roads),this.sceneRenderer.setTraces(i.traces,this.traceLabels(i.traces)),this.pushPhenomenaAt(t);const d=s?.lat??Jd.lat,f=s?.lng??Jd.lng,p=xr(i.event.time??{},f,i.event.utcOffsetHours),g={lat:d,lng:f,elevationM:this.altitudeOf(s)};this.pushSatellitesAt(p,t,g),this.ensureFireballs(p);const m=this.skyEventsOf(i),v=m?.reentries??[];this.hearDetonations(v,t,{lat:d,lng:f,heightM:g.elevationM},e!==void 0);const M=v.filter(C=>Ct.mayDazzle(C));if(this.sceneRenderer.setRetinaHistory(M.length===0?void 0:C=>{const N=Te(i,C),O={lat:N?.lat??d,lng:N?.lng??f,heightM:N?this.altitudeOf(N):g.elevationM};return{views:Ct.viewsAt(M,C,O),pose:N}},i),this.skyEventsStartDate=p,this.sceneRenderer.setSkyEvents(m,!1,p),m&&this.loadSkyEventTexts(zg.map(C=>Rr.of(C)).filter(C=>Rr.eventsOf(m,C).length>0&&!this.skyEventTexts.has(C))),e&&!e.sky)return;if(this.sceneRenderer.setSkyUnknown(!p),!p){this.sceneRenderer.setAstronomy(TO);return}const x=new Date(p.getTime()+t),y=Math.max(1,Math.round(.25*this.degreesPerPixelAt(t)/nc.DEG_PER_SECOND*1e3)),w=Math.max(1e-8,this.degreesPerPixelAt(t)*.1),S=`${Math.floor(x.getTime()/y)}|${Math.round(d/w)}|${Math.round(f/w)}|${Math.round(g.elevationM)}|${this.starCatalog?this.starCatalogDepth:0}`;if(S===this.lastSkyKey){this.sceneRenderer.render();return}this.lastSkyKey=S;const E=Wo("Sun",x,g),b=Wo("Moon",x,g);let A=Yi.separationOf(E,b)<1?Yi.viewAt(x,g):void 0;if(A){const C=Yi.offsetOf(E,b,A.separationDeg);if(A.obscuration>me.LIMB_FROM_OBSCURATION){const N=this.limbFor(x,g);N&&(A={...A,obscuration:1-Zn.uncoveredFraction(N,A.sunRadiusDeg,C),limb:N})}A={...A,horizonShare:Yi.horizonShare(A,C,E.altitudeDeg,E.azimuthDeg,Wa.distanceKm(x,g))}}const T={...E,magnitude:T0("Sun",x)-2.5*Math.log10(Yi.beamFraction(A))};this.lastSun={altitudeDeg:T.altitudeDeg,azimuthDeg:T.azimuthDeg};const D={...b,phase:PE(x),magnitude:T0("Moon",x),radiusDeg:Wa.apparentRadiusDeg(x,g)},I=IE.map(C=>({body:C,position:Wo(C,x,g),magnitude:T0(C,x)}));this.sceneRenderer.setAstronomy({sun:T,moon:D,planets:I,comet:this.cometAt(x,g),novae:nx.appearancesAt(x,g).map(({outburst:C,position:N,magnitude:O})=>({id:C.id,position:N,magnitude:O})),stars:this.starCatalog?{catalog:this.starCatalog,date:x,observer:g}:void 0,frame:{date:x,observer:g},localHour:((x.getUTCHours()+x.getUTCMinutes()/60+(i.event.utcOffsetHours??Math.round(f/15)))%24+24)%24,eclipse:A}),this.ufoElement.setSunAltitude(T.altitudeDeg)}static LIMB_FROM_OBSCURATION=.98;limbRelief;limbRequested=!1;limbCache;limbFor(t,e){if(!this.limbRelief){this.limbRequested||(this.limbRequested=!0,ru.load(SO).then(n=>{this.limbRelief=n,this.lastSkyKey="",n&&this.isConnected&&this.updateAstronomy(this.lastTimeMs)}));return}const i=this.limbCache;if(i&&Math.abs(t.getTime()-i.atMs)<5e3&&i.lat===e.lat&&i.lng===e.lng&&i.elevationM===e.elevationM)return i.profile;const s=Zn.profile(t,e,this.limbRelief);return this.limbCache={profile:s,atMs:t.getTime(),lat:e.lat,lng:e.lng,elevationM:e.elevationM},s}pushSatellitesAt(t,e,i){if(this.ensureSatellites(t),!t||!this.satellites){this.sceneRenderer.setSatellites([]);return}const s=new Date(t.getTime()+e),n=[];for(const a of this.satellites.passes.positionsAt(s,i,-1))a.magnitude!==void 0&&n.push({norad:a.object.norad,name:a.object.name,position:{altitudeDeg:a.altitudeDeg,azimuthDeg:a.azimuthDeg},magnitude:a.magnitude,heightKm:a.heightKm});this.sceneRenderer.setSatellites(n)}ensureFireballs(t){const e=this.ufoElement.sighting,i=Math.max((e.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),s=t?.getTime(),n=e.skySources!==!1,a=s===void 0||!n?"":`${s}+${i}`;if(this.fireballs?.key===a)return;if(!n){this.fireballs={key:a,status:"outside",reentries:[]};return}if(s===void 0||!Xa.mayCover(s+i)){this.fireballs={key:a,status:"outside",reentries:[]};return}const r={key:a,status:"loading",reentries:[]};this.fireballs=r,me.fireballArchive.between(s,s+i).then(o=>{r.status=o?"ready":"unavailable",r.records=o??[],r.reentries=r.records.map(l=>Xa.asReentry(l,s)),!(this.fireballs!==r||!this.isConnected)&&(this.dispatchEvent(new CustomEvent(Gb)),r.reentries.length>0&&this.updateAstronomy(this.lastTimeMs))})}decorWithTraffic(t){const e=this.ensureTraffic(t);if(!e||e.objects.length===0)return t.decor;const i=this.decorMemo;if(i&&i.base===t.decor&&i.traffic===e.objects)return i.merged;const s=[...t.decor,...e.objects];return this.decorMemo={base:t.decor,traffic:e.objects,merged:s},s}seatedDecor(t,e){if(!t.some(a=>a.observerKeyframes?.length))return t;const i=t.map(a=>{if(!a.observerKeyframes?.length)return"";const r=vv(a,e);return`${r.side??"-"}/${r.facing??"-"}`}).join("|"),s=this.seatedMemo;if(s&&s.base===t&&s.seats===i)return s.seated;const n=t.map(a=>{if(!a.observerKeyframes?.length)return a;const r=vv(a,e);return{...a,observerSide:r.side,observerFacing:r.facing}});return this.seatedMemo={base:t,seats:i,seated:n},n}ensureTraffic(t){const e=Te(t,0),i=e?.lng===void 0?void 0:xr(t.event.time??{},e.lng,t.event.utcOffsetHours),s=Math.max((t.event.durationSeconds??0)*1e3,this.ufoElement.seekableDuration),n=i?.getTime(),a=n===void 0||e?.lat===void 0||e.lng===void 0?"":`${this.aircraftSource.id}|${n}+${s}|${e.lat.toFixed(3)},${e.lng.toFixed(3)}|${Math.round(e.elevationM??0)}|${Math.round(this.sceneRenderer.groundAltitudeM)}`;if(t.skySources===!1){this.traffic?.status!=="byHand"&&(this.traffic={key:"byHand",status:"byHand"},this.upperAirHeardLive=void 0);return}if(this.traffic?.key===a)return this.traffic.set;if(this.upperAirHeardLive=void 0,a===""||n===void 0||e?.lat===void 0||e.lng===void 0){this.traffic={key:a,status:"outside"};return}let r=me.aircraftProviders.get(this.aircraftSource.id);if(r||me.aircraftProviders.set(this.aircraftSource.id,r=this.aircraftSource.create()),r.mayCover&&!r.mayCover(n+s)){this.traffic={key:a,status:"outside"};return}const o={key:a,status:"loading",startMs:n,observer:{lat:e.lat,lng:e.lng}};this.traffic=o;const l={lat:e.lat,lng:e.lng,heightM:this.sceneRenderer.groundAltitudeM},h=Ss.MAX_GAP_S*1e3,u=me.SOUND_LOOKBACK_MS,d={lat:e.lat,lng:e.lng,elevationM:this.altitudeOf(e)},f=(p,g)=>p.TrafficDecor.from(o.tracks??[],l,n,p.TrafficDecor.MAX_OBJECTS,{models:g,sunElevationAt:m=>this.sunElevationAt(m,d)});r.between(l,n-u,n+s+h).then(async p=>{if(this.traffic!==o)return;if(p.status!=="found"){o.status=p.status==="outside"?"outside":"unavailable",p.status==="failed"&&(o.problem=p.problem,o.creditsSpent=p.creditsSpent),this.announceTraffic();return}let g;try{g=await me.loadTrafficRuntime()}catch{this.traffic===o&&(o.status="unavailable",this.announceTraffic());return}this.traffic===o&&(o.status="ready",o.tracks=p.tracks,o.partial=p.partial,o.creditsSpent=p.creditsSpent,o.set=f(g),this.startAircraftSound(o,g),this.announceTraffic(),this.describeTraffic(r,o,g,f),o.set.shown>0&&(this.readUpperAir(o,g,n-u,n+s+h),this.readTrailTraffic(r,o,g,l,n-me.TRAIL_LOOKBACK_MS,n+s+h)))})}trafficSunlight(t){const e=new Map,i=this.traffic,s=i?.set,n=this.lastSun;if(!s||!n||i.startMs===void 0||!i.observer)return e;for(const[a,r]of s.presence){if(t<r.fromMs||t>r.untilMs)continue;const o=s.flights.get(a),l=o?Ss.positionAt(o,i.startMs+t):void 0;l&&e.set(a,{heightM:l.geo.heightM,sunElevationDeg:ln.sunElevationDeg(n,i.observer,l.geo)})}return e}trafficTooltipAt(t,e){const i=this.sceneRenderer.pickTrafficAt(t,e),s=i?this.trafficInfoAt(i):void 0;if(!s)return;const n=this.naming;return me.trafficRuntime?.TrafficTooltip.text(s,n.names.trafficTooltip,r=>n.towards(r))}trafficInfoAt(t){const e=this.traffic,i=e?.set?.flights.get(t);if(!e||!i||e.startMs===void 0||!e.observer)return;const s=me.trafficRuntime;if(!s)return;const n=e.descriptions?.get(Ye.keyOf(i)),a=Te(this.ufoElement.sighting,this.lastTimeMs),r={lat:e.observer.lat,lng:e.observer.lng,heightM:this.altitudeOf(a)},o=th(this.ufoElement.sighting,this.lastTimeMs),l=this.ufoElement.sighting.around,h=s.AmbientNoise.dbA(o,l),u=s.TrafficInfos.at(i,n,r,e.startMs+this.lastTimeMs,{ambientDbA:h,ambientShapeDb:s.AmbientNoise.shapeDb(o,l)}),d=u&&this.contrailAt(t,this.lastTimeMs);return u&&d?{...u,contrail:d}:u}contrailAt(t,e){const i=this.traffic?.contrails?.find(n=>n.id===t);if(!i)return;let s;for(const n of i.points){if(n.tMs>e)break;s=n}return s?.forms?{persistent:s.persistent,iceRelativeHumidity:s.iceRelativeHumidity}:void 0}startAircraftSound(t,e){this.aircraftAudio??=this.newAircraftAudio(e),this.sortOutAudible(t,e)}sortOutAudible(t,e){if(!t.set||!t.observer)return;const i={windSpeed:0,precipitationType:"none",precipitationIntensity:0};t.audible=e.TrafficSound.candidates(t.set.flights,t.descriptions??new Map,Ye.keyOf,{...t.observer,heightM:this.sceneRenderer.groundAltitudeM},{ambientDbA:e.AmbientNoise.dbA(i,this.ufoElement.sighting.around),ambientShapeDb:e.AmbientNoise.shapeDb(i,this.ufoElement.sighting.around)}),this.ufoElement.refreshSoundControls()}pushAircraftSound(t,e){this.startDecorAircraftSound(t),this.startBodySound(),this.startRideSound(t);const i=this.aircraftAudio;if(!i)return;const s=me.trafficRuntime;if(!s){i.setVoices([]);return}const n=Te(t,e),a=th(t,e),r={ambientDbA:s.AmbientNoise.dbA(a,t.around),referenceAmplitude:s.AmbientNoise.referenceAmplitude(a,t.around),ambientShapeDb:s.AmbientNoise.shapeDb(a,t.around),expandUnderKnee:!s.AmbientNoise.bedPlays(a,t.around)},o=t.event.place?.[0],l={lat:n?.lat??o?.lat,lng:n?.lng??o?.lng},h=l.lat!==void 0&&l.lng!==void 0?{lat:l.lat,lng:l.lng,heightM:n?.elevationM??0}:void 0,u=v=>this.decorModelSounds.get(v.model?.id??""),d=!t.vehicle&&h?s.DecorAircraftHearing.ridden(t,e,h,u):void 0,f=t.vehicle??(d?{kind:d.kind}:void 0),p=f?s.CabinHearing.voice(f,r):void 0,g={...r,ambientDbA:Math.max(r.ambientDbA,p?.levelDbA??0),...f?{throughDb:Os.insulationDb(f)}:{}},m=this.trafficVoices(e,n,g,s);h&&(this.decorAircraftHearing??=new s.DecorAircraftHearing,m.push(...this.decorAircraftHearing.voices(t,e,h,g,u)),m.push(...this.bodyVoices(t,e,g,s)),p&&m.push(p),m.sort((v,M)=>M.levelDbA-v.levelDbA),m.length=Math.min(m.length,4)),i.setVoices(m,n?.headingDeg??0)}startRideSound(t){this.aircraftAudio||Os.aircraftOf(t.vehicle)===void 0||(me.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(me.trafficRuntime):me.loadTrafficRuntime().catch(()=>{}))}startBodySound(){this.aircraftAudio||!this.interpretationShown?.bodies.some(t=>t.sound)||(me.trafficRuntime?this.aircraftAudio=this.newAircraftAudio(me.trafficRuntime):me.loadTrafficRuntime().catch(()=>{}))}bodyVoices(t,e,i,s){const n=this.interpretationShown,a=t.event.place?.[0];if(!n||!a||!n.bodies.some(f=>f.sound))return[];const r=this.sceneRenderer.bodyGround,o=f=>It.eyeOf(t,f,r),l=o(e);if(!l)return[];const h=new Map,u=(f,p)=>{let g=h.get(f.id);return g||h.set(f.id,g=new It(f,r,o)),g.at(p)};this.bodyHearing??=new s.BodyHearing;const d=Math.max(t.observerTrack.duration,(t.event.durationSeconds??0)*1e3);return this.bodyHearing.voices(n.bodies,u,l,a,e,d,i)}trafficVoices(t,e,i,s){const n=this.traffic,a=n?.set;if(!n||!a||!n.audible||n.startMs===void 0||!n.observer)return[];const r={lat:n.observer.lat,lng:n.observer.lng,heightM:this.altitudeOf(e)};return s.TrafficSound.voices(n.audible,a.flights,n.descriptions??new Map,Ye.keyOf,r,n.startMs+t,i)}startDecorAircraftSound(t){const e=t.decor.filter(s=>s.kind==="aircraft"&&s.track?.some(n=>(n.altitudeM??0)>0));if(e.length===0)return;for(const s of e){const n=s.model?.id;s.aircraftSound||!n||s.model?.url!==void 0||this.decorModelSounds.has(n)||(this.decorModelSounds.set(n,void 0),this.decorModelsAsked.add(n),this.sceneRenderer.entryOfDecorModel(n).then(a=>{this.decorModelSounds.set(n,a?.parameters?.sound),this.decorModelsAsked.delete(n),this.ufoElement.refreshSoundControls(),this.startDecorAircraftSound(t)}))}if(e.some(s=>{if(s.aircraftSound)return s.aircraftSound!=="silent";const n=s.model?.id;return!n||s.model?.url!==void 0?!0:!this.decorModelsAsked.has(n)&&this.decorModelSounds.get(n)!=="silent"})){if(this.aircraftAudio||me.trafficRuntime){!this.aircraftAudio&&me.trafficRuntime&&(this.aircraftAudio=this.newAircraftAudio(me.trafficRuntime));return}me.loadTrafficRuntime().catch(()=>{})}}newAircraftAudio(t){const e=new t.AircraftAudio(this.filmSound);return this.filmSound||e.setLevel(this.ufoElement.level),(this.interacted||this.filmSound)&&e.resume(),e.setPaused(this.ufoElement.playbackState!=="playing"&&!this.filmSound),e}get aircraftFlights(){return[...this.declaredFlights,...this.recordedFlights]}get declaredFlights(){return this.ufoElement.sighting.decor.filter(t=>t.kind==="aircraft"&&gv.flies(t)).map(t=>{const e=this.sceneRenderer.decorSkyPoint(t.id);return{key:Ye.declaredKeyOf(t.id),type:this.said.read(t.title)||this.naming.decorKind(t.kind),sky:e?.sky,altitudeFt:e?e.altitudeM/.3048:void 0,firstMs:0,drawn:e!==void 0,declared:!0}})}get recordedFlights(){const t=this.traffic;if(!t?.tracks||t.startMs===void 0||!t.observer)return[];const e=t.startMs,i=this.observerAt(this.lastTimeMs,t.observer),s=new Set([...t.set?.flights.values()??[]].map(r=>Ye.keyOf(r))),n=t.nearestPassKm??=new Map(t.tracks.map(r=>[Ye.keyOf(r),Math.min(...r.points.map(o=>Ss.groundDistanceKm(t.observer,o)))])),a=this.ufoElement.seekableDuration;return[...t.tracks].sort((r,o)=>n.get(Ye.keyOf(r))-n.get(Ye.keyOf(o))).map(r=>{const o=Ye.keyOf(r),l=t.descriptions?.get(o),h=t.models?.get(o),u=Ss.seenFrom(r,i,e+this.lastTimeMs),d=r.points.find(f=>f.t>=e)?.t;return{key:o,type:h?.basis==="type"?h.name:l?.type,registration:l?.registration,sky:u?.sky,altitudeFt:u?.altitudeFt,firstMs:d!==void 0&&d-e<=a?d-e:void 0,drawn:s.has(o)}})}lookAtFlight(t,e=this.lastTimeMs){const i=this.traffic,s=Te(this.ufoElement.sighting,e),n=Ye.declaredIdOf(t);if(n!==void 0){const o=this.sceneRenderer.decorSkyPoint(n);return!o||s?.headingDeg===void 0?!1:(this.setLookOffset(((o.sky.azimuthDeg-s.headingDeg)%360+540)%360-180,o.sky.altitudeDeg-(s.pitchDeg??0)),!0)}const a=i?.tracks?.find(o=>Ye.keyOf(o)===t);if(!i?.observer||i.startMs===void 0||!a||s?.headingDeg===void 0)return!1;const r=Ss.seenFrom(a,this.observerAt(e,i.observer),i.startMs+e);return r?(this.setLookOffset(((r.sky.azimuthDeg-s.headingDeg)%360+540)%360-180,r.sky.altitudeDeg-(s.pitchDeg??0)),!0):!1}markFlight(t){this.markedFlight=t,this.placeFlightMark()}placeFlightMark(){const t=this.markedFlight,e=t===void 0?void 0:this.sceneRenderer.flightScreenPoint(t);if(this.flightMark.toggleAttribute("hidden",!e),!e)return;const i=this.sceneCanvas.getBoundingClientRect(),s=this.stageElement.getBoundingClientRect(),n=i.left-s.left+(e.ndcX+1)/2*i.width,a=i.top-s.top+(1-e.ndcY)/2*i.height;for(const r of Array.from(this.flightMark.children))r.setAttribute("cx",String(n)),r.setAttribute("cy",String(a))}altitudeOf(t){return this.sceneRenderer.groundAltitudeM+(t?.elevationM??0)}observerAt(t,e){const i=Te(this.ufoElement.sighting,t);return{lat:i?.lat??e.lat,lng:i?.lng??e.lng,heightM:this.altitudeOf(i)}}announceTraffic(){this.isConnected&&(this.dispatchEvent(new CustomEvent(Wb)),this.updateAstronomy(this.lastTimeMs))}async describeTraffic(t,e,i,s){if(!t.describe||!e.set||!e.tracks)return;const n=new Set([...e.set.flights.values()].map(l=>Ye.keyOf(l))),a=e.tracks.filter(l=>n.has(Ye.keyOf(l))&&l.points.length>0),r=new Map,o=new Map;await Promise.all(a.map(async l=>{const h=new Date(l.points[0].t).toISOString().slice(0,10),u=await t.describe(l,h).catch(()=>{});u&&(o.set(Ye.keyOf(l),u),r.set(Ye.keyOf(l),i.AircraftModels.of(u)))})),!(this.traffic!==e||r.size===0)&&(e.descriptions=o,e.models=r,e.set=s(i,r),this.planContrails(e,i),this.sortOutAudible(e,i),this.announceTraffic())}async readTrailTraffic(t,e,i,s,n,a){if(e.startMs===void 0)return;const r=await t.between(s,n,a).catch(()=>{});if(this.traffic!==e||r?.status!=="found")return;const o=r.tracks.filter(u=>u.points.some(d=>d.altitudeFt>=i.AircraftContrails.MIN_ALTITUDE_FT)),l=new Map(e.models??[]);if(t.describe&&await Promise.all(o.filter(u=>u.points.length>0&&!l.has(Ye.keyOf(u))).map(async u=>{const d=await t.describe(u,new Date(u.points[0].t).toISOString().slice(0,10)).catch(()=>{});d&&l.set(Ye.keyOf(u),i.AircraftModels.of(d))})),this.traffic!==e||e.startMs===void 0)return;const h=i.TrafficDecor.from(o,s,e.startMs,me.TRAIL_MAX_AIRCRAFT,{models:l});e.trailSet=me.alignTrailIds(h,e.set),e.models=new Map([...l,...e.models??[]]),this.planContrails(e,i),this.announceTraffic()}static alignTrailIds(t,e){if(!e)return t;const i=new Map;for(const[r,o]of e.flights){const l=e.presence.get(r);if(l)for(const[h,u]of t.flights){const d=t.presence.get(h);!d||Ye.keyOf(u)!==Ye.keyOf(o)||d.fromMs<=l.untilMs&&l.fromMs<=d.untilMs&&i.set(h,r)}}const s=r=>i.get(r)??`${r}-trail`,n=new Set(i.values()),a=e.objects.filter(r=>!n.has(r.id));return{...t,objects:[...t.objects.map(r=>({...r,id:s(r.id)})),...a],presence:new Map([...[...t.presence].map(([r,o])=>[s(r),o]),...a.map(r=>[r.id,e.presence.get(r.id)])]),flights:new Map([...[...t.flights].map(([r,o])=>[s(r),o]),...a.map(r=>[r.id,e.flights.get(r.id)])])}}async readUpperAir(t,e,i,s){if(!t.observer)return;const n=jd.held(this.ufoElement.sighting.snapshots,"upperAir");let a;if(n){const l=hi.address(n.src,this.documentUrl);a=me.upperAirProviders.get(l),a||me.upperAirProviders.set(l,a=new Al(hi.json(l)))}else{const l=this.upperAirSource??e.UPPER_AIR_SOURCES[0];a=me.upperAirProviders.get(l.id),a||me.upperAirProviders.set(l.id,a=l.create())}const r={lat:t.observer.lat,lng:t.observer.lng},o=await a.between(r,i,s);this.traffic!==t||o.status!=="found"||(n||(this.upperAirHeardLive={...r,startMs:i,endMs:s,answer:o}),t.air=o.samples,t.airSource=o.source,this.planContrails(t,e),this.announceTraffic())}planContrails(t,e){const i=t.trailSet??t.set;!i||!t.air||t.startMs===void 0||(t.contrails=e.AircraftContrails.plan(i,t.models,t.air,t.startMs))}contrailSunlight(t){const e=new Map,i=this.traffic,s=i?.trailSet??i?.set,n=this.lastSun;if(!i||!s||!n||!i.contrails?.length||i.startMs===void 0||!i.observer)return e;for(const a of i.contrails){const r=s.presence.get(a.id),o=s.flights.get(a.id);if(!r||!o)continue;const l=Ss.positionAt(o,i.startMs+Math.min(r.untilMs,Math.max(r.fromMs,t)));l&&e.set(a.id,{heightM:l.geo.heightM,sunElevationDeg:ln.sunElevationDeg(n,i.observer,l.geo)})}return e}sunElevationAt(t,e){const i=Wo("Sun",new Date(t.t),e);return ln.sunElevationDeg(i,e,t)}upperAirSource;upperAirHeardLive;get upperAirHeard(){return this.upperAirHeardLive}setUpperAirSource(t){t.id!==this.upperAirSource?.id&&(this.upperAirSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}setAircraftSource(t,e=!1){!e&&t.id===this.aircraftSource.id||(this.aircraftSource=t,this.traffic=void 0,this.decorMemo=void 0,this.updateAstronomy(this.lastTimeMs))}get aircraftState(){const t=this.traffic?.contrails?.length?this.upperAirSource??me.trafficRuntime?.UPPER_AIR_SOURCES[0]:void 0;return{trailCredit:t&&{credit:t.credit,creditUrl:t.creditUrl},status:this.traffic?.status??"none",problem:this.traffic?.problem,partial:this.traffic?.partial,creditsSpent:this.traffic?.creditsSpent,total:this.traffic?.set?.total??0,shown:this.traffic?.set?.shown??0,credit:this.aircraftSource.credit,creditUrl:this.aircraftSource.creditUrl}}get fireballState(){return{status:this.fireballs?.status??"none",records:this.fireballs?.records??[]}}ensureSatellites(t){this.ufoElement.sighting.skySources===!1&&(t=void 0);const e=t?String(t.getTime()):"";if(e===this.satellitesFor)return;this.satellitesFor=e,this.satellites=void 0,this.satellitePassesMemo=void 0;const i=++this.satelliteRequest;if(!t){this.satelliteStatus="none";return}this.satelliteStatus="loading";const s=a=>{i===this.satelliteRequest&&(this.satelliteStatus=a,this.isConnected&&this.dispatchEvent(new CustomEvent(Hb)))},n=me.tleArchive;(async()=>{if(!await n.covers(t))return s("outside");const[a,r]=await Promise.all([n.at(t),Ht(()=>import("./SatellitePasses-Pfro2-0Z.js"),[],import.meta.url)]);if(i===this.satelliteRequest){if(!a)return s("unavailable");this.satellites={snapshot:a,passes:new r.SatellitePasses(a.objects)},s("ready"),this.isConnected&&this.updateAstronomy(this.lastTimeMs)}})().catch(()=>s("unavailable"))}get satelliteState(){const t=this.satellites?.snapshot;return{status:this.satelliteStatus,coverage:t?.coverage,credit:t?.credit,creditUrl:t?.creditUrl}}burningCandidates(){return{reentries:this.ufoElement.sighting.skyEvents?.reentries??[],fireballs:this.fireballs?.reentries??[]}}trafficCandidates(){const t=this.traffic;if(!(t?.status!=="ready"||!t.tracks||t.startMs===void 0))return{tracks:t.tracks,startMs:t.startMs,describe:e=>t.descriptions?.get(Ye.keyOf(e))}}satellitePositionsAt(t){const e=this.satellites,i=this.ufoElement.sighting,s=Te(i,0),n=i.event.place?.[0],a=s?.lat??n?.lat,r=s?.lng??n?.lng;if(!(!e||a===void 0||r===void 0))return e.passes.positionsAt(t,{lat:a,lng:r,elevationM:this.altitudeOf(s)})}satellitePassesDuring(t){const e=this.satellites,i=this.ufoElement.sighting,s=Te(i,0),n=i.event.place?.[0],a=s?.lat??n?.lat,r=s?.lng??n?.lng;if(!e||a===void 0||r===void 0)return[];const o=xr(i.event.time??{},r,i.event.utcOffsetHours);if(!o)return[];const l=Math.min(Math.max(t,0),4*36e5),h={lat:a,lng:r,elevationM:this.altitudeOf(s)},u=JSON.stringify([this.satellitesFor,o.getTime(),a,r,h.elevationM,l]);if(this.satellitePassesMemo?.key===u)return this.satellitePassesMemo.passes;const d=Math.max(10,Math.ceil(l/1e3/600)),f=e.passes.passesDuring(o,new Date(o.getTime()+l),h,d);return this.satellitePassesMemo={key:u,passes:f},f}cometAt(t,e){const i=mO.brightestAt(t,e);if(i)return{id:i.apparition.id,position:i.position,tailEnd:i.tailEnd,magnitude:i.magnitude}}approachOf(t,e){return this.approaches.of.has(e)||this.approaches.of.set(e,cu.of(t,e)),this.approaches.of.get(e)}pushPhenomenaAt(t){const e=this.ufoElement.sighting;e!==this.sizeEstimatesFor&&(this.sizeEstimates.clear(),this.distanceHypotheses.clear(),this.sizeEstimatesFor=e);const i=JSON.stringify([e.timeline.allKeyframes.map(g=>[g.t,g.shapes.map(m=>[m.sourceId,m.shape.angular?.widthDeg,m.shape.aim?.azimuthDeg])]),e.observerTrack.allKeyframes,e.event.place?.[0]]);i!==this.approaches.key&&(this.approaches={key:i,of:new Map});const s=e.timeline,n=this.ufoElement.canvasElement,a=this.ufoElement.frameShiftPx,r=this.projectionAt(t),o=new Map,l=new Map,h=new Set;for(const g of s.sourceIds){const m=s.getInterpolatedShapeAt(t,g);if(!m)continue;const v={...m,bounds:{...m.bounds,x:m.bounds.x+a.x,y:m.bounds.y+a.y}};o.set(g,v);const M=m.aim?this.sceneRenderer.screenPointOf(xn.directionOf(m.aim,this.directionScratch)):{ndcX:(v.bounds.x+v.bounds.width/2)/n.width*2-1,ndcY:-((v.bounds.y+v.bounds.height/2)/n.height*2-1)},x=M!==void 0&&Math.abs(M.ndcX)<=1&&Math.abs(M.ndcY)<=1,y=x?this.sceneRenderer.decorDistancesAt(M.ndcX,M.ndcY,g):{};h.add(g),(x||m.aim)&&h.delete(g);const w=m.angular?.widthDeg??r.pxToDeg(m.bounds.width),S=this.sizeEstimateOf(g);S.add(w,y);const E=this.approachOf(e,g);l.set(g,rn.resolve({hypothesisM:this.distanceHypotheses.get(g),derivedM:E&&w>0?Di.distanceMAt(E.widthM,w):void 0,range:S.distanceRangeAt(w),crossing:y}))}for(const[g,m]of o)for(const[v,M]of o){if(v===g||M.transparency>=1||M.bounds.width*M.bounds.height<=m.bounds.width*m.bounds.height||!(m.bounds.x>=M.bounds.x&&m.bounds.y>=M.bounds.y&&m.bounds.x+m.bounds.width<=M.bounds.x+M.bounds.width&&m.bounds.y+m.bounds.height<=M.bounds.y+M.bounds.height))continue;const y=l.get(v);y&&l.set(g,{distanceM:y.distanceM*.999,basis:y.basis});break}this.depths=l;const u=s.sourceIds,d=[];for(const[g,m]of o)d.push({sourceId:g,shape:m,distanceM:l.get(g).distanceM,renderOrder:u.indexOf(g),aim:m.aim,hidden:h.has(g)||this.interpretationShown!==void 0&&(!this.comparing||m.transparency>=1),ghost:this.interpretationShown!==void 0&&this.comparing});const f=Te(e,t),p=(f?.rollDeg??0)+ii.bodyAt(e,t,this.ufoElement.steadyBody).rollDeg;this.sceneRenderer.setPhenomena(d,{projection:r,canvasWidthPx:n.width,canvasHeightPx:n.height,scale:Math.max(1,this.sceneCanvas.height/Math.max(1,n.height)),starPoints:Ts.starPointsOf(e.instrument,f?.fNumber),rollRad:p*Math.PI/180})}get interpretation(){return this.interpretationShown}set interpretation(t){this.showInterpretation(t),this.ufoElement.playerTitle=t?.title,this.ufoElement.refreshSoundControls(),this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome()}redrawSky(){this.updateAstronomy(this.lastTimeMs)}syncAccountHidden(){this.ufoElement.accountHidden=this.interpretationShown!==void 0&&!this.comparing}get accountInTheRound(){return this.inTheRound}set accountInTheRound(t){this.inTheRound=t}get compareAccount(){return this.comparing}set compareAccount(t){t!==this.comparing&&(this.comparing=t,this.syncAccountHidden(),this.updateAstronomy(this.lastTimeMs),this.ufoElement.repaintChrome())}get confrontation(){return this.confrontationReadings}groundAlong(t,e,i){const s=this.sceneRenderer.bodyGround,n=It.eyeOf(this.ufoElement.sighting,i,s);return n?It.lineOfSightMeetsGround(n,t,e,s):void 0}bodyMaskedBy(t,e){return this.sceneRenderer.bodyMaskedByDecor(t,e)}bodyReading(t,e){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=d=>It.eyeOf(s,d,i),a=new It(t,i,n).at(e),r=n(e);if(!a||!r)return;const o=a.eastM-r.eastM,l=a.northM-r.northM,h=a.upM-r.upM,u=Math.hypot(o,l);return{azimuthDeg:(Math.atan2(o,l)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(h,u)*180/Math.PI,distanceM:Math.hypot(u,h),eastM:a.eastM,northM:a.northM,aboveGroundM:a.upM-a.sizeM.heightM/2-i.heightAt(a.eastM,a.northM),sizeM:a.sizeM,attitude:a.attitude,appearance:a.appearance}}bodyProjectionAt(t,e){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=o=>It.eyeOf(s,o,i),a=new It(t,i,n).at(e),r=n(e);return a&&r?We.projectionOf(a,r):void 0}directionToDecor(t){return this.sceneRenderer.directionToDecor(t)}directionToBody(t,e){const i=this.sceneRenderer.bodyGround,s=this.ufoElement.sighting,n=p=>It.eyeOf(s,p,i),a=new It(t,i,n),r=a.at(e)?e:t.track[0]?.t,o=r===void 0?void 0:a.at(r),l=r===void 0?void 0:n(r);if(!o||!l)return;const h=o.eastM-l.eastM,u=o.northM-l.northM,d=o.upM-l.upM,f=Math.hypot(h,u);if(!(f===0&&d===0))return{azimuthDeg:(Math.atan2(h,u)*180/Math.PI+360)%360,altitudeDeg:Math.atan2(d,f)*180/Math.PI}}placeBodiesAt(t,e){const i=this.interpretationShown,s=this.ufoElement.sighting;let n=[],a=[];const r=this.sceneRenderer.bodyGround,o=p=>It.eyeOf(s,p,r);i&&(n=i.bodies.map(p=>new It(p,r,o).at(t)).filter(p=>p!==void 0));const l=tl(s,t),h=l.windDirectionDeg*Math.PI/180,u={x:l.windSpeed*Math.sin(h),z:-l.windSpeed*Math.cos(h)};this.sceneRenderer.setBodies(n,t/1e3,i?.bodies.map(p=>p.id)??[],i?.smoke??[],u);const d=i&&this.comparing?o(t):void 0;if(d&&(a=new We(s.timeline,this.confrontationTolerance,We.sizeHows(s.timeline,s.provenance),wn.seeingOf(s)).at(t,n,d,p=>p.outlineNode?this.sceneRenderer.bodyOutline?.(p.id,p.outlineNode):void 0)),this.confrontationReadings=a,!e)return;const f=JSON.stringify(a);f!==this.confrontationSignature&&(this.confrontationSignature=f,this.dispatchEvent(new CustomEvent(Xb,{detail:a})))}async pictureAt(t,e=640){const i=document.createElement("canvas");i.width=e,i.height=Math.round(e*(this.sceneCanvas.height||9)/(this.sceneCanvas.width||16));let s=!1;for(const n of[1200,0]){this.showAt(t),s=!1;for(let a=0;a<900&&!s;a++)await new Promise(r=>requestAnimationFrame(()=>r())),s=this.snapshotTo(i);if(!s)return;n&&await new Promise(a=>setTimeout(a,n))}return i.toDataURL("image/jpeg",.85)}setDistanceHypothesis(t,e){e===void 0||!(e>0)?this.distanceHypotheses.delete(t):this.distanceHypotheses.set(t,e),this.updateAstronomy(this.lastTimeMs)}depthOf(t){return this.depths.get(t)}sizeRangeOf(t){return this.sizeEstimateOf(t).sizeRange}distanceRangeAt(t,e){const i=this.ufoElement.sighting.timeline.getInterpolatedShapeAt(e,t);if(!i)return{};const s=i.angular?.widthDeg??this.projectionAt(e).pxToDeg(i.bounds.width);return this.sizeEstimateOf(t).distanceRangeAt(s)}sizeContradictory(t){return this.sizeEstimateOf(t).contradictory}updateMeteorShower(t,e){this.ensureMeteorSchedule(t),this.sceneRenderer.updateMeteors(e)}updateLightning(t,e,i){if(this.ensureLightningSchedule(t),this.sceneRenderer.updateLightning(e),i)return;const s=this.lastLightningT;if(this.lastLightningT=e,s===void 0||e<s||this.ufoElement.playbackState!=="playing")return;const n=this.lightningFlashes.filter(a=>a.t>s&&a.t<=e).pop();n&&tl(t,n.t).storm&&this.handleLightningFlash(n)}ensureLightningSchedule(t){const e=tl(t,0).precipitationIntensity,i=`${this.meteorInputsOf(t)}|${e}`;if(i===this.lightningScheduleFor)return;this.lightningScheduleFor=i;const s=t.event.time,n=t.event.place?.[0],a=s?.year!==void 0?xr(s,n?.lng??0,t.event.utcOffsetHours):void 0,r=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,o=Math.round((a?.getTime()??0)/1e3)+Math.round((n?.lat??0)*1e3)+7;this.lightningFlashes=is.schedule({durationMs:r,seed:o,intensity:e}),this.sceneRenderer.setLightning(this.lightningFlashes)}ensureMeteorSchedule(t){const e=this.meteorInputsOf(t);e!==this.meteorScheduleFor&&(this.meteorScheduleFor=e,this.scheduleMeteors(t))}meteorInputsOf(t){const e=t.event.place?.[0],i=t.event.time;return JSON.stringify([e?.lat,e?.lng,i?.year,i?.month,i?.day,i?.hour,i?.minute,i?.second,t.event.utcOffsetHours,t.event.durationSeconds,t.timeline.duration,t.skySources])}scheduleMeteors(t){const e=t.event.place?.[0],i=t.event.time,s=e?.lat!==void 0&&e.lng!==void 0&&i?.year!==void 0?xr(i,e.lng,t.event.utcOffsetHours):void 0;if(!s||e?.lat===void 0||e.lng===void 0||t.skySources===!1){this.sceneRenderer.setMeteorShower([],0,0);return}const n={lat:e.lat,lng:e.lng,elevationM:0},a=(t.event.durationSeconds??0)*1e3||t.timeline.duration||2e4,r=Math.round(s.getTime()/1e3)+Math.round(e.lat*1e3),o=zi.schedule({ratePerHour:zi.observedRatePerHour(zi.apexPosition(s,n).altitudeDeg),durationMs:a,velocityKmS:zi.TYPICAL_VELOCITY_KM_S,seed:r}),l=fm.activeAt(s).map(u=>{const d=fm.radiantPosition(u.shower,s,n);return{entry:u,position:d,rate:fm.observedRatePerHour(u.zhr,d.altitudeDeg,u.shower.populationIndex)}}).sort((u,d)=>d.rate-u.rate)[0];if(!l||l.rate<=0){this.sceneRenderer.setMeteorShower(o,0,0);return}const h=Jn.schedule({ratePerHour:l.rate,durationMs:a,velocityKmS:l.entry.shower.velocityKmS,seed:r+1});this.sceneRenderer.setMeteorShower([...h,...o],l.position.altitudeDeg,l.position.azimuthDeg)}groundHides(t,e){return this.sceneRenderer.groundHidesDirection(t,e)}get groundKey(){return this.sceneRenderer.groundKey}meteorByRank(t,e=Number.POSITIVE_INFINITY){this.ensureMeteorSchedule(this.ufoElement.sighting);const i=[...this.sceneRenderer.meteorSchedule].filter(a=>a.t+a.durationMs<=this.ufoElement.seekableDuration).filter(a=>Jn.magnitudeOf(a)<=e).filter(a=>{const r=this.sceneRenderer.meteorMidpoint(a);return r!==void 0&&!this.sceneRenderer.groundHidesDirection(r.altitudeDeg,r.azimuthDeg)}).sort((a,r)=>r.brightness-a.brightness);if(i.length===0)return;const s=i[t%i.length],n=this.sceneRenderer.meteorMidpoint(s);if(n)return{t:Math.round(s.t+s.durationMs*.45),...n}}lensOpticsAt(t){const e=this.ufoElement.sighting,i=e.instrument,s=i.frame,n=Te(e,t),a=n?.fNumber??i.fNumber;if(!s||a===void 0)return;const r=Ts.focalLengthMmFor(i,ns.fovOf(e,t));if(r!==void 0)return{focalLengthMm:r,fNumber:a,focusDistance:n?.focusDistanceM??0,frameHeightMm:s.heightMm}}projectionAt(t){const e=this.ufoElement.sighting;return $a.of(e.instrument,Di.CANVAS_HEIGHT_PX,ns.fovOf(e,t))}sizeEstimateOf(t){let e=this.sizeEstimates.get(t);return e||(e=new vO,this.sizeEstimates.set(t,e)),e}}const i0="rr0-scene";function RO(){fw(),customElements.get(i0)||customElements.define(i0,me)}const aL=Object.freeze(Object.defineProperty({__proto__:null,AIRCRAFT_CHANGE_EVENT:Wb,CONFRONTATION_EVENT:Xb,FIREBALLS_CHANGE_EVENT:Gb,REFERENCES_CHANGE_EVENT:Vb,SATELLITES_CHANGE_EVENT:Hb,SCENE_ELEMENT_NAME:i0,SceneElement:me,registerScene:RO},Symbol.toStringTag,{value:"Module"}));class Ka{static PACKAGE="@rr0/ufoathome";static CDN="https://cdn.jsdelivr.net/npm";static DIRECTORIES={"rr0-sighting":"dist-embed-sighting","rr0-sighting-editor":"dist-embed-sighting-editor"};static current(t,e,i){const s=new URL(`${t}.mjs`,e);return s.href.startsWith(`${Ka.CDN}/`)?`${i}/lib/${t}.mjs`:(s.pathname=s.pathname.replace(/\/lib\/\d+\.\d+\.\d+[^/]*\//,"/lib/"),s.href)}static VERSION_PARAMETER="v";static pinnable(t){return t in Ka.DIRECTORIES}static pinnedLink(t,e){const i=new URL(t);return i.searchParams.set(Ka.VERSION_PARAMETER,e),i.href}static pinned(t,e){return`${Ka.CDN}/${Ka.PACKAGE}@${e}/${Ka.DIRECTORIES[t]}/${t}.mjs`}}class s0{static PRODUCTION="https://ufoathome.org";static home(){try{const t=new URL(import.meta.url),e=new URL(location.href);return(e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]"||e.hostname.endsWith(".localhost"))&&t.origin===e.origin?e.origin:s0.PRODUCTION}catch{return s0.PRODUCTION}}}const DO=`
|
|
@@ -9218,5 +9218,5 @@ ${hi.generation}`;return this.snapshotMap?.key!==i&&(this.snapshotMap={key:i,ima
|
|
|
9218
9218
|
<button id="copy" class="share-copy" type="button"></button>
|
|
9219
9219
|
</div>
|
|
9220
9220
|
</dialog>
|
|
9221
|
-
`;class pf extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(pf.TAG)||customElements.define(pf.TAG,pf)}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=DO;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.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(t){const e=++this.languageToken,i=await iS.load(t);if(e===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(t){this.noteElement.textContent=t??"",this.noteElement.hidden=t===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?Ka.pinnedLink(t.link(),"0.
|
|
9222
|
-
${t.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const t=this.messages;if(!t)return;const e=(i,s)=>{this.shadow.getElementById(i).textContent=s};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("pin-label",t.pin.replace("{version}","0.
|
|
9221
|
+
`;class pf extends HTMLElement{static TAG="rr0-share-dialog";static register(){customElements.get(pf.TAG)||customElements.define(pf.TAG,pf)}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=DO;const t=e=>this.shadow.getElementById(e);this.dialog=t("dialog"),this.linkField=t("link"),this.copyButton=t("copy"),this.linkBox=t("link-box"),this.embedBox=t("embed-box"),this.linkOption=t("link-option"),this.embedOption=t("embed-option"),this.pin=t("pin"),this.embedMarkup=t("embed-markup"),this.noteElement=t("note"),t("close").addEventListener("click",()=>this.close()),this.dialog.addEventListener("click",e=>{e.target===this.dialog&&this.close()}),this.linkOption.addEventListener("click",()=>this.show("link")),this.embedOption.addEventListener("click",()=>this.show("embed")),this.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(t){const e=++this.languageToken,i=await iS.load(t);if(e===this.languageToken)return this.messages=i,this.applyMessages(),i}set note(t){this.noteElement.textContent=t??"",this.noteElement.hidden=t===void 0}get isOpen(){return this.dialog.open||this.dialog.hasAttribute("open")}open(){this.refresh(),this.show("link"),typeof this.dialog.showModal=="function"?this.dialog.showModal():this.dialog.setAttribute("open",""),this.fitLink(),requestAnimationFrame(()=>this.fitLink()),this.linkField.select()}close(){typeof this.dialog.close=="function"?this.dialog.close():this.dialog.removeAttribute("open")}refresh(){const t=this.subject;if(!t)return;const e=this.pin.checked;this.linkField.value=e?Ka.pinnedLink(t.link(),"0.195.0"):t.link(),this.fitLink();const s=`<script type="module" src="${e?Ka.pinned(t.module,"0.195.0"):Ka.current(t.module,import.meta.url,s0.home())}"><\/script>
|
|
9222
|
+
${t.element()}`;this.embedMarkup.value=s,this.codeEditor&&(this.codeEditor.text=s)}applyMessages(){const t=this.messages;if(!t)return;const e=(i,s)=>{this.shadow.getElementById(i).textContent=s};e("title",t.share),e("link-label",t.link),e("embed-label",t.embed),e("copy",t.copy),e("pin-label",t.pin.replace("{version}","0.195.0")),this.pin.parentElement.title=t.pinHint,this.shadow.getElementById("close").setAttribute("aria-label",t.close),this.linkField.setAttribute("aria-label",t.link)}show(t){this.linkBox.hidden=t!=="link",this.embedBox.hidden=t!=="embed",this.linkOption.setAttribute("aria-pressed",String(t==="link")),this.embedOption.setAttribute("aria-pressed",String(t==="embed")),t==="embed"?this.loadCodeEditor():this.fitLink()}fitLink(){this.linkField.style.height="auto",this.linkField.style.height=`${this.linkField.scrollHeight}px`}loadCodeEditor(){this.codeLoading??=Ht(async()=>{const{ShareCodeEditor:t}=await import("./ShareCodeEditor-DyEYu_9d.js");return{ShareCodeEditor:t}},__vite__mapDeps([47,48]),import.meta.url).then(({ShareCodeEditor:t})=>{this.codeEditor=new t(this.shadow.getElementById("embed-code"),this.embedMarkup.value,e=>{this.embedMarkup.value=e},this.messages?.embed??""),this.embedMarkup.hidden=!0}).catch(()=>{this.codeLoading=void 0})}async copy(t,e){try{await navigator.clipboard.writeText(t),this.copyButton.textContent=this.messages?.copied??"",window.setTimeout(()=>this.copyButton.textContent=this.messages?.copy??"",1500)}catch{e.select()}}}export{Ep as $,s0 as A,ee as B,Xb as C,fi as D,nn as E,Oe as F,PE as G,cl as H,ua as I,dc as J,Zo as K,le as L,Ol as M,Et as N,Cl as O,jt as P,zg as Q,Xn as R,pf as S,gA as T,Rr as U,nL as V,mo as W,Ub as X,zb as Y,Pi as Z,er as _,FO as a,cw as a$,J2 as a0,KI as a1,jf as a2,Pl as a3,li as a4,hi as a5,Yx as a6,g1 as a7,fw as a8,kn as a9,wl as aA,Ps as aB,lm as aC,zi as aD,fm as aE,mO as aF,e0 as aG,nx as aH,Yi as aI,Wa as aJ,Xa as aK,we as aL,In as aM,kO as aN,cn as aO,VE as aP,ll as aQ,ls as aR,It as aS,Un as aT,Ci as aU,Pg as aV,Ye as aW,Ss as aX,pi as aY,Ws as aZ,Os as a_,Ib as aa,We as ab,Wb as ac,Vb as ad,Gb as ae,Hb as af,ns as ag,Go as ah,sL as ai,pA as aj,fA as ak,dA as al,$x as am,_l as an,ZP as ao,bO as ap,ma as aq,$a as ar,lf as as,Pe as at,Au as au,Nv as av,Ff as aw,Hh as ax,qh as ay,ht as az,i0 as b,JO as b$,ow as b0,cu as b1,He as b2,D_ as b3,at as b4,Gt as b5,Ns as b6,_ as b7,fa as b8,Ae as b9,Xh as bA,So as bB,el as bC,un as bD,ds as bE,ZO as bF,gs as bG,gi as bH,Je as bI,Gi as bJ,ks as bK,Kf as bL,Fs as bM,KO as bN,Es as bO,Ds as bP,Ai as bQ,Ji as bR,tn as bS,_i as bT,xO as bU,iv as bV,wO as bW,UO as bX,BO as bY,zO as bZ,Iu as b_,Q as ba,dt as bb,$h as bc,Ke as bd,ge as be,Be as bf,ye as bg,de as bh,_r as bi,ve as bj,sa as bk,jO as bl,tL as bm,Of as bn,YO as bo,ze as bp,ia as bq,_e as br,Fa as bs,__ as bt,xt as bu,Or as bv,HO as bw,tA as bx,bg as by,Cn as bz,eL as c,W_ as c$,$O as c0,Df as c1,eb as c2,kf as c3,VO as c4,EM as c5,qO as c6,QO as c7,Nw as c8,Fn as c9,Pt as cA,us as cB,La as cC,Qa as cD,mi as cE,Mo as cF,uu as cG,pt as cH,kS as cI,Ul as cJ,Vt as cK,vl as cL,W1 as cM,zt as cN,ha as cO,Sn as cP,to as cQ,Le as cR,_t as cS,no as cT,Ma as cU,he as cV,Jx as cW,aI as cX,Op as cY,Dt as cZ,zn as c_,Hu as ca,N0 as cb,zA as cc,yo as cd,Vm as ce,Hi as cf,nr as cg,X3 as ch,ri as ci,GO as cj,WO as ck,Uw as cl,XO as cm,Bn as cn,Fw as co,WM as cp,z3 as cq,Pb as cr,_f as cs,xg as ct,Qw as cu,U1 as cv,z1 as cw,ke as cx,sr as cy,Du as cz,cs as d,F1 as d0,go as d1,dn as d2,Qs as d3,ql as d4,Vi as d5,aL as d6,cI as e,il as f,Q2 as g,iL as h,hb as i,Hs as j,Iy as k,wr as l,Wo as m,WI as n,m1 as o,Ct as p,T0 as q,RO as r,xr as s,Jr as t,ss as u,Ie as v,bn as w,Br as x,fe as y,rE as z};
|