Revision control

Copy as Markdown

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t():"function"==typeof define&&define.amd?define(t):t()}(0,function(){"use strict";const e="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t=Symbol("@@webxr-polyfill/EventTarget");class r{constructor(){this[t]={listeners:new Map}}addEventListener(e,r){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof r)throw new Error("`listener` must be a function");const i=this[t].listeners.get(e)||[];i.push(r),this[t].listeners.set(e,i)}removeEventListener(e,r){if("string"!=typeof e)throw new Error("`type` must be a string");if("function"!=typeof r)throw new Error("`listener` must be a function");const i=this[t].listeners.get(e)||[];for(let e=i.length;e>=0;e--)i[e]===r&&i.pop()}dispatchEvent(e,r){const i=this[t].listeners.get(e)||[],s=[];for(let e=0;e<i.length;e++)s[e]=i[e];for(let e of s)e(r);"function"==typeof this[`on${e}`]&&this[`on${e}`](r)}}const i=Symbol("@@webxr-polyfill/XR");class s extends r{constructor(e){super(),this[i]={device:e}}async requestDevice(){const e=await this[i].device;if(e)return e;throw new Error("NotFoundError")}}let n;if("performance"in e==!1){let e=Date.now();n=(()=>Date.now()-e)}else n=(()=>performance.now());var a=n;const o=Symbol("@@webxr-polyfill/XRPresentationContext");class h{constructor(e,t,r){this[o]={canvas:e,ctx:t,glAttribs:r},Object.assign(this,t)}get canvas(){return this[o].canvas}}let l="undefined"!=typeof Float32Array?Float32Array:Array;Math.PI;function c(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function d(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function u(e,t){let r=t[0],i=t[1],s=t[2],n=t[3],a=t[4],o=t[5],h=t[6],l=t[7],c=t[8],d=t[9],u=t[10],m=t[11],_=t[12],p=t[13],f=t[14],g=t[15],b=r*o-i*a,w=r*h-s*a,v=r*l-n*a,y=i*h-s*o,E=i*l-n*o,A=s*l-n*h,R=c*p-d*_,M=c*f-u*_,x=c*g-m*_,I=d*f-u*p,T=d*g-m*p,S=u*g-m*f,C=b*S-w*T+v*I+y*x-E*M+A*R;return C?(C=1/C,e[0]=(o*S-h*T+l*I)*C,e[1]=(s*T-i*S-n*I)*C,e[2]=(p*A-f*E+g*y)*C,e[3]=(u*E-d*A-m*y)*C,e[4]=(h*x-a*S-l*M)*C,e[5]=(r*S-s*x+n*M)*C,e[6]=(f*v-_*A-g*w)*C,e[7]=(c*A-u*v+m*w)*C,e[8]=(a*T-o*x+l*R)*C,e[9]=(i*x-r*T-n*R)*C,e[10]=(_*E-p*v+g*b)*C,e[11]=(d*v-c*E-m*b)*C,e[12]=(o*M-a*I-h*R)*C,e[13]=(r*I-i*M+s*R)*C,e[14]=(p*w-_*y-f*b)*C,e[15]=(c*y-d*w+u*b)*C,e):null}function m(e,t,r){let i=t[0],s=t[1],n=t[2],a=t[3],o=t[4],h=t[5],l=t[6],c=t[7],d=t[8],u=t[9],m=t[10],_=t[11],p=t[12],f=t[13],g=t[14],b=t[15],w=r[0],v=r[1],y=r[2],E=r[3];return e[0]=w*i+v*o+y*d+E*p,e[1]=w*s+v*h+y*u+E*f,e[2]=w*n+v*l+y*m+E*g,e[3]=w*a+v*c+y*_+E*b,w=r[4],v=r[5],y=r[6],E=r[7],e[4]=w*i+v*o+y*d+E*p,e[5]=w*s+v*h+y*u+E*f,e[6]=w*n+v*l+y*m+E*g,e[7]=w*a+v*c+y*_+E*b,w=r[8],v=r[9],y=r[10],E=r[11],e[8]=w*i+v*o+y*d+E*p,e[9]=w*s+v*h+y*u+E*f,e[10]=w*n+v*l+y*m+E*g,e[11]=w*a+v*c+y*_+E*b,w=r[12],v=r[13],y=r[14],E=r[15],e[12]=w*i+v*o+y*d+E*p,e[13]=w*s+v*h+y*u+E*f,e[14]=w*n+v*l+y*m+E*g,e[15]=w*a+v*c+y*_+E*b,e}const _=Symbol("@@webxr-polyfill/XRDevicePose");class p{constructor(e){this[_]={polyfill:e,leftViewMatrix:d(new Float32Array(16)),rightViewMatrix:d(new Float32Array(16)),poseModelMatrix:d(new Float32Array(16))}}get poseModelMatrix(){return this[_].poseModelMatrix}getViewMatrix(e){switch(e.eye){case"left":return this[_].leftViewMatrix;case"right":return this[_].rightViewMatrix}throw new Error("view is not a valid XREye")}updateFromFrameOfReference(e){const t=this[_].polyfill.getBasePoseMatrix(),r=this[_].polyfill.getBaseViewMatrix("left"),i=this[_].polyfill.getBaseViewMatrix("right");t&&e.transformBasePoseMatrix(this[_].poseModelMatrix,t),r&&i&&(e.transformBaseViewMatrix(this[_].leftViewMatrix,r,this[_].poseModelMatrix),e.transformBaseViewMatrix(this[_].rightViewMatrix,i,this[_].poseModelMatrix))}}const f=Symbol("@@webxr-polyfill/XRViewport");class g{constructor(e){this[f]={target:e}}get x(){return this[f].target.x}get y(){return this[f].target.y}get width(){return this[f].target.width}get height(){return this[f].target.height}}const b=["left","right"],w=Symbol("@@webxr-polyfill/XRView");class v{constructor(e,t,r){if(!b.includes(t))throw new Error(`XREye must be one of: ${b}`);const i=Object.create(null),s=new g(i);this[w]={polyfill:e,eye:t,viewport:s,temp:i,sessionId:r}}get eye(){return this[w].eye}get projectionMatrix(){return this[w].polyfill.getProjectionMatrix(this.eye)}_getViewport(e){this[w].viewport;if(this[w].polyfill.getViewport(this[w].sessionId,this.eye,e,this[w].temp))return this[w].viewport}}const y=Symbol("@@webxr-polyfill/XRFrame");class E{constructor(e,t,r){const i=new p(e),s=[new v(e,"left",r)];t.immersive&&s.push(new v(e,"right",r)),this[y]={polyfill:e,devicePose:i,views:s,session:t}}get session(){return this[y].session}get views(){return this[y].views}getDevicePose(e){return this[y].devicePose.updateFromFrameOfReference(e),this[y].devicePose}getInputPose(e,t){return this[y].polyfill.getInputPose(e,t)}}const A=Symbol("@@webxr-polyfill/XRStageBoundsPoint");class R{constructor(e,t){this[A]={x:e,z:t}}get x(){return this[A].x}get z(){return this[A].z}}const M=Symbol("@@webxr-polyfill/XRStageBounds");class x{constructor(e){const t=[];for(let r=0;r<e.length;r+=2)t.push(new R(e[r],e[r+1]));this[M]={geometry:t}}get geometry(){return this[M].geometry}}class I{constructor(){}getTransformTo(e){throw new Error("Not yet supported")}}const T=1.6,S=Symbol("@@webxr-polyfill/XRFrameOfReference"),C=["head-model","eye-level","stage"],O=Object.freeze({disableStageEmulation:!1,stageEmulationHeight:0});class P extends I{constructor(e,t,r,i,s){if(r=Object.assign({},O,r),!C.includes(t))throw new Error(`XRFrameOfReferenceType must be one of ${C}`);if(super(),"stage"===t&&r.disableStageEmulation&&!i)throw new Error("XRFrameOfReference cannot use 'stage' type, if disabling emulation and platform does not provide");const{disableStageEmulation:n,stageEmulationHeight:a}=r;let o=0;"stage"!==t||i||(o=0!==a?a:T),"stage"!==t||i||((i=d(new Float32Array(16)))[13]=o),this[S]={disableStageEmulation:n,stageEmulationHeight:a,emulatedHeight:o,type:t,transform:i,polyfill:e,bounds:s},this.onboundschange=void 0}get bounds(){return this[S].bounds}get emulatedHeight(){return this[S].emulatedHeight}get type(){return this[S].type}transformBasePoseMatrix(e,t){if(this[S].transform)m(e,this[S].transform,t);else switch(this.type){case"head-model":return e!==t&&c(e,t),void(e[12]=e[13]=e[14]=0);case"eye-level":return void(e!==t&&c(e,t))}}transformBaseViewMatrix(e,t){let r=this[S].transform;if(r)u(e,r),m(e,t,e);else{if("head-model"===this.type)return u(e,t),e[12]=0,e[13]=0,e[14]=0,u(e,e),e;c(e,t)}return e}}const N=Symbol("@@webxr-polyfill/XRSession"),D=Object.freeze({immersive:!1,outputContext:void 0}),F=e=>{const{immersive:t,outputContext:r}=e;return!(!t&&!r)&&(void 0===r||r instanceof h)};class L extends r{constructor(e,t,r,i){r=Object.assign({},D,r),super();const{immersive:s,outputContext:n}=r;this[N]={polyfill:e,device:t,immersive:s,outputContext:n,ended:!1,suspended:!1,suspendedCallback:null,id:i};const a=new E(e,this,this[N].id);this[N].frame=a,this[N].onPresentationEnd=(t=>{if(t!==this[N].id){this[N].suspended=!1,this.dispatchEvent("focus",{session:this});const e=this[N].suspendedCallback;return this[N].suspendedCallback=null,void(e&&this.requestAnimationFrame(e))}this[N].ended=!0,e.removeEventListener("@webvr-polyfill/vr-present-end",this[N].onPresentationEnd),e.removeEventListener("@webvr-polyfill/vr-present-start",this[N].onPresentationStart),e.removeEventListener("@@webvr-polyfill/input-select-start",this[N].onSelectStart),e.removeEventListener("@@webvr-polyfill/input-select-end",this[N].onSelectEnd),this.dispatchEvent("end",{session:this})}),e.addEventListener("@@webxr-polyfill/vr-present-end",this[N].onPresentationEnd),this[N].onPresentationStart=(e=>{e!==this[N].id&&(this[N].suspended=!0,this.dispatchEvent("blur",{session:this}))}),e.addEventListener("@@webxr-polyfill/vr-present-start",this[N].onPresentationStart),this[N].onSelectStart=(e=>{e.sessionId===this[N].id&&this.dispatchEvent("selectstart",{frame:this[N].frame,inputSource:e.inputSource})}),e.addEventListener("@@webxr-polyfill/input-select-start",this[N].onSelectStart),this[N].onSelectEnd=(e=>{e.sessionId===this[N].id&&(this.dispatchEvent("selectend",{frame:this[N].frame,inputSource:e.inputSource}),this.dispatchEvent("select",{frame:this[N].frame,inputSource:e.inputSource}))}),e.addEventListener("@@webxr-polyfill/input-select-end",this[N].onSelectEnd),this.onblur=void 0,this.onfocus=void 0,this.onresetpose=void 0,this.onend=void 0,this.onselect=void 0,this.onselectstart=void 0,this.onselectend=void 0}get device(){return this[N].device}get immersive(){return this[N].immersive}get outputContext(){return this[N].outputContext}get depthNear(){return this[N].polyfill.depthNear}set depthNear(e){this[N].polyfill.depthNear=e}get depthFar(){return this[N].polyfill.depthFar}set depthFar(e){this[N].polyfill.depthFar=e}get environmentBlendMode(){return this[N].polyfill.environmentBlendMode||"opaque"}get baseLayer(){return this[N].baseLayer}set baseLayer(e){this[N].ended||(this[N].baseLayer=e,this[N].polyfill.onBaseLayerSet(this[N].id,e))}async requestFrameOfReference(e,t={}){if(this[N].ended)return;if(t=Object.assign({},O,t),!C.includes(e))throw new TypeError(`XRFrameOfReferenceType must be one of ${C}`);let r=null,i=null;try{r=await this[N].polyfill.requestFrameOfReferenceTransform(e,t)}catch(r){if("stage"!==e||t.disableStageEmulation)throw r}return"stage"===e&&r&&(i=this[N].polyfill.requestStageBounds())&&(i=new x(i)),new P(this[N].polyfill,e,t,r,i)}requestAnimationFrame(e){if(!(this[N].ended||this[N].suspended&&this[N].suspendedCallback))return this[N].suspended&&!this[N].suspendedCallback&&(this[N].suspendedCallback=e),this[N].polyfill.requestAnimationFrame(()=>{this[N].polyfill.onFrameStart(this[N].id),e(a(),this[N].frame),this[N].polyfill.onFrameEnd(this[N].id)})}cancelAnimationFrame(e){this[N].ended||this[N].polyfill.cancelAnimationFrame(e)}getInputSources(){return this[N].polyfill.getInputSources()}async end(){if(!this[N].ended)return this.immersive||(this[N].ended=!0,this[N].polyfill.removeEventListener("@@webvr-polyfill/vr-present-start",this[N].onPresentationStart),this[N].polyfill.removeEventListener("@@webvr-polyfill/vr-present-end",this[N].onPresentationEnd),this[N].polyfill.removeEventListener("@@webvr-polyfill/input-select-start",this[N].onSelectStart),this[N].polyfill.removeEventListener("@@webvr-polyfill/input-select-end",this[N].onSelectEnd),this.dispatchEvent("end",{session:this})),this[N].polyfill.endSession(this[N].id)}}const k=Symbol("@@webxr-polyfill/XRDevice");let V="DOMPointReadOnly"in e?DOMPointReadOnly:null;if(!V){const e=Symbol("@@webxr-polyfill/DOMPointReadOnly");V=class{constructor(t,r,i,s){if(1===arguments.length)this[e]={x:t.x,y:t.y,z:t.z,w:t.w};else{if(4!==arguments.length)throw new TypeError("Must supply either 1 or 4 arguments");this[e]={x:t,y:r,z:i,w:s}}}get x(){return this[e].x}get y(){return this[e].y}get z(){return this[e].z}get w(){return this[e].w}}}var G=V;class W{constructor(e=new G(0,0,0,1),t=new G(0,0,-1,0),r=new Float32Array(16)){if(!(e instanceof G))throw new Error("origin must be a DOMPointReadOnly");if(!(t instanceof G))throw new Error("direction must be a DOMPointReadOnly");if(!(r instanceof Float32Array))throw new Error("transformMatrix must be a Float32Array");Object.defineProperties(this,{origin:{value:e,writable:!1},direction:{value:t,writable:!1},transformMatrix:{value:r,writable:!1}})}}const X=Symbol("@@webxr-polyfill/XRInputPose");const U=Symbol("@@webxr-polyfill/XRInputSource");class B{constructor(){}getViewport(e){return e._getViewport(this)}}const j=Symbol("@@webxr-polyfill/polyfilled-compatible-xr-device"),H=Symbol("@@webxr-polyfill/compatible-xr-device"),z=Symbol("@@webxr-polyfill/XRWebGLLayer"),q=Object.freeze({antialias:!0,depth:!1,stencil:!1,alpha:!0,multiview:!1,framebufferScaleFactor:0});var K={XR:s,XRDevice:class extends r{constructor(e){if(!e)throw new Error("XRDevice must receive a PolyfilledXRDevice.");super(),this[k]={polyfill:e,immersiveSession:null,nonImmersiveSessions:new Set},this.ondeactive=void 0}async supportsSession(e={}){return e=Object.assign({},D,e),F(e)&&this[k].polyfill.supportsSession(e)?null:Promise.reject(null)}async requestSession(e){if(e=Object.assign({},D,e),!F(e))throw new Error("NotSupportedError");if(this[k].immersiveSession&&e.immersive)throw new Error("InvalidStateError");const t=await this[k].polyfill.requestSession(e),r=new L(this[k].polyfill,this,e,t);e.immersive?this[k].immersiveSession=r:this[k].nonImmersiveSessions.add(r);const i=()=>{r.immersive?this[k].immersiveSession=null:this[k].nonImmersiveSessions.delete(r),r.removeEventListener("end",i)};return r.addEventListener("end",i),r}},XRSession:L,XRFrame:E,XRView:v,XRViewport:g,XRDevicePose:p,XRLayer:B,XRWebGLLayer:class extends B{constructor(e,t,r={}){const i=Object.assign({},q,r);if(!(e instanceof L))throw new Error("session must be a XRSession");if(e.ended)throw new Error("InvalidStateError");if(t[j]&&t[H]!==e.device)throw new Error("InvalidStateError");const s=t.getParameter(t.FRAMEBUFFER_BINDING);super(),this[z]={context:t,config:i,framebuffer:s}}get context(){return this[z].context}get antialias(){return this[z].config.antialias}get depth(){return this[z].config.depth}get stencil(){return this[z].config.stencil}get alpha(){return this[z].config.alpha}get multiview(){return!1}get framebuffer(){return this[z].framebuffer}get framebufferWidth(){return this[z].context.drawingBufferWidth}get framebufferHeight(){return this[z].context.drawingBufferHeight}requestViewportScaling(e){console.warn("requestViewportScaling is not yet implemented")}},XRPresentationContext:h,XRCoordinateSystem:I,XRFrameOfReference:P,XRStageBounds:x,XRStageBoundsPoint:R,XRInputPose:class{constructor(e,t){this[X]={inputSourceImpl:e,targetRay:new W,gripMatrix:t?function(){let e=new l(16);return l!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}():null}}get targetRay(){return this[X].targetRay}set targetRay(e){this[X].targetRay=e}get emulatedPosition(){return this[X].inputSourceImpl.emulatedPosition}get gripMatrix(){return this[X].gripMatrix}},XRInputSource:class{constructor(e){this[U]={impl:e}}get handedness(){return this[U].impl.handedness}get targetRayMode(){return this[U].impl.targetRayMode}},XRRay:W};const Y=e=>"function"!=typeof e.prototype.setCompatibleXRDevice&&(e.prototype.setCompatibleXRDevice=function(e){return new Promise((t,r)=>{e&&"function"==typeof e.requestSession?t():r()}).then(()=>this[H]=e)},!0),Z=(e,t)=>{const r=e.prototype.getContext;e.prototype.getContext=function(e,i){if(t&&"xrpresent"===e){let e=r.call(this,t,i);return new h(this,e,i)}const s=r.call(this,e,i);return s[j]=!0,i&&"compatibleXRDevice"in i&&(s[H]=i.compatibleXRDevice),s}};!function(){let e=function(){let e=new l(3);return l!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}()}();const $=e=>!(!e.ImageBitmapRenderingContext||!e.createImageBitmap),J=e=>{var t=!1;return Q=e.navigator.userAgent||e.navigator.vendor||e.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(Q)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(Q.substr(0,4)))&&(t=!0),t};var Q;const ee=async function(e,t){let r=await async function(e){let t=null;if("xr"in e.navigator)try{t=await e.navigator.xr.requestDevice()}catch(e){}return t}(e);return r||null},te={webvr:!0,cardboard:!0},re=["navigator","HTMLCanvasElement","WebGLRenderingContext"];class ie{constructor(t,r={}){this.global=t||e,this.config=Object.freeze(Object.assign({},te,r)),this.nativeWebXR="xr"in this.global.navigator,this.injected=!1,this.nativeWebXR?this.config.cardboard&&J(this.global)&&this._patchRequestDevice():this._injectPolyfill(this.global)}_injectPolyfill(e){if(!re.every(t=>!!e[t]))throw new Error(`Global must have the following attributes : ${re}`);for(const t of Object.keys(K))void 0!==e[t]?console.warn(`${t} already defined on global.`):e[t]=K[t];if(Y(e.WebGLRenderingContext)){const t=$(e)?"bitmaprenderer":"2d";Z(e.HTMLCanvasElement,t),e.OffscreenCanvas&&Z(e.OffscreenCanvas,null),e.WebGL2RenderingContext&&Y(e.WebGL2RenderingContext)}this.injected=!0,this._patchRequestDevice()}_patchRequestDevice(){const e=ee(this.global,this.config);this.xr=new s(e),Object.defineProperty(this.global.navigator,"xr",{value:this.xr,configurable:!0})}}const se=1e-6;let ne="undefined"!=typeof Float32Array?Float32Array:Array;Math.PI;function ae(){let e=new ne(16);return ne!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function oe(e){let t=new ne(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function he(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function le(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function ce(e,t,r){let i=t[0],s=t[1],n=t[2],a=t[3],o=t[4],h=t[5],l=t[6],c=t[7],d=t[8],u=t[9],m=t[10],_=t[11],p=t[12],f=t[13],g=t[14],b=t[15],w=r[0],v=r[1],y=r[2],E=r[3];return e[0]=w*i+v*o+y*d+E*p,e[1]=w*s+v*h+y*u+E*f,e[2]=w*n+v*l+y*m+E*g,e[3]=w*a+v*c+y*_+E*b,w=r[4],v=r[5],y=r[6],E=r[7],e[4]=w*i+v*o+y*d+E*p,e[5]=w*s+v*h+y*u+E*f,e[6]=w*n+v*l+y*m+E*g,e[7]=w*a+v*c+y*_+E*b,w=r[8],v=r[9],y=r[10],E=r[11],e[8]=w*i+v*o+y*d+E*p,e[9]=w*s+v*h+y*u+E*f,e[10]=w*n+v*l+y*m+E*g,e[11]=w*a+v*c+y*_+E*b,w=r[12],v=r[13],y=r[14],E=r[15],e[12]=w*i+v*o+y*d+E*p,e[13]=w*s+v*h+y*u+E*f,e[14]=w*n+v*l+y*m+E*g,e[15]=w*a+v*c+y*_+E*b,e}function de(e,t){let r=Math.sin(t),i=Math.cos(t);return e[0]=i,e[1]=r,e[2]=0,e[3]=0,e[4]=-r,e[5]=i,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function ue(e,t){return e[0]=t[12],e[1]=t[13],e[2]=t[14],e}function me(e,t){let r=t[0]+t[5]+t[10],i=0;return r>0?(i=2*Math.sqrt(r+1),e[3]=.25*i,e[0]=(t[6]-t[9])/i,e[1]=(t[8]-t[2])/i,e[2]=(t[1]-t[4])/i):t[0]>t[5]&&t[0]>t[10]?(i=2*Math.sqrt(1+t[0]-t[5]-t[10]),e[3]=(t[6]-t[9])/i,e[0]=.25*i,e[1]=(t[1]+t[4])/i,e[2]=(t[8]+t[2])/i):t[5]>t[10]?(i=2*Math.sqrt(1+t[5]-t[0]-t[10]),e[3]=(t[8]-t[2])/i,e[0]=(t[1]+t[4])/i,e[1]=.25*i,e[2]=(t[6]+t[9])/i):(i=2*Math.sqrt(1+t[10]-t[0]-t[5]),e[3]=(t[1]-t[4])/i,e[0]=(t[8]+t[2])/i,e[1]=(t[6]+t[9])/i,e[2]=.25*i),e}function _e(){let e=new ne(3);return ne!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0),e}function pe(e,t){let r=e[0],i=e[1],s=e[2],n=t[0],a=t[1],o=t[2];return Math.abs(r-n)<=se*Math.max(1,Math.abs(r),Math.abs(n))&&Math.abs(i-a)<=se*Math.max(1,Math.abs(i),Math.abs(a))&&Math.abs(s-o)<=se*Math.max(1,Math.abs(s),Math.abs(o))}!function(){let e=_e()}();class fe extends r{constructor(e,t=null,r=0){super(),this._uid=t||fe._generateUID(),this._transform=oe(e),this._timestamp=r,this._poseChanged=!0,this._deleted=!1,this._placeholder=!1}get deleted(){return this._deleted}set deleted(e){this._deleted=e}get placeholder(){return this._placeholder}set placeholder(e){this._placeholder=e}isMesh(){return!1}get timeStamp(){return this._timestamp}get changed(){return this._poseChanged}clearChanged(){this._poseChanged=!1}get modelMatrix(){return this._transform}updateModelMatrix(e,t){if(this._timestamp=t,!this._deleted&&!function(e,t){let r=e[0],i=e[1],s=e[2],n=e[3],a=e[4],o=e[5],h=e[6],l=e[7],c=e[8],d=e[9],u=e[10],m=e[11],_=e[12],p=e[13],f=e[14],g=e[15],b=t[0],w=t[1],v=t[2],y=t[3],E=t[4],A=t[5],R=t[6],M=t[7],x=t[8],I=t[9],T=t[10],S=t[11],C=t[12],O=t[13],P=t[14],N=t[15];return Math.abs(r-b)<=se*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(i-w)<=se*Math.max(1,Math.abs(i),Math.abs(w))&&Math.abs(s-v)<=se*Math.max(1,Math.abs(s),Math.abs(v))&&Math.abs(n-y)<=se*Math.max(1,Math.abs(n),Math.abs(y))&&Math.abs(a-E)<=se*Math.max(1,Math.abs(a),Math.abs(E))&&Math.abs(o-A)<=se*Math.max(1,Math.abs(o),Math.abs(A))&&Math.abs(h-R)<=se*Math.max(1,Math.abs(h),Math.abs(R))&&Math.abs(l-M)<=se*Math.max(1,Math.abs(l),Math.abs(M))&&Math.abs(c-x)<=se*Math.max(1,Math.abs(c),Math.abs(x))&&Math.abs(d-I)<=se*Math.max(1,Math.abs(d),Math.abs(I))&&Math.abs(u-T)<=se*Math.max(1,Math.abs(u),Math.abs(T))&&Math.abs(m-S)<=se*Math.max(1,Math.abs(m),Math.abs(S))&&Math.abs(_-C)<=se*Math.max(1,Math.abs(_),Math.abs(C))&&Math.abs(p-O)<=se*Math.max(1,Math.abs(p),Math.abs(O))&&Math.abs(f-P)<=se*Math.max(1,Math.abs(f),Math.abs(P))&&Math.abs(g-N)<=se*Math.max(1,Math.abs(g),Math.abs(N))}(this._transform,e)){this._poseChanged=!0;for(var r=0;r<16;r++)this._transform[r]=e[r];try{this.dispatchEvent("update",{source:this})}catch(e){console.error("XRAnchor update event error",e)}}}notifyOfRemoval(){try{this.dispatchEvent("remove",{source:this})}catch(e){console.error("XRAnchor removed event error",e)}}get position(){return ue(new Float32Array(3),this._poseMatrix)}get orientation(){return me(new Float32Array(4),this._poseMatrix)}get uid(){return this._uid}static _generateUID(){return"anchor-"+(new Date).getTime()+"-"+Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)}}class ge extends fe{constructor(e,t=null){super(t,null),this._anchor=e,this._timestamp=e.timeStamp,this._tempArray=new Float32Array(16),this._offsetMatrix=ae(),t&&he(this._offsetMatrix,t),ce(this._transform,e.modelMatrix,this._offsetMatrix),this._handleAnchorUpdateListener=this._handleAnchorUpdate.bind(this),this._notifyOfRemovalListener=this.notifyOfRemoval.bind(this),this._handleReplaceAnchorListener=this._handleReplaceAnchor.bind(this),e.addEventListener("update",this._handleAnchorUpdateListener),e.addEventListener("removal",this._notifyOfRemovalListener),e.addEventListener("replaceAnchor",this._handleReplaceAnchorListener)}_handleReplaceAnchor(e){this._anchor.removeEventListener("update",this._handleAnchorUpdateListener),this._anchor.removeEventListener("removal",this._notifyOfRemovalListener),this._anchor.removeEventListener("replaceAnchor",this._handleReplaceAnchorListener),this._anchor=e,this._anchor.addEventListener("update",this._handleAnchorUpdateListener),this._anchor.addEventListener("removal",this._notifyOfRemovalListener),this._anchor.addEventListener("replaceAnchor",this._handleReplaceAnchorListener)}_handleAnchorUpdate(){ce(this._tempArray,this._anchor.modelMatrix,this._offsetMatrix),this.updateModelMatrix(this._tempArray,Math.max(this._anchor.timeStamp,this._timestamp))}get modelMatrix(){return this._transform}clearChanged(){super.clearChanged()}get anchor(){return this._anchor}get offsetMatrix(){return this._offsetMatrix}set offsetMatrix(e){he(this._offsetMatrix,e),this._handleAnchorUpdate()}}var be=!1;class we extends fe{static setUseGeomArrays(){be=!0}static useGeomArrays(){return be}constructor(e,t,r=null,i=0){super(e,r,i),this._useGeomArrays=be,this._vertexCountChanged=!0,this._vertexPositionsChanged=!0,this._triangleIndicesChanged=!0,this._textureCoordinatesChanged=!0,this._vertexPositions=[],this._triangleIndices=[],this._textureCoordinates=[],this._vertexNormalsChanged=!0,this._vertexNormals=[],t&&(this._geometry=t,this._updateGeometry(this._geometry))}isMesh(){return!0}get changed(){return super.changed||this._vertexPositionsChanged||this._vertexNormalsChanged||this._triangleIndicesChanged||this._vertexCountChanged}clearChanged(){super.clearChanged(),this._vertexPositionsChanged=!1,this._vertexNormalsChanged=!1,this._triangleIndicesChanged=!1,this._vertexCountChanged=!1}get vertexCountChanged(){return this._vertexCountChanged}get vertexPositionsChanged(){return this._vertexPositionsChanged}get triangleIndicesChanged(){this._triangleIndicesChanged}get textureCoordinatesChanged(){this._textureCoordinatesChanged}get vertexNormalsChanged(){this._vertexNormalsChanged}get vertexPositions(){return this._vertexPositions}get vertexNormals(){return this._vertexNormals}get triangleIndices(){return this._triangleIndices}get textureCoordinates(){return this._textureCoordinates}get vertexCount(){return this._vertexPositions.length}get triangleCount(){return this._triangleIndices.length}get hasNormals(){return this._vertexNormals.length>0}get hasTextureCoordinates(){return this._textureCoordinates.length>0}_updateGeometry(e){this._geometry=e;let t=e;if(0==t.vertexCount)return void(this._vertexPositions.length>0&&(this._vertexPositionsChanged=!0,this._vertexNormalsChanged=!0,this._triangleIndicesChanged=!0,this._textureCoordinatesChanged=!0,this._vertexPositions=[],this._vertexNormals=[],this.triangleIndices=[],this._textureCoordinates=[]));if(void 0===t.vertexCount)return void console.warn("bad geometry data passed to XRMesh._updateGeometry: no vertex count",t);let r=0;if(this._vertexPositions.length!=3*t.vertexCount){if(void 0===t.vertices)return void console.warn("bad geometry data passed to XRMesh._updateGeometry: no vertices",t);this._vertexCountChanged=!0,this._vertexPositionsChanged=!0,this._vertexPositions=new Float32Array(3*t.vertexCount),t.textureCoordinates&&(this._textureCoordinatesChanged=!0,this._textureCoordinates=new Float32Array(2*t.vertexCount))}else if(this._useGeomArrays)this._vertexPositionsChanged=void 0!==t.vertices&&!we.arrayFuzzyEquals(this._vertexPositions,t.vertices),this._textureCoordinatesChanged=void 0!==t.textureCoordinates&&!we.arrayFuzzyEquals(this._textureCoordinates,t.textureCoordinates);else{if(this._vertexPositionsChanged=!1,t.vertices){r=0;for(var i=0,s=t.vertexCount;i<s;i++)if(Math.abs(this._vertexPositions[r++]-t.vertices[i].x)>se||Math.abs(this._vertexPositions[r++]-t.vertices[i].y)>se||Math.abs(this._vertexPositions[r++]-t.vertices[i].z)>se){this._vertexPositionsChanged=!0;break}}if(this._textureCoordinatesChanged=!1,t.textureCoordinates){r=0;for(i=0,s=t.vertexCount;i<s;i++)if(Math.abs(this._textureCoordinates[r++]-t.textureCoordinates[i].x)>se||Math.abs(this._textureCoordinates[r++]-t.textureCoordinates[i].x)>se){this._textureCoordinatesChanged=!0;break}}}if(t.triangleCount?this._triangleIndices.length!=3*t.triangleCount?(this._triangleIndicesChanged=!0,this._triangleIndices=(we.arrayMax(t.triangleIndices),new Uint32Array(3*t.triangleCount))):this._triangleIndicesChanged=t.triangleIndicies&&!we.arrayEquals(this._triangleIndices,t.triangleIndices):this._triangleIndicesChanged=!1,this._vertexPositionsChanged)if(this._useGeomArrays)this._vertexPositions.set(t.vertices);else{r=0;for(let e of t.vertices)this._vertexPositions[r++]=e.x,this._vertexPositions[r++]=e.y,this._vertexPositions[r++]=e.z}if(this._textureCoordinatesChanged)if(r=0,this._useGeomArrays)this._textureCoordinates.set(t.textureCoordinates);else for(let e of t.textureCoordinates)this._textureCoordinates[r++]=e.x,this._textureCoordinates[r++]=e.y;this._triangleIndicesChanged&&this._triangleIndices.set(t.triangleIndices)}static arrayMax(e){if(0===e.length)return-1/0;for(var t=e[0],r=1,i=e.length;r<i;++r)e[r]>t&&(t=e[r]);return t}static arrayEquals(e,t){if(!e||!t)return!1;if(e.length!=t.length)return!1;for(var r=0,i=e.length;r<i;r++)if(e[r]!=t[r])return!1;return!0}static arrayFuzzyEquals(e,t){if(!e||!t)return!1;if(e.length!=t.length)return!1;for(var r=0,i=e.length;r<i;r++)if(Math.abs(e[r]-t[r])>se)return!1;return!0}}class ve extends we{constructor(e,t,r,i=null,s=0){super(e,t,i,s),this._blendShapes={},this._blendShapesChanged=!0,this._updateBlendShapes(r)}get changed(){return super.changed||this._blendShapesChanged}clearChanged(){super.clearChanged(),this._blendShapesChanged=!1}_updateBlendShapes(e){for(let i=0;i<ye.length;i++){let s=ye[i];var t=this._blendShapes[s],r=e[i];Math.abs(t-r)>se&&(this._blendShapesChanged=!0,this._blendShapes[s]=r)}}updateFaceData(e,t,r,i){super.updateModelMatrix(e,i),void 0===t.vertexCount&&(t.vertexCount=t.vertices.length/(we.useGeomArrays()?3:1)),this._updateGeometry(t),this._updateBlendShapes(r)}get blendShapes(){return this._blendShapes}}const ye=["browDownLeft","browDownRight","browInnerUp","browOuterUpLeft","browOuterUpRight","cheekPuff","cheekSquintLeft","cheekSquintRight","eyeBlinkLeft","eyeBlinkRight","eyeLookDownLeft","eyeLookDownRight","eyeLookInLeft","eyeLookInRight","eyeLookOutLeft","eyeLookOutRight","eyeLookUpLeft","eyeLookUpRight","eyeSquintLeft","eyeSquintRight","eyeWideLeft","eyeWideRight","jawForward","jawLeft","jawOpen","jawRight","mouthClose","mouthDimpleLeft","mouthDimpleRight","mouthFrownLeft","mouthFrownRight","mouthFunnel","mouthLeft","mouthLowerDownLeft","mouthLowerDownRight","mouthPressLeft","mouthPressRight","mouthPucker","mouthRight","mouthRollLower","mouthRollUpper","mouthShrugLower","mouthShrugUpper","mouthSmileLeft","mouthSmileRight","mouthStretchLeft","mouthStretchRight","mouthUpperUpLeft","mouthUpperUpRight","noseSneerLeft","noseSneerRight"];class Ee{constructor(e=null,t=null,r){this._hit=t,this._timestamp=r,this._hitMatrix=oe(e)}get hitMatrix(){return this._hitMatrix}get timeStamp(){return this._timestamp}}class Ae extends fe{}class Re{constructor(){this._ambientLightIntensity=1}set ambientIntensity(e){this._ambientLightIntensity=e/1e3}get ambientIntensity(){return this._ambientLightIntensity}getAmbientColorTemperature(){throw new Error("Not implemented")}}function Me(){let e=new ne(4);return ne!=Float32Array&&(e[0]=0,e[1]=0,e[2]=0,e[3]=0),e}!function(){let e=Me()}();class xe extends we{constructor(e,t,r,i,s,n=null,a=0){super(e,null,n,a),this._center=t,this._extent=r,this._alignment=i,this._planeFeatureChanged=!0,this._yAxis=function(e,t,r,i){let s=new ne(4);return s[0]=e,s[1]=t,s[2]=r,s[3]=i,s}(0,1,0,0),this._normal=Me(),this._boundaryVerticesChanged=!0,this._boundaryVertices=[],this._geometry=s,this._updateGeometry(this._geometry)}get changed(){return super.changed||this._planeFeatureChanged}clearChanged(){super.clearChanged(),this._planeFeatureChanged=!1}updatePlaneData(e,t,r,i,s,n){super.updateModelMatrix(e,n),pe(this._center,t)&&pe(this._extent,r)&&!this._alignment||(this._center=t,this._extent=r,this._alignment=i,this._planeFeatureChanged=!0),this._updateGeometry(s)}get center(){return this._center}get extent(){return this._extent}get alignment(){return this._alignment}get boundaryVertices(){return this._boundaryVertices}get boundaryVerticesChanged(){return this._boundaryVerticesChanged}get boundaryVertexCount(){return this._boundaryVertices.length}_updateGeometry(e){super._updateGeometry(e);let t=e;const r=function(e,t,r){let i=t[0],s=t[1],n=t[2],a=t[3];return e[0]=r[0]*i+r[4]*s+r[8]*n+r[12]*a,e[1]=r[1]*i+r[5]*s+r[9]*n+r[13]*a,e[2]=r[2]*i+r[6]*s+r[10]*n+r[14]*a,e[3]=r[3]*i+r[7]*s+r[11]*n+r[15]*a,e}(this._normal,this._yAxis,this._transform),i=r[0],s=r[1],n=r[2];let a=0;if(this._boundaryVertices.length!=3*t.boundaryVertexCount)this._boundaryVerticesChanged=!0,this._boundaryVertices=new Float32Array(3*t.vertexCount),this._vertexNormalsChanged=!0,this._vertexNormals=new Float32Array(3*t.vertexCount);else if(this._vertexNormalsChanged=Math.abs(this._vertexNormals[0]-i)>se||Math.abs(this._vertexNormals[1]-s)>se||Math.abs(this._vertexNormals[2]-n)>se,this._useGeomArrays)this._vertexPositionsChanged=!we.arrayFuzzyEquals(this._boundaryVertices,t.boundaryVertices);else{this._boundaryVerticesChanged=!1,a=0;for(var o=0,h=t.vertexCount;o<h;o++)if(Math.abs(this._boundaryVertices[a++]-t.boundaryVertices[o].x)>se||Math.abs(this._boundaryVertices[a++]-t.boundaryVertices[o].y)>se||Math.abs(this._boundaryVertices[a++]-t.boundaryVertices[o].z)>se){this._boundaryVerticesChanged=!0;break}}if(this._boundaryVerticesChanged)if(this._useGeomArrays)this._boundaryVertices.set(t.boundaryVertices);else{a=0;for(let e of t.boundaryVertices)this._boundaryVertices[a++]=e.x,this._boundaryVertices[a++]=e.y,this._boundaryVertices[a++]=e.z}if(this._vertexNormalsChanged){a=0;for(o=0;o<t.vertexCount;o++)this._vertexNormals[a++]=i,this._vertexNormals[a++]=s,this._vertexNormals[a++]=n}}}class Ie{static decodeLength(e){return e.length/4*3}static decodeArrayBuffer(e,t){var r=e.length/4*3;return t&&t.byteLength==r||(t=new ArrayBuffer(r)),this.decode(e,t),t}static removePaddingChars(e){return 64==this._keyStr.indexOf(e.charAt(e.length-1))?e.substring(0,e.length-1):e}static decode(e,t){e=this.removePaddingChars(e),e=this.removePaddingChars(e);var r,i,s,n,a,o,h,l=parseInt(e.length/4*3,10),c=0,d=0;for(r=t?new Uint8Array(t):new Uint8Array(l),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),c=0;c<l;c+=3)i=this._keyStr.indexOf(e.charAt(d++))<<2|(a=this._keyStr.indexOf(e.charAt(d++)))>>4,s=(15&a)<<4|(o=this._keyStr.indexOf(e.charAt(d++)))>>2,n=(3&o)<<6|(h=this._keyStr.indexOf(e.charAt(d++))),r[c]=i,64!=o&&(r[c+1]=s),64!=h&&(r[c+2]=n);return r}static encode(e){var t="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=e;e instanceof ArrayBuffer?i=new Uint8Array(arrayBuffer):e instanceof ImageData&&(i=e.data);for(var s,n=e.length,a=n%3,o=n-a,h=0;h<o;h+=3)t+=r[(16515072&(s=i[h]<<16|i[h+1]<<8|i[h+2]))>>18]+r[(258048&s)>>12]+r[(4032&s)>>6]+r[63&s];return 1==a?t+=r[(252&(s=i[o]))>>2]+r[(3&s)<<4]+"==":2==a&&(t+=r[(64512&(s=i[o]<<8|i[o+1]))>>10]+r[(1008&s)>>4]+r[(15&s)<<2]+"="),t}}Ie._keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";var Te=[];class Se{constructor(e,t,r,i){this._buffers=e;for(var s=0;s<e.length;s++)if(e[s]._buffer=e[s].buffer,e[s].buffer=null,e[s]._abCache||"string"!=typeof e[s]._buffer){if(!e[s]._abCache&&e[s]._buffer instanceof ImageData){var n=e[s]._buffer.data;for(l=n.length,c=0;c<Te.length;c++)if(Te[c].byteLength==l){e[s]._abCache=Te[c],Te.splice(c,1);break}var a=e[s]._abCache?e[s]._abCache:new ArrayBuffer(l);e[s]._abCache=null;for(var o=new Uint8Array(a),h=0;h<l;h++)o[h]=n[h];e[s]._buffer=a}}else for(var l=Ie.decodeLength(e[s]._buffer),c=0;c<Te.length;c++)if(Te[c].byteLength==l){e[s]._abCache=Te[c],Te.splice(c,1);break}this._pixelFormat=t,this._timestamp=r,this._camera=i}static createFromMessage(e){return new this(e.data.buffers,e.data.pixelFormat,e.data.timestamp,e.data.camera)}numBuffers(){this._buffers.length}buffer(e){if(e>=0&&e<this._buffers.length){var t=this._buffers[e];return t.buffer||("string"==typeof t._buffer?(t._buffer=Ie.decodeArrayBuffer(t._buffer,t._abCache),t._abCache=null,t.buffer=new Uint8Array(t._buffer)):t._buffer instanceof ArrayBuffer?t.buffer=new Uint8Array(t._buffer):t._buffer instanceof ImageData&&(t.buffer=ImageData.data)),t}return null}get pixelFormat(){return this._pixelFormat}get timestamp(){return this._timestamp}get camera(){return this._camera}release(){for(var e=this._buffers,t=0;t<e.length;t++)e[t]._buffer instanceof ArrayBuffer&&e[t]._buffer.byteLength>0&&Te.push(e[t]._buffer),e[t]._abCache instanceof ArrayBuffer&&e[t]._abCache.byteLength>0&&Te.push(e[t]._abCache)}postMessageToWorker(e,t){var r=Object.assign({},t||{});r.buffers=this._buffers,r.timestamp=this._timestamp,r.pixelFormat=this._pixelFormat,r.camera=this._camera;for(var i=[],s=0;s<r.buffers.length;s++)r.buffers[s].buffer=r.buffers[s]._buffer,(r.buffers[s]._buffer instanceof ArrayBuffer||r.buffers[s]._buffer instanceof ImageData)&&i.push(r.buffers[s]._buffer),r.buffers[s]._buffer=null,r.buffers[s]._abCache instanceof ArrayBuffer&&i.push(r.buffers[s]._abCache);e.postMessage(r,i)}postReplyMessage(e){var t=Object.assign({},e);t.buffers=this._buffers,t.timestamp=this._timestamp,t.pixelFormat=this._pixelFormat,t.camera=this._camera;for(var r=[],i=0;i<t.buffers.length;i++)t.buffers[i].buffer=null,(t.buffers[i]._buffer instanceof ArrayBuffer||t.buffers[i]._buffer instanceof ImageData)&&(r.push(t.buffers[i]._buffer),t.buffers[i].buffer=t.buffers[i]._buffer),t.buffers[i]._buffer=null,t.buffers[i]._abCache instanceof ArrayBuffer&&r.push(t.buffers[i]._abCache);postMessage(t,r)}}Se.IMAGEFORMAT_RGBA32="RGBA32",Se.IMAGEFORMAT_BGRA32="BGRA32",Se.IMAGEFORMAT_RGB24="RGB24",Se.IMAGEFORMAT_BGR24="BGR24",Se.IMAGEFORMAT_GRAY8="GRAY8",Se.IMAGEFORMAT_YUV444P="YUV444P",Se.IMAGEFORMAT_YUV422P="YUV422P",Se.IMAGEFORMAT_YUV420P="YUV420P",Se.IMAGEFORMAT_YUV420SP_NV12="YUV420SP_NV12",Se.IMAGEFORMAT_YUV420SP_NV21="YUV420SP_NV21",Se.IMAGEFORMAT_HSV="HSV",Se.IMAGEFORMAT_Lab="Lab",Se.IMAGEFORMAT_DEPTH="DEPTH",Se.IMAGEFORMAT_NULL="",Se.IMAGEFORMAT=[Se.IMAGEFORMAT_RGBA32,Se.IMAGEFORMAT_BGRA32,Se.IMAGEFORMAT_RGB24,Se.IMAGEFORMAT_BGR24,Se.IMAGEFORMAT_GRAY8,Se.IMAGEFORMAT_YUV444P,Se.IMAGEFORMAT_YUV422P,Se.IMAGEFORMAT_YUV420P,Se.IMAGEFORMAT_YUV420SP_NV12,Se.IMAGEFORMAT_YUV420SP_NV21,Se.IMAGEFORMAT_HSV,Se.IMAGEFORMAT_Lab,Se.IMAGEFORMAT_DEPTH,Se.IMAGEFORMAT_NULL];var Ce={XRAnchor:fe,XRAnchorOffset:ge,XRFaceMesh:ve,XRHitResult:Ee,XRImageAnchor:Ae,XRLightEstimate:Re,XRMesh:we,XRPlaneMesh:xe,XRVideoFrame:Se};class Oe extends r{constructor(e){super(),this.global=e,this.onWindowResize=this.onWindowResize.bind(this),this.global.window.addEventListener("resize",this.onWindowResize),this.environmentBlendMode="opaque"}get depthNear(){throw new Error("Not implemented")}set depthNear(e){throw new Error("Not implemented")}get depthFar(){throw new Error("Not implemented")}set depthFar(e){throw new Error("Not implemented")}onBaseLayerSet(e,t){throw new Error("Not implemented")}supportsSession(e={}){throw new Error("Not implemented")}async requestSession(e={}){throw new Error("Not implemented")}requestAnimationFrame(e){throw new Error("Not implemented")}onFrameStart(e){throw new Error("Not implemented")}onFrameEnd(e){throw new Error("Not implemented")}requestStageBounds(){throw new Error("Not implemented")}async requestFrameOfReferenceTransform(e,t){}cancelAnimationFrame(e){throw new Error("Not implemented")}endSession(e){throw new Error("Not implemented")}getViewport(e,t,r,i){throw new Error("Not implemented")}getProjectionMatrix(e){throw new Error("Not implemented")}getBasePoseMatrix(){throw new Error("Not implemented")}getBaseViewMatrix(e){throw new Error("Not implemented")}getInputSources(){throw new Error("Not implemented")}getInputPose(e,t){throw new Error("Not implemented")}onWindowResize(){this.onWindowResize()}}let Pe=function(e,t,r=!0,i=!0){var s,n,a,o,h=0,l=function(){h=!1===r?0:Date.now(),s=null,o=e.apply(n,a),s||(n=a=null)},c=function(){var c=Date.now();h||!1!==r||(h=c);var d=t-(c-h);return n=this,a=arguments,d<=0||d>t?(s&&(clearTimeout(s),s=null),h=c,o=e.apply(n,a),s||(n=a=null)):s||!1===i||(s=setTimeout(l,d)),o};return c.cancel=function(){clearTimeout(s),h=0,s=n=a=null},c};Pe(function(...e){console.log(...e)},1e3);const Ne=Math.PI/180;class De extends r{constructor(){if(super(),!1===De.HasARKit())throw new Error("ARKitWrapper will only work in Mozilla's ARDemo test app");if(void 0!==De.GLOBAL_INSTANCE)throw new Error("ARKitWrapper is a singleton. Use ARKitWrapper.GetOrCreate() to get the global instance.");this._timestamp=0,this._lightIntensity=new Re,this._deviceId=null,this._isWatching=!1,this._waitingForSessionStart=!1,this._isInitialized=!1,this._rawARData=null,this._rAF_callback=null,this._rAF_callbackParams=[],this._requestedPermissions={cameraAccess:!1,worldAccess:!1},this._currentPermissions={cameraAccess:!1,worldAccess:!1},this._worldSensingState={illuminationDetectionState:!1,meshDetectionState:!1},this._worldInformation=null,this._projectionMatrix=new Float32Array(16),this._viewMatrix=new Float32Array(16),this._cameraTransform=new Float32Array(16),this._anchors=new Map,this._anchorOffsets=new Map,this._timeOffsets=[],this._timeOffset=0,this._timeOffsetComputed=!1,this._dataBeforeNext=0,this._worldMappingStatus=De.WEB_AR_WORLDMAPPING_NOT_AVAILABLE,this._globalCallbacksMap={};let e=["onInit","onData"];for(let t=0;t<e.length;t++)this._generateGlobalCallback(e[t],t);this._defaultOptions={location:!0,camera:!0,objects:!0,light_intensity:!0,computer_vision_data:!1},this._m90=de(ae(),90*Ne),this._m90neg=de(ae(),-90*Ne),this._m180=de(ae(),180*Ne),this._mTemp=ae();let t=[["arkitStartRecording",De.RECORD_START_EVENT],["arkitStopRecording",De.RECORD_STOP_EVENT],["arkitDidMoveBackground",De.DID_MOVE_BACKGROUND_EVENT],["arkitWillEnterForeground",De.WILL_ENTER_FOREGROUND_EVENT],["arkitInterrupted",De.INTERRUPTED_EVENT],["arkitInterruptionEnded",De.INTERRUPTION_ENDED_EVENT],["arkitShowDebug",De.SHOW_DEBUG_EVENT],["arkitWindowResize",De.WINDOW_RESIZE_EVENT],["onError",De.ON_ERROR],["arTrackingChanged",De.AR_TRACKING_CHANGED]];for(let e=0;e<t.length;e++)window[t[e][0]]=(r=>{r=r||null;try{this.dispatchEvent(t[e][1],new CustomEvent(t[e][1],{source:this,detail:r}))}catch(r){console.error(t[e][0]+" callback error",r)}});window.onComputerVisionData=(e=>{this._onComputerVisionData(e)}),window.setNativeTime=(e=>{this._timeOffsets.push((performance||Date).now()-e.nativeTime),this._timeOffsetComputed=!0,this._timeOffset=0;for(var t=0;t<this._timeOffsets.length;t++)this._timeOffset+=this._timeOffsets[t];this._timeOffset=this._timeOffset/this._timeOffsets.length}),window.userGrantedComputerVisionData=(e=>{this._sessionCameraAccess|=e.granted}),window.userGrantedWorldSensingData=(e=>{this._sessionWorldAccess|=e.granted})}static GetOrCreate(e=null){if(void 0===De.GLOBAL_INSTANCE){De.GLOBAL_INSTANCE=new De;let t={browser:!0,points:!0,focus:!1,rec:!0,rec_time:!0,mic:!1,build:!1,plane:!0,warnings:!0,anchors:!1,debug:!0,statistics:!1},r="object"==typeof(e=e&&"object"==typeof e?e:{}).ui?e.ui:{};e.ui=Object.assign(t,r),e.geometry_arrays=!0,we.setUseGeomArrays(),De.GLOBAL_INSTANCE._sendInit(e)}return De.GLOBAL_INSTANCE}static HasARKit(){return void 0!==window.webkit}get deviceId(){return this._deviceId}get hasSession(){return this._isWatching}get isInitialized(){return this._isInitialized}_sendInit(e){console.log("----INIT"),window.webkit.messageHandlers.initAR.postMessage({options:e,callback:this._globalCallbacksMap.onInit})}waitForInit(){return new Promise((e,t)=>{if(this._isInitialized)return void e();const r=()=>{this.removeEventListener(De.INIT_EVENT,r,!1),e()};this.addEventListener(De.INIT_EVENT,r,!1)})}_onInit(e){this._deviceId=e,this._isInitialized=!0;try{this.dispatchEvent(De.INIT_EVENT,new CustomEvent(De.INIT_EVENT,{source:this}))}catch(e){console.error("INIT_EVENT event error",e)}}hitTest(e,t,r=De.HIT_TEST_TYPE_ALL){return new Promise((i,s)=>{this._isInitialized?window.webkit.messageHandlers.hitTest.postMessage({x:e,y:t,type:r,callback:this._createPromiseCallback("hitTest",i)}):s(new Error("ARKit is not initialized"))})}pickBestHit(e){if(0===e.length)return null;let t=e.filter(e=>e.type!=De.HIT_TEST_TYPE_FEATURE_POINT),r=t.filter(e=>e.type==De.HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT),i=t.filter(e=>e.type==De.HIT_TEST_TYPE_EXISTING_PLANE);return r.length?(r=r.sort((e,t)=>e.distance-t.distance))[0]:i.length?(i=i.sort((e,t)=>e.distance-t.distance))[0]:t.length?(t=t.sort((e,t)=>e.distance-t.distance))[0]:e[0]}_addAnchor(e,t){return new Promise((r,i)=>{this._isInitialized?window.webkit.messageHandlers.addAnchor.postMessage({uuid:e,transform:t,callback:this._createPromiseCallback("addAnchor",r)}):i(new Error("ARKit is not initialized"))})}createAnchor(e){return new Promise((t,r)=>{var i=new fe(e,null,this._timestamp);this._addAnchor(i.uid,e).then(e=>{if(e.error)r(e.error);else{var s=this._anchors.get(e.uuid);s?(s.placeholder=!1,s.deleted=!1,s.updateModelMatrix(e.transform,this._timestamp),t(s)):(this._anchors.set(e.uuid,i),t(i))}}).catch((...e)=>{console.error("could not create anchor",...e),r()})})}createAnchorFromHit(e){return new Promise((t,r)=>{if(e.anchor_transform){let r=this._anchors.get(e.uuid);r||(r=new fe(e.anchor_transform,e.uuid,this._timestamp),console.log("created dummy anchor from hit test"),r.placeholder=!0,this._anchors.set(e.uuid,r)),t(new ge(r,e.local_transform))}else{let r=this._anchors.get(e.uuid);r?(r.placeholder=!1,r.deleted=!1,console.log("hit test resulted in a hit on an existing anchor, without an offset")):(r=new fe(e.world_transform,e.uuid),console.log("created dummy anchor (not a plane) from hit test"),r.placeholder=!0,this._anchors.set(e.uuid,r)),t(r)}})}removeAnchor(e){let t=this._anchors.get(e.uid);t.placeholder?this._anchors.delete(e.uid):(t&&(t.deleted=!0),!e instanceof ge&&window.webkit.messageHandlers.removeAnchors.postMessage([e.uid]))}_createDetectionImage(e,t,r,i,s){return new Promise((n,a)=>{if(!this._isInitialized)return void a(new Error("ARKit is not initialized"));let o=Ie.encode(t);window.webkit.messageHandlers.createImageAnchor.postMessage({uid:e,buffer:o,imageWidth:r,imageHeight:i,physicalWidth:s,callback:this._createPromiseCallback("createImageAnchor",n)})})}createDetectionImage(e,t,r,i,s){return new Promise((n,a)=>{this._createDetectionImage(e,t,r,i,s).then(e=>{e.error?a(e.error):e.created?n():a(null)}).catch((...e)=>{console.error("could not create image",...e),a()})})}_destroyDetectionImage(e){return new Promise((t,r)=>{this._isInitialized?window.webkit.messageHandlers.destroyImageAnchor.postMessage({uid:e,callback:this._createPromiseCallback("destroyImageAnchor",t)}):r(new Error("ARKit is not initialized"))})}destroyDetectionImage(e){return new Promise((t,r)=>{this._destroyDetectionImage(e).then(e=>{e.error?r(e.error):t()}).catch((...e)=>{console.error("could not destroy image",...e),r()})})}_activateDetectionImage(e,t=!1){return new Promise((r,i)=>{this._isInitialized?window.webkit.messageHandlers.activateDetectionImage.postMessage({uid:e,trackable:t,callback:this._createPromiseCallback("activateDetectionImage",r)}):i(new Error("ARKit is not initialized"))})}activateDetectionImage(e,t=!1){return new Promise((r,i)=>{var s=this._anchors.get(e);!s||s.deleted?this._activateDetectionImage(e,t).then(e=>{e.error&&i(e.error),e.activated?(this._createOrUpdateAnchorObject(e.imageAnchor),e.imageAnchor.object.deleted=!1,r(e.imageAnchor.object)):i(null)}).catch((...e)=>{console.error("could not activate image",...e),i()}):r(s)})}_deactivateDetectionImage(e){return new Promise((t,r)=>{this._isInitialized?window.webkit.messageHandlers.deactivateDetectionImage.postMessage({uid:e,callback:this._createPromiseCallback("deactivateDetectionImage",t)}):r(new Error("ARKit is not initialized"))})}deactivateDetectionImage(e){return new Promise((t,r)=>{this._deactivateDetectionImage(e).then(i=>{i.error&&r(i.error);var s=this._anchors.get(e);s&&(console.warn("anchor for image target '"+e+"' still exists after deactivation"),removeAnchor(s)),t()}).catch((...e)=>{console.error("could not activate image",...e),r()})})}setNumberOfTrackedImages(e){"number"!=typeof e&&(e=0),window.webkit.messageHandlers.setNumberOfTrackedImages.postMessage({numberOfTrackedImages:e})}_getWorldMap(){return new Promise((e,t)=>{this._isInitialized?window.webkit.messageHandlers.getWorldMap.postMessage({callback:this._createPromiseCallback("getWorldMap",e)}):t(new Error("ARKit is not initialized"))})}getWorldMap(){return new Promise((e,t)=>{this._getWorldMap().then(r=>{if(!0!==r.saved)return null!==r.error?void t(r.error):void t(null);e(r.worldMap)}).catch((...e)=>{console.error("could not get world map",...e),t()})})}setWorldMap(e){return new Promise((t,r)=>{this._isInitialized?window.webkit.messageHandlers.setWorldMap.postMessage({worldMap:e.worldMap,callback:this._createPromiseCallback("setWorldMap",t)}):r(new Error("ARKit is not initialized"))})}stop(){return new Promise((e,t)=>{this._isWatching?(console.log("----STOP"),window.webkit.messageHandlers.stopAR.postMessage({callback:this._createPromiseCallback("stop",e)})):e()})}watch(e=null){return new Promise((t,r)=>{if(!this._isInitialized)return void r("ARKitWrapper hasn't been initialized yet");if(this._waitingForSessionStart)return void r("ARKitWrapper startSession called, waiting to finish");if(this._isWatching)return void t({cameraAccess:this._sessionCameraAccess,worldAccess:this._sessionWorldAccess,webXRAccess:!0});this._waitingForSessionStart=!0;var i=Object.assign({},this._defaultOptions);null!=e&&(i=Object.assign(i,e)),this._requestedPermissions.cameraAccess=i.videoFrames,this._requestedPermissions.worldAccess=i.worldSensing,i.videoFrames&&(delete i.videoFrames,i.computer_vision_data=!0);const s={options:i,callback:this._createPromiseCallback("requestSession",e=>{e.webXRAccess?(this._waitingForSessionStart=!1,this._isWatching=!0,this._currentPermissions.cameraAccess=e.cameraAccess,this._currentPermissions.worldAccess=e.worldAccess,t(e)):r("user did not give permission to start a webxr session")}),data_callback:this._globalCallbacksMap.onData};console.log("----WATCH"),window.webkit.messageHandlers.requestSession.postMessage(s)})}setUIOptions(e){window.webkit.messageHandlers.setUIOptions.postMessage(e)}_createOrUpdateAnchorObject(e){var t;if(e.plane_center)if(!(t=this._anchors.get(e.uuid))||t.placeholder){var r=new xe(e.transform,e.plane_center,[e.plane_extent.x,e.plane_extent.z],e.plane_alignment,e.geometry,e.uuid,this._timestamp);if(t){try{t.dispatchEvent("replaceAnchor",new CustomEvent("replaceAnchor",{source:t,detail:r}))}catch(e){console.error("replaceAnchor event error",e)}console.log("replaced dummy anchor created from hit test with plane"),this._anchors.delete(e.uuid)}this._anchors.set(e.uuid,r),e.object=r}else t&&(t.updatePlaneData(e.transform,e.plane_center,[e.plane_extent.x,e.plane_extent.y],e.plane_alignment,e.geometry,this._timestamp),e.object=t);else if(!(t=this._anchors.get(e.uuid))||t.placeholder){let r;switch(e.type){case De.ANCHOR_TYPE_FACE:r=new ve(e.transform,e.geometry,e.blendShapes,e.uuid,this._timestamp);break;case De.ANCHOR_TYPE_ANCHOR:r=new fe(e.transform,e.uuid,this._timestamp);break;case De.ANCHOR_TYPE_IMAGE:r=new Ae(e.transform,e.uuid,this._timestamp)}if(t){try{t.dispatchEvent("replaceAnchor",new CustomEvent("replaceAnchor",{source:t||mesh,detail:r}))}catch(e){console.error("replaceAnchor event error",e)}console.log("replaced dummy anchor created from hit test with new anchor")}this._anchors.set(e.uuid,r),e.object=r}else{switch(t=t,e.type){case De.ANCHOR_TYPE_FACE:t.updateFaceData(e.transform,e.geometry,e.blendShapes,this._timestamp);break;default:t.updateModelMatrix(e.transform,this._timestamp)}e.object=t}}updateWorldSensingState(e){return e.hasOwnProperty("illuminationDetectionState")&&this._currentPermissions.worldAccess?this._worldSensingState.illuminationDetectionState=e.illuminationDetectionState.enabled||!1:this._worldSensingState.illuminationDetectionState=!1,e.hasOwnProperty("meshDetectionState")&&this._currentPermissions.worldAccess?this._worldSensingState.meshDetectionState=e.meshDetectionState.enabled||!1:this._worldSensingState.meshDetectionState=!1,this._worldSensingState}getWorldInformation(){if(this._worldInformation)return this._worldInformation;let e={};return this._worldSensingState.illuminationDetectionState&&(e.estimatedLight=this._lightIntensity),this._worldSensingState.meshDetectionState&&(e.meshes=[],this._anchors.forEach(t=>{!t.isMesh()||t.deleted||t.placeholder||e.meshes.push(t)})),this._worldInformation=e,e}get hasData(){return null!==this._rawARData}_getData(e=null){return e?this._rawARData&&void 0!==this._rawARData[e]?this._rawARData[e]:null:this._rawARData}requestAnimationFrame(e,...t){this._rAF_callback=e,this._rAF_callbackParams=t}_do_rAF(){if(this._rAF_callback){var e=this._rAF_callback,t=this._rAF_callbackParams;return this._rAF_callback=null,this._rAF_callbackParams=[],window.requestAnimationFrame((...r)=>{this.startingRender();try{e(...t)}catch(e){console.error("application callback error: ",e)}this.finishedRender()})}}finishedRender(){this._dataBeforeNext=0,this._anchors.forEach(e=>{e.clearChanged()})}startingRender(){this._dataBeforeNext}_onData(e){if(this._rawARData=e,this._worldInformation=null,this._timestamp=this._adjustARKitTime(e.timestamp),this._lightIntensity.ambientIntensity=e.light_intensity,he(this._cameraTransform,e.camera_transform),he(this._viewMatrix,e.camera_view),he(this._projectionMatrix,e.projection_camera),this._worldMappingStatus=e.worldMappingStatus,e.newObjects.length)for(let r=0;r<e.newObjects.length;r++){const i=e.newObjects[r];var t;(t=this._anchors.get(i.uuid))&&t.deleted&&(t.deleted=!1),this._createOrUpdateAnchorObject(i)}if(e.removedObjects.length)for(let t=0;t<e.removedObjects.length;t++){const r=e.removedObjects[t],i=this._anchors.get(r);i?(i.notifyOfRemoval(),this._anchors.delete(r)):console.error("app signalled removal of non-existant anchor/plane")}if(e.objects.length)for(let t=0;t<e.objects.length;t++){const r=e.objects[t];this._createOrUpdateAnchorObject(r)}try{this.dispatchEvent(De.WATCH_EVENT,new CustomEvent(De.WATCH_EVENT,{source:this,detail:this}))}catch(e){console.error("WATCH_EVENT event error",e)}this._rAF_callback&&this._do_rAF(),this._dataBeforeNext++}_onStop(){this._isWatching=!1}_adjustARKitTime(e){return this._timeOffsetComputed?e+this._timeOffset:(performance||Date).now()}_createPromiseCallback(e,t){const r=this._generateCallbackUID(e);return window[r]=(i=>{delete window[r];const s="_on"+e[0].toUpperCase()+e.slice(1);"function"==typeof this[s]&&this[s](i),t(i)}),r}_generateCallbackUID(e){return"arkitCallback_"+e+"_"+(new Date).getTime()+"_"+Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)}_generateGlobalCallback(e,t){const r="arkitCallback"+t;this._globalCallbacksMap[e]=r;const i=this;window[r]=function(t){i["_"+e](t)}}_onComputerVisionData(e){if(!e)return console.error("detail passed to _onComputerVisionData is null"),void this._requestComputerVisionData();if(!e.frame||!e.frame.buffers||e.frame.buffers.length<=0)return console.error("detail passed to _onComputerVisionData is bad, no buffers"),void this._requestComputerVisionData();e.camera.arCamera=!0;var t=e.camera.interfaceOrientation;switch(e.camera.viewMatrix=e.camera.inverse_viewMatrix,t){case 1:e.camera.cameraOrientation=-90;break;case 2:e.camera.cameraOrientation=90;break;case 3:e.camera.cameraOrientation=0;break;case 4:e.camera.cameraOrientation=180}switch(e.frame.pixelFormatType){case"kCVPixelFormatType_420YpCbCr8BiPlanarFullRange":e.frame.pixelFormat="YUV420P";break;default:e.frame.pixelFormat=e.frame.pixelFormatType}var r=new Se(e.frame.buffers,e.frame.pixelFormat,this._adjustARKitTime(e.frame.timestamp),e.camera);try{this.dispatchEvent(De.COMPUTER_VISION_DATA,new CustomEvent(De.COMPUTER_VISION_DATA,{source:this,detail:r}))}catch(e){console.error("COMPUTER_VISION_DATA event error",e)}}_requestComputerVisionData(){window.webkit.messageHandlers.requestComputerVisionData.postMessage({})}_startSendingComputerVisionData(){window.webkit.messageHandlers.startSendingComputerVisionData.postMessage({})}_stopSendingComputerVisionData(){window.webkit.messageHandlers.stopSendingComputerVisionData.postMessage({})}}De.INIT_EVENT="arkit-init",De.WATCH_EVENT="arkit-watch",De.RECORD_START_EVENT="arkit-record-start",De.RECORD_STOP_EVENT="arkit-record-stop",De.DID_MOVE_BACKGROUND_EVENT="arkit-did-move-background",De.WILL_ENTER_FOREGROUND_EVENT="arkit-will-enter-foreground",De.INTERRUPTED_EVENT="arkit-interrupted",De.INTERRUPTION_ENDED_EVENT="arkit-interruption-ended",De.SHOW_DEBUG_EVENT="arkit-show-debug",De.WINDOW_RESIZE_EVENT="arkit-window-resize",De.ON_ERROR="on-error",De.AR_TRACKING_CHANGED="ar_tracking_changed",De.COMPUTER_VISION_DATA="cv_data",De.USER_GRANTED_COMPUTER_VISION_DATA="user-granted-cv-data",De.USER_GRANTED_WORLD_SENSING_DATA="user-granted-world-sensing-data",De.ORIENTATION_UP=1,De.ORIENTATION_UP_MIRRORED=2,De.ORIENTATION_DOWN=3,De.ORIENTATION_DOWN_MIRRORED=4,De.ORIENTATION_LEFT_MIRRORED=5,De.ORIENTATION_RIGHT=6,De.ORIENTATION_RIGHT_MIRRORED=7,De.ORIENTATION_LEFT=8,De.WEB_AR_WORLDMAPPING_NOT_AVAILABLE="ar_worldmapping_not_available",De.WEB_AR_WORLDMAPPING_LIMITED="ar_worldmapping_limited",De.WEB_AR_WORLDMAPPING_EXTENDING="ar_worldmapping_extending",De.WEB_AR_WORLDMAPPING_MAPPED="ar_worldmapping_mapped",De.HIT_TEST_TYPE_FEATURE_POINT=1,De.HIT_TEST_TYPE_ESTIMATED_HORIZONTAL_PLANE=2,De.HIT_TEST_TYPE_ESTIMATED_VERTICAL_PLANE=4,De.HIT_TEST_TYPE_EXISTING_PLANE=8,De.HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT=16,De.HIT_TEST_TYPE_EXISTING_PLANE_USING_GEOMETRY=32,De.HIT_TEST_TYPE_ALL=De.HIT_TEST_TYPE_FEATURE_POINT|De.HIT_TEST_TYPE_EXISTING_PLANE|De.HIT_TEST_TYPE_ESTIMATED_HORIZONTAL_PLANE|De.HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT,De.HIT_TEST_TYPE_EXISTING_PLANES=De.HIT_TEST_TYPE_EXISTING_PLANE|De.HIT_TEST_TYPE_EXISTING_PLANE_USING_EXTENT,De.ANCHOR_TYPE_PLANE="plane",De.ANCHOR_TYPE_FACE="face",De.ANCHOR_TYPE_ANCHOR="anchor",De.ANCHOR_TYPE_IMAGE="image";class Fe{constructor(e){this._subscribed=!1,this._arKitWrapper=e,this.subscribe()}subscribe(){this._subscribed||(this._subscribed=!0,this._arKitWrapper.addEventListener(De.INIT_EVENT,this.handleARKitInit.bind(this)),this._arKitWrapper.addEventListener(De.WATCH_EVENT,this.handleARKitUpdate.bind(this)),this._arKitWrapper.addEventListener(De.WINDOW_RESIZE_EVENT,this.handleARKitWindowResize.bind(this)),this._arKitWrapper.addEventListener(De.ON_ERROR,this.handleOnError.bind(this)),this._arKitWrapper.addEventListener(De.AR_TRACKING_CHANGED,this.handleArTrackingChanged.bind(this)),this._arKitWrapper.addEventListener(De.COMPUTER_VISION_DATA,this.handleComputerVisionData.bind(this)))}handleARKitInit(){}handleARKitUpdate(){}handleARKitWindowResize(){}handleOnError(){}handleArTrackingChanged(){}handleComputerVisionData(){}}class Le extends Oe{constructor(e){super(e),this._throttledLogPose=Pe(this.logPose,1e3),this._sessions=new Map,this._activeSession=null,this._wrapperDiv=document.createElement("div"),this._wrapperDiv.setAttribute("class","arkit-device-wrapper"),document.addEventListener("DOMContentLoaded",e=>{document.body.insertBefore(this._wrapperDiv,document.body.firstChild||null)}),this._headModelMatrix=ae(),this._projectionMatrix=ae(),this._eyeLevelMatrix=le(ae()),this._stageMatrix=le(ae()),this._stageMatrix[13]=-1.3,this._baseFrameSet=!1,this._frameOfRefRequestsWaiting=[],this._depthNear=.1,this._depthFar=1e3;try{this._arKitWrapper=De.GetOrCreate(),this._arWatcher=new Ge(this._arKitWrapper,this)}catch(e){console.error("Error initializing the ARKit wrapper",e),this._arKitWrapper=null,this._arWatcher=null}}static initStyles(){window.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{try{var e=document.createElement("style");document.head.appendChild(e);var t=e.sheet;t.insertRule(".arkit-device-wrapper { z-index: -1; }",0),t.insertRule(".arkit-device-wrapper, .xr-canvas { position: absolute; top: 0; left: 0; bottom: 0; right: 0; }",0),t.insertRule(".arkit-device-wrapper, .arkit-device-wrapper canvas { width: 100%; height: 100%; padding: 0; margin: 0; -webkit-user-select: none; user-select: none; }",0)}catch(e){console.error("page error",e)}},1)})}get depthNear(){return this._depthNear}set depthNear(e){this._depthNear=e}get depthFar(){return this._depthFar}set depthFar(e){this._depthFar=e}supportsSession(e={}){return!e.hasOwnProperty("immersive")||!e.immersive}async requestSession(e={}){if(!this.supportsSession(e))return console.error("Invalid session options",e),Promise.reject();if(!this._arKitWrapper)return console.error("Session requested without an ARKitWrapper"),Promise.reject();if(null!==this._activeSession)return console.error("Tried to start a second active session"),Promise.reject();var t={};e.hasOwnProperty("worldSensing")&&(t.worldSensing=e.worldSensing),e.hasOwnProperty("computerVision")&&(t.videoFrames=e.useComputerVision),e.hasOwnProperty("alignEUS")&&(t.alignEUS=e.alignEUS);await this._arKitWrapper.waitForInit().then(()=>{}).catch((...e)=>(console.error("app failed to initialize: ",...e),Promise.reject()));return await this._arKitWrapper.watch(t).then(t=>{const r=new Ve(e.outputContext||null);return this._sessions.set(r.id,r),this._activeSession=r,Promise.resolve(r.id)}).catch((...e)=>(console.error("session request failed: ",...e),Promise.reject()))}onBaseLayerSet(e,t){this._sessions.get(e).baseLayer=t,this._wrapperDiv.appendChild(t.context.canvas),t.context.canvas.style.width="100%",t.context.canvas.style.height="100%"}requestAnimationFrame(e,...t){this._arKitWrapper.requestAnimationFrame(e,t)}cancelAnimationFrame(e){return window.cancelAnimationFrame(e)}onFrameStart(e){}onFrameEnd(e){}logPose(){console.log("pose",ue(new Float32Array(3),this._headModelMatrix),me(new Float32Array(4),this._headModelMatrix))}requestFrameOfReferenceTransform(e,t){var r=this;return new Promise((t,i)=>{let s=function(e){r._baseFrameSet?e():r._frameOfRefRequestsWaiting.push(e)};switch(e){case"head-model":return void s(function(){t(r._headModelMatrix)});case"eye-level":return void s(function(){t(r._eyeLevelMatrix)});case"stage":i(new Error("stage not supported",e));default:i(new Error("Unsupported frame of reference type",e))}})}endSession(e){const t=this._sessions.get(e);t&&!t.ended&&(t.ended=!0,this._activeSession===t&&(this._activeSession=null,this._arKitWrapper.stop()),null!==t.baseLayer&&this._wrapperDiv.removeChild(t.baseLayer.context.canvas))}getViewport(e,t,r,i){const{offsetWidth:s,offsetHeight:n}=r.context.canvas;return i.x=0,i.y=0,i.width=s,i.height=n,!0}getProjectionMatrix(e){return this._projectionMatrix}setProjectionMatrix(e){he(this._projectionMatrix,e)}getBasePoseMatrix(){return this._headModelMatrix}getBaseViewMatrix(e){return this._headModelMatrix}setBaseViewMatrix(e){if(he(this._headModelMatrix,e),!this._baseFrameSet){this._baseFrameSet=!0;for(let e=0;e<this._frameOfRefRequestsWaiting.length;e++){const t=this._frameOfRefRequestsWaiting[e];try{t()}catch(e){console.error("finalization of reference frame requests failed: ",e)}}this._frameOfRefRequestsWaiting=[]}}requestStageBounds(){return null}getInputSources(){return[]}getInputPose(e,t){return null}onWindowResize(){this._sessions.forEach((e,t)=>{})}}let ke=100;class Ve{constructor(e){this.ended=null,this.outputContext=e,this.baseLayer=null,this.id=++ke}}class Ge extends Fe{constructor(e,t){super(e),this._arKitDevice=t}handleARKitUpdate(e){this._arKitDevice.setBaseViewMatrix(this._arKitWrapper._cameraTransform),this._arKitDevice.setProjectionMatrix(this._arKitWrapper._projectionMatrix)}handleOnError(...e){console.error("ARKit error",...e)}}const We=ae(),Xe=ae();ie.prototype._patchRequestDevice=function(){var e=new Le(this.global);this.xr=new XR(new XRDevice(e)),this.xr._mozillaXRViewer=!0,Object.defineProperty(this.global.navigator,"xr",{value:this.xr,configurable:!0})};let Ue=navigator.userAgent.indexOf("Mobile/");const Be=-1!==navigator.userAgent.indexOf("WebXRViewer")||(-1!==navigator.userAgent.indexOf("iPhone")||-1!==navigator.userAgent.indexOf("iPad"))&&-1!==Ue&&-1!==navigator.userAgent.indexOf("AppleWebKit")&&-1===navigator.userAgent.indexOf(" ",Ue)?new ie(null,{webvr:!1,cardboard:!1}):null;function je(e,t){return function(e,t,r){return function(e,t){let r=t[0],i=t[1],s=t[2],n=t[3],a=t[4],o=t[5],h=t[6],l=t[7],c=t[8],d=t[9],u=t[10],m=t[11],_=t[12],p=t[13],f=t[14],g=t[15],b=r*o-i*a,w=r*h-s*a,v=r*l-n*a,y=i*h-s*o,E=i*l-n*o,A=s*l-n*h,R=c*p-d*_,M=c*f-u*_,x=c*g-m*_,I=d*f-u*p,T=d*g-m*p,S=u*g-m*f,C=b*S-w*T+v*I+y*x-E*M+A*R;C&&(C=1/C,e[0]=(o*S-h*T+l*I)*C,e[1]=(s*T-i*S-n*I)*C,e[2]=(p*A-f*E+g*y)*C,e[3]=(u*E-d*A-m*y)*C,e[4]=(h*x-a*S-l*M)*C,e[5]=(r*S-s*x+n*M)*C,e[6]=(f*v-_*A-g*w)*C,e[7]=(c*A-u*v+m*w)*C,e[8]=(a*T-o*x+l*R)*C,e[9]=(i*x-r*T-n*R)*C,e[10]=(_*E-p*v+g*b)*C,e[11]=(d*v-c*E-m*b)*C,e[12]=(o*M-a*I-h*R)*C,e[13]=(r*I-i*M+s*R)*C,e[14]=(p*w-_*y-f*b)*C,e[15]=(c*y-d*w+u*b)*C)}(We,t),ce(r,e,We)}(this[S].transform,e[S].transform,t)}function He(e){return st.updateWorldSensingState(e)}function ze(){return st.getWorldInformation()}async function qe(e,t,r){return"head-model"!==r.type?Promise.reject("Only head-model hit testing is supported"):0!=e[0]&&0!=e[1]&&0!=e[2]?Promise.reject("Platform only supports hit testing with ray origin = [0,0,0]"):new Promise((e,i)=>{const s=function(e,t){var r=function(e,t,r){let i=t[0],s=t[1],n=t[2],a=r[3]*i+r[7]*s+r[11]*n+r[15];return a=a||1,e[0]=(r[0]*i+r[4]*s+r[8]*n+r[12])/a,e[1]=(r[1]*i+r[5]*s+r[9]*n+r[13])/a,e[2]=(r[2]*i+r[6]*s+r[10]*n+r[14])/a,e}(_e(),e,t);let i=(r[0]+1)/2,s=(1-r[1])/2;return[i,s]}(t,st._projectionMatrix);st.hitTest(...s,De.HIT_TEST_TYPE_EXISTING_PLANE_USING_GEOMETRY).then(t=>{0===t.length&&e([]),this.requestFrameOfReference("eye-level").then(i=>{i.getTransformTo(r,We),e(t.map(e=>(ce(Xe,We,e.world_transform),new Ee(Xe,e,st._timestamp))))}).catch((...e)=>{console.error("Error testing for hits",...e),i()})}).catch((...e)=>{console.error("Error testing for hits",...e),i()})})}async function Ke(e,t){return e instanceof Ee?st.createAnchorFromHit(e._hit):e instanceof Float32Array?new Promise((r,i)=>{this.requestFrameOfReference("eye-level").then(s=>{t.getTransformTo(s,We);const n=ce(ae(),We,e);st.createAnchor(n).then(e=>{r(e)}).catch((...e)=>{console.error("could not create anchor",...e),i()})}).catch((...e)=>{console.error("could not create eye-level frame of reference",...e),i()})}):Promise.reject("invalid value passed to addAnchor",e)}async function Ye(e){return new Promise((t,r)=>{st.removeAnchor(e),t()})}function Ze(e){return st.setNumberOfTrackedImages(e)}function $e(e,t,r,i,s){return st.createDetectionImage(e,t,r,i,s)}function Je(e){return st.createDetectionImage(e)}function Qe(e){return st.activateDetectionImage(e)}function et(e){return st.deactivateDetectionImage(e)}function tt(){return st.getWorldMap()}function rt(e){return st.setWorldMap(e)}function it(){return st._worldMappingStatus}var st=null;Be&&Be.injected&&function(){if(navigator.xr){st=De.GetOrCreate(),Le.initStyles(),window.XRSession&&(XRSession.prototype.requestHitTest=qe,XRSession.prototype.updateWorldSensingState=He,XRSession.prototype.addAnchor=Ke,XRSession.prototype.removeAnchor=Ye,XRSession.prototype.nonStandard_createDetectionImage=$e,XRSession.prototype.nonStandard_destroyDetectionImage=Je,XRSession.prototype.nonStandard_activateDetectionImage=Qe,XRSession.prototype.nonStandard_deactivateDetectionImage=et,XRSession.prototype.nonStandard_setNumberOfTrackedImages=Ze,XRSession.prototype.nonStandard_getWorldMap=tt,XRSession.prototype.nonStandard_setWorldMap=rt,XRSession.prototype.nonStandard_getWorldMappingStatus=it),window.XRFrame&&Object.defineProperty(XRFrame.prototype,"worldInformation",{get:ze}),window.XRFrameOfReference&&(XRFrameOfReference.prototype.getTransformTo=je);for(const e of Object.keys(Ce))void 0!==window[e]?console.warn(`${e} already defined on global.`):window[e]=Ce[e]}}()});