@rr0/ufoathome 0.178.3 → 0.178.4
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-ByLXCo0I.js → CaseReportExport-DHdgnsTQ.js} +1 -1
- package/dist-embed-sighting/rr0-sighting.mjs +8 -8
- package/dist-embed-sighting-editor/{CaseReportExport-DBSSDC9F.js → CaseReportExport-D_e5Uij7.js} +1 -1
- package/dist-embed-sighting-editor/rr0-sighting-editor.mjs +7 -7
- package/package.json +1 -1
|
@@ -1921,9 +1921,9 @@ canvas[data-cursor="rotate"] {
|
|
|
1921
1921
|
`;class sa{static MAX_SPECKS=4;static BROADCAST_35MM={framesPerSecond:24,contrast:1.6,tint:[.99,.98,.92],softness:1.6/480,specksPerFrame:1.15,speckRadius:1.6/480,speckRadiusMax:4.5/480,weave:[.25/640,.6/480],grain:.008};static hash(t,e){const i=Math.sin(t*127.1+e*311.7)*43758.5453;return i-Math.floor(i)}static frameAt(t,e){return Math.floor(e*t.framesPerSecond/1e3)}static frame(t,e){const i=a=>sa.hash(e,a),n=a=>(i(a)+i(a+1)+i(a+2)-1.5)*2,s=Math.min(1,t.specksPerFrame/sa.MAX_SPECKS),r=[];for(let a=0;a<sa.MAX_SPECKS;a++){const c=10+a*6;if(i(c)>=s)continue;const l=i(c+3)**3;r.push({u:i(c+1),v:i(c+2),radius:t.speckRadius*.6+l*(t.speckRadiusMax-t.speckRadius*.6),kept:.25+.4*i(c+4)})}return{weave:[n(1)*t.weave[0],n(4)*t.weave[1]],specks:r,seed:i(7)}}}class Gl{static DEFAULT_FOCAL_MM=50;static FOCAL_RANGE_MM={minMm:14,maxMm:135};static BODIES=[{id:"eos-450d",name:"Canon EOS 450D (APS-C)",widthMm:22.2,heightMm:14.8,pixelUm:5.2,year:2008},{id:"eos-60da",name:"Canon EOS 60Da (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.3,year:2012},{id:"eos-70d",name:"Canon EOS 70D (APS-C)",widthMm:22.5,heightMm:15,pixelUm:4.1,year:2013},{id:"eos-80d",name:"Canon EOS 80D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:3.7,year:2016},{id:"eos-7d",name:"Canon EOS 7D (APS-C)",widthMm:22.3,heightMm:14.9,pixelUm:4.1,year:2009},{id:"eos-7d-ii",name:"Canon EOS 7D Mark II (APS-C)",widthMm:22.4,heightMm:15,pixelUm:4.1,year:2014},{id:"eos-5d",name:"Canon EOS 5D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:8.2,year:2005},{id:"eos-5d-ii",name:"Canon EOS 5D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:6.4,year:2008},{id:"eos-5d-iii",name:"Canon EOS 5D Mark III (full frame)",widthMm:36,heightMm:24,pixelUm:6.25,year:2012},{id:"eos-5d-iv",name:"Canon EOS 5D Mark IV (full frame)",widthMm:36,heightMm:24,pixelUm:5.36,year:2016},{id:"eos-6d",name:"Canon EOS 6D (full frame)",widthMm:35.8,heightMm:23.9,pixelUm:6.55,year:2012},{id:"eos-6d-ii",name:"Canon EOS 6D Mark II (full frame)",widthMm:36,heightMm:24,pixelUm:5.77,year:2017},{id:"nikon-d3",name:"Nikon D3 / D700 (full frame)",widthMm:36,heightMm:23.9,pixelUm:8.44,year:2007},{id:"nikon-d7000",name:"Nikon D7000 (DX)",widthMm:23.6,heightMm:15.6,pixelUm:4.78,year:2010},{id:"nikon-d7100",name:"Nikon D7100 / D7200 (DX)",widthMm:23.5,heightMm:15.6,pixelUm:3.9,year:2013},{id:"nikon-d500",name:"Nikon D500 / D7500 (DX)",widthMm:23.5,heightMm:15.7,pixelUm:4.2,year:2016}];static instruments(){return Gl.BODIES.map(t=>({id:t.id,category:"dslr",name:t.name,projection:"rectilinear",frame:{widthMm:t.widthMm,heightMm:t.heightMm,focalLengthMm:Gl.DEFAULT_FOCAL_MM,focalRangeMm:Gl.FOCAL_RANGE_MM},fNumber:8,fNumberRange:{min:1.4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/8e3,max:3600},years:{from:t.year},apertureBlades:7,detailUm:t.pixelUm,medium:{kind:"sensor",iso:100}}))}static names(){return Object.fromEntries(Gl.BODIES.map(t=>[t.id,t.name]))}}class mr{static DEFAULT_EYEPIECE_MM=26;static DEFAULT_APPARENT_FIELD_DEG=52;static FIELD_STOP_MM=2*mr.DEFAULT_EYEPIECE_MM*Math.tan(mr.DEFAULT_APPARENT_FIELD_DEG*Math.PI/360);static RANGE={min:26/40*.63,max:26/6*3};static BINOCULARS=[{id:"binoculars-zeiss-6x30",name:"Carl Zeiss 6x30",magnification:6,apertureMm:30,trueFieldDeg:5,fromYear:1960},{id:"binoculars-zeiss-dialyt-10x40",name:"Carl Zeiss Dialyt 10x40 B T*",magnification:10,apertureMm:40,trueFieldDeg:6.3,fromYear:1975},{id:"binoculars-jenoptem-10x50",name:"Jenoptem 10x50 W",magnification:10,apertureMm:50,trueFieldDeg:7.3,fromYear:1960},{id:"binoculars-swarovski-7x50-habicht",name:"Swarovski 7x50 SL Habicht",magnification:7,apertureMm:50,trueFieldDeg:6.6,fromYear:1960},{id:"binoculars-swarovski-7x50-slc",name:"Swarovski 7x50 SLC",magnification:7,apertureMm:50,trueFieldDeg:7.1,fromYear:1990},{id:"binoculars-nikon-10x42-edg",name:"Nikon 10x42 EDG",magnification:10,apertureMm:42,trueFieldDeg:6.5,fromYear:2011},{id:"binoculars-canon-15x50-is",name:"Canon 15x50 IS All Weather",magnification:15,apertureMm:50,trueFieldDeg:4.5,fromYear:2008},{id:"binoculars-celestron-15x70",name:"Celestron 15x70 SkyMaster",magnification:15,apertureMm:70,trueFieldDeg:4.4,fromYear:1990},{id:"binoculars-miyauchi-25x141",name:"Miyauchi BR-141 Galaxy 45 25x141",magnification:25,apertureMm:141,trueFieldDeg:2.6,fromYear:2e3}];static TELESCOPES=[{id:"telescope-generic-60-700",name:"Telescope 60/700",apertureMm:60,focalLengthMm:700},{id:"telescope-generic-60-1000",name:"Telescope 60/1000",apertureMm:60,focalLengthMm:1e3},{id:"telescope-celestron-onyx-80edf",name:"Celestron Onyx 80EDF",apertureMm:80,focalLengthMm:500,fromYear:2010},{id:"telescope-celestron-c5",name:"Celestron C5 f/10",apertureMm:125,focalLengthMm:1250,fromYear:1970},{id:"telescope-celestron-c8",name:"Celestron C8 f/10",apertureMm:203,focalLengthMm:2032,fromYear:1970},{id:"telescope-celestron-c11",name:"Celestron C11 f/10",apertureMm:280,focalLengthMm:2800,fromYear:1970},{id:"telescope-celestron-c14",name:"Celestron C14 f/11",apertureMm:355.6,focalLengthMm:3910,fromYear:1970},{id:"telescope-meade-etx-80",name:"Meade ETX 80 f/5",apertureMm:80,focalLengthMm:400,fromYear:1996},{id:"telescope-meade-etx-90",name:"Meade ETX 90 f/13.8",apertureMm:90,focalLengthMm:1242,fromYear:1996},{id:"telescope-meade-etx-125",name:"Meade ETX 125 f/15",apertureMm:127,focalLengthMm:1900,fromYear:1996},{id:"telescope-meade-lx200-8",name:"Meade LX200 8 in f/10",apertureMm:200,focalLengthMm:2e3,fromYear:1992},{id:"telescope-meade-lx200-10",name:"Meade LX200 10 in f/10",apertureMm:250,focalLengthMm:2500,fromYear:1992},{id:"telescope-meade-lx200-12",name:"Meade LX200 12 in f/10",apertureMm:305,focalLengthMm:3048,fromYear:1992},{id:"telescope-meade-lx200-14",name:"Meade LX200 14 in f/10",apertureMm:355,focalLengthMm:3556,fromYear:1992},{id:"telescope-meade-lx200-16",name:"Meade LX200 16 in f/10",apertureMm:406,focalLengthMm:4064,fromYear:1992}];static instruments(){const t=mr.BINOCULARS.map(n=>({id:n.id,category:"binoculars",name:n.name,projection:"rectilinear",visualAid:{apertureMm:n.apertureMm,magnification:n.magnification,trueFieldDeg:n.trueFieldDeg},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}})),e=mr.FIELD_STOP_MM,i=mr.TELESCOPES.map(n=>({id:n.id,category:"telescope",name:n.name,projection:"rectilinear",frame:{widthMm:e*16/9,heightMm:e,focalLengthMm:n.focalLengthMm,focalRangeMm:{minMm:n.focalLengthMm*mr.RANGE.min,maxMm:n.focalLengthMm*mr.RANGE.max}},visualAid:{apertureMm:n.apertureMm,eyepieceFocalMm:mr.DEFAULT_EYEPIECE_MM},...n.fromYear!==void 0?{years:{from:n.fromYear}}:{}}));return[...t,...i]}static names(){return Object.fromEntries(mr.instruments().map(t=>[t.id,t.name]))}}const Kd=[{id:"eye",category:"eye",name:"Naked eye",projection:"equidistant",stabilization:.97},{id:"rectilinear-lens",category:"camera",name:"Camera, unknown device",projection:"rectilinear",fNumber:8,fNumberRange:{min:2,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:8},apertureBlades:6},{id:"roamer-1-120",filmFormat:"120",category:"camera",name:"Roamer 1, 120 film",projection:"rectilinear",frame:{widthMm:74,heightMm:60,focalLengthMm:100},fNumber:11,exposureSeconds:1/50,years:{from:1930,to:1965},detailUm:40,medium:{kind:"negative",iso:125}},{id:"instamatic-126",filmFormat:"126",category:"camera",name:"Instamatic, 126 film",projection:"rectilinear",frame:{widthMm:28,heightMm:28,focalLengthMm:43},fNumber:11,exposureSeconds:1/90,years:{from:1963,to:1988},apertureBlades:5,detailUm:20,medium:{kind:"negative",iso:64}},{id:"slr-35mm-50",filmFormat:"135",category:"camera",name:"35 mm SLR, 50 mm lens",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:50},fNumber:8,fNumberRange:{min:2,max:16},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},years:{from:1959},apertureBlades:6,detailUm:20,medium:{kind:"negative",iso:100}},{id:"cine-35mm-broadcast",filmFormat:"35mm-cine",category:"camera",name:"35 mm film camera, seen on television",projection:"rectilinear",frame:{widthMm:21.3,heightMm:16,focalLengthMm:50,focalRangeMm:{minMm:18,maxMm:300}},fNumber:11,fNumberRange:{min:2,max:22},exposureSeconds:1/48,exposureRangeSeconds:{min:1/96,max:1/24},years:{from:1950,to:1995},apertureBlades:6,detailUm:15,medium:{kind:"negative",iso:100,print:sa.BROADCAST_35MM}},{id:"slr-35mm-zoom",filmFormat:"135",category:"camera",name:"35 mm SLR, 70-210 mm zoom",projection:"rectilinear",frame:{widthMm:36,heightMm:24,focalLengthMm:135,focalRangeMm:{minMm:70,maxMm:210}},fNumber:8,fNumberRange:{min:4,max:22},exposureSeconds:1/250,exposureRangeSeconds:{min:1/1e3,max:3600},apertureBlades:8,years:{from:1975},detailUm:20,medium:{kind:"negative",iso:100}},{id:"phone-landscape",category:"phone",name:"Phone, held sideways",projection:"rectilinear",frame:{widthMm:7.6,heightMm:5.7,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"phone-portrait",category:"phone",name:"Phone, held upright",projection:"rectilinear",frame:{widthMm:5.7,heightMm:7.6,focalLengthMm:5.7},fNumber:1.8,exposureSeconds:1/120,exposureRangeSeconds:{min:1/8e3,max:10},years:{from:2007},apertureBlades:void 0,detailUm:1.4,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:3200,metering:"highlights",development:"computational"}},{id:"dashcam",mounted:!0,category:"video",name:"Dashcam",projection:"equidistant",frame:{widthMm:5.76,heightMm:3.24,focalLengthMm:3.2},fNumber:2,exposureSeconds:1/30,exposureRangeSeconds:{min:1/1e4,max:1/30},years:{from:2008},apertureBlades:void 0,detailUm:3,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},{id:"cctv",mounted:!0,category:"video",name:"Security camera",projection:"rectilinear",frame:{widthMm:4.8,heightMm:3.6,focalLengthMm:3.6},fNumber:2,exposureSeconds:1/50,exposureRangeSeconds:{min:1/1e5,max:1/50},years:{from:1990},apertureBlades:void 0,detailUm:6,medium:{kind:"sensor",iso:100,autoExposure:!0,maxIso:1600,metering:"average",exposureFollowMs:500}},...Gl.instruments(),...mr.instruments()];class $i{static get default(){return Kd[0]}static byId(t){return Kd.find(e=>e.id===t)??this.default}static UNAIDED_FIELD_DEG=60;static UNAIDED_ASPECT=16/9;static fieldOfViewDeg(t){const e=t.frame;return e?$i.fieldOf(t.projection,e.heightMm,e.focalLengthMm):t.visualAid?.trueFieldDeg??$i.UNAIDED_FIELD_DEG}static fieldOf(t,e,i){return(t==="equidistant"?e/i:2*Math.atan(e/(2*i)))*180/Math.PI}static aspectOf(t){const e=t.frame;return e?e.widthMm/e.heightMm:$i.UNAIDED_ASPECT}static frameWidthPx(t,e){return Math.round(e*$i.aspectOf(t))}static CATEGORIES=["eye","camera","dslr","phone","video","binoculars","telescope"];static unavailability(t,e){const i=t.years;if(!(e===void 0||!i)){if(e<i.from)return{kind:"before",from:i.from};if(i.to!==void 0&&e>i.to)return{kind:"after",to:i.to}}}static availableAt(t){return t===void 0?Kd:Kd.filter(e=>!e.years||t>=e.years.from&&(e.years.to===void 0||t<=e.years.to))}static fieldOfViewDegAt(t,e){const i=t.frame;if(!(!i||e<=0))return $i.fieldOf(t.projection,i.heightMm,e)}static focalLengthMmFor(t,e){const i=t.frame;if(!(!i||e<=0||e>=180))return t.projection==="equidistant"?i.heightMm/(e*Math.PI/180):i.heightMm/(2*Math.tan(e*Math.PI/360))}static bladesShowing(t,e){if(t.apertureBlades===void 0)return 0;const i=e??t.fNumber,n=t.fNumberRange?.min;if(i===void 0||n===void 0)return 1;const s=Math.max(0,Math.min(1,(i/n-1)/.3));return s*s*(3-2*s)}static starPointsOf(t,e){const i=t.apertureBlades;return i===void 0||i<3||$i.bladesShowing(t,e)<.5?0:i%2===0?i:i*2}}class hh{constructor(t){this.points=t}static STATIONARY_M=5;static of(t){const e=[];for(const i of t.observerTrack.allKeyframes){const{lat:n,lng:s,headingDeg:r}=i.pose;n===void 0||s===void 0||e.push({t:i.t,lat:n,lng:s,headingDeg:r})}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 hh(e)}static TRAVEL_M=50;get travels(){return this.spanM>hh.TRAVEL_M}get moved(){return this.spanM>hh.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(se(e,t.east,e,t.west).x),Math.abs(se(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:n}=this.center,s=Math.max(this.spanM*(1+e),t)/2;return{north:Cs(0,-s,i,n).lat,south:Cs(0,s,i,n).lat,east:Cs(s,0,i,n).lng,west:Cs(-s,0,i,n).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 Qs{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)>Qs.HAND_HELD_S,i=t.sway??(e?0:1);if(i>0)return new Qs(Math.max(1-(t.instrument.stabilization??0),Qs.GAZE_DRIFT_SHARE),i)}offsetAt(t){const e=t/1e3,i=this.scale,n=(u,d)=>Math.sin(2*Math.PI*u*e+d),[s,r,a,c,l,h]=Qs.HZ;return{eastM:i*Qs.SWAY_M*(.7*n(s,.3)+.3*n(c,1.9)),northM:i*Qs.SWAY_M*(.6*n(a,2.2)+.4*n(l,.8)),upM:i*Qs.BREATH_M*n(r,0),yawDeg:i*this.rotationPassed*Qs.DRIFT_YAW_DEG*(.6*n(h,1.1)+.4*n(c,2.7)),pitchDeg:i*this.rotationPassed*Qs.DRIFT_PITCH_DEG*(.5*n(r,1.6)+.5*n(a,.4)),rollDeg:i*this.rotationPassed*Qs.DRIFT_ROLL_DEG*n(s,2.9)}}}class ai{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=hh.of(t);if(!e||e.points.length<2)return;const i=[];let n=0;for(let s=1;s<e.points.length;s++){const r=e.points[s-1],a=e.points[s],c=(a.t-r.t)/1e3;if(c<=0)continue;const l=se(a.lat,a.lng,r.lat,r.lng),h=l.x,u=-l.z,d=Math.hypot(h,u),f=d/c,p=ai.stepHzFor(f);i.push({startMs:r.t,endMs:a.t,speedMPerS:f,eastUnit:d>0?h/d:0,northUnit:d>0?u/d:0,stepHz:p,stepsBefore:n,rampsIn:!0,rampsOut:!0}),n+=p*c}for(let s=0;s<i.length;s++){const r=i[s-1],a=i[s+1];i[s].rampsIn=r===void 0||r.stepHz===0,i[s].rampsOut=a===void 0||a.stepHz===0}if(i.some(s=>s.stepHz>0))return new ai(i,1-(t.instrument.stabilization??0))}static bodyAt(t,e,i=!1){const n=ai.of(t)?.offsetAt(e)??ai.STILL;return i?n:ai.add(n,Qs.of(t)?.offsetAt(e))}static stepHzFor(t){return t<ai.SLOWEST_WALK_M_PER_S||t>ai.FASTEST_WALK_M_PER_S?0:ai.REFERENCE_STEP_HZ*Math.pow(t/ai.REFERENCE_SPEED_M_PER_S,ai.CADENCE_EXPONENT)}offsetAt(t){return ai.add(this.cycleAt(t),this.joltAt(t))}joltAt(t){for(const e of this.stretches){if(e.stepHz===0)continue;const i=e.speedMPerS/ai.REFERENCE_SPEED_M_PER_S,n=(a,c,l,h)=>{if(a<0||a>ai.JOLT_LASTS_MS)return;const u=a/1e3,d=Math.exp(-u/ai.JOLT_DECAY_S)*Math.sin(2*Math.PI*ai.JOLT_HZ*u),f=h*c*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}},s=e.rampsOut?n(t-e.endMs,ai.STOP_LURCH_M,ai.STOP_PITCH_DEG,1):void 0;if(s)return s;const r=e.rampsIn?n(t-e.startMs,ai.START_LURCH_M,ai.START_PITCH_DEG,-1):void 0;if(r)return r}}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(c=>t>=c.startMs&&t<=c.endMs);if(!e||e.stepHz===0)return ai.STILL;const i=e.stepsBefore+e.stepHz*(t-e.startMs)/1e3,n=2*Math.PI*i,s=this.amplitudeAt(e,t),r=ai.SWAY_M*s*Math.cos(n/2),a=s*this.rotationPassed*e.speedMPerS/ai.REFERENCE_SPEED_M_PER_S;return{eastM:r*e.northUnit,northM:-r*e.eastUnit,upM:ai.RISE_M_PER_M_PER_S*e.speedMPerS*s*Math.cos(n),rollDeg:ai.HEAD_ROLL_DEG*a*Math.cos(n/2),pitchDeg:-1.25*a*Math.cos(n),yawDeg:ai.HEAD_YAW_DEG*a*Math.cos(n/2)}}amplitudeAt(t,e){const i=1e3/t.stepHz,n=Math.min(i,(t.endMs-t.startMs)/2);if(n<=0)return 1;const s=e-t.startMs,r=t.endMs-e,a=Math.min(t.rampsIn?s/n:1,t.rampsOut?r/n:1,1);return(1-Math.cos(Math.PI*Math.max(a,0)))/2}}class Du{static ISO=/^P(?:(\d+(?:[.,]\d+)?)W)?(?:(\d+(?:[.,]\d+)?)D)?(?:T(?:(\d+(?:[.,]\d+)?)H)?(?:(\d+(?:[.,]\d+)?)M)?(?:(\d+(?:[.,]\d+)?)S)?)?$/;static seconds(t){const e=t.trim().toUpperCase(),i=Du.ISO.exec(e);if(!i||e==="P"||e.endsWith("T"))return;const[,n,s,r,a,c]=i,l=u=>u===void 0?0:Number(u.replace(",",".")),h=l(n)*604800+l(s)*86400+l(r)*3600+l(a)*60+l(c);return Number.isFinite(h)?h:void 0}static parse(t){let e=t.trim();if(e==="")return;const i=e.slice(-1),n="?~%".includes(i)?i:"";n!==""&&(e=e.slice(0,-1).trim());const s=e.split("/");if(s.length>2)return;const r=s.map(u=>Du.seconds(u));if(r.some(u=>u===void 0))return;const[a,c]=r,l=Math.min(a,c??a),h=Math.max(a,c??a);return{doubt:n,minSeconds:l,maxSeconds:h,chosenSeconds:(l+h)/2}}static isExact(t){const e=Du.parse(t);return e!==void 0&&e.doubt===""&&e.minSeconds===e.maxSeconds}static format(t){const e=Math.max(0,Math.round(t*10)/10),i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10;return`PT${`${i>0?`${i}H`:""}${n>0?`${n}M`:""}${s>0||i===0&&n===0?`${s}S`:""}`}`}static say(t){const e=Math.round(t*10)/10;if(e<60)return`${e} s`;const i=Math.floor(e/3600),n=Math.floor(e%3600/60),s=Math.round(e%60*10)/10,r=[];return i>0&&r.push(`${i} h`),n>0&&r.push(`${n} min`),s>0&&r.push(`${s} s`),r.join(" ")}}class ui{static MOON_ANGULAR_WIDTH_DEG=.5237;static CANVAS_WIDTH_PX=640;static CANVAS_HEIGHT_PX=360;static angularWidthDeg(t){return 2*Math.atan(t.sizeM/(2*t.distanceM))*180/Math.PI}static inMoons(t){return t/ui.MOON_ANGULAR_WIDTH_DEG}static lerpAngular(t,e,i){if(!(!t||!e))return{widthDeg:t.widthDeg+(e.widthDeg-t.widthDeg)*i,heightDeg:t.heightDeg+(e.heightDeg-t.heightDeg)*i}}static sizeMAt(t,e){return 2*t*Math.tan(e*Math.PI/360)}static distanceMAt(t,e){return t/(2*Math.tan(e*Math.PI/360))}}function i3(o,t,e){if(!o||!t)return e<1?o:t;const i=((t.azimuthDeg-o.azimuthDeg)%360+540)%360-180;return{azimuthDeg:((o.azimuthDeg+i*e)%360+360)%360,altitudeDeg:o.altitudeDeg+(t.altitudeDeg-o.altitudeDeg)*e}}function n3(o,t,e){const{bounds:i}=o;return t>=i.x&&t<=i.x+i.width&&e>=i.y&&e<=i.y+i.height}function Es(o,t,e){return o+(t-o)*e}function py(o){const t=/^#([0-9a-f]{6})$/i.exec(o);if(!t)return;const e=parseInt(t[1],16);return[e>>16&255,e>>8&255,e&255]}function s3(o){return`#${o.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`}function r3(o,t,e){const i=py(o),n=py(t);return!i||!n?e<1?o:t:s3([Es(i[0],n[0],e),Es(i[1],n[1],e),Es(i[2],n[2],e)])}function a3(o,t,e){const i={x:Es(o.bounds.x,t.bounds.x,e),y:Es(o.bounds.y,t.bounds.y,e),width:Es(o.bounds.width,t.bounds.width,e),height:Es(o.bounds.height,t.bounds.height,e)},n=Es(o.angle,t.angle,e),s=Es(o.transparency,t.transparency,e),r=Es(o.haloScale,t.haloScale,e),a=Es(o.blur??0,t.blur??0,e),c=Es(o.brightness??0,t.brightness??0,e),l=r3(o.color,t.color,e),h=ui.lerpAngular(o.angular,t.angular,e),u=i3(o.aim,t.aim,e);return o.kind==="polygon"&&t.kind==="polygon"&&o.points.length===t.points.length?{...o,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u,points:o.points.map((d,f)=>({x:Es(d.x,t.points[f].x,e),y:Es(d.y,t.points[f].y,e)}))}:{...e<1?o:t,bounds:i,angle:n,transparency:s,haloScale:r,blur:a,brightness:c,color:l,angular:h,aim:u}}class yo{static DEFAULT_COLOR="#e8e6df";static complete(t,e=[]){const i=new Map;return t.map((n,s)=>({keyframe:n,index:s})).sort((n,s)=>n.keyframe.t-s.keyframe.t).map(({keyframe:n,index:s})=>({t:n.t,shapes:(n.shapes??[]).map((r,a)=>{const c=`timeline.keyframes.${s}.shapes.${a}.shape`,l=yo.completed(r,i.get(r.sourceId),c,e);return i.set(r.sourceId,l),{sourceId:r.sourceId,shape:l}})}))}static thin(t,e){const i=new Map,n=new Set;return t.map((s,r)=>({t:s.t,shapes:s.shapes.map(a=>{const c=i.get(a.sourceId);if(i.set(a.sourceId,a.shape),!c)return{sourceId:a.sourceId,shape:a.shape};const l=yo.thinned(a.shape,c);if(e){const h=l;e(r,a.sourceId)?(delete h.bounds,delete h.points,n.add(a.sourceId)):n.delete(a.sourceId)&&(h.bounds=a.shape.bounds,a.shape.kind==="polygon"&&(h.points=a.shape.points),a.shape.aim&&(h.aim=a.shape.aim),a.shape.angular&&(h.angular=a.shape.angular))}return{sourceId:a.sourceId,shape:l}})}))}static thinned(t,e){const i=e,n={};for(const[s,r]of Object.entries(t))(typeof r=="object"&&r!==null&&!Array.isArray(r)&&"value"in r||r!==i[s]&&JSON.stringify(r)!==JSON.stringify(i[s]))&&(n[s]=r);return"bounds"in n&&(t.aim&&(n.aim=t.aim),t.angular&&(n.angular=t.angular)),n}static completed(t,e,i,n){const s=t.shape??{},r=e??yo.firstAppearance(s,i,n),a={...r};s.bounds&&e&&(e.aim||e.angular)&&!s.aim&&!s.angular&&n.push({kind:"pixels-over-angles",path:i}),s.bounds&&(s.aim||delete a.aim,s.angular||delete a.angular);const c=s.kind??r.kind??"oval",l={...a,...s,kind:c};if(c==="polygon"&&!l.points){n.push({kind:"defaulted",path:`${i}.points`,expected:"rectangle"});const{width:h,height:u}=l.bounds;return{...l,points:[{x:0,y:0},{x:h,y:0},{x:h,y:u},{x:0,y:u}]}}return l}static firstAppearance(t,e,i){return t.kind||i.push({kind:"defaulted",path:`${e}.kind`,expected:'"oval"'}),t.color||i.push({kind:"defaulted",path:`${e}.color`,expected:`"${yo.DEFAULT_COLOR}"`}),!t.bounds&&!t.aim&&i.push({kind:"unplaced",path:e}),!t.bounds&&!t.angular&&i.push({kind:"unsized",path:e}),{kind:t.kind??"oval",bounds:{...yo.NEUTRAL_BOUNDS},color:yo.DEFAULT_COLOR,angle:0,transparency:0,haloScale:0,selected:!1}}static NEUTRAL_BOUNDS={x:ui.CANVAS_WIDTH_PX/2,y:ui.CANVAS_HEIGHT_PX/2,width:1,height:1}}class Ud{keyframes=[];order=[];groups=[];span=0;addKeyframe(t,e){const i=this.findInsertIndex(t);if(this.keyframes[i]?.t===t){const n=new Set(e.map(s=>s.sourceId));this.keyframes[i]={t,shapes:[...this.keyframes[i].shapes.filter(s=>!n.has(s.sourceId)),...e]}}else this.keyframes.splice(i,0,{t,shapes:[...e]});for(const n of e)this.order.includes(n.sourceId)||this.order.push(n.sourceId)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getKeyframeAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e];return i?.t===t?i:void 0}getShapeAt(t,e){return this.getKeyframeAt(t)?.shapes.find(i=>i.sourceId===e)?.shape}getLatestShapeAt(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return n.shape}}getInterpolatedShapeAt(t,e){const i=this.findShapeAtOrBefore(t,e);if(i?.t===t)return i.shape;const n=this.findShapeAtOrAfter(t,e);return i?n?a3(i.shape,n.shape,(t-i.t)/(n.t-i.t)):i.shape:n?.shape}findShapeAtOrBefore(t,e){let i=this.findInsertIndex(t);for(this.keyframes[i]?.t!==t&&(i-=1);i>=0;i--){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}findShapeAtOrAfter(t,e){for(let i=this.findInsertIndex(t);i<this.keyframes.length;i++){const n=this.keyframes[i].shapes.find(s=>s.sourceId===e);if(n)return{t:this.keyframes[i].t,shape:n.shape}}}hitTest(t,e,i,n){const s=this.sourceIds;for(let r=s.length-1;r>=0;r--){if(n?.has(s[r]))continue;const a=this.getInterpolatedShapeAt(t,s[r]);if(a&&n3(a,e,i))return{sourceId:s[r],shape:a}}}removeSource(t){for(let e=this.keyframes.length-1;e>=0;e--){const i=this.keyframes[e].shapes.filter(n=>n.sourceId!==t);i.length===0?this.keyframes.splice(e,1):i.length!==this.keyframes[e].shapes.length&&(this.keyframes[e]={t:this.keyframes[e].t,shapes:i})}this.order=this.order.filter(e=>e!==t),this.removeFromGroup(t)}removeShapeAt(t,e){const i=this.findInsertIndex(t),n=this.keyframes[i];if(n?.t!==t)return;const s=n.shapes.filter(r=>r.sourceId!==e);s.length===0?this.keyframes.splice(i,1):s.length!==n.shapes.length&&(this.keyframes[i]={t,shapes:s})}group(t,e){const i=new Set(t),n=[];for(const r of t){const a=this.topOf(r),c=a!==r&&this.leavesOf(a).every(l=>i.has(l))?a:r;c===r&&a!==r&&this.removeFromGroup(r),n.includes(c)||n.push(c)}if(n.length<2)return;const s=e??this.freshGroupId();return this.groups.push({id:s,members:n}),s}ungroup(t){const e=this.topOf(t);e!==t&&(this.groups=this.groups.filter(i=>i.id!==e))}groupMembers(t){const e=this.topOf(t);return e===t?void 0:this.leavesOf(e)}get allGroups(){return this.groups}setGroups(t,e=!0){this.groups=t.map(i=>({...i,members:[...i.members]})),e&&this.pruneGroups()}groupOf(t){return this.groups.find(e=>e.id===t)}leavesOf(t,e=new Set){const i=this.groupOf(t);return i?e.has(t)?[]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e))):[t]}parentOf(t){return this.groups.find(e=>e.members.includes(t))}topOf(t){let e=t;for(let i=this.parentOf(e),n=0;i&&n<100;i=this.parentOf(e),n++)e=i.id;return e}freshGroupId(){for(let t=this.groups.length+1;;t++){const e=`group-${t}`;if(!this.groupOf(e)&&!this.order.includes(e))return e}}removeFromGroup(t){const e=this.parentOf(t);e&&(e.members=e.members.filter(i=>i!==t),this.collapse())}pruneGroups(){const t=e=>this.order.includes(e)||this.groupOf(e)!==void 0;for(const e of this.groups)e.members=e.members.filter(t);this.collapse()}collapse(){for(let t=this.groups.find(e=>e.members.length<2);t;t=this.groups.find(e=>e.members.length<2)){const e=t;this.groups=this.groups.filter(i=>i!==e);for(const i of this.groups)i.members=i.members.flatMap(n=>n===e.id?e.members:[n])}}bringToFront(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.push(t))}sendToBack(t){const e=this.order.indexOf(t);e!==-1&&(this.order.splice(e,1),this.order.unshift(t))}get duration(){const t=this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t;return Math.max(t,this.span)}get hasSpan(){return this.span>0}setSpan(t){this.span=Math.max(0,t)}get sourceIds(){return[...this.order]}get allKeyframes(){return this.keyframes}toJSON(){return this.span>0?{keyframes:this.keyframes,order:this.order,groups:this.groupsJson(),span:this.span}:{keyframes:this.keyframes,order:this.order,groups:this.groupsJson()}}groupsJson(){return this.groups.map(t=>({...t,members:[...t.members]}))}static fromJSON(t,e,i=!0){const n=new Ud;for(const s of yo.complete(t.keyframes??[],e))n.addKeyframe(s.t,s.shapes);if(t.span!==void 0&&t.span>0&&(n.span=t.span),t.order){const s=n.order.filter(r=>!t.order.includes(r));n.order=[...t.order,...s]}return t.groups&&(n.groups=t.groups.filter(s=>typeof s?.id=="string"&&Array.isArray(s.members)).map(s=>({...s,members:[...s.members]})),i&&n.pruneGroups()),n}}function o3(o,t,e){return Math.max(t,Math.min(e,o))}function c3(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function jc(o,t,e){return o+(t-o)*e}function l3(o,t,e){return{lat:o.lat===void 0||t.lat===void 0?void 0:jc(o.lat,t.lat,e),lng:o.lng===void 0||t.lng===void 0?void 0:jc(o.lng,t.lng,e),elevationM:jc(o.elevationM,t.elevationM,e),headingDeg:o.headingDeg===void 0||t.headingDeg===void 0?void 0:c3(o.headingDeg,t.headingDeg,e),pitchDeg:jc(o.pitchDeg,t.pitchDeg,e),rollDeg:jc(o.rollDeg??0,t.rollDeg??0,e),fovDeg:jc(o.fovDeg,t.fovDeg,e),fNumber:o.fNumber,focusDistanceM:o.focusDistanceM,filter:o.filter}}class vn{static at(t,e,i,n,s){const r=t[i],c=t[i+1]-r;if(c<=0)return e[i];const l=vn.tangent(t,e,i,s),h=vn.tangent(t,e,i+1,s),u=(n-r)/c,d=u*u,f=d*u;return(2*f-3*d+1)*e[i]+(f-2*d+u)*c*l+(-2*f+3*d)*e[i+1]+(f-d)*c*h}static SETTLE_MS=120;static ARRIVAL=.5;static gaze(t,e,i,n){const s=t[i],a=t[i+1]-s;if(a<=0)return e[i];const c=h=>h+1<e.length?e[h+1]===e[h]:!0,l=e[i+1]!==e[i];if(l&&c(i+1)){const h=vn.tangent(t,e,i,!0),u=vn.ARRIVAL*(e[i+1]-e[i])/a;return vn.hermite(e[i],h,e[i+1],u,a,(n-s)/a)}return!l&&i>0&&e[i-1]!==e[i]?e[i]+vn.settle(t,e,i,n-s,a):vn.at(t,e,i,n,!0)}static settle(t,e,i,n,s){const r=t[i]-t[i-1];if(r<=0||n<=0)return 0;const a=vn.ARRIVAL*(e[i]-e[i-1])/r,c=Math.min(vn.SETTLE_MS,.4*r),l=Number.isFinite(s)?(1-Math.min(1,n/s))**2:1;return a*n*Math.exp(-n/c)*l}static hermite(t,e,i,n,s,r){const a=r*r,c=a*r;return(2*c-3*a+1)*t+(c-2*a+r)*s*e+(-2*c+3*a)*i+(c-a)*s*n}static BRAKE_S=.8;static paced(t,e,i,n){if(!i&&!n)return t;const s=e>0?Math.min(.5,vn.BRAKE_S/e):.5;if(i&&n){const a=1/(1-s);return t<=s?a*t*t/(2*s):t>=1-s?1-a*(1-t)*(1-t)/(2*s):a*(t-s/2)}const r=a=>{const c=1/(1-s/2);if(a<=1-s)return c*a;const l=a-(1-s);return c*(1-s)+c*(l-l*l/(2*s))};return n?r(t):1-r(1-t)}static tangent(t,e,i,n){const s=t.length-1,r=f=>(e[f+1]-e[f])/(t[f+1]-t[f]||1);if(i===0)return n?0:r(0);if(i===s)return n?0:r(s-1);const a=r(i-1),c=r(i);if(a*c<=0)return 0;const l=t[i]-t[i-1],h=t[i+1]-t[i],u=2*h+l,d=h+2*l;return(u+d)/(u/a+d/c)}}class Qu{keyframes=[];addKeyframe(t,e,i){const n=this.findInsertIndex(t),s=this.keyframes[n]?.t===t?this.keyframes[n]:void 0,a=i??s?.viewOnly?{t,pose:e,viewOnly:!0}:{t,pose:e};s?this.keyframes[n]=a:this.keyframes.splice(n,0,a)}setViewOnly(t,e){const i=this.findInsertIndex(t),n=this.keyframes[i];n?.t===t&&(this.keyframes[i]=e?{...n,viewOnly:!0}:{t:n.t,pose:n.pose})}turnIsViewOnly(t,e){if(this.keyframes.length===0)return!1;const i=Math.max(0,this.findInsertIndex(t)-(this.keyframes[this.findInsertIndex(t)]?.t===t?0:1));for(let n=i;n<this.keyframes.length;n++){const s=this.keyframes[n];if(s.viewOnly)return!0;if(s.t>=e)break}return!1}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestPoseAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].pose:void 0}getInterpolatedPoseAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.pose;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.pose;if(!n)return this.settledAfterEnd(e-1,t);const s=l3(i.pose,n.pose,o3((t-i.t)/(n.t-i.t),0,1));return this.humanly(e-1,t,s)}settledAfterEnd(t,e){const i=this.keyframes[t];if(t<1)return i.pose;const n=this.keyframes[t-1],s=[n.t,i.t],r=(h,u)=>h===void 0||u===void 0?0:vn.settle(s,[h,u],1,e-i.t,1/0),a=n.pose.headingDeg===void 0||i.pose.headingDeg===void 0?void 0:((i.pose.headingDeg-n.pose.headingDeg)%360+540)%360-180,c=i.pose.headingDeg===void 0||a===void 0?i.pose.headingDeg:((i.pose.headingDeg+r(0,a))%360+360)%360,l=i.pose.pitchDeg+r(n.pose.pitchDeg,i.pose.pitchDeg);return c===i.pose.headingDeg&&l===i.pose.pitchDeg?i.pose:{...i.pose,headingDeg:c,pitchDeg:l}}humanly(t,e,i){const n=Math.max(0,t-1),s=Math.min(this.keyframes.length-1,t+2),r=this.keyframes.slice(n,s+1),a=t-n,c=r.map(y=>y.t),l=(y,w)=>{const S=r.map(E=>y(E.pose));if(!S.some(E=>E===void 0))return vn.at(c,S,a,e,w)},h=y=>{const w=r.map(S=>y(S.pose));if(!w.some(S=>S===void 0))return vn.gaze(c,w,a,e)},u=r.map(y=>y.pose.headingDeg);let d;if(u.every(y=>y!==void 0)){const y=[u[0]];for(let w=1;w<u.length;w++)y.push(y[w-1]+((u[w]-u[w-1])%360+540)%360-180);d=(vn.gaze(c,y,a,e)%360+360)%360}const f=this.keyframes[t],p=this.keyframes[t+1],m=(y,w)=>y.lat===w.lat&&y.lng===w.lng&&y.elevationM===w.elevationM,g=!m(f.pose,p.pose),v=g&&t>0&&m(this.keyframes[t-1].pose,f.pose),M=g&&t+2<this.keyframes.length&&m(p.pose,this.keyframes[t+2].pose);let x;if(v||M){const y=vn.paced((e-f.t)/(p.t-f.t),(p.t-f.t)/1e3,v,M),w=(S,E)=>S===void 0||E===void 0?void 0:S+(E-S)*y;x={lat:w(f.pose.lat,p.pose.lat),lng:w(f.pose.lng,p.pose.lng),elevationM:w(f.pose.elevationM,p.pose.elevationM)}}return{...i,lat:x?x.lat:l(y=>y.lat,!1)??i.lat,lng:x?x.lng:l(y=>y.lng,!1)??i.lng,elevationM:x?x.elevationM:l(y=>y.elevationM,!1)??i.elevationM,headingDeg:d??i.headingDeg,pitchDeg:h(y=>y.pitchDeg)??i.pitchDeg,rollDeg:l(y=>y.rollDeg??0,!0)??i.rollDeg,fovDeg:l(y=>y.fovDeg,!0)??i.fovDeg}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new Qu;for(const i of t.keyframes)e.addKeyframe(i.t,i.pose,i.viewOnly);return e}}class xo{static MAX_CHANGE_PER_S=.05;points;followed;constructor(t){let e="none",i=0;this.points=t.map(({t:n,weather:s})=>(s.precipitationType!=="none"&&(e=s.precipitationType,i=s.precipitationIntensity),{t:n,lastFalling:e,lastFallingIntensity:i,intensity:s.precipitationType==="none"?0:s.precipitationIntensity,type:s.precipitationType})),this.followed=[];for(let n=0;n<this.points.length;n++){if(n===0){this.followed.push(this.points[0].intensity);continue}const s=this.points[n-1],r=this.points[n];this.followed.push(xo.follow(this.followed[n-1],s.intensity,r.intensity,(r.t-s.t)/1e3,(r.t-s.t)/1e3))}}at(t){if(this.points.length===0||t<this.points[0].t)return;let e=this.points.length-1;for(;e>0&&this.points[e].t>t;)e--;const i=this.points[e],n=this.points[e+1],s=n?xo.follow(this.followed[e],i.intensity,n.intensity,(n.t-i.t)/1e3,(t-i.t)/1e3):xo.follow(this.followed[e],i.intensity,i.intensity,1,(t-i.t)/1e3);return{type:xo.typeBetween(i,n,t,s),intensity:s,character:xo.characterBetween(i,n,t)}}static characterBetween(t,e,i){return t.type==="none"?e&&e.type!=="none"?e.intensity:t.lastFallingIntensity:!e||e.type==="none"?t.intensity:t.intensity+(e.intensity-t.intensity)*(i-t.t)/(e.t-t.t||1)}static typeBetween(t,e,i,n){return t.type==="none"?e&&e.type!=="none"&&i>t.t?e.type:n>0?t.lastFalling:"none":e&&e.type==="none"&&n<=0?"none":t.type}static follow(t,e,i,n,s){const r=xo.MAX_CHANGE_PER_S,a=n>0?(i-e)/n:0,c=u=>e+a*Math.min(Math.max(u,0),n);let l=t,h=0;for(let u=0;u<8&&h<s;u++){const d=c(h)-l;if(Math.abs(d)<1e-9){const x=h<n?a:0;if(Math.abs(x)<=r){const w=h<n?Math.min(s,n):s;l=c(w),h=w;continue}const y=Math.min(s,n);l+=Math.sign(x)*r*(y-h),h=y;continue}const f=Math.sign(d),p=h<n?a:0,m=r-f*p,g=m>0?h+Math.abs(d)/m:1/0,v=h<n?n:1/0,M=Math.min(s,g,v);l+=f*r*(M-h),h=M,M===g&&(l=c(h))}return Math.min(1,Math.max(0,l))}}function xi(o,t,e){return o+(t-o)*e}function Gv(o,t,e){const i=((t-o)%360+540)%360-180;return((o+i*e)%360+360)%360}function h3(o,t,e){return Math.max(t,Math.min(e,o))}function u3(o=[],t=[],e){if(!(!o.length&&!t.length))return[...new Set([...o.map(i=>i.id),...t.map(i=>i.id)])].map(i=>{const n=o.find(c=>c.id===i),s=t.find(c=>c.id===i),r=n??{...s,density:0},a=s??{...n,density:0};return{...r,eastM:xi(r.eastM,a.eastM,e),northM:xi(r.northM,a.northM,e),baseM:xi(r.baseM,a.baseM,e),thicknessM:xi(r.thicknessM,a.thicknessM,e),widthM:xi(r.widthM,a.widthM,e),depthM:xi(r.depthM,a.depthM,e),rotationDeg:Gv(r.rotationDeg,a.rotationDeg,e),density:xi(r.density,a.density,e),darkness:xi(r.darkness??0,a.darkness??0,e)}})}function d3(o,t,e){if(o.cloudLayers===void 0&&t.cloudLayers===void 0)return;const i=B0(o),n=B0(t);return e>=1?n.map(r=>({...r})):[...new Set([...i.map(r=>r.id),...n.map(r=>r.id)])].map(r=>{const a=i.find(u=>u.id===r),c=n.find(u=>u.id===r),l=a??{...c,coverage:0},h=c??{...a,coverage:0};return{...l,instances:u3(a?.instances,c?.instances,e),baseM:xi(l.baseM,h.baseM,e),thicknessM:xi(l.thicknessM,h.thicknessM,e),coverage:xi(l.coverage,h.coverage,e),sizeM:xi(l.sizeM,h.sizeM,e),density:xi(l.density,h.density,e),darkness:xi(l.darkness??o.cloudDarkness,h.darkness??t.cloudDarkness,e),iceCrystalAlignment:l.iceCrystalAlignment===void 0||h.iceCrystalAlignment===void 0?void 0:xi(l.iceCrystalAlignment,h.iceCrystalAlignment,e),windSpeed:l.windSpeed===void 0&&h.windSpeed===void 0?void 0:xi(l.windSpeed??o.windSpeed,h.windSpeed??t.windSpeed,e),windDirectionDeg:l.windDirectionDeg===void 0&&h.windDirectionDeg===void 0?void 0:Gv(l.windDirectionDeg??o.windDirectionDeg,h.windDirectionDeg??t.windDirectionDeg,e)}})}function f3(o,t,e){return{cloudLayers:d3(o,t,e),cloudCover:xi(o.cloudCover,t.cloudCover,e),cloudDarkness:xi(o.cloudDarkness,t.cloudDarkness,e),highCloudCover:o.highCloudCover===void 0||t.highCloudCover===void 0?void 0:xi(o.highCloudCover,t.highCloudCover,e),iceCrystalAlignment:o.iceCrystalAlignment===void 0||t.iceCrystalAlignment===void 0?void 0:xi(o.iceCrystalAlignment,t.iceCrystalAlignment,e),rareIceCrystals:o.rareIceCrystals===void 0||t.rareIceCrystals===void 0?void 0:xi(o.rareIceCrystals,t.rareIceCrystals,e),lowerCloudCover:o.lowerCloudCover===void 0||t.lowerCloudCover===void 0?void 0:xi(o.lowerCloudCover,t.lowerCloudCover,e),cloudBaseM:o.cloudBaseM===void 0||t.cloudBaseM===void 0?void 0:xi(o.cloudBaseM,t.cloudBaseM,e),relativeHumidity:o.relativeHumidity===void 0||t.relativeHumidity===void 0?void 0:xi(o.relativeHumidity,t.relativeHumidity,e),visibilityKm:o.visibilityKm===void 0||t.visibilityKm===void 0?void 0:xi(o.visibilityKm,t.visibilityKm,e),precipitationType:e<1?o.precipitationType:t.precipitationType,precipitationIntensity:xi(o.precipitationIntensity,t.precipitationIntensity,e),windDirectionDeg:Gv(o.windDirectionDeg,t.windDirectionDeg,e),windSpeed:xi(o.windSpeed,t.windSpeed,e),storm:e<1?o.storm:t.storm}}class td{keyframes=[];ramp;addKeyframe(t,e){this.ramp=void 0;const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,weather:e}:this.keyframes.splice(i,0,{t,weather:e})}clear(){this.ramp=void 0,this.keyframes.length=0}removeKeyframeAt(t){this.ramp=void 0;const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}getLatestWeatherAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].weather:void 0}getInterpolatedWeatherAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.weather;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];return i?n?f3(i.weather,n.weather,h3((t-i.t)/(n.t-i.t),0,1)):i.weather:n?.weather}getActualWeatherAt(t){const e=this.getInterpolatedWeatherAt(t);if(!e)return;const i=(this.ramp??=new xo(this.keyframes)).at(t);if(!i)return e;const{type:n,intensity:s,character:r}=i,a=r>0?Math.min(1,s/r):n==="none"?0:1;return{...e,precipitationType:n,precipitationIntensity:r,precipitationAmount:a}}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new td;for(const i of t.keyframes)e.addKeyframe(i.t,{...Ep,...i.weather});return e}}class ed{keyframes=[];addKeyframe(t,e){const i=this.findInsertIndex(t);this.keyframes[i]?.t===t?this.keyframes[i]={t,sound:e}:this.keyframes.splice(i,0,{t,sound:e})}clear(){this.keyframes.length=0}removeKeyframeAt(t){const e=this.findInsertIndex(t);this.keyframes[e]?.t===t&&this.keyframes.splice(e,1)}getLatestSoundAt(t){let e=this.findInsertIndex(t);return this.keyframes[e]?.t!==t&&(e-=1),e>=0?this.keyframes[e].sound:void 0}getInterpolatedSoundAt(t){const e=this.findInsertIndex(t),i=this.keyframes[e]?.t===t?this.keyframes[e]:this.keyframes[e-1];if(i?.t===t)return i.sound;const n=this.keyframes[e]?.t===t?void 0:this.keyframes[e];if(!i)return n?.sound;if(!n)return i.sound;const s=(t-i.t)/(n.t-i.t);return this.lerp(i.sound,n.sound,Math.max(0,Math.min(1,s)))}get duration(){return this.keyframes.length===0?0:this.keyframes[this.keyframes.length-1].t}get allKeyframes(){return this.keyframes}toJSON(){return{keyframes:this.keyframes}}static fromJSON(t){const e=new ed;for(const i of t.keyframes)e.addKeyframe(i.t,i.sound);return e}lerp(t,e,i){return{kind:i<1?t.kind:e.kind,volume:t.volume+(e.volume-t.volume)*i,pitchHz:t.pitchHz+(e.pitchHz-t.pitchHz)*i,src:i<1?t.src:e.src}}findInsertIndex(t){let e=0,i=this.keyframes.length;for(;e<i;){const n=e+i>>>1;this.keyframes[n].t<t?e=n+1:i=n}return e}}const p3=100,m3={kind:"none",volume:0,pitchHz:p3};class sr{constructor(t){this.entries=t}static free(t){return t?.basis==="assumed"||t?.basis==="fitted"}static empty(){return new sr(new Map)}get size(){return this.entries.size}at(t){return this.entries.get(t)}paths(){return[...this.entries.keys()]}sourced(){return[...this.entries].filter(([,t])=>t.source!==void 0).map(([t,e])=>({path:t,basis:e.basis,source:e.source}))}interviewsCited(){const t=[];for(const{source:e}of this.sourced()){const i=e.said?.interview;i!==void 0&&!t.includes(i)&&t.push(i)}return t}pathsFromInterview(t){return this.sourced().filter(({source:e})=>e.said!==void 0&&e.said.interview===t).map(({path:e})=>e)}set(t,e){e.basis==="stated"&&e.rationale===void 0&&e.how===void 0&&e.range===void 0&&e.source===void 0?this.entries.delete(t):this.entries.set(t,e)}clear(t){for(const e of this.entries.keys())(e===t||e.startsWith(`${t}.`))&&this.entries.delete(e)}static strip(t){const e=new sr(new Map);return{recording:sr.stripValue(t,[],e),provenance:e}}static restore(t,e){if(e.size===0)return t;const i={...t},n=new Set([i]);for(const s of e.paths()){const r=e.at(s),a=s.split("."),c=sr.writableHolderOf(i,a,n);if(!c)continue;const l=a[a.length-1],h=c[l];h!==void 0&&(r.of!==void 0&&JSON.stringify(r.of)!==JSON.stringify(h)||(c[l]={value:h,...r.basis==="stated"?{}:{basis:r.basis},...r.rationale===void 0?{}:{rationale:r.rationale},...r.how===void 0?{}:{how:r.how},...r.range===void 0?{}:{range:r.range},...r.source===void 0?{}:{source:r.source}}))}return i}static isWrapper(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&"value"in t}static stripValue(t,e,i){return sr.isWrapper(t)?(i.set(e.join("."),{basis:t.basis??"stated",...t.rationale===void 0?{}:{rationale:t.rationale},...t.how===void 0?{}:{how:t.how},...t.range===void 0?{}:{range:t.range},...t.source===void 0?{}:{source:t.source},of:t.value}),sr.stripValue(t.value,e,i)):Array.isArray(t)?t.map((n,s)=>sr.stripValue(n,[...e,String(s)],i)):typeof t=="object"&&t!==null?Object.fromEntries(Object.entries(t).map(([n,s])=>[n,sr.stripValue(s,[...e,n],i)])):t}static writableHolderOf(t,e,i){let n=t;for(const s of e.slice(0,-1)){const r=n[s];if(typeof r!="object"||r===null)return;if(i.has(r)){n=r;continue}const a=Array.isArray(r)?[...r]:{...r};i.add(a),n[s]=a,n=a}return n}}class Ns extends Error{}class Ap{constructor(t){this.name=t}validate(t){return!0}}class eb extends Ap{min;max;constructor(t,e,i){super(t),this.min=e,this.max=i}validate(t){if(typeof t!="number")throw new Ns(`${this.name} value must be a number, but was ${t}`);if(t<this.min||t>this.max)throw new Ns(`${this.name} value must be >= ${this.min} and <= ${this.max}, but was ${t}`);return super.validate(t)}}class gi{name;min;max;duration;subUnit;validator;constructor(t,e,i,n,s=new eb(t,e,i)){this.name=t,this.min=e,this.max=i,this.subUnit=n,this.duration=n?(n.max-n.min+1)*n.duration:1,this.validator=s}validate(t){return this.validator.validate(t)}[Symbol.iterator](){let t=this.min;return{next:()=>{const e={done:t>this.max,value:t};return t++,e}}}}class Vv{millisecond;second;minute;hour;day;month;year}class g3 extends Vv{}class ib extends g3{millisecond=new gi("millisecond",0,999,void 0);second=new gi("second",0,59,this.millisecond);minute=new gi("minute",0,59,this.second);hour=new gi("hour",0,23,this.minute);day=new gi("day",1,31,this.hour);month=new gi("month",1,12,this.day);year=new gi("year",0,9999,this.month)}const oe=new ib;class nb extends eb{constructor(t=1,e=12){super("month",t,e)}}class Vl extends gi{static Month28=new Vl(28);static Month29=new Vl(29);static ThirtyDays=new Vl(30);static ThirtyOneDays=new Vl(31);constructor(t,e=new nb(1,t)){super("month",1,t,oe.day,e)}static create(t,e){switch(t){case 1:case 3:case 5:case 7:case 8:case 10:case 12:return this.ThirtyOneDays;case 2:return e%4===0?this.Month29:this.Month28;case 4:case 6:case 9:case 11:return this.ThirtyDays;default:throw new Ns("Unsupported month",t,e)}}}class ra{static instance=new ra;render(t){return t.value.toString()}}class ts{unit;#t;constructor(t,e){this.unit=e,this.value=typeof t=="number"?t:t.value}get value(){return this.#t}set value(t){this.unit.validate(t),this.#t=t}get duration(){return this.value*this.unit.duration}#e(t){if(this.constructor.name!==t.constructor.name)throw new Ap(`${this.unit.name} "${this.toString()}" cannot be compared with ${t.unit?.name} "${t.toString()}"`)}compare(t){return this.#e(t),this.value-t.value}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}previous(t=this.unit){const e=this.value-1;return new this.constructor(e,t)}next(t=this.unit){const e=this.value+1;return new this.constructor(e,t)}toString(t=ra.instance){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class Ot{static#t=new Map;static register(t,e){Ot.#t.set(t,e)}static get(t){const e=Ot.#t.get(t);if(!e)throw new Ns(`No default parser registered for ${t.name}: import "@rr0/time/defaults" or pass a parser to fromString()`);return e()}}class _h extends ts{constructor(t=new Date().getFullYear(),e=oe.year){super(t,e)}static fromString(t,e=Ot.get(_h)){return new _h(e.parse(t))}}class xa extends ra{static default=new xa("0",2);constructor(t,e){super(),this.char=t,this.size=e}render(t){return super.render(t).padStart(this.size,this.char)}}class Th extends ts{constructor(t=new Date().getMonth()+1,e=oe.month){super(t,e)}static fromString(t,e=Ot.get(Th)){return new Th(e.parse(t))}toString(t=xa.default){return super.toString(t)}}class Rh extends ts{constructor(t=new Date().getDate(),e=oe.day){super(t,e)}static fromString(t,e=Ot.get(Rh)){const i=e.parse(t);return new Rh(i)}toString(t=xa.default){return super.toString(t)}}class Ih extends ts{constructor(t=new Date().getHours(),e=oe.hour){super(t,e)}static fromString(t,e=Ot.get(Ih)){return new Ih(e.parse(t))}toString(t=xa.default){return super.toString(t)}}class Dh extends ts{constructor(t=new Date().getMinutes(),e=oe.minute){super(t,e)}static fromString(t,e=Ot.get(Dh)){return new Dh(e.parse(t))}toString(t=xa.default){return super.toString(t)}}class Ch extends ts{constructor(t=new Date().getSeconds(),e=oe.second){super(t,e)}static fromString(t,e=Ot.get(Ch)){return new Ch(e.parse(t),oe.second)}toString(t=xa.default){return super.toString(t)}}class Qo extends ts{static renderer=new xa("0",3);constructor(t,e=oe.millisecond){super(t,e)}static parseFraction(t){return parseInt(t.padEnd(3,"0").substring(0,3),10)}toString(t=Qo.renderer){return super.toString(t)}}class v3{render(t){return t.toString()}}class M3 extends v3{render(t){const e=t.value,i=Math.abs(e),n=Math.floor(i/60),s=i%60;if(n===0&&s===0)return"Z";{const r=e<0?"-":"+",a=n.toString().padStart(2,"0"),c=s>0?":"+s.toString().padEnd(2,"0"):"";return r+a+c}}}class Ko{value;name="timeshift";renderer;constructor(t=0){this.value=t}static fromString(t,e=Ot.get(Ko),i=void 0){const n=e.parse(t,i);return new Ko(n)}toString(t=new M3){return t.render(this)}toSpec(){return{value:this.value}}toJSON(){return this.toSpec()}}class qn{static timeshift(t,e){return t+(qn.isDaylight(e)?60:0)}static isDaylight(t){const{year:e,month:i,day:n}=t,s=t.hour??12;if(![e,i,n].every(Number.isInteger))throw new RangeError("Daylight saving time depends on the year, month and day");const r=qn.rule(e);if(!r)return!1;const a=qn.rank(i,n,s);return a>=qn.rank(r.start.month,r.start.day,2)&&a<qn.rank(r.end.month,r.end.day,2)}static rule(t){if(t<1967)return;const e={month:10,day:qn.sunday(t,10,-1)};return t>=2007?{start:{month:3,day:qn.sunday(t,3,2)},end:{month:11,day:qn.sunday(t,11,1)}}:t>=1987?{start:{month:4,day:qn.sunday(t,4,1)},end:e}:t===1975?{start:{month:2,day:23},end:e}:t===1974?{start:{month:1,day:6},end:e}:{start:{month:4,day:qn.sunday(t,4,-1)},end:e}}static sunday(t,e,i){const n=new Date(Date.UTC(2e3,e-1,1));n.setUTCFullYear(t);const s=1+(7-n.getUTCDay())%7;if(i>0)return s+7*(i-1);const r=[31,qn.isLeap(t)?29:28,31,30,31,30,31,31,30,31,30,31][e-1];let a=s;for(;a+7<=r;)a+=7;return a}static isLeap(t){return t%4===0&&(t%100!==0||t%400===0)}static rank(t,e,i){return(t*100+e)*100+i}}const y3={name:"PST",timeshift:"-08",title:"Pacific Standard Time (US)"},x3={name:"PDT",timeshift:"-07",title:"Pacific Daylight Time (US)"},w3={name:"MDT",timeshift:"-06",title:"Mountain Standard Time (US)"},S3={name:"MST",timeshift:"-07",title:"Mountain Daylight Time (US)"},b3={name:"PT",timeshift:o=>qn.timeshift(-480,o),title:"Pacific Time (US)"},E3={name:"MT",timeshift:o=>qn.timeshift(-420,o),title:"Mountain Time (US)"},A3={name:"CT",timeshift:o=>qn.timeshift(-360,o),title:"Central Time (US)"},_3={name:"ET",timeshift:o=>qn.timeshift(-300,o),title:"Eastern Time (US)"},T3={name:"CWT",timeshift:"-05",title:"Central War Time (US)"},R3={name:"CDT",timeshift:"-05",title:"Central Daylight Time"},I3={name:"EST",timeshift:"-05",title:"Eastern Standard Time (US)"},D3={name:"EDT",timeshift:"-04",title:"Eastern Time (US)"},C3={name:"AST",timeshift:"-04",title:"Atlantic Standard Time (US)"},P3={name:"ADT",timeshift:"-03",title:"Atlantic Daylight Time (US)"},O3={name:"UTC",timeshift:"Z",title:"Coordinated Universal Time"},N3={name:"Z",timeshift:"Z",title:"UTC"},L3={name:"GMT",timeshift:"Z",title:"Greenwich Mean Time"},k3={name:"BST",timeshift:"+01",title:"British Summer Time"},F3={name:"CEST",timeshift:"+02",title:"Central European Summer Time"},U3={name:"CET",timeshift:"+01",title:"Central European Time"},z3={name:"MSK",timeshift:"+03",title:"Moscow Time (RU)"},B3={name:"IST",timeshift:"+05:30",title:"Indian Standard Time"},H3={name:"BJT",timeshift:"+08",title:"Beijing Time"},G3={name:"CST",timeshift:"-06",title:"Central Standard Time"},V3={name:"JST",timeshift:"+09",title:"Japan Standard Time"},W3={name:"AEST",timeshift:"+10",title:"Australian Eastern Standard Time"},X3={name:"NZST",timeshift:"+12",title:"New Zealand Standard Time"},Y3={name:"LST",timeshift:"?",title:"Local Sideral Time"},my=[P3,W3,C3,H3,k3,G3,R3,U3,F3,A3,T3,D3,I3,_3,L3,B3,V3,Y3,w3,z3,S3,E3,X3,x3,y3,b3,O3,N3];class _p{static instance=new _p;renderComponent(t,e){return t[e].toString()}renderSecond(t){return this.renderComponent(t,"second")+(t.millisecond?"."+t.millisecond.toString():"")}render(t){const e=[];t.year&&e.push(this.renderComponent(t,"year")),t.month&&e.push(this.renderComponent(t,"month")),t.day&&e.push(this.renderComponent(t,"day"));const i=[];t.hour&&i.push(this.renderComponent(t,"hour")),t.minute&&i.push(this.renderComponent(t,"minute")),t.second&&i.push(this.renderSecond(t));const n=e.join("-"),s=t.timeshift?t.timeshift.toString():"",r=i.join(":")+s;return n+(r.length>0?"T"+r:"")}}class mc extends Ns{constructor(t="method is abstract"){super(t)}}class Wv{units;constructor(t){this.units=t}newYear(t){throw new mc}newMonth(t){throw new mc}newDay(t){throw new mc}newHour(t){throw new mc}newMinute(t){throw new mc}newSecond(t){throw new mc}}class $3 extends Vv{millisecond=new gi("milliseconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,void 0);second=new gi("seconds",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minutes",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hours",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.minutes);day=new gi("days",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("months",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.day);year=new gi("years",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const zd=new $3;class Tp{static instance=new Tp;render(t){const e=Ar.toSpec(t);let i="P";const n=e.years;n&&(i+=n.toString()+"Y");const s=e.months;s&&(i+=s.toString(ra.instance)+"MM");const r=e.days;r&&(i+=r.toString(ra.instance)+"D");const a=e.hours;a&&(i+=a.toString(ra.instance)+"H");const c=e.minutes;c&&(i+=c.toString(ra.instance)+"M");const l=e.seconds;return l&&(i+=l.toString(ra.instance)+"S"),i}}class Ar extends ts{constructor(t={years:new Date().getFullYear(),months:new Date().getMonth(),days:new Date().getDate(),hours:new Date().getHours(),minutes:new Date().getMinutes(),seconds:new Date().getSeconds(),milliseconds:new Date().getMilliseconds()}){super({value:typeof t=="number"?t:+(t.years?t.years*oe.year.duration:0)+(t.months?t.months*oe.month.duration:0)+(t.days?t.days*oe.day.duration:0)+(t.hours?t.hours*oe.hour.duration:0)+(t.minutes?t.minutes*oe.minute.duration:0)+(t.seconds?t.seconds*oe.second.duration:0)},new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0))}static toSpec(t,e=q3){let i=typeof t=="number"?t:t.value;const n=i>0?1:-1;i=Math.abs(i);const s={},r=i/oe.year.duration,a=Math.floor(r);a>0&&(s.years=e.newYear(n*a),i-=a*oe.year.duration);const c=i/oe.month.duration,l=Math.floor(c);l>0&&(s.months=e.newMonth(n*l),i-=l*oe.month.duration);const h=i/oe.day.duration,u=Math.floor(h);u>0&&(s.days=e.newDay(n*u),i-=u*oe.day.duration);const d=i/oe.hour.duration,f=Math.floor(d);f>0&&(s.hours=e.newHour(n*f),i-=f*oe.hour.duration);const p=i/oe.minute.duration,m=Math.floor(p);m>0&&(s.minutes=e.newMinute(n*m),i-=m*oe.minute.duration);const g=i/oe.second.duration,v=Math.floor(n*g);return v>0&&(s.seconds=e.newSecond(v)),s}static fromString(t,e=Ot.get(Ar)){return new Ar(e.parse(t))}static between(t,e){const i=e.getTime(),n=t.getTime();return new Ar(i-n)}toSpec(){return Ar.toSpec(this)}toString(t=Tp.instance){return t.render(this)}}class sb extends Wv{constructor(t){super(t)}newYear(t){return new _h(t,this.units.year)}newMonth(t){return new Th(t,this.units.month)}newDay(t){return new Rh(t,this.units.day)}newHour(t){return new Ih(t,this.units.hour)}newMinute(t){return new Dh(t,this.units.minute)}newSecond(t){return new Ch(t,this.units.second)}newMillisecond(t){return new Qo(t,this.units.millisecond)}newTimeshift(t){return new Ko(typeof t=="number"?t:t.value)}}const K3=new sb(oe),q3=new sb(zd);class Cn{#t;#e;#i;#n;#s;#r;#a;#o;constructor(t={year:new Date().getFullYear(),month:new Date().getMonth()+1,day:new Date().getDate(),hour:new Date().getHours(),minute:new Date().getMinutes(),second:new Date().getSeconds(),timeshift:Cn.timeshiftOf(new Date)}){this.year=t.year,this.month=t.month,this.day=t.day,this.hour=t.hour,this.minute=t.minute,this.second=t.second,this.millisecond=t.millisecond,this.timeshift=t.timeshift}get year(){return this.#t}set year(t){const e=typeof t=="number";this.#t&&e?this.#t.value=t:this.#t=e?this.factory.newYear(t):!t||t.start||t instanceof ts?t:this.factory.newYear(t)}get month(){return this.#e}set month(t){const e=typeof t=="number";this.#e&&e?this.#e.value=t:this.#e=e?this.factory.newMonth(t):!t||t.start||t instanceof ts?t:this.factory.newMonth(t)}get day(){return this.#i}set day(t){const e=typeof t=="number";this.#i&&e?this.#i.value=t:this.#i=e?this.factory.newDay(t):!t||t.start||t instanceof ts?t:this.factory.newDay(t)}get hour(){return this.#n}set hour(t){const e=typeof t=="number";this.#n&&e?this.#n.value=t:this.#n=e?this.factory.newHour(t):!t||t.start||t instanceof ts?t:this.factory.newHour(t)}get minute(){return this.#s}set minute(t){const e=typeof t=="number";this.#s&&e?this.#s.value=t:this.#s=e?this.factory.newMinute(t):!t||t.start||t instanceof ts?t:this.factory.newMinute(t)}get second(){return this.#r}set second(t){const e=typeof t=="number";this.#r&&e?this.#r.value=t:this.#r=e?this.factory.newSecond(t):!t||t.start||t instanceof ts?t:this.factory.newSecond(t)}get millisecond(){return this.#a}set millisecond(t){const e=typeof t=="number";this.#a&&e?this.#a.value=t:this.#a=e||t&&!(t instanceof ts)?this.factory.newMillisecond(t):t}get timeshift(){return this.#o}set timeshift(t){const e=typeof t=="number";this.#o&&e?this.#o.value=t:this.#o=e||t&&!(t instanceof Ko)?this.factory.newTimeshift(t):t}get factory(){return K3}static fromString(t,e=Ot.get(Cn)){const{year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h}=e.parse(t);return new Cn({year:i,month:n,day:s,hour:r,minute:a,second:c,millisecond:l,timeshift:h})}static timeshiftOf(t){return-t.getTimezoneOffset()||0}static fromDate(t){return new Cn({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Cn.fromString(i)}#c(t){if(this.constructor.name!==t.constructor.name)throw new Ap(`Date "${this.toString()}" cannot be compared with "${t.toString()}"`)}compare(t){return this.#c(t),this.getTime()-t.getTime()}delta(t){const e=this.compare(t);return new Ar(e)}getTime(){return(this.year?.duration||0)+(this.month?.duration||0)+(this.day?.duration||0)+(this.hour?.duration||0)+(this.minute?.duration||0)+(this.second?.duration||0)+(this.millisecond?.duration||0)}isEqual(t){return this.compare(t)===0}isBefore(t){return this.compare(t)<0}isAfter(t){return this.compare(t)>0}clone(){return new Cn(this.toSpec())}previous(){let t=this.clone();try{t.second=this.second.previous()}catch{try{t.minute=this.minute.previous()}catch{try{t.hour=this.hour.previous()}catch{try{t.day=this.day.previous()}catch{try{t.month=this.month.previous()}catch{t.year=this.year.previous()}}}}}return t}next(){let t=this.clone();try{t.second=this.second.next()}catch{try{t.minute=this.minute.next()}catch{try{t.hour=this.hour.next()}catch{try{t.day=this.day.next()}catch{try{t.month=this.month.next()}catch{t.year=this.year.next()}}}}}return t}toString(t=_p.instance){return t.render(this)}toSpec(){const t={},e=this.year?.toSpec();e&&(t.year=e);const i=this.month?.toSpec();i&&(t.month=i);const n=this.day?.toSpec();n&&(t.day=n);const s=this.hour?.toSpec();s&&(t.hour=s);const r=this.minute?.toSpec();r&&(t.minute=r);const a=this.second?.toSpec();a&&(t.second=a);const c=this.millisecond?.toSpec();c&&(t.millisecond=c);const l=this.timeshift?.toSpec();return l&&(t.timeshift=l),t}toJSON(){return this.toSpec()}}class Xv{static instance=new Xv;render(t){return(t.start?t.start.toString():"")+"/"+(t.end?t.end.toString():"")}}class id{constructor(t,e){this.start=t,this.end=e}_start;get start(){return this._start}set start(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof Ar))throw new Ns("Interval start is not a level 0 date or duration: "+t);this._start=t}_end;get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Cn.fromString(t)),t&&!(t instanceof Cn)&&!(t instanceof Ar))throw new Ns("Interval end is not a level 0 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(id)){const{start:i,end:n}=e.parse(t);return new id(i,n)}toString(t=Xv.instance){return t.render(this)}[Symbol.iterator](){let t=this.start;return{next:()=>{const e={done:t>this.end,value:t};return t++,e}}}}class Bd extends ra{static instance=new Bd(xa.default);constructor(t){super(),this.valueRenderer=t}render(t){return(this.valueRenderer?this.valueRenderer.render(t):super.render(t))+this.qualifier(t)}qualifier(t){return t.uncertain?t.approximate?"%":"?":t.approximate?"~":""}}class ga extends ts{#t;#e;constructor(t,e){super(t,e),this.#t=t.uncertain||!1,this.#e=t.approximate||!1}get uncertain(){return this.#t}set uncertain(t){return this.#t=t}get approximate(){return this.#e}set approximate(t){return this.#e=t}isCertainAndPrecise(){return!this.approximate&&!this.uncertain}isEqual(t){return this.isCertainAndPrecise()&&super.isEqual(t)}isBefore(t){return this.isCertainAndPrecise()&&super.isBefore(t)}isAfter(t){return this.isCertainAndPrecise()&&super.isAfter(t)}toString(t=Bd.instance){return super.toString(t)}toSpec(){return{...super.toSpec(),uncertain:this.uncertain,approximate:this.approximate}}toJSON(){return this.toSpec()}}class rb extends ib{year=new gi("year",-9999,9999,this.month);yearExtended=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const M0=new rb;class No extends ga{constructor(t,e=M0.year){super(t,e)}static fromString(t,e=M0.year,i=Ot.get(No)){const n=i.parse(t),s=n.value.start;if(t.startsWith("Y")&&(e=M0.yearExtended),s!==void 0){const r=new No(Object.assign({...n},{value:Math.max(s,e.min)})),a=new No(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new No(n,e)}}class ab extends Ap{monthValidator=new nb;validate(t){switch(t){case 21:case 22:case 23:case 24:return!0;default:return this.monthValidator.validate(t)}}}class Lo extends ga{constructor(t,e=new gi(oe.month.name,1,24,oe.day,new ab)){super(t,e)}static fromString(t,e=Ot.get(Lo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.month;const r=new Lo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Lo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Lo(i)}toString(t){return super.toString(t).padStart(2,"0")}}class ko extends ga{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ot.get(ko)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.day;const r=new ko(Object.assign({...i},{value:Math.max(n,s.min)})),a=new ko(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new ko(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Fo extends ga{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ot.get(Fo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){let s=oe.hour;const r=new Fo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Fo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Fo(i)}}class Uo extends ga{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ot.get(Uo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new Uo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Uo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Uo(i)}toString(t=Bd.instance){return super.toString(t)}}class zo extends ga{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=Ot.get(zo)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.second,r=new zo(Object.assign({...i},{value:Math.max(n,s.min)})),a=new zo(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new zo(i)}}class zc extends Ko{static fromString(t,e=Ot.get(zc),i=void 0){return new zc(e.parse(t,i))}}class ob extends Wv{constructor(t){super(t)}newYear(t){return new No(t,this.units.year)}newMonth(t){return new Lo(t,this.units.month)}newDay(t){return new ko(t,this.units.day)}newHour(t){return new Fo(t,this.units.hour)}newMinute(t){return new Uo(t,this.units.minute)}newSecond(t){return new zo(t,this.units.second)}newMillisecond(t){return new Qo(t,this.units.millisecond)}newTimeshift(t){return new zc(typeof t=="number"?t:t.value)}}const Z3=new ob(M0),J3=new ob(zd);class Ds extends Cn{constructor(t){super(t)}get factory(){return Z3}get uncertain(){return this.year?.uncertain===!0||this.month?.uncertain===!0||this.day?.uncertain===!0||this.hour?.uncertain===!0||this.minute?.uncertain===!0||this.second?.uncertain===!0}get approximate(){return this.year?.approximate===!0||this.month?.approximate===!0||this.day?.approximate===!0||this.hour?.approximate===!0||this.minute?.approximate===!0||this.second?.approximate===!0}static fromDate(t){return new Ds({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ot.get(Ds)){const i=e.parse(t);return new Ds(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return Ds.fromString(i)}clone(){return new Ds(this.toSpec())}}const gn=Object.freeze({year:"year",month:"month",day:"day",hour:"hour",minute:"minute",second:"second",timeshift:"timeshift",uncertain:"uncertain",approximate:"approx"});class Rp extends Tp{static instance=new Rp;render(t){return super.render(t)}}class dn extends ga{constructor(t){super(typeof t=="number"||t.hasOwnProperty("value")?t:{value:dn.getValue(t,gn.year)+dn.getValue(t,gn.month)+dn.getValue(t,gn.day)+dn.getValue(t,gn.hour)+dn.getValue(t,gn.minute)+dn.getValue(t,gn.second),uncertain:dn.getBoolean(t,gn.uncertain),approximate:dn.getBoolean(t,"approximate")},zd.millisecond)}static getBoolean(t,e){return t[e]||t[gn.year+"s"]?.[e]||t[gn.month+"s"]?.[e]||t[gn.day+"s"]?.[e]||t[gn.hour+"s"]?.[e]||t[gn.minute+"s"]?.[e]||t[gn.second+"s"]?.[e]||!1}static getValue(t,e){let i=0,n=t[e+"s"];if(n instanceof ga?n=n.value:typeof t=="number"&&(n=t),n){const s=oe[e];i=n*s.duration}return i}static toSpec(t,e=J3){return{...Ar.toSpec(t,e),uncertain:t.uncertain||!1,approximate:t.approximate||!1}}static fromString(t,e=Ot.get(dn)){const i=e.parse(t);return new dn(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new dn(i-n)}toString(t=Rp.instance){return super.toString(t)}toSpec(){return dn.toSpec(this)}}class nd extends id{constructor(t,e){super(t,e)}get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=Ds.fromString(t)),t&&!(t instanceof Ds)&&!(t instanceof dn))throw new Ns("Interval start is not a level 1 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=Ds.fromString(t)),t&&!(t instanceof Ds)&&!(t instanceof dn))throw new Ns("Interval end is not a level 1 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(nd)){const{start:i,end:n}=e.parse(t);return new nd(i,n)}}class Bh extends ga{uncertainComponent;approximateComponent;constructor(t,e){super(t,e),this.uncertainComponent=t.uncertainComponent||!1,this.approximateComponent=t.approximateComponent||!1}get uncertain(){return super.uncertain||this.uncertainComponent}set uncertain(t){return super.uncertain=t}get approximate(){return super.approximate||this.approximateComponent}set approximate(t){return super.approximate=t}get uncertainGroup(){return super.uncertain}get approximateGroup(){return super.approximate}toSpec(){return{...super.toSpec(),uncertain:this.uncertainGroup,approximate:this.approximateGroup,uncertainComponent:this.uncertainComponent,approximateComponent:this.approximateComponent}}toJSON(){return this.toSpec()}}class j3 extends rb{year=new gi("year",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,this.month)}const Zg=new j3;class Ba extends Bh{constructor(t,e=Zg.year){super(t,e)}static fromString(t,e=Zg.year,i=Ot.get(Ba)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Ba(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Ba(Object.assign({...n},{value:Math.min(n.value.end,e.max)})),c={start:r,end:a},l=n.value.estimate;return l&&(c.estimate=l),c}else return new Ba(n)}}class Q3 extends ab{validate(t){switch(t){case 25:case 26:case 27:case 28:case 29:case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 37:case 38:case 39:case 40:case 41:return!0;default:return super.validate(t)}}}class Ha extends Bh{constructor(t,e=new gi(oe.month.name,1,41,oe.day,new Q3)){super(t,e)}static fromString(t,e=Ot.get(Ha)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.month,r=new Ha(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ha(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ha(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Ga extends Bh{constructor(t,e=oe.day){super(t,e)}static fromString(t,e=Ot.get(Ga)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.day,r=new Ga(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Ga(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Ga(i)}toString(t){return super.toString(t).padStart(2,"0")}}class Va extends Bh{constructor(t,e=oe.hour){super(t,e)}static fromString(t,e=Ot.get(Va)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.hour,r=new Va(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Va(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Va(i)}}class Wa extends Bh{constructor(t,e=oe.minute){super(t,e)}static fromString(t,e=Ot.get(Wa)){const i=e.parse(t),n=i.value.start;if(n!==void 0){const s=oe.minute,r=new Wa(Object.assign({...i},{value:Math.max(n,s.min)})),a=new Wa(Object.assign({...i},{value:Math.min(i.value.end,s.max)}));return{start:r,end:a}}else return new Wa(i)}}class Xa extends Bh{constructor(t,e=oe.second){super(t,e)}static fromString(t,e=oe.second,i=Ot.get(Xa)){const n=i.parse(t),s=n.value.start;if(s!==void 0){const r=new Xa(Object.assign({...n},{value:Math.max(s,e.min)})),a=new Xa(Object.assign({...n},{value:Math.min(n.value.end,e.max)}));return{start:r,end:a}}else return new Xa(n,e)}}class cb extends zc{}class t_ extends Bd{qualifier(){return""}}class wo extends _p{static instance=new wo;static valueRenderer=new t_(xa.default);static names=["year","month","day","hour","minute","second"];static qualifier(t,e){return t?e?"%":"?":e?"~":""}renderComponent(t,e){const i=t[e],n=wo.names.slice(wo.names.indexOf(e)+1).map(a=>t[a]).filter(Boolean),s=wo.qualifier(i.uncertainComponent,i.approximateComponent),r=wo.qualifier(i.uncertainGroup&&!i.uncertainComponent&&!n.some(a=>a.uncertain),i.approximateGroup&&!i.approximateComponent&&!n.some(a=>a.approximate));return s+i.toString(wo.valueRenderer)+r}}class lb extends Wv{constructor(t){super(t)}newYear(t){return new Ba(t,this.units.year)}newMonth(t){return new Ha(t,this.units.month)}newDay(t){return new Ga(t,this.units.day)}newHour(t){return new Va(t,this.units.hour)}newMinute(t){return new Wa(t,this.units.minute)}newSecond(t){return new Xa(t,this.units.second)}newMillisecond(t){return new Qo(t,this.units.millisecond)}newTimeshift(t){return new cb(typeof t=="number"?t:t.value)}}const e_=new lb(Zg),i_=new lb(zd);class ms extends Ds{constructor(t){super(t)}toString(t=wo.instance){return super.toString(t)}get year(){return super.year}set year(t){super.year=t}get month(){return super.month}set month(t){super.month=t}get factory(){return e_}static fromDate(t){return new ms({year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),minute:t.getMinutes(),second:t.getSeconds(),timeshift:Cn.timeshiftOf(t)})}static fromString(t,e=Ot.get(ms)){const i=e.parse(t);return new ms(i)}static newInstance(){const t=new Date().toISOString(),e=t.indexOf("."),i=t.substring(0,e)+t.substring(e+4);return ms.fromString(i)}clone(){return new ms(this.toSpec())}}class eo{regExp;constructor(t,e){this.name=t,this.regExp=new RegExp(`^(?:${e})$`)}regexGroups(t){const e=this.regExp.exec(t);if(!e)throw new Ns(`Invalid ${this.name} "${t}"`);return e.groups}parseGroups(t){throw new mc(`${this.constructor.name} is abstract`)}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}class Wl extends Rp{static instance=new Wl;static designators=[["years","Y"],["months","MM"],["days","D"],["hours","H"],["minutes","M"],["seconds","S"]];static qualifier(t,e){return t?e?"%":"?":e?"~":""}render(t){const e=Wl.qualifier(t.uncertainDuration,t.approximateDuration);if(!t.hasQualifiedComponent)return e+super.render(t);let i=e+"P";for(const[n,s]of Wl.designators){const r=t.components[n];r&&(i+=Wl.qualifier(r.uncertainComponent,r.approximateComponent)+r.value+s)}return i}}class un extends dn{#t;constructor(t){if(super(typeof t=="number"?t:{value:un.valueFromSpec(t),uncertain:t.uncertain===!0,approximate:t.approximate===!0},zd.millisecond),typeof t!="number"){const e={};for(const i of un.componentNames)t[i]instanceof ga&&(e[i]=t[i]);Object.keys(e).length>0&&(this.#t=e)}}static componentNames=["years","months","days","hours","minutes","seconds"];get components(){return this.#t}#e(t){return this.#t?Object.values(this.#t).some(e=>e[t]):!1}get uncertainDuration(){return super.uncertain}get approximateDuration(){return super.approximate}get uncertain(){return super.uncertain||this.#e("uncertain")}set uncertain(t){super.uncertain=t}get approximate(){return super.approximate||this.#e("approximate")}set approximate(t){super.approximate=t}get hasQualifiedComponent(){return this.#t?Object.values(this.#t).some(t=>t.uncertainComponent||t.approximateComponent):!1}static valueFromSpec(t){return un.getValue(t,gn.year)+un.getValue(t,gn.month)+un.getValue(t,gn.day)+un.getValue(t,gn.hour)+un.getValue(t,gn.minute)+un.getValue(t,gn.second)}static toSpec(t,e=i_){const i=dn.toSpec(t,e);if(t instanceof un&&t.hasQualifiedComponent)for(const n of un.componentNames)delete i[n],t.components[n]&&(i[n]=t.components[n]);return i}static fromString(t,e=Ot.get(un)){const i=e.parse(t);return new un(i)}static between(t,e){const i=e.getTime(),n=t.getTime();return new un(i-n)}toSpec(){return un.toSpec(this)}toString(t=Wl.instance){return super.toString(t)}}class sd extends nd{get start(){return this._start}set start(t){if(typeof t=="string"&&(super.start=ms.fromString(t)),t&&!(t instanceof ms)&&!(t instanceof un))throw new Ns("Interval start is not a level 2 date or duration: "+t);this._start=t}get end(){return this._end}set end(t){if(typeof t=="string"&&(t=ms.fromString(t)),t&&!(t instanceof ms)&&!(t instanceof un))throw new Ns("Interval end is not a level 2 date or duration: "+t);this._end=t}static fromString(t,e=Ot.get(sd)){const{start:i,end:n}=e.parse(t);return new sd(i,n)}}class H0 extends Set{constructor(t,e){super(t),this.exclusive=e}has(t){const e=t.toString().replace("..","/");for(const i of this)if(i.toString()===e)return!0;return!1}static fromString(t,e=Ot.get(H0)){const{exclusive:i,values:n}=e.parse(t);return new H0(n,i)}}class io extends eo{constructor(t,e){super(t,e)}static read(t){return{value:t?parseInt(t,10):void 0}}parseGroups(t){return io.read(t[this.name])}parse(t){if(t.startsWith("-"))throw new Ns(`${this.name} cannot be negative`);return super.parse(t)}}class F{static groupName(...t){return t.reduce((e,i)=>e?e+i.charAt(0).toUpperCase()+i.substring(1):i,"")}static group(t,...e){return`(?<${t}>${e.join("")})`}static optional(t){return t+"?"}static nonCapturingGroup(...t){return`(?:${t.join("")})`}static optionalGroup(t,...e){return F.optional(F.group(t,...e))}static optionalNonCapturingGroup(...t){return F.optional(F.nonCapturingGroup(...t))}static numberGroup(t,e,i,n="\\d"){return F.group(t,`${i||""}[${n}]${e}`)}}const gy="yearValue";class rd extends io{static format(t=""){return F.numberGroup(F.groupName(t,gy),"{4}",void 0)}constructor(){super(gy,rd.format())}}const vy="monthValue";class ad extends io{static format(t=""){return F.numberGroup(F.groupName(t,vy),"{1,2}",void 0)}constructor(){super(vy,ad.format())}}const My="dayValue";class uh extends io{static format(t=""){return F.numberGroup(F.groupName(t,My),"{1,2}",void 0)}constructor(){super(My,uh.format())}}const yy="hourValue";class dh extends io{static format(t=""){return F.numberGroup(F.groupName(t,yy),"{1,2}",void 0)}constructor(){super(yy,dh.format())}}const xy="minuteValue";class od extends io{static format(t=""){return F.numberGroup(F.groupName(t,xy),"{1,2}",void 0)}constructor(){super(xy,od.format())}}const wy="secondValue";class cd extends io{static format(t=""){return F.numberGroup(F.groupName(t,wy),"{1,2}",void 0)}constructor(){super(wy,cd.format())}}const Sy="timeshiftValue",by="shiftHour",Ey="shiftMinute";class Ph extends eo{static format(t=""){return my.map(e=>e.name).join("|")+"|"+F.nonCapturingGroup(F.group(t+by,F.numberGroup(F.groupName(t,Sy),"{2}","[+-]")),F.optionalNonCapturingGroup(":?",F.numberGroup(F.groupName(t,Ey),"{2}",void 0)))}constructor(){super(Sy,Ph.format())}parse(t,e){let i=0;const n=my.find(s=>s.name===t);if(n){if(typeof n.timeshift=="function")try{return n.timeshift(e??{})}catch(s){throw new Ns(`The time zone ${t} depends on the date: ${s.message}`)}t=n.timeshift}if(t!=="Z"){const s=this.regexGroups(t),r=s[by];r&&(i+=parseInt(r,10)*60);const a=s[Ey];a&&(i+=parseInt(a,10))}return i}}const Ay="year",_y="month",Ty="day",Ry="hour",Iy="minute",Dy="second",Cy="millisecond",Py="timeshift";class bc extends eo{static format(t=""){return F.group(F.groupName(t,Ay),rd.format(t))+F.optionalNonCapturingGroup("-",F.group(F.groupName(t,_y),ad.format(t)),F.optionalNonCapturingGroup("-",F.group(F.groupName(t,Ty),uh.format(t)),F.optionalNonCapturingGroup("[T ]",F.group(F.groupName(t,Ry),dh.format(t)),":?",F.group(F.groupName(t,Iy),od.format(t)),F.optionalNonCapturingGroup(":",F.group(F.groupName(t,Dy),cd.format(t)),F.optionalNonCapturingGroup("[.,]",F.group(F.groupName(t,Cy),"\\d+"))),"\\s*",F.optionalGroup(F.groupName(t,Py),Ph.format(t)))))}constructor(){super("date",bc.format())}parse(t){const e=this.regexGroups(t),i=e[Ay],n=e[_y],s=e[Ty],r=e[Ry],a=e[Iy],c=e[Dy],l=e[Cy],h=e[Py],u=i?new _h(rd.read(i)):void 0,d=n?ad.read(n):void 0;return{year:u,month:d?new Th(d,Vl.create(d.value,u?.value)):void 0,day:s?new Rh(uh.read(s)):void 0,hour:r?new Ih(dh.read(r)):void 0,minute:a?new Dh(od.read(a)):void 0,second:c?new Ch(cd.read(c)):void 0,millisecond:l?Qo.parseFraction(l):void 0,timeshift:h?Ko.fromString(h,new Ph,{year:u?.value,month:d?.value,day:s?uh.read(s).value:void 0,hour:r?dh.read(r).value:void 0}):void 0}}}const Oy="years",jp="months",n_="days",Ny="hours",Ly="minutes",ky="seconds";class Yv extends eo{static format(t=""){return"P"+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Oy),"+",void 0,"\\d"),"Y")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,jp),"+",void 0,"\\d"),"MM")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,n_),"+",void 0,"\\d"),"D")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Ny),"+",void 0,"\\d"),"H")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Ly),"+",void 0,"\\d"),"M")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,ky),"+",void 0,"\\d"),"S")}constructor(){super("duration",Yv.format())}parseGroups(t){return{years:t[Oy],months:t[jp],days:t[jp],hours:t[Ny],minutes:t[Ly],seconds:t[ky]}}}const Qp="start",tm="end";class $v extends eo{static format=F.group(Qp,bc.format(Qp))+"/"+F.group(tm,bc.format(tm));constructor(){super("interval",$v.format)}parse(t){const e=this.regexGroups(t),i=e[Qp],n=e[tm];return{start:i?Cn.fromString(i,new bc):void 0,end:n?Cn.fromString(n,new bc):void 0}}}class _i extends io{static uncertainGroup="uncertain";static approximateGroup="approx";static uncertainAndApproximateGroup=_i.uncertainGroup+_i.approximateGroup;constructor(t,e){super(t,e)}static qualifierFormat(t,e){return F.optionalGroup(t,`\\${e}`)}static formatSuffix(t){return this.qualifierFormat(F.groupName(_i.uncertainGroup,t),"?")+this.qualifierFormat(F.groupName(_i.approximateGroup,t),"~")+this.qualifierFormat(F.groupName(_i.uncertainAndApproximateGroup,t),"%")}static numberFormat(t,e,i){return F.numberGroup(t,e,i,"\\dX")+this.formatSuffix(t)}getValueAndSign(t){let e=t[this.name],i;return e.charAt(0)==="-"?(i=-1,e=e.substring(1)):i=1,{valueStr:e,sign:i}}parseGroups(t){const{valueStr:e,sign:i}=this.getValueAndSign(t);let n=0,s;for(s=0;s<e.length;s++){const l=e[s];if(l==="X")break;n=n*10+parseInt(l,10)}if(s<e.length){let l=1;for(let d=0;d<e.length-s;d++)l*=10;const h=i*n*l,u=h+l-1;n={start:h,end:u}}else n*=i;const r=t[F.groupName(_i.uncertainAndApproximateGroup,this.name)],a=t[F.groupName(_i.approximateGroup,this.name)]||r,c=t[F.groupName(_i.uncertainGroup,this.name)]||r;return{value:n,approximate:a?!!a:!1,uncertain:c?!!c:!1}}}const Fy="yearValue";class ld extends _i{constructor(){super(Fy,ld.format())}static format(t=""){return"Y?"+_i.numberFormat(F.groupName(t,Fy),"+","[-]?")}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const Uy="monthValue";class hd extends _i{static format(t=""){return _i.numberFormat(F.groupName(t,Uy),"{1,2}",void 0)}constructor(){super(Uy,hd.format())}}const zy="dayValue";class ud extends _i{static format(t=""){return _i.numberFormat(F.groupName(t,zy),"{1,2}",void 0)}constructor(){super(zy,ud.format())}}const By="hourValue";class dd extends _i{static format(t=""){return _i.numberFormat(F.groupName(t,By),"{1,2}",void 0)}constructor(){super(By,dd.format())}}const Hy="minuteValue";class fd extends _i{static format(t=""){return _i.numberFormat(F.groupName(t,Hy),"{1,2}",void 0)}constructor(){super(Hy,fd.format())}}const Gy="secondValue";class pd extends _i{static format(t=""){return _i.numberFormat(F.groupName(t,Gy),"{1,2}",void 0)}constructor(){super(Gy,pd.format())}}class md extends Ph{}class Fi extends eo{static yearGroup="year";static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(t=Fi.format()){super("date",t)}static format(t=""){return F.group(F.groupName(t,Fi.yearGroup),ld.format(t))+F.optionalNonCapturingGroup("-",F.group(F.groupName(t,Fi.monthGroup),hd.format(t)),F.optionalNonCapturingGroup("-",F.group(F.groupName(t,Fi.dayGroup),ud.format(t)),F.optionalNonCapturingGroup("[T ]",F.group(F.groupName(t,Fi.hourGroup),dd.format(t)),":",F.group(F.groupName(t,Fi.minuteGroup),fd.format(t)),F.optionalNonCapturingGroup(":",F.group(F.groupName(t,Fi.secondGroup),pd.format(t)),F.optionalNonCapturingGroup("[.,]",F.group(F.groupName(t,Fi.millisecondGroup),"\\d+"))),F.optionalGroup(F.groupName(t,Fi.timeshiftGroup),md.format(t)))))}parseGroups(t){const e=t[Fi.millisecondGroup],i=e?Qo.parseFraction(e):void 0,n=t[Fi.secondGroup],s=n?zo.fromString(n,new pd):void 0,r=t[Fi.minuteGroup];let a;r&&(a=Uo.fromString(r,new fd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[Fi.hourGroup];let l;c&&(l=Fo.fromString(c,new dd),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[Fi.dayGroup];let u;h&&(u=ko.fromString(h,new ud),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[Fi.monthGroup];let f;d&&(f=Lo.fromString(d,new hd),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[Fi.yearGroup];let m;p&&(m=No.fromString(p,void 0,new ld),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[Fi.timeshiftGroup],v=g?zc.fromString(g,new md,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:v}}}const Vy="years",Wy="months",Xy="days",Yy="hours",$y="minutes",Ky="seconds";class Ec extends _i{static format(t=""){return"P"+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Vy),"+",void 0,"\\d"),"Y")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Wy),"+",void 0,"\\d"),"MM")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Xy),"+",void 0,"\\d"),"D")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Yy),"+",void 0,"\\d"),"H")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,$y),"+",void 0,"\\d"),"M")+F.optionalNonCapturingGroup(F.numberGroup(F.groupName(t,Ky),"+",void 0,"\\d"),"S")+this.formatSuffix(t)}constructor(){super("duration",Ec.format())}parseGroups(t){return{years:t[Vy],months:t[Wy],days:t[Xy],hours:t[Yy],minutes:t[$y],seconds:t[Ky],uncertain:!!t[_i.uncertainGroup],approximate:!!t[_i.approximateGroup]}}}const s_="dates",em="start",im="end",qy="durations",nm="durationMin",sm="durationMax";class Kv extends eo{static format=F.group(s_,F.optionalGroup(em,F.group("openStart","\\.\\.")+"|"+Fi.format(em))+"/"+F.optionalGroup(im,F.group("openEnd","\\.\\.")+"|"+Fi.format(im)))+"|"+F.group(qy,F.group(nm,Ec.format(nm))+"/"+F.group(sm,Ec.format(sm)));constructor(t="interval",e=Kv.format){super(t,e)}parseGroups(t){let e,i;if(t[qy]){const s=t[nm];e=dn.fromString(s,new Ec);const r=t[sm];i=dn.fromString(r,new Ec)}else{const s=t[em];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=Ds.fromString(s,new Fi)}const r=t[im];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=Ds.fromString(r,new Fi)}}return{start:e,end:i}}}class Ve extends _i{static uncertainGroup="uncertain1";static approximateGroup="approx1";static uncertainAndApproximateGroup=Ve.uncertainGroup+Ve.approximateGroup;constructor(t,e){super(t,e)}static numberFormat(t,e,i){return this.qualifierFormat(F.groupName(Ve.uncertainGroup,t),"?")+this.qualifierFormat(F.groupName(Ve.approximateGroup,t),"~")+this.qualifierFormat(F.groupName(Ve.uncertainAndApproximateGroup,t),"%")+_i.numberFormat(t,e,i)}parseGroups(t){const e=super.parseGroups(t),i=t[F.groupName(Ve.uncertainAndApproximateGroup,this.name)];return(t[F.groupName(Ve.uncertainGroup,this.name)]||i)&&(e.uncertainComponent=!0),(t[F.groupName(Ve.approximateGroup,this.name)]||i)&&(e.approximateComponent=!0),e}}const Xh="yearValue",Zy="exp",Jy="signif";class gd extends Ve{constructor(){super(Xh,gd.format())}static format(t=""){return"Y?"+F.nonCapturingGroup(F.group(F.groupName(t,Zy),"[-]?\\d+E\\d+")+"|"+Ve.numberFormat(F.groupName(t,Xh),"+","[-]?")+F.optionalGroup(F.groupName(t,Jy),"S\\d+"))}parseGroups(t){const e=t[Zy];if(e){const r=e.indexOf("E"),a=parseInt(e.substring(r+1),10),l=parseInt(e.substring(0,r),10)*Math.pow(10,a);t[Xh]=l.toString()}const i=t[Jy],n=t[Xh];if(i){const r=parseInt(i.substring(1),10),{valueStr:a,sign:c}=this.getValueAndSign(t);let l="";for(let h=0;h<a.length;h++)l+=h<r?a.charAt(h):"X";t[Xh]=(c<0?"-":"")+l}const s=super.parseGroups(t);return i&&(s.value.estimate=parseInt(n,10)),s}parse(t){const e=this.regexGroups(t);return this.parseGroups(e)}}const jy="monthValue";class vd extends Ve{static format(t=""){return Ve.numberFormat(F.groupName(t,jy),"{1,2}",void 0)}constructor(){super(jy,vd.format())}}const Qy="dayValue";class Md extends Ve{static format(t=""){return Ve.numberFormat(F.groupName(t,Qy),"{1,2}",void 0)}constructor(){super(Qy,Md.format())}}const t2="hourValue";class yd extends Ve{static format(t=""){return Ve.numberFormat(F.groupName(t,t2),"{1,2}",void 0)}constructor(){super(t2,yd.format())}}const e2="secondValue";class xd extends Ve{static format(t=""){return Ve.numberFormat(F.groupName(t,e2),"{1,2}",void 0)}constructor(){super(e2,xd.format())}}const i2="minuteValue";class wd extends Ve{static format(t=""){return Ve.numberFormat(F.groupName(t,i2),"{1,2}",void 0)}constructor(){super(i2,wd.format())}}class r_ extends md{}class qe extends eo{static yearGroup=Fi.yearGroup;static monthGroup="month";static dayGroup="day";static hourGroup="hour";static minuteGroup="minute";static secondGroup="second";static millisecondGroup="millisecond";static timeshiftGroup="timeshift";constructor(){super("date",qe.format())}static format(t=""){return F.group(F.groupName(t,qe.yearGroup),gd.format(t))+F.optionalNonCapturingGroup("-",F.group(F.groupName(t,qe.monthGroup),vd.format(t)),F.optionalNonCapturingGroup("-",F.group(F.groupName(t,qe.dayGroup),Md.format(t)),F.optionalNonCapturingGroup("[T ]",F.group(F.groupName(t,qe.hourGroup),yd.format(t)),":",F.group(F.groupName(t,qe.minuteGroup),wd.format(t)),F.optionalNonCapturingGroup(":",F.group(F.groupName(t,qe.secondGroup),xd.format(t)),F.optionalNonCapturingGroup("[.,]",F.group(F.groupName(t,qe.millisecondGroup),"\\d+"))),F.optionalGroup(F.groupName(t,qe.timeshiftGroup),r_.format(t)))))}parseGroups(t){const e=t[qe.millisecondGroup],i=e?Qo.parseFraction(e):void 0,n=t[qe.secondGroup];let s;n&&(s=Xa.fromString(n,void 0,new xd),s.uncertain=s?.uncertain||!1,s.approximate=s?.approximate||!1);const r=t[qe.minuteGroup];let a;r&&(a=Wa.fromString(r,new wd),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[qe.hourGroup];let l;c&&(l=Va.fromString(c,new yd),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[qe.dayGroup];let u;h&&(u=Ga.fromString(h,new Md),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[qe.monthGroup];let f;d&&(f=Ha.fromString(d,new vd),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[qe.yearGroup];let m;p&&(m=Ba.fromString(p,void 0,new gd),m.uncertain=m.uncertain||f?.uncertain||!1,m.approximate=m.approximate||f?.approximate||!1);const g=t[qe.timeshiftGroup],v=g?cb.fromString(g,new md,{year:m?.value,month:f?.value,day:u?.value,hour:l?.value}):void 0;return{year:m,month:f,day:u,hour:l,minute:a,second:s,millisecond:i,timeshift:v}}}const n2="durationValue";class qv extends Ve{static format(t=""){return"^"+Ve.numberFormat(F.groupName(t,n2),"+",void 0)}constructor(){super(n2,qv.format())}}class a_ extends Vv{millisecond=new gi("millisecond",0,Number.MAX_SAFE_INTEGER,void 0);second=new gi("second",0,Number.MAX_SAFE_INTEGER,this.millisecond);minute=new gi("minute",0,Number.MAX_SAFE_INTEGER,this.second);hour=new gi("hour",0,Number.MAX_SAFE_INTEGER,this.minute);day=new gi("day",1,Number.MAX_SAFE_INTEGER,this.hour);month=new gi("month",1,Number.MAX_SAFE_INTEGER,this.day);year=new gi("year",0,Number.MAX_SAFE_INTEGER,this.month)}const Qc=new a_;class ee extends Ve{static yearsGroup="years";static monthsGroup="months";static isoMonthsGroup="isoMonths";static daysGroup="days";static hoursGroup="hours";static minutesGroup="minutes";static secondsGroup="seconds";static durationGroup="duration";static suffixGroup="durationSuffix";static componentParser=new qv;static componentFormat(t,e,i,n,s=""){const r=F.group(F.groupName(t,ee.quantityGroup(e)),Ve.numberFormat(F.groupName(t,i),"+",void 0,"\\d"));return F.group(F.groupName(t,e),r,n,s)}static quantityGroup(t){return t+"Quantity"}static isoMonthsLookahead="(?=[?~%]?\\d+D|T)";constructor(){super("duration",ee.format())}static format(t=""){const e=F.groupName(t,ee.durationGroup);return this.qualifierFormat(F.groupName(Ve.uncertainGroup,e),"?")+this.qualifierFormat(F.groupName(Ve.approximateGroup,e),"~")+this.qualifierFormat(F.groupName(Ve.uncertainAndApproximateGroup,e),"%")+"P"+F.optional(ee.componentFormat(t,ee.yearsGroup,qe.yearGroup,"Y"))+F.optionalNonCapturingGroup(ee.componentFormat(t,ee.monthsGroup,qe.monthGroup,"MM")+"|"+ee.componentFormat(t,ee.isoMonthsGroup,"isoMonth","M",ee.isoMonthsLookahead))+F.optional(ee.componentFormat(t,ee.daysGroup,qe.dayGroup,"D"))+"T?"+F.optional(ee.componentFormat(t,ee.hoursGroup,qe.hourGroup,"H"))+F.optional(ee.componentFormat(t,ee.minutesGroup,qe.minuteGroup,"M"))+F.optional(ee.componentFormat(t,ee.secondsGroup,qe.secondGroup,"S"))+F.optionalGroup(F.groupName(t,ee.suffixGroup),"[?~%]")}static parseComponent(t,e,i){const n=ee.componentParser.parse(t);return new e(n,i)}parseGroups(t){const e=t[ee.quantityGroup(ee.secondsGroup)];let i;e&&(i=ee.parseComponent(e,Xa,Qc.second),i.uncertain=!!t[F.groupName(Ve.uncertainGroup,ee.secondsGroup)]||!1,i.approximate=!!t[F.groupName(Ve.approximateGroup,ee.secondsGroup)]||!1);const n=t[ee.quantityGroup(ee.minutesGroup)];let s;n&&(s=ee.parseComponent(n,Wa,Qc.minute),s.uncertain=s.uncertain||i?.uncertain||!1,s.approximate=s.approximate||i?.approximate||!1);const r=t[ee.quantityGroup(ee.hoursGroup)];let a;r&&(a=ee.parseComponent(r,Va,Qc.hour),a.uncertain=a.uncertain||s?.uncertain||!1,a.approximate=a.approximate||s?.approximate||!1);const c=t[ee.quantityGroup(ee.daysGroup)];let l;c&&(l=ee.parseComponent(c,Ga,Qc.day),l.uncertain=l.uncertain||a?.uncertain||!1,l.approximate=l.approximate||a?.approximate||!1);const h=t[ee.quantityGroup(ee.monthsGroup)]||t[ee.quantityGroup(ee.isoMonthsGroup)];let u;h&&(u=ee.parseComponent(h,Ha,Qc.month),u.uncertain=u.uncertain||l?.uncertain||!1,u.approximate=u.approximate||l?.approximate||!1);const d=t[ee.quantityGroup(ee.yearsGroup)];let f;d&&(f=ee.parseComponent(d,Ba,Qc.year),f.uncertain=f.uncertain||u?.uncertain||!1,f.approximate=f.approximate||u?.approximate||!1);const p=t[ee.suffixGroup],m=!!t[F.groupName(Ve.uncertainAndApproximateGroup,ee.durationGroup)]||p==="%",g=m||!!t[F.groupName(Ve.uncertainGroup,ee.durationGroup)]||p==="?",v=m||!!t[F.groupName(Ve.approximateGroup,ee.durationGroup)]||p==="~";return{years:f,months:u,days:l,hours:a,minutes:s,seconds:i,uncertain:g,approximate:v}}}const o_="dates",rm="start",am="end",s2="durations",om="durationMin",cm="durationMax";class Ip extends eo{static format=F.group(o_,F.optionalGroup(rm,F.group("openStart","\\.\\.")+"|"+qe.format(rm))+"/"+F.optionalGroup(am,F.group("openEnd","\\.\\.")+"|"+qe.format(am)))+"|"+F.group(s2,F.group(om,ee.format(om))+"/"+F.group(cm,ee.format(cm)));constructor(t="interval",e=Ip.format){super(t,e)}parseGroups(t){let e,i;if(t[s2]){const s=t[om];e=un.fromString(s,new ee);const r=t[cm];i=un.fromString(r,new ee)}else{const s=t[rm];switch(s){case void 0:e=null;break;case"..":e=void 0;break;default:e=ms.fromString(s,new qe)}const r=t[am];switch(r){case void 0:i=null;break;case"..":i=void 0;break;default:i=ms.fromString(r,new qe)}}return{start:e,end:i}}}class c_{parse(t){t=t.trim();const e=t.startsWith("["),n=t.substring(1,t.length-1).split(","),s=[];for(const r of n){let a;r.includes("..")?a=sd.fromString(r.replace("..","/"),new Ip):a=ms.fromString(r,new qe),s.push(a)}return{values:s,exclusive:e}}}const hb=["spring","summer","autumn","winter"],Jg=21,l_=32,h_=/^(?<hour>[01]?\d|2[0-3]):(?<minute>[0-5]\d)(?::(?<second>[0-5]\d))?[?~%]?$/;let u_;function d_(){return u_??=new qe}function tl(o){return typeof o?.value=="number"?o.value:void 0}function f_(o){const t=o.trim();if(/^\d{1,2}:/.test(t)){const r=h_.exec(t)?.groups;return r?{year:void 0,month:void 0,day:void 0,hour:Number(r.hour),minute:Number(r.minute),second:r.second?Number(r.second):void 0,raw:t}:void 0}let e;try{e=ms.fromString(t,d_())}catch{return}const i=tl(e.year),n=tl(e.month),s=n!==void 0&&n>=Jg&&n<=l_;if(!(e.timeshift||i!==void 0&&Math.abs(i)>9999)&&!(n!==void 0&&n>12&&!s)&&!(s&&(e.day||e.hour)))return{year:i,month:s?void 0:n,...s?{season:hb[(n-Jg)%4]}:{},day:tl(e.day),hour:tl(e.hour),minute:tl(e.minute),second:tl(e.second),raw:t}}function p_(o){if(o.raw!==void 0)return o.raw;if(o.year===void 0){if(o.hour===void 0)return"";let e=`${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`;return o.second!==void 0&&(e+=`:${String(o.second).padStart(2,"0")}`),e}let t=String(o.year).padStart(4,"0");return o.season!==void 0?`${t}-${Jg+hb.indexOf(o.season)}`:(o.month===void 0||(t+=`-${String(o.month).padStart(2,"0")}`,o.day===void 0)||(t+=`-${String(o.day).padStart(2,"0")}`,o.hour===void 0)||(t+=`T${String(o.hour).padStart(2,"0")}:${String(o.minute??0).padStart(2,"0")}`,o.second!==void 0&&(t+=`:${String(o.second).padStart(2,"0")}`)),t)}function jg(o){if(o.year!==void 0)return Date.UTC(o.year,(o.month??1)-1,o.day??1,o.hour??0,o.minute??0,o.second??0)}function r2(o){return(((o.day??0)*24+(o.hour??0))*60+(o.minute??0))*6e4+(o.second??0)*1e3}const m_=["year","month","day","hour","minute"],g_=["day","hour","minute"];function a2(o,t){return t.filter(e=>o[e]!==void 0).join(",")}function v_(o){if(o.durationSeconds!==void 0)return o.durationSeconds*1e3;const t=o.durationText===void 0?void 0:Du.parse(o.durationText);if(t)return t.chosenSeconds*1e3;if(!o.time||!o.endTime)return;const e=o.time.year!==void 0&&o.endTime.year!==void 0,i=e?m_:g_,n=a2(o.time,i);if(!(n===""||n!==a2(o.endTime,i)))return e?jg(o.endTime)-jg(o.time):r2(o.endTime)-r2(o.time)}class Dp{constructor(t,e,i,n,s,r,a,c,l=[],h,u,d,f=[],p=[],m=[],g=[]){this.event=t,this.timeline=e,this.observerTrack=i,this.weatherTrack=n,this.soundTrack=s,this.observer=r,this.id=a,this.weather=c,this.decor=l,this.weatherSource=h,this.instrumentId=u,this.exposureSeconds=d,this.milestones=f,this.references=p,this.roads=m,this.traces=g}provenance=sr.empty();loadIssues=[];account;sources;interpretation;variants=[];skyEvents;snapshots;modules;sway;lightPollution;observerMap;iso;film;metering;lens;lighting;vehicle;events;eventsExpansion;sampleMs;get observerCount(){return 1+this.decor.filter(t=>t.kind==="observer").length}get exposure(){return this.exposureSeconds??this.instrument.exposureSeconds}get instrument(){return $i.byId(this.instrumentId)}static create(t,e,i){return new Dp({eventType:"sighting",time:t,place:e},new Ud,new Qu,new td,new ed,i)}}const M_=0,y_=0;function ke(o,t){const e=o.observerTrack.getInterpolatedPoseAt(t);if(e)return e;const i=o.event.place?.[0];if(i)return{lat:i.lat,lng:i.lng,elevationM:M_,headingDeg:void 0,pitchDeg:y_,fovDeg:$i.fieldOfViewDeg(o.instrument)}}function Yh(o,t){return o.weatherTrack.getInterpolatedWeatherAt(t)??o.weather??Ep}function $h(o,t){return o.weatherTrack.getActualWeatherAt(t)??o.weather??Ep}function x_(o,t){return o.soundTrack.getInterpolatedSoundAt(t)??m3}class w_{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 n=this.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}this.onFrame(t,e)}}const ub=["nw","n","ne","e","se","s","sw","w"],S_=24,qd=8,b_=3,E_=8;function Zd(o,t,e){const i=o.x-t.x,n=o.y-t.y,s=Math.cos(e),r=Math.sin(e);return{x:t.x+i*s-n*r,y:t.y+i*r+n*s}}function Kh(o){return{x:o.x+o.width/2,y:o.y+o.height/2}}const A_={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 Hs{static handlePointsFor(t){const{x:e,y:i,width:n,height:s}=t.bounds,r={nw:{x:e,y:i},n:{x:e+n/2,y:i},ne:{x:e+n,y:i},e:{x:e+n,y:i+s/2},se:{x:e+n,y:i+s},s:{x:e+n/2,y:i+s},sw:{x:e,y:i+s},w:{x:e,y:i+s/2},rotate:{x:e+n/2,y:i-S_}},a=Kh(t.bounds),c={};for(const l of Object.keys(r))c[l]=Zd(r[l],a,t.angle);return c}static hitTestHandle(t,e,i=8,n=[...ub,"rotate"]){const s=Hs.handlePointsFor(t);for(const r of n)if(Math.hypot(e.x-s[r].x,e.y-s[r].y)<=i)return r}static HANDLE_DIRECTION_DEG={e:0,se:45,s:90,sw:135,w:180,nw:225,n:270,ne:315};static resizeAxisFor(t,e){const n=((Hs.HANDLE_DIRECTION_DEG[t]+e*180/Math.PI)%180+180)%180/45,s=["ew","nwse","ns","nesw"];return s[Math.round(n)%s.length]}static resizeBounds(t,e,i,n){const s=Kh(t),r=Zd(n,s,-e),{x:a,y:c,width:l,height:h}=t,u=A_[i];let d=a,f=c,p=a+l,m=c+h;return u.left&&(d=Math.min(r.x,p-qd)),u.right&&(p=Math.max(r.x,d+qd)),u.top&&(f=Math.min(r.y,m-qd)),u.bottom&&(m=Math.max(r.y,f+qd)),{x:d,y:f,width:p-d,height:m-f}}static resizeShape(t,e,i){if(e==="rotate")throw new Error("resizeShape does not accept the rotate handle");const{width:n,height:s}=t.bounds,r=Hs.resizeBounds(t.bounds,t.angle,e,i);if(t.kind==="oval")return{...t,bounds:r};const a=n===0?1:r.width/n,c=s===0?1:r.height/s;return{...t,bounds:r,points:t.points.map(l=>({x:l.x*a,y:l.y*c}))}}static rotateShape(t,e){const i=Kh(t.bounds),n=Math.atan2(e.y-i.y,e.x-i.x)+Math.PI/2;return{...t,angle:n}}static groupBoundsFor(t){const e=Math.min(...t.map(r=>r.x)),i=Math.min(...t.map(r=>r.y)),n=Math.max(...t.map(r=>r.x+r.width)),s=Math.max(...t.map(r=>r.y+r.height));return{x:e,y:i,width:n-e,height:s-i}}static vertexPointsFor(t){const e=Kh(t.bounds);return t.points.map(i=>Zd({x:t.bounds.x+i.x,y:t.bounds.y+i.y},e,t.angle))}static hitTestVertex(t,e,i=E_){const n=Hs.vertexPointsFor(t);let s,r=i;return n.forEach((a,c)=>{const l=Math.hypot(e.x-a.x,e.y-a.y);l<=r&&(r=l,s=c)}),s}static toLocalPoint(t,e){const i=Kh(t.bounds),n=Zd(e,i,-t.angle);return{x:n.x-t.bounds.x,y:n.y-t.bounds.y}}static moveVertex(t,e,i){const n=t.points.map((u,d)=>d===e?Hs.toLocalPoint(t,i):u),s=Math.min(...n.map(u=>u.x)),r=Math.min(...n.map(u=>u.y)),a=Math.max(...n.map(u=>u.x)),c=Math.max(...n.map(u=>u.y)),l={x:t.bounds.x+s,y:t.bounds.y+r,width:a-s,height:c-r},h=n.map(u=>({x:u.x-s,y:u.y-r}));return{...t,bounds:l,points:h}}static insertVertexNear(t,e){const i=Hs.toLocalPoint(t,e),{points:n}=t;let s=n.length-1,r=1/0;for(let c=0;c<n.length;c++){const l=n[c],h=n[(c+1)%n.length],u=Hs.distanceToSegment(i,l,h);u<r&&(r=u,s=c)}const a=[...n.slice(0,s+1),i,...n.slice(s+1)];return{...t,points:a}}static distanceToSegment(t,e,i){const n=i.x-e.x,s=i.y-e.y,r=n*n+s*s,a=r===0?0:Math.max(0,Math.min(1,((t.x-e.x)*n+(t.y-e.y)*s)/r)),c=e.x+a*n,l=e.y+a*s;return Math.hypot(t.x-c,t.y-l)}static deleteVertex(t,e){return t.points.length<=b_?t:{...t,points:t.points.filter((i,n)=>n!==e)}}}const Qg=6,Jd=Qg/2,o2=20,c2=24,l2=9,h2=6,u2=7,d2=6,Or=4;class Oh{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:n,height:s}=t.bounds,r=e+n/2,a=i+s/2,c=t.angle%(2*Math.PI)!==0,l=Math.hypot(n,s)/2,h=c?l:n/2,u=c?l:s/2,d=Math.max(n,s)/2,f=t.brightness??0,p=f>0?Math.max(d*(1+l2*f),d2*f)-d:0,m=f>0?d*(1+u2*f)-d:0,g=3*c2*(t.blur??0)+1.5*o2*t.haloScale,v=Math.max(p,m,0)+g+2;return{x:r-h-v,y:a-u-v,width:2*(h+v),height:2*(u+v)}}paintInto(t,e,i,n=!1){this.ctx.save(),this.ctx.scale(i,i),this.ctx.translate(-e.x,-e.y);const s=t.selected?{...t,selected:!1}:t;n?this.paintGhost(s,1.5):this.paintShape(s),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(${(c2*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:n,width:s,height:r}=t.bounds,a=i+s/2,c=n+r/2,l=Math.max(s,r)/2,h=Math.max(l*(1+l2*e),d2*e);if(h<=0)return;this.ctx.save(),this.ctx.globalCompositeOperation="lighter";const u=this.ctx.createRadialGradient(a,c,0,a,c,h);for(let d=0;d<=h2;d++){const f=d/h2,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(a,c,h,0,2*Math.PI),this.ctx.fill(),this.starPoints>0){const d=l*(1+u2*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,m=a+Math.cos(p)*d,g=c+Math.sin(p)*d,v=this.ctx.createLinearGradient(a,c,m,g);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(a,c),this.ctx.lineTo(m,g),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 n=Number.parseInt(i[1],16),s=r=>Math.round(r+(255-r)*e);return`rgb(${s(n>>16&255)}, ${s(n>>8&255)}, ${s(n&255)})`}withAlpha(t,e){const i=Math.max(0,Math.min(1,e)),n=/^#([0-9a-f]{6})$/i.exec(t.trim());if(!n)return t;const s=Number.parseInt(n[1],16);return`rgba(${s>>16&255}, ${s>>8&255}, ${s&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:n,height:s}=t.bounds,r=n/2,a=s/2;this.ctx.ellipse(e+r,i+a,r,a,t.angle,0,2*Math.PI)}else{const{x:e,y:i,width:n,height:s}=t.bounds;this.ctx.save(),this.ctx.translate(e+n/2,i+s/2),this.ctx.rotate(t.angle),this.ctx.translate(-n/2,-s/2),t.points.forEach((r,a)=>{a===0?this.ctx.moveTo(r.x,r.y):this.ctx.lineTo(r.x,r.y)}),this.ctx.closePath(),this.ctx.restore()}}paintHalo(t){this.ctx.save(),this.ctx.shadowColor=t.color,this.ctx.shadowBlur=o2*t.haloScale,this.paintBase(t),this.ctx.restore()}paintSelectionHandles(t){this.paintHandleFrame(Hs.handlePointsFor(t),{includeRotate:!0}),t.kind==="polygon"&&this.paintVertexHandles(t)}paintVertexHandles(t){this.ctx.fillStyle="#39f";for(const e of Hs.vertexPointsFor(t))this.ctx.beginPath(),this.ctx.ellipse(e.x,e.y,Or,Or,0,0,2*Math.PI),this.ctx.fill()}paintMemberOutline(t){this.paintOutline(Hs.handlePointsFor(t))}paintSelectionOnly(t){this.paintSelectionHandles(t)}paintPictureFrame(t,e,i){const n=this.ctx;if(n.save(),t&&t.length===4){n.strokeStyle="#39f",n.lineWidth=1.5,n.setLineDash([6,4]),n.beginPath(),n.moveTo(t[0].x,t[0].y);for(const s of t.slice(1))n.lineTo(s.x,s.y);n.closePath(),n.stroke(),n.setLineDash([])}for(const s of e){const r=Oh.landmarkColour(s.residualDeg),a=s.selected?3:2;s.selected&&(n.strokeStyle="#fff",n.lineWidth=a+3,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Or+2,Or+2,0,0,2*Math.PI),n.stroke()),s.scene&&(n.strokeStyle=r,n.lineWidth=1,n.beginPath(),n.moveTo(s.picture.x,s.picture.y),n.lineTo(s.scene.x,s.scene.y),n.stroke(),n.fillStyle=r,n.beginPath(),n.ellipse(s.scene.x,s.scene.y,Or,Or,0,0,2*Math.PI),n.fill()),n.strokeStyle=r,n.lineWidth=a,n.beginPath(),n.ellipse(s.picture.x,s.picture.y,Or+2,Or+2,0,0,2*Math.PI),n.stroke(),this.paintLabel(s.label,s.picture.x+Or+5,s.picture.y-Or-2,r)}i&&this.paintLabel(i,8,8,"#fff",13),n.restore()}paintGhosts(t,e,i){const n=this.ctx;n.save();const s=(c,l,h,u=[])=>{n.setLineDash(u),n.lineWidth=h+2,n.strokeStyle="rgba(0, 0, 0, 0.6)",c(),n.lineWidth=h,n.strokeStyle=l,c(),n.setLineDash([])},r=(c,l)=>()=>{n.beginPath(),n.arc(c.x,c.y,l,0,2*Math.PI),n.stroke()},a=(c,l,h)=>()=>{const[u,d]=h?[l,l]:[l,0];n.beginPath(),n.moveTo(c.x-u,c.y-d),n.lineTo(c.x+u,c.y+d),n.moveTo(c.x+d,c.y-u),n.lineTo(c.x-d,c.y+u),n.stroke()};for(const c of t)s(()=>{n.beginPath(),n.moveTo(c.ghost.x,c.ghost.y),n.lineTo(c.light.x,c.light.y),n.stroke()},"rgba(255, 255, 255, 0.85)",1,[4,4]),s(r(c.light,7),"#ffffff",1.5),s(r(c.ghost,Math.max(9,c.ghostRadius)),"#ffd23f",2);e&&s(a(e,8,!1),"#ffd23f",2),i&&s(a(i,5,!0),"rgba(255, 255, 255, 0.7)",1),n.restore()}static landmarkColour(t){return t===void 0?"#ffb000":t<=1?"#3c3":t<=3?"#ffb000":"#f33"}paintLabel(t,e,i,n,s=11){const r=this.ctx;r.save(),r.font=`${s}px system-ui, sans-serif`,r.textBaseline="top";const a=r.measureText(t).width;r.fillStyle="rgba(0, 0, 0, 0.6)",r.fillRect(e-3,i-2,a+6,s+4),r.fillStyle=n,r.fillText(t,e,i),r.restore()}paintGroupHandles(t){this.paintHandleFrame(Hs.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 ub){const n=t[i];this.ctx.fillRect(n.x-Jd,n.y-Jd,Qg,Qg)}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,Jd+1,Jd+1,0,0,2*Math.PI),this.ctx.fill())}}const f2=.05,p2=.08,m2=2,g2=3,__=14,T_=.02;class v2{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}}Ys.isLive(this.context)&&Ys.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(),Ys.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 n=i.currentTime;t.volumeParam.setTargetAtTime(Math.max(0,Math.min(1,e.volume))*t.gainScale,n,f2);for(const{param:s,ratio:r}of t.pitch)s.setTargetAtTime(Math.min(e.pitchHz*r,i.sampleRate/2-1),n,f2)}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 n=t.createOscillator();n.type="sawtooth";const s=t.createBiquadFilter();s.type="lowpass",s.Q.value=1;const r=t.createGain();return r.gain.value=0,i.connect(s),n.connect(s),s.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.16,pitch:[{param:i.frequency,ratio:1},{param:n.frequency,ratio:1.006},{param:s.frequency,ratio:6}]}}buildWhistle(t,e){const i=t.createOscillator();i.type="sine";const n=t.createOscillator();n.type="sine",n.frequency.value=5;const s=t.createGain(),r=t.createGain();return r.gain.value=0,n.connect(s).connect(i.frequency),i.connect(r).connect(this.output(t)),i.start(),n.start(),{key:e,nodes:[s,r],sources:[i,n],volumeParam:r.gain,gainScale:.22,pitch:[{param:i.frequency,ratio:1},{param:s.gain,ratio:.012}]}}buildRumble(t,e){const i=t.createBufferSource();i.buffer=this.brownNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="lowpass",n.Q.value=.8;const s=t.createGain();return s.gain.value=0,i.connect(n).connect(s).connect(this.output(t)),i.start(),{key:e,nodes:[n,s],sources:[i],volumeParam:s.gain,gainScale:1.4,pitch:[{param:n.frequency,ratio:1}]}}buildCrackle(t,e){const i=t.createBufferSource();i.buffer=this.whiteNoise(t),i.loop=!0;const n=t.createBiquadFilter();n.type="bandpass",n.Q.value=1.2;const s=t.createGain();s.gain.value=0;const r=t.createBufferSource();r.buffer=this.crackleEnvelope(t),r.loop=!0;const a=t.createGain();return a.gain.value=0,r.connect(a).connect(s.gain),i.connect(n).connect(s).connect(this.output(t)),i.start(),r.start(),{key:e,nodes:[n,s,a],sources:[i,r],volumeParam:a.gain,gainScale:.9,pitch:[{param:n.frequency,ratio:4}]}}async buildRecordedVoice(t,e,i){const n=this.context;if(!n)return;let s;try{s=await this.getBuffer(t)}catch(c){console.warn("SightingAudio: the recorded sound failed to load, staying silent:",c);return}if(i!==this.voiceToken||!this.context)return;const r=n.createBufferSource();r.buffer=s,r.loop=!0;const a=n.createGain();a.gain.value=0,r.connect(a).connect(this.output(n)),r.start(),this.voice={key:e,nodes:[a],sources:[r],volumeParam:a.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(n=>{if(!n.ok)throw new Error(`Audio fetch failed (${n.status}): ${t}`);return n.arrayBuffer()}).then(n=>e.decodeAudioData(n)),this.buffers.set(t,i)),i}whiteNoise(t){if(!this.noiseBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*m2),t.sampleRate),i=e.getChannelData(0);for(let n=0;n<i.length;n++)i[n]=Math.random()*2-1;this.noiseBuffer=e}return this.noiseBuffer}brownNoise(t){const e=t.createBuffer(1,Math.floor(t.sampleRate*m2),t.sampleRate),i=e.getChannelData(0);let n=0,s=0;for(let r=0;r<i.length;r++)n=(n+.02*(Math.random()*2-1))/1.02,i[r]=n,s=Math.max(s,Math.abs(n));if(s>0)for(let r=0;r<i.length;r++)i[r]/=s;return e}crackleEnvelope(t){if(!this.crackleBuffer){const e=t.createBuffer(1,Math.floor(t.sampleRate*g2),t.sampleRate),i=e.getChannelData(0),n=Math.max(1,Math.floor(T_*t.sampleRate)),s=Math.round(g2*__);for(let r=0;r<s;r++){const a=Math.floor(Math.random()*i.length),c=.4+Math.random()*.6;for(let l=0;l<n&&a+l<i.length;l++)i[a+l]=Math.max(i[a+l],c*(1-l/n))}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,p2/3);const n=i+p2;for(const s of t.sources){s.onended=()=>{s.disconnect();for(const r of t.nodes)r.disconnect()};try{s.stop(n)}catch{s.disconnect();for(const r of t.nodes)r.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 Vr{static KINDS=["beams","launches","reentries"];static statedKinds(t){return Object.keys(t??{}).filter(e=>Array.isArray(t[e])&&t[e].length>0)}static isEmpty(t){return Vr.statedKinds(t).length===0}static written(t){const e=Vr.statedKinds(t);if(e.length===0)return;const i={};for(const n of e)i[n]=t[n];return i}static read(t,e){const i=e,n={};for(const r of Vr.statedKinds(t))n[r]=t[r];for(const r of Vr.KINDS){const a=[...t?.[r]??[],...i?.[r]??[]];a.length>0&&(n[r]=a)}let s=e;if(i&&Vr.KINDS.some(r=>r in i)){const{beams:r,launches:a,reentries:c,...l}=i;s=Vr.isReading(l)?l:void 0}return{skyEvents:Vr.written(n),interpretation:s}}static isReading(t){return(t.bodies?.length??0)>0||t.title!==void 0||(t.smoke?.length??0)>0}}function Cu(o){return[...o].sort((t,e)=>t.t-e.t)}function jd(o,t){let e;for(const i of Cu(o)){if(i.t>t)break;e=i}return e}const lm=Math.PI/180,Qd=180/Math.PI;class aa{constructor(t,e,i){this.kind=t,this.canvasHeightPx=e,this.fovDeg=i;const n=i*lm/2;this.focalPx=t==="equidistant"?e/2/n:e/2/Math.tan(n)}focalPx;static of(t,e,i){return new aa(t.projection,e,i)}degToPx(t){const e=t*lm;return this.kind==="equidistant"?this.focalPx*e:2*this.focalPx*Math.tan(e/2)}pxToDeg(t){return this.kind==="equidistant"?t/this.focalPx*Qd:2*Math.atan(t/(2*this.focalPx))*Qd}angleDegToRadiusPx(t){const e=t*lm;return this.kind==="equidistant"?this.focalPx*e:this.focalPx*Math.tan(e)}halfWidthAngleDeg(t){return this.radiusPxToAngleDeg(this.canvasHeightPx*t/2)}radiusPxToAngleDeg(t){return this.kind==="equidistant"?t/this.focalPx*Qd:Math.atan(t/this.focalPx)*Qd}ofBounds(t){return{widthDeg:this.pxToDeg(t.width),heightDeg:this.pxToDeg(t.height)}}toBoundsSize(t){return{width:this.degToPx(t.widthDeg),height:this.degToPx(t.heightDeg)}}widthPx(t){return this.degToPx(ui.angularWidthDeg(t))}}class fn{static fovOf(t,e){return ke(t,e)?.fovDeg??$i.fieldOfViewDeg(t.instrument)}static toAngular(t){this.eachKeyframe(t,(e,i)=>{const n=i.ofBounds(e.bounds);return e.angular?.widthDeg===n.widthDeg&&e.angular.heightDeg===n.heightDeg?e:{...e,angular:n}})}static toBounds(t){this.eachKeyframe(t,(e,i)=>this.sizedFromAngle(e,i))}static sizedFromAngle(t,e){if(!t.angular)return t;const{width:i,height:n}=e.toBoundsSize(t.angular),s={x:t.bounds.x+(t.bounds.width-i)/2,y:t.bounds.y+(t.bounds.height-n)/2,width:i,height:n};if(t.kind!=="polygon")return{...t,bounds:s};const r=t.bounds.width===0?1:i/t.bounds.width,a=t.bounds.height===0?1:n/t.bounds.height;return{...t,bounds:s,points:t.points.map(c=>({x:c.x*r,y:c.y*a}))}}static toAim(t){this.eachKeyframe(t,(e,i,n)=>{const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);if(s&&Math.abs(s.x-e.bounds.x)<fn.UNMOVED_PX&&Math.abs(s.y-e.bounds.y)<fn.UNMOVED_PX)return e;const r=this.aimFrom(t,i,n,e.bounds);return r?{...e,aim:r}:e})}static UNMOVED_PX=.01;static aimOf(t,e,i){const n=aa.of(t.instrument,ui.CANVAS_HEIGHT_PX,this.fovOf(t,e));return this.aimFrom(t,n,ke(t,e),i)}static aimFrom(t,e,i,n){if(i?.headingDeg===void 0)return;const s=this.frameCentre(t),r=e.radiusPxToAngleDeg(n.x+n.width/2-s.x),a=e.radiusPxToAngleDeg(s.y-(n.y+n.height/2));return{azimuthDeg:((i.headingDeg+r)%360+360)%360,altitudeDeg:i.pitchDeg+a}}static toPosition(t){this.eachKeyframe(t,(e,i,n)=>this.placedByAim(t,e,i,n))}static placedByAim(t,e,i,n){const s=e.aim&&this.positionOf(t,e.aim,e.bounds,i,n);return s?{...e,bounds:{...e.bounds,...s}}:e}static derivable(t){const e=new Set,i=new Map,n=new Map;return t.timeline.allKeyframes.forEach((s,r)=>{const a=ke(t,s.t),c=aa.of(t.instrument,ui.CANVAS_HEIGHT_PX,this.fovOf(t,s.t));for(const{sourceId:l,shape:h}of s.shapes){const u=n.get(l),d=i.get(l);if(n.set(l,h),!u||!d){i.set(l,h);continue}const f=Object.fromEntries(Object.entries(h).filter(([g,v])=>g!=="bounds"&&g!=="points"&&JSON.stringify(v)!==JSON.stringify(u[g]))),p={...d,...f},m=this.placedByAim(t,this.sizedFromAngle(p,c),c,a);fn.near(m,h)?(e.add(`${r}:${l}`),i.set(l,p)):i.set(l,h)}}),(s,r)=>e.has(`${s}:${r}`)}static SAME_PX=1e-6;static near(t,e){const i=(r,a)=>Math.abs(r-a)<=fn.SAME_PX*Math.max(1,Math.abs(a)),n=t.bounds,s=e.bounds;return!i(n.x,s.x)||!i(n.y,s.y)||!i(n.width,s.width)||!i(n.height,s.height)?!1:e.kind!=="polygon"||t.kind!=="polygon"?!0:t.points.length===e.points.length&&t.points.every((r,a)=>i(r.x,e.points[a].x)&&i(r.y,e.points[a].y))}static positionOf(t,e,i,n,s){if(s?.headingDeg===void 0)return;const r=this.frameCentre(t),a=this.shortestArc(e.azimuthDeg-s.headingDeg),c=e.altitudeDeg-s.pitchDeg;return{x:r.x+this.offAxisPx(n,a)-i.width/2,y:r.y-this.offAxisPx(n,c)-i.height/2}}static frameCentre(t){return{x:$i.frameWidthPx(t.instrument,ui.CANVAS_HEIGHT_PX)/2,y:ui.CANVAS_HEIGHT_PX/2}}static shortestArc(t){return(t%360+540)%360-180}static offAxisPx(t,e){return Math.abs(e)>=fn.OFF_CANVAS_DEG?Math.sign(e)*fn.OFF_CANVAS_PX:t.angleDegToRadiusPx(e)}static OFF_CANVAS_DEG=89;static OFF_CANVAS_PX=1e5;static reproject(t,e,i){const n=$i.frameWidthPx(e,ui.CANVAS_HEIGHT_PX)/2,s=$i.frameWidthPx(t.instrument,ui.CANVAS_HEIGHT_PX)/2,r=ui.CANVAS_HEIGHT_PX/2;for(const a of[...t.timeline.allKeyframes]){const c=this.fovOf(t,a.t),l=i?.get(a.t)??c,h=aa.of(e,ui.CANVAS_HEIGHT_PX,l),u=aa.of(t.instrument,ui.CANVAS_HEIGHT_PX,c);t.timeline.addKeyframe(a.t,a.shapes.map(d=>{const{bounds:f}=d.shape,p=f.x+f.width/2-n,m=f.y+f.height/2-r,g=Math.hypot(p,m),v=g===0?1:u.angleDegToRadiusPx(h.radiusPxToAngleDeg(g))/g,M={...f,x:s+p*v-f.width/2,y:r+m*v-f.height/2};return{...d,shape:{...d.shape,bounds:M}}}))}this.toBounds(t)}static eachKeyframe(t,e){const{timeline:i}=t;for(const n of[...i.allKeyframes]){const s=ke(t,n.t),r=this.fovOf(t,n.t),a=aa.of(t.instrument,ui.CANVAS_HEIGHT_PX,r);let c=!1;const l=n.shapes.map(h=>{const u=e(h.shape,a,s);return u===h.shape?h:(c=!0,{...h,shape:u})});c&&i.addKeyframe(n.t,l)}}}class ds{static isRelative(t){return t!==void 0&&typeof t.eastM=="number"&&typeof t.northM=="number"}static isAbsolute(t){return t!==void 0&&typeof t.lat=="number"&&typeof t.lng=="number"}static referenceOf(t,e){return e.references.find(i=>(i.id??void 0)===(t.relativeTo??void 0))}static resolve(t,e){if(ds.isRelative(t)){const i=ds.referenceOf(t,e);return i?{eastM:i.eastM+t.eastM,northM:i.northM+t.northM}:void 0}return ds.isAbsolute(t)&&e.origin?ds.toLocal(t,e.origin):void 0}static restated(t,e,i){if(ds.isRelative(t)){const s=ds.referenceOf(t,i);return s?ds.relative(e.eastM-s.eastM,e.northM-s.northM,t.relativeTo):void 0}if(!i.origin)return t;const n=ds.toGeo(e,i.origin);return{lat:ds.degrees(n.lat),lng:ds.degrees(n.lng)}}static relative(t,e,i){const n={eastM:ds.metres(t),northM:ds.metres(e)};return i!==void 0&&(n.relativeTo=i),n}static toLocal(t,e){const i=se(t.lat,t.lng,e.lat,e.lng);return{eastM:i.x,northM:-i.z}}static toGeo(t,e){return Cs(t.eastM,-t.northM,e.lat,e.lng)}static metres(t){return Math.round(t*100)/100}static degrees(t){return Math.round(t*1e7)/1e7}}class Zn{static restatedDecor(t){const e=Zn.originOf(t);return t.decor.map(i=>{let n=i;if(i.saidPosition){const s=Zn.restated(i.saidPosition,i,Zn.frameAt(t,0,e,i.id));JSON.stringify(s)!==JSON.stringify(i.saidPosition)&&(n={...i,saidPosition:s},s||delete n.saidPosition)}if(i.track?.some(s=>s.saidPosition)){const s=i.track.map(r=>{if(!r.saidPosition)return r;const a=Zn.restated(r.saidPosition,r,Zn.frameAt(t,r.t,e,i.id));if(JSON.stringify(a)===JSON.stringify(r.saidPosition))return r;const c={...r,saidPosition:a};return a||delete c.saidPosition,c});n={...n,track:s}}return n})}static restatedObserverTrack(t){const e=t.observerTrack.toJSON(),i=Zn.originOf(t);return!i||!e.keyframes.some(n=>n.pose.saidPosition)?e:{...e,keyframes:e.keyframes.map(n=>{const{pose:s}=n;if(!s.saidPosition||s.lat===void 0||s.lng===void 0)return n;const r=ds.toLocal({lat:s.lat,lng:s.lng},i),a=Zn.restated(s.saidPosition,r,Zn.frameAt(t,n.t,i));if(JSON.stringify(a)===JSON.stringify(s.saidPosition))return n;const c={...s,saidPosition:a};return a||delete c.saidPosition,{...n,pose:c}})}}static restatedInterpretation(t){const e=t.interpretation;if(!e?.bodies.some(n=>n.track.some(s=>s.saidPosition)))return e;const i=Zn.originOf(t);return{...e,bodies:e.bodies.map(n=>n.track.some(s=>s.saidPosition)?{...n,track:n.track.map(s=>{if(!s.saidPosition)return s;const r=s.eastM!==void 0&&s.northM!==void 0?Zn.restated(s.saidPosition,{eastM:s.eastM,northM:s.northM},Zn.frameAt(t,s.t,i)):void 0;if(JSON.stringify(r)===JSON.stringify(s.saidPosition))return s;const a={...s,saidPosition:r};return r||delete a.saidPosition,a})}:n)}}static originOf(t){const e=t.observerTrack.getInterpolatedPoseAt(0),i=t.event.place?.[0],n=e?.lat??i?.lat,s=e?.lng??i?.lng;return typeof n=="number"&&typeof s=="number"?{lat:n,lng:s}:void 0}static frameAt(t,e,i,n){const s=[{label:"",eastM:0,northM:0},...t.decor.filter(r=>r.id!==n).map(r=>{const{eastM:a,northM:c}=ha(r,e);return{id:r.id,label:r.id,eastM:a,northM:c}})];return{origin:i,references:s}}static restated(t,e,i){return ds.restated(t,{eastM:e.eastM,northM:e.northM},i)}}class oi{constructor(t,e,i){this.params=t,this.from=e,this.origin=t.path[0],this.cos0=Math.cos(t.path[0].lat*Math.PI/180),this.points=t.path.map(r=>this.local(r)),this.cumulative=[0];for(let r=1;r<this.points.length;r++){const a=this.points[r-1],c=this.points[r];this.cumulative.push(this.cumulative[r-1]+Math.hypot(c.e-a.e,c.n-a.n))}this.distances=[];let n=0;for(let r=e;r<=i+oi.BEYOND_MS;r+=oi.STEP_MS)this.distances.push(n),n+=this.speedAt(r)*oi.STEP_MS/1e3;this.shift=this.project(this.local(t.through))-this.distanceAt(t.through.t);const s=[];for(let r=e;r<=i;r+=oi.SAMPLE_MS)s.push({t:r,place:this.placeAt(r)});this.sampleOrigin=s[0].place,this.sampleCos=Math.cos(this.sampleOrigin.lat*Math.PI/180),this.samples=s.map(({t:r,place:a})=>({t:r,e:(a.lng-this.sampleOrigin.lng)*Math.PI/180*oi.R*this.sampleCos,n:(a.lat-this.sampleOrigin.lat)*Math.PI/180*oi.R}))}static R=63710088e-1;static STEP_MS=100;static SAMPLE_MS=2e3;static BEYOND_MS=8e4;origin;cos0;points;cumulative;distances;shift;samples;sampleOrigin;sampleCos;get start(){return this.sampleOrigin}stateAt(t){const e=this.samples,i=e.length-2;let n=0;for(;n<i&&e[n+1].t<t;)n++;const s=e[n],r=e[n+1],a=(t-s.t)/(r.t-s.t),c=p=>[n>0?p[n-1]:2*p[n]-p[n+1],p[n],p[n+1],n+2<p.length?p[n+2]:2*p[n+1]-p[n]],l=e.map(p=>p.e),h=e.map(p=>p.n),u=oi.catmull(c(l),a),d=oi.catmull(c(h),a),f=(Math.atan2(oi.slope(c(l),a),oi.slope(c(h),a))*180/Math.PI%360+360)%360;return{eastM:u,northM:d,roadDeg:f,lat:this.sampleOrigin.lat+d/oi.R*180/Math.PI,lng:this.sampleOrigin.lng+u/(oi.R*this.sampleCos)*180/Math.PI}}bearingAt(t,e){const i=this.local(this.placeAt(t)),n=this.local(e);return(Math.atan2(n.e-i.e,n.n-i.n)*180/Math.PI%360+360)%360}get sampleTimes(){return this.samples.map(t=>t.t)}placeAt(t){const e=this.along(this.distanceAt(t)+this.shift);return{lat:this.origin.lat+e.n/oi.R*180/Math.PI,lng:this.origin.lng+e.e/(oi.R*this.cos0)*180/Math.PI}}distanceAt(t){const e=Math.max(0,Math.min(this.distances.length-1,Math.round((t-this.from)/oi.STEP_MS)));return this.distances[e]}speedAt(t){const e=this.params.speedDivisors?oi.linear(this.params.speedDivisors.map(({t:i,divisor:n,step:s})=>({t:i,value:n,step:s})),t):1;return oi.linear(this.params.speeds.map(({t:i,kmh:n,step:s})=>({t:i,value:n,step:s})),t)/3.6/e}local(t){return{e:(t.lng-this.origin.lng)*Math.PI/180*oi.R*this.cos0,n:(t.lat-this.origin.lat)*Math.PI/180*oi.R}}along(t){const e=this.points;let i=0;for(;i<e.length-2&&this.cumulative[i+1]<t;)i++;const n=e[i],s=e[i+1],r=(t-this.cumulative[i])/(this.cumulative[i+1]-this.cumulative[i]);return{e:n.e+(s.e-n.e)*r,n:n.n+(s.n-n.n)*r}}project(t){let e=1/0,i=0;for(let n=0;n<this.points.length-1;n++){const s=this.points[n],r=this.points[n+1],a=r.e-s.e,c=r.n-s.n,l=Math.max(0,Math.min(1,((t.e-s.e)*a+(t.n-s.n)*c)/(a*a+c*c))),h=Math.hypot(s.e+a*l-t.e,s.n+c*l-t.n);h<e&&(e=h,i=this.cumulative[n]+l*Math.hypot(a,c))}return i}static linear(t,e){if(e<=t[0].t)return t[0].value;for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];if(s.step&&e<s.t)return n.value;if(e<=s.t)return n.value+(s.value-n.value)*(e-n.t)/(s.t-n.t)}return t[t.length-1].value}static catmull([t,e,i,n],s){return .5*(2*e+(i-t)*s+(2*t-5*e+4*i-n)*s*s+(3*e-t-3*i+n)*s**3)}static slope([t,e,i,n],s){return .5*(i-t+2*(2*t-5*e+4*i-n)*s+3*(3*e-t-3*i+n)*s*s)}}class Qe{constructor(t,e,i,n,s,r){this.drive=t,this.eye=e,this.lookAhead=i,this.lean=n,this.watch=s,this.times=t.sampleTimes;const a=i.pitchShare??1;this.aimed=[];for(const c of this.times){const l=t.bearingAt(c,i.target),h=this.aimed[this.aimed.length-1];this.aimed.push(h===void 0?l:h+Qe.signed(l-h))}this.pitched=this.times.map(c=>r(c)*a)}static STEP_MS=250;static DENSE_MS=50;static SETTLED_MS=700;static TURN_S=.4;static TURN_S_PER_DEG=.5/150;static ROAD_PITCH_DEG=-1;static SHOULDER={x:-.08,y:0,z:-.07};static TWIST_FROM_DEG=60;aimed;pitched;times;poses(t,e){const i=[];for(let u=t;u<e;u+=Qe.STEP_MS)i.push(u);i.push(e);const n=new Map(i.map(u=>{const d=this.sample(u);return[u,Qe.signed(d.headingDeg-d.roadDeg)]})),s=u=>n.get(i.reduce((d,f)=>Math.abs(f-u)<Math.abs(d-u)?f:d)),r=this.schedule(s,e),a=this.watch?.t,c=r.map(([u,d],f)=>{if(f===0)return 0;if(u===a&&this.lean)return this.lean.params.turnS;const p=this.sample(u);return Qe.turnS(this.target(r[f-1][1],p),this.target(d,p))}),l=new Set(i),h=r.map(([u],d)=>[u,c[d]]);this.lean&&h.push([this.lean.t,this.lean.params.turnS],[this.lean.t+this.lean.params.holdS*1e3,this.lean.params.turnS]);for(const[u,d]of h){const f=Math.round(u+d*1e3+Qe.SETTLED_MS)+Qe.DENSE_MS;for(let p=Math.round(u);p<f;p+=Qe.DENSE_MS)p>=t&&p<=e&&l.add(p)}return[...l].sort((u,d)=>u-d).map(u=>{const d=this.sample(u),[f,p]=this.gaze(r,c,d),m=this.drive.stateAt(u);return{t:u,headingDeg:f,pitchDeg:p,eye:this.eyeAt(u,Qe.signed(f-d.roadDeg)),roadDeg:m.roadDeg,lat:m.lat,lng:m.lng}})}schedule(t,e){const i=[],n=this.lookAhead,s=this.watch?.t??e;let r=0;for(;r<s;){if(Math.abs(t(r))<=n.glanceBeyondDeg){(i.length===0||i[i.length-1][1]!=="watch")&&i.push([r,"watch"]),r+=Qe.STEP_MS;continue}if(i.push([r,"glance"]),r+=n.glanceS*1e3,r>=s)break;i.push([r,"road"]),r+=n.roadS*1e3}if(!this.watch)return i;const a=this.watch.params;r=s,i.push([r,"mirror"]),r+=a.firstS*1e3;let c=0;for(;r<e;){const l=r<a.glancesUntil&&c%2===0?"glance":"road";i.push([r,l]),r+=(l==="glance"?a.glanceS:a.roadS)*1e3,i.push([r,"mirror"]),r+=a.mirrorS*1e3,c++}return i}sample(t){const e=this.times,i=e.length-2;let n=0;for(;n<i&&e[n+1]<t;)n++;const s=(t-e[n])/(e[n+1]-e[n]),r=a=>[n>0?a[n-1]:2*a[n]-a[n+1],a[n],a[n+1],n+2<a.length?a[n+2]:2*a[n+1]-a[n]];return{t,roadDeg:this.drive.stateAt(t).roadDeg,headingDeg:(oi.catmull(r(this.aimed),s)%360+360)%360,pitchDeg:oi.catmull(r(this.pitched),s),eye:this.eyeAt(t,0)}}target(t,e){const{roadDeg:i,headingDeg:n,pitchDeg:s,eye:r}=e;if(t==="glance")return[n,s];if(t==="watch"){const u=Qe.signed(n-i),d=this.lookAhead.keepDeg,f=u-d*Math.tanh(u/d),p=u?f/u:0;return[Qe.normalized(i+f),Qe.ROAD_PITCH_DEG+(s-Qe.ROAD_PITCH_DEG)*p]}if(t==="road"||!this.watch)return[i,Qe.ROAD_PITCH_DEG];const a=this.watch.params.mirror,c={x:a.x-r.x,y:a.y-r.y,z:a.z-r.z},l=Math.atan2(-c.x,-c.z)*180/Math.PI,h=Math.atan2(c.y,Math.hypot(c.x,c.z))*180/Math.PI;return[Qe.normalized(i-l),h]}gaze(t,e,i,n){const s=i.t;let r=n??0;if(n===void 0&&s>=t[0][0])for(let g=0;g<t.length;g++)t[g][0]<=s&&(r=g);const[a,c]=this.target(t[r][1],i);if(r===0)return[a,c];const l=e[r]*1e3,h=s-t[r][0];if(h>l+Qe.SETTLED_MS)return[a,c];const[u,d]=this.gaze(t,e,i,r-1);if(h<l){const g=h/l,v=-2*g**3+3*g*g+(g**3-g*g)*vn.ARRIVAL;return[Qe.normalized(u+Qe.signed(a-u)*v),d+(c-d)*v]}const f=Qe.signed(a-u),p=h-l,m=vn.ARRIVAL/l*p*Math.exp(-p/Math.min(vn.SETTLE_MS,.4*l));return[Qe.normalized(a+f*m),c+(c-d)*m]}leanAt(t){if(!this.lean)return 0;const{holdS:e,turnS:i}=this.lean.params,n=(t-this.lean.t)/1e3;return n<0||n>e+i?0:Qe.smooth(Math.min(1,n/i,(e+i-n)/i))}eyeAt(t,e){const i=this.leanAt(t),n=this.lean?.params.offsetM??{x:0,y:0,z:0},s=Qe.smooth((Math.abs(e)-Qe.TWIST_FROM_DEG)/(180-Qe.TWIST_FROM_DEG)),r=Qe.SHOULDER;return{x:this.eye.x+n.x*i+r.x*s,y:this.eye.y+n.y*i+r.y*s,z:this.eye.z+n.z*i+r.z*s}}static turnS(t,e){return Qe.TURN_S+Qe.TURN_S_PER_DEG*Math.hypot(Qe.signed(e[0]-t[0]),e[1]-t[1])}static smooth(t){const e=Math.min(1,Math.max(0,t));return e*e*e*(10-15*e+6*e*e)}static signed(t){return((t+540)%360+360)%360-180}static normalized(t){return(t%360+360)%360}}const hm=Math.PI/180;class Gt{constructor(t,e,i){this.body=t,this.ground=e,this.eyeAt=i;const n=[...t.track].sort((s,r)=>s.t-r.t);this.keys=this.place(n,i);for(const s of n)Gt.collect(this.motionKeys,s.t,s.motions),Gt.collect(this.turnKeys,s.t,s.turns),Gt.collect(this.lightKeys,s.t,s.lights)}static EYE_HEIGHT_M=1.6;static MAX_RANGE_M=3e4;static DEFAULT_SIZE={widthM:1,lengthM:1,heightM:1};static DEFAULT_APPEARANCE={color:"#c8c8c8",albedo:.5,luminanceCdM2:0,transparency:0,haloScale:1};keys;motionKeys=new Map;turnKeys=new Map;lightKeys=new Map;static collect(t,e,i){for(const[n,s]of Object.entries(i??{})){const r=t.get(n)??[];r.push({t:e,value:s}),t.set(n,r)}}motionsAt(t){return Gt.channelsAt(this.motionKeys,t,0)}lightsAt(t){return this.lightKeys.size>0?Gt.channelsAt(this.lightKeys,t,void 0):void 0}static channelsAt(t,e,i){const n={};for(const[s,r]of t){let a=r.length-1;for(;a>=0&&r[a].t>e;)a--;if(a<0){i!==void 0&&(n[s]=i);continue}const c=r[a],l=r[Math.min(a+1,r.length-1)],h=l===c||l.t===c.t?0:Math.min(1,(e-c.t)/(l.t-c.t));n[s]=Gt.lerp(c.value,l.value,h)}return n}static eyeOf(t,e,i){const n=ke(t,0),s=ke(t,e),a=n?.lat!==void 0&&n.lng!==void 0&&s?.lat!==void 0&&s.lng!==void 0?se(s.lat,s.lng,n.lat,n.lng):void 0,c=a?a.x:0,l=a?-a.z:0;return{eastM:c,northM:l,upM:i.heightAt(c,l)+Gt.EYE_HEIGHT_M+(s?.elevationM??0),headingDeg:s?.headingDeg}}static lineOfSightMeetsGround(t,e,i,n){const s=Gt.directionOf(e,i),r=l=>t.upM+s.upM*l-n.heightAt(t.eastM+s.eastM*l,t.northM+s.northM*l);let a=0,c=0;for(;c<Gt.MAX_RANGE_M;){if(c=a+Math.max(.5,a*.01),r(c)<=0){for(let l=0;l<30;l++){const h=(a+c)/2;r(h)<=0?c=h:a=h}return c}a=c}}static directionOf(t,e){const i=t*hm,n=e*hm;return{eastM:Math.sin(i)*Math.cos(n),northM:Math.cos(i)*Math.cos(n),upM:Math.sin(n)}}at(t){const e=this.keys;if(e.length===0||t<e[0].t)return;let i=0,n=e.length-1;for(;i<n;){const m=i+n+1>>1;e[m].t>t?n=m-1:i=m}const s=i,r=e[s];if(!r.present)return;const a=e[Math.min(s+1,e.length-1)],c=a===r||a.t===r.t?0:Math.min(1,(t-r.t)/(a.t-r.t)),l=this.body.withObserver&&r.carried&&a.carried?this.eyeAt(t):void 0,h=l?l.eastM+Gt.lerp(r.carried.eastM,a.carried.eastM,c):Gt.lerp(r.eastM,a.eastM,c),u=l?l.northM+Gt.lerp(r.carried.northM,a.carried.northM,c):Gt.lerp(r.northM,a.northM,c),d={widthM:Gt.lerp(r.sizeM.widthM,a.sizeM.widthM,c),lengthM:Gt.lerp(r.sizeM.lengthM,a.sizeM.lengthM,c),heightM:Gt.lerp(r.sizeM.heightM,a.sizeM.heightM,c)},f={headingDeg:Gt.lerpAngle(r.attitude.headingDeg,a.attitude.headingDeg,c),pitchDeg:Gt.lerp(r.attitude.pitchDeg,a.attitude.pitchDeg,c),rollDeg:Gt.lerp(r.attitude.rollDeg,a.attitude.rollDeg,c)};let p;if(l)p=l.upM+Gt.lerp(r.carried.upM,a.carried.upM,c);else if("aboveGroundM"in r.vertical&&"aboveGroundM"in a.vertical){const m=Gt.lerp(r.vertical.aboveGroundM,a.vertical.aboveGroundM,c);p=this.groundUnderFootprint(h,u,d,f.headingDeg)+m+d.heightM/2}else p=Gt.lerp(this.centreUpOf(r),this.centreUpOf(a),c);return{id:this.body.id,model:this.body.model,modelParameters:this.body.modelParameters,flicker:this.body.flicker,explains:this.body.explains??[],outlineNode:this.body.outlineNode,eastM:h,northM:u,upM:p,sizeM:d,attitude:f,appearance:{color:Gt.lerpColor(r.appearance.color,a.appearance.color,c),albedo:Gt.lerp(r.appearance.albedo,a.appearance.albedo,c),luminanceCdM2:Gt.lerp(r.appearance.luminanceCdM2,a.appearance.luminanceCdM2,c),transparency:Gt.lerp(r.appearance.transparency,a.appearance.transparency,c),haloScale:Gt.lerp(r.appearance.haloScale,a.appearance.haloScale,c)},flame:Gt.flameBetween(r.flame,a.flame,c),motions:this.motionsAt(t),...this.turnKeys.size>0?{turns:Gt.channelsAt(this.turnKeys,t,0)}:{},lights:this.lightsAt(t),throwsFlame:this.body.track.some(m=>m.flame!==void 0&&m.flame.luminanceCdM2>0)}}static flameBetween(t,e,i){if(!t||t.luminanceCdM2<=0)return i>=1&&e&&e.luminanceCdM2>0?e:void 0;const n=t,s=e??t,r={...i<1?n:s,lengthM:Gt.lerp(n.lengthM,s.lengthM,i),widthM:Gt.lerp(n.widthM,s.widthM,i),luminanceCdM2:Gt.lerp(n.luminanceCdM2,s.luminanceCdM2,i)};return r.luminanceCdM2>0?r:void 0}centreUpOf(t){if(!("upM"in t.vertical))return this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.vertical.aboveGroundM+t.sizeM.heightM/2;const e=t.vertical.fromGround;if(!e)return t.vertical.upM;const i=t.vertical.upM+this.ground.heightAt(e.eastM,e.northM);return Math.max(i,this.groundUnderFootprint(t.eastM,t.northM,t.sizeM,t.attitude.headingDeg)+t.sizeM.heightM/2)}groundUnderFootprint(t,e,i,n){const s=n*hm,r={eastM:Math.cos(s),northM:-Math.sin(s)},a={eastM:Math.sin(s),northM:Math.cos(s)};let c=this.ground.heightAt(t,e);for(const[l,h]of[[-1,-1],[1,-1],[-1,1],[1,1]]){const u=l*i.widthM/2,d=h*i.lengthM/2;c=Math.max(c,this.ground.heightAt(t+r.eastM*u+a.eastM*d,e+r.northM*u+a.northM*d))}return c}place(t,e){const i=[];let n;for(const s of t){const r=s.sizeM??n?.sizeM??Gt.DEFAULT_SIZE,a={headingDeg:s.attitude?.headingDeg??n?.attitude.headingDeg??0,pitchDeg:s.attitude?.pitchDeg??n?.attitude.pitchDeg??0,rollDeg:s.attitude?.rollDeg??n?.attitude.rollDeg??0},c={color:s.appearance?.color??n?.appearance.color??Gt.DEFAULT_APPEARANCE.color,albedo:s.appearance?.albedo??n?.appearance.albedo??Gt.DEFAULT_APPEARANCE.albedo,luminanceCdM2:s.appearance?.luminanceCdM2??n?.appearance.luminanceCdM2??Gt.DEFAULT_APPEARANCE.luminanceCdM2,transparency:s.appearance?.transparency??n?.appearance.transparency??Gt.DEFAULT_APPEARANCE.transparency,haloScale:s.appearance?.haloScale??n?.appearance.haloScale??Gt.DEFAULT_APPEARANCE.haloScale},l=this.positionOf(s,r,e)??(n&&{eastM:n.eastM,northM:n.northM,vertical:this.verticalOf(s,r)??n.vertical});if(!l)continue;const h=s.flame??n?.flame,u=s.present??n?.present??!0;if(n={t:s.t,...l,sizeM:r,attitude:a,appearance:c,flame:h,present:u},this.body.withObserver&&s.azimuthDeg!==void 0&&s.distanceM!==void 0){const d=Gt.directionOf(s.azimuthDeg,s.altitudeDeg??0);n.carried={eastM:d.eastM*s.distanceM,northM:d.northM*s.distanceM,upM:d.upM*s.distanceM}}i.push(n)}return i}verticalOf(t,e){if(t.onGround)return{aboveGroundM:0};if(t.altitudeAboveGroundM!==void 0)return{aboveGroundM:t.altitudeAboveGroundM};if(t.altitudeM!==void 0)return{upM:t.altitudeM+e.heightM/2,fromGround:this.body.altitudeFrom}}positionOf(t,e,i){if(t.eastM!==void 0&&t.northM!==void 0)return{eastM:t.eastM,northM:t.northM,vertical:this.verticalOf(t,e)??{aboveGroundM:0}};if(t.azimuthDeg===void 0||t.altitudeDeg===void 0)return;const n=i(t.t);if(!n)return;const s=t.distanceM??(t.onGround?Gt.lineOfSightMeetsGround(n,t.azimuthDeg,t.altitudeDeg,this.ground):void 0);if(s===void 0)return;const r=Gt.directionOf(t.azimuthDeg,t.altitudeDeg),a=n.eastM+r.eastM*s,c=n.northM+r.northM*s;return{eastM:a,northM:c,vertical:this.verticalOf(t,e)??{upM:n.upM+r.upM*s}}}static lerp(t,e,i){return t+(e-t)*i}static lerpColor(t,e,i){const n=Gt.rgbOf(t),s=Gt.rgbOf(e);return!n||!s?i<1?t:e:"#"+n.map((r,a)=>Math.round(Gt.lerp(r,s[a],i)).toString(16).padStart(2,"0")).join("")}static rgbOf(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t);if(!e)return;const i=e[1].length===3?e[1].replace(/./g,"$&$&"):e[1];return[0,2,4].map(n=>parseInt(i.slice(n,n+2),16))}static lerpAngle(t,e,i){const n=((e-t)%360+540)%360-180;return((t+n*i)%360+360)%360}}class Ts{static ANONYMOUS_OBSERVER="observer";static observerId(t){return t.observer?.id??Ts.ANONYMOUS_OBSERVER}static shapeIds(t){const e=new Set(t.timeline.sourceIds);for(const i of t.events??[])if(i.eventType==="appearance")for(const n of i.params?.parts??[])e.add(n.sourceId);return[...e]}static ids(t){const e=new Map,i=(n,s)=>{n!==void 0&&e.set(n,[...e.get(n)??[],s])};i(Ts.observerId(t),"observer");for(const n of Ts.shapeIds(t))i(n,"shape");for(const n of t.timeline.allGroups)i(n.id,"group");for(const n of t.interpretation?.bodies??[])i(n.id,"body");for(const n of t.decor)i(n.id,"decor");return e}static kindOf(t,e){if(e===void 0)return;const i=Ts.ids(t).get(e);return i?.length===1?i[0]:void 0}static partOf(t){const e=t?.indexOf("/")??-1;if(!(t===void 0||e<=0||e===t.length-1))return{element:t.slice(0,e),part:t.slice(e+1)}}static hasPart(t,e,i){if(e==="body")return!0;if(e!=="decor")return!1;const n=t.decor.find(s=>s.id===i.element);return!!(n?.lights?.some(s=>s.id===i.part)||n?.groups?.some(s=>s.id===i.part))}static isObserver(t,e){return e.who===Ts.observerId(t)}static isPhenomenon(t,e){return e.who===void 0?!1:t.timeline.groupOf(e.who)!==void 0||Ts.shapeIds(t).includes(e.who)}static within(t,e){const i=new Set([e]),n=s=>{for(const r of t.timeline.groupOf(s)?.members??[])i.has(r)||(i.add(r),n(r))};return n(e),i}static renamed(t,e,i){if(e!==i)for(const n of t.events??[])n.who===e&&(n.who=i)}static issues(t){const e=[],i=Ts.ids(t);for(const[n,s]of i)s.length>1&&e.push({kind:"duplicate-id",id:n,path:s.join(", ")});return(t.events??[]).forEach((n,s)=>{const r=Ts.partOf(n.who);r&&i.get(r.element)?.length===1&&Ts.hasPart(t,i.get(r.element)[0],r)||(n.who===void 0||!i.has(n.who))&&e.push({kind:"unknown-who",id:n.who??"",path:`events.${s}.who`})}),e}}class we{constructor(t,e,i){this.travel=t;const n=t.params,s=t.until??i;let r=we.unit(n.from),a=we.towards(r,we.unit(n.towards));const c=e.map(h=>{const u=h.params,d=u.side==="left"?1:-1;return{from:h.t,to:h.until??h.t,radians:u.byDeg*Math.PI/180*(u.seenFrom==="craft"?-d:d)}}),l=we.STEP_MS;for(let h=t.t;h<=s;h+=l){this.directions.push(we.direction(r));for(const f of c){const p=f.to-f.from;if(p<=0)continue;const m=f.radians*(we.smooth((h+l-f.from)/p)-we.smooth((h-f.from)/p));m&&(a=we.add(we.scale(a,Math.cos(m)),we.scale(we.cross(a,r),Math.sin(m))))}const u=we.speedAt(n.speeds,h)*l/1e3*Math.PI/180,d=we.add(we.scale(r,Math.cos(u)),we.scale(a,Math.sin(u)));a=we.add(we.scale(a,Math.cos(u)),we.scale(r,-Math.sin(u))),r=d}}static STEP_MS=5;directions=[];at(t){const e=Math.round((t-this.travel.t)/we.STEP_MS);return this.directions[Math.max(0,Math.min(this.directions.length-1,e))]}sizeAt(t){const e=this.travel.params;return e.sizeBy!=="altitude"?e.sizeDeg:e.sizeDeg*Math.max(.1,Math.sin(Math.max(this.at(t).altitudeDeg,1)*Math.PI/180))}static speedAt(t,e){if(t.length===0)return 0;if(e<=t[0].t)return t[0].degPerS;for(let i=1;i<t.length;i++){const n=t[i-1],s=t[i];if(s.step&&e<s.t)return n.degPerS;if(e<s.t)return n.degPerS+(s.degPerS-n.degPerS)*we.smooth((e-n.t)/(s.t-n.t))}return t[t.length-1].degPerS}static smooth(t){const e=Math.max(0,Math.min(1,t));return e*e*(3-2*e)}static unit(t){const e=t.azimuthDeg*Math.PI/180,i=t.altitudeDeg*Math.PI/180;return[Math.cos(i)*Math.sin(e),Math.cos(i)*Math.cos(e),Math.sin(i)]}static direction(t){return{azimuthDeg:(Math.atan2(t[0],t[1])*180/Math.PI%360+360)%360,altitudeDeg:Math.asin(Math.max(-1,Math.min(1,t[2])))*180/Math.PI}}static towards(t,e){const i=we.add(e,we.scale(t,-we.dot(t,e))),n=Math.hypot(...i)||1;return we.scale(i,1/n)}static toScreen(t,e,i){const[n,s,r]=we.basis(e,i),a=we.unit(t),c=we.dot(a,n);return[we.dot(a,s)/c,we.dot(a,r)/c]}static fromScreen(t,e,i,n){const[s,r,a]=we.basis(i,n),c=[s[0]+t*r[0]+e*a[0],s[1]+t*r[1]+e*a[1],s[2]+t*r[2]+e*a[2]],l=Math.hypot(...c);return we.direction([c[0]/l,c[1]/l,c[2]/l])}static basis(t,e){const i=t*Math.PI/180,n=e*Math.PI/180;return[[Math.cos(n)*Math.sin(i),Math.cos(n)*Math.cos(i),Math.sin(n)],[Math.cos(i),-Math.sin(i),0],[-Math.sin(n)*Math.sin(i),-Math.sin(n)*Math.cos(i),Math.cos(n)]]}static dot(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}static cross(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}static add(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}static scale(t,e){return[t[0]*e,t[1]*e,t[2]*e]}}class So{constructor(t,e){this.sighting=t,this.events=e}static FOV_DEG=60;keyframes(){const t=this.events.filter(c=>c.eventType==="look").sort((c,l)=>c.t-l.t),e=this.events.filter(c=>c.eventType==="walk").sort((c,l)=>c.t-l.t),i=this.events.filter(c=>c.eventType==="follow").sort((c,l)=>c.t-l.t);if(t.length===0&&e.length===0)return[];const n=new Set([0]);for(const c of[...t,...e,...i])n.add(c.t),c.until!==void 0&&n.add(c.until);const s=c=>{let l;for(const h of e){const u=h.params;if(c<=h.t)return l??u.from;if(h.until===void 0||c>=h.until)l=u.to;else return}return l??this.sighting.event.place?.[0]},r=c=>([...t].reverse().find(h=>h.t<=c)??t[0])?.params??{headingDeg:0,pitchDeg:0},a=[...n].sort((c,l)=>c-l).flatMap(c=>{const l=s(c);if(!l)return[];const h=r(c);return[{t:c,pose:So.pose(l,h.headingDeg,h.pitchDeg,h.fovDeg)}]});for(const c of a)this.sighting.observerTrack.addKeyframe(c.t,c.pose);for(const c of i)this.follow(c,r(c.t));return[...this.sighting.observerTrack.allKeyframes]}follow(t,e){const i=t.params;if(this.followSky(t,e))return;const n=this.sighting.interpretation?.bodies.find(h=>h.id===i.target);if(!n)return;const s={heightAt:()=>0},r=h=>Gt.eyeOf(this.sighting,h,s),a=new Gt(n,s,r),c=t.until??1/0;let l=e;for(const h of n.track){if(h.t<=t.t||h.t>=c)continue;const u=a.at(h.t),d=r(h.t),f=this.sighting.observerTrack.getInterpolatedPoseAt(h.t);if(!u||!d||!f)continue;const p=u.eastM-d.eastM,m=u.northM-d.northM,g=u.upM-d.upM;l={headingDeg:(Math.atan2(p,m)*180/Math.PI%360+360)%360,pitchDeg:Math.atan2(g,Math.hypot(p,m))*180/Math.PI},this.sighting.observerTrack.addKeyframe(h.t,{...f,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}if(Number.isFinite(c)){const h=this.sighting.observerTrack.getInterpolatedPoseAt(c);h&&this.sighting.observerTrack.addKeyframe(c,{...h,headingDeg:l.headingDeg,pitchDeg:l.pitchDeg})}}static FOLLOW_SKY_MS=25;static CATCH_UP_MS=900;static OVERHEAD_DEG=78;static HIGHEST_PITCH_DEG=88;followSky(t,e){const i=t.params,n=Ts.within(this.sighting,i.target),s=this.sighting.events??[],r=s.find(v=>v.eventType==="travel"&&v.who!==void 0&&n.has(v.who));if(!r)return!1;const a=this.sighting.event.durationSeconds!==void 0?this.sighting.event.durationSeconds*1e3:r.until??t.t,c=new we(r,s.filter(v=>v.eventType==="turn"&&v.who!==void 0&&n.has(v.who)),a),l=t.until??a,h=(i.lagS??0)*1e3,u=(i.reactionS??0)*1e3,d=[],f=this.sighting.sampleMs??So.FOLLOW_SKY_MS;for(let v=t.t;v<=l;v+=f)d.push(v);const p=d.map(v=>c.at(Math.max(r.t,v-h))),m=p.map(v=>v.azimuthDeg),g=p.flatMap((v,M)=>v.altitudeDeg>So.OVERHEAD_DEG?[M]:[]);if(g.length>0){const v=Math.max(0,g[0]-1),M=Math.min(d.length-1,g[g.length-1]+1),x=m[v],y=(m[M]-x+540)%360-180;for(let w=v;w<=M;w++)m[w]=((x+y*we.smooth((w-v)/(M-v)))%360+360)%360}return d.forEach((v,M)=>{const x=we.smooth((v-t.t-u)/So.CATCH_UP_MS),y=(m[M]-e.headingDeg+540)%360-180,w=Math.min(p[M].altitudeDeg,So.HIGHEST_PITCH_DEG),S=this.sighting.observerTrack.getInterpolatedPoseAt(v)??this.sighting.observerTrack.getLatestPoseAt(v);if(!S)return;const E=b=>Math.round(b*100)/100;this.sighting.observerTrack.addKeyframe(v,{...S,headingDeg:E(((e.headingDeg+y*x)%360+360)%360),pitchDeg:E(e.pitchDeg+(w-e.pitchDeg)*x)})}),!0}static pose(t,e,i,n=So.FOV_DEG){return{lat:t.lat,lng:t.lng,elevationM:0,headingDeg:e,pitchDeg:i,fovDeg:n}}}class Bo{constructor(t,e,i,n){this.body=t,this.events=e,this.endMs=i,this.sampleMs=n}static SAMPLE_MS=250;track(){const t=new Map,e=l=>{const h=t.get(l.t);t.set(l.t,h?{...h,...l,motions:{...h.motions,...l.motions},...h.turns||l.turns?{turns:{...h.turns,...l.turns}}:{},...h.lights||l.lights?{lights:{...h.lights,...l.lights}}:{}}:l)};for(const l of this.body.track)e({...l});const i=[...this.events].sort((l,h)=>l.t-h.t),n=new Map,s=new Map,r=new Map;let a=0;for(const l of this.body.track){for(const[h,u]of Object.entries(l.motions??{}))n.set(h,u);for(const[h,u]of Object.entries(l.turns??{}))s.set(h,u);for(const[h,u]of Object.entries(l.lights??{}))r.set(h,u);l.attitude?.headingDeg!==void 0&&(a=l.attitude.headingDeg)}let c=this.startPlace();for(const l of i){const h=Bo.partOf(l.who,this.body.id);if(h!==void 0&&(l.eventType==="light"||l.eventType==="blink")){for(const u of this.leavesOf(h))this.switchLight(u,l,r,e,d=>t.get(d)?.lights?.[u]);continue}if(h!==void 0){if(l.eventType!=="spin"&&l.eventType!=="turn")continue;const u=s.get(h)??0,d=l.until??l.t,f=l.eventType==="spin"?u+360*l.params.turnsPerS*(d-l.t)/1e3:l.params.headingDeg;e({t:l.t,turns:{[h]:u}}),e({t:d,turns:{[h]:f}}),s.set(h,f);continue}if((l.eventType==="motion"||l.eventType==="spin")&&l.params?.motion){const u=l.params,d=u.motion,f=n.get(d)??0,p=l.until??l.t,m=l.eventType==="motion"?u.to:f+u.turnsPerS*(p-l.t)/1e3;e({t:l.t,motions:{[d]:f}}),e({t:p,motions:{[d]:m}}),n.set(d,m)}else if(l.eventType==="rise"&&c){const u=l.params,d=l.until??l.t,f=u.angleDeg*Math.PI/180,p=(u.headingDeg??0)*Math.PI/180,m=c,g=v=>{const M=u.stops===!1?v*v:v*v*v*(10-15*v+6*v*v),x=u.distanceM*M;return{eastM:m.eastM+x*Math.sin(f)*Math.sin(p),northM:m.northM+x*Math.sin(f)*Math.cos(p),aboveGroundM:m.aboveGroundM+x*Math.cos(f)}};for(let v=l.t;v<d;v+=this.sampleMs??Bo.SAMPLE_MS)e(Bo.key(v,g((v-l.t)/(d-l.t))));c=g(1),e(Bo.key(d,c))}else if(l.eventType==="turn"){const u=l.params;e({t:l.t,attitude:{headingDeg:a}}),e({t:l.until??l.t,attitude:{headingDeg:u.headingDeg}}),a=u.headingDeg}else l.eventType==="vanish"&&e({t:l.t,present:!1})}return[...t.values()].sort((l,h)=>l.t-h.t)}static ride(t,e,i){const n=e.params,s=e.until??1/0,r=new Map(t.track.map(a=>[a.t,{...a}]));for(const a of i.track){if(a.t<e.t||a.t>s||(a.present===!1&&r.set(a.t,{...r.get(a.t),t:a.t,present:!1}),a.eastM===void 0||a.northM===void 0))continue;const c=(a.onGround?0:a.altitudeAboveGroundM??0)+n.aboveM;r.set(a.t,{...r.get(a.t),t:a.t,eastM:a.eastM,northM:a.northM,altitudeAboveGroundM:c})}return[...r.values()].sort((a,c)=>a.t-c.t)}switchLight(t,e,i,n,s){const r=i.get(t)??0,a=e.eventType==="light"?e.until:e.until??this.endMs,c=(l,h)=>n({t:l,lights:{[t]:h}});if(e.t>0&&s(e.t-1)===void 0&&c(e.t-1,r),e.eventType==="light"){const l=e.params.cdM2;if(c(e.t,l),a===void 0){i.set(t,l);return}c(a-1,l)}else{const l=e.params;if(a===void 0)return;const h=l.cdM2??r;let u=e.t,d=!0;for(;u<a;){const f=Math.min(Math.round(u+1e3*(d?l.onS:l.offS)),a);if(f<=u)break;c(u,d?h:0),c(f-1,d?h:0),u=f,d=!d}}c(a,r),i.set(t,r)}leavesOf(t,e=new Set){const i=this.body.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}startPlace(){const t=this.body.track.find(e=>e.eastM!==void 0&&e.northM!==void 0);return t&&{eastM:t.eastM,northM:t.northM,aboveGroundM:t.onGround?0:t.altitudeAboveGroundM??0}}static key(t,e){return e.aboveGroundM<=0?{t,eastM:e.eastM,northM:e.northM,onGround:!0}:{t,eastM:e.eastM,northM:e.northM,altitudeAboveGroundM:e.aboveGroundM}}}class Sd{constructor(t,e,i){this.object=t,this.events=e,this.endMs=i}lights(){const t=new Map,e=[...this.events].sort((i,n)=>i.t-n.t);for(const i of e){const n=Sd.partOf(i.who,this.object.id);if(!(n===void 0||i.eventType!=="light"&&i.eventType!=="blink"))for(const s of this.leavesOf(n)){const r=this.object.lights?.find(a=>a.id===s);r&&t.set(s,this.switched(r,t.get(s)??[],i))}}return(this.object.lights??[]).map(i=>t.has(i.id)?{...i,keyframes:t.get(i.id)}:i)}switched(t,e,i){const n=Sd.stateAt(t,e,i.t),s=i.eventType==="light"?i.until:i.until??this.endMs,r=[];if(i.eventType==="light")r.push({t:i.t,intensity:i.params.intensity,pattern:n.pattern});else{const c=i.params,l=c.onS+c.offS;if(s===void 0||l<=0)return e;const h=l*1e3,u=(-i.t/h%1+1)%1,d={kind:"flash",perMinute:60/l,dutyCycle:c.onS/l,...u?{phase:u}:{}},f=c.intensity??(n.intensity>0?n.intensity:t.intensity??1);r.push({t:i.t,intensity:f,pattern:d})}s!==void 0&&r.push({t:s,intensity:n.intensity,pattern:n.pattern});const a=new Set(r.map(c=>c.t));return[...e.filter(c=>!a.has(c.t)),...r].sort((c,l)=>c.t-l.t)}static stateAt(t,e,i){const n=e.filter(s=>s.t<=i).at(-1);return{intensity:n?.intensity??t.intensity??1,pattern:n?.pattern??t.pattern}}leavesOf(t,e=new Set){const i=this.object.groups?.find(n=>n.id===t);return!i||e.has(t)?[t]:(e.add(t),i.members.flatMap(n=>this.leavesOf(n,e)))}static partOf(t,e){return t!==void 0&&t.startsWith(`${e}/`)&&t.length>e.length+1?t.slice(e.length+1):void 0}}class fh{static observer(t){const e=t.allKeyframes,i=e.map(s=>fh.said(s.pose)),n=e.filter((s,r)=>r>0&&r<e.length-1&&i[r]===i[r-1]&&i[r]===i[r+1]);for(const s of n)t.removeKeyframeAt(s.t)}static said(t){return JSON.stringify(t,(e,i)=>typeof i=="number"?Math.round(i*1e10)/1e10:i)}static timeline(t){const e=new Map;for(const i of t.allKeyframes)for(const n of i.shapes){const s=e.get(n.sourceId)??[];s.push({t:i.t,said:fh.said(n.shape)}),e.set(n.sourceId,s)}for(const[i,n]of e){const s=n.filter((r,a)=>a>0&&a<n.length-1&&r.said===n[a-1].said&&r.said===n[a+1].said);for(const r of s)t.removeShapeAt(r.t,i)}}}class G0{constructor(t,e){this.end=e;const i=[...t].sort((n,s)=>n.t-s.t);this.rolls=i.filter(n=>n.eventType==="roll"),this.vibrations=i.filter(n=>n.eventType==="vibrate"),this.spirals=i.filter(n=>n.eventType==="spiral")}static SPIRAL_OPENS=4;static THINNEST=.08;rolls;vibrations;spirals;rollAt(t){let e=0,i=0;for(const n of this.rolls){if(t<n.t)break;const s=n.params,r=this.progress(n,t);i=e+(s.toDeg-e)*(s.andBack?Math.sin(Math.PI*we.smooth(r)):we.smooth(r)),s.andBack||(e=s.toDeg)}for(const n of this.spirals){if(t<n.t)break;const s=n.params;i=e+(s.clockwise?1:-1)*s.rollDeg*this.progress(n,t)}return i}acrossShareAt(t){return Math.max(G0.THINNEST,Math.abs(Math.cos(this.rollAt(t)*Math.PI/180)))}sidewaysAt(t,e){let i=0;for(const n of this.vibrations){const s=n.until??this.end;if(t<n.t||t>=s)continue;const r=n.params,a=we.smooth((t-n.t)/(r.riseS*1e3))*Math.max(0,1-(t-n.t)/(s-n.t));i+=r.amplitudeShare*e*a*Math.sin(2*Math.PI*r.hz*(t-n.t)/1e3)}return i}spiralAt(t){const e=[...this.spirals].reverse().find(a=>a.t<=t);if(!e)return;const i=e.params,n=this.progress(e,t),s=Math.tan(i.radiusDeg*Math.PI/180)*we.smooth(n*G0.SPIRAL_OPENS)*(1-i.shrink*we.smooth(n)),r=-(i.clockwise?1:-1)*2*Math.PI*i.turns*n;return[s*(Math.cos(r)-1),s*Math.sin(r)]}progress(t,e){const i=t.until??this.end;return i<=t.t?1:Math.max(0,Math.min(1,(e-t.t)/(i-t.t)))}}class As{constructor(t,e,i,n){this.sighting=t,this.stand=e;const s=i.filter(a=>a.eventType==="appearance").sort((a,c)=>a.t-c.t);this.vanishAt=i.find(a=>a.eventType==="vanish")?.t;const r=this.vanishAt??n;this.path=e.eventType==="travel"?new we(e,i.filter(a=>a.eventType==="turn"),n):void 0,this.motion=this.path?new G0(i,e.until??n):void 0,this.looks=s.map((a,c)=>({t:a.t,until:a.until??s[c+1]?.t??r,parts:a.params.parts})),this.blinks=i.filter(a=>a.eventType==="blink").map(a=>({t:a.t,until:a.until??r,parts:a.who===void 0?[]:t.timeline.leavesOf(a.who),params:a.params}))}static SAMPLE_MS=2e3;static TRAVEL_SAMPLE_MS=25;static MOTION_MS=40;static SPIRAL_AHEAD_MS=20;static R=63710088e-1;looks;blinks;vanishAt;path;motion;timeline(){const t=new Map,e=(r,a)=>{const c=this.state(a,r);c&&(t.has(r)||t.set(r,new Map),t.get(r).set(a,c))},i=[...new Set(this.looks.flatMap(r=>r.parts.map(a=>a.sourceId)))];this.looks.forEach((r,a)=>{const c=this.looks[a+1];for(const l of i){if(!r.parts.some(d=>d.sourceId===l)){e(r.t,l),c?.parts.some(d=>d.sourceId===l)&&e(c.t-1,l);continue}const u=this.sighting.sampleMs??(this.path?As.TRAVEL_SAMPLE_MS:As.SAMPLE_MS);for(let d=r.t;d<r.until;d+=u)e(d,l);e(r.until-1,l)}});for(const r of this.blinks)for(const[a,c]of this.phases(r))for(const l of r.parts)e(a,l),e(c-1,l);if(this.vanishAt!==void 0)for(const r of i)e(this.vanishAt,r);const n=[...t.keys()].sort((r,a)=>r-a).map(r=>({t:r,shapes:[...t.get(r).values()]})),s=new Map;for(const r of n)for(const a of r.shapes){const c=a.shape.angle,l=s.get(a.sourceId);if(c===void 0)continue;const h=l===void 0?c:c+2*Math.PI*Math.round((l-c)/(2*Math.PI));a.shape.angle=Math.round(h*1e4)/1e4,s.set(a.sourceId,h)}return{keyframes:n,order:i,groups:[]}}phases(t){const e=[];let i=!0;for(let n=t.t;n<t.until;){const s=Math.min(n+(i?t.params.onS:t.params.offS)*1e3,t.until);e.push([n,s]),n=s,i=!i}return e}off(t,e){for(const i of this.blinks){if(e<i.t||e>=i.until||!i.parts.includes(t))continue;if(this.phases(i).findIndex(([s,r])=>e>=s&&e<r)%2===1)return i.params.off}}state(t,e){const i=[...this.looks].reverse().find(l=>l.t<=e)??this.looks[0],n=i?.parts.find(l=>l.sourceId===t),r=(n?i:this.looks.find(l=>l.t>e&&l.parts.some(h=>h.sourceId===t))??[...this.looks].reverse().find(l=>l.parts.some(h=>h.sourceId===t)))?.parts.find(l=>l.sourceId===t);if(!r)return;const a=!n||this.vanishAt!==void 0&&e>=this.vanishAt,c=a?void 0:this.off(t,e);return this.path?{sourceId:t,shape:this.onPath(r,e,c,a)}:{sourceId:t,shape:As.shape(r,this.geometry(e),c,a)}}onPath(t,e,i,n){const s=this.path,r=this.sighting.observerTrack.getInterpolatedPoseAt(e)??this.sighting.observerTrack.getLatestPoseAt(e),a=r?.headingDeg??0,c=r?.pitchDeg??0,l=this.motion,h=b=>we.toScreen(s.at(b),a,c),u=(b,A)=>{const _=Math.hypot(A[0]-b[0],A[1]-b[1])||1;return[(A[0]-b[0])/_,(A[1]-b[1])/_]};let d=h(e),[f,p]=u(h(e-As.MOTION_MS),h(e+As.MOTION_MS));const m=s.sizeAt(e),g=Math.tan(l.sidewaysAt(e,m)*Math.PI/180);d=[d[0]-g*p,d[1]+g*f];const v=l.spiralAt(e);if(v){const b=l.spiralAt(e+As.SPIRAL_AHEAD_MS),A=h(e),_=h(e+As.SPIRAL_AHEAD_MS);d=[d[0]+v[0],d[1]+v[1]],[f,p]=u([A[0]+v[0],A[1]+v[1]],[_[0]+b[0],_[1]+b[1]])}const M=l.acrossShareAt(e),x={...t,heightShare:(t.heightShare??t.widthShare)*M,...t.upShare===void 0?{}:{upShare:t.upShare*M}},y=Math.tan(m*(x.alongShare??0)*Math.PI/180),w=Math.tan(m*(x.upShare??0)*Math.PI/180),S=we.fromScreen(d[0]+y*f-w*p,d[1]+y*p+w*f,a,c),E=As.shape(x,{...S,sizeDeg:m},i,n,!0);return E.angle=Math.atan2(-p,f),E}geometry(t){const e=this.stand.params,i=this.sighting.observerTrack.getInterpolatedPoseAt(t)??this.sighting.observerTrack.getLatestPoseAt(t),n=i?.lat!==void 0&&i.lng!==void 0?{lat:i.lat,lng:i.lng}:this.sighting.event.place?.[0]??e.place;return As.seenFrom(e,n,t)}static seenFrom(t,e,i){const n=(t.place.lng-e.lng)*Math.PI/180*As.R*Math.cos(e.lat*Math.PI/180),s=(t.place.lat-e.lat)*Math.PI/180*As.R,r=Math.hypot(n,s),a=oi.linear(t.metres.map(({t:l,widthM:h,step:u})=>({t:l,value:h,step:u})),i),c=oi.linear(t.metres.map(({t:l,heightM:h,step:u})=>({t:l,value:h,step:u})),i);return{azimuthDeg:(Math.atan2(n,s)*180/Math.PI%360+360)%360,altitudeDeg:Math.atan2(c,r)*180/Math.PI,sizeDeg:2*Math.atan(a/(2*r))*180/Math.PI}}static shape(t,e,i,n,s=!1){const r=e.sizeDeg,a=Math.max(t.minWidthDeg??0,r*t.widthShare),c=t.kind==="oval"&&t.heightShare===void 0?a:Math.max(t.minHeightDeg??0,r*(t.heightShare??t.widthShare)),l=s?e.altitudeDeg:e.altitudeDeg+r*(t.upShare??0),h=s?e.azimuthDeg:e.azimuthDeg+r*(t.alongShare??0)/Math.cos(l*Math.PI/180),u=(p,m)=>Math.round(p*10**m)/10**m,d=t.kind==="polygon"?{kind:"polygon",bounds:{x:300,y:170,width:100,height:100*c/a},points:(t.points??[]).map(p=>({x:u(p.x*100,2),y:u(p.y*100*c/a,2)}))}:{kind:"oval",bounds:{x:320,y:180,width:2,height:2}};Object.assign(d,{color:i?.color??t.color,angle:0,transparency:n?1:i?.transparency??t.transparency??0,haloScale:t.halo??0,selected:!1,...t.blur===void 0?{}:{blur:t.blur},...t.title===void 0?{}:{title:t.title},angular:{widthDeg:u(a,4),heightDeg:u(c,4)},aim:{azimuthDeg:u((h%360+360)%360,3),altitudeDeg:u(l,3)}});const f=i&&"brightness"in i?i.brightness:t.brightness;return f!=null&&(d.brightness=n?0:f),d}}class Pe{static STANDING_EYE_M=1.6;static METERS_PER_DEGREE=111320;static expand(t){Pe.expandBodies(t),Pe.expandObserver(t),Pe.expandFlights(t),Pe.expandDecorLights(t),Pe.expandPhenomenon(t)}static expandDecorLights(t){for(const e of t.decor){if(!e.lights?.length||e.lights.some(s=>s.keyframes?.length))continue;const i=(t.events??[]).filter(s=>Sd.partOf(s.who,e.id)!==void 0);if(i.length===0)continue;const n=JSON.stringify(e.lights);e.lights=new Sd(e,i,Pe.endOf(t)).lights(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorLights={...t.eventsExpansion.decorLights,[e.id]:{stated:n,expanded:JSON.stringify(e.lights)}}}}static writtenLights(t,e,i){const n=t.eventsExpansion?.decorLights?.[e];return n&&JSON.stringify(i)===n.expanded?JSON.parse(n.stated):i}static expandPhenomenon(t){if(t.timeline.allKeyframes.length>0)return;const e=Pe.stands(t);for(const i of e){const n=Ts.within(t,i.who),s=(t.events??[]).filter(a=>a.who!==void 0&&n.has(a.who)),r=new As(t,i,s,i.until??Pe.endOf(t)).timeline();for(const a of Ud.fromJSON(r).allKeyframes)t.timeline.addKeyframe(a.t,a.shapes)}e.length!==0&&(fh.timeline(t.timeline),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.timelinePending=!0)}static stands(t){return(t.events??[]).filter(e=>(e.eventType==="stand"||e.eventType==="travel")&&Ts.isPhenomenon(t,e))}static shapesOf(t){const{groups:e,...i}=t.timeline.toJSON();return JSON.stringify(i)}static timelineWithoutShapes(t){const e=t.timeline.toJSON().groups??[];return e.length>0?{keyframes:[],groups:e}:{keyframes:[]}}static settle(t){t.eventsExpansion?.timelinePending&&(fn.toAngular(t),fn.toAim(t),t.eventsExpansion.timeline=Pe.shapesOf(t),t.eventsExpansion.timelinePending=!1)}static timelineIsExpanded(t){return t.eventsExpansion?.timeline!==void 0&&t.eventsExpansion.timeline===Pe.shapesOf(t)}static expandFlights(t){const e=t.observerTrack.allKeyframes[0]?.pose??t.event.place?.[0];if(e?.lat===void 0||e.lng===void 0)return;const i=Math.cos(e.lat*Math.PI/180);for(const n of t.events??[]){if(n.eventType!=="fly"||n.who===void 0)continue;const s=t.decor.find(m=>m.id===n.who);if(!s||s.track?.length)continue;const r=n.params,a=n.until??Pe.endOf(t),c=r.headingDeg*Math.PI/180,l=(r.from.lng-e.lng)*Math.PI/180*Pe.R*i,h=(r.from.lat-e.lat)*Math.PI/180*Pe.R,u=r.speeds.map(({t:m,kmh:g,step:v})=>({t:m,value:g/3.6,step:v})),d=r.heights.map(({t:m,altitudeM:g,step:v})=>({t:m,value:g,step:v})),f=m=>{const g=Math.sign(m-r.at.t)*Pe.FLY_STEP_MS;let v=0;for(let M=r.at.t;g!==0&&(g>0?M<m:M>m);M+=g){const x=g>0?Math.min(m,M+g):Math.max(m,M+g);v+=(oi.linear(u,M)+oi.linear(u,x))/2*(x-M)/1e3}return v},p=[];for(let m=n.t;m<=a;m+=oi.SAMPLE_MS){const g=r.at.metresBefore-f(m);p.push({t:m,eastM:l-Math.sin(c)*g,northM:h-Math.cos(c)*g,altitudeM:oi.linear(d,m),headingDeg:r.headingDeg})}s.track=p,s.eastM=p[0].eastM,s.northM=p[0].northM,s.headingDeg=r.headingDeg,t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.decorTracks[s.id]=JSON.stringify(p)}}static R=63710088e-1;static FLY_STEP_MS=100;static expandObserver(t){const e=(t.events??[]).filter(m=>Ts.isObserver(t,m)),i=e.find(m=>m.eventType==="drive"),n=e.find(m=>m.eventType==="lookAhead");if(t.observerTrack.allKeyframes.length>0)return;if(!i){new So(t,e).keyframes().length>0&&(fh.observer(t.observerTrack),t.eventsExpansion={...t.eventsExpansion,observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:t.eventsExpansion?.decorTracks??{}});return}if(!n)return;const s=i.until??Pe.endOf(t),r=i.params,a=new oi(r,i.t,s),c=e.find(m=>m.eventType==="lean"),l=e.find(m=>m.eventType==="watch"),u=new Qe(a,r.eye,n.params,c&&{t:c.t,params:c.params},l&&{t:l.t,params:l.params},m=>{const g=Pe.stands(t).find(M=>M.eventType==="stand");if(!g)return Pe.phenomenonPitchAt(t,m);const v=a.stateAt(m);return As.seenFrom(g.params,{lat:v.lat,lng:v.lng},m).altitudeDeg}).poses(i.t,s),d=u.map(m=>({t:m.t,pose:{lat:m.lat,lng:m.lng,elevationM:m.eye.y-Pe.STANDING_EYE_M,headingDeg:m.headingDeg,pitchDeg:m.pitchDeg,fovDeg:r.fovDeg??60}}));for(const m of d)t.observerTrack.addKeyframe(m.t,m.pose);fh.observer(t.observerTrack);const f={observerTrack:JSON.stringify(t.observerTrack.toJSON()),decorTracks:{}},p=r.vehicle===void 0?void 0:t.decor.find(m=>m.id===r.vehicle);if(p&&!p.track?.length){const m=u[0],g=M=>Math.cos(M*Math.PI/180),v=u.map(M=>{const x=M.roadDeg*Math.PI/180,y=-M.eye.z,w=M.eye.x,S=(M.lng-m.lng)*Pe.METERS_PER_DEGREE*g(M.lat),E=(M.lat-m.lat)*Pe.METERS_PER_DEGREE;return{t:M.t,eastM:S-y*Math.sin(x)-w*Math.cos(x),northM:E-y*Math.cos(x)+w*Math.sin(x),altitudeM:0,headingDeg:M.roadDeg}});p.track=v,p.eastM=v[0].eastM,p.northM=v[0].northM,p.headingDeg=v[0].headingDeg,f.decorTracks[p.id]=JSON.stringify(v)}t.eventsExpansion={...t.eventsExpansion,...f}}static expandBodies(t){const e=t.interpretation?.bodies??[],i=n=>(t.events??[]).some(s=>s.who===n.id&&s.eventType==="ride");for(const n of[...e.filter(s=>!i(s)),...e.filter(i)]){const s=(t.events??[]).filter(h=>h.who===n.id||Bo.partOf(h.who,n.id)!==void 0);if(s.length===0)continue;const r=Math.min(...s.map(h=>h.t));if(n.track.some(h=>h.t>r))continue;const a=JSON.stringify(n.track),c=s.find(h=>h.eventType==="ride"),l=c&&e.find(h=>h.id===c.params.in);n.track=c?l?Bo.ride(n,c,l):n.track:new Bo(n,s,Pe.endOf(t),t.sampleMs).track(),t.eventsExpansion??={decorTracks:{}},t.eventsExpansion.bodies={...t.eventsExpansion.bodies,[n.id]:{stated:a,expanded:JSON.stringify(n.track)}}}}static writtenInterpretation(t,e){const i=t.eventsExpansion?.bodies;return!e||!i?e:{...e,bodies:e.bodies.map(n=>{const s=i[n.id];return s&&JSON.stringify(n.track)===s.expanded?{...n,track:JSON.parse(s.stated)}:n})}}static refresh(t){const e=t.observerTrack.allKeyframes.length===0||Pe.observerTrackIsExpanded(t),i=t.timeline.allKeyframes.length===0||Pe.timelineIsExpanded(t);Pe.again(t,e,i)}static reset(t){Pe.again(t,!0,Pe.stands(t).length>0)}static again(t,e,i){for(const s of t.interpretation?.bodies??[]){const r=t.eventsExpansion?.bodies?.[s.id];r&&JSON.stringify(s.track)===r.expanded&&(s.track=JSON.parse(r.stated))}for(const s of t.decor)s.lights&&(s.lights=Pe.writtenLights(t,s.id,s.lights));if(e){for(const s of Object.keys(t.eventsExpansion?.decorTracks??{})){const r=t.decor.find(a=>a.id===s);r&&delete r.track}t.observerTrack.clear()}const n=t.timeline.toJSON().groups??[];if(i){for(const s of[...t.timeline.sourceIds])t.timeline.removeSource(s);t.timeline.setGroups(n,!1)}t.eventsExpansion=void 0,Pe.expand(t),i&&t.timeline.pruneGroups(),i&&(fn.toBounds(t),fn.toPosition(t)),Pe.settle(t)}static bodiesAreExpanded(t){const e=t.eventsExpansion?.bodies??{};return(t.interpretation?.bodies??[]).every(i=>!e[i.id]||JSON.stringify(i.track)===e[i.id].expanded)}static observerTrackIsExpanded(t){return t.eventsExpansion?.observerTrack!==void 0&&t.eventsExpansion.observerTrack===JSON.stringify(t.observerTrack.toJSON())}static decorTrackIsExpanded(t,e,i){const n=t.eventsExpansion?.decorTracks[e];return n!==void 0&&n===JSON.stringify(i)}static phenomenonPitchAt(t,e){let i;for(const n of t.timeline.sourceIds){const s=t.timeline.getInterpolatedShapeAt(e,n),r=s?.aim?.altitudeDeg;if(!s||s.transparency>=1||r===void 0)continue;const a=(s.angular?.widthDeg??0)*(s.angular?.heightDeg??0);(!i||a>i.area)&&(i={area:a,altitude:r})}return i?.altitude??0}static endOf(t){return t.event.durationSeconds!==void 0?t.event.durationSeconds*1e3:Math.max(...(t.events??[]).map(e=>e.until??e.t))}}function db(o){return sr.restore(fb(o),o.provenance)}function fb(o,t=!1){return fn.toAngular(o),fn.toAim(o),{version:4,id:o.id,time:V0.write(o.event.time),endTime:V0.write(o.event.endTime),durationSeconds:o.event.durationSeconds,durationText:o.event.durationText,utcOffsetHours:o.event.utcOffsetHours,timeZone:o.event.timeZone,place:mb.write(o.event.place),observer:o.observer,account:o.account,sources:o.sources?.length?o.sources:void 0,sway:o.sway,vehicle:o.vehicle,description:o.event.description,image:o.event.image,summary:o.event.summary,summaryTime:o.event.summaryTime,tags:o.event.tags,timeline:!t&&Pe.timelineIsExpanded(o)?Pe.timelineWithoutShapes(o):o.timeline.toJSON(),observerTrack:!t&&Pe.observerTrackIsExpanded(o)?void 0:Zn.restatedObserverTrack(o),events:o.events?.length?o.events:void 0,weatherTrack:o.weatherTrack.toJSON(),soundTrack:o.soundTrack.toJSON(),weather:o.weather,decor:Zn.restatedDecor(o).map(e=>{if(!t&&e.lights&&(e={...e,lights:Pe.writtenLights(o,e.id,e.lights)}),t||!Pe.decorTrackIsExpanded(o,e.id,e.track))return e;const{track:i,...n}=e;return n}),milestones:o.milestones.length>0?o.milestones:void 0,references:o.references.length>0?o.references:void 0,roads:o.roads.length>0?o.roads:void 0,traces:o.traces.length>0?o.traces:void 0,weatherSource:o.weatherSource,instrument:o.instrumentId,exposureSeconds:o.exposureSeconds,iso:o.iso,film:o.film,metering:o.metering,sampleMs:o.sampleMs,lens:o.lens,lighting:o.lighting,lightPollution:o.lightPollution,observerMap:o.observerMap,interpretation:t?Zn.restatedInterpretation(o):Pe.writtenInterpretation(o,Zn.restatedInterpretation(o)),variants:o.variants.length>0?o.variants:void 0,skyEvents:Vr.written(o.skyEvents),snapshots:o.snapshots,modules:o.modules?.length?o.modules:void 0}}function R_(o){return o.observer?.id??"observer"}function pb(o){const t=na.check(o,"sighting"),{recording:e,provenance:i}=sr.strip(t),n=I_(e);return n.provenance=i,n}function I_(o){const t=[],e=new Dp({eventType:"sighting",time:V0.read(o.time),endTime:V0.read(o.endTime),durationSeconds:o.durationSeconds,durationText:o.durationText,utcOffsetHours:o.utcOffsetHours,timeZone:o.timeZone,place:mb.read(o.place),description:o.description,image:o.image,summary:o.summary,summaryTime:o.summaryTime,tags:o.tags},Ud.fromJSON(o.timeline,t,!1),o.observerTrack?Qu.fromJSON(o.observerTrack):new Qu,o.weatherTrack?td.fromJSON(o.weatherTrack):new td,o.soundTrack?ed.fromJSON(o.soundTrack):new ed,o.observer&&{id:o.observer.id,title:o.observer.title,lastName:o.observer.lastName,firstNames:o.observer.firstNames},o.id,o.weather,(o.decor??[]).map(n=>{if(!n.facade?.plain)return n;const{plain:s,...r}=n.facade;return{...n,facade:{...r,openings:"plain"}}}),o.weatherSource,o.instrument,o.exposureSeconds??o.observerTrack?.keyframes.map(n=>n.pose.exposureSeconds).find(n=>n!==void 0),Cu(o.milestones??[]),o.references??[],o.roads??[],o.traces??[]);e.account=o.account,e.sources=o.sources,e.sway=o.sway,e.iso=o.iso,e.film=o.film,e.metering=o.metering,e.sampleMs=o.sampleMs,e.lens=o.lens,e.lighting=o.lighting,e.lightPollution=o.lightPollution,e.observerMap=o.observerMap,e.vehicle=o.vehicle,e.events=o.events?.map(n=>n.who===void 0?{...n,who:R_(o)}:n);const i=Vr.read(o.skyEvents,o.interpretation);return e.interpretation=i.interpretation,e.variants=Array.isArray(o.variants)?o.variants:[],e.skyEvents=i.skyEvents,e.snapshots=o.snapshots,e.modules=Array.isArray(o.modules)?o.modules.filter(n=>typeof n=="string"):void 0,e.loadIssues=t,Pe.expand(e),e.timeline.pruneGroups(),fn.toBounds(e),fn.toPosition(e),Pe.settle(e),e}class V0{static read(t){return t===void 0||t.trim()===""?void 0:f_(t)}static write(t){if(t===void 0)return;const e=p_(t);return e===""?void 0:e}}class mb{static read(t){if(t?.locations?.length)return t.locations.map(({lat:e,lng:i})=>({lat:e,lng:i,...t.name===void 0?{}:{name:t.name}}))}static write(t){if(!t?.length)return;const e=t.find(i=>i.name)?.name;return{...e===void 0?{}:{name:e},locations:t.map(({lat:i,lng:n})=>({lat:i,lng:n}))}}}const D_=Object.freeze(Object.defineProperty({__proto__:null,fromSightingJson:pb,plainSightingJson:fb,toSightingJson:db},Symbol.toStringTag,{value:"Module"}));class bd{static EN={"unknown-key":"{path}: unknown key, ignored","wrong-type":"{path}: expected {expected}, found {found}","not-in-list":"{path}: {found} is not one of {expected}","out-of-range":"{path}: {found} is outside {expected}",defaulted:"{path}: missing, {expected} used",unplaced:"{path}: no aim (and no bounds), drawn at the middle of the view",unsized:"{path}: no angular size (and no bounds), drawn one pixel wide","pixels-over-angles":"{path}: bounds restated without aim or angular, so the shape follows the pixels"};static text(t,e=bd.EN){return e[t.kind].replace("{path}",t.path).replace("{expected}",t.expected??"").replace("{found}",t.found??"")}static warn(t,e){if(t.length===0)return;const i=t.map(n=>` ${bd.text(n)}`);console.warn(`UFO@home: ${t.length} problem(s) in ${e??"this recording"}:
|
|
1922
1922
|
${i.join(`
|
|
1923
1923
|
`)}`)}}class tr{constructor(t){this.format=t}issues(t){const e=[];return this.object(t,this.format,"",e),e}object(t,e,i,n){if(!tr.isObject(t)){n.push({kind:"wrong-type",path:i||"(the file)",expected:"object",found:tr.typeOf(t)});return}for(const[s,r]of Object.entries(t)){const a=i?`${i}.${s}`:s,c=e[s];c?this.field(r,c,a,n):n.push({kind:"unknown-key",path:a})}}field(t,e,i,n){if(tr.isStated(t)){this.field(t.value,e,i,n);return}if(!(e.loose||t===void 0||t===null))switch(e.type){case"enum":(typeof t!="string"||!e.values?.includes(t))&&n.push({kind:"not-in-list",path:i,expected:(e.values??[]).map(s=>`"${s}"`).join(", "),found:JSON.stringify(t)});return;case"object":e.fields?this.object(t,e.fields,i,n):tr.isObject(t)||n.push({kind:"wrong-type",path:i,expected:"object",found:tr.typeOf(t)});return;case"array":Array.isArray(t)?e.fields&&t.forEach((s,r)=>{const a=tr.isStated(s)?s.value:s;this.object(a,e.fields,`${i}.${r}`,n)}):n.push({kind:"wrong-type",path:i,expected:"array",found:tr.typeOf(t)});return;default:typeof t!==e.type?n.push({kind:"wrong-type",path:i,expected:e.type,found:tr.typeOf(t)}):typeof t=="number"&&(e.minimum!==void 0&&t<e.minimum||e.maximum!==void 0&&t>e.maximum)&&n.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 tr.isObject(t)&&"value"in t&&Object.keys(t).every(e=>tr.STATED_KEYS.has(e))}static typeOf(t){return Array.isArray(t)?"array":t===null?"null":typeof t}}class xr{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,n=Math.max(0,t-i*1e3),s=Math.max(0,t-n);return{fromMs:n,toMs:t,ms:s,seconds:s/1e3}}static instants(t,e,i,n,s){if(!(n>0))return 1;const r=s>0?xr.travelDegOver(t,e,i,i+n*1e3)/s/xr.PIXELS_PER_INSTANT:0,a=xr.flashesOver(t,n)*xr.INSTANTS_PER_FLASH,c=Math.ceil(Math.max(r,a));return c<2?1:Math.min(xr.MAX_INSTANTS,c)}static travelDegOver(t,e,i,n){let s=0;for(const r of t){if(!r.track||r.track.length<2)continue;const a=xr.directionAt(r,e,i),c=xr.directionAt(r,e,n),l=Math.min(1,Math.max(-1,a.x*c.x+a.y*c.y+a.z*c.z));s=Math.max(s,Math.acos(l)*180/Math.PI)}return s}static flashesOver(t,e){let i=0;for(const n of t)for(const s of n.lights??[])s.pattern.kind==="flash"&&(i=Math.max(i,s.pattern.perMinute));return i/60*e}static directionAt(t,e,i){const n=ha(t,i),s=n.eastM,r=n.altitudeM-e,a=n.northM,c=Math.hypot(s,r,a);return c===0?{x:0,y:1,z:0}:{x:s/c,y:r/c,z:a/c}}}function y0(o,t){for(const e of o){const i=e.toLowerCase().split("-")[0];if(t.includes(i))return i}return"en"}class Ro{static preferencesFor(t){const e=navigator.languages??[],i=this.declaredFor(t);return i?[i,...e]:e}static declaredFor(t){for(let e=t;e;){const i=e.closest("[lang]")?.getAttribute("lang")?.trim();if(i)return i;const n=e.getRootNode();e=n instanceof ShadowRoot?n.host:void 0}}}Ot.register(Cn,()=>new bc);Ot.register(Rh,()=>new uh);Ot.register(Ar,()=>new Yv);Ot.register(Ih,()=>new dh);Ot.register(id,()=>new $v);Ot.register(Dh,()=>new od);Ot.register(Th,()=>new ad);Ot.register(Ch,()=>new cd);Ot.register(Ko,()=>new Ph);Ot.register(_h,()=>new rd);Ot.register(Ds,()=>new Fi);Ot.register(ko,()=>new ud);Ot.register(dn,()=>new Ec);Ot.register(Fo,()=>new dd);Ot.register(nd,()=>new Kv);Ot.register(Uo,()=>new fd);Ot.register(Lo,()=>new hd);Ot.register(zo,()=>new pd);Ot.register(zc,()=>new md);Ot.register(No,()=>new ld);Ot.register(ms,()=>new qe);Ot.register(Ga,()=>new Md);Ot.register(un,()=>new ee);Ot.register(Va,()=>new yd);Ot.register(sd,()=>new Ip);Ot.register(Wa,()=>new wd);Ot.register(Ha,()=>new vd);Ot.register(Xa,()=>new xd);Ot.register(H0,()=>new c_);Ot.register(Ba,()=>new gd);class br{constructor(t){this.preferences=t}read(t){var e,i;if(t===void 0)return;if(typeof t=="string")return t===""?void 0:t;for(const s of this.preferences){const r=(e=t[s])!==null&&e!==void 0?e:t[br.base(s)];if(r)return r}const n=new Set(this.preferences.map(s=>br.base(s)));for(const[s,r]of Object.entries(t))if(r&&n.has(br.base(s)))return r;return(i=Object.values(t).find(s=>s))!==null&&i!==void 0?i:void 0}write(t,e,i){var n,s;const r=e?.trim()?e.trim():void 0;if(t===void 0||typeof t=="string")return r;const a={...t},c=(s=(n=Object.keys(a).find(l=>l===i))!==null&&n!==void 0?n:Object.keys(a).find(l=>br.base(l)===br.base(i)))!==null&&s!==void 0?s:i;return r===void 0?delete a[c]:a[c]=r,Object.keys(a).length===0?void 0:a}static base(t){return t.toLowerCase().split("-")[0]}}br.any=new br([]);var M2;(function(o){o.abductee="abductee",o.actor="actor",o.artist="artist",o.anthropologist="anthropologist",o.archeologist="archeologist",o.astronaut="astronaut",o.astronomer="astronomer",o.astrologist="astrologist",o.astrophysicist="astrophysicist",o.banker="banker",o.barman="barman",o.biologist="biologist",o.biochemist="biochemist",o.biophysicist="biophysicist",o.bishop="bishop",o.businessman="businessman",o.botanist="botanist",o.cameraman="cameraman",o.chemist="chemist",o.contactee="contactee",o.cryptozoologist="cryptozoologist",o.dentist="dentist",o.director="director",o.diplomat="diplomat",o.diver="diver",o.electronics="electronics",o.engineer="engineer",o.ethnologist="ethnologist",o.exobiologist="exobiologist",o.farmer="farmer",o.firefighter="firefighter",o.flightAttendant="flightAttendant",o.geologist="geologist",o.geophysicist="geophysicist",o.geographer="geographer",o.historian="historian",o.houseWife="houseWife",o.hypnotherapist="hypnotherapist",o.illusionist="illusionist",o.journalist="journalist",o.judge="judge",o.lawyer="lawyer",o.leader="leader",o.librarian="librarian",o.logger="logger",o.mathematician="mathematician",o.mechanic="mechanic",o.meteorologist="meteorologist",o.military="military",o.musician="musician",o.neurologist="neurologist",o.neuroscientist="neuroscientist",o.neuropsychiatrist="neuropsychiatrist",o.nurse="nurse",o.oceanographer="oceanographer",o.painter="painter",o.parapsychologist="parapsychologist",o.philosopher="philosopher",o.photographer="photographer",o.physician="physician",o.physicist="physicist",o.pilot="pilot",o.politician="politician",o.policeman="policeman",o.priest="priest",o.producer="producer",o.prospector="prospector",o.psychologist="psychologist",o.psychiatrist="psychiatrist",o.radioastronomer="radioastronomer",o.radioamateur="radioamateur",o.salesman="salesman",o.sailor="sailor",o.sociologist="sociologist",o.softwareEngineer="softwareEngineer",o.stuntman="stuntman",o.taxiDriver="taxiDriver",o.teacher="teacher",o.telegrapher="telegrapher",o.truckDriver="truckDriver",o.ufologist="ufologist",o.ufoWitness="ufoWitness",o.ufoWitness2="ufoWitness2",o.worker="worker",o.writer="writer"})(M2||(M2={}));var y2;(function(o){o.neutral="neutral",o.male="male",o.female="female"})(y2||(y2={}));class C_ extends Error{constructor(t,e){super(t),this.cause=e}}class Zv extends C_{constructor(t=Zv.defaultMessage,e){super(t,e)}}Zv.defaultMessage="Assertion failed";var x2;(function(o){o.country="country",o.region="region",o.department="department",o.city="city",o.company="company"})(x2||(x2={}));var w2;(function(o){o.at="at",o.au="au",o.ar="ar",o.be="be",o.br="br",o.ca="ca",o.ch="ch",o.cn="cn",o.cl="cl",o.co="co",o.cy="cy",o.de="de",o.dk="dk",o.do="do",o.dz="dz",o.gr="gr",o.ec="ec",o.eg="eg",o.es="es",o.fi="fi",o.fr="fr",o.ga="ga",o.ge="ge",o.hu="hu",o.in="in",o.ie="ie",o.ir="ir",o.il="il",o.it="it",o.jp="jp",o.kr="kr",o.ma="ma",o.mx="mx",o.my="my",o.mz="mz",o.nl="nl",o.no="no",o.nz="nz",o.pa="pa",o.pe="pe",o.ph="ph",o.pl="pl",o.pt="pt",o.ro="ro",o.ru="ru",o.sc="sc",o.tr="tr",o.ua="ua",o.uk="uk",o.us="us",o.sa="sa",o.se="se",o.su="su",o.tn="tn",o.tw="tw",o.ve="ve",o.za="za"})(w2||(w2={}));const P_=["en","fr","es","it"];class Rr{static catalog(t){const e=new Map;return{load(i){const n=Rr.languageOf(i);let s=e.get(n);return s||(s=t[n](),e.set(n,s),s.catch(()=>e.delete(n))),s}}}static none(){return new Proxy({},{get:()=>""})}static blank(){const t=new Proxy(()=>t,{get:(e,i)=>i===Symbol.toPrimitive?()=>"":i===Symbol.iterator?function*(){}:i==="toString"||i==="valueOf"?()=>"":i==="then"?void 0:t,apply:()=>t,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor:()=>{}});return t}static languageOf(t){const e=t.toLowerCase().split("-")[0];return P_.includes(e)?e:"en"}}const x0=["en","fr","es","it"],O_={en:()=>Ct(()=>import("./UfoMessages_en-CXQNZd8v.js"),[],import.meta.url).then(o=>o.ufoMessages_en),fr:()=>Ct(()=>import("./UfoMessages_fr-CGkQBn5r.js"),[],import.meta.url).then(o=>o.ufoMessages_fr),es:()=>Ct(()=>import("./UfoMessages_es-CO-v8Jl6.js"),[],import.meta.url).then(o=>o.ufoMessages_es),it:()=>Ct(()=>import("./UfoMessages_it-BScqxIaH.js"),[],import.meta.url).then(o=>o.ufoMessages_it)},N_=Rr.catalog(O_),L_=Rr.catalog({en:()=>Ct(()=>import("./SceneNames_en-BCTAMSLj.js"),[],import.meta.url).then(o=>o.sceneNames_en),fr:()=>Ct(()=>import("./SceneNames_fr-De6iQ9ff.js"),[],import.meta.url).then(o=>o.sceneNames_fr),es:()=>Ct(()=>import("./SceneNames_es-BOWBdXXS.js"),[],import.meta.url).then(o=>o.sceneNames_es),it:()=>Ct(()=>import("./SceneNames_it-DfBWbCPR.js"),[],import.meta.url).then(o=>o.sceneNames_it)});function k_(o){return L_.load(o)}const gb=Math.PI/180,F_=180/Math.PI,U_=256,vb=19,z_=1.25;function Mb(o,t){return 156543.03392*Math.cos(o*gb)/2**t}function yb(o,t){return Mb(o,t)*U_}function B_(o,t){let e=0;for(;e<vb&&yb(o,e+1)>=t;)e++;return e}function xb(o,t){return yb(o,t)}function H_(o,t){const e=t*z_;let i=0;for(;i<vb&&Mb(o,i)>e;)i++;return i}function w0(o){const t=o*gb;return(1-Math.log(Math.tan(t)+1/Math.cos(t))/Math.PI)/2}function wb(o,t,e){const i=2**e;return{x:(o+180)/360*i,y:w0(t)*i}}function Sb(o,t,e){const i=w0(o.north),n=w0(o.south);return{x:(t-o.west)/(o.east-o.west),y:(w0(e)-i)/(n-i)}}function G_(o,t,e){const{x:i,y:n}=wb(o,t,e);return{x:Math.floor(i),y:Math.floor(n),z:e}}function V_(o){const t=2**o.z,e=o.x/t*360-180,i=(o.x+1)/t*360-180,n=S2(o.y,t);return{south:S2(o.y+1,t),north:n,west:e,east:i}}function S2(o,t){const e=o/t;return Math.atan(Math.sinh(Math.PI*(1-2*e)))*F_}function bb(o,t,e,i){const n=G_(o,t,e),s=Math.floor(i/2),r=[];for(let l=-s;l<=s;l++)for(let h=-s;h<=s;h++)r.push({x:n.x+h,y:n.y+l,z:e});const a=r.map(V_),c={south:Math.min(...a.map(l=>l.south)),north:Math.max(...a.map(l=>l.north)),west:Math.min(...a.map(l=>l.west)),east:Math.max(...a.map(l=>l.east))};return{tiles:r,bounds:c}}const W_="#2ec4ff";class gc{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,n=1/0;for(const s of this.targets){const r=Math.hypot(s.x-t,s.y-e);r>s.radius||r>n||(i=s,n=r)}return i}get width(){return this.ctx.canvas.width}get height(){return this.ctx.canvas.height}paint(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 n=Sb(t,i,e);return{x:n.x*this.width,y:n.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 n=this.toCanvas(t.bounds,i.bounds.north,i.bounds.west),s=this.toCanvas(t.bounds,i.bounds.south,i.bounds.east);e.drawImage(i.source,n.x,n.y,s.x-n.x,s.y-n.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 n=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:n.x,y:n.y,radius:7}),e.beginPath(),e.rect(n.x-3.5,n.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 s=(i.headingDeg-90)*Math.PI/180;e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(n.x+Math.cos(s)*10,n.y+Math.sin(s)*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(n=>this.toCanvas(t.bounds,n.lat,n.lng));e.beginPath(),e.moveTo(i[0].x,i[0].y);for(const n of i.slice(1))e.lineTo(n.x,n.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 n=i.points.map(r=>this.toCanvas(t.bounds,r.lat,r.lng));if(n.length===0)continue;const s=i.color??W_;if(i.kind==="point")e.beginPath(),e.moveTo(n[0].x,n[0].y-6),e.lineTo(n[0].x+6,n[0].y),e.lineTo(n[0].x,n[0].y+6),e.lineTo(n[0].x-6,n[0].y),e.closePath(),e.fillStyle=s,e.fill(),e.lineWidth=1.5,e.strokeStyle="rgba(0, 0, 0, 0.8)",e.stroke();else{e.beginPath(),e.moveTo(n[0].x,n[0].y);for(const r of n.slice(1))e.lineTo(r.x,r.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=s,e.lineWidth=2.5,e.stroke(),e.setLineDash([])}if(i.label){e.font="11px sans-serif",e.textAlign="left",e.textBaseline="middle";let r=n[0];if(i.kind==="line"&&t.position){const a=this.toCanvas(t.bounds,t.position.lat,t.position.lng);r=n.reduce((c,l)=>Math.hypot(l.x-a.x,l.y-a.y)>Math.hypot(c.x-a.x,c.y-a.y)?l:c)}this.paintOutlinedText(i.label,r.x+9,r.y-9)}}}paintCone(t,e){const{headingDeg:i,coneHalfAngleDeg:n}=t;if(i===void 0||n===void 0)return;const{ctx:s}=this,r=this.toCanvas(t.bounds,e.lat,e.lng),a=Math.hypot(this.width,this.height),c=(i-90)*Math.PI/180,l=n*Math.PI/180;s.save(),s.beginPath(),s.moveTo(r.x,r.y),s.arc(r.x,r.y,a,c-l,c+l),s.closePath();const h=s.createRadialGradient(r.x,r.y,0,r.x,r.y,a);h.addColorStop(0,"rgba(255, 224, 130, 0.55)"),h.addColorStop(.35,"rgba(255, 224, 130, 0.22)"),h.addColorStop(1,"rgba(255, 224, 130, 0)"),s.fillStyle=h,s.fill(),s.restore()}paintMarkers(t){const{ctx:e}=this;e.textAlign="center",e.textBaseline="middle",e.font="bold 10px sans-serif";for(const i of[...t.markers].sort((n,s)=>Number(n.current)-Number(s.current))){const n=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:n.x,y:n.y,radius:gc.MARKER_RADIUS_PX}),e.beginPath(),e.arc(n.x,n.y,gc.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,n.x,n.y)}}paintObserver(t,e){const{ctx:i}=this,n=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:n.x,y:n.y,radius:8});const s=t.markers.some(r=>{if(!r.current)return!1;const a=se(r.lat,r.lng,e.lat,e.lng);return Math.hypot(a.x,a.z)<=gc.ON_MARKER_M});i.beginPath(),i.arc(n.x,n.y,s?gc.MARKER_RADIUS_PX+2.5:5.5,0,Math.PI*2),s||(i.fillStyle="#ff5a3c",i.fill()),i.lineWidth=4,i.strokeStyle="rgba(0, 0, 0, 0.5)",i.stroke(),i.lineWidth=s?3:2.5,i.strokeStyle=s?"#ff5a3c":"#fff",i.stroke()}paintNorth(){const{ctx: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 n=e?this.wrap(e,this.width-20):[];let s=this.height-4;i.textAlign="right";for(const f of n.slice().reverse())this.paintOutlinedText(f,this.width-6,s),s-=11;const r=(t.south+t.north)/2,c=Math.abs(se(r,t.east,r,t.west).x)/this.width,l=gc.SCALE_STEPS_M.find(f=>f/c<=this.width/3);if(l===void 0)return;const h=l/c,u=8,d=s-3;i.lineWidth=3,i.strokeStyle="rgba(0, 0, 0, 0.6)",i.beginPath(),i.moveTo(u,d),i.lineTo(u+h,d),i.stroke(),i.lineWidth=1.5,i.strokeStyle="rgba(255, 255, 255, 0.95)",i.stroke(),i.textAlign="left",this.paintOutlinedText(l>=1e3?`${l/1e3} km`:`${l} m`,u,d-3)}paintOutlinedText(t,e,i){const{ctx:n}=this;n.lineWidth=3,n.strokeStyle="rgba(0, 0, 0, 0.75)",n.strokeText(t,e,i),n.fillStyle="#fff",n.fillText(t,e,i)}wrap(t,e){const i=[];let n="";for(const s of t.split(" ")){const r=n?`${n} ${s}`:s;n&&this.ctx.measureText(r).width>e?(i.push(n),n=s):n=r}return n&&i.push(n),i}}class pi{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 pi.including(t.boundsAround(pi.MIN_SPAN_M,pi.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 n=Math.min(pi.MAX_ZOOM,Math.max(pi.MIN_ZOOM,this.zoom*i)),s=this.centerX+(t-.5)/this.zoom,r=this.centerY+(e-.5)/this.zoom;this.centerX=s-(t-.5)/n,this.centerY=r-(e-.5)/n,this.zoom=n}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),n=pi.mercatorY01(e.north),s=pi.mercatorY01(e.south),r=pi.mercatorY01(i.north),a=pi.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=((r+a)/2-n)/(s-n)}keepInView(t,e,i){if(!this.changed)return!1;const n=this.boundsWithin(t),s=pi.mercatorY01(n.north),r=pi.mercatorY01(n.south),a=(e.lng-n.west)/(n.east-n.west),c=(pi.mercatorY01(e.lat)-s)/(r-s);return a>=i&&a<=1-i&&c>=i&&c<=1-i?!1:(this.panBy(.5-a,.5-c),!0)}boundsWithin(t){if(!this.changed)return t;const e=.5/this.zoom,i=pi.mercatorY01(t.north),n=pi.mercatorY01(t.south),s=t.east-t.west;return{west:t.west+(this.centerX-e)*s,east:t.west+(this.centerX+e)*s,north:pi.latitudeAt(i+(this.centerY-e)*(n-i)),south:pi.latitudeAt(i+(this.centerY+e)*(n-i))}}static including(t,e,i=3){const n=(t.north+t.south)/2,s=(t.east+t.west)/2,r=se(n,t.east,n,s).x;let a=r;for(const c of e){const{x:l,z:h}=se(c.lat,c.lng,n,s),u=Math.max(Math.abs(l),Math.abs(h));u<=r*i&&(a=Math.max(a,u*1.15))}return a<=r?t:{north:Cs(0,-a,n,s).lat,south:Cs(0,a,n,s).lat,east:Cs(a,0,n,s).lng,west:Cs(-a,0,n,s).lng}}static expand(t,e){const i=t.east-t.west,n=t.north-t.south;return{west:t.west-i*e,east:t.east+i*e,south:t.south-n*e,north:t.north+n*e}}static pointAt(t,e,i){const n=pi.mercatorY01(t.north),s=pi.mercatorY01(t.south);return{lat:pi.latitudeAt(n+i*(s-n)),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 Zs=256,b2=3,X_=32768;class Eb{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,n=(t.west+t.east)/2,s=Math.abs(se(i,t.east,i,t.west).x),r=Math.abs(se(t.north,n,t.south,n).z),a=B_(i,Math.max(s,r)),{tiles:c}=bb(n,i,a,b2),l=b2*Zs,h=new Float32Array(l*l),u=c[0];await Promise.all(c.map(f=>this.decodeTileInto(f,u,h,l)));const d=new Float32Array(e.width*e.height);for(let f=0;f<e.height;f++){const p=t.north+(t.south-t.north)*(f/(e.height-1));for(let m=0;m<e.width;m++){const g=t.west+(t.east-t.west)*(m/(e.width-1));d[f*e.width+m]=this.sampleAt(p,g,a,u,h,l)}}return{heights:d,width:e.width,height:e.height,bounds:t}}async decodeTileInto(t,e,i,n){const s=this.tileUrlTemplate.replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y)),r=await this.fetchImpl(s);if(!r.ok)throw new Error(`Elevation tile fetch failed (${r.status}): ${s}`);const a=await createImageBitmap(await r.blob()),c=document.createElement("canvas");c.width=Zs,c.height=Zs;const l=c.getContext("2d");if(!l)throw new Error("2D canvas context unavailable");l.drawImage(a,0,0);const{data:h}=l.getImageData(0,0,Zs,Zs),u=(t.x-e.x)*Zs,d=(t.y-e.y)*Zs;for(let f=0;f<Zs;f++)for(let p=0;p<Zs;p++){const m=(f*Zs+p)*4,g=h[m]*256+h[m+1]+h[m+2]/256-X_,v=u+p,M=d+f;i[M*n+v]=g}}sampleAt(t,e,i,n,s,r){const{x:a,y:c}=wb(e,t,i),l=(a-n.x)*Zs,h=(c-n.y)*Zs,u=Math.max(0,Math.min(r-1,Math.floor(l))),d=Math.max(0,Math.min(r-1,Math.floor(h))),f=Math.min(r-1,u+1),p=Math.min(r-1,d+1),m=l-u,g=h-d,v=s[d*r+u],M=s[d*r+f],x=s[p*r+u],y=s[p*r+f],w=v+(M-v)*m,S=x+(y-x)*m;return w+(S-w)*g}}class Cp{constructor(t,e,i,n){this.width=t,this.height=e,this.samples=i,this.values=n}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),n=e.getUint16(i,!0),s=new Map;for(let v=0;v<n;v++){const M=i+2+v*12;s.set(e.getUint16(M,!0),{type:e.getUint16(M+2,!0),count:e.getUint32(M+4,!0),value:e.getUint32(M+8,!0)})}const r=(v,M)=>{const x=s.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},a=v=>{const M=s.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(r(259,1)!==1)throw new Error("Compressed TIFF");if(s.has(322))throw new Error("Tiled TIFF");const c=r(256),l=r(257),h=r(277,1),u=a(258)[0],d=r(339,1)===3;if(!(d&&u===32||!d&&u===8))throw new Error(`Unsupported TIFF samples: ${u} bits`);const f=a(273),p=a(279),m=new Uint8Array(c*l*h*(u/8));let g=0;for(let v=0;v<f.length&&g<m.length;v++){const M=Math.min(p[v],m.length-g);m.set(new Uint8Array(t,f[v],M),g),g+=M}if(g<m.length)throw new Error("Truncated TIFF");return new Cp(c,l,h,d?new Float32Array(m.buffer):m)}}class ao extends Error{constructor(t,e){super(e),this.reason=t,this.name="SurroundingsUnavailableError"}}class Y_{constructor(t,e,i,n,s){this.heights=t,this.plants=e,this.buildings=i,this.size=n,this.metresPerPixel=s}structureAt(t,e){const i=Math.floor(t/this.metresPerPixel+this.size/2),n=Math.floor(this.size/2-e/this.metresPerPixel);if(i<0||n<0||i>=this.size||n>=this.size)return;const s=n*this.size+i;if(!(this.plants[s]||this.buildings[s]))return this.heights[s]}tallestStructureNear(t,e,i){let n;const s=Math.ceil(i/this.metresPerPixel);for(let r=-s;r<=s;r++)for(let a=-s;a<=s;a++){if(Math.hypot(a,r)*this.metresPerPixel>i)continue;const c=this.structureAt(t+a*this.metresPerPixel,e+r*this.metresPerPixel);c!==void 0&&(n===void 0||c>n)&&(n=c)}return n}}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),n=Math.ceil(2*i/Le.METRES_PER_PIXEL),[s,r]=await Promise.all([this.raster(t,i,n,Le.HEIGHT_LAYER),this.raster(t,i,n,Le.CLASS_LAYER)]);if(s.samples!==1||r.samples<3)throw new ao("unreachable","The survey answered in a layout this does not read");const a=s.values;if(a.every(u=>u===Le.NO_DATA))throw new ao("no-coverage","No LiDAR HD survey here yet");const c=new Uint8Array(n*n),l=new Uint8Array(n*n);for(let u=0;u<n*n;u++){const d=r.values[u*r.samples],f=r.values[u*r.samples+1],p=r.values[u*r.samples+2];c[u]=f>d&&f>p?1:0,l[u]=d>120&&f<90&&p<90?1:0}const h=2*i/n;return{size:n,metresPerPixel:h,heights:a,vegetation:c,building:l,structures:new Y_(a,c,l,n,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,n){const r=[n.lng-1e-4,n.lat-1e-4,n.lng+1e-4,n.lat+1e-4].map(a=>a.toFixed(6)).join(",");try{return(await this.features(t,`BBOX(${e},${r},'EPSG:4326')`,i,20)).map(a=>a.properties[i])}catch{return[]}}async photo(t,e){const i=Le.radius(e),n=Math.min(Le.MAX_PHOTO_PIXELS,Math.ceil(2*i/Le.METRES_PER_PIXEL)),s=await this.raster(t,i,n,Le.PHOTO_LAYER);if(s.samples<3)throw new ao("unreachable","The photograph came in a layout this does not read");return{size:n,metresPerPixel:2*i/n,samples:s.samples,values:s.values}}async vectors(t,e,i){const n=Le.radius(e),s=n/Le.METRES_PER_DEGREE,r=n/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),c=`BBOX(geometrie,${[t.lng-r,t.lat-s,t.lng+r,t.lat+s].map(v=>v.toFixed(6)).join(",")},'EPSG:4326')`,[l,h,u,d,f,p]=await Promise.all([this.features("construction_lineaire",`${c} AND nature='Pont'`,"nature,geometrie"),this.features("troncon_de_route",`${c} 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",`${c} AND position_par_rapport_au_sol>'0'`,"position_par_rapport_au_sol,geometrie").catch(()=>[]),this.features("ligne_electrique",c,"voltage,geometrie"),i?this.features("batiment",c,Le.BUILDING_PROPERTIES,5e3):Promise.resolve([]),i?this.features("zone_d_activite_ou_d_interet",c,"toponyme,categorie,geometrie",100).catch(()=>[]):Promise.resolve([])]),m=i?await this.wholeWorship(p,f,[t.lng-r,t.lat-s,t.lng+r,t.lat+s]):[],g=[...f,...m];return{bridges:l,elevatedRoads:h,elevatedRailways:u,lines:d,buildings:g,zones:p,mapDate:Le.latest(g.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[n,s,r,a]=i,c=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,m]=Le.extent(u);if(d>=n&&f>=s&&p<=r&&m<=a)continue;const g=[Math.max(d,n-c),Math.max(f,s-c),Math.min(p,r+c),Math.min(m,a+c)];l=l?[Math.min(l[0],g[0]),Math.min(l[1],g[1]),Math.max(l[2],g[2]),Math.max(l[3],g[3])]:g}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,n=-1/0,s=-1/0;const r=a=>{Array.isArray(a)&&typeof a[0]=="number"?(e=Math.min(e,a[0]),n=Math.max(n,a[0]),i=Math.min(i,a[1]),s=Math.max(s,a[1])):Array.isArray(a)&&a.forEach(r)};return r(t.geometry.coordinates),[e,i,n,s]}async elevatedRoadLines(t){const e=`BBOX(geometrie,${[t.west,t.south,t.east,t.north].map(s=>s.toFixed(6)).join(",")},'EPSG:4326')`,i=await this.features("troncon_de_route",`${e} AND position_par_rapport_au_sol>'0'`,"geometrie",300),n=[];for(const s of i){const{type:r,coordinates:a}=s.geometry,c=r==="LineString"?[a]:r==="MultiLineString"?a:[];for(const l of c)n.push(l.map(h=>({lat:h[1],lng:h[0]})))}return n}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,n){const s=e/Le.METRES_PER_DEGREE,r=e/(Le.METRES_PER_DEGREE*Math.cos(t.lat*Math.PI/180)),a=new URLSearchParams({SERVICE:"WMS",VERSION:"1.3.0",REQUEST:"GetMap",LAYERS:n,STYLES:"",CRS:"EPSG:4326",BBOX:[t.lat-s,t.lng-r,t.lat+s,t.lng+r].map(l=>l.toFixed(6)).join(","),WIDTH:String(i),HEIGHT:String(i),FORMAT:"image/geotiff"});let c;try{c=await this.fetchImpl(`${this.wms}?${a}`)}catch(l){throw new ao("unreachable",l instanceof Error?l.message:String(l))}if(!c.ok)throw new ao("unreachable",`The survey answered ${c.status}`);try{return Cp.parse(await c.arrayBuffer())}catch(l){throw new ao("unreachable",l instanceof Error?l.message:String(l))}}async features(t,e,i,n=200){const s=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(n),CQL_FILTER:e,PROPERTYNAME:i});let r;try{r=await this.fetchImpl(`${this.wfs}?${s}`)}catch(c){throw new ao("unreachable",c instanceof Error?c.message:String(c))}if(!r.ok)throw new ao("unreachable",`The map answered ${r.status}`);return(await r.json()).features??[]}}class bo{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],n=e.map(a=>se(a.lat,a.lng,i.lat,i.lng)),s=t.map(a=>se(a.lat,a.lng,i.lat,i.lng));let r=0;for(let a=0;a<s.length-1;a++){const c=s[a],l=s[a+1],h=Math.hypot(l.x-c.x,l.z-c.z);if(h<1e-6)continue;const u=Math.max(1,Math.ceil(h/bo.SAMPLE_M)),d=Math.atan2(l.x-c.x,-(l.z-c.z));for(let f=0;f<=u;f++){const p=f/u,m=bo.nearest(n,c.x+(l.x-c.x)*p,c.z+(l.z-c.z)*p);m.distanceM>bo.NEAR_M||bo.angleBetween(d,m.heading)<=bo.ALIGNED_DEG&&(r+=h/u)}}return r>=bo.LONG_ENOUGH_M}static nearest(t,e,i){let n={distanceM:1/0,heading:0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.z-r.z,h=c*c+l*l,u=h<1e-9?0:Math.max(0,Math.min(1,((e-r.x)*c+(i-r.z)*l)/h)),d=Math.hypot(e-(r.x+c*u),i-(r.z+l*u));d<n.distanceM&&(n={distanceM:d,heading:Math.atan2(c,-l)})}return n}static angleBetween(t,e){const i=Math.abs((t-e)*180/Math.PI%180);return Math.min(i,180-i)}}class Ce{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??Ce.WMS,this.timeoutMs=t.timeoutMs??Ce.DEFAULT_TIMEOUT_MS,this.maxWindowM=t.maxWindowM??Ce.MAX_WINDOW_M,this.geoplatform=new Le({fetchImpl:this.fetchImpl,wmsEndpoint:this.wms,wfsEndpoint:t.wfsEndpoint})}async getElevationGrid(t,e,i){const n={lat:(t.south+t.north)/2,lng:(t.west+t.east)/2};if(!Le.covers(n.lat,n.lng))throw new Error("The IGN's relief covers France only");const s=Math.abs(se(n.lat,t.east,n.lat,t.west).x),r=Math.abs(se(t.north,n.lng,t.south,n.lng).z);e=this.finer(e,s,r);const a={x:s/Math.max(1,e.width-1),y:r/Math.max(1,e.height-1)},c={x:Math.min(a.x,this.maxWindowM),y:Math.min(a.y,this.maxWindowM)},l={south:t.south-c.y/Ce.METRES_PER_DEGREE,north:t.north+c.y/Ce.METRES_PER_DEGREE,west:t.west-c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180)),east:t.east+c.x/(Ce.METRES_PER_DEGREE*Math.cos(n.lat*Math.PI/180))},h=m=>Math.min(Ce.MAX_PIXELS,Math.max(Ce.MIN_PIXELS,Math.ceil(m/Ce.METRES_PER_PIXEL))),u={width:h(s+2*c.x),height:h(r+2*c.y)},d={x:(s+2*c.x)/u.width,y:(r+2*c.y)/u.height};let f=new Error("No layer of the IGN's relief answered");const p=Math.max(d.x,d.y)>Ce.COARSE_METRES_PER_PIXEL;for(const m of p?[...Ce.LAYERS].reverse():Ce.LAYERS)try{const g=await this.heights(l,u,m);m===Ce.LAYERS[0]&&await this.layBridgeDecks(g,l,u,i?.route);const v=this.sample(g,e,t,l,d,a);if(v)return{heights:v,width:e.width,height:e.height,bounds:t};f=new Error(`${m} does not cover this place`)}catch(g){f=g}throw f}finer(t,e,i){if(t.width<Ce.MESH_FROM_VERTICES||t.height<Ce.MESH_FROM_VERTICES)return t;const n=(s,r)=>{const a=Math.ceil(s/Ce.FINE_SPACING_M),c=Math.max(r-1,Math.min(Ce.MAX_SEGMENTS,a));return c%2===0?c:c+1};return{width:n(e,t.width)+1,height:n(i,t.height)+1}}async raster(t,e,i){const n=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(r=>r.toFixed(6)).join(","),WIDTH:String(e.width),HEIGHT:String(e.height),FORMAT:"image/geotiff"}),s=await this.fetchImpl(`${this.wms}?${n}`,{signal:AbortSignal.timeout(this.timeoutMs)});if(!s.ok)throw new Error(`The IGN's relief answered ${s.status}`);return Cp.parse(await s.arrayBuffer())}async heights(t,e,i){const n=await this.raster(t,e,i);if(n.samples!==1||!(n.values instanceof Float32Array))throw new Error("The IGN's relief came in a layout this does not read");return n}async layBridgeDecks(t,e,i,n){if(!(!n||n.length<2)&&!(!(t.values instanceof Float32Array)||!t.values.some(s=>s>Ce.NO_DATA_BELOW)))try{const s=(await this.geoplatform.elevatedRoadLines({west:e.west,south:e.south,east:e.east,north:e.north})).filter(a=>bo.follows(n,a));if(s.length===0)return;const r=Float32Array.from(t.values);await this.layClassifiedDecks(t,e,i,s),this.layRouteDecks(t,r,e,s)}catch{}}async layClassifiedDecks(t,e,i,n){try{const s=await this.raster(e,i,Ce.CLASS_LAYER);if(s.samples<3||s.width!==t.width||s.height!==t.height)return;const r=(g,[v,M,x])=>s.values[g*s.samples]===v&&s.values[g*s.samples+1]===M&&s.values[g*s.samples+2]===x,a=t.width,c=t.height,l=new Uint8Array(a*c);let h=!1;for(let g=0;g<l.length;g++)r(g,Ce.DECK)&&(l[g]=1,h=!0);if(!h)return;const u=Ce.DECK_END_PIXELS,d=[];for(let g=0;g<l.length;g++){if(l[g]!==1)continue;const v=g%a,M=(g-v)/a;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>=a||S>=c)continue;const E=S*a+w;l[E]===0&&r(E,Ce.NO_CLASS)&&d.push(E)}}for(const g of d)l[g]=1;const f=this.paint(n,e,a,c),p=this.touching(l,f,a,c);if(p.every(g=>g===0))return;const m=await this.heights(e,i,Ce.SURFACE_LAYER);if(m.width!==a||m.height!==c)return;for(let g=0;g<p.length;g++){if(p[g]===0)continue;const v=m.values[g];Number.isFinite(v)&&v>Ce.NO_DATA_BELOW&&v>t.values[g]&&(t.values[g]=v)}}catch{}}layRouteDecks(t,e,i,n){const{width:s,height:r}=t,a=(i.north+i.south)/2,c=(i.east-i.west)*Ce.METRES_PER_DEGREE*Math.cos(a*Math.PI/180),l=(i.north-i.south)*Ce.METRES_PER_DEGREE,h=c/s,u=l/r,d=v=>({x:(v.lng-i.west)/(i.east-i.west)*c,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>=s||y>=r)return;const w=e[y*s+x];return Number.isFinite(w)&&w>Ce.NO_DATA_BELOW?w:void 0},p=Ce.DECK_HALF_WIDTH_M,m=Ce.DECK_APPROACH_M,g=(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,m/2,m].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 Ce.chains(n.map(M=>M.map(d)))){const M=[0];for(let I=1;I<v.length;I++)M.push(M[I-1]+Math.hypot(v[I].x-v[I-1].x,v[I].y-v[I-1].y));const x=M[M.length-1];if(x<1||x>Ce.DECK_STRAIGHT_MAX_M)continue;const y=g(v[0],v[1]),w=g(v[v.length-1],v[v.length-2]);if(y===void 0||w===void 0)continue;const S=p+m,E=Math.max(0,Math.floor((Math.min(...v.map(I=>I.x))-S)/h)),b=Math.min(s-1,Math.ceil((Math.max(...v.map(I=>I.x))+S)/h)),A=Math.max(0,Math.floor((Math.min(...v.map(I=>I.y))-S)/u)),_=Math.min(r-1,Math.ceil((Math.max(...v.map(I=>I.y))+S)/u));for(let I=A;I<=_;I++)for(let D=E;D<=b;D++){const P=Ce.nearestAlong(v,M,{x:(D+.5)*h,y:(I+.5)*u});if(P.distance>p||P.s<-m||P.s>x+m)continue;const O=y+(w-y)*Math.min(1,Math.max(0,P.s/x)),N=I*s+D;e[N]>=O||(t.values[N]=O)}}}static chains(t){const e=t.filter(s=>s.length>=2).map(s=>[...s]),i=[],n=(s,r)=>Math.hypot(s.x-r.x,s.y-r.y)<=1;for(;e.length>0;){let s=e.shift(),r=!0;for(;r;){r=!1;for(let a=0;a<e.length;a++){const c=e[a],l=s[0],h=s[s.length-1];if(n(h,c[0]))s=[...s,...c.slice(1)];else if(n(h,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else if(n(l,c[c.length-1]))s=[...c.slice(0,-1),...s];else if(n(l,c[0]))s=[...[...c].reverse().slice(0,-1),...s];else continue;e.splice(a,1),r=!0;break}}i.push(s)}return i}static nearestAlong(t,e,i){let n={s:0,distance:1/0};for(let s=0;s<t.length-1;s++){const r=t[s],a=t[s+1],c=a.x-r.x,l=a.y-r.y,h=c*c+l*l;if(h<1e-9)continue;let u=((i.x-r.x)*c+(i.y-r.y)*l)/h;s>0&&(u=Math.max(0,u)),s<t.length-2&&(u=Math.min(1,u));const d=Math.hypot(i.x-(r.x+c*u),i.y-(r.y+l*u));d<n.distance&&(n={s:e[s]+u*Math.sqrt(h),distance:d})}return n}paint(t,e,i,n){const s=new Uint8Array(i*n),r=c=>(c-e.west)/(e.east-e.west)*i,a=c=>(e.north-c)/(e.north-e.south)*n;for(const c of t)for(let l=0;l<c.length-1;l++){const h=r(c[l].lng),u=a(c[l].lat),d=r(c[l+1].lng),f=a(c[l+1].lat),p=Math.max(1,Math.ceil(Math.hypot(d-h,f-u)*2));for(let m=0;m<=p;m++){const g=Math.floor(h+(d-h)*m/p),v=Math.floor(u+(f-u)*m/p);for(let M=-1;M<=1;M++)for(let x=-1;x<=1;x++){const y=g+x,w=v+M;y>=0&&w>=0&&y<i&&w<n&&(s[w*i+y]=1)}}}return s}touching(t,e,i,n){const s=new Uint8Array(t.length),r=new Uint8Array(t.length);for(let a=0;a<t.length;a++){if(t[a]===0||r[a]===1)continue;const c=[],l=[a];r[a]=1;let h=!1;for(;l.length>0;){const u=l.pop();c.push(u),e[u]===1&&(h=!0);const d=u%i,f=(u-d)/i;for(let p=-1;p<=1;p++)for(let m=-1;m<=1;m++){const g=d+m,v=f+p;if(g<0||v<0||g>=i||v>=n)continue;const M=v*i+g;t[M]===1&&r[M]===0&&(r[M]=1,l.push(M))}}if(h)for(const u of c)s[u]=1}return s}sample(t,e,i,n,s,r){const{width:a,height:c}=e,l=new Float32Array(a*c),h=new Uint8Array(a*c),u=Math.min(r.x,this.maxWindowM)/s.x,d=Math.min(r.y,this.maxWindowM)/s.y;let f=0;for(let p=0;p<c;p++){const m=i.north+(i.south-i.north)*(c===1?.5:p/(c-1)),g=(n.north-m)/(n.north-n.south)*t.height-.5;for(let v=0;v<a;v++){const x=(i.west+(i.east-i.west)*(a===1?.5:v/(a-1))-n.west)/(n.east-n.west)*t.width-.5,y=u>1||d>1?this.tent(t,x,g,Math.max(1,u),Math.max(1,d)):this.bilinear(t,x,g),w=p*a+v;y===void 0?f++:(l[w]=y,h[w]=1)}}if(!(f===a*c||f/(a*c)>Ce.MAX_HOLE_SHARE))return this.fill(l,h,a,c),l}tent(t,e,i,n,s){let r=0,a=0,c=0;const l=Math.max(0,Math.ceil(i-s)),h=Math.min(t.height-1,Math.floor(i+s)),u=Math.max(0,Math.ceil(e-n)),d=Math.min(t.width-1,Math.floor(e+n));for(let f=l;f<=h;f++){const p=1-Math.abs(f-i)/s;if(!(p<=0))for(let m=u;m<=d;m++){const g=p*(1-Math.abs(m-e)/n);if(g<=0)continue;c+=g;const v=t.at(m,f);!Number.isFinite(v)||v<Ce.NO_DATA_BELOW||(r+=g*v,a+=g)}}return c>0&&a>=c*.5?r/a:void 0}bilinear(t,e,i){const n=Math.max(0,Math.min(t.width-1,Math.floor(e))),s=Math.max(0,Math.min(t.height-1,Math.floor(i))),r=Math.min(t.width-1,n+1),a=Math.min(t.height-1,s+1),c=Math.max(0,Math.min(1,e-n)),l=Math.max(0,Math.min(1,i-s)),h=t.at(n,s),u=t.at(r,s),d=t.at(n,a),f=t.at(r,a);for(const g of[h,u,d,f])if(!Number.isFinite(g)||g<Ce.NO_DATA_BELOW)return;const p=h+(u-h)*c,m=d+(f-d)*c;return p+(m-p)*l}fill(t,e,i,n){let s=e.reduce((r,a)=>r+(a?0:1),0);for(;s>0;){const r=[];for(let a=0;a<n;a++)for(let c=0;c<i;c++){const l=a*i+c;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=a+d,m=c+f;p<0||m<0||p>=n||m>=i||!e[p*i+m]||(h+=t[p*i+m],u++)}u>0&&r.push([l,h/u])}if(r.length===0)return;for(const[a,c]of r)t[a]=c,e[a]=1;s-=r.length}}}class $_{providers;constructor(...t){this.providers=t}async getElevationGrid(t,e,i){let n=new Error("No source of relief to ask");for(const s of this.providers)try{return await s.getElevationGrid(t,e,i)}catch(r){n=r}throw n}}const S0=256,K_=5;async function Ab(o,t,e,i){const n=(o.south+o.north)/2,s=(o.west+o.east)/2,r=Math.abs(se(n,o.east,n,o.west).x),a=Math.abs(se(o.north,s,o.south,s).z),c=Math.max(r,a),{zoom:l,gridSize:h}=q_(n,c,Math.max(t.width,t.height)),{tiles:u,bounds:d}=bb(s,n,l,h),f=h*S0,p=document.createElement("canvas");p.width=f,p.height=f;const m=p.getContext("2d");if(!m)throw new Error("2D canvas context unavailable");const g=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());m.drawImage(E,(y.x-g.x)*S0,(y.y-g.y)*S0)}));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 q_(o,t,e){let i=H_(o,t/Math.max(1,e)),n=E2(o,i,t);for(;n>K_&&i>0;)i--,n=E2(o,i,t);return{zoom:i,gridSize:n,mPerPixel:xb(o,i)/S0}}function E2(o,t,e){const i=Math.ceil(e/2/xb(o,t));return Math.max(3,2*i+1)}class _b{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 Ab(t,e,i=>this.tileUrlTemplate.replace("{z}",String(i.z)).replace("{y}",String(i.y)).replace("{x}",String(i.x)),this.fetchImpl)}}class Rs{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=Rs.ENDPOINTS){const i=/\((-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)\)/.exec(t);if(!i)return[...e];const[n,s,r,a]=i.slice(1).map(Number),c=(n+r)/2,l=(s+a)/2,h=Rs.FRANCE;return c>=h.south&&c<=h.north&&l>=h.west&&l<=h.east?[Rs.FRANCE_ENDPOINT,...e.filter(d=>d!==Rs.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=Rs.queue.then(t,t);return Rs.queue=e.catch(()=>{}),e}async ask(t){let e;for(const i of this.endpoints??Rs.endpointsFor(t))for(let n=0;n<2;n++){try{const s=await this.fetchImpl(`${i}?data=${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Rs.HANG_MS)});if(s.ok)return await s.json();if(e=new Error(`${new URL(i).host} refused (${s.status})`),s.status!==429&&s.status!==504)break}catch(s){e=new Error(`${new URL(i).host} unreachable (${String(s)})`);break}await new Promise(s=>setTimeout(s,Rs.RETRY_MS))}throw e??new Error("No Overpass instance answered")}}class Eo{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 Rs(t)}async getRoads(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:30];way["highway"~"^(${Eo.DRIVABLE.join("|")})$"](${e});out geom;`;return this.waysFrom(await this.client.query(i))}waysFrom(t){const e=[];for(const i of t.elements??[]){const n=i.geometry,s=i.tags;!s||!n||n.length<2||e.push({id:`osm-${i.id??e.length}`,name:s.name,surface:Eo.surfaceOf(s),widthM:Eo.widthOf(s),...Eo.paintOf(s),points:n.map(r=>({lat:r.lat,lng:r.lon}))})}return e}static paintOf(t){const e=t.highway??"",i=t.junction==="roundabout"||t.junction==="circular",n=t.oneway,s=n==="yes"||n==="1"||n==="true"||n===void 0&&(e==="motorway"||i),r=n==="-1"||n==="reverse",a=Number.parseInt(t.lanes??"",10),c=Number.parseInt(t.maxspeed??"",10),l=i?"roundabout":e==="motorway"?"motorway":e.endsWith("_link")?"slip":(e==="trunk"||e==="primary")&&(s||r)?"dual":e?"road":void 0;return{...l?{kind:l}:{},...Number.isFinite(a)&&a>0?{lanes:a}:{},...n!==void 0||e==="motorway"||i?{direction:r?"backward":s?"forward":"both"}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{}}}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:Eo.WIDTH_M[t.highway]??Eo.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 um="https://ufoathome.org/roads/index.json";class Xl{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??Xl.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:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.ways)?(this.attributionRead=s.attribution,this.contemporaryRead=s.contemporary,s.ways):void 0}catch{return}}load(){if(this.index)return this.index;if(!this.sharing)return this.index=this.fetchFirstAvailable();const t=this.indexUrls.join(`
|
|
1924
|
-
`);let e=Xl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Xl.shared.set(t,e),e.then(i=>{i.length===0&&Xl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.
|
|
1925
|
-
`);let e=Yl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Yl.shared.set(t,e),e.then(i=>{i.length===0&&Yl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.3")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==dm?[e,dm]:[dm]).map(i=>i+t)}}class xs{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=xs.key(t);let i=xs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),xs.asked.set(e,i),i.catch(()=>xs.asked.delete(e))),structuredClone(await i)}static forget(){xs.asked.clear()}static key(t){return`v${xs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await xs.openCache(),n=xs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<xs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&xs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-xs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Do{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,n)=>Do.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Do.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Do.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Do.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Do.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}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 zn{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 Rs(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${zn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return zn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=zn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>se(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of zn.samples(a)){u++;const M=zn.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&c.set(x.name,(c.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=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}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 n=zn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}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=zn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=zn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>se(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=zn.SAMPLE_M/2;a<n;a+=zn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(zn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.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-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=zn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class $l{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 Rs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${$l.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=zn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=zn.voltageOf(r),l=$l.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=$l.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:$l.levelOf(r),points:s.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 j_{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(!Do.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 cn{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=cn.key(t);let i=cn.asked.get(e)??cn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},cn.asked.set(e,i),n.catch(()=>cn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){cn.asked.clear(),cn.failedAt=-1/0}static key(t){return`v${cn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of cn.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 cn.openCache(),n=cn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<cn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-cn.failedAt<cn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(cn.failedAt=this.now(),s)return s;throw a}return i&&cn.store(i,n,{savedAt:this.now(),lines:r}),r}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 n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-cn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(cn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const fm="https://ufoathome.org/railways/index.json";class Kl{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??Kl.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:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.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(`
|
|
1926
|
-
`);let e=Kl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Kl.shared.set(t,e),e.then(i=>{i.length===0&&Kl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.3")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==fm?[e,fm]:[fm]).map(i=>i+t)}}function Tb(){return{elevation:Rb(),imagery:Ib(),roads:Q_(),water:tT(),railways:eT()}}function Rb(){return new $_(new Ce,new Eb)}function Ib(){return new _b}function Q_(){return new Xl({fallback:new Z_(new Io,new Eo)})}function tT(){return new Yl({fallback:new xs(new J_(new Ed,new vc))})}function eT(){return new Kl({fallback:new cn(new j_(new Do,new $l))})}const iT=new Set,ph="show-observer-map",mh="hide-milestones",Ac="minified";class Be extends HTMLElement{static get observedAttributes(){return["src",ph,mh,Ac]}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 pi;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=Dp.create();issues=[];issueCheck=0;sightingAudio=new v2;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new v2(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>Be.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,n=!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 s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Be.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 Ct(async()=>{const{VideoButton:s}=await import("./VideoButton-Cy_r767Z.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.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?jd(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.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),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.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)<Be.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>=pi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=pi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Be.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 n=pi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${e3}</style>${t3}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Oh(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new gc(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",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const 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===ph&&this.applyObserverMapDefault(),t===mh&&this.setMilestonesShown(!this.hasAttribute(mh)),t===Ac){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Ac)}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(Cb)))};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 ju.recording(t)}get sightingData(){return db(this.currentSighting)}set sightingData(t){const e=na.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=pb(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 n=[];try{const{default:s}=await Ct(async()=>{const{default:r}=await import("./sightingSchema-pBDQNwMz.js");return{default:r}},[],import.meta.url);n=new tr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],bd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(sT,{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 n=document.createElement("li");return n.textContent=bd.text(i,this.messages.issueTemplates),n}))}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.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Be.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(nT,{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(n=>this.highlightedSourceIds.has(n))||(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 n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const 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 n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);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??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});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(s=>this.viewOfReference(s).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"),Be.setIcon(this.referencesButton,i?Jt.PICTURES_ON:Jt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Be.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?Cu(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.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 n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=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 n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,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=Be.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){const e=this.seekInput.getBoundingClientRect(),i=this.player.seekableDuration;if(e.width<=0||i<=0)return;const n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Be.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?jd(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}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 n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Oh(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 n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*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 n=Be.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}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 n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?jd(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 n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=xr.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Be.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Be.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Be.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Be.EXPOSURE_STEP_PX),s=Math.min(Be.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}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=$i.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:iT;this.canvasRenderer.setStarPoints($i.starPointsOf(this.sighting.instrument,ke(this.sighting,t)?.fNumber));const n=(ke(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Hs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).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(x_(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 w_(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*Be.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){Be.icons.get(t)!==e&&(Be.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},Be.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(),Be.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(ph),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;Be.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[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=hh.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(n=>n.points):[],i=pi.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?pi.expand(t,Be.OBSERVER_MAP_IMAGERY_AHEAD):t,n=pi.IMAGERY_PX*(e?1+2*Be.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:Ib();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?pi.expand(t,Be.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}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},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Be.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const 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,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ke(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},Be.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?jd(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Cu(this.currentSighting.milestones):[]){const a=ke(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position: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?aa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg($i.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(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,Cu(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??"",Be.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=ke(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=ha(i,t),{lat:s,lng:r}=Cs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.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 n=ke(this.currentSighting,this.currentTime),s=aa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ai.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=Be.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)),Be.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){Be.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}Be.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;Be.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 br(Ro.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=y0(Ro.preferencesFor(this),x0);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await N_.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=v_(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?jg(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 oo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?_2(A2(this.realStartMs+i)):oo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?oo(t):oo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return oo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return oo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?oo(this.currentSighting.timeline.duration):this.canShowClockTime?_2(A2(this.realStartMs+this.realDurationMs)):oo(this.realDurationMs)}}function A2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function _2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function oo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const t1="rr0-ufo";function Db(){customElements.get(t1)||customElements.define(t1,Be)}const nT="timechange",sT="recordingissues",Cb="minifiedreset";/**
|
|
1924
|
+
`);let e=Xl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Xl.shared.set(t,e),e.then(i=>{i.length===0&&Xl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.4")}`,e=typeof location>"u"?void 0:new URL("/roads/index.json",location.href).href;return(e&&e!==um?[e,um]:[um]).map(i=>i+t)}}class Io{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,n)=>Io.wayOf(i,n))}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 n=String(t.properties.nature??""),s=Io.BY_NATURE[n]??Io.DEFAULT,r=Number(t.properties.largeur_de_chaussee),a=Number(t.properties.nombre_de_voies),c=Number(t.properties.vitesse_moyenne_vl),l=Io.DIRECTIONS[String(t.properties.sens_de_circulation??"")],h=Io.KINDS[n],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:s.surface,widthM:Number.isFinite(r)&&r>0?r:s.widthM,...t.properties.urbain===!0?{urban:!0}:{},...h?{kind:h}:{},...Number.isInteger(a)&&a>0?{lanes:a}:{},...l?{direction:l}:{},...Number.isFinite(c)&&c>0?{speedKmh:c}:{},points:i}]}}class Z_{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(Io.covers(t))try{const e=await this.regional.getRoads(t);if(e.length>0)return e}catch{}return this.worldwide.getRoads(t)}}class Ed{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,n)=>Ed.surfacesOf(i,n))}static surfacesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="Polygon"?[n]:i==="MultiPolygon"?n:[],r=String(t.properties.cleabs??`ign-water-${e}`);return s.flatMap((a,c)=>{const l=a.map(h=>Ed.open(h.map(u=>({lat:u[1],lng:u[0]})))).filter(h=>h.length>=3);return l.length>0?[{id:s.length>1?`${r}-${c}`:r,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 vc{attribution="Water © OpenStreetMap contributors";client;constructor(t={}){this.client=new Rs(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 vc.surfacesFrom(await this.client.query(i))}static surfacesFrom(t){const e=t.elements??[],i=new Map;for(const r of e)r.type==="way"&&r.id!==void 0&&r.geometry&&i.set(r.id,r.geometry.map(a=>({lat:a.lat,lng:a.lon})));const n=[],s=new Set;for(const r of e){if(r.type!=="relation")continue;const a=l=>(r.members??[]).filter(h=>h.type==="way"&&h.role===l&&h.ref!==void 0&&i.has(h.ref)).map(h=>(s.add(h.ref),i.get(h.ref))),c=vc.rings(a("inner"));for(const[l,h]of vc.rings(a("outer")).entries()){const u=c.filter(d=>vc.contains(h,d[0]));n.push({id:`osm-r${r.id}-${l}`,rings:[h,...u]})}}for(const r of e)if(!(r.type!=="way"||!r.tags||r.id===void 0||s.has(r.id))&&!(r.tags.natural!=="water"&&r.tags.waterway!=="riverbank"))for(const a of vc.rings([i.get(r.id)??[]]))n.push({id:`osm-w${r.id}`,rings:[a]});return n}static rings(t){const e=(s,r)=>s.lat===r.lat&&s.lng===r.lng,i=t.filter(s=>s.length>=2).map(s=>[...s]),n=[];for(;i.length>0;){let s=i.pop(),r=!0;for(;!e(s[0],s[s.length-1])&&r;){r=!1;for(let a=0;a<i.length;a++){const c=i[a],l=s[s.length-1];if(e(l,c[0]))s=[...s,...c.slice(1)];else if(e(l,c[c.length-1]))s=[...s,...[...c].reverse().slice(1)];else continue;i.splice(a,1),r=!0;break}}s.length>=4&&e(s[0],s[s.length-1])&&n.push(s.slice(0,-1))}return n}static contains(t,e){let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n],a=t[s];r.lat>e.lat!=a.lat>e.lat&&e.lng<(a.lng-r.lng)*(e.lat-r.lat)/(a.lat-r.lat)+r.lng&&(i=!i)}return i}}class J_{constructor(t,e){this.regional=t,this.worldwide=e}attribution="Water © IGN, BD TOPO, in France; © OpenStreetMap contributors elsewhere";async getWater(t){if(Ed.covers(t))try{const e=await this.regional.getWater(t);if(e.length>0)return e}catch{}return this.worldwide.getWater(t)}}const dm="https://ufoathome.org/water/index.json";class Yl{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??Yl.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:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.surfaces)?(this.attributionRead=s.attribution,s.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(`
|
|
1925
|
+
`);let e=Yl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Yl.shared.set(t,e),e.then(i=>{i.length===0&&Yl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.4")}`,e=typeof location>"u"?void 0:new URL("/water/index.json",location.href).href;return(e&&e!==dm?[e,dm]:[dm]).map(i=>i+t)}}class xs{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=xs.key(t);let i=xs.asked.get(e);return i===void 0&&(i=this.recalled(e,t),xs.asked.set(e,i),i.catch(()=>xs.asked.delete(e))),structuredClone(await i)}static forget(){xs.asked.clear()}static key(t){return`v${xs.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}async recalled(t,e){const i=await xs.openCache(),n=xs.request(t);if(i)try{const r=await i.match(n);if(r){const{savedAt:a,surfaces:c}=await r.json();if(Date.now()-a<xs.MAX_AGE_MS&&Array.isArray(c))return c;await i.delete(n)}}catch{}const s=await this.water.getWater(e);return i&&xs.store(i,n,s),s}static async store(t,e,i){try{const n={savedAt:Date.now(),surfaces:i};await t.put(e,new Response(JSON.stringify(n),{headers:{"Content-Type":"application/json"}}));const s=await t.keys();for(const r of s.slice(0,Math.max(0,s.length-xs.MAX_STORED)))await t.delete(r)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(xs.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__water__/${encodeURIComponent(t)}`)}}class Do{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,n)=>Do.linesOf(i,n))}static linesOf(t,e){const{type:i,coordinates:n}=t.geometry,s=i==="LineString"?[n]:i==="MultiLineString"?n:[],r=Do.BY_NATURE[String(t.properties.nature??"")];if(!r)return[];const a=String(t.properties.cleabs??`ign-rail-${e}`),c=Number(t.properties.nombre_de_voies),l=Number(t.properties.position_par_rapport_au_sol),h=t.properties.cpx_toponyme,u=Do.GAUGE_MM[String(t.properties.largeur??"")]??1435,d=Do.electrificationOf(r.kind,u,t.properties.electrifie);return s.flatMap((f,p)=>{const m=f.map(g=>({lat:g[1],lng:g[0],...g.length>2&&Number.isFinite(g[2])&&g[2]>Do.NO_ALTITUDE?{altitudeM:g[2]}:{}}));return m.length<2?[]:[{id:s.length>1?`${a}-${p}`:a,...typeof h=="string"&&h.length>0?{name:h}:{},kind:r.kind,...r.service?{service:!0}:{},...r.highSpeed?{highSpeed:!0}:{},gaugeMm:u,tracks:Number.isInteger(c)&&c>0?c:1,...d?{electrification:d}:{},level:Number.isFinite(l)?l:0,points:m}]})}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 zn{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 Rs(t)}async named(t,e){if(t.length===0)return[...t];const i=`${e.south},${e.west},${e.north},${e.east}`,n=`[out:json][timeout:120];way["railway"~"^(${zn.KINDS})$"](${i})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return zn.apply(t,await this.client.query(n),e)}static apply(t,e,i){const n={lat:(i.north+i.south)/2,lng:(i.east+i.west)/2},s=zn.ways(e,n);return s.length===0?[...t]:t.map(r=>{const a=r.points.map(v=>se(v.lat,v.lng,n.lat,n.lng)),c=new Map,l=new Map,h=new Map;let u=0;const d=s.filter(v=>v.service===!!r.service);for(const v of zn.samples(a)){u++;const M=zn.waysAt(d,v);if(M.length===0)continue;const[x]=M;x.name&&c.set(x.name,(c.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=r.name??f(c),m=r.voltageV??(r.electrification==="none"?void 0:f(l)),g=[...h.entries()].filter(([,v])=>v*4>=u).sort((v,M)=>M[1]-v[1]||v[0].localeCompare(M[0])).map(([v])=>v);return{...r,...p?{name:p}:{},...m?{voltageV:m}:{},...g.length>0?{services:g}:{}}})}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 n=zn.serviceOf(i.tags);if(n)for(const s of i.members??[]){if(s.type!=="way"||s.ref===void 0)continue;const r=e.get(s.ref)??new Set;r.add(n),e.set(s.ref,r)}}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=zn.servicesByWay(t),n=[];for(const s of t.elements??[]){if(s.type!=="way"||!s.geometry||s.geometry.length<2)continue;const r=s.tags??{},a=zn.voltageOf(r);n.push({service:!!r.service||r.usage==="industrial",...r.name?{name:r.name}:{},...a?{voltageV:a}:{},services:[...i.get(s.id??-1)??[]],path:s.geometry.map(c=>se(c.lat,c.lon,e.lat,e.lng))})}return n}static samples(t){const e=[];for(let i=0;i<t.length-1;i++){const n=Math.hypot(t[i+1].x-t[i].x,t[i+1].z-t[i].z);if(n<1e-6)continue;const s=(t[i+1].x-t[i].x)/n,r=(t[i+1].z-t[i].z)/n;for(let a=zn.SAMPLE_M/2;a<n;a+=zn.SAMPLE_M)e.push({x:t[i].x+s*a,z:t[i].z+r*a,dx:s,dz:r})}return e}static waysAt(t,e){const i=Math.cos(zn.ALIGNED_DEG*Math.PI/180),n=[];for(const s of t){let r;for(let a=0;a<s.path.length-1;a++){const c=s.path[a],l=s.path[a+1],h=l.x-c.x,u=l.z-c.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-c.x)*h+(e.z-c.z)*u)/(d*d))),p=Math.hypot(e.x-(c.x+h*f),e.z-(c.z+u*f));p<=zn.NEAR_M&&(r===void 0||p<r)&&(r=p)}r!==void 0&&n.push({way:s,distance:r})}return n.sort((s,r)=>s.distance-r.distance).map(({way:s})=>s)}}class $l{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 Rs(t)}async getRailways(t){const e=`${t.south},${t.west},${t.north},${t.east}`,i=`[out:json][timeout:25];way["railway"~"^(${$l.KINDS.join("|")})$"](${e})->.w;.w out tags geom;rel(bw.w)["route"~"^(${zn.ROUTES})$"];out body;`;return this.linesFrom(await this.client.query(i))}linesFrom(t){const e=[],i=zn.servicesByWay(t);for(const n of t.elements??[]){const s=n.geometry,r=n.tags;if(n.type==="relation"||!r||!s||s.length<2)continue;const a=[...i.get(n.id??-1)??[]].sort(),c=zn.voltageOf(r),l=$l.kindOf(r),h=Number.parseInt((r.gauge??"").split(";")[0],10),u=Number.parseInt(r.tracks??"",10),d=$l.electrificationOf(r.electrified),f=r.highspeed==="yes"||Number.parseInt(r.maxspeed??"",10)>=250;e.push({id:`osm-rail-${n.id??e.length}`,...r.name?{name:r.name}:{},...a.length>0?{services:a}:{},...c?{voltageV:c}:{},kind:l,...r.service||r.usage==="industrial"?{service:!0}:{},...f?{highSpeed:!0}:{},gaugeMm:Number.isFinite(h)&&h>300?h:r.railway==="narrow_gauge"?1e3:1435,tracks:Number.isFinite(u)&&u>0?u:1,...d?{electrification:d}:{},level:$l.levelOf(r),points:s.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 j_{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(!Do.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 cn{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=cn.key(t);let i=cn.asked.get(e)??cn.containing(t);if(i===void 0){const n=this.recalled(e,t);i={bounds:t,answer:n},cn.asked.set(e,i),n.catch(()=>cn.asked.delete(e))}return structuredClone(await i.answer)}static forget(){cn.asked.clear(),cn.failedAt=-1/0}static key(t){return`v${cn.FORMAT}/${[t.north,t.south,t.east,t.west].map(e=>e.toFixed(5)).join("/")}`}static containing(t){for(const e of cn.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 cn.openCache(),n=cn.request(t);let s;if(i)try{const a=await i.match(n);if(a){const{savedAt:c,lines:l}=await a.json();if(Array.isArray(l)){if(this.now()-c<cn.MAX_AGE_MS)return l;s=l}}}catch{}if(this.now()-cn.failedAt<cn.RETRY_AFTER_MS){if(s)return s;throw new Error("The railway survey failed a moment ago: not asked again yet")}let r;try{r=await this.railways.getRailways(e)}catch(a){if(cn.failedAt=this.now(),s)return s;throw a}return i&&cn.store(i,n,{savedAt:this.now(),lines:r}),r}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 n=await t.keys();for(const s of n.slice(0,Math.max(0,n.length-cn.MAX_STORED)))await t.delete(s)}catch{}}static async openCache(){try{return typeof caches>"u"?void 0:await caches.open(cn.CACHE_NAME)}catch{return}}static request(t){const e=typeof location>"u"?"http://localhost":location.origin;return new Request(`${e}/__railways__/${encodeURIComponent(t)}`)}}const fm="https://ufoathome.org/railways/index.json";class Kl{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??Kl.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:n})=>n.north>=t.north&&n.south<=t.south&&n.east>=t.east&&n.west<=t.west);if(i)try{const n=await this.fetchImpl(new URL(i.entry.file,i.indexUrl).href);if(!n.ok)return;const s=await n.json();return Array.isArray(s?.lines)?(this.attributionRead=s.attribution,s.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(`
|
|
1926
|
+
`);let e=Kl.shared.get(t);return e||(e=this.fetchFirstAvailable(),Kl.shared.set(t,e),e.then(i=>{i.length===0&&Kl.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(n=>({entry:n,indexUrl:t}))}catch{}return[]}static defaultIndexUrls(){const t=`?v=${encodeURIComponent("0.178.4")}`,e=typeof location>"u"?void 0:new URL("/railways/index.json",location.href).href;return(e&&e!==fm?[e,fm]:[fm]).map(i=>i+t)}}function Tb(){return{elevation:Rb(),imagery:Ib(),roads:Q_(),water:tT(),railways:eT()}}function Rb(){return new $_(new Ce,new Eb)}function Ib(){return new _b}function Q_(){return new Xl({fallback:new Z_(new Io,new Eo)})}function tT(){return new Yl({fallback:new xs(new J_(new Ed,new vc))})}function eT(){return new Kl({fallback:new cn(new j_(new Do,new $l))})}const iT=new Set,ph="show-observer-map",mh="hide-milestones",Ac="minified";class Be extends HTMLElement{static get observedAttributes(){return["src",ph,mh,Ac]}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 pi;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=Dp.create();issues=[];issueCheck=0;sightingAudio=new v2;liveSightingAudio;hearInto(t){t?(this.liveSightingAudio??=this.sightingAudio,this.sightingAudio=new v2(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>Be.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,n=!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 s of["nomoments","compact","tiny"]){if(!i())break;t.classList.add(s)}e&&t.classList.add("more-open")}this.momentsMenu.hidden=!n,this.updateMoreButton()}setControlsFolded(t){this.controlsRow.classList.toggle("more-open",!t),this.updateMoreButton()}updateMoreButton(){const t=this.controlsRow.classList.contains("more-open");Be.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 Ct(async()=>{const{VideoButton:s}=await import("./VideoButton-Cy_r767Z.js");return{VideoButton:s}},[],import.meta.url);if(this.videoElement!==e)return;const n=new i(t,e);this.videoButton=n,this.messages&&(n.messages=this.messages),this.stageElement.append(n.panel),n.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?jd(this.sighting.milestones,e):void 0,n=i?this.said.read(i.label)??"":void 0,s=this.canvas.getBoundingClientRect(),r=t.map&&!this.observerMapPanel.hidden?this.observerMapPanel.getBoundingClientRect():void 0;return{...i?{caption:{label:n,note:this.said.read(i.note)}}:{},...t.time?{time:this.formatPosition(e)}:{},...r&&s.width>0&&s.height>0?{map:{canvas:this.observerMapCanvas,left:(r.left-s.left)/s.width,top:(r.top-s.top)/s.height,width:r.width/s.width,height:r.height/s.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),n=this.said.read(i?.shape.title);if(!n){this.tooltip.hidden=!0;return}this.tooltip.textContent=n,this.tooltip.hidden=!1;const s=this.stageElement.getBoundingClientRect();this.tooltip.style.left=`${t.clientX-s.left+12}px`,this.tooltip.style.top=`${t.clientY-s.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)<Be.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>=pi.MAX_ZOOM,this.mapZoomOutButton.disabled=this.observerMapView.zoomFactor<=pi.MIN_ZOOM,this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}scheduleObserverMapImagery(){this.observerMapImageryTimer===void 0&&(this.observerMapImageryTimer=setTimeout(()=>{this.observerMapImageryTimer=void 0,this.loadObserverMapImagery()},Be.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 n=pi.pointAt(e,(t.clientX-i.left)/i.width,(t.clientY-i.top)/i.height);this.dispatchEvent(new CustomEvent("observerplace",{detail:n,bubbles:!0,composed:!0}))}constructor(){super(),this.shadow=this.attachShadow({mode:"open"});const t=document.createElement("template");t.innerHTML=`<style>${e3}</style>${t3}`,this.shadow.appendChild(t.content.cloneNode(!0)),this.stageElement=this.shadow.getElementById("stage"),this.canvas=this.shadow.getElementById("canvas"),this.canvasRenderer=new Oh(this.canvas.getContext("2d")),this.chromeCanvas=this.shadow.getElementById("chrome"),this.tooltip=this.shadow.getElementById("tooltip"),this.toolbar=this.shadow.getElementById("toolbar"),this.issuesBox=this.shadow.getElementById("issues"),this.issuesButton=this.shadow.getElementById("issues-button"),this.issuesPanel=this.shadow.getElementById("issues-panel"),this.issuesButton.addEventListener("click",a=>{a.stopPropagation(),this.issuesPanel.hidden=!this.issuesPanel.hidden,this.issuesButton.setAttribute("aria-expanded",String(!this.issuesPanel.hidden))}),this.playPauseButton=this.shadow.getElementById("play-pause"),this.fullscreenButton=this.shadow.getElementById("fullscreen"),this.cornerButtons=this.shadow.getElementById("corner-buttons"),this.observerMapButton=this.shadow.getElementById("observer-map"),this.referencesButton=this.shadow.getElementById("references"),this.tracesButton=this.shadow.getElementById("traces"),this.referenceOpacityInput=this.shadow.getElementById("reference-opacity"),this.referencesMenu=this.shadow.getElementById("references-menu"),this.milestonesButton=this.shadow.getElementById("milestones"),this.observerMapPanel=this.shadow.getElementById("observer-map-panel"),this.observerMapCanvas=this.shadow.getElementById("observer-map-canvas"),this.observerMapRenderer=new gc(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",a=>{a.key!=="Enter"&&a.key!==" "||(a.preventDefault(),this.toggleTimeDisplay())}),this.volumeInput=this.shadow.getElementById("volume"),this.controlsRow=this.shadow.querySelector(".controls"),this.momentsBox=this.shadow.getElementById("moments"),this.momentsButton=this.shadow.getElementById("moments-button"),this.momentsCurrent=this.shadow.getElementById("moments-current"),this.momentsMenu=this.shadow.getElementById("moments-menu"),this.momentsButton.addEventListener("click",()=>this.toggleMomentsMenu()),this.moreButton=this.shadow.getElementById("controls-more"),this.moreButton.addEventListener("click",()=>this.setControlsFolded(this.controlsRow.classList.contains("more-open"))),this.muteButton.addEventListener("click",()=>this.toggleMuted()),this.miniPlayed=this.shadow.getElementById("mini-played"),this.miniRemaining=this.shadow.getElementById("mini-remaining"),this.miniMuteButton=this.shadow.getElementById("mini-mute"),this.miniDot=this.shadow.getElementById("mini-dot"),this.miniScrubTime=this.shadow.getElementById("mini-scrub-time");const e=this.shadow.getElementById("mini-bar"),i=e.querySelector(".mini-track"),n=a=>{const c=i.getBoundingClientRect(),l=this.player.seekableDuration;if(c.width<=0||l<=0)return;const h=Math.min(Math.max((a.clientX-c.left)/c.width,0),1)*l;this.player.seek(h),this.miniScrubTime.textContent=this.formatElapsedAt(h),this.miniScrubTime.style.left=this.miniDot.style.left};let s=!1;e.addEventListener("pointerdown",a=>{a.button===0&&(a.stopPropagation(),e.setPointerCapture(a.pointerId),e.classList.add("scrubbing"),s=this.playRequested,this.pause(),this.miniScrubTime.hidden=!1,n(a))}),e.addEventListener("pointermove",a=>{e.hasPointerCapture(a.pointerId)&&n(a)});const r=a=>{e.classList.contains("scrubbing")&&(e.classList.remove("scrubbing"),e.hasPointerCapture(a.pointerId)&&e.releasePointerCapture(a.pointerId),this.miniScrubTime.hidden=!0,s&&this.play())};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",r),e.addEventListener("click",a=>a.stopPropagation()),this.miniMuteButton.addEventListener("click",a=>{a.stopPropagation(),this.toggleMuted()}),this.stageElement.addEventListener("pointerenter",this.handleMinifiedEnter),this.stageElement.addEventListener("pointerleave",this.handleMinifiedLeave),this.volumeInput.addEventListener("input",()=>{this.setVolume(Number(this.volumeInput.value))}),this.fullscreenTarget=this.stageElement,this.playPauseButton.addEventListener("click",()=>this.togglePlayPause()),this.fullscreenButton.addEventListener("click",()=>this.toggleFullscreen()),this.addEventListener("keydown",this.handleFullscreenKey),this.observerMapButton.addEventListener("click",()=>this.toggleObserverMap()),this.referencesButton.addEventListener("click",()=>this.toggleReferences()),this.tracesButton.addEventListener("click",()=>this.toggleTraces()),this.referenceOpacityInput.addEventListener("input",()=>{this.referenceOpacityTouched=!0,this.dispatchReferenceView()}),this.milestonesButton.addEventListener("click",()=>this.toggleMilestones()),this.observerMapCanvas.addEventListener("pointermove",this.handleObserverMapPointerMove),this.observerMapCanvas.addEventListener("pointerleave",this.handlePointerLeave),this.observerMapCanvas.addEventListener("click",this.handleObserverMapClick),this.observerMapCanvas.addEventListener("pointerdown",this.handleObserverMapPointerDown),this.observerMapCanvas.addEventListener("pointerup",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("pointercancel",this.handleObserverMapPointerUp),this.observerMapCanvas.addEventListener("wheel",this.handleObserverMapWheel,{passive:!1}),this.mapZoomInButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,2)),this.mapZoomOutButton.addEventListener("click",()=>this.zoomObserverMap(.5,.5,.5)),this.mapFitButton.addEventListener("click",()=>{this.observerMapView.reset(),this.observerMapViewChanged()}),this.seekInput.addEventListener("input",()=>{this.player.seek(this.snapSeekToMark(Number(this.seekInput.value))),this.announceReveal()}),this.seekInput.addEventListener("pointerdown",a=>{this.suspendForScrub(),this.seekSnapArmed=!0,this.nameMarkUnder(a),this.seekPreview.hidden=!0,this.beginTouchScrub(a)}),this.seekInput.addEventListener("pointerup",a=>{this.seekSnapArmed=!1,this.endTouchScrub(a)}),this.seekInput.addEventListener("pointercancel",a=>this.endTouchScrub(a)),this.seekInput.addEventListener("pointermove",a=>{this.nameMarkUnder(a),this.hoverSeek(a),this.touchScrub(a)}),this.seekInput.addEventListener("pointerleave",()=>{this.seekInput.removeAttribute("title"),this.leaveSeek()}),this.seekInput.addEventListener("keydown",this.handleSeekKey),this.stageElement.addEventListener("pointerdown",()=>{this.handlePointerDown(),this.touchedStage()},!0);for(const a of["touchend","click"])this.stageElement.addEventListener(a,()=>this.sightingAudio.resume(),!0);this.stageElement.addEventListener("pointermove",()=>this.touchedStage()),this.canvas.addEventListener("click",a=>{if(!(!this.enableClickToPlay||this.minified)){if(this.tapRevealedOnly){this.tapRevealedOnly=!1;return}a.detail<=1&&(this.playbackBeforeClick={state:this.playbackState,time:this.currentTime}),this.togglePlayPause()}}),this.canvas.addEventListener("dblclick",a=>{!this.enableClickToPlay||this.minified||(a.preventDefault(),this.restorePlayback(),this.toggleFullscreen())}),this.canvas.addEventListener("pointermove",this.handlePointerMove),this.canvas.addEventListener("pointerleave",this.handlePointerLeave),document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("pointerdown",this.handleMomentsDismiss,!0),document.addEventListener("keydown",this.handleMomentsDismiss,!0),document.addEventListener("visibilitychange",this.handleVisibility),window.addEventListener("pagehide",this.handleHidden),document.addEventListener("pointerup",this.handlePointerRelease,!0),document.addEventListener("pointercancel",this.handlePointerRelease,!0),this.observerMapResizeObserver?.observe(this.observerMapPanel),this.chromeResizeObserver?.observe(this.chromeCanvas),this.controlsFitObserver?.observe(this.controlsRow),this.controlsFitObserver?.observe(this.controlsRow.querySelector(".controls-left")),typeof MutationObserver<"u"&&(this.controlsMutations=new MutationObserver(()=>this.fitControls()),this.controlsMutations.observe(this.controlsRight,{attributes:!0,attributeFilter:["hidden"],childList:!0,subtree:!0})),this.hostControls(void 0),this.player=this.createPlayer(),this.updateTimeLabels(),this.updatePlayPauseButton(),this.updateFullscreenButton(),this.updateMuteButton(),this.updateObserverMapButton(),this.updateReferencesButton(),this.updateTracesButton(),this.updateMilestonesButton(),this.refresh()}connectedCallback(){this.saidTexts=void 0,this.ready=this.loadLocaleMessages();const 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===ph&&this.applyObserverMapDefault(),t===mh&&this.setMilestonesShown(!this.hasAttribute(mh)),t===Ac){const n=this.minified;this.stageElement.classList.toggle("minified",n),n&&e===null&&(this.muted=!0),this.updateStartState()}}get minified(){return this.hasAttribute(Ac)}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(Cb)))};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 ju.recording(t)}get sightingData(){return db(this.currentSighting)}set sightingData(t){const e=na.recording(t);this.player.stop(),this.soundPreview=void 0,this.sightingAudio.silence(),this.currentSighting=pb(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 n=[];try{const{default:s}=await Ct(async()=>{const{default:r}=await import("./sightingSchema-pBDQNwMz.js");return{default:r}},[],import.meta.url);n=new tr(s).issues(t)}catch{}i===this.issueCheck&&(this.issues=[...n,...e.loadIssues],bd.warn(this.issues,e.id),this.renderIssues(),this.dispatchEvent(new CustomEvent(sT,{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 n=document.createElement("li");return n.textContent=bd.text(i,this.messages.issueTemplates),n}))}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.style.left=`${Math.min(Math.max(e.at*1e3/t,0),1)*100}%`;const n=e.quote??"";return i.title=n,i.setAttribute("aria-label",n),i.addEventListener("click",()=>this.player.seek(e.at*1e3)),i}))}sayTimeMoved(t){Math.abs(t-this.timeSaid)<Be.TIME_SAID_EVERY_MS||(this.timeSaid=t,this.dispatchEvent(new CustomEvent(nT,{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(n=>this.highlightedSourceIds.has(n))||(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 n of e)this.controlsRight.insertBefore(n,i)}}get referencesShown(){return this.referencesShownState}get referenceOpacity(){return Number(this.referenceOpacityInput.value)}get severalReferences(){return this.currentSighting.references.length>1}toggleReferences(){if(this.severalReferences){this.toggleReferencesMenu();return}this.referencesShownState=!this.referencesShownState,this.updateReferencesButton(),this.dispatchReferenceView()}updateReferences(){const 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 n=e.getBoundingClientRect().width;e.style.left=`${Math.max(i,Math.min(t.left,window.innerWidth-n-i))}px`}renderReferencesMenu(){const t=this.currentSighting.references.map(e=>{const i=this.viewOfReference(e),n=this.said.read(e.title)??e.id,s=document.createElement("div");s.className="reference-row";const r=document.createElement("label"),a=document.createElement("input");a.type="checkbox",a.checked=i.shown;const c=document.createElement("span");c.textContent=n,c.title=n,r.append(a,c);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??""}: ${n}`),l.disabled=!i.shown,a.addEventListener("change",()=>{i.shown=a.checked,l.disabled=!i.shown,this.updateReferencesButton(),this.dispatchReferenceView()}),l.addEventListener("input",()=>{i.opacity=Number(l.value),this.dispatchReferenceView()}),s.append(r,l),s});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(s=>this.viewOfReference(s).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"),Be.setIcon(this.referencesButton,i?Jt.PICTURES_ON:Jt.PICTURES_OFF);const n=e?this.messages?.referencesMenu??"":this.referencesShownState?this.messages?.hideReferences??"":this.messages?.showReferences??"";this.referencesButton.title=n,this.referencesButton.setAttribute("aria-label",n),this.referenceOpacityInput.title=this.messages?.referenceOpacity??"",this.referenceOpacityInput.setAttribute("aria-label",this.messages?.referenceOpacity??"")}get tracesShown(){return this.tracesShownState}toggleTraces(){this.tracesShownState=!this.tracesShownState,this.updateTracesButton(),this.updateObserverMap(),this.dispatchEvent(new CustomEvent("traceview",{detail:{shown:this.tracesShown}}))}updateTracesButton(){this.tracesButton.hidden=this.currentSighting.traces.length===0,this.tracesButton.setAttribute("aria-pressed",String(this.tracesShownState)),Be.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?Cu(this.sighting.milestones):[];this.milestoneMarks.replaceChildren(...e.map(i=>{const n=document.createElement("button");n.type="button",n.className="milestone-mark",n.style.left=`${Math.min(Math.max(i.t/t,0),1)*100}%`;const s=this.said.read(i.label)??"",r=this.said.read(i.note),a=r?`${s} — ${r}`:s;return n.title=a,n.setAttribute("aria-label",a),n.dataset.t=String(i.t),n.addEventListener("click",()=>this.player.seek(i.t)),n})),this.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 n=document.createElement("li"),s=document.createElement("button");s.type="button",s.dataset.t=String(i.t);const r=this.said.read(i.label)??"",a=this.said.read(i.note);return s.textContent=a?`${r} — ${a}`:r,s.addEventListener("click",()=>{this.player.seek(i.t),this.closeMomentsMenu()}),n.appendChild(s),n})),this.momentsButton.title=this.messages?.moments??"",this.showCurrentMoment(void 0)}showCurrentMoment(t){const i=(t?this.said.read(t.label)??"":"")||(this.messages?.moments??"");this.momentsCurrent.textContent!==i&&(this.momentsCurrent.textContent=i);for(const n of this.momentsMenu.querySelectorAll("button")){const s=t!==void 0&&Number(n.dataset.t)===t.t;n.getAttribute("aria-current")==="true"!==s&&n.setAttribute("aria-current",String(s))}}toggleMomentsMenu(){this.momentsMenu.hidden?(this.momentsMenu.hidden=!1,this.momentsButton.setAttribute("aria-expanded","true")):this.closeMomentsMenu()}closeMomentsMenu(){this.momentsMenu.hidden=!0,this.momentsButton.setAttribute("aria-expanded","false")}handleMomentsDismiss=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 n=[0,...this.milestonesShown&&t>0?[...new Set(e.filter(r=>r>0&&r<t))].sort((r,a)=>r-a):[],Math.max(t,0)];this.seekSegmentList=[];const s=[];for(let r=0;r<n.length-1;r++){const a=document.createElement("div");a.className="seek-segment",a.style.flexGrow=String(Math.max(n[r+1]-n[r],1));const c=document.createElement("i");c.className="seek-hover";const l=document.createElement("i");l.className="seek-played",a.append(c,l),s.push(a),this.seekSegmentList.push({start:n[r],end:n[r+1],element:a,played:l,hover:c})}this.seekSegments.replaceChildren(...s),this.paintSeekProgress(this.player.time)}static fillOf(t,e){const i=t.end-t.start,n=i>0?(e-t.start)/i:e>=t.end?1:0;return`${Math.min(Math.max(n,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=Be.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 n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1),s=n*i,r=this.seekSegmentList.length-1;this.seekSegmentList.forEach((f,p)=>{f.hover.style.width=Be.fillOf(f,s),f.element.classList.toggle("hovered",s>=f.start&&(s<f.end||p===r))});const a=this.milestonesShown?this.sighting.milestones:[],c=a.length>0?jd(a,s):void 0,l=c?this.said.read(c.label)??"":"",h=c?this.said.read(c.note):void 0,u=h?`${l} — ${h}`:l;this.seekPreviewTitle.textContent=u,this.seekPreviewTime.textContent=this.formatPosition(s),this.seekPreview.hidden=!1;const d=this.seekPreview.offsetWidth;this.seekPreview.style.left=`${Math.min(Math.max(n*e.width-d/2,0),Math.max(e.width-d,0))}px`,this.paintSeekPreview(s)}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 n=this.chromeCanvas.clientWidth,s=this.chromeCanvas.clientHeight;if(!e||typeof e.setTransform!="function"||n===0||s===0){t(this.canvasRenderer);return}const r=window.devicePixelRatio||1,a=Math.max(1,Math.round(n*r)),c=Math.max(1,Math.round(s*r));this.chromeCanvas.width!==a&&(this.chromeCanvas.width=a),this.chromeCanvas.height!==c&&(this.chromeCanvas.height=c),e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,a,c),this.chromeDirty=!1,i&&(e.setTransform(a/this.canvas.width,0,0,c/this.canvas.height,0,0),this.chromeRenderer??=new Oh(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 n=Math.min(Math.max((t.clientX-e.left)/e.width,0),1);this.player.seek(this.snapSeekToMark(n*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 n=Be.MARK_SNAP_PX/i*e;let s;for(const r of this.milestoneMarks.children){const a=Number(r.dataset.t);Math.abs(a-t)>n||(!s||Math.abs(a-t)<Math.abs(s.t-t))&&(s={t:a,name:r.title})}return s}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 n=(t.clientX-e.left)/e.width*i,s=this.markNear(n);s?this.seekInput.title=s.name:this.seekInput.removeAttribute("title")}showMilestoneAt(t){const e=this.milestonesShown&&this.sighting.milestones.length>0?jd(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 n=this.said.read(e.note),s=n?` — ${n}`:"";this.milestoneCaption.replaceChildren(i,document.createTextNode(s))}exposureInstants(t){const e=this.exposureTimes(t),i=1/e.length;return e.map(n=>({shapes:this.shapesAt(n),share:i}))}exposureTimes(t=this.currentTime){const e=xr.windowEndingAt(t,this.currentSighting.exposure??0);if(e.ms<Be.SHORTEST_VISIBLE_EXPOSURE_MS)return[t];const i=Math.min(Be.MAX_EXPOSURE_STEPS,Math.max(2,Math.round(e.ms/Be.SHORTEST_VISIBLE_EXPOSURE_MS))),n=Math.ceil(this.travelPxOver(e.fromMs,e.ms)/Be.EXPOSURE_STEP_PX),s=Math.min(Be.MAX_TRAVEL_STEPS,Math.max(i,n)),r=[];for(let a=0;a<s;a++)r.push(e.fromMs+e.ms*a/(s-1));return r}travelPxOver(t,e){const i=this.shapesAt(t),n=this.shapesAt(t+e);let s=0;for(const[r,a]of i){const c=n.get(r);if(!c)continue;const l=c.bounds.x+c.bounds.width/2-(a.bounds.x+a.bounds.width/2),h=c.bounds.y+c.bounds.height/2-(a.bounds.y+a.bounds.height/2);s=Math.max(s,Math.hypot(l,h))}return s}shapeAt(t,e,i){if(!this.accountHidden)for(const n of this.exposureTimes()){const s=this.currentSighting.timeline.hitTest(n,t,e,i);if(s)return s}}shapesAt(t){const e=new Map;for(const i of this.currentSighting.timeline.sourceIds){const n=this.currentSighting.timeline.getInterpolatedShapeAt(t,i);n&&e.set(i,n)}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=$i.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:iT;this.canvasRenderer.setStarPoints($i.starPointsOf(this.sighting.instrument,ke(this.sighting,t)?.fNumber));const n=(ke(this.sighting,t)?.rollDeg??0)+this.gaitAt(t).rollDeg;this.canvasRenderer.setRoll(n*Math.PI/180);const s=this.exposureInstants(t),r=this.frameShift;if(this.paintsShapes)for(const c of s)for(const[,l]of c.shapes){const h=c.share,u=h===1?l:{...l,transparency:1-(1-l.transparency)*h};this.canvasRenderer.paintShape(this.shifted(u,r))}for(const[c,l]of s[0].shapes)!this.selectionShown||!i.has(c)||(this.paintsShapes?i.size===1?this.canvasRenderer.paintShape({...l,selected:!0}):this.canvasRenderer.paintMemberOutline(l):this.canvasRenderer.paintSelectionOnly(this.shifted(l,r)));const a=this.selectionShown&&i.size>1?Hs.groupBoundsFor([...e].filter(([c])=>i.has(c)).map(([,c])=>c.bounds)):void 0;this.chromeDraw=c=>{a&&c.paintGroupHandles(a),this.overlayPainter?.(c)},this.paintChrome(this.chromeDraw),this.mapShapeBounds=s.flatMap(c=>[...c.shapes.values()].filter(l=>l.transparency<1).map(l=>this.shifted(l,r).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(x_(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 w_(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*Be.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){Be.icons.get(t)!==e&&(Be.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},Be.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(),Be.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(ph),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;Be.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[n,s]of i)n.title=s,n.setAttribute("aria-label",s)}updateObserverMap(){const t=this.observerPath!==void 0;if(this.observerPath=hh.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(n=>n.points):[],i=pi.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?pi.expand(t,Be.OBSERVER_MAP_IMAGERY_AHEAD):t,n=pi.IMAGERY_PX*(e?1+2*Be.OBSERVER_MAP_IMAGERY_AHEAD:1);this.observerMapImageryBounds=i,this.observerMapImageryViewWidth=t.east-t.west,this.observerMapImageryLoading=!0;const s=this.observerMapSnapshotImagery,r=s?void 0:Ib();try{const a=r?await r.getImageryTexture(i,{width:n,height:n}):await s.getImagery();if(this.observerMapImageryBounds!==i)return;this.observerMapImagery=a,this.observerMapImageryCredit=(r??s).attribution,this.observerMapImageryFailed=!1}catch{if(this.observerMapImageryBounds!==i)return;this.observerMapImageryFailed=this.observerMapImagery===void 0}finally{this.observerMapImageryBounds===i&&(this.observerMapImageryLoading=!1)}this.paintObserverMap(this.currentTime),this.scheduleObserverMapImagery()}static OBSERVER_MAP_IMAGERY_AHEAD=.5;static OBSERVER_MAP_IMAGERY_LOOKAHEAD=.25;observerMapImageryNeededFor(t){const e=this.observerMapImageryBounds;if(!e)return!0;const i=this.observerMapImagery?.bounds??e,n=this.observerMapView.changed?pi.expand(t,Be.OBSERVER_MAP_IMAGERY_LOOKAHEAD):t,s=n.west>=i.west&&n.east<=i.east&&n.south>=i.south&&n.north<=i.north,r=t.east-t.west>this.observerMapImageryViewWidth/2;return!s||!r}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},n=[this.canvas.width-t.width,this.canvas.width],s=[0,t.width],r=Be.OBSERVER_MAP_CLEARANCE_PX,a=i(...n,0),c=i(...s,0);if(this.observerMapPanel.classList.toggle("subject-overlap",a&&c&&!this.observerMapAsked),this.observerMapPanel.classList.contains("on-the-left")){!a&&(c||!i(n[0],n[1],r))&&this.observerMapPanel.classList.remove("on-the-left");return}i(n[0],n[1],0)&&!i(s[0],s[1],0)&&this.observerMapPanel.classList.add("on-the-left")}observerMapBoxPx;static OBSERVER_MAP_CLEARANCE_PX=24;sizeObserverMapCanvas(){const 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,n=this.canvas.height/e.height;this.observerMapBoxPx={width:t.width*i,top:(t.top-e.top)*n,bottom:(t.bottom-e.top)*n}}paintObserverMap(t){if(this.observerMapPanel.hidden||!this.observerPath||!this.observerMapBounds)return;const e=ke(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},Be.OBSERVER_MAP_FOLLOW_MARGIN)&&this.scheduleObserverMapImagery();const i=this.currentSighting.instrument,n=[],s=this.currentSighting.milestones.length>0?jd(this.currentSighting.milestones,t):void 0;for(const r of this.milestonesShown?Cu(this.currentSighting.milestones):[]){const a=ke(this.currentSighting,r.t);a?.lat===void 0||a.lng===void 0||n.push({label:this.said.read(r.label)??"",note:this.said.read(r.note),t:r.t,lat:a.lat,lng:a.lng,current:r===s})}this.observerMapRenderer.paint({bounds:this.observerMapViewBounds,imagery:this.observerMapImagery,path:this.observerPath,position: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?aa.of(i,this.canvas.height,e.fovDeg).halfWidthAngleDeg($i.aspectOf(i)):void 0,markers:n,traces:(this.tracesShownState?this.currentSighting.traces:[]).map(r=>({kind:r.kind,points:r.points,color:r.color,label:this.said.read(r.title)})),decor:this.observerMapDecorAt(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,Cu(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??"",Be.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=ke(this.currentSighting,0);return e?.lat===void 0||e.lng===void 0?[]:this.currentSighting.decor.filter(i=>i.kind!=="crop").map(i=>{const n=ha(i,t),{lat:s,lng:r}=Cs(n.eastM,-n.northM,e.lat,e.lng);return{lat:s,lng:r,headingDeg:n.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 n=ke(this.currentSighting,this.currentTime),s=aa.of(this.currentSighting.instrument,this.canvas.height,n?.fovDeg??60);return{x:-s.angleDegToRadiusPx(e),y:s.angleDegToRadiusPx(i)}}gaitAt(t){return ai.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=Be.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)),Be.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){Be.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}Be.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;Be.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 br(Ro.preferencesFor(this))}saidTexts;async loadLocaleMessages(){const t=y0(Ro.preferencesFor(this),x0);if(t===this.messagesLanguage)return;this.messagesLanguage=t;const e=await N_.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=v_(t);this.realDurationMs=e!==void 0&&e>0?e:void 0,this.realStartMs=t.time?jg(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 oo(t);const e=this.currentSighting.timeline.duration,i=e>0&&t<=e?t/e*this.realDurationMs:t;return this.canShowClockTime?_2(A2(this.realStartMs+i)):oo(i)}formatElapsedAt(t){const e=this.currentSighting.timeline.duration;return this.realDurationMs===void 0?oo(t):oo(e>0&&t<=e?t/e*this.realDurationMs:t)}formatRemaining(t){const e=this.currentSighting.timeline.duration;if(this.realDurationMs===void 0)return oo(Math.max(0,e-t));const i=e>0&&t<=e?t/e*this.realDurationMs:t;return oo(Math.max(0,this.realDurationMs-i))}formatEndOfTimeline(){return this.realDurationMs===void 0?oo(this.currentSighting.timeline.duration):this.canShowClockTime?_2(A2(this.realStartMs+this.realDurationMs)):oo(this.realDurationMs)}}function A2(o){const t=new Date(o);return{hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds()}}function _2(o){if(o.hour===void 0)return"0:00";const t=e=>String(e).padStart(2,"0");return o.second?`${t(o.hour)}:${t(o.minute??0)}:${t(o.second)}`:`${t(o.hour)}:${t(o.minute??0)}`}function oo(o){const t=Math.round(o/1e3),e=Math.floor(t/60),i=t%60;return`${e}:${String(i).padStart(2,"0")}`}const t1="rr0-ufo";function Db(){customElements.get(t1)||customElements.define(t1,Be)}const nT="timechange",sT="recordingissues",Cb="minifiedreset";/**
|
|
1927
1927
|
* @license
|
|
1928
1928
|
* Copyright 2010-2026 Three.js Authors
|
|
1929
1929
|
* SPDX-License-Identifier: MIT
|
|
@@ -8256,7 +8256,7 @@ ${l.fragmentShader.replace("#include <emissivemap_fragment>",`#include <emissive
|
|
|
8256
8256
|
gl_FragColor = vec4(around * wall, wall + (1.0 - wall) * uAbsorption);
|
|
8257
8257
|
}
|
|
8258
8258
|
`,transparent:!0,depthWrite:!1,side:xn,fog:!1,blending:Bc,blendSrc:Hc,blendDst:Ad})}static wallReflectance(t,e,i){const n=i(t,1,e);return 2*n/(1+n)}setSurroundings(t){this.uniforms.uSurroundings.value=t}static reflectedResponse(t,e){return zt.respond(e*zt.relativeOfResponse(Math.max(t,1e-5)))}}class Ss{static SIZE=64;static MOVE_M=.01;holder=new Ni;cameras=[];faces=[];target=new Ze(Ss.SIZE,Ss.SIZE);white=new gs({color:new rt(1,1,1),side:xn});scene=new $s;cabin;meshes=0;eye=new R;scratch=new R;constructor(){const t=[[new R(1,0,0),new R(0,1,0)],[new R(-1,0,0),new R(0,1,0)],[new R(0,1,0),new R(0,0,1)],[new R(0,-1,0),new R(0,0,-1)],[new R(0,0,1),new R(0,1,0)],[new R(0,0,-1),new R(0,1,0)]];for(const[e,i]of t){const n=new Hn(90,1,.02,20);n.up.copy(i),n.lookAt(e),this.holder.add(n),this.cameras.push(n),this.faces.push(new Uint8Array(Ss.SIZE*Ss.SIZE*4))}this.scene.background=new rt(0,0,0)}get any(){return this.cabin!==void 0}update(t,e,i){if(!e){this.forget();return}e.updateWorldMatrix(!0,!0);const n=this.scratch.copy(i);e.worldToLocal(n);let s=0;e.traverse(r=>{r.isMesh&&s++}),!(e===this.cabin&&s===this.meshes&&n.distanceTo(this.eye)<Ss.MOVE_M)&&(this.cabin=e,this.meshes=s,this.eye.copy(n),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],n=this.scratch.copy(t).transformDirection(i.matrixWorldInverse);if(n.z>=0)continue;const s=n.x/-n.z,r=n.y/-n.z;if(Math.abs(s)>1||Math.abs(r)>1)continue;const a=Math.min(Ss.SIZE-1,Math.floor((s+1)/2*Ss.SIZE)),c=Math.min(Ss.SIZE-1,Math.floor((r+1)/2*Ss.SIZE));return this.faces[e][(c*Ss.SIZE+a)*4]>127}return!1}forget(){this.holder.removeFromParent(),this.cabin=void 0,this.meshes=0}dispose(){this.forget(),this.target.dispose(),this.white.dispose()}draw(t,e){e.add(this.holder),this.holder.position.copy(this.eye),this.holder.updateWorldMatrix(!0,!0);const i=[];e.traverse(r=>{const a=r;if(!a.isMesh||!a.visible||(Array.isArray(a.material)?a.material:[a.material]).every(h=>h instanceof Za))return;const l=new Mt(a.geometry,this.white);l.matrixAutoUpdate=!1,l.matrix.copy(a.matrixWorld),l.matrixWorld.copy(a.matrixWorld),i.push(l)});for(const r of i)this.scene.add(r);const n=t.getRenderTarget(),s=t.shadowMap.autoUpdate;t.shadowMap.autoUpdate=!1;for(let r=0;r<6;r++){const a=this.cameras[r];a.updateMatrixWorld(!0),t.setRenderTarget(this.target),t.clear(),t.render(this.scene,a),t.readRenderTargetPixels(this.target,0,0,Ss.SIZE,Ss.SIZE,this.faces[r])}t.setRenderTarget(n),t.shadowMap.autoUpdate=s;for(const r of i)r.removeFromParent()}}const mg="https://ufoathome.org/models/index.json";class Xu{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??B8()}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(`
|
|
8259
|
-
`);let e=Xu.shared.get(t);return e||(e=this.fetchFirstAvailable(),Xu.shared.set(t,e),e.then(i=>{i.length===0&&Xu.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:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function B8(){const o=`?v=${encodeURIComponent("0.178.
|
|
8259
|
+
`);let e=Xu.shared.get(t);return e||(e=this.fetchFirstAvailable(),Xu.shared.set(t,e),e.then(i=>{i.length===0&&Xu.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:n,...s})=>({...s,url:new URL(n,t).href})):void 0}catch{return}}}function B8(){const o=`?v=${encodeURIComponent("0.178.4")}`,t=typeof location>"u"?void 0:new URL("/models/index.json",location.href).href;return(t&&t!==mg?[t,mg]:[mg]).map(e=>e+o)}const H8=Re.point("decorModels").provide(Re.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 Xu}]);class vA{constructor(t,e=H8){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 n=this.built.get(i);return n||(n=i.create(),this.built.set(i,n)),n})}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=Re.point("decorModels");for(const i of this.sources){const n=e.ownerOf(i.id);if(!(n===void 0||n===Re.BUILT_IN)&&await this.catalogueOf(i).entry(t).catch(()=>{}))return n}}catalogueOf(t){return this.catalogues(),this.built.get(t)}}async function gg(o){const{GLTFLoader:t}=await Ct(async()=>{const{GLTFLoader:i}=await import("./GLTFLoader-BxToReDu.js");return{GLTFLoader:i}},[],import.meta.url),e=new t;return new Promise((i,n)=>{e.load(o,s=>i(Object.assign(s.scene,{animations:s.animations})),void 0,s=>n(new Error(`Could not load 3D model ${o}: ${s instanceof Error?s.message:String(s)}`)))})}const MA=["ellipsoid","sphere","disc","cylinder","cone","box","torus","figure"];class Vs{static MIN_ANGLE_RAD=.002;static FILL=(1-Math.exp(-4))/4;static MAX_SHARE=.3;mesh;constructor(t,e){this.mesh=new Mt(new as(2,2),new Te({uniforms:{uColor:{value:new rt(0,0,0)},uRadius:{value:1}},vertexShader:Vs.VERTEX,fragmentShader:Vs.FRAGMENT,transparent:!0,depthWrite:!1,blending:En,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,n){const s=Math.max(t,n*Vs.MIN_ANGLE_RAD),r=Vs.FILL*Math.PI*s*s;return{radiusM:s,luminanceCdM2:i*Math.min(Vs.MAX_SHARE,e/r)}}static conserving(t){return Math.sqrt(t/(Vs.MAX_SHARE*Vs.FILL*Math.PI))}static VERTEX=`
|
|
8260
8260
|
uniform float uRadius;
|
|
8261
8261
|
varying vec2 vOffset;
|
|
8262
8262
|
void main() {
|