@wemap/providers 13.2.1 → 13.2.3
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/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +101 -5
- package/dist/index.mjs.map +1 -1
- package/dist/package.json.d.ts +70 -0
- package/dist/src/providers/vision/vps/ImageRelocalization.d.ts +2 -2
- package/dist/src/providers/vision/vps/VpsProvider.d.ts +4 -0
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var t=Object.defineProperty,e=(e,i,s)=>(((e,i,s)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s})(e,"symbol"!=typeof i?i+"":i,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@wemap/geo"),s=require("@wemap/maths"),r=require("@wemap/routers"),n=require("@wemap/utils"),o=require("@wemap/logger"),a=require("geomag"),l=require("@wemap/camera");function h(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t)for(const i in t)if("default"!==i){const s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>t[i]})}return e.default=t,Object.freeze(e)}const c=h(a);class d extends i.Attitude{}class u extends i.Attitude{}class v extends i.UserPosition{}const E={useMapMatching:!0,ignoreProviders:[],optionalProviders:[],stopOnError:!0,checkAvailabilityOnStart:!0,get hasPoleStar(){return this.optionalProviders.includes("PoleStar")}};const _=new class{constructor(){e(this,"_enabled",!1),e(this,"currentId",0),e(this,"objectsIdMap",new WeakMap),e(this,"pushEvents",{}),e(this,"pushEventsRef",{}),e(this,"interval"),e(this,"initDate")}get enabled(){return this._enabled}set enabled(t){this._enabled=t}initializeInterval(){this.interval||(this.interval=window.setInterval((()=>{for(const[t,e]of Object.entries(this.pushEvents))o.debug("Received "+e+" notifications from "+this.pushEventsRef[Number(t)].getName()+" last second");this.pushEvents={},this.pushEventsRef={}}),1e3))}getObjectId(t){return this.objectsIdMap.has(t)||this.objectsIdMap.set(t,++this.currentId),this.objectsIdMap.get(t)}addEvent(t,e){if(!this.enabled)return;this.initDate||(this.initDate=Date.now()),this.initializeInterval();const i=this.getObjectId(t),s=t.getName();o.debug(s+"["+i+"]."+e)}incrementNotifications(t){if(!this.enabled)return;const e=this.getObjectId(t);let i=this.pushEvents[e];i||(i=0,this.pushEventsRef[e]=t),this.pushEvents[e]=i+1}},m=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(m,"DEFAULT_MESSAGE","Contains ignored provider");let p=m;const g=class t{constructor(){e(this,"id"),e(this,"state","stopped"),e(this,"_lastEvent",null),e(this,"_eventsCallbacks",[]),e(this,"_monitoringCallbacks",[]),e(this,"notify",(t=>{_.incrementNotifications(this),this._eventsCallbacks.forEach((e=>{var i;return null==(i=e.onEvent)?void 0:i.call(e,t)})),this._lastEvent=t})),e(this,"notifyError",(t=>{this._eventsCallbacks.forEach((({id:e,onError:i})=>{E.stopOnError&&this.removeEventListener(e),null==i||i(t)}))})),this.id=t._uniqueId++,_.addEvent(this,"constructor")}getAvailability(){return E.ignoreProviders.includes(this.getName())?Promise.resolve(new p):this.availability()}get hasNativeInterface(){return Boolean(this.nativeInterface)}get nativeInterface(){return"undefined"!=typeof window&&window.__nativeProviders||null}get nativeJsInterface(){return"undefined"==typeof window?null:(window.__nativeJsProviders||(window.__nativeJsProviders={}),window.__nativeJsProviders)}get useCameraNatively(){return!1}addEventListener(e=null,i=null,s=!0){const r=++t._callbackUniqueId;if(this._eventsCallbacks.push({id:r,onEvent:e||(()=>{}),onError:i||(()=>{}),optional:!s}),!s)return r;if("stopped"!==this.state)return r;this.state="starting";let n=Promise.resolve();return E.checkAvailabilityOnStart&&(n=this.getAvailability()),(async()=>{const t=await n;if(t)return this.state="stopped",void this.notifyError(t);_.addEvent(this,"start"),this.start(),this.state="started",this._monitoringCallbacks.forEach((t=>{var e;return null==(e=t.onStarted)?void 0:e.call(t)}))})(),r}removeEventListener(t){const e=this._eventsCallbacks.find((e=>e.id===t));e&&(this._eventsCallbacks=this._eventsCallbacks.filter((t=>t!==e)),e.optional||this._eventsCallbacks.find((t=>!t.optional))||"stopped"!==this.state&&(_.addEvent(this,"stop"),this.stop(),this.state="stopped",this._monitoringCallbacks.forEach((t=>{var e;return null==(e=t.onStopped)?void 0:e.call(t)}))))}addMonitoringListener(e,i){const s=t._callbackUniqueId++;return this._monitoringCallbacks.push({id:s,onStarted:e||null,onStopped:i||null}),s}removeMonitoringListener(t){this._monitoringCallbacks=this._monitoringCallbacks.filter((e=>e.id!==t))}get lastEvent(){return this._lastEvent}};e(g,"_callbackUniqueId",0),e(g,"_uniqueId",1);let A=g;class I{static async every(t){for(const e of t){const t=await e;if(t)return t}return null}static async some(t){let e;for(const i of t){const t=await i;if(!t)return null;e||(e=t)}return e||null}}const f=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(f,"DEFAULT_MESSAGE","It seems that you ask for IMU events on a desktop browser");let P=f;const T=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}from(t){return this.message+=" from "+t,this}};e(T,"DEFAULT_MESSAGE","Impossible to retrieve events, a sensor is missing");let S=T;class y extends S{constructor(t){super(t)}}const M=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(M,"DEFAULT_MESSAGE","Geolocation api is missing");let b=M;const L=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(L,"DEFAULT_MESSAGE","Geolocation permission denied");let R=L;const w=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(w,"DEFAULT_MESSAGE","Geolocation position unavailable");let N=w;const D={DEFAULT_ALTITUDE:1.6},C=class t extends A{constructor(){super(...arguments),e(this,"discardPositionsAbove",t.DEFAULT_DISCARD_POSITIONS_ABOVE),e(this,"enableHighAccuracy",!0),e(this,"geoLocationId"),e(this,"getName",(()=>"GnssWifi")),e(this,"onNewPosition",(t=>{const{coords:e}=t;if(!e)return;let r;e.heading&&(r=s.deg2rad(e.heading));const o=n.TimeUtils.unixTimestampToPreciseTime(t.timestamp)/1e3,a=new i.UserPosition(e.latitude,e.longitude,D.DEFAULT_ALTITUDE,null,o,e.accuracy,r);this.enableHighAccuracy&&"number"==typeof this.discardPositionsAbove&&e.accuracy>this.discardPositionsAbove||this.notify(a)})),e(this,"onPositionError",(t=>{let e;switch(o.warn(`[Providers] watchPosition error: [${t.code}] ${t.message}`),t.code){case 1:e=new R(t.message);break;case 2:e=new N(t.message);break;default:e=new Error(t.message)}this.notifyError(e)}))}get positionOptions(){return{enableHighAccuracy:this.enableHighAccuracy,timeout:1/0,maximumAge:0}}availability(){return"object"==typeof navigator&&navigator.geolocation?Promise.resolve():Promise.resolve(new b)}start(){navigator.geolocation.getCurrentPosition(this.onNewPosition,this.onPositionError,this.positionOptions),setTimeout((()=>{this.geoLocationId=navigator.geolocation.watchPosition(this.onNewPosition,this.onPositionError,this.positionOptions)}),150)}stop(){void 0!==this.geoLocationId&&navigator.geolocation.clearWatch(this.geoLocationId)}};e(C,"DEFAULT_DISCARD_POSITIONS_ABOVE",50);const F=new C,O=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(O,"DEFAULT_MESSAGE","ARCore is missing");let x=O;const U=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(U,"DEFAULT_MESSAGE","Native interface is missing. You are maybe trying to execute a code which is not available in a web browser");let H=U;const B=class t extends A{constructor(){super(...arguments),e(this,"_nativeProvider"),e(this,"previousPosition",[0,0,0]),e(this,"getName",(()=>"ArCore")),e(this,"pullDataLoop",(()=>{if("stopped"===this.state)return;const t=JSON.parse(this.nativeProvider.getInfo());t.length>1&&this.parsePayload(t),requestAnimationFrame(this.pullDataLoop)}))}availability(){try{if(!this.nativeProvider.checkAvailability())return Promise.resolve(new x)}catch(t){return Promise.resolve(t)}return Promise.resolve()}start(){var t;null==(t=this.nativeProvider)||t.start(),this.pullDataLoop()}stop(){var t;null==(t=this.nativeProvider)||t.stop()}parsePayload(e){const s=e[0];let r,o,a,l,h=1;const c=n.TimeUtils.preciseTime()/1e3;if(s&t.Payload.Pose.ref){r=new d(e.slice(h,h+4),c,t.RELATIVE_ATTITUDE_DRIFT);const s=[e[h+4],e[h+5],e[h+6]];o=new i.RelativePosition(s[0]-this.previousPosition[0],s[1]-this.previousPosition[1],s[2]-this.previousPosition[2],c,1e-4),this.previousPosition=s,h+=t.Payload.Pose.size}s&t.Payload.Barcode.ref&&(l=e[h],h+=t.Payload.Barcode.size),s&t.Payload.ProjMat.ref&&(a=e.slice(h,h+t.Payload.ProjMat.size),h+=t.Payload.ProjMat.size),this.notify({relativePosition:o,relativeAttitude:r,...l&&{barcode:l},...a&&{cameraProjection:a}})}get nativeProvider(){if(!this._nativeProvider){if(!this.nativeInterface)throw new H;if(this._nativeProvider=this.nativeInterface.getArCoreProvider(),!this._nativeProvider)throw new x}return this._nativeProvider}enableBarcodeScanner(){try{this.nativeProvider.enableBarcodeScanner()}catch(t){this.notifyError(t)}}disableBarcodeScanner(){try{this.nativeProvider.disableBarcodeScanner()}catch(t){this.notifyError(t)}}get useCameraNatively(){return!0}};e(B,"Payload",{Pose:{ref:1,size:7},Barcode:{ref:2,size:1},ProjMat:{ref:4,size:16},ImageRef:{ref:8,size:1}}),e(B,"RELATIVE_ATTITUDE_DRIFT",s.deg2rad(3)/60);const W=new B;const V=new class extends A{constructor(){super(...arguments),e(this,"absoluteAttitudeProviderId"),e(this,"arCoreProviderId"),e(this,"absoluteAttitudeEvent"),e(this,"getName",(()=>"GeoRelativePositionFromArCore")),e(this,"onArCoreEvents",(t=>{const e=t.relativeAttitude,i=t.relativePosition;e&&i&&this.absoluteAttitudeEvent&&this.compute(i,e,this.absoluteAttitudeEvent)}))}availability(){return I.every([W.getAvailability(),xt.getAvailability()])}start(){this.arCoreProviderId=W.addEventListener(this.onArCoreEvents,this.notifyError),this.absoluteAttitudeProviderId=xt.addEventListener((t=>this.absoluteAttitudeEvent=t),this.notifyError)}stop(){W.removeEventListener(this.arCoreProviderId),xt.removeEventListener(this.absoluteAttitudeProviderId)}compute(t,e,s){const r=s.heading-e.heading,n=Math.cos(r)*t.x-Math.sin(r)*t.z,o=-Math.sin(r)*t.x-Math.cos(r)*t.z,a=t.y,l=new i.GeoRelativePosition(n,o,a,t.time,0,s.heading);this.notify(l)}},G={acc:.5,gyr:.3},k={acc:.5,gyr:.3,yc:2};class Q{constructor(t=[0,0,1],i=[-1,0,0]){e(this,"P"),e(this,"accRef"),e(this,"cRef"),e(this,"noises"),e(this,"quaternion"),this.accRef=t,this.cRef=i,this.P=s.Matrix4.fromDiagVector(Array(4).fill(.1**2)),this.quaternion=null,this.noises={},this.setRelativeNoises(G),this.setAbsoluteNoises(k)}setRelativeNoises(t){this.noises.relative={acc:s.Matrix3.diag(Array(3).fill(t.acc**2)),gyr:s.Matrix3.diag(Array(3).fill(t.gyr**2))}}setAbsoluteNoises(t){this.noises.absolute={acc:s.Matrix3.diag(Array(3).fill(t.acc**2)),gyr:s.Matrix3.diag(Array(3).fill(t.gyr**2)),yc:s.Matrix3.diag(Array(3).fill(t.yc**2))}}tryInitialize(t,e){const i=s.Vector3.normalize(t);if(e){const t=s.Vector3.normalize(e),r=s.Vector3.normalize(s.Vector3.cross(t,i)),n=s.Vector3.cross(i,r),o=[[r[0],n[0],i[0]],[r[1],n[1],i[1]],[r[2],n[2],i[2]]];this.quaternion=s.Quaternion.fromMatrix3Matlab(o)}else{const t=s.Vector3.dot(i,this.accRef)+1,e=s.Vector3.cross(i,this.accRef);let r=[t,e[0],e[1],e[2]];r=s.Quaternion.normalize(r),this.quaternion=r}return this.quaternion}update(t,e,i,r){if(!this.quaternion)return this.tryInitialize(e,r);let n=this.quaternion;const o=n,a=s.Vector3.multiplyScalar(i,.5*t),l=this.computeC([1,a[0],a[1],a[2]]),h=s.Matrix4.multiplyVector(l,n),c=s.Matrix3.diag([o[0],o[0],o[0]]),d=s.Matrix3.skew([o[1],o[2],o[3]]),u=[-1*o[1],-1*o[2],-1*o[3]],v=s.Matrix.concatRow([u],s.Matrix3.sum(d,c)),E=s.Matrix4.multiplyScalar(s.Matrix.multiply(s.Matrix.multiply(v,this.noises[r?"absolute":"relative"].gyr),s.Matrix.transpose(v)),(t/2)**2),_=s.Matrix4.sum(s.Matrix4.multiply(s.Matrix4.multiply(l,this.P),s.Matrix4.transpose(l)),E),m=s.Vector3.normalize(e);let p,g,A;if(r){const t=s.Vector3.normalize(r),e=s.Vector3.cross(m,t),i=s.Vector3.normalize(e),n=s.Vector3.subtract(i,s.Quaternion.rotateMatlab(h,this.cRef)),o=s.Vector3.subtract(m,s.Quaternion.rotateMatlab(h,this.accRef));p=s.Vector.concat(n,o);const a=this.jacobianES(h,this.cRef),l=this.jacobianES(h,this.accRef);A=s.Matrix.concatRow(a,l);const c=s.Matrix.concatLine(this.noises.absolute.yc,s.Matrix3.zeros),d=s.Matrix.concatLine(s.Matrix3.zeros,this.noises.absolute.acc),u=s.Matrix.concatRow(c,d);g=s.Matrix.multiply(s.Matrix.multiply(_,s.Matrix.transpose(A)),s.Matrix.inverse(s.Matrix.sum(s.Matrix.multiply(s.Matrix.multiply(A,_),s.Matrix.transpose(A)),u)))}else{p=s.Vector3.subtract(m,s.Quaternion.rotateMatlab(h,this.accRef)),A=this.jacobianES(h,this.accRef);const t=this.noises.relative.acc;g=s.Matrix.multiply(s.Matrix.multiply(_,s.Matrix.transpose(A)),s.Matrix3.inverse(s.Matrix3.sum(s.Matrix.multiply(s.Matrix.multiply(A,_),s.Matrix.transpose(A)),t)))}n=s.Quaternion.sum(h,s.Matrix.multiplyVector(g,p));const I=s.Matrix4.multiply(s.Matrix4.subtract(s.Matrix4.identity,s.Matrix.multiply(g,A)),_);return n=s.Quaternion.normalize(n),this.quaternion=n,this.P=I,n}computeC(t){return[[t[0],-t[1],-t[2],-t[3]],[t[1],t[0],t[3],-t[2]],[t[2],-t[3],t[0],t[1]],[t[3],t[2],-t[1],t[0]]]}jacobianES(t,e){const[i,s,r,n]=t,[o,a,l]=e;return[[2*n*a-2*r*l,2*r*a+2*n*l,2*s*a-2*i*l-4*r*o,2*i*a+2*s*l-4*n*o],[2*s*l-2*n*o,2*i*l-4*s*a+2*r*o,2*s*o+2*n*l,2*r*l-2*i*o-4*n*a],[2*r*o-2*s*a,2*n*o-4*s*l-2*i*a,2*i*o-4*r*l+2*n*a,2*s*o+2*r*a]]}}const q=new class extends A{constructor(){super(...arguments),e(this,"getName",(()=>"IMU")),e(this,"parseDeviceMotionEvent",(t=>{const e=t.timeStamp/1e3;let i,r;if(t.accelerationIncludingGravity){const{x:e,y:s,z:r}=t.accelerationIncludingGravity;"number"==typeof e&&"number"==typeof s&&"number"==typeof r&&(i=[e,s,r],n.BrowserUtils.getName()!==n.Browser.SAFARI&&n.BrowserUtils.getName()!==n.Browser.IOS_WEBVIEW||(i[0]*=-1,i[1]*=-1,i[2]*=-1))}if(t.rotationRate){const{alpha:e,beta:i,gamma:n}=t.rotationRate;"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&(r=[s.deg2rad(e),s.deg2rad(i),s.deg2rad(n)])}(i||r)&&this.notify({...i&&{acceleration:{timestamp:e,values:i}},...r&&{angularRate:{timestamp:e,values:r}}})}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>window.addEventListener("devicemotion",this.parseDeviceMotionEvent,!0),e=DeviceMotionEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch(this.notifyError):t()}stop(){window.removeEventListener("devicemotion",this.parseDeviceMotionEvent,!0)}},j=class t extends S{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(j,"DEFAULT_MESSAGE","Impossible to retrieve Acceleration data");let z=j;const J=new class extends A{constructor(){super(...arguments),e(this,"imuProviderId"),e(this,"getName",(()=>"Accelerometer")),e(this,"availability",(()=>q.getAvailability()))}start(){this.imuProviderId=q.addEventListener((t=>{t.acceleration?this.notify(t.acceleration):this.notifyError((new z).from("devicemotion"))}),this.notifyError)}stop(){q.removeEventListener(this.imuProviderId)}};class Y extends S{constructor(t){super(t||S.DEFAULT_MESSAGE)}}e(Y,"DEFAULT_MESSAGE","Impossible to retrieve Angular Rate data");const X=new class extends A{constructor(){super(...arguments),e(this,"imuProviderId"),e(this,"getName",(()=>"Gyroscope")),e(this,"availability",(()=>q.getAvailability()))}start(){this.imuProviderId=q.addEventListener((t=>{t.angularRate?this.notify(t.angularRate):this.notifyError((new Y).from("devicemotion"))}),this.notifyError)}stop(){q.removeEventListener(this.imuProviderId)}},K=class t extends A{constructor(){super(...arguments),e(this,"accelerometerProviderId"),e(this,"ekfAttitude",new Q),e(this,"gyroscopeEvent"),e(this,"gyroscopeProviderId"),e(this,"lastTimestamp",0),e(this,"getName",(()=>"RelativeAttitudeFromEkf")),e(this,"onAccelerometerEvent",(e=>{if(!this.gyroscopeEvent)return;const{values:i,timestamp:s}=e;if(0===this.lastTimestamp)return void(this.lastTimestamp=s);const r=s-this.lastTimestamp;this.lastTimestamp=s;const n=this.ekfAttitude.update(r,i,this.gyroscopeEvent.values);if(n){const e=new d(n,s,t.DEFAULT_DRIFT);this.notify(e)}}))}availability(){return I.every([J.getAvailability(),X.getAvailability()])}start(){this.accelerometerProviderId=J.addEventListener((t=>this.onAccelerometerEvent(t)),(t=>this.notifyError(t))),this.gyroscopeProviderId=X.addEventListener((t=>this.gyroscopeEvent=t),(t=>this.notifyError(t)))}stop(){J.removeEventListener(this.accelerometerProviderId),X.removeEventListener(this.gyroscopeProviderId)}};e(K,"DEFAULT_DRIFT",s.deg2rad(5)/60);const Z=new K,$=class t extends A{constructor(){super(...arguments),e(this,"getName",(()=>"RelativeAttitudeFromBrowser")),e(this,"onDeviceOrientationEvent",(e=>{if("number"!=typeof e.alpha||"number"!=typeof e.beta||"number"!=typeof e.gamma)return void this.notifyError((new S).from("deviceorientation"));const i=s.Rotations.eulerToQuaternionZXYDegrees([e.alpha,e.beta,e.gamma]),r=new d(i,e.timeStamp/1e3,t.DEFAULT_DRIFT);this.notify(r)}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>window.addEventListener("deviceorientation",this.onDeviceOrientationEvent,!0),e=DeviceOrientationEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch((t=>this.notifyError(t))):t()}stop(){window.removeEventListener("deviceorientation",this.onDeviceOrientationEvent,!0)}};e($,"DEFAULT_DRIFT",s.deg2rad(5)/60);const tt=new $,et=class t extends A{constructor(){super(...arguments),e(this,"gyroscopeProviderId"),e(this,"getName",(()=>"HighRotationsProvider")),e(this,"availability",(()=>X.getAvailability())),e(this,"_parseGyroscopeEvent",(e=>{const{values:i,timestamp:r}=e;s.Vector3.norm(i)>t.THRESHOLD&&this.notify({timestamp:r})}))}start(){this.gyroscopeProviderId=X.addEventListener(this._parseGyroscopeEvent,this.notifyError)}stop(){X.removeEventListener(this.gyroscopeProviderId)}isInProgress(){if(!this.lastEvent||!X.lastEvent)return!1;return X.lastEvent.timestamp-this.lastEvent.timestamp<t.DELAY_CONSIDERATION}};e(et,"THRESHOLD",10),e(et,"DELAY_CONSIDERATION",3);const it=new et,st=class t extends A{constructor(){super(...arguments),e(this,"_highRotationsProviderId"),e(this,"listenerId"),e(this,"provider"),e(this,"getName",(()=>"RelativeAttitudeFromInertial"))}availability(){return I.some([Z.getAvailability(),tt.getAvailability()])}start(){Z.getAvailability().then((t=>{this.provider=t?tt:Z,this.listenerId=this.provider.addEventListener((t=>this._parseEvent(t)),this.notifyError),this._highRotationsProviderId=it.addEventListener(null,this.notifyError)}))}_parseEvent(e){const i=e.clone();if(it.isInProgress()){let e=(i.accuracy||0)+100*t.DEFAULT_DRIFT;e=Math.min(e,Math.PI),i.accuracy=e}this.notify(i)}stop(){this.provider&&(this.provider.removeEventListener(this.listenerId),delete this.provider),it.removeEventListener(this._highRotationsProviderId)}};e(st,"DEFAULT_DRIFT",s.deg2rad(5)/60);const rt=new st,nt=class t{constructor(){e(this,"frequency",0),e(this,"lastVerticalAcc",0),e(this,"maxAcceleration",0),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS)}compute(e,i){let s=!1;const r=i[2],n=e-this.lastStepTimestamp;if(r>this.lastVerticalAcc)r>this.maxAcceleration&&(this.maxAcceleration=r);else if(this.maxAcceleration>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&n>t.MIN_TIME_BETWEEN_STEPS){this.maxAcceleration=0;const i=e-this.lastStepTimestamp;this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),s=!0,this.lastStepTimestamp=e}else this.maxAcceleration=0;return this.lastVerticalAcc=r,s}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepTimestamp?this.lastStepSize*this.frequency:0}};e(nt,"MIN_TIME_BETWEEN_STEPS",.4),e(nt,"MAX_FRENQUENCY",4),e(nt,"MIN_FRENQUENCY",1),e(nt,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",1);let ot=nt;const at=class t{constructor(){e(this,"frequency",0),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"slidingWindow",[])}compute(e,i){if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let s=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER;const n=t.WINDOW_TIME;if(this.slidingWindow.forEach(((t,i,o)=>{t.timestamp<e-n?o.splice(i,1):(s=Math.max(t.verticalAcc,s),r=Math.min(t.verticalAcc,r))})),this.slidingWindow.push({timestamp:e,verticalAcc:i[2]}),s>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&r<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){const i=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}return!1}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepTimestamp?this.lastStepSize*this.frequency:0}};e(at,"WINDOW_TIME",.3),e(at,"MIN_TIME_BETWEEN_STEPS",.4),e(at,"MAX_FRENQUENCY",4),e(at,"MIN_FRENQUENCY",1),e(at,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",1.5),e(at,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-1);let lt=at;const ht=class t{constructor(){e(this,"frequency",0),e(this,"influence",.2),e(this,"slidingWindow",[]),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"previousVerticalAcc",0)}compute(e,i,s){const r=this.influence*(2*i[2])+(1-this.influence)*this.previousVerticalAcc;if(this.previousVerticalAcc=r,Math.sqrt(s[0]**2+s[1]**2+s[2]**2)>.75)return!1;if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let n=Number.MIN_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER;if(this.slidingWindow.forEach(((i,s,r)=>{i.timestamp<e-t.WINDOW_TIME?r.splice(s,1):(n=Math.max(i.verticalAcc,n),o=Math.min(i.verticalAcc,o))})),this.slidingWindow.push({timestamp:e,verticalAcc:r}),n>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&o<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){const i=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}return!1}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepSize&&this.frequency?this.lastStepSize*this.frequency:0}mean(t){let e=0,i=0;for(let s=0;s<t.length;++s)e+=t[s].verticalAcc;return i=e/t.length,i}stddev(t){const e=this.mean(t);let i=0;for(let s=0;s<t.length;++s)i+=(t[s].verticalAcc-e)**2;return Math.sqrt(i/t.length)}};e(ht,"WINDOW_TIME",.3),e(ht,"MIN_TIME_BETWEEN_STEPS",.4),e(ht,"MAX_FRENQUENCY",4),e(ht,"MIN_FRENQUENCY",1),e(ht,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",.75),e(ht,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-.3);let ct=ht;const dt=class t{constructor(){e(this,"frequency",0),e(this,"influence",.05),e(this,"slidingWindow",[]),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"previousVerticalAcc",0),e(this,"previousHorizontalAcc",0)}compute(e,i){const s=this.influence*i[2]+(1-this.influence)*this.previousVerticalAcc;this.previousVerticalAcc=s,this.slidingWindow=this.slidingWindow.filter((i=>i.timestamp>=e-t.WINDOW_TIME)),this.slidingWindow.push({timestamp:e,verticalAcc:s});if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let r=Number.MIN_VALUE,n=-1,o=!1;if(this.slidingWindow.forEach(((e,i)=>{e.verticalAcc>r&&e.verticalAcc>=t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&(r=e.verticalAcc,n=i,o=!0)})),!o)return!1;let a=!1,l=Number.MAX_VALUE;for(let u=0;u<n;u++){const e=this.slidingWindow[u].verticalAcc;if(l=Math.min(l,e),e<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){a=!0;break}}if(!a)return!1;const h=r-.5*(r-l);let c=!1;for(let t=n+1;t<this.slidingWindow.length;t++)if(this.slidingWindow[t].verticalAcc<=h){c=!0;break}if(!c)return!1;const d=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/d,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepSize&&this.frequency?this.lastStepSize*this.frequency:0}mean(t){let e=0,i=0;for(let s=0;s<t.length;++s)e+=t[s];return i=e/t.length,i}stddev(t){const e=this.mean(t);let i=0;for(let s=0;s<t.length;++s)i+=(t[s]-e)**2;return Math.sqrt(i/t.length)}};e(dt,"WINDOW_TIME",.6),e(dt,"MIN_TIME_BETWEEN_STEPS",.6),e(dt,"MAX_FRENQUENCY",4),e(dt,"MIN_FRENQUENCY",1),e(dt,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",.2),e(dt,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-.1);let ut=dt;const vt=class t extends A{constructor(){super(),e(this,"accelerometerProviderId"),e(this,"attitudeProviderId"),e(this,"gyroscopeProviderId"),e(this,"angularRateEvent"),e(this,"attitudeEvent"),e(this,"numOfSteps",0),e(this,"stepDetector"),e(this,"_stepSizeMultiplier",t.DEFAULT_STEP_SIZE_MULTIPLIER),e(this,"_algorithm",t.DEFAULT_ALGORITHM),e(this,"_accValues",[]),e(this,"getName",(()=>"StepDetector")),e(this,"onAccelerometerEvent",(e=>{if(!this.attitudeEvent||!this.angularRateEvent)return;const{values:i,timestamp:s}=e,r=t.computeLinearAcceleration(this.attitudeEvent.quaternion,i);if(this.stepDetector.compute(s,r,this.angularRateEvent.values)){const t=this.stepDetector.lastStepSize*this._stepSizeMultiplier;this.numOfSteps++,this.notify({size:t,number:this.numOfSteps})}})),this.algorithm=this._algorithm}availability(){return I.every([J.getAvailability(),X.getAvailability(),rt.getAvailability()])}start(){this.numOfSteps=0,this.accelerometerProviderId=J.addEventListener(this.onAccelerometerEvent,this.notifyError),this.gyroscopeProviderId=X.addEventListener((t=>this.angularRateEvent=t),this.notifyError),this.attitudeProviderId=rt.addEventListener((t=>this.attitudeEvent=t),this.notifyError)}stop(){J.removeEventListener(this.accelerometerProviderId),X.removeEventListener(this.gyroscopeProviderId),rt.removeEventListener(this.attitudeProviderId)}static computeLinearAcceleration(t,e){const r=s.Quaternion.rotateMatlab(s.Quaternion.inverse(t),e);return r[2]-=i.Constants.EARTH_GRAVITY,r}set stepSizeMultiplier(t){this._stepSizeMultiplier=t}get stepSizeMultiplier(){return this._stepSizeMultiplier}set algorithm(t){switch(t){case"ladetto":this.stepDetector=new ot;break;case"minMaxPeaks":this.stepDetector=new lt;break;case"minMaxPeaks2":this.stepDetector=new ct;break;default:t="minMaxPeaks3",this.stepDetector=new ut}this._algorithm=t}get algorithm(){return this._algorithm}};e(vt,"DEFAULT_STEP_SIZE_MULTIPLIER",1),e(vt,"DEFAULT_ALGORITHM","minMaxPeaks3");const Et=new vt;const _t=new class extends A{constructor(){super(...arguments),e(this,"absoluteAttitudeProviderId"),e(this,"stepDetectionProviderId"),e(this,"attitudeEvent"),e(this,"misalignmentError",s.deg2rad(3)),e(this,"getName",(()=>"Pdr")),e(this,"onStepEvent",(t=>{if(!this.attitudeEvent)return;const e=t.size,s=this.attitudeEvent,r=s.heading,n=s.accuracy+this.misalignmentError,o=e/2*Math.sin(n/2),a=s.time,l=new i.GeoRelativePosition(e*Math.sin(r),e*Math.cos(r),0,a,o,r);this.notify(l)}))}availability(){return I.every([Et.getAvailability(),xt.getAvailability()])}start(){this.stepDetectionProviderId=Et.addEventListener(this.onStepEvent,this.notifyError),this.absoluteAttitudeProviderId=xt.addEventListener((t=>this.attitudeEvent=t),this.notifyError)}stop(){Et.removeEventListener(this.stepDetectionProviderId),xt.removeEventListener(this.absoluteAttitudeProviderId)}};const mt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"geoRelativeProvider"),e(this,"getName",(()=>"GeoRelativePosition"))}availability(){return I.some([_t.getAvailability(),V.getAvailability()])}async start(){const t=await V.getAvailability();this.geoRelativeProvider=t?_t:V,this.providerId=this.geoRelativeProvider.addEventListener(this.notify,this.notifyError)}stop(){var t;null==(t=this.geoRelativeProvider)||t.removeEventListener(this.providerId),delete this.geoRelativeProvider}};const pt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"InclinationFromAcc")),e(this,"availability",(()=>J.getAvailability())),e(this,"onAccelerometerEvent",(t=>{const e=t.values,i=window.orientation||0,s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),r=[e[0]/s,e[1]/s,e[2]/s],n=[r[2]+1,r[1],-r[0],0],o=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),a=[n[0]/o,n[1]/o,n[2]/o,0];let l;l=0===i?Math.asin(2*a[1]*a[0]):90===i?-Math.asin(2*a[2]*a[0]):-90===i?Math.asin(2*a[2]*a[0]):-Math.asin(2*a[1]*a[0]),this.notify(l)}))}start(){this.providerId=J.addEventListener(this.onAccelerometerEvent,this.notifyError)}stop(){J.removeEventListener(this.providerId)}};const gt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"InclinationFromRelativeAttitude")),e(this,"availability",(()=>rt.getAvailability()))}start(){this.providerId=rt.addEventListener((t=>{const e=this.enuQuatToInclination(t.quaternion);this.notify(e)}),this.notifyError)}stop(){rt.removeEventListener(this.providerId)}enuQuatToInclination(t){const e=window.orientation||0;return 0===e?Math.asin(2*(t[2]*t[3]+t[1]*t[0])):90===e?Math.asin(2*(t[1]*t[3]-t[2]*t[0])):-90===e?Math.asin(2*(t[2]*t[0]-t[1]*t[3])):-Math.asin(2*(t[2]*t[3]+t[1]*t[0]))}};const At=new class extends A{constructor(){super(...arguments),e(this,"provider"),e(this,"providerId"),e(this,"getName",(()=>"Inclination"))}availability(){return I.some([pt.getAvailability(),gt.getAvailability()])}async start(){const t=()=>{this.provider=pt,this.providerId=this.provider.addEventListener(this.notify,this.notifyError)};await gt.getAvailability()?(this.provider=gt,this.providerId=this.provider.addEventListener(this.notify,(()=>{gt.removeEventListener(this.providerId),t()}))):t()}stop(){this.provider&&this.provider.removeEventListener(this.providerId)}};class It{constructor(t,e=null,i=null,s=null){this.size=t,this.calibration=e,this.coarse=i,this.device=s}toJson(){return{size:[this.size.width,this.size.height],...this.calibration&&{calibration:this.calibration},...this.coarse&&{coarse:{...this.coarse.attitude&&{attitude:this.coarse.attitude.toJson()},...this.coarse.position&&{position:this.coarse.position.toJson()}}},..."object"==typeof this.device&&{device:this.device}}}static fromJson(t){var e,s;return new It({width:t.size[0],height:t.size[1]},t.calibration,{...(null==(e=t.coarse)?void 0:e.position)&&{position:i.UserPosition.fromJson(t.coarse.position)},...(null==(s=t.coarse)?void 0:s.attitude)&&{attitude:i.Attitude.fromJson(t.coarse.attitude)}},t.device)}}class ft{constructor(t,e){this.metadata=t,this.image=e}toJson(){return{image:l.canvasToBase64(this.image),...this.metadata.toJson()}}static fromJson(t){return new ft(It.fromJson(t),l.base64ToCanvas(t.image))}}class Pt{constructor(t,e=null,i=null){this.success=t,this.attitude=e,this.position=i}toJson(){var t,e;return{success:this.success,attitude:null==(t=this.attitude)?void 0:t.toJson(),position:null==(e=this.position)?void 0:e.toJson()}}static fromJson(t,e=null){let s=null;t.attitude&&(s=i.Attitude.fromJson(t.attitude),s.time=e);let r=null;return t.position&&(r=i.UserPosition.fromJson(t.position),r.time=e),new Pt(t.success,s,r)}}class Tt{static _prepareRequest(t,e=null,i=null){l.convertToGrayscale(t);const s=l.reduceImageSize(t,1280),r=new It({width:s.width,height:s.height},e,i,n.UserAgentUtils.getDeviceFromUserAgent());return new ft(r,s)}static async relocalize(t,e,i=null,s=null,r=null){const a=n.TimeUtils.preciseTime()/1e3,l=this._prepareRequest(e,i,s);let h;try{const e=JSON.stringify(l.toJson());o.debug(`[VPS] Request (${(e.length/1024).toFixed(0)} kB) sent to server ${t}`),h=await fetch(t,{method:"POST",body:e,headers:Object.assign({"Content-Type":"application/json",Accept:"application/vnd.geopose+json; version=1"},r||{})})}catch(u){return o.debug("[VPS] Server respond error"),null}if(200!==h.status)return o.debug("[VPS] Server respond error"),null;const c=await h.json(),d=Pt.fromJson(c,a);return o.debug("[VPS] Server respond "+(d.success?"success":"not found")),d}static getHeadingFromQuaternion(t){const[e,i,s,r]=t,n=Math.sqrt(2)/2,o=[n*(e-i),n*(e+i),n*(s+r),n*(r-s)];return-Math.atan2(2*o[3]*o[0]-2*o[2]*o[1],1-2*o[1]**2-2*o[3]**2)}}class St{constructor(){e(this,"_providerId"),e(this,"_isRunning",!1),e(this,"_dataOnStart",null)}tickStart(){this._dataOnStart=null,this._isRunning||(this._isRunning=!0,this._providerId=tt.addEventListener((t=>{this._dataOnStart||(this._dataOnStart=t)})))}tickEnd(){if(!this._isRunning)return o.warn("You have to call tickStart before tickEnd"),null;if(this._internalStop(),!this._dataOnStart)return o.warn("Delay was too short between tickStart and tickEnd or RelativeAttitudeProvider cannot be retrieved."),null;const t=tt.lastEvent;return i.Attitude.diff(this._dataOnStart,t)}_internalStop(){tt.removeEventListener(this._providerId),delete this._providerId,this._isRunning=!1}release(){this._isRunning&&this._internalStop()}}const yt=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(yt,"DEFAULT_MESSAGE","PoleStar is missing");let Mt=yt;const bt=new class extends A{constructor(){super(),e(this,"getName",(()=>"PoleStar")),this.addMethodsToNativeJsProvider()}availability(){try{return this.nativeProvider.checkAvailability(),Promise.resolve()}catch(t){return Promise.resolve(t)}}setApiKey(t){this.nativeProvider.setApiKey(t)}start(){this.nativeProvider.start()}stop(){this.nativeProvider.stop()}get nativeProvider(){if(!this.nativeInterface)throw new H;const t=this.nativeInterface.getPoleStarProvider();if(!t)throw new Mt;return t}addMethodsToNativeJsProvider(){this.nativeJsInterface&&(this.nativeJsInterface.polestar={callbackError:t=>this.notifyError(new Error(t)),callbackPosition:t=>{const e=JSON.parse(t),i=n.TimeUtils.unixTimestampToPreciseTime(e.time)/1e3,r=new v(e.lat,e.lng,D.DEFAULT_ALTITUDE,e.alt/5,i,e.accuracy,s.deg2rad(e.bearing));this.notify(r)}})}},Lt=class t extends A{constructor(){super(...arguments),e(this,"_relativeRotationCalc"),e(this,"_serverError",!1),e(this,"_cameraError",!1),e(this,"_camera",null),e(this,"_endpoint",null),e(this,"_inclinationProviderId"),e(this,"_minInclinationForRequest",t.DEFAULT_MIN_INCLINATION_FOR_REQUEST),e(this,"_waitTimeMinInclinationForRequest",t.DEFAULT_WAIT_TIME_MIN_INCLINATION_FOR_REQUEST),e(this,"_useCoarsePose",t.DEFAULT_USE_COARSE_POSE),e(this,"getName",(()=>"Vps")),e(this,"availability",(()=>l.Camera.checkAvailability())),e(this,"_onCameraDetected",(({camera:t})=>{this._camera&&o.warn("It seems that more than 1 camera has been detected for VPS. Taking the first..."),this._useCamera(t)})),e(this,"_onCameraRemoved",(()=>{this._camera?(this._camera.off("started",this._internalStart),this._camera.off("stopped",this._internalStop)):o.warn("There is no previously detected camera but once has stopped"),this._camera=null})),e(this,"_internalStart",(async()=>{var e,r;if(!this._endpoint)return void this.notifyError(new Error("VPS endpoint has not been set before calling start()"));let o=null;const a=()=>"stopped"===this.state;for(;!a();){if(null!==o){const e=n.TimeUtils.preciseTime()-o,i=Math.max(0,t.MIN_TIME_BETWEEN_TWO_REQUESTS-e);await new Promise((t=>setTimeout(t,i)))}if(o=n.TimeUtils.preciseTime(),a()||!this._camera||"started"!==this._camera.state)break;const l=At.lastEvent?At.lastEvent:null;if(null!==l&&l<this._minInclinationForRequest){await new Promise((t=>setTimeout(t,this._waitTimeMinInclinationForRequest)));continue}null==(e=this._relativeRotationCalc)||e.tickStart();const h=await this._camera.currentImage;if(!h)continue;let c=null;const d=Nt.getBestPositionEvent(F.lastEvent,bt.lastEvent);this._useCoarsePose&&(d||xt.lastEvent)&&(c={...d&&{position:d},...xt.lastEvent&&{attitude:xt.lastEvent}});const v=await Tt.relocalize(this._endpoint,h,null,c);if(!v||!v.success)continue;const E=v.attitude.quaternion,_=s.Quaternion.multiply(E,t.CAMERA_TO_SMARTPHONE_ROT),m=s.Quaternion.multiply(s.Quaternion.fromAxisAngle([0,0,1],s.deg2rad(window.orientation||0)),_),p=(null==(r=this._relativeRotationCalc)?void 0:r.tickEnd())||new i.Attitude([1,0,0,0]),g=s.Quaternion.multiply(m,p.quaternion),A=new u(g,v.attitude.time,v.attitude.accuracy),I=v.position.clone();if(null===I.accuracy&&(I.accuracy=5),a())break;this.notify({absoluteAttitude:A,absolutePosition:I})}})),e(this,"_internalStop",(()=>{}))}start(){this._inclinationProviderId=At.addEventListener(),this._relativeRotationCalc=new St,l.SharedCameras.on("added",this._onCameraDetected),l.SharedCameras.on("removed",this._onCameraRemoved),l.SharedCameras.list.length&&(l.SharedCameras.list.length>1&&o.warn("It seems that more than 1 camera has been detected for VPS. Taking the first..."),this._useCamera(l.SharedCameras.list[0].camera))}stop(){var t;At.removeEventListener(this._inclinationProviderId),null==(t=this._relativeRotationCalc)||t.release(),l.SharedCameras.off("added",this._onCameraDetected),l.SharedCameras.off("removed",this._onCameraRemoved),this._camera=null}_useCamera(t){this._camera=t,t.on("started",this._internalStart),t.on("stopped",this._internalStop),"started"===t.state&&this._internalStart()}get endpoint(){return this._endpoint}set endpoint(t){this._endpoint=t}get minInclinationForRequest(){return this._minInclinationForRequest}set minInclinationForRequest(t){this._minInclinationForRequest=t}get waitTimeMinInclinationForRequest(){return this._waitTimeMinInclinationForRequest}set waitTimeMinInclinationForRequest(t){this._waitTimeMinInclinationForRequest=t}get useCoarsePose(){return this._useCoarsePose}set useCoarsePose(t){this._useCoarsePose=t}};e(Lt,"MIN_TIME_BETWEEN_TWO_REQUESTS",1e3),e(Lt,"DEFAULT_MIN_INCLINATION_FOR_REQUEST",s.deg2rad(60)),e(Lt,"DEFAULT_WAIT_TIME_MIN_INCLINATION_FOR_REQUEST",200),e(Lt,"DEFAULT_USE_COARSE_POSE",!0),e(Lt,"CAMERA_TO_SMARTPHONE_ROT",s.Quaternion.fromAxisAngle([1,0,0],Math.PI));const Rt=new Lt,wt=class t extends A{constructor(){super(...arguments),e(this,"_polestarProviderId"),e(this,"_vpsProviderId"),e(this,"_gnssWifiProviderId"),e(this,"_relativePositionProviderId"),e(this,"_mapMatchingHandlerId"),e(this,"useAllAbsolutePositions",!1),e(this,"_waitUntilNextVpsPosition",!1),e(this,"_lastPolestarFix",null),e(this,"getName",(()=>"AbsolutePosition"))}availability(){return I.some([mt.getAvailability(),F.getAvailability(),...E.hasPoleStar?[bt.getAvailability()]:[],Rt.getAvailability()])}start(){mt.getAvailability().then((t=>{t||(this._relativePositionProviderId=mt.addEventListener((t=>this._onRelativePosition(t))))})),this._gnssWifiProviderId=F.addEventListener((t=>{const e=t.clone();e.bearing=null,this._onAbsolutePosition(e,!1)})),this._vpsProviderId=Rt.addEventListener((t=>this._onAbsolutePosition(t.absolutePosition)),this.notifyError,!1),E.hasPoleStar&&(this._polestarProviderId=bt.addEventListener((t=>{var e;this._lastPolestarFix=n.TimeUtils.preciseTime();if(!this._onAbsolutePosition(t)&&null===(null==(e=this.lastEvent)?void 0:e.level)){const e=this.lastEvent.clone();e.level=t.level,this.notify(e)}}))),this._mapMatchingHandlerId=Gt.addEventListener()}stop(){this._relativePositionProviderId&&(mt.removeEventListener(this._relativePositionProviderId),delete this._relativePositionProviderId),this._gnssWifiProviderId&&(F.removeEventListener(this._gnssWifiProviderId),delete this._gnssWifiProviderId),this._vpsProviderId&&(Rt.removeEventListener(this._vpsProviderId),delete this._vpsProviderId),this._polestarProviderId&&(bt.removeEventListener(this._polestarProviderId),delete this._polestarProviderId),Gt.removeEventListener(this._mapMatchingHandlerId)}_shouldTakeIntoAccountNewAbsolutePosition(e,s=!0){const r=e,n=this.lastEvent||null;if(!n)return!0;const o=r.accuracy*t.ACCURACY_RELOC_RATIO<=n.accuracy;if(o)return!0;const a=n.distanceTo(r)>n.accuracy+r.accuracy;if(a)return!0;const l=a&&r.accuracy<=n.accuracy;if(o&&l)return!0;return!(!s||i.Level.equals(r.level,n.level))}_onAbsolutePosition(t,e=!0){if(!this._shouldTakeIntoAccountNewAbsolutePosition(t,e)&&!this.useAllAbsolutePositions)return!1;const i=t.clone(),s=this.lastEvent?this.lastEvent:null;return s&&(e||(i.level=s.level),null===i.bearing&&(i.bearing=s.bearing)),Gt.canUseMapMatching()?Gt.notifyPositionFromAbsolute(i):(this.notify(i),!0)}_onRelativePosition(t){if(!this.lastEvent||this._waitUntilNextVpsPosition)return!1;const e=this.lastEvent,i=t,s=Math.sqrt(i.x**2+i.y**2),r=Math.atan2(i.x,i.y),n=null!==e.alt?i.z:null,o=e.destinationPoint(s,r,n);return o.bearing=i.bearing,o.time=i.time,o.accuracy+=i.accuracy,Gt.canUseMapMatching()?Gt.notifyPositionFromRelative(o):(this.notify(o),!0)}feed(e){let s;if(!(e instanceof i.UserPosition))throw new Error("data is nor an UserPosition or an AbsolutePositionEvent");if(null===e.time)throw Error("the time of the position is not defined");if(null===e.accuracy)throw Error("the accuracy of the position is not defined");s=e,t.USE_MM_FOR_FEED&&Gt.canUseMapMatching()?Gt.notifyPositionFromFeed(s):this.notify(s)}getBestPositionEvent(...t){return t.reduce(((t,e)=>{if(!t)return e;if(!e||null===e.accuracy||null===e.time)return t;const{accuracy:i,time:s}=e,{accuracy:r,time:n}=t;return i<r+1.3888*(s-n)?e:t}),null)}};e(wt,"ACCURACY_RELOC_RATIO",1),e(wt,"USE_MM_FOR_FEED",!0);const Nt=new wt;class Dt extends A{constructor(){super(...arguments),e(this,"DEFAULT_ACCURACY",s.deg2rad(15)),e(this,"absolutePositionProviderId"),e(this,"absolutePositionEvent"),e(this,"declinationQuaternion"),e(this,"magQuaternion"),e(this,"magQuaternionTimestamp"),e(this,"iosPreviousQuat"),e(this,"iosIsSkyMode",null),e(this,"getName",(()=>"AbsoluteAttitudeFromBrowser")),e(this,"onDeviceOrientationChromeEvent",(t=>{this.magQuaternionTimestamp=t.timeStamp/1e3,"number"==typeof t.alpha&&"number"==typeof t.beta&&"number"==typeof t.gamma?(this.magQuaternion=s.Rotations.eulerToQuaternionZXYDegrees([t.alpha,t.beta,t.gamma]),this.compute()):this.notifyError((new S).from("deviceorientationabsolute"))})),e(this,"onDeviceOrientationSafariEvent",(t=>{if(this.magQuaternionTimestamp=t.timeStamp/1e3,"number"!=typeof t.beta||"number"!=typeof t.gamma)return void this.notifyError((new S).from("deviceorientation"));if("number"!=typeof t.webkitCompassHeading)return void this.notifyError((new y).from("deviceorientation"));let e;const[i,r,n,o]=s.Rotations.eulerToQuaternionZXYDegrees([t.webkitCompassHeading,t.beta,t.gamma]),a=s.rad2deg(Math.acos(i**2-r**2-n**2+o**2));let l=null;a>136?l=!0:a<134?l=!1:this.iosPreviousQuat&&null!==this.iosIsSkyMode&&(l=s.Quaternion.distance([i,r,n,o],this.iosPreviousQuat)<.5?this.iosIsSkyMode:!this.iosIsSkyMode),this.iosPreviousQuat=[i,r,n,o],this.iosIsSkyMode=l,void 0!==l&&(e=l?180-t.webkitCompassHeading:Dt.webkitCompassToHeading(t.webkitCompassHeading,t.beta,t.gamma),this.magQuaternion=s.Rotations.eulerToQuaternionZXYDegrees([e,t.beta,t.gamma]),this.compute())})),e(this,"onAbsolutePositionEvent",(t=>{this.absolutePositionEvent=t;const e=c.field(t.lat,t.lng);this.declinationQuaternion=s.Quaternion.fromAxisAngle([0,0,1],-s.deg2rad(e.declination)),Nt.removeEventListener(this.absolutePositionProviderId),delete this.absolutePositionProviderId,this.compute()}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>{switch(n.BrowserUtils.getName()){case n.Browser.CHROME:window.addEventListener("deviceorientationabsolute",this.onDeviceOrientationChromeEvent,!0);break;case n.Browser.SAFARI:case n.Browser.IOS_WEBVIEW:window.addEventListener("deviceorientation",this.onDeviceOrientationSafariEvent,!0)}},e=DeviceOrientationEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch(this.notifyError):t();const i=Nt.lastEvent;i?this.onAbsolutePositionEvent(i):this.absolutePositionProviderId=Nt.addEventListener(this.onAbsolutePositionEvent,this.notifyError,!1)}stop(){switch(n.BrowserUtils.getName()){case n.Browser.CHROME:window.removeEventListener("deviceorientationabsolute",this.onDeviceOrientationChromeEvent,!0);break;case n.Browser.SAFARI:case n.Browser.IOS_WEBVIEW:window.removeEventListener("deviceorientation",this.onDeviceOrientationSafariEvent,!0)}Nt.removeEventListener(this.absolutePositionProviderId)}compute(){if(!this.declinationQuaternion||!this.magQuaternion||!this.absolutePositionEvent)return;const t=s.Quaternion.multiply(this.declinationQuaternion,this.magQuaternion),e=new u(t,this.magQuaternionTimestamp,this.DEFAULT_ACCURACY);this.notify(e)}static webkitCompassToHeading(t,e,i){const r=s.deg2rad(t),n=s.deg2rad(e),o=s.deg2rad(i),a=Math.cos(r/2),l=Math.cos(n/2),h=Math.cos(o/2),c=Math.sin(r/2),d=Math.sin(n/2),u=Math.sin(o/2),v=a*l*h-c*d*u,E=c*l*h+a*d*u;return s.rad2deg(-2*Math.atan(E/v))}}const Ct=new Dt;const Ft=new class extends A{constructor(){super(...arguments),e(this,"arCoreMonitoringId"),e(this,"arCoreProviderId"),e(this,"inertialProviderId"),e(this,"getName",(()=>"RelativeAttitude")),e(this,"availability",(()=>rt.getAvailability())),e(this,"listenInertial",(()=>{this.inertialProviderId=rt.addEventListener(this.notify,this.notifyError)})),e(this,"unlistenInertial",(()=>{rt.removeEventListener(this.inertialProviderId)})),e(this,"listenArCore",(()=>{this.arCoreProviderId=W.addEventListener((t=>this.notify(t.relativeAttitude)),null,!1)})),e(this,"unlistenArCore",(()=>{W.removeEventListener(this.arCoreProviderId)}))}start(){this.arCoreMonitoringId=W.addMonitoringListener((()=>{this.listenArCore(),this.unlistenInertial()}),(()=>{this.unlistenArCore(),this.listenInertial()})),"started"===W.state?this.listenArCore():this.listenInertial()}stop(){W.removeMonitoringListener(this.arCoreMonitoringId),this.unlistenArCore(),this.unlistenInertial()}},Ot=class t extends A{constructor(){super(...arguments),e(this,"_absAttitudeFromBrowser"),e(this,"_vpsProviderId"),e(this,"fromBrowserProviderId"),e(this,"highRotationProviderId"),e(this,"inclinationProviderId"),e(this,"relativeAttitudeProviderId"),e(this,"_attitudeFromBrowserErrored",!1),e(this,"_attitudeFromRelativeErrored",!1),e(this,"_relativeAttitude",null),e(this,"_relativeAccuracy",0),e(this,"_lastForcedHeadingEvent"),e(this,"_relAbsQuat"),e(this,"_wasHighRotationInProgress",!1),e(this,"_timeFirstDivergence",null),e(this,"_callbackMagCalibration"),e(this,"getName",(()=>"AbsoluteAttitude")),e(this,"_onError",(t=>{this._attitudeFromBrowserErrored&&this._attitudeFromRelativeErrored&&this.notifyError(t)})),e(this,"_forceHeadingForRelative",(t=>{if(this.lastEvent&&t.accuracy>this.lastEvent.accuracy)return;const e=e=>{const i=e.heading;this._relAbsQuat=s.Quaternion.fromAxisAngle([0,0,1],i-t.heading),this._relativeAccuracy=0,this._lastForcedHeadingEvent=t};if(this._relativeAttitude)return void e(this._relativeAttitude);const i=Ft.addEventListener((t=>{e(t),Ft.removeEventListener(i)}))})),e(this,"_onRelativeAttitudeEvent",(e=>{var r;const{quaternion:n,accuracy:o,time:a}=e;if(this._relativeAttitude&&(this._relativeAccuracy+=(a-this._relativeAttitude.time)*o),this._relativeAttitude=e,!this._lastForcedHeadingEvent||!this._relAbsQuat)return;const l=Math.min((this._lastForcedHeadingEvent.accuracy||0)+this._relativeAccuracy,Math.PI),h=it.isInProgress();let c=!1;if(this._absAttitudeFromBrowser){const{accuracy:e,heading:o}=this._absAttitudeFromBrowser;if(this._wasHighRotationInProgress&&!h)this._forceHeadingForRelative(this._absAttitudeFromBrowser);else if(e<l){const e=s.Quaternion.multiply(this._relAbsQuat,n),l=new i.Attitude(e),h=Math.abs(s.diffAngle(l.heading,o)),d=At.lastEvent;h>t.REL_ABS_DIVERGENCE_ANGLE_THRESHOLD&&null!==d&&Math.abs(d-Math.PI/4)>t.REL_ABS_DIVERGENCE_INCLINATION_THRESHOLD&&(c=!0,null!==this._timeFirstDivergence&&a-this._timeFirstDivergence>t.REL_ABS_DIVERGENCE_TIME_THRESHOLD?(this._forceHeadingForRelative(this._absAttitudeFromBrowser),null==(r=this._callbackMagCalibration)||r.call(this,{angle:h}),this._timeFirstDivergence=null):null===this._timeFirstDivergence&&(this._timeFirstDivergence=a))}}c||(this._timeFirstDivergence=null),this._wasHighRotationInProgress=h;const d=s.Quaternion.multiply(this._relAbsQuat,n),v=new u(d,a,l);this.notify(v)})),e(this,"_onAttitudeFromBrowser",(t=>{this._absAttitudeFromBrowser=t,this._lastForcedHeadingEvent||this._forceHeadingForRelative(t)})),e(this,"_onAttitudeFromVps",(t=>{this._forceHeadingForRelative(t)}))}availability(){return I.some([Ct.getAvailability(),Ft.getAvailability()])}start(){this.fromBrowserProviderId=Ct.addEventListener(this._onAttitudeFromBrowser,(t=>{this._attitudeFromBrowserErrored=!0,this._onError(t)})),this._vpsProviderId=Rt.addEventListener((t=>this._onAttitudeFromVps(t.absoluteAttitude)),(t=>this.notifyError(t)),!1),this.relativeAttitudeProviderId=Ft.addEventListener(this._onRelativeAttitudeEvent,(t=>{this._attitudeFromRelativeErrored=!0,this._onError(t)})),this.inclinationProviderId=At.addEventListener(),this.highRotationProviderId=it.addEventListener()}stop(){Ct.removeEventListener(this.fromBrowserProviderId),Ft.removeEventListener(this.relativeAttitudeProviderId),At.removeEventListener(this.inclinationProviderId),it.removeEventListener(this.highRotationProviderId),Rt.removeEventListener(this._vpsProviderId)}_setCallbackMagCalibration(t){this._callbackMagCalibration=t}feed(t){if(t instanceof i.AbsoluteHeading){if(null===t.time)throw Error("the time of the absolute heading is not defined");if(null===t.accuracy)throw Error("the accuracy of the absolute heading is not defined");this._forceHeadingForRelative(t)}else{if(!(t instanceof u))throw new Error("data is nor an AbsoluteHeading or an Attitude object");if(null===t.time)throw Error("the time of the attitude is not defined");if(null===t.accuracy)throw Error("the accuracy of the attitude is not defined");this._forceHeadingForRelative(t)}}};e(Ot,"REL_ABS_DIVERGENCE_ANGLE_THRESHOLD",s.deg2rad(25)),e(Ot,"REL_ABS_DIVERGENCE_TIME_THRESHOLD",2.5),e(Ot,"REL_ABS_DIVERGENCE_INCLINATION_THRESHOLD",s.deg2rad(15));const xt=new Ot,Ut=class t extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"slidingWindow",[]),e(this,"getName",(()=>"Turn")),e(this,"availability",(()=>Ft.getAvailability())),e(this,"_parseRelativeAttitude",(e=>{const{heading:i}=e,r=e.time;this.slidingWindow=this.slidingWindow.filter((e=>e[0]>=r-t.SLIDING_WINDOW_TIME)),this.slidingWindow.push([r,i]);s.std(this.slidingWindow.map((t=>t[1])))>t.STD_THRESHOLD&&this.notify({timestamp:r})}))}start(){this.providerId=Ft.addEventListener(this._parseRelativeAttitude,this.notifyError)}stop(){Ft.removeEventListener(this.providerId)}isTurning(){if(!this.lastEvent||!Ft.lastEvent)return!1;return Ft.lastEvent.time-this.lastEvent.timestamp<t.CONSIDER_TURN_UNTIL}};e(Ut,"SLIDING_WINDOW_TIME",.3),e(Ut,"STD_THRESHOLD",.075),e(Ut,"CONSIDER_TURN_UNTIL",1);const Ht=new Ut,Bt=class t extends A{constructor(){super(...arguments),e(this,"_turnProviderId"),e(this,"_stepProviderId"),e(this,"_countSteps",0),e(this,"_stepsConsideredForStraightLine",t.DEFAULT_STEPS_CONSIDERED_FOR_STRAIGHT_LINE),e(this,"getName",(()=>"StraightLine")),e(this,"_onTurn",(()=>{this._countSteps>=this._stepsConsideredForStraightLine&&this.notify(!1),this._countSteps=0})),e(this,"_onStep",(()=>{this._countSteps++,this._countSteps===this._stepsConsideredForStraightLine&&this.notify(!0)}))}availability(){return I.every([Ht.getAvailability(),Et.getAvailability()])}start(){this._turnProviderId=Ht.addEventListener(this._onTurn),this._stepProviderId=Et.addEventListener(this._onStep)}stop(){Ht.removeEventListener(this._turnProviderId),Et.removeEventListener(this._stepProviderId)}isStraight(){return this._countSteps>=this._stepsConsideredForStraightLine}get numStepsDetectedFromLastTurn(){return this._countSteps}get stepsConsideredForStraightLine(){return this._stepsConsideredForStraightLine}set stepsConsideredForStraightLine(t){this._stepsConsideredForStraightLine=t}};e(Bt,"DEFAULT_STEPS_CONSIDERED_FOR_STRAIGHT_LINE",2);const Wt=new Bt,Vt=class t extends A{constructor(){super(...arguments),e(this,"_mapMatchingMaxDistance",t.DEFAULT_MM_MAX_DIST),e(this,"_mapMatchingMinDistance",t.DEFAULT_MM_MIN_DIST),e(this,"_mapMatchingMaxAngleBearing",t.DEFAULT_MM_MAX_ANGLE),e(this,"_useItineraryStartAsPosition",t.DEFAULT_USE_ITINERARY_START_AS_POSITION),e(this,"_useOrientationMatching",t.DEFAULT_USE_ORIENTATION_MATCHING),e(this,"_hugeJumpDistance",t.DEFAULT_MM_HUGE_JUMP_DISTANCE),e(this,"_disableMMCloseToATurnDistance",t.DEFAULT_DISABLE_MM_CLOSE_TO_A_TURN_DISTANCE),e(this,"_minStepsBetweenOrientationMatching",t.DEFAULT_MIN_STEPS_BETWEEN_ORIENTATION_MATCHING),e(this,"_minStepsForOrientationMatching",t.DEFAULT_MIN_STEPS_FOR_ORIENTATION_MATCHING),e(this,"_lastProjectionsWindowSize",t.DEFAULT_LAST_PROJECTIONS_WINDOW_SIZE),e(this,"_lastProjectionsEdgeAngleThreshold",t.DEFAULT_LAST_PROJECTIONS_EDGE_ANGLE_THRESHOLD),e(this,"_graph",null),e(this,"_internalProvidersStarted",!1),e(this,"_straightLineProviderId"),e(this,"_turnProviderId"),e(this,"_stepProviderId"),e(this,"_projectionsWithAbsAndWithoutRelAttitudeInARow",[]),e(this,"_countStepsFromLastMatching",0),e(this,"_lastProjections",[]),e(this,"_itineraryInfoManager",null),e(this,"getName",(()=>"MapMatchingHandler")),e(this,"availability",(()=>Promise.resolve())),e(this,"_manageStartStop",(()=>{this.graph&&!this._internalProvidersStarted?this._startInternalProviders():!this.graph&&this._internalProvidersStarted&&this._stopInternalProviders()}))}start(){this.graph&&this._startInternalProviders()}stop(){this._stopInternalProviders()}_startInternalProviders(){this.enabled&&this._internalProvidersStarted||(this._straightLineProviderId=Wt.addEventListener(),this._turnProviderId=Ht.addEventListener(),this._stepProviderId=Et.addEventListener((()=>this._countStepsFromLastMatching++)),this._internalProvidersStarted=!0)}_stopInternalProviders(){this.enabled&&!this._internalProvidersStarted||(Wt.removeEventListener(this._straightLineProviderId),Ht.removeEventListener(this._turnProviderId),Et.removeEventListener(this._stepProviderId),this._internalProvidersStarted=!1)}get enabled(){return E.useMapMatching}get graph(){return this._graph}set graph(t){this._graph=t,this._itineraryInfoManager=null,this.notify({...t&&{graph:t}}),this._manageStartStop(),this.canUseMapMatching()}set itinerary(t){this._graph=t?t.toGraph():null,this._itineraryInfoManager=new r.ItineraryInfoManager(t),this.notify({...t&&{itinerary:t}}),this._manageStartStop(),this.canUseMapMatching()&&t&&this._notifyPositionFromItineraryInput(t)}canUseMapMatching(){return this.enabled&&this.graph}_notifyPositionFromItineraryInput(t){if(!this._useItineraryStartAsPosition||!t.origin)return;const e=Nt.lastEvent||null,s=i.UserPosition.fromCoordinates(t.origin);if(e)s.alt=e.alt,s.time=e.time,s.accuracy=e.accuracy+s.distanceTo(e),s.bearing=e.bearing;else{if(!(t.coords.length>=2))return;s.alt=D.DEFAULT_ALTITUDE,s.time=n.TimeUtils.preciseTime(),s.accuracy=0,s.bearing=t.coords[0].bearingTo(t.coords[1])}const r=this.getProjection(s,!0);r?Nt.notify(r.coords):Nt.notify(s)}notifyPositionFromFeed(t){const e=this.getProjection(t,!0,!1);e?Nt.notify(e.coords):Nt.notify(t)}notifyPositionFromAbsolute(t){let e=null;if(null!==t.bearing&&(e=this.getProjection(t,!0,!0)),!e)return Nt.notify(t),!0;const i=e.distanceFromNearestElement>this._hugeJumpDistance;return!(i&&!Wt.isStraight())&&((!i||!this._detectWrongBigJump(e))&&(Nt.notify(e.coords),this.tryOrientationMatching(e),!0))}notifyPositionFromRelative(t){var e;if(Ht.isTurning())return this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections=[],Nt.notify(t),!0;const i=this.getProjection(t,!0,!0);if(i){this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections.push(i),this._lastProjections.length>this._lastProjectionsWindowSize&&this._lastProjections.shift();const e=i.distanceFromNearestElement>this._hugeJumpDistance;return e&&!Wt.isStraight()||e&&this._detectWrongBigJump(i)?(Nt.notify(t),!0):this._areLastProjectionsInTheSameDirection()?this._disableMMCloseToATurnDistance>0&&this._hasTurnInCircle(i.coords,this._disableMMCloseToATurnDistance)?(Nt.notify(t),!0):(Nt.notify(i.coords),this.tryOrientationMatching(i),!0):(Nt.notify(t),!0)}if(Wt.isStraight()){const i=t.clone();i.bearing=(null==(e=Ct.lastEvent)?void 0:e.heading)||null;const s=this.getProjection(i,!0,!0);if(s)return this._projectionsWithAbsAndWithoutRelAttitudeInARow.push(s),this._projectionsWithAbsAndWithoutRelAttitudeInARow.length<3?(Nt.notify(t),!0):(this._lastProjections.push(s),this._lastProjections.length>this._lastProjectionsWindowSize&&this._lastProjections.shift(),this._areLastProjectionsInTheSameDirection()?(Nt.notify(s.coords),this.tryOrientationMatching(s),!0):(Nt.notify(t),!0))}return this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections=[],Nt.notify(t),!0}_detectWrongBigJump(t){if(this._itineraryInfoManager&&Nt.lastEvent){const e=this._itineraryInfoManager.getInfo(Nt.lastEvent),i=this._itineraryInfoManager.getInfo(t.coords);if(e&&i&&e.traveledDistance>i.traveledDistance&&e.traveledDistance-i.traveledDistance>t.origin.accuracy&&t.distanceFromNearestElement>t.origin.accuracy&&t.origin.distanceTo(Nt.lastEvent)<t.origin.accuracy+Nt.lastEvent.accuracy)return!0}return!1}_areLastProjectionsInTheSameDirection(){if(0===this._lastProjections.length)return!1;const t=this._lastProjections[0];return!this._lastProjections.some((e=>!(e.nearestElement instanceof r.Edge)||!(t.nearestElement instanceof r.Edge)||s.diffAngleLines(e.nearestElement.bearing,t.nearestElement.bearing)>this._lastProjectionsEdgeAngleThreshold))}_nodeHasTurn(e){if(!this._graph)return;const i=this._graph.edges.filter((t=>t.vertex1===e||t.vertex2===e));for(let r=0;r<i.length;r++)for(let e=r+1;e<i.length;e++){if(s.diffAngleLines(i[r].bearing,i[e].bearing)>t.DEFAULT_MM_MAX_ANGLE)return!0}return!1}_hasTurnInCircle(t,e){const s=this._graph;return!!s&&s.vertices.filter((s=>s.coords.distanceTo(t)<=e&&i.Level.intersect(s.coords.level,t.level))).some((t=>this._nodeHasTurn(t)))}tryOrientationMatching(t){if(!this._useOrientationMatching)return;if("started"!==this.state||this._countStepsFromLastMatching<this._minStepsBetweenOrientationMatching||Wt.numStepsDetectedFromLastTurn<this._minStepsForOrientationMatching)return;const{nearestElement:e,origin:n}=t;if(!(e instanceof r.Edge))return;let o;const a=s.diffAngle(e.bearing,n.bearing),l=s.diffAngle(e.bearing+Math.PI,n.bearing);o=Math.abs(a)<Math.abs(l)?e.bearing:(e.bearing+Math.PI)%(2*Math.PI);const h=new i.AbsoluteHeading(o,n.time,0);xt._forceHeadingForRelative(h),this._countStepsFromLastMatching=0}getProjection(t,e,i){var s;const r={...e&&{maxDistance:this._mapMatchingMaxDistance},...i&&{maxBearingAngle:this._mapMatchingMaxAngleBearing}};return null==(s=this._graph)?void 0:s.getProjection(t,r)}get maxDistance(){return this._mapMatchingMaxDistance}set maxDistance(t){this._mapMatchingMaxDistance=t}get minDistance(){return this._mapMatchingMinDistance}set minDistance(t){this._mapMatchingMinDistance=t}get maxAngleBearing(){return this._mapMatchingMaxAngleBearing}set maxAngleBearing(t){this._mapMatchingMaxAngleBearing=t}get useItineraryStartAsPosition(){return this._useItineraryStartAsPosition}set useItineraryStartAsPosition(t){this._useItineraryStartAsPosition=t}get useOrientationMatching(){return this._useOrientationMatching}set useOrientationMatching(t){this._useOrientationMatching=t}get hugeJumpDistance(){return this._hugeJumpDistance}set hugeJumpDistance(t){this._hugeJumpDistance=t}get disableMMCloseToATurnDistance(){return this._disableMMCloseToATurnDistance}set disableMMCloseToATurnDistance(t){this._disableMMCloseToATurnDistance=t}get minStepsBetweenOrientationMatching(){return this._minStepsBetweenOrientationMatching}set minStepsBetweenOrientationMatching(t){this._minStepsBetweenOrientationMatching=t}get minStepsForOrientationMatching(){return this._minStepsForOrientationMatching}set minStepsForOrientationMatching(t){this._minStepsForOrientationMatching=t}get lastProjectionsWindowSize(){return this._lastProjectionsWindowSize}set lastProjectionsWindowSize(t){this._lastProjectionsWindowSize=t}get lastProjectionsEdgeAngleThreshold(){return this._lastProjectionsEdgeAngleThreshold}set lastProjectionsEdgeAngleThreshold(t){this._lastProjectionsEdgeAngleThreshold=t}};e(Vt,"DEFAULT_MM_MAX_ANGLE",s.deg2rad(30)),e(Vt,"DEFAULT_MM_MAX_DIST",30),e(Vt,"DEFAULT_MM_MIN_DIST",0),e(Vt,"DEFAULT_USE_ITINERARY_START_AS_POSITION",!1),e(Vt,"DEFAULT_USE_ORIENTATION_MATCHING",!0),e(Vt,"DEFAULT_MM_HUGE_JUMP_DISTANCE",3),e(Vt,"DEFAULT_DISABLE_MM_CLOSE_TO_A_TURN_DISTANCE",2),e(Vt,"DEFAULT_MIN_STEPS_BETWEEN_ORIENTATION_MATCHING",3),e(Vt,"DEFAULT_MIN_STEPS_FOR_ORIENTATION_MATCHING",5),e(Vt,"DEFAULT_LAST_PROJECTIONS_WINDOW_SIZE",3),e(Vt,"DEFAULT_LAST_PROJECTIONS_EDGE_ANGLE_THRESHOLD",s.deg2rad(3));const Gt=new Vt,kt=class t{constructor(i,s=t.DEFAULT_FREQUENCY){e(this,"positionsQueue",[]),e(this,"previousPosition",null),e(this,"timeoutNotify"),e(this,"_notifyNext",(()=>{var t;this.positionsQueue.length&&(null==(t=this.callback)||t.call(this,this.positionsQueue.shift()),0!==this.positionsQueue.length?this.timeoutNotify=setTimeout(this._notifyNext,1e3/this.frequency):delete this.timeoutNotify)})),this.callback=i,this.frequency=s}feed(e,s=t.DEFAULT_FLYBY_TIME){if(!(e instanceof i.UserPosition))throw new TypeError("newPosition is not instance of UserPosition");if(null===e.time)throw new Error("newPosition does not have time property");let r;if(0!==this.positionsQueue.length?(r=this.positionsQueue[0],this.positionsQueue=[]):r=this.previousPosition,r){const t=e.time,n=r.distanceTo(e),o=r.bearingTo(e);let a=1;const l=this.frequency*s+1,h=i.Level.clone(e.level);for(;a<l+1;){const i=r.destinationPoint(n*a/l,o);i.time=t+(a-1)/this.frequency,i.level=h,i.bearing=e.bearing,i.accuracy=Math.max(i.accuracy+(e.accuracy-i.accuracy)*a/l,0),this.positionsQueue.push(i),a++}this.timeoutNotify&&clearTimeout(this.timeoutNotify)}else this.positionsQueue.push(e.clone());this.previousPosition=e,this._notifyNext()}clear(){clearTimeout(this.timeoutNotify),delete this.timeoutNotify,this.positionsQueue=[]}};e(kt,"DEFAULT_FREQUENCY",60),e(kt,"DEFAULT_FLYBY_TIME",1);let Qt=kt;const qt=class t{constructor(t){e(this,"_previousAttitude"),e(this,"_smoothing",null),this.callback=t}feed(e){if(null===e.time)throw new Error("newAttitude does not have time property");const{_previousAttitude:r}=this;if(this._previousAttitude=e,r){if(t.isJump(r,e)){const n=null===this._smoothing?r:this._smoothing.interpAttitude(r),o=n.heading,a=e.heading,l=s.diffAngle(a,o),h=Math.abs(l)<t.HIGH_JUMP_THRESHOLD?t.ROTATION_SPEED_CONVERGENCE:t.ROTATION_SPEED_HIGH_JUMP_CONVERGENCE,c=n.time,d=Math.abs(l)/h,u=l<0?-1:1;this._smoothing={toTime:c+d,interpAttitude:t=>{const e=h*(t.time-c),r=o+e*u,n=s.Quaternion.fromAxisAngle([0,0,1],a-r),l=s.Quaternion.multiply(n,t.quaternion);return new i.Attitude(l,t.time,t.accuracy)}}}if(null!==this._smoothing){if(!(e.time>=this._smoothing.toTime)){const t=this._smoothing.interpAttitude(e);return void this.callback(t)}this._smoothing=null}this.callback(e)}else this.callback(e)}static isJump(e,i){const r=e.heading,n=i.heading,o=s.diffAngle(n,r),a=i.time-e.time,[l,h,c,d]=i.quaternion;return!(Math.abs(Math.asin(2*(l*h+c*d))-Math.PI/4)<t.PITCH_UNCERTAINITY_HEADING_THRESHOLD)&&Math.abs(o)>t.ROTATION_SPEED_JUMP_THRESHOLD*a}};e(qt,"ROTATION_SPEED_JUMP_THRESHOLD",s.deg2rad(180)),e(qt,"ROTATION_SPEED_CONVERGENCE",s.deg2rad(10)),e(qt,"HIGH_JUMP_THRESHOLD",s.deg2rad(20)),e(qt,"ROTATION_SPEED_HIGH_JUMP_CONVERGENCE",s.deg2rad(100)),e(qt,"PITCH_UNCERTAINITY_HEADING_THRESHOLD",s.deg2rad(5));let jt=qt;const zt=new class extends A{constructor(){super(),e(this,"getName",(()=>"MagnetometerCalibrationProvider")),e(this,"availability",(()=>xt.getAvailability())),xt._setCallbackMagCalibration((t=>"started"===this.state&&this.notify(t)))}start(){}stop(){}},Jt=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(Jt,"DEFAULT_MESSAGE","IP Resolver failed");let Yt=Jt;const Xt=new class extends A{constructor(){super(...arguments),e(this,"getName",(()=>"Ip")),e(this,"availability",(()=>Promise.resolve()))}async start(){const t=await fetch("https://ipinfo.io/geo?token=24a7ca2f3b489d");if(!t)return void this.notifyError(new Yt);const e=n.TimeUtils.preciseTime()/1e3,s=(await t.json()).loc.split(","),r=new i.UserPosition(parseFloat(s[0]),parseFloat(s[1]),null,null,e,1e5);this.notify(r)}stop(){}};const Kt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"Barcode")),e(this,"availability",(()=>W.getAvailability()))}start(){W.enableBarcodeScanner(),this.providerId=W.addEventListener((t=>t.barcode&&this.notify(t.barcode)),this.notifyError)}stop(){W.disableBarcodeScanner(),W.removeEventListener(this.providerId)}};const Zt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"CameraNative")),e(this,"availability",(()=>Promise.resolve()))}start(){"stopped"!==W.state&&this.notify("started"),this.providerId=W.addMonitoringListener((()=>this.notify("started")),(()=>this.notify("stopped")))}stop(){W.removeMonitoringListener(this.providerId)}};const $t=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"CameraProjectionMatrix")),e(this,"availability",(()=>W.getAvailability()))}start(){this.providerId=W.addEventListener((t=>t.cameraProjection&&this.notify(t.cameraProjection)),this.notifyError)}stop(){W.removeEventListener(this.providerId)}};exports.AbsoluteAttitude=u,exports.AbsoluteAttitudeFromBrowserProvider=Ct,exports.AbsoluteAttitudeProvider=xt,exports.AbsolutePosition=v,exports.AbsolutePositionProvider=Nt,exports.AccelerometerProvider=J,exports.ArCoreProvider=W,exports.AttitudeSmoother=jt,exports.BarcodeProvider=Kt,exports.CameraNativeProvider=Zt,exports.CameraProjectionMatrixProvider=$t,exports.Constants=D,exports.GeoRelativePositionFromArCoreProvider=V,exports.GeoRelativePositionProvider=mt,exports.GnssWifiProvider=F,exports.GyroscopeProvider=X,exports.HighRotationsProvider=it,exports.ImageRelocalization=Tt,exports.ImuProvider=q,exports.InclinationFromAccProvider=pt,exports.InclinationFromRelativeAttitudeProvider=gt,exports.InclinationProvider=At,exports.IpProvider=Xt,exports.MagnetometerCalibrationProvider=zt,exports.MapMatchingHandler=Gt,exports.PdrProvider=_t,exports.PoleStarProvider=bt,exports.PositionSmoother=Qt,exports.ProvidersLoggerOld=_,exports.ProvidersOptions=E,exports.RelativeAttitude=d,exports.RelativeAttitudeFromBrowserProvider=tt,exports.RelativeAttitudeFromEkfProvider=Z,exports.RelativeAttitudeFromInertialProvider=rt,exports.RelativeAttitudeProvider=Ft,exports.RelativeRotationCalc=St,exports.StepDetectionMinMaxPeaks2=ct,exports.StepDetectionMinMaxPeaks3=ut,exports.StepProvider=Et,exports.StraightLineProvider=Wt,exports.TurnProvider=Ht,exports.VpsMetadata=It,exports.VpsProvider=Rt,exports.VpsRequest=ft,exports.VpsResponse=Pt;
|
|
1
|
+
"use strict";var t=Object.defineProperty,e=(e,i,s)=>(((e,i,s)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s})(e,"symbol"!=typeof i?i+"":i,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@wemap/geo"),s=require("@wemap/maths"),r=require("@wemap/routers"),n=require("@wemap/utils"),o=require("@wemap/logger"),a=require("geomag"),l=require("@wemap/camera");function h(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t)for(const i in t)if("default"!==i){const s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>t[i]})}return e.default=t,Object.freeze(e)}const c=h(a);class d extends i.Attitude{}class u extends i.Attitude{}class v extends i.UserPosition{}const E={useMapMatching:!0,ignoreProviders:[],optionalProviders:[],stopOnError:!0,checkAvailabilityOnStart:!0,get hasPoleStar(){return this.optionalProviders.includes("PoleStar")}};const _=new class{constructor(){e(this,"_enabled",!1),e(this,"currentId",0),e(this,"objectsIdMap",new WeakMap),e(this,"pushEvents",{}),e(this,"pushEventsRef",{}),e(this,"interval"),e(this,"initDate")}get enabled(){return this._enabled}set enabled(t){this._enabled=t}initializeInterval(){this.interval||(this.interval=window.setInterval((()=>{for(const[t,e]of Object.entries(this.pushEvents))o.debug("Received "+e+" notifications from "+this.pushEventsRef[Number(t)].getName()+" last second");this.pushEvents={},this.pushEventsRef={}}),1e3))}getObjectId(t){return this.objectsIdMap.has(t)||this.objectsIdMap.set(t,++this.currentId),this.objectsIdMap.get(t)}addEvent(t,e){if(!this.enabled)return;this.initDate||(this.initDate=Date.now()),this.initializeInterval();const i=this.getObjectId(t),s=t.getName();o.debug(s+"["+i+"]."+e)}incrementNotifications(t){if(!this.enabled)return;const e=this.getObjectId(t);let i=this.pushEvents[e];i||(i=0,this.pushEventsRef[e]=t),this.pushEvents[e]=i+1}},m=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(m,"DEFAULT_MESSAGE","Contains ignored provider");let p=m;const g=class t{constructor(){e(this,"id"),e(this,"state","stopped"),e(this,"_lastEvent",null),e(this,"_eventsCallbacks",[]),e(this,"_monitoringCallbacks",[]),e(this,"notify",(t=>{_.incrementNotifications(this),this._eventsCallbacks.forEach((e=>{var i;return null==(i=e.onEvent)?void 0:i.call(e,t)})),this._lastEvent=t})),e(this,"notifyError",(t=>{this._eventsCallbacks.forEach((({id:e,onError:i})=>{E.stopOnError&&this.removeEventListener(e),null==i||i(t)}))})),this.id=t._uniqueId++,_.addEvent(this,"constructor")}getAvailability(){return E.ignoreProviders.includes(this.getName())?Promise.resolve(new p):this.availability()}get hasNativeInterface(){return Boolean(this.nativeInterface)}get nativeInterface(){return"undefined"!=typeof window&&window.__nativeProviders||null}get nativeJsInterface(){return"undefined"==typeof window?null:(window.__nativeJsProviders||(window.__nativeJsProviders={}),window.__nativeJsProviders)}get useCameraNatively(){return!1}addEventListener(e=null,i=null,s=!0){const r=++t._callbackUniqueId;if(this._eventsCallbacks.push({id:r,onEvent:e||(()=>{}),onError:i||(()=>{}),optional:!s}),!s)return r;if("stopped"!==this.state)return r;this.state="starting";let n=Promise.resolve();return E.checkAvailabilityOnStart&&(n=this.getAvailability()),(async()=>{const t=await n;if(t)return this.state="stopped",void this.notifyError(t);_.addEvent(this,"start"),this.start(),this.state="started",this._monitoringCallbacks.forEach((t=>{var e;return null==(e=t.onStarted)?void 0:e.call(t)}))})(),r}removeEventListener(t){const e=this._eventsCallbacks.find((e=>e.id===t));e&&(this._eventsCallbacks=this._eventsCallbacks.filter((t=>t!==e)),e.optional||this._eventsCallbacks.find((t=>!t.optional))||"stopped"!==this.state&&(_.addEvent(this,"stop"),this.stop(),this.state="stopped",this._monitoringCallbacks.forEach((t=>{var e;return null==(e=t.onStopped)?void 0:e.call(t)}))))}addMonitoringListener(e,i){const s=t._callbackUniqueId++;return this._monitoringCallbacks.push({id:s,onStarted:e||null,onStopped:i||null}),s}removeMonitoringListener(t){this._monitoringCallbacks=this._monitoringCallbacks.filter((e=>e.id!==t))}get lastEvent(){return this._lastEvent}};e(g,"_callbackUniqueId",0),e(g,"_uniqueId",1);let A=g;class I{static async every(t){for(const e of t){const t=await e;if(t)return t}return null}static async some(t){let e;for(const i of t){const t=await i;if(!t)return null;e||(e=t)}return e||null}}const f=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(f,"DEFAULT_MESSAGE","It seems that you ask for IMU events on a desktop browser");let P=f;const T=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}from(t){return this.message+=" from "+t,this}};e(T,"DEFAULT_MESSAGE","Impossible to retrieve events, a sensor is missing");let S=T;class y extends S{constructor(t){super(t)}}const M=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(M,"DEFAULT_MESSAGE","Geolocation api is missing");let b=M;const L=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(L,"DEFAULT_MESSAGE","Geolocation permission denied");let R=L;const w=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(w,"DEFAULT_MESSAGE","Geolocation position unavailable");let N=w;const D={DEFAULT_ALTITUDE:1.6},C=class t extends A{constructor(){super(...arguments),e(this,"discardPositionsAbove",t.DEFAULT_DISCARD_POSITIONS_ABOVE),e(this,"enableHighAccuracy",!0),e(this,"geoLocationId"),e(this,"getName",(()=>"GnssWifi")),e(this,"onNewPosition",(t=>{const{coords:e}=t;if(!e)return;let r;e.heading&&(r=s.deg2rad(e.heading));const o=n.TimeUtils.unixTimestampToPreciseTime(t.timestamp)/1e3,a=new i.UserPosition(e.latitude,e.longitude,D.DEFAULT_ALTITUDE,null,o,e.accuracy,r);this.enableHighAccuracy&&"number"==typeof this.discardPositionsAbove&&e.accuracy>this.discardPositionsAbove||this.notify(a)})),e(this,"onPositionError",(t=>{let e;switch(o.warn(`[Providers] watchPosition error: [${t.code}] ${t.message}`),t.code){case 1:e=new R(t.message);break;case 2:e=new N(t.message);break;default:e=new Error(t.message)}this.notifyError(e)}))}get positionOptions(){return{enableHighAccuracy:this.enableHighAccuracy,timeout:1/0,maximumAge:0}}availability(){return"object"==typeof navigator&&navigator.geolocation?Promise.resolve():Promise.resolve(new b)}start(){navigator.geolocation.getCurrentPosition(this.onNewPosition,this.onPositionError,this.positionOptions),setTimeout((()=>{this.geoLocationId=navigator.geolocation.watchPosition(this.onNewPosition,this.onPositionError,this.positionOptions)}),150)}stop(){void 0!==this.geoLocationId&&navigator.geolocation.clearWatch(this.geoLocationId)}};e(C,"DEFAULT_DISCARD_POSITIONS_ABOVE",50);const F=new C,O=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(O,"DEFAULT_MESSAGE","ARCore is missing");let x=O;const U=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(U,"DEFAULT_MESSAGE","Native interface is missing. You are maybe trying to execute a code which is not available in a web browser");let H=U;const B=class t extends A{constructor(){super(...arguments),e(this,"_nativeProvider"),e(this,"previousPosition",[0,0,0]),e(this,"getName",(()=>"ArCore")),e(this,"pullDataLoop",(()=>{if("stopped"===this.state)return;const t=JSON.parse(this.nativeProvider.getInfo());t.length>1&&this.parsePayload(t),requestAnimationFrame(this.pullDataLoop)}))}availability(){try{if(!this.nativeProvider.checkAvailability())return Promise.resolve(new x)}catch(t){return Promise.resolve(t)}return Promise.resolve()}start(){var t;null==(t=this.nativeProvider)||t.start(),this.pullDataLoop()}stop(){var t;null==(t=this.nativeProvider)||t.stop()}parsePayload(e){const s=e[0];let r,o,a,l,h=1;const c=n.TimeUtils.preciseTime()/1e3;if(s&t.Payload.Pose.ref){r=new d(e.slice(h,h+4),c,t.RELATIVE_ATTITUDE_DRIFT);const s=[e[h+4],e[h+5],e[h+6]];o=new i.RelativePosition(s[0]-this.previousPosition[0],s[1]-this.previousPosition[1],s[2]-this.previousPosition[2],c,1e-4),this.previousPosition=s,h+=t.Payload.Pose.size}s&t.Payload.Barcode.ref&&(l=e[h],h+=t.Payload.Barcode.size),s&t.Payload.ProjMat.ref&&(a=e.slice(h,h+t.Payload.ProjMat.size),h+=t.Payload.ProjMat.size),this.notify({relativePosition:o,relativeAttitude:r,...l&&{barcode:l},...a&&{cameraProjection:a}})}get nativeProvider(){if(!this._nativeProvider){if(!this.nativeInterface)throw new H;if(this._nativeProvider=this.nativeInterface.getArCoreProvider(),!this._nativeProvider)throw new x}return this._nativeProvider}enableBarcodeScanner(){try{this.nativeProvider.enableBarcodeScanner()}catch(t){this.notifyError(t)}}disableBarcodeScanner(){try{this.nativeProvider.disableBarcodeScanner()}catch(t){this.notifyError(t)}}get useCameraNatively(){return!0}};e(B,"Payload",{Pose:{ref:1,size:7},Barcode:{ref:2,size:1},ProjMat:{ref:4,size:16},ImageRef:{ref:8,size:1}}),e(B,"RELATIVE_ATTITUDE_DRIFT",s.deg2rad(3)/60);const W=new B;const V=new class extends A{constructor(){super(...arguments),e(this,"absoluteAttitudeProviderId"),e(this,"arCoreProviderId"),e(this,"absoluteAttitudeEvent"),e(this,"getName",(()=>"GeoRelativePositionFromArCore")),e(this,"onArCoreEvents",(t=>{const e=t.relativeAttitude,i=t.relativePosition;e&&i&&this.absoluteAttitudeEvent&&this.compute(i,e,this.absoluteAttitudeEvent)}))}availability(){return I.every([W.getAvailability(),Ut.getAvailability()])}start(){this.arCoreProviderId=W.addEventListener(this.onArCoreEvents,this.notifyError),this.absoluteAttitudeProviderId=Ut.addEventListener((t=>this.absoluteAttitudeEvent=t),this.notifyError)}stop(){W.removeEventListener(this.arCoreProviderId),Ut.removeEventListener(this.absoluteAttitudeProviderId)}compute(t,e,s){const r=s.heading-e.heading,n=Math.cos(r)*t.x-Math.sin(r)*t.z,o=-Math.sin(r)*t.x-Math.cos(r)*t.z,a=t.y,l=new i.GeoRelativePosition(n,o,a,t.time,0,s.heading);this.notify(l)}},G={acc:.5,gyr:.3},q={acc:.5,gyr:.3,yc:2};class Q{constructor(t=[0,0,1],i=[-1,0,0]){e(this,"P"),e(this,"accRef"),e(this,"cRef"),e(this,"noises"),e(this,"quaternion"),this.accRef=t,this.cRef=i,this.P=s.Matrix4.fromDiagVector(Array(4).fill(.1**2)),this.quaternion=null,this.noises={},this.setRelativeNoises(G),this.setAbsoluteNoises(q)}setRelativeNoises(t){this.noises.relative={acc:s.Matrix3.diag(Array(3).fill(t.acc**2)),gyr:s.Matrix3.diag(Array(3).fill(t.gyr**2))}}setAbsoluteNoises(t){this.noises.absolute={acc:s.Matrix3.diag(Array(3).fill(t.acc**2)),gyr:s.Matrix3.diag(Array(3).fill(t.gyr**2)),yc:s.Matrix3.diag(Array(3).fill(t.yc**2))}}tryInitialize(t,e){const i=s.Vector3.normalize(t);if(e){const t=s.Vector3.normalize(e),r=s.Vector3.normalize(s.Vector3.cross(t,i)),n=s.Vector3.cross(i,r),o=[[r[0],n[0],i[0]],[r[1],n[1],i[1]],[r[2],n[2],i[2]]];this.quaternion=s.Quaternion.fromMatrix3Matlab(o)}else{const t=s.Vector3.dot(i,this.accRef)+1,e=s.Vector3.cross(i,this.accRef);let r=[t,e[0],e[1],e[2]];r=s.Quaternion.normalize(r),this.quaternion=r}return this.quaternion}update(t,e,i,r){if(!this.quaternion)return this.tryInitialize(e,r);let n=this.quaternion;const o=n,a=s.Vector3.multiplyScalar(i,.5*t),l=this.computeC([1,a[0],a[1],a[2]]),h=s.Matrix4.multiplyVector(l,n),c=s.Matrix3.diag([o[0],o[0],o[0]]),d=s.Matrix3.skew([o[1],o[2],o[3]]),u=[-1*o[1],-1*o[2],-1*o[3]],v=s.Matrix.concatRow([u],s.Matrix3.sum(d,c)),E=s.Matrix4.multiplyScalar(s.Matrix.multiply(s.Matrix.multiply(v,this.noises[r?"absolute":"relative"].gyr),s.Matrix.transpose(v)),(t/2)**2),_=s.Matrix4.sum(s.Matrix4.multiply(s.Matrix4.multiply(l,this.P),s.Matrix4.transpose(l)),E),m=s.Vector3.normalize(e);let p,g,A;if(r){const t=s.Vector3.normalize(r),e=s.Vector3.cross(m,t),i=s.Vector3.normalize(e),n=s.Vector3.subtract(i,s.Quaternion.rotateMatlab(h,this.cRef)),o=s.Vector3.subtract(m,s.Quaternion.rotateMatlab(h,this.accRef));p=s.Vector.concat(n,o);const a=this.jacobianES(h,this.cRef),l=this.jacobianES(h,this.accRef);A=s.Matrix.concatRow(a,l);const c=s.Matrix.concatLine(this.noises.absolute.yc,s.Matrix3.zeros),d=s.Matrix.concatLine(s.Matrix3.zeros,this.noises.absolute.acc),u=s.Matrix.concatRow(c,d);g=s.Matrix.multiply(s.Matrix.multiply(_,s.Matrix.transpose(A)),s.Matrix.inverse(s.Matrix.sum(s.Matrix.multiply(s.Matrix.multiply(A,_),s.Matrix.transpose(A)),u)))}else{p=s.Vector3.subtract(m,s.Quaternion.rotateMatlab(h,this.accRef)),A=this.jacobianES(h,this.accRef);const t=this.noises.relative.acc;g=s.Matrix.multiply(s.Matrix.multiply(_,s.Matrix.transpose(A)),s.Matrix3.inverse(s.Matrix3.sum(s.Matrix.multiply(s.Matrix.multiply(A,_),s.Matrix.transpose(A)),t)))}n=s.Quaternion.sum(h,s.Matrix.multiplyVector(g,p));const I=s.Matrix4.multiply(s.Matrix4.subtract(s.Matrix4.identity,s.Matrix.multiply(g,A)),_);return n=s.Quaternion.normalize(n),this.quaternion=n,this.P=I,n}computeC(t){return[[t[0],-t[1],-t[2],-t[3]],[t[1],t[0],t[3],-t[2]],[t[2],-t[3],t[0],t[1]],[t[3],t[2],-t[1],t[0]]]}jacobianES(t,e){const[i,s,r,n]=t,[o,a,l]=e;return[[2*n*a-2*r*l,2*r*a+2*n*l,2*s*a-2*i*l-4*r*o,2*i*a+2*s*l-4*n*o],[2*s*l-2*n*o,2*i*l-4*s*a+2*r*o,2*s*o+2*n*l,2*r*l-2*i*o-4*n*a],[2*r*o-2*s*a,2*n*o-4*s*l-2*i*a,2*i*o-4*r*l+2*n*a,2*s*o+2*r*a]]}}const k=new class extends A{constructor(){super(...arguments),e(this,"getName",(()=>"IMU")),e(this,"parseDeviceMotionEvent",(t=>{const e=t.timeStamp/1e3;let i,r;if(t.accelerationIncludingGravity){const{x:e,y:s,z:r}=t.accelerationIncludingGravity;"number"==typeof e&&"number"==typeof s&&"number"==typeof r&&(i=[e,s,r],n.BrowserUtils.getName()!==n.Browser.SAFARI&&n.BrowserUtils.getName()!==n.Browser.IOS_WEBVIEW||(i[0]*=-1,i[1]*=-1,i[2]*=-1))}if(t.rotationRate){const{alpha:e,beta:i,gamma:n}=t.rotationRate;"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&(r=[s.deg2rad(e),s.deg2rad(i),s.deg2rad(n)])}(i||r)&&this.notify({...i&&{acceleration:{timestamp:e,values:i}},...r&&{angularRate:{timestamp:e,values:r}}})}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>window.addEventListener("devicemotion",this.parseDeviceMotionEvent,!0),e=DeviceMotionEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch(this.notifyError):t()}stop(){window.removeEventListener("devicemotion",this.parseDeviceMotionEvent,!0)}},j=class t extends S{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(j,"DEFAULT_MESSAGE","Impossible to retrieve Acceleration data");let z=j;const J=new class extends A{constructor(){super(...arguments),e(this,"imuProviderId"),e(this,"getName",(()=>"Accelerometer")),e(this,"availability",(()=>k.getAvailability()))}start(){this.imuProviderId=k.addEventListener((t=>{t.acceleration?this.notify(t.acceleration):this.notifyError((new z).from("devicemotion"))}),this.notifyError)}stop(){k.removeEventListener(this.imuProviderId)}};class Y extends S{constructor(t){super(t||S.DEFAULT_MESSAGE)}}e(Y,"DEFAULT_MESSAGE","Impossible to retrieve Angular Rate data");const X=new class extends A{constructor(){super(...arguments),e(this,"imuProviderId"),e(this,"getName",(()=>"Gyroscope")),e(this,"availability",(()=>k.getAvailability()))}start(){this.imuProviderId=k.addEventListener((t=>{t.angularRate?this.notify(t.angularRate):this.notifyError((new Y).from("devicemotion"))}),this.notifyError)}stop(){k.removeEventListener(this.imuProviderId)}},K=class t extends A{constructor(){super(...arguments),e(this,"accelerometerProviderId"),e(this,"ekfAttitude",new Q),e(this,"gyroscopeEvent"),e(this,"gyroscopeProviderId"),e(this,"lastTimestamp",0),e(this,"getName",(()=>"RelativeAttitudeFromEkf")),e(this,"onAccelerometerEvent",(e=>{if(!this.gyroscopeEvent)return;const{values:i,timestamp:s}=e;if(0===this.lastTimestamp)return void(this.lastTimestamp=s);const r=s-this.lastTimestamp;this.lastTimestamp=s;const n=this.ekfAttitude.update(r,i,this.gyroscopeEvent.values);if(n){const e=new d(n,s,t.DEFAULT_DRIFT);this.notify(e)}}))}availability(){return I.every([J.getAvailability(),X.getAvailability()])}start(){this.accelerometerProviderId=J.addEventListener((t=>this.onAccelerometerEvent(t)),(t=>this.notifyError(t))),this.gyroscopeProviderId=X.addEventListener((t=>this.gyroscopeEvent=t),(t=>this.notifyError(t)))}stop(){J.removeEventListener(this.accelerometerProviderId),X.removeEventListener(this.gyroscopeProviderId)}};e(K,"DEFAULT_DRIFT",s.deg2rad(5)/60);const Z=new K,$=class t extends A{constructor(){super(...arguments),e(this,"getName",(()=>"RelativeAttitudeFromBrowser")),e(this,"onDeviceOrientationEvent",(e=>{if("number"!=typeof e.alpha||"number"!=typeof e.beta||"number"!=typeof e.gamma)return void this.notifyError((new S).from("deviceorientation"));const i=s.Rotations.eulerToQuaternionZXYDegrees([e.alpha,e.beta,e.gamma]),r=new d(i,e.timeStamp/1e3,t.DEFAULT_DRIFT);this.notify(r)}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>window.addEventListener("deviceorientation",this.onDeviceOrientationEvent,!0),e=DeviceOrientationEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch((t=>this.notifyError(t))):t()}stop(){window.removeEventListener("deviceorientation",this.onDeviceOrientationEvent,!0)}};e($,"DEFAULT_DRIFT",s.deg2rad(5)/60);const tt=new $,et=class t extends A{constructor(){super(...arguments),e(this,"gyroscopeProviderId"),e(this,"getName",(()=>"HighRotationsProvider")),e(this,"availability",(()=>X.getAvailability())),e(this,"_parseGyroscopeEvent",(e=>{const{values:i,timestamp:r}=e;s.Vector3.norm(i)>t.THRESHOLD&&this.notify({timestamp:r})}))}start(){this.gyroscopeProviderId=X.addEventListener(this._parseGyroscopeEvent,this.notifyError)}stop(){X.removeEventListener(this.gyroscopeProviderId)}isInProgress(){if(!this.lastEvent||!X.lastEvent)return!1;return X.lastEvent.timestamp-this.lastEvent.timestamp<t.DELAY_CONSIDERATION}};e(et,"THRESHOLD",10),e(et,"DELAY_CONSIDERATION",3);const it=new et,st=class t extends A{constructor(){super(...arguments),e(this,"_highRotationsProviderId"),e(this,"listenerId"),e(this,"provider"),e(this,"getName",(()=>"RelativeAttitudeFromInertial"))}availability(){return I.some([Z.getAvailability(),tt.getAvailability()])}start(){Z.getAvailability().then((t=>{this.provider=t?tt:Z,this.listenerId=this.provider.addEventListener((t=>this._parseEvent(t)),this.notifyError),this._highRotationsProviderId=it.addEventListener(null,this.notifyError)}))}_parseEvent(e){const i=e.clone();if(it.isInProgress()){let e=(i.accuracy||0)+100*t.DEFAULT_DRIFT;e=Math.min(e,Math.PI),i.accuracy=e}this.notify(i)}stop(){this.provider&&(this.provider.removeEventListener(this.listenerId),delete this.provider),it.removeEventListener(this._highRotationsProviderId)}};e(st,"DEFAULT_DRIFT",s.deg2rad(5)/60);const rt=new st,nt=class t{constructor(){e(this,"frequency",0),e(this,"lastVerticalAcc",0),e(this,"maxAcceleration",0),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS)}compute(e,i){let s=!1;const r=i[2],n=e-this.lastStepTimestamp;if(r>this.lastVerticalAcc)r>this.maxAcceleration&&(this.maxAcceleration=r);else if(this.maxAcceleration>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&n>t.MIN_TIME_BETWEEN_STEPS){this.maxAcceleration=0;const i=e-this.lastStepTimestamp;this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),s=!0,this.lastStepTimestamp=e}else this.maxAcceleration=0;return this.lastVerticalAcc=r,s}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepTimestamp?this.lastStepSize*this.frequency:0}};e(nt,"MIN_TIME_BETWEEN_STEPS",.4),e(nt,"MAX_FRENQUENCY",4),e(nt,"MIN_FRENQUENCY",1),e(nt,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",1);let ot=nt;const at=class t{constructor(){e(this,"frequency",0),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"slidingWindow",[])}compute(e,i){if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let s=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER;const n=t.WINDOW_TIME;if(this.slidingWindow.forEach(((t,i,o)=>{t.timestamp<e-n?o.splice(i,1):(s=Math.max(t.verticalAcc,s),r=Math.min(t.verticalAcc,r))})),this.slidingWindow.push({timestamp:e,verticalAcc:i[2]}),s>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&r<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){const i=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}return!1}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepTimestamp?this.lastStepSize*this.frequency:0}};e(at,"WINDOW_TIME",.3),e(at,"MIN_TIME_BETWEEN_STEPS",.4),e(at,"MAX_FRENQUENCY",4),e(at,"MIN_FRENQUENCY",1),e(at,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",1.5),e(at,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-1);let lt=at;const ht=class t{constructor(){e(this,"frequency",0),e(this,"influence",.2),e(this,"slidingWindow",[]),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"previousVerticalAcc",0)}compute(e,i,s){const r=this.influence*(2*i[2])+(1-this.influence)*this.previousVerticalAcc;if(this.previousVerticalAcc=r,Math.sqrt(s[0]**2+s[1]**2+s[2]**2)>.75)return!1;if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let n=Number.MIN_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER;if(this.slidingWindow.forEach(((i,s,r)=>{i.timestamp<e-t.WINDOW_TIME?r.splice(s,1):(n=Math.max(i.verticalAcc,n),o=Math.min(i.verticalAcc,o))})),this.slidingWindow.push({timestamp:e,verticalAcc:r}),n>t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&o<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){const i=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/i,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}return!1}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepSize&&this.frequency?this.lastStepSize*this.frequency:0}mean(t){let e=0,i=0;for(let s=0;s<t.length;++s)e+=t[s].verticalAcc;return i=e/t.length,i}stddev(t){const e=this.mean(t);let i=0;for(let s=0;s<t.length;++s)i+=(t[s].verticalAcc-e)**2;return Math.sqrt(i/t.length)}};e(ht,"WINDOW_TIME",.3),e(ht,"MIN_TIME_BETWEEN_STEPS",.4),e(ht,"MAX_FRENQUENCY",4),e(ht,"MIN_FRENQUENCY",1),e(ht,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",.75),e(ht,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-.3);let ct=ht;const dt=class t{constructor(){e(this,"frequency",0),e(this,"influence",.05),e(this,"slidingWindow",[]),e(this,"lastStepTimestamp",-t.MIN_TIME_BETWEEN_STEPS),e(this,"previousVerticalAcc",0),e(this,"previousHorizontalAcc",0)}compute(e,i){const s=this.influence*i[2]+(1-this.influence)*this.previousVerticalAcc;this.previousVerticalAcc=s,this.slidingWindow=this.slidingWindow.filter((i=>i.timestamp>=e-t.WINDOW_TIME)),this.slidingWindow.push({timestamp:e,verticalAcc:s});if(this.lastStepTimestamp&&this.lastStepTimestamp+t.MIN_TIME_BETWEEN_STEPS>e)return!1;let r=Number.MIN_VALUE,n=-1,o=!1;if(this.slidingWindow.forEach(((e,i)=>{e.verticalAcc>r&&e.verticalAcc>=t.VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD&&(r=e.verticalAcc,n=i,o=!0)})),!o)return!1;let a=!1,l=Number.MAX_VALUE;for(let u=0;u<n;u++){const e=this.slidingWindow[u].verticalAcc;if(l=Math.min(l,e),e<t.VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD){a=!0;break}}if(!a)return!1;const h=r-.5*(r-l);let c=!1;for(let t=n+1;t<this.slidingWindow.length;t++)if(this.slidingWindow[t].verticalAcc<=h){c=!0;break}if(!c)return!1;const d=this.lastStepTimestamp?e-this.lastStepTimestamp:1;return this.frequency=Math.min(Math.max(1/d,t.MIN_FRENQUENCY),t.MAX_FRENQUENCY),this.lastStepTimestamp=e,!0}get lastStepSize(){if(!this.frequency)return 0;return.45+.2*this.frequency}get speed(){return this.lastStepSize&&this.frequency?this.lastStepSize*this.frequency:0}mean(t){let e=0,i=0;for(let s=0;s<t.length;++s)e+=t[s];return i=e/t.length,i}stddev(t){const e=this.mean(t);let i=0;for(let s=0;s<t.length;++s)i+=(t[s]-e)**2;return Math.sqrt(i/t.length)}};e(dt,"WINDOW_TIME",.6),e(dt,"MIN_TIME_BETWEEN_STEPS",.6),e(dt,"MAX_FRENQUENCY",4),e(dt,"MIN_FRENQUENCY",1),e(dt,"VERTICAL_ACC_POSITIVE_PEAK_THRESHOLD",.2),e(dt,"VERTICAL_ACC_NEGATIVE_PEAK_THRESHOLD",-.1);let ut=dt;const vt=class t extends A{constructor(){super(),e(this,"accelerometerProviderId"),e(this,"attitudeProviderId"),e(this,"gyroscopeProviderId"),e(this,"angularRateEvent"),e(this,"attitudeEvent"),e(this,"numOfSteps",0),e(this,"stepDetector"),e(this,"_stepSizeMultiplier",t.DEFAULT_STEP_SIZE_MULTIPLIER),e(this,"_algorithm",t.DEFAULT_ALGORITHM),e(this,"_accValues",[]),e(this,"getName",(()=>"StepDetector")),e(this,"onAccelerometerEvent",(e=>{if(!this.attitudeEvent||!this.angularRateEvent)return;const{values:i,timestamp:s}=e,r=t.computeLinearAcceleration(this.attitudeEvent.quaternion,i);if(this.stepDetector.compute(s,r,this.angularRateEvent.values)){const t=this.stepDetector.lastStepSize*this._stepSizeMultiplier;this.numOfSteps++,this.notify({size:t,number:this.numOfSteps})}})),this.algorithm=this._algorithm}availability(){return I.every([J.getAvailability(),X.getAvailability(),rt.getAvailability()])}start(){this.numOfSteps=0,this.accelerometerProviderId=J.addEventListener(this.onAccelerometerEvent,this.notifyError),this.gyroscopeProviderId=X.addEventListener((t=>this.angularRateEvent=t),this.notifyError),this.attitudeProviderId=rt.addEventListener((t=>this.attitudeEvent=t),this.notifyError)}stop(){J.removeEventListener(this.accelerometerProviderId),X.removeEventListener(this.gyroscopeProviderId),rt.removeEventListener(this.attitudeProviderId)}static computeLinearAcceleration(t,e){const r=s.Quaternion.rotateMatlab(s.Quaternion.inverse(t),e);return r[2]-=i.Constants.EARTH_GRAVITY,r}set stepSizeMultiplier(t){this._stepSizeMultiplier=t}get stepSizeMultiplier(){return this._stepSizeMultiplier}set algorithm(t){switch(t){case"ladetto":this.stepDetector=new ot;break;case"minMaxPeaks":this.stepDetector=new lt;break;case"minMaxPeaks2":this.stepDetector=new ct;break;default:t="minMaxPeaks3",this.stepDetector=new ut}this._algorithm=t}get algorithm(){return this._algorithm}};e(vt,"DEFAULT_STEP_SIZE_MULTIPLIER",1),e(vt,"DEFAULT_ALGORITHM","minMaxPeaks3");const Et=new vt;const _t=new class extends A{constructor(){super(...arguments),e(this,"absoluteAttitudeProviderId"),e(this,"stepDetectionProviderId"),e(this,"attitudeEvent"),e(this,"misalignmentError",s.deg2rad(3)),e(this,"getName",(()=>"Pdr")),e(this,"onStepEvent",(t=>{if(!this.attitudeEvent)return;const e=t.size,s=this.attitudeEvent,r=s.heading,n=s.accuracy+this.misalignmentError,o=e/2*Math.sin(n/2),a=s.time,l=new i.GeoRelativePosition(e*Math.sin(r),e*Math.cos(r),0,a,o,r);this.notify(l)}))}availability(){return I.every([Et.getAvailability(),Ut.getAvailability()])}start(){this.stepDetectionProviderId=Et.addEventListener(this.onStepEvent,this.notifyError),this.absoluteAttitudeProviderId=Ut.addEventListener((t=>this.attitudeEvent=t),this.notifyError)}stop(){Et.removeEventListener(this.stepDetectionProviderId),Ut.removeEventListener(this.absoluteAttitudeProviderId)}};const mt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"geoRelativeProvider"),e(this,"getName",(()=>"GeoRelativePosition"))}availability(){return I.some([_t.getAvailability(),V.getAvailability()])}async start(){const t=await V.getAvailability();this.geoRelativeProvider=t?_t:V,this.providerId=this.geoRelativeProvider.addEventListener(this.notify,this.notifyError)}stop(){var t;null==(t=this.geoRelativeProvider)||t.removeEventListener(this.providerId),delete this.geoRelativeProvider}},pt="13.2.3";const gt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"InclinationFromAcc")),e(this,"availability",(()=>J.getAvailability())),e(this,"onAccelerometerEvent",(t=>{const e=t.values,i=window.orientation||0,s=Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]),r=[e[0]/s,e[1]/s,e[2]/s],n=[r[2]+1,r[1],-r[0],0],o=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),a=[n[0]/o,n[1]/o,n[2]/o,0];let l;l=0===i?Math.asin(2*a[1]*a[0]):90===i?-Math.asin(2*a[2]*a[0]):-90===i?Math.asin(2*a[2]*a[0]):-Math.asin(2*a[1]*a[0]),this.notify(l)}))}start(){this.providerId=J.addEventListener(this.onAccelerometerEvent,this.notifyError)}stop(){J.removeEventListener(this.providerId)}};const At=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"InclinationFromRelativeAttitude")),e(this,"availability",(()=>rt.getAvailability()))}start(){this.providerId=rt.addEventListener((t=>{const e=this.enuQuatToInclination(t.quaternion);this.notify(e)}),this.notifyError)}stop(){rt.removeEventListener(this.providerId)}enuQuatToInclination(t){const e=window.orientation||0;return 0===e?Math.asin(2*(t[2]*t[3]+t[1]*t[0])):90===e?Math.asin(2*(t[1]*t[3]-t[2]*t[0])):-90===e?Math.asin(2*(t[2]*t[0]-t[1]*t[3])):-Math.asin(2*(t[2]*t[3]+t[1]*t[0]))}};const It=new class extends A{constructor(){super(...arguments),e(this,"provider"),e(this,"providerId"),e(this,"getName",(()=>"Inclination"))}availability(){return I.some([gt.getAvailability(),At.getAvailability()])}async start(){const t=()=>{this.provider=gt,this.providerId=this.provider.addEventListener(this.notify,this.notifyError)};await At.getAvailability()?(this.provider=At,this.providerId=this.provider.addEventListener(this.notify,(()=>{At.removeEventListener(this.providerId),t()}))):t()}stop(){this.provider&&this.provider.removeEventListener(this.providerId)}};class ft{constructor(t,e=null,i=null,s=null){this.size=t,this.calibration=e,this.coarse=i,this.device=s}toJson(){return{size:[this.size.width,this.size.height],...this.calibration&&{calibration:this.calibration},...this.coarse&&{coarse:{...this.coarse.attitude&&{attitude:this.coarse.attitude.toJson()},...this.coarse.position&&{position:this.coarse.position.toJson()}}},..."object"==typeof this.device&&{device:this.device}}}static fromJson(t){var e,s;return new ft({width:t.size[0],height:t.size[1]},t.calibration,{...(null==(e=t.coarse)?void 0:e.position)&&{position:i.UserPosition.fromJson(t.coarse.position)},...(null==(s=t.coarse)?void 0:s.attitude)&&{attitude:i.Attitude.fromJson(t.coarse.attitude)}},t.device)}}class Pt{constructor(t,e){this.metadata=t,this.image=e}toJson(){return{image:l.canvasToBase64(this.image),...this.metadata.toJson()}}static fromJson(t){return new Pt(ft.fromJson(t),l.base64ToCanvas(t.image))}}class Tt{constructor(t,e=null,i=null){this.success=t,this.attitude=e,this.position=i}toJson(){var t,e;return{success:this.success,attitude:null==(t=this.attitude)?void 0:t.toJson(),position:null==(e=this.position)?void 0:e.toJson()}}static fromJson(t,e=null){let s=null;t.attitude&&(s=i.Attitude.fromJson(t.attitude),s.time=e);let r=null;return t.position&&(r=i.UserPosition.fromJson(t.position),r.time=e),new Tt(t.success,s,r)}}class St{static _prepareRequest(t,e=null,i=null,s=null){l.convertToGrayscale(t);const r=l.reduceImageSize(t,1280),o=n.UserAgentUtils.getDeviceFromUserAgent()||{};o.caller=s;const a=new ft({width:r.width,height:r.height},e,i,o);return new Pt(a,r)}static async relocalize(t,e,i=null,s=null,r=null,a=null){const l=n.TimeUtils.preciseTime()/1e3,h=this._prepareRequest(e,i,s,r);let c;try{const e=JSON.stringify(h.toJson());o.debug(`[VPS] Request (${(e.length/1024).toFixed(0)} kB) sent to server ${t}`),c=await fetch(t,{method:"POST",body:e,headers:Object.assign({"Content-Type":"application/json",Accept:"application/vnd.geopose+json; version=1"},a||{})})}catch(v){return o.debug("[VPS] Server respond error"),null}if(200!==c.status)return o.debug("[VPS] Server respond error"),null;const d=await c.json(),u=Tt.fromJson(d,l);return o.debug("[VPS] Server respond "+(u.success?"success":"not found")),u}static getHeadingFromQuaternion(t){const[e,i,s,r]=t,n=Math.sqrt(2)/2,o=[n*(e-i),n*(e+i),n*(s+r),n*(r-s)];return-Math.atan2(2*o[3]*o[0]-2*o[2]*o[1],1-2*o[1]**2-2*o[3]**2)}}class yt{constructor(){e(this,"_providerId"),e(this,"_isRunning",!1),e(this,"_dataOnStart",null)}tickStart(){this._dataOnStart=null,this._isRunning||(this._isRunning=!0,this._providerId=tt.addEventListener((t=>{this._dataOnStart||(this._dataOnStart=t)})))}tickEnd(){if(!this._isRunning)return o.warn("You have to call tickStart before tickEnd"),null;if(this._internalStop(),!this._dataOnStart)return o.warn("Delay was too short between tickStart and tickEnd or RelativeAttitudeProvider cannot be retrieved."),null;const t=tt.lastEvent;return i.Attitude.diff(this._dataOnStart,t)}_internalStop(){tt.removeEventListener(this._providerId),delete this._providerId,this._isRunning=!1}release(){this._isRunning&&this._internalStop()}}const Mt=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(Mt,"DEFAULT_MESSAGE","PoleStar is missing");let bt=Mt;const Lt=new class extends A{constructor(){super(),e(this,"getName",(()=>"PoleStar")),this.addMethodsToNativeJsProvider()}availability(){try{return this.nativeProvider.checkAvailability(),Promise.resolve()}catch(t){return Promise.resolve(t)}}setApiKey(t){this.nativeProvider.setApiKey(t)}start(){this.nativeProvider.start()}stop(){this.nativeProvider.stop()}get nativeProvider(){if(!this.nativeInterface)throw new H;const t=this.nativeInterface.getPoleStarProvider();if(!t)throw new bt;return t}addMethodsToNativeJsProvider(){this.nativeJsInterface&&(this.nativeJsInterface.polestar={callbackError:t=>this.notifyError(new Error(t)),callbackPosition:t=>{const e=JSON.parse(t),i=n.TimeUtils.unixTimestampToPreciseTime(e.time)/1e3,r=new v(e.lat,e.lng,D.DEFAULT_ALTITUDE,e.alt/5,i,e.accuracy,s.deg2rad(e.bearing));this.notify(r)}})}},Rt=class t extends A{constructor(){super(...arguments),e(this,"_relativeRotationCalc"),e(this,"_serverError",!1),e(this,"_cameraError",!1),e(this,"_camera",null),e(this,"_endpoint",null),e(this,"_inclinationProviderId"),e(this,"_minInclinationForRequest",t.DEFAULT_MIN_INCLINATION_FOR_REQUEST),e(this,"_waitTimeMinInclinationForRequest",t.DEFAULT_WAIT_TIME_MIN_INCLINATION_FOR_REQUEST),e(this,"_useCoarsePose",t.DEFAULT_USE_COARSE_POSE),e(this,"_requestCaller",t.DEFAULT_REQUEST_CALLER),e(this,"getName",(()=>"Vps")),e(this,"availability",(()=>l.Camera.checkAvailability())),e(this,"_onCameraDetected",(({camera:t})=>{this._camera&&o.warn("It seems that more than 1 camera has been detected for VPS. Taking the first..."),this._useCamera(t)})),e(this,"_onCameraRemoved",(()=>{this._camera?(this._camera.off("started",this._internalStart),this._camera.off("stopped",this._internalStop)):o.warn("There is no previously detected camera but once has stopped"),this._camera=null})),e(this,"_internalStart",(async()=>{var e,r;if(!this._endpoint)return void this.notifyError(new Error("VPS endpoint has not been set before calling start()"));let o=null;const a=()=>"stopped"===this.state;for(;!a();){if(null!==o){const e=n.TimeUtils.preciseTime()-o,i=Math.max(0,t.MIN_TIME_BETWEEN_TWO_REQUESTS-e);await new Promise((t=>setTimeout(t,i)))}if(o=n.TimeUtils.preciseTime(),a()||!this._camera||"started"!==this._camera.state)break;const l=It.lastEvent?It.lastEvent:null;if(null!==l&&l<this._minInclinationForRequest){await new Promise((t=>setTimeout(t,this._waitTimeMinInclinationForRequest)));continue}null==(e=this._relativeRotationCalc)||e.tickStart();const h=await this._camera.currentImage;if(!h)continue;let c=null;const d=Dt.getBestPositionEvent(F.lastEvent,Lt.lastEvent);this._useCoarsePose&&(d||Ut.lastEvent)&&(c={...d&&{position:d},...Ut.lastEvent&&{attitude:Ut.lastEvent}});const v=await St.relocalize(this._endpoint,h,null,c,this._requestCaller);if(!v||!v.success)continue;const E=v.attitude.quaternion,_=s.Quaternion.multiply(E,t.CAMERA_TO_SMARTPHONE_ROT),m=s.Quaternion.multiply(s.Quaternion.fromAxisAngle([0,0,1],s.deg2rad(window.orientation||0)),_),p=(null==(r=this._relativeRotationCalc)?void 0:r.tickEnd())||new i.Attitude([1,0,0,0]),g=s.Quaternion.multiply(m,p.quaternion),A=new u(g,v.attitude.time,v.attitude.accuracy),I=v.position.clone();if(null===I.accuracy&&(I.accuracy=5),a())break;this.notify({absoluteAttitude:A,absolutePosition:I})}})),e(this,"_internalStop",(()=>{}))}start(){this._inclinationProviderId=It.addEventListener(),this._relativeRotationCalc=new yt,l.SharedCameras.on("added",this._onCameraDetected),l.SharedCameras.on("removed",this._onCameraRemoved),l.SharedCameras.list.length&&(l.SharedCameras.list.length>1&&o.warn("It seems that more than 1 camera has been detected for VPS. Taking the first..."),this._useCamera(l.SharedCameras.list[0].camera))}stop(){var t;It.removeEventListener(this._inclinationProviderId),null==(t=this._relativeRotationCalc)||t.release(),l.SharedCameras.off("added",this._onCameraDetected),l.SharedCameras.off("removed",this._onCameraRemoved),this._camera=null}_useCamera(t){this._camera=t,t.on("started",this._internalStart),t.on("stopped",this._internalStop),"started"===t.state&&this._internalStart()}get endpoint(){return this._endpoint}set endpoint(t){this._endpoint=t}get minInclinationForRequest(){return this._minInclinationForRequest}set minInclinationForRequest(t){this._minInclinationForRequest=t}get waitTimeMinInclinationForRequest(){return this._waitTimeMinInclinationForRequest}set waitTimeMinInclinationForRequest(t){this._waitTimeMinInclinationForRequest=t}get useCoarsePose(){return this._useCoarsePose}set useCoarsePose(t){this._useCoarsePose=t}get requestCaller(){return this._requestCaller}set requestCaller(t){this._requestCaller=t}};e(Rt,"MIN_TIME_BETWEEN_TWO_REQUESTS",1e3),e(Rt,"DEFAULT_MIN_INCLINATION_FOR_REQUEST",s.deg2rad(60)),e(Rt,"DEFAULT_WAIT_TIME_MIN_INCLINATION_FOR_REQUEST",200),e(Rt,"DEFAULT_USE_COARSE_POSE",!0),e(Rt,"DEFAULT_REQUEST_CALLER",`@wemap/providers(VpsProvider) ${pt}`),e(Rt,"CAMERA_TO_SMARTPHONE_ROT",s.Quaternion.fromAxisAngle([1,0,0],Math.PI));const wt=new Rt,Nt=class t extends A{constructor(){super(...arguments),e(this,"_polestarProviderId"),e(this,"_vpsProviderId"),e(this,"_gnssWifiProviderId"),e(this,"_relativePositionProviderId"),e(this,"_mapMatchingHandlerId"),e(this,"useAllAbsolutePositions",!1),e(this,"_waitUntilNextVpsPosition",!1),e(this,"_lastPolestarFix",null),e(this,"getName",(()=>"AbsolutePosition"))}availability(){return I.some([mt.getAvailability(),F.getAvailability(),...E.hasPoleStar?[Lt.getAvailability()]:[],wt.getAvailability()])}start(){mt.getAvailability().then((t=>{t||(this._relativePositionProviderId=mt.addEventListener((t=>this._onRelativePosition(t))))})),this._gnssWifiProviderId=F.addEventListener((t=>{const e=t.clone();e.bearing=null,this._onAbsolutePosition(e,!1)})),this._vpsProviderId=wt.addEventListener((t=>this._onAbsolutePosition(t.absolutePosition)),this.notifyError,!1),E.hasPoleStar&&(this._polestarProviderId=Lt.addEventListener((t=>{var e;this._lastPolestarFix=n.TimeUtils.preciseTime();if(!this._onAbsolutePosition(t)&&null===(null==(e=this.lastEvent)?void 0:e.level)){const e=this.lastEvent.clone();e.level=t.level,this.notify(e)}}))),this._mapMatchingHandlerId=qt.addEventListener()}stop(){this._relativePositionProviderId&&(mt.removeEventListener(this._relativePositionProviderId),delete this._relativePositionProviderId),this._gnssWifiProviderId&&(F.removeEventListener(this._gnssWifiProviderId),delete this._gnssWifiProviderId),this._vpsProviderId&&(wt.removeEventListener(this._vpsProviderId),delete this._vpsProviderId),this._polestarProviderId&&(Lt.removeEventListener(this._polestarProviderId),delete this._polestarProviderId),qt.removeEventListener(this._mapMatchingHandlerId)}_shouldTakeIntoAccountNewAbsolutePosition(e,s=!0){const r=e,n=this.lastEvent||null;if(!n)return!0;const o=r.accuracy*t.ACCURACY_RELOC_RATIO<=n.accuracy;if(o)return!0;const a=n.distanceTo(r)>n.accuracy+r.accuracy;if(a)return!0;const l=a&&r.accuracy<=n.accuracy;if(o&&l)return!0;return!(!s||i.Level.equals(r.level,n.level))}_onAbsolutePosition(t,e=!0){if(!this._shouldTakeIntoAccountNewAbsolutePosition(t,e)&&!this.useAllAbsolutePositions)return!1;const i=t.clone(),s=this.lastEvent?this.lastEvent:null;return s&&(e||(i.level=s.level),null===i.bearing&&(i.bearing=s.bearing)),qt.canUseMapMatching()?qt.notifyPositionFromAbsolute(i):(this.notify(i),!0)}_onRelativePosition(t){if(!this.lastEvent||this._waitUntilNextVpsPosition)return!1;const e=this.lastEvent,i=t,s=Math.sqrt(i.x**2+i.y**2),r=Math.atan2(i.x,i.y),n=null!==e.alt?i.z:null,o=e.destinationPoint(s,r,n);return o.bearing=i.bearing,o.time=i.time,o.accuracy+=i.accuracy,qt.canUseMapMatching()?qt.notifyPositionFromRelative(o):(this.notify(o),!0)}feed(e){let s;if(!(e instanceof i.UserPosition))throw new Error("data is nor an UserPosition or an AbsolutePositionEvent");if(null===e.time)throw Error("the time of the position is not defined");if(null===e.accuracy)throw Error("the accuracy of the position is not defined");s=e,t.USE_MM_FOR_FEED&&qt.canUseMapMatching()?qt.notifyPositionFromFeed(s):this.notify(s)}getBestPositionEvent(...t){return t.reduce(((t,e)=>{if(!t)return e;if(!e||null===e.accuracy||null===e.time)return t;const{accuracy:i,time:s}=e,{accuracy:r,time:n}=t;return i<r+1.3888*(s-n)?e:t}),null)}};e(Nt,"ACCURACY_RELOC_RATIO",1),e(Nt,"USE_MM_FOR_FEED",!0);const Dt=new Nt;class Ct extends A{constructor(){super(...arguments),e(this,"DEFAULT_ACCURACY",s.deg2rad(15)),e(this,"absolutePositionProviderId"),e(this,"absolutePositionEvent"),e(this,"declinationQuaternion"),e(this,"magQuaternion"),e(this,"magQuaternionTimestamp"),e(this,"iosPreviousQuat"),e(this,"iosIsSkyMode",null),e(this,"getName",(()=>"AbsoluteAttitudeFromBrowser")),e(this,"onDeviceOrientationChromeEvent",(t=>{this.magQuaternionTimestamp=t.timeStamp/1e3,"number"==typeof t.alpha&&"number"==typeof t.beta&&"number"==typeof t.gamma?(this.magQuaternion=s.Rotations.eulerToQuaternionZXYDegrees([t.alpha,t.beta,t.gamma]),this.compute()):this.notifyError((new S).from("deviceorientationabsolute"))})),e(this,"onDeviceOrientationSafariEvent",(t=>{if(this.magQuaternionTimestamp=t.timeStamp/1e3,"number"!=typeof t.beta||"number"!=typeof t.gamma)return void this.notifyError((new S).from("deviceorientation"));if("number"!=typeof t.webkitCompassHeading)return void this.notifyError((new y).from("deviceorientation"));let e;const[i,r,n,o]=s.Rotations.eulerToQuaternionZXYDegrees([t.webkitCompassHeading,t.beta,t.gamma]),a=s.rad2deg(Math.acos(i**2-r**2-n**2+o**2));let l=null;a>136?l=!0:a<134?l=!1:this.iosPreviousQuat&&null!==this.iosIsSkyMode&&(l=s.Quaternion.distance([i,r,n,o],this.iosPreviousQuat)<.5?this.iosIsSkyMode:!this.iosIsSkyMode),this.iosPreviousQuat=[i,r,n,o],this.iosIsSkyMode=l,void 0!==l&&(e=l?180-t.webkitCompassHeading:Ct.webkitCompassToHeading(t.webkitCompassHeading,t.beta,t.gamma),this.magQuaternion=s.Rotations.eulerToQuaternionZXYDegrees([e,t.beta,t.gamma]),this.compute())})),e(this,"onAbsolutePositionEvent",(t=>{this.absolutePositionEvent=t;const e=c.field(t.lat,t.lng);this.declinationQuaternion=s.Quaternion.fromAxisAngle([0,0,1],-s.deg2rad(e.declination)),Dt.removeEventListener(this.absolutePositionProviderId),delete this.absolutePositionProviderId,this.compute()}))}availability(){return n.BrowserUtils.isMobile?Promise.resolve():Promise.resolve(new P)}start(){const t=()=>{switch(n.BrowserUtils.getName()){case n.Browser.CHROME:window.addEventListener("deviceorientationabsolute",this.onDeviceOrientationChromeEvent,!0);break;case n.Browser.SAFARI:case n.Browser.IOS_WEBVIEW:window.addEventListener("deviceorientation",this.onDeviceOrientationSafariEvent,!0)}},e=DeviceOrientationEvent.requestPermission||void 0;e?e().then((e=>{if("granted"!==e)throw new Error("Permission not granted");t()})).catch(this.notifyError):t();const i=Dt.lastEvent;i?this.onAbsolutePositionEvent(i):this.absolutePositionProviderId=Dt.addEventListener(this.onAbsolutePositionEvent,this.notifyError,!1)}stop(){switch(n.BrowserUtils.getName()){case n.Browser.CHROME:window.removeEventListener("deviceorientationabsolute",this.onDeviceOrientationChromeEvent,!0);break;case n.Browser.SAFARI:case n.Browser.IOS_WEBVIEW:window.removeEventListener("deviceorientation",this.onDeviceOrientationSafariEvent,!0)}Dt.removeEventListener(this.absolutePositionProviderId)}compute(){if(!this.declinationQuaternion||!this.magQuaternion||!this.absolutePositionEvent)return;const t=s.Quaternion.multiply(this.declinationQuaternion,this.magQuaternion),e=new u(t,this.magQuaternionTimestamp,this.DEFAULT_ACCURACY);this.notify(e)}static webkitCompassToHeading(t,e,i){const r=s.deg2rad(t),n=s.deg2rad(e),o=s.deg2rad(i),a=Math.cos(r/2),l=Math.cos(n/2),h=Math.cos(o/2),c=Math.sin(r/2),d=Math.sin(n/2),u=Math.sin(o/2),v=a*l*h-c*d*u,E=c*l*h+a*d*u;return s.rad2deg(-2*Math.atan(E/v))}}const Ft=new Ct;const Ot=new class extends A{constructor(){super(...arguments),e(this,"arCoreMonitoringId"),e(this,"arCoreProviderId"),e(this,"inertialProviderId"),e(this,"getName",(()=>"RelativeAttitude")),e(this,"availability",(()=>rt.getAvailability())),e(this,"listenInertial",(()=>{this.inertialProviderId=rt.addEventListener(this.notify,this.notifyError)})),e(this,"unlistenInertial",(()=>{rt.removeEventListener(this.inertialProviderId)})),e(this,"listenArCore",(()=>{this.arCoreProviderId=W.addEventListener((t=>this.notify(t.relativeAttitude)),null,!1)})),e(this,"unlistenArCore",(()=>{W.removeEventListener(this.arCoreProviderId)}))}start(){this.arCoreMonitoringId=W.addMonitoringListener((()=>{this.listenArCore(),this.unlistenInertial()}),(()=>{this.unlistenArCore(),this.listenInertial()})),"started"===W.state?this.listenArCore():this.listenInertial()}stop(){W.removeMonitoringListener(this.arCoreMonitoringId),this.unlistenArCore(),this.unlistenInertial()}},xt=class t extends A{constructor(){super(...arguments),e(this,"_absAttitudeFromBrowser"),e(this,"_vpsProviderId"),e(this,"fromBrowserProviderId"),e(this,"highRotationProviderId"),e(this,"inclinationProviderId"),e(this,"relativeAttitudeProviderId"),e(this,"_attitudeFromBrowserErrored",!1),e(this,"_attitudeFromRelativeErrored",!1),e(this,"_relativeAttitude",null),e(this,"_relativeAccuracy",0),e(this,"_lastForcedHeadingEvent"),e(this,"_relAbsQuat"),e(this,"_wasHighRotationInProgress",!1),e(this,"_timeFirstDivergence",null),e(this,"_callbackMagCalibration"),e(this,"getName",(()=>"AbsoluteAttitude")),e(this,"_onError",(t=>{this._attitudeFromBrowserErrored&&this._attitudeFromRelativeErrored&&this.notifyError(t)})),e(this,"_forceHeadingForRelative",(t=>{if(this.lastEvent&&t.accuracy>this.lastEvent.accuracy)return;const e=e=>{const i=e.heading;this._relAbsQuat=s.Quaternion.fromAxisAngle([0,0,1],i-t.heading),this._relativeAccuracy=0,this._lastForcedHeadingEvent=t};if(this._relativeAttitude)return void e(this._relativeAttitude);const i=Ot.addEventListener((t=>{e(t),Ot.removeEventListener(i)}))})),e(this,"_onRelativeAttitudeEvent",(e=>{var r;const{quaternion:n,accuracy:o,time:a}=e;if(this._relativeAttitude&&(this._relativeAccuracy+=(a-this._relativeAttitude.time)*o),this._relativeAttitude=e,!this._lastForcedHeadingEvent||!this._relAbsQuat)return;const l=Math.min((this._lastForcedHeadingEvent.accuracy||0)+this._relativeAccuracy,Math.PI),h=it.isInProgress();let c=!1;if(this._absAttitudeFromBrowser){const{accuracy:e,heading:o}=this._absAttitudeFromBrowser;if(this._wasHighRotationInProgress&&!h)this._forceHeadingForRelative(this._absAttitudeFromBrowser);else if(e<l){const e=s.Quaternion.multiply(this._relAbsQuat,n),l=new i.Attitude(e),h=Math.abs(s.diffAngle(l.heading,o)),d=It.lastEvent;h>t.REL_ABS_DIVERGENCE_ANGLE_THRESHOLD&&null!==d&&Math.abs(d-Math.PI/4)>t.REL_ABS_DIVERGENCE_INCLINATION_THRESHOLD&&(c=!0,null!==this._timeFirstDivergence&&a-this._timeFirstDivergence>t.REL_ABS_DIVERGENCE_TIME_THRESHOLD?(this._forceHeadingForRelative(this._absAttitudeFromBrowser),null==(r=this._callbackMagCalibration)||r.call(this,{angle:h}),this._timeFirstDivergence=null):null===this._timeFirstDivergence&&(this._timeFirstDivergence=a))}}c||(this._timeFirstDivergence=null),this._wasHighRotationInProgress=h;const d=s.Quaternion.multiply(this._relAbsQuat,n),v=new u(d,a,l);this.notify(v)})),e(this,"_onAttitudeFromBrowser",(t=>{this._absAttitudeFromBrowser=t,this._lastForcedHeadingEvent||this._forceHeadingForRelative(t)})),e(this,"_onAttitudeFromVps",(t=>{this._forceHeadingForRelative(t)}))}availability(){return I.some([Ft.getAvailability(),Ot.getAvailability()])}start(){this.fromBrowserProviderId=Ft.addEventListener(this._onAttitudeFromBrowser,(t=>{this._attitudeFromBrowserErrored=!0,this._onError(t)})),this._vpsProviderId=wt.addEventListener((t=>this._onAttitudeFromVps(t.absoluteAttitude)),(t=>this.notifyError(t)),!1),this.relativeAttitudeProviderId=Ot.addEventListener(this._onRelativeAttitudeEvent,(t=>{this._attitudeFromRelativeErrored=!0,this._onError(t)})),this.inclinationProviderId=It.addEventListener(),this.highRotationProviderId=it.addEventListener()}stop(){Ft.removeEventListener(this.fromBrowserProviderId),Ot.removeEventListener(this.relativeAttitudeProviderId),It.removeEventListener(this.inclinationProviderId),it.removeEventListener(this.highRotationProviderId),wt.removeEventListener(this._vpsProviderId)}_setCallbackMagCalibration(t){this._callbackMagCalibration=t}feed(t){if(t instanceof i.AbsoluteHeading){if(null===t.time)throw Error("the time of the absolute heading is not defined");if(null===t.accuracy)throw Error("the accuracy of the absolute heading is not defined");this._forceHeadingForRelative(t)}else{if(!(t instanceof u))throw new Error("data is nor an AbsoluteHeading or an Attitude object");if(null===t.time)throw Error("the time of the attitude is not defined");if(null===t.accuracy)throw Error("the accuracy of the attitude is not defined");this._forceHeadingForRelative(t)}}};e(xt,"REL_ABS_DIVERGENCE_ANGLE_THRESHOLD",s.deg2rad(25)),e(xt,"REL_ABS_DIVERGENCE_TIME_THRESHOLD",2.5),e(xt,"REL_ABS_DIVERGENCE_INCLINATION_THRESHOLD",s.deg2rad(15));const Ut=new xt,Ht=class t extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"slidingWindow",[]),e(this,"getName",(()=>"Turn")),e(this,"availability",(()=>Ot.getAvailability())),e(this,"_parseRelativeAttitude",(e=>{const{heading:i}=e,r=e.time;this.slidingWindow=this.slidingWindow.filter((e=>e[0]>=r-t.SLIDING_WINDOW_TIME)),this.slidingWindow.push([r,i]);s.std(this.slidingWindow.map((t=>t[1])))>t.STD_THRESHOLD&&this.notify({timestamp:r})}))}start(){this.providerId=Ot.addEventListener(this._parseRelativeAttitude,this.notifyError)}stop(){Ot.removeEventListener(this.providerId)}isTurning(){if(!this.lastEvent||!Ot.lastEvent)return!1;return Ot.lastEvent.time-this.lastEvent.timestamp<t.CONSIDER_TURN_UNTIL}};e(Ht,"SLIDING_WINDOW_TIME",.3),e(Ht,"STD_THRESHOLD",.075),e(Ht,"CONSIDER_TURN_UNTIL",1);const Bt=new Ht,Wt=class t extends A{constructor(){super(...arguments),e(this,"_turnProviderId"),e(this,"_stepProviderId"),e(this,"_countSteps",0),e(this,"_stepsConsideredForStraightLine",t.DEFAULT_STEPS_CONSIDERED_FOR_STRAIGHT_LINE),e(this,"getName",(()=>"StraightLine")),e(this,"_onTurn",(()=>{this._countSteps>=this._stepsConsideredForStraightLine&&this.notify(!1),this._countSteps=0})),e(this,"_onStep",(()=>{this._countSteps++,this._countSteps===this._stepsConsideredForStraightLine&&this.notify(!0)}))}availability(){return I.every([Bt.getAvailability(),Et.getAvailability()])}start(){this._turnProviderId=Bt.addEventListener(this._onTurn),this._stepProviderId=Et.addEventListener(this._onStep)}stop(){Bt.removeEventListener(this._turnProviderId),Et.removeEventListener(this._stepProviderId)}isStraight(){return this._countSteps>=this._stepsConsideredForStraightLine}get numStepsDetectedFromLastTurn(){return this._countSteps}get stepsConsideredForStraightLine(){return this._stepsConsideredForStraightLine}set stepsConsideredForStraightLine(t){this._stepsConsideredForStraightLine=t}};e(Wt,"DEFAULT_STEPS_CONSIDERED_FOR_STRAIGHT_LINE",2);const Vt=new Wt,Gt=class t extends A{constructor(){super(...arguments),e(this,"_mapMatchingMaxDistance",t.DEFAULT_MM_MAX_DIST),e(this,"_mapMatchingMinDistance",t.DEFAULT_MM_MIN_DIST),e(this,"_mapMatchingMaxAngleBearing",t.DEFAULT_MM_MAX_ANGLE),e(this,"_useItineraryStartAsPosition",t.DEFAULT_USE_ITINERARY_START_AS_POSITION),e(this,"_useOrientationMatching",t.DEFAULT_USE_ORIENTATION_MATCHING),e(this,"_hugeJumpDistance",t.DEFAULT_MM_HUGE_JUMP_DISTANCE),e(this,"_disableMMCloseToATurnDistance",t.DEFAULT_DISABLE_MM_CLOSE_TO_A_TURN_DISTANCE),e(this,"_minStepsBetweenOrientationMatching",t.DEFAULT_MIN_STEPS_BETWEEN_ORIENTATION_MATCHING),e(this,"_minStepsForOrientationMatching",t.DEFAULT_MIN_STEPS_FOR_ORIENTATION_MATCHING),e(this,"_lastProjectionsWindowSize",t.DEFAULT_LAST_PROJECTIONS_WINDOW_SIZE),e(this,"_lastProjectionsEdgeAngleThreshold",t.DEFAULT_LAST_PROJECTIONS_EDGE_ANGLE_THRESHOLD),e(this,"_graph",null),e(this,"_internalProvidersStarted",!1),e(this,"_straightLineProviderId"),e(this,"_turnProviderId"),e(this,"_stepProviderId"),e(this,"_projectionsWithAbsAndWithoutRelAttitudeInARow",[]),e(this,"_countStepsFromLastMatching",0),e(this,"_lastProjections",[]),e(this,"_itineraryInfoManager",null),e(this,"getName",(()=>"MapMatchingHandler")),e(this,"availability",(()=>Promise.resolve())),e(this,"_manageStartStop",(()=>{this.graph&&!this._internalProvidersStarted?this._startInternalProviders():!this.graph&&this._internalProvidersStarted&&this._stopInternalProviders()}))}start(){this.graph&&this._startInternalProviders()}stop(){this._stopInternalProviders()}_startInternalProviders(){this.enabled&&this._internalProvidersStarted||(this._straightLineProviderId=Vt.addEventListener(),this._turnProviderId=Bt.addEventListener(),this._stepProviderId=Et.addEventListener((()=>this._countStepsFromLastMatching++)),this._internalProvidersStarted=!0)}_stopInternalProviders(){this.enabled&&!this._internalProvidersStarted||(Vt.removeEventListener(this._straightLineProviderId),Bt.removeEventListener(this._turnProviderId),Et.removeEventListener(this._stepProviderId),this._internalProvidersStarted=!1)}get enabled(){return E.useMapMatching}get graph(){return this._graph}set graph(t){this._graph=t,this._itineraryInfoManager=null,this.notify({...t&&{graph:t}}),this._manageStartStop(),this.canUseMapMatching()}set itinerary(t){this._graph=t?t.toGraph():null,this._itineraryInfoManager=new r.ItineraryInfoManager(t),this.notify({...t&&{itinerary:t}}),this._manageStartStop(),this.canUseMapMatching()&&t&&this._notifyPositionFromItineraryInput(t)}canUseMapMatching(){return this.enabled&&this.graph}_notifyPositionFromItineraryInput(t){if(!this._useItineraryStartAsPosition||!t.origin)return;const e=Dt.lastEvent||null,s=i.UserPosition.fromCoordinates(t.origin);if(e)s.alt=e.alt,s.time=e.time,s.accuracy=e.accuracy+s.distanceTo(e),s.bearing=e.bearing;else{if(!(t.coords.length>=2))return;s.alt=D.DEFAULT_ALTITUDE,s.time=n.TimeUtils.preciseTime(),s.accuracy=0,s.bearing=t.coords[0].bearingTo(t.coords[1])}const r=this.getProjection(s,!0);r?Dt.notify(r.coords):Dt.notify(s)}notifyPositionFromFeed(t){const e=this.getProjection(t,!0,!1);e?Dt.notify(e.coords):Dt.notify(t)}notifyPositionFromAbsolute(t){let e=null;if(null!==t.bearing&&(e=this.getProjection(t,!0,!0)),!e)return Dt.notify(t),!0;const i=e.distanceFromNearestElement>this._hugeJumpDistance;return!(i&&!Vt.isStraight())&&((!i||!this._detectWrongBigJump(e))&&(Dt.notify(e.coords),this.tryOrientationMatching(e),!0))}notifyPositionFromRelative(t){var e;if(Bt.isTurning())return this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections=[],Dt.notify(t),!0;const i=this.getProjection(t,!0,!0);if(i){this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections.push(i),this._lastProjections.length>this._lastProjectionsWindowSize&&this._lastProjections.shift();const e=i.distanceFromNearestElement>this._hugeJumpDistance;return e&&!Vt.isStraight()||e&&this._detectWrongBigJump(i)?(Dt.notify(t),!0):this._areLastProjectionsInTheSameDirection()?this._disableMMCloseToATurnDistance>0&&this._hasTurnInCircle(i.coords,this._disableMMCloseToATurnDistance)?(Dt.notify(t),!0):(Dt.notify(i.coords),this.tryOrientationMatching(i),!0):(Dt.notify(t),!0)}if(Vt.isStraight()){const i=t.clone();i.bearing=(null==(e=Ft.lastEvent)?void 0:e.heading)||null;const s=this.getProjection(i,!0,!0);if(s)return this._projectionsWithAbsAndWithoutRelAttitudeInARow.push(s),this._projectionsWithAbsAndWithoutRelAttitudeInARow.length<3?(Dt.notify(t),!0):(this._lastProjections.push(s),this._lastProjections.length>this._lastProjectionsWindowSize&&this._lastProjections.shift(),this._areLastProjectionsInTheSameDirection()?(Dt.notify(s.coords),this.tryOrientationMatching(s),!0):(Dt.notify(t),!0))}return this._projectionsWithAbsAndWithoutRelAttitudeInARow=[],this._lastProjections=[],Dt.notify(t),!0}_detectWrongBigJump(t){if(this._itineraryInfoManager&&Dt.lastEvent){const e=this._itineraryInfoManager.getInfo(Dt.lastEvent),i=this._itineraryInfoManager.getInfo(t.coords);if(e&&i&&e.traveledDistance>i.traveledDistance&&e.traveledDistance-i.traveledDistance>t.origin.accuracy&&t.distanceFromNearestElement>t.origin.accuracy&&t.origin.distanceTo(Dt.lastEvent)<t.origin.accuracy+Dt.lastEvent.accuracy)return!0}return!1}_areLastProjectionsInTheSameDirection(){if(0===this._lastProjections.length)return!1;const t=this._lastProjections[0];return!this._lastProjections.some((e=>!(e.nearestElement instanceof r.Edge)||!(t.nearestElement instanceof r.Edge)||s.diffAngleLines(e.nearestElement.bearing,t.nearestElement.bearing)>this._lastProjectionsEdgeAngleThreshold))}_nodeHasTurn(e){if(!this._graph)return;const i=this._graph.edges.filter((t=>t.vertex1===e||t.vertex2===e));for(let r=0;r<i.length;r++)for(let e=r+1;e<i.length;e++){if(s.diffAngleLines(i[r].bearing,i[e].bearing)>t.DEFAULT_MM_MAX_ANGLE)return!0}return!1}_hasTurnInCircle(t,e){const s=this._graph;return!!s&&s.vertices.filter((s=>s.coords.distanceTo(t)<=e&&i.Level.intersect(s.coords.level,t.level))).some((t=>this._nodeHasTurn(t)))}tryOrientationMatching(t){if(!this._useOrientationMatching)return;if("started"!==this.state||this._countStepsFromLastMatching<this._minStepsBetweenOrientationMatching||Vt.numStepsDetectedFromLastTurn<this._minStepsForOrientationMatching)return;const{nearestElement:e,origin:n}=t;if(!(e instanceof r.Edge))return;let o;const a=s.diffAngle(e.bearing,n.bearing),l=s.diffAngle(e.bearing+Math.PI,n.bearing);o=Math.abs(a)<Math.abs(l)?e.bearing:(e.bearing+Math.PI)%(2*Math.PI);const h=new i.AbsoluteHeading(o,n.time,0);Ut._forceHeadingForRelative(h),this._countStepsFromLastMatching=0}getProjection(t,e,i){var s;const r={...e&&{maxDistance:this._mapMatchingMaxDistance},...i&&{maxBearingAngle:this._mapMatchingMaxAngleBearing}};return null==(s=this._graph)?void 0:s.getProjection(t,r)}get maxDistance(){return this._mapMatchingMaxDistance}set maxDistance(t){this._mapMatchingMaxDistance=t}get minDistance(){return this._mapMatchingMinDistance}set minDistance(t){this._mapMatchingMinDistance=t}get maxAngleBearing(){return this._mapMatchingMaxAngleBearing}set maxAngleBearing(t){this._mapMatchingMaxAngleBearing=t}get useItineraryStartAsPosition(){return this._useItineraryStartAsPosition}set useItineraryStartAsPosition(t){this._useItineraryStartAsPosition=t}get useOrientationMatching(){return this._useOrientationMatching}set useOrientationMatching(t){this._useOrientationMatching=t}get hugeJumpDistance(){return this._hugeJumpDistance}set hugeJumpDistance(t){this._hugeJumpDistance=t}get disableMMCloseToATurnDistance(){return this._disableMMCloseToATurnDistance}set disableMMCloseToATurnDistance(t){this._disableMMCloseToATurnDistance=t}get minStepsBetweenOrientationMatching(){return this._minStepsBetweenOrientationMatching}set minStepsBetweenOrientationMatching(t){this._minStepsBetweenOrientationMatching=t}get minStepsForOrientationMatching(){return this._minStepsForOrientationMatching}set minStepsForOrientationMatching(t){this._minStepsForOrientationMatching=t}get lastProjectionsWindowSize(){return this._lastProjectionsWindowSize}set lastProjectionsWindowSize(t){this._lastProjectionsWindowSize=t}get lastProjectionsEdgeAngleThreshold(){return this._lastProjectionsEdgeAngleThreshold}set lastProjectionsEdgeAngleThreshold(t){this._lastProjectionsEdgeAngleThreshold=t}};e(Gt,"DEFAULT_MM_MAX_ANGLE",s.deg2rad(30)),e(Gt,"DEFAULT_MM_MAX_DIST",30),e(Gt,"DEFAULT_MM_MIN_DIST",0),e(Gt,"DEFAULT_USE_ITINERARY_START_AS_POSITION",!1),e(Gt,"DEFAULT_USE_ORIENTATION_MATCHING",!0),e(Gt,"DEFAULT_MM_HUGE_JUMP_DISTANCE",3),e(Gt,"DEFAULT_DISABLE_MM_CLOSE_TO_A_TURN_DISTANCE",2),e(Gt,"DEFAULT_MIN_STEPS_BETWEEN_ORIENTATION_MATCHING",3),e(Gt,"DEFAULT_MIN_STEPS_FOR_ORIENTATION_MATCHING",5),e(Gt,"DEFAULT_LAST_PROJECTIONS_WINDOW_SIZE",3),e(Gt,"DEFAULT_LAST_PROJECTIONS_EDGE_ANGLE_THRESHOLD",s.deg2rad(3));const qt=new Gt,Qt=class t{constructor(i,s=t.DEFAULT_FREQUENCY){e(this,"positionsQueue",[]),e(this,"previousPosition",null),e(this,"timeoutNotify"),e(this,"_notifyNext",(()=>{var t;this.positionsQueue.length&&(null==(t=this.callback)||t.call(this,this.positionsQueue.shift()),0!==this.positionsQueue.length?this.timeoutNotify=setTimeout(this._notifyNext,1e3/this.frequency):delete this.timeoutNotify)})),this.callback=i,this.frequency=s}feed(e,s=t.DEFAULT_FLYBY_TIME){if(!(e instanceof i.UserPosition))throw new TypeError("newPosition is not instance of UserPosition");if(null===e.time)throw new Error("newPosition does not have time property");let r;if(0!==this.positionsQueue.length?(r=this.positionsQueue[0],this.positionsQueue=[]):r=this.previousPosition,r){const t=e.time,n=r.distanceTo(e),o=r.bearingTo(e);let a=1;const l=this.frequency*s+1,h=i.Level.clone(e.level);for(;a<l+1;){const i=r.destinationPoint(n*a/l,o);i.time=t+(a-1)/this.frequency,i.level=h,i.bearing=e.bearing,i.accuracy=Math.max(i.accuracy+(e.accuracy-i.accuracy)*a/l,0),this.positionsQueue.push(i),a++}this.timeoutNotify&&clearTimeout(this.timeoutNotify)}else this.positionsQueue.push(e.clone());this.previousPosition=e,this._notifyNext()}clear(){clearTimeout(this.timeoutNotify),delete this.timeoutNotify,this.positionsQueue=[]}};e(Qt,"DEFAULT_FREQUENCY",60),e(Qt,"DEFAULT_FLYBY_TIME",1);let kt=Qt;const jt=class t{constructor(t){e(this,"_previousAttitude"),e(this,"_smoothing",null),this.callback=t}feed(e){if(null===e.time)throw new Error("newAttitude does not have time property");const{_previousAttitude:r}=this;if(this._previousAttitude=e,r){if(t.isJump(r,e)){const n=null===this._smoothing?r:this._smoothing.interpAttitude(r),o=n.heading,a=e.heading,l=s.diffAngle(a,o),h=Math.abs(l)<t.HIGH_JUMP_THRESHOLD?t.ROTATION_SPEED_CONVERGENCE:t.ROTATION_SPEED_HIGH_JUMP_CONVERGENCE,c=n.time,d=Math.abs(l)/h,u=l<0?-1:1;this._smoothing={toTime:c+d,interpAttitude:t=>{const e=h*(t.time-c),r=o+e*u,n=s.Quaternion.fromAxisAngle([0,0,1],a-r),l=s.Quaternion.multiply(n,t.quaternion);return new i.Attitude(l,t.time,t.accuracy)}}}if(null!==this._smoothing){if(!(e.time>=this._smoothing.toTime)){const t=this._smoothing.interpAttitude(e);return void this.callback(t)}this._smoothing=null}this.callback(e)}else this.callback(e)}static isJump(e,i){const r=e.heading,n=i.heading,o=s.diffAngle(n,r),a=i.time-e.time,[l,h,c,d]=i.quaternion;return!(Math.abs(Math.asin(2*(l*h+c*d))-Math.PI/4)<t.PITCH_UNCERTAINITY_HEADING_THRESHOLD)&&Math.abs(o)>t.ROTATION_SPEED_JUMP_THRESHOLD*a}};e(jt,"ROTATION_SPEED_JUMP_THRESHOLD",s.deg2rad(180)),e(jt,"ROTATION_SPEED_CONVERGENCE",s.deg2rad(10)),e(jt,"HIGH_JUMP_THRESHOLD",s.deg2rad(20)),e(jt,"ROTATION_SPEED_HIGH_JUMP_CONVERGENCE",s.deg2rad(100)),e(jt,"PITCH_UNCERTAINITY_HEADING_THRESHOLD",s.deg2rad(5));let zt=jt;const Jt=new class extends A{constructor(){super(),e(this,"getName",(()=>"MagnetometerCalibrationProvider")),e(this,"availability",(()=>Ut.getAvailability())),Ut._setCallbackMagCalibration((t=>"started"===this.state&&this.notify(t)))}start(){}stop(){}},Yt=class t extends Error{constructor(e){super(e||t.DEFAULT_MESSAGE)}};e(Yt,"DEFAULT_MESSAGE","IP Resolver failed");let Xt=Yt;const Kt=new class extends A{constructor(){super(...arguments),e(this,"getName",(()=>"Ip")),e(this,"availability",(()=>Promise.resolve()))}async start(){const t=await fetch("https://ipinfo.io/geo?token=24a7ca2f3b489d");if(!t)return void this.notifyError(new Xt);const e=n.TimeUtils.preciseTime()/1e3,s=(await t.json()).loc.split(","),r=new i.UserPosition(parseFloat(s[0]),parseFloat(s[1]),null,null,e,1e5);this.notify(r)}stop(){}};const Zt=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"Barcode")),e(this,"availability",(()=>W.getAvailability()))}start(){W.enableBarcodeScanner(),this.providerId=W.addEventListener((t=>t.barcode&&this.notify(t.barcode)),this.notifyError)}stop(){W.disableBarcodeScanner(),W.removeEventListener(this.providerId)}};const $t=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"CameraNative")),e(this,"availability",(()=>Promise.resolve()))}start(){"stopped"!==W.state&&this.notify("started"),this.providerId=W.addMonitoringListener((()=>this.notify("started")),(()=>this.notify("stopped")))}stop(){W.removeMonitoringListener(this.providerId)}};const te=new class extends A{constructor(){super(...arguments),e(this,"providerId"),e(this,"getName",(()=>"CameraProjectionMatrix")),e(this,"availability",(()=>W.getAvailability()))}start(){this.providerId=W.addEventListener((t=>t.cameraProjection&&this.notify(t.cameraProjection)),this.notifyError)}stop(){W.removeEventListener(this.providerId)}};exports.AbsoluteAttitude=u,exports.AbsoluteAttitudeFromBrowserProvider=Ft,exports.AbsoluteAttitudeProvider=Ut,exports.AbsolutePosition=v,exports.AbsolutePositionProvider=Dt,exports.AccelerometerProvider=J,exports.ArCoreProvider=W,exports.AttitudeSmoother=zt,exports.BarcodeProvider=Zt,exports.CameraNativeProvider=$t,exports.CameraProjectionMatrixProvider=te,exports.Constants=D,exports.GeoRelativePositionFromArCoreProvider=V,exports.GeoRelativePositionProvider=mt,exports.GnssWifiProvider=F,exports.GyroscopeProvider=X,exports.HighRotationsProvider=it,exports.ImageRelocalization=St,exports.ImuProvider=k,exports.InclinationFromAccProvider=gt,exports.InclinationFromRelativeAttitudeProvider=At,exports.InclinationProvider=It,exports.IpProvider=Kt,exports.MagnetometerCalibrationProvider=Jt,exports.MapMatchingHandler=qt,exports.PdrProvider=_t,exports.PoleStarProvider=Lt,exports.PositionSmoother=kt,exports.ProvidersLoggerOld=_,exports.ProvidersOptions=E,exports.RelativeAttitude=d,exports.RelativeAttitudeFromBrowserProvider=tt,exports.RelativeAttitudeFromEkfProvider=Z,exports.RelativeAttitudeFromInertialProvider=rt,exports.RelativeAttitudeProvider=Ot,exports.RelativeRotationCalc=yt,exports.StepDetectionMinMaxPeaks2=ct,exports.StepDetectionMinMaxPeaks3=ut,exports.StepProvider=Et,exports.StraightLineProvider=Vt,exports.TurnProvider=Bt,exports.VpsMetadata=ft,exports.VpsProvider=wt,exports.VpsRequest=Pt,exports.VpsResponse=Tt;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|