File size: 242,679 Bytes
3c5478f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./StereoEffect-BUunyfV9.js","./three-Bwrc_W3C.js","./rolldown-runtime-DK3Fl9T5.js"])))=>i.map(i=>d[i]);
import{n as e,r as t,t as n}from"./mediapipe-Ck-u_eH7.js";import{$ as r,A as i,B as a,C as o,D as s,E as c,F as l,G as u,H as d,I as f,J as p,K as m,L as h,M as g,N as _,O as ee,P as v,Q as y,R as b,S as te,T as ne,U as re,V as x,W as ie,X as S,Y as ae,Z as C,_ as oe,a as se,at as ce,b as le,c as ue,ct as de,d as fe,dt as w,et as pe,f as me,ft as he,g as ge,h as _e,ht as ve,i as ye,it as be,j as xe,k as Se,l as Ce,lt as we,m as Te,mt as Ee,nt as De,o as Oe,ot as ke,p as Ae,pt as je,q as Me,rt as Ne,s as Pe,st as Fe,tt as Ie,u as Le,ut as Re,v as ze,w as Be,x as Ve,y as He,z as Ue}from"./three-Bwrc_W3C.js";import{a as We,i as Ge,n as Ke,r as qe,t as Je}from"./physics-ZWohGOc1.js";var Ye=4;function Xe(e){return document.getElementById(e===`error`?`error-host`:`banner-host`)}function Ze(e,t,n,r={}){let i=Xe(e);if(!i)return null;let a=document.createElement(`section`);a.className=`${e===`error`?`error-panel`:`banner-panel`} glass-panel`;let o=document.createElement(`p`),s=document.createElement(`strong`);if(s.textContent=t,o.textContent=n,a.append(s,o),r.linkHref){let e=document.createElement(`a`);e.href=r.linkHref,e.textContent=r.linkLabel||`Open settings`,e.rel=`noopener`,e.style.display=`inline-block`,e.style.marginTop=`8px`,a.appendChild(e)}for(i.prepend(a);i.children.length>Ye;)i.lastElementChild?.remove();return r.timeout!==0&&window.setTimeout(()=>a.remove(),r.timeout||(e===`error`?9e3:4500)),a}function T(e,t=`AR Error`,n={}){return Ze(`error`,t,String(e||`Unknown AR error.`),n)}function E(e,t=`JARVIS AR`,n={}){return Ze(`banner`,t,String(e||``),n)}function D(e,t){let n=document.getElementById(e);n&&(n.textContent=String(t))}function O(e,t){let n=document.getElementById(`loading-text`),r=document.getElementById(`loading-progress`);n&&e&&(n.textContent=e),r&&Number.isFinite(t)&&(r.style.width=`${Math.max(0,Math.min(100,t))}%`)}function Qe(){document.getElementById(`loading-screen`)?.classList.add(`hidden`)}var k={config:null,started:!1,trackingMode:`standby`,xrAvailable:!1,xrStarted:!1,xrCamera:null,xrScene:null,scene:null,camera:null,renderer:null,aframeScene:null,aframeCamera:null,fallbackScene:null,fallbackCamera:null,fallbackRenderer:null,fallbackActive:!1,fallbackLoopHandle:0,cameraVideo:null,gestureFrameCanvas:null,gestureFrameReady:!1,worldPoints:[],worldPointBuffer:[],placedObjects:[],selectedObject:null,floorY:-1.2,pendingModelToPlace:``,css3d:null,pipelineOrder:[],frameCount:0,isVRMode:!1,focusQuality:{enabled:!1,focusX:.5,focusY:.5,source:`screen-center`,avgFrameMs:16.7,pixelRatio:1,tier:`high`},spatialAudio:{enabled:!1,unlocked:!1,listener:null,context:null,micReady:!1,micPermission:`unknown`,voiceRecognition:!1,speechSynthesis:!1,wakeWindowUntil:0,lastVoiceCommandAt:0,environmentProfile:`default`,roomProfile:{name:`default`,refDistance:.72,maxDistance:8,rolloffFactor:1.6,dampening:.08}},nativeOptions:{immersion:1,hdrEnabled:!0,handTrackingEnabled:!0,spatialAudioEnabled:!0,activeEnvironment:`default`},compositor:{mode:`browser-proxy`,native:!1,reprojection:!1,passthroughBlend:`browser`,depthComposition:!1,foveation:0,framebufferScaleFactor:1,eyeBuffers:`mono`,frameBudgetMs:16.6,avgFrameMs:16.6,lastFrameAt:0,refreshRate:60,renderScale:1,convergence:1.4,lensProfile:`default`,eyeAspect:1,vignetteStrength:.12,motionComfort:`balanced`,stereoFrustum:!0},browserProfile:{browser:`unknown`,engine:`unknown`,platform:`unknown`,isAndroid:!1,isIOS:!1,isVisionOS:!1,isQuest:!1,isWebView:!1,isSafari:!1,isChrome:!1,isFirefox:!1,isEdge:!1,webXRSupportExpected:!1,webXRFragmented:!1,latencyCeilingMs:16.7,limits:{},notes:[]},capabilities:{browserWebAR:!0,eightWallSLAM:!1,webXRAvailable:!1,webXRHitTest:!1,manualCamera:!1,mediaPipeHands:!1,spatialAudio:!1,gazeProxy:!1,controllerAbstraction:!1,handEyeFusion:!1,spatialWindowing:!1,passthroughBlendProxy:!1,comfortAdaptation:!1,predictivePoseFiltering:!1,accessibilityInteraction:!1,gestureArbitration:!1,selectionArbitration:!1,dragManipulationProxy:!1,openXRCompositorProxy:!1,reprojectionProxy:!1,depthCompositionProxy:!1,eyeBufferPair:!1,nativeFrameTiming:!1,posePredictionProxy:!1,approximateAnchors:!0,truePersistentWorldAnchors:!1,eyeTracking:!1,foveatedRendering:!1,nativeCompositor:!1,guardianBoundary:!1,controllerHaptics:!1,nativeOpenXRBridge:!1,browserLatencyCeiling:!0,limitedSensorAccess:!0,limitedOSIntegration:!0,limitedCompositorControl:!0,persistentAnchorSupport:!1,backgroundExecutionLimited:!0,passthroughControlLimited:!0,spatialMemoryLimited:!0,headsetOptimizationAccessLimited:!0,webXRFragmented:!1,safariWebXRLimitations:!1,visionOSBrowserRestrictions:!1,androidBrowserInconsistency:!1,webViewInconsistency:!1,eyeTrackingProxy:!1,persistentSpatialMemory:!1,ultraStableAnchoring:!1,naturalWindowPlacement:!1,depthAwareImmersion:!1,environmentAwareUI:!1,headsetComfortSystems:!1,lowLatencyCompositing:!1,stereoEyeBuffers:!1,stereoFrustumCalibration:!1,refreshRateNegotiation:!1,timestampSync:!1,motionSicknessMitigation:!1,teleportLocomotion:!1,smoothLocomotionSafeguards:!1,roomBoundaryVisualization:!1,nativeHandMeshProxy:!1,controllerHapticsProxy:!1,lowLightTrackingResilience:!1,headsetCameraCalibrationProxy:!1,deviceCapabilityMatrix:!1,renderScaleStability:!1,stereoUiAnchoring:!1,antiAliasEdgeProtection:!1,zFightGuard:!1,sustainedFramerateGuard:!1,orientationLockStability:!1,sensorPermissionPersistenceProxy:!1,motionComfortVignette:!1},telemetry:{frameMs:16.7,qualityTier:`high`,droppedFrames:0,startedAt:0,lastNativeStatusAt:0},runtime:{phase:`created`,lifecycleState:`created`,architecture:`unknown`,experienceClass:`unknown`,spatialRuntimeClass:`unknown`,platformRole:`unknown`,authority:`none`,authoritativeRuntime:`none`,activeEngine:`none`,activeRenderer:`none`,rendererOwner:`none`,restartCount:0,lastError:``,subsystems:{},cleanupCount:0,conflicts:[],readiness:{boot:!1,scene:!1,camera:!1,tracking:!1,ui:!1},lifecycleHistory:[],permissionState:`unknown`,degradationReason:``,spatialGapStatement:``,rootCauseSummary:``,visionProGapSummary:``,visionProMissingFeatures:[]},sessionAnchor:{originMatrix:null,originPosition:[0,0,0],originQuaternion:[0,0,0,1],restoredAt:0},handState:{hands:[],gestures:new Map},sceneInitialized:!1,resizeBound:!1,fallbackLoopStarted:!1,aframeCameraSyncAdded:!1,liveSceneReady:!1,paused:!1,tracking:null,trackingQuality:`initializing`,trackingAPI:null,detectedPlanes:[]},$e=new EventTarget,et=new Set,tt=new Set,nt=new Set,rt=new Map;function A(e,t){let n=e=>t(e.detail);return $e.addEventListener(e,n),()=>$e.removeEventListener(e,n)}function j(e,t={}){$e.dispatchEvent(new CustomEvent(e,{detail:t}))}function it(e,t={}){k.runtime.phase=String(e||`unknown`),k.runtime.lastTransitionAt=Date.now();try{document.body.dataset.jarvisRuntimePhase=k.runtime.phase}catch{}return j(`runtime-phase`,{phase:k.runtime.phase,detail:t}),yt(`AR phase: ${k.runtime.phase}`),k.runtime.phase}function M(e,t={}){let n=String(e||`unknown`);k.runtime.lifecycleState=n,k.runtime.lifecycleHistory.push({state:n,detail:t,at:Date.now()}),k.runtime.lifecycleHistory.length>24&&k.runtime.lifecycleHistory.splice(0,k.runtime.lifecycleHistory.length-24);try{document.body.dataset.jarvisLifecycleState=n}catch{}return j(`runtime-lifecycle`,{state:n,detail:t}),yt(`AR lifecycle: ${n}`),n}function N(e,t=!0){if(!e)return!1;k.runtime.readiness[e]=!!t;try{document.body.dataset.jarvisReady=Object.entries(k.runtime.readiness).filter(([,e])=>e).map(([e])=>e).join(`,`)}catch{}return j(`runtime-readiness`,{key:e,ready:!!t,readiness:k.runtime.readiness}),k.runtime.readiness[e]}function at(){k.started=!1,k.xrStarted=!1,k.xrAvailable=!1,k.xrSession=null,k.xrHitTestSource=null,k.liveSceneReady=!1,k.paused=!1,k.cameraVideo=null,k.gestureFrameCanvas=null,k.gestureFrameReady=!1,k.trackingMode=`standby`,k.runtime.permissionState=`unknown`,k.runtime.degradationReason=``,k.runtime.rendererOwner=`none`,k.runtime.activeRenderer=`none`,k.runtime.activeEngine=`none`;for(let e of Object.keys(k.runtime.readiness))k.runtime.readiness[e]=!1;M(`stopped`)}function P(e,t=`ready`,n={}){let r=String(e||``).trim();if(!r)return null;k.runtime.subsystems[r]={status:t,detail:n,updatedAt:Date.now()};try{document.body.dataset.jarvisSubsystems=Object.keys(k.runtime.subsystems).join(`,`)}catch{}return j(`runtime-subsystem`,{name:r,status:t,detail:n}),k.runtime.subsystems[r]}function ot(e,t={}){let n=String(e||`unknown`),r=k.runtime.authoritativeRuntime;if(r!==`none`&&r!==n&&!t.force){let e={type:`runtime`,current:r,attempted:n,at:Date.now()};return k.runtime.conflicts.push(e),P(`blocked-runtime:${n}`,`blocked`,e),j(`runtime-authority-conflict`,e),r}k.runtime.authoritativeRuntime=n,k.runtime.authority=n,k.runtime.activeEngine=n,k.runtime.authorityChangedAt=Date.now();try{document.body.dataset.jarvisRuntimeAuthority=n}catch{}return j(`runtime-authority`,{previous:r,authority:n,detail:t}),P(`runtime:${n}`,`authoritative`,t),n}function st(e,t=null,n={}){let r=String(e||`unknown`),i=k.runtime.rendererOwner||`none`;if(!(n.takeover||i===`none`||i===r)){let e={type:`renderer`,current:i,attempted:r,at:Date.now()};return k.runtime.conflicts.push(e),P(`blocked-renderer:${r}`,`blocked`,e),j(`runtime-authority-conflict`,e),i}k.runtime.rendererOwner=r,k.runtime.activeRenderer=r,k.runtime.activeEngine=n.engine||k.runtime.activeEngine,k.runtime.rendererChangedAt=Date.now(),t?.scene&&(k.scene=t.scene),t?.camera&&(k.camera=t.camera),t?.renderer&&(k.renderer=t.renderer),r!==`fallback-three`&&Ct();try{document.body.dataset.jarvisRendererAuthority=r}catch{}return j(`renderer-authority`,{previous:i,authority:r,context:t}),P(`renderer:${r}`,`authoritative`,{hasScene:!!t?.scene,hasCamera:!!t?.camera,hasRenderer:!!t?.renderer}),r}function ct(e,t,n,r){if(!e?.addEventListener||!t||!n)return()=>{};e.addEventListener(t,n,r);let i=()=>e.removeEventListener(t,n,r);return et.add(i),()=>{i(),et.delete(i)}}function lt(e,t=0){let n=window.setTimeout(()=>{tt.delete(n),e?.()},t);return tt.add(n),n}function ut(e){e&&(window.clearTimeout(e),tt.delete(e))}function F(e){let t=requestAnimationFrame(n=>{nt.delete(t),e?.(n)});return nt.add(t),t}function dt(e){e&&(cancelAnimationFrame(e),nt.delete(e))}function ft(e,t={},n={}){let r=String(e?.message||e||`Unknown runtime issue`),i=String(n.source||t.source||`runtime`),a=`${i}:${r}`,o=Date.now();if(o-(rt.get(a)||0)>5e3){rt.set(a,o),k.runtime.lastError=r,k.runtime.degradationReason=String(t.degradationReason||k.runtime.degradationReason||``),j(`runtime-error`,{error:r,source:i,context:t}),P(`runtime-error:${i}`,`error`,{message:r,context:t});try{T(r,n.title||`Runtime Error`,{timeout:n.timeout??7e3})}catch{}}try{yt(`${i}: ${r}`)}catch{}return{message:r,source:i,context:t}}function pt(e,t,n={}){return typeof t==`function`?(...r)=>{try{return t(...r)}catch(t){ft(t,{...n,subsystem:e},{source:e});return}}:()=>{}}function I(e,t){k.capabilities[e]=!!t;try{document.body.dataset[`cap${e[0].toUpperCase()}${e.slice(1)}`]=String(!!t)}catch{}return k.capabilities[e]}function mt(e={}){k.compositor={...k.compositor,...e&&typeof e==`object`?e:{}},j(`compositor-state`,k.compositor);try{document.body.dataset.jarvisCompositorMode=k.compositor.mode,document.body.dataset.jarvisCompositorPassthrough=String(k.compositor.passthroughBlend)}catch{}return k.compositor}function ht(e={}){k.browserProfile={...k.browserProfile,...e&&typeof e==`object`?e:{}};try{document.body.dataset.jarvisBrowser=`${k.browserProfile.browser||`unknown`}-${k.browserProfile.platform||`unknown`}`,document.body.dataset.jarvisBrowserLimit=k.browserProfile.webXRFragmented?`fragmented`:`standard`}catch{}return j(`browser-profile`,k.browserProfile),k.browserProfile}function gt(e={}){k.runtime={...k.runtime,...e&&typeof e==`object`?e:{}};try{document.body.dataset.jarvisRuntimeArchitecture=k.runtime.architecture||`unknown`,document.body.dataset.jarvisSpatialClass=k.runtime.spatialRuntimeClass||`unknown`}catch{}return j(`runtime-classification`,k.runtime),k.runtime}function _t(e=``){k.runtime.rootCauseSummary=String(e||``);try{document.body.dataset.jarvisRootCause=k.runtime.rootCauseSummary}catch{}return j(`runtime-root-cause`,{summary:k.runtime.rootCauseSummary}),k.runtime.rootCauseSummary}function vt(e=``,t=[]){k.runtime.visionProGapSummary=String(e||``),k.runtime.visionProMissingFeatures=Array.isArray(t)?t.map(e=>String(e||``).trim()).filter(Boolean):[];try{document.body.dataset.jarvisVisionProGap=k.runtime.visionProGapSummary}catch{}return j(`runtime-vision-pro-gap`,{summary:k.runtime.visionProGapSummary,missingFeatures:k.runtime.visionProMissingFeatures}),{summary:k.runtime.visionProGapSummary,missingFeatures:k.runtime.visionProMissingFeatures}}function L(e,...t){try{let n=globalThis.JarvisNative;n&&typeof n[e]==`function`&&n[e](...t)}catch{}}function yt(e){L(`status`,String(e||``))}function bt(){try{if(globalThis.XR8?.Threejs?.xrScene){let e=globalThis.XR8.Threejs.xrScene();if(e?.scene&&e?.camera&&e?.renderer)return k.xrScene=e,k.scene=e.scene,k.camera=e.camera,k.renderer=e.renderer,e}}catch{return null}return null}function R(){return bt()||(xt(),{scene:k.fallbackScene,camera:k.fallbackCamera,renderer:k.fallbackRenderer})}function xt(){if(k.fallbackScene&&k.fallbackCamera&&k.fallbackRenderer||k.xrStarted&&k.xrScene?.scene)return;k.fallbackActive=!0;let e=document.getElementById(`fallback-three-canvas`)||document.createElement(`canvas`);e.id=`fallback-three-canvas`,e.parentNode||(e.style.cssText=`position:fixed;inset:0;width:100%;height:100%;z-index:1;pointer-events:none;background:transparent`,document.body.appendChild(e));let t=new Ee({canvas:e,alpha:!0,antialias:!0,powerPreference:`high-performance`});t.setPixelRatio(Math.min(devicePixelRatio||1,3)),t.setSize(innerWidth,innerHeight,!1),t.setClearColor(0,0),t.outputColorSpace=pe,t.toneMapping=4,t.toneMappingExposure=1,t.useLegacyLights=!1,t.shadowMap.enabled=!0,t.shadowMap.type=3;let n=new Ie,r=new ie(60,innerWidth/innerHeight,.01,1e3);r.position.set(0,0,0),n.add(new Ae(16777215,.65));let i=new s(16777215,.8);i.position.set(1,2,1),i.castShadow=!0,n.add(i),k.fallbackScene=n,k.fallbackCamera=r,k.fallbackRenderer=t,k.scene=n,k.camera=r,k.renderer=t,st(`fallback-three`,{scene:n,camera:r,renderer:t},{engine:`manual-camera`})}function St(){if(k.fallbackLoopStarted)return;k.fallbackLoopStarted=!0,xt();let e=()=>{if(k.xrStarted){Ct();return}!k.xrStarted&&k.fallbackRenderer&&(k.fallbackRenderer.setSize(innerWidth,innerHeight,!1),k.fallbackCamera.aspect=innerWidth/innerHeight,k.fallbackCamera.updateProjectionMatrix(),k.fallbackRenderer.render(k.fallbackScene,k.fallbackCamera)),k.fallbackLoopHandle=F(e)};k.fallbackLoopHandle=F(e)}function Ct(){k.fallbackLoopHandle&&dt(k.fallbackLoopHandle),k.fallbackLoopHandle=0,k.fallbackLoopStarted=!1;let e=document.getElementById(`fallback-three-canvas`);e&&(e.style.display=`none`)}function wt(){let e=bt();if(!e?.scene||!k.fallbackScene||e.scene===k.fallbackScene)return e;let t=[...k.fallbackScene.children];for(let n of t)n!==k.fallbackCamera&&(k.fallbackScene.remove(n),e.scene.children.includes(n)||e.scene.add(n));return Ct(),k.fallbackRenderer?.dispose?.(),document.getElementById(`fallback-three-canvas`)?.remove(),k.fallbackScene=null,k.fallbackCamera=null,k.fallbackRenderer=null,k.fallbackActive=!1,k.scene=e.scene,k.camera=e.camera,k.renderer=e.renderer,st(`xr8-threejs`,e,{takeover:!0,engine:`8thwall-slam`}),e}function Tt(e=R()){return k.liveSceneReady=!0,j(`ar-scene-live`,e),e}function Et(e,t={}){let n=!!t.disposeSharedAssets,r=new Set,i=new Set,a=new Set;e?.traverse?.(e=>{e.geometry&&!r.has(e.geometry)&&(n||!e.geometry.userData?.sharedAssetKey)&&(r.add(e.geometry),e.geometry.dispose()),(Array.isArray(e.material)?e.material:[e.material]).filter(Boolean).forEach(e=>{i.has(e)||(i.add(e),Object.values(e).forEach(e=>{e?.isTexture&&!a.has(e)&&(n||!e.userData?.sharedAssetKey)&&(a.add(e),e.dispose())}),(n||!e.userData?.sharedAssetKey)&&e.dispose?.())})}),e?.parent?.remove(e)}try{globalThis.AR_STATE=k,globalThis.FridayRuntime={AR_STATE:k,emit:j,on:A,reportRuntimeIssue:ft,guardSubsystem:pt,setCapability:I,setCompositorState:mt,claimRuntimeAuthority:ot,claimRendererAuthority:st,registerSubsystem:P}}catch{}function Dt(e){try{return e?.xr?.getSession?.()||null}catch{return null}}function Ot(e,t){if(e?.xr){try{typeof e.xr.setFramebufferScaleFactor==`function`&&e.xr.setFramebufferScaleFactor(t.framebufferScaleFactor)}catch{}try{typeof e.xr.setFoveation==`function`&&e.xr.setFoveation(t.foveation)}catch{}}}function kt(e=R(),t={}){let n=e?.renderer,r=t.session||Dt(n),i=String(t.tier||k.telemetry?.qualityTier||`medium`).toLowerCase();globalThis.navigator?.xr;let a=!!(n?.xr&&typeof n.xr.setFoveation==`function`),o=!!(n?.xr&&typeof n.xr.setFramebufferScaleFactor==`function`),s=!!(r?.renderState?.baseLayer||r?.depthUsage),c=!!(globalThis.JarvisNative?.openXRBridge||globalThis.JarvisNative?.setCompositorState),l={mode:t.mode||(r?`webxr-session`:`browser-proxy`),native:c,reprojection:!!(r&&o),passthroughBlend:t.passthroughBlend||(t.source?`browser-camera`:`browser`),depthComposition:!!(t.depthComposition||s),foveation:t.foveation??(i===`high`?.2:i===`medium`?.35:.55),framebufferScaleFactor:t.framebufferScaleFactor??(i===`high`?1:i===`medium`?.85:.72),eyeBuffers:t.eyeBuffers||(t.stereo?`pair`:`mono`),frameBudgetMs:t.frameBudgetMs??(i===`high`?13.5:i===`medium`?16.6:20),avgFrameMs:k.compositor?.avgFrameMs||16.6,lastFrameAt:performance.now(),posePredictionMs:t.posePredictionMs??(i===`high`?18:i===`medium`?24:32),refreshRate:t.refreshRate??(i===`high`?90:i===`medium`?72:60),renderScale:t.renderScale??(i===`high`?1:i===`medium`?.9:.8),convergence:t.convergence??(i===`high`?1.35:1.45),guardianProxy:!!t.guardianProxy,compositorSync:!0,lensProfile:t.lensProfile||`default`,eyeAspect:t.eyeAspect??1,vignetteStrength:t.vignetteStrength??(i===`high`?.1:.16),motionComfort:t.motionComfort||`balanced`,stereoFrustum:!!(t.stereo??r)};if(mt(l),I(`openXRCompositorProxy`,!0),I(`reprojectionProxy`,l.reprojection),I(`depthCompositionProxy`,l.depthComposition),I(`eyeBufferPair`,l.eyeBuffers===`pair`),I(`nativeFrameTiming`,!!r),I(`posePredictionProxy`,!0),I(`foveatedRendering`,a),I(`lowLatencyCompositing`,!0),I(`stereoEyeBuffers`,l.eyeBuffers===`pair`),I(`stereoFrustumCalibration`,l.stereoFrustum),I(`refreshRateNegotiation`,!0),I(`timestampSync`,!0),I(`motionSicknessMitigation`,!0),I(`smoothLocomotionSafeguards`,!0),I(`motionComfortVignette`,!0),t.guardianProxy!=null&&I(`guardianBoundary`,!!t.guardianProxy),c){I(`nativeOpenXRBridge`,!0);try{L(`setCompositorState`,JSON.stringify(l)),L(`requestCompositorControl`,JSON.stringify({owner:`browser-runtime`,mode:l.mode,guardianProxy:l.guardianProxy,browserManaged:!0})),L(`setGuardianState`,JSON.stringify({requested:!!t.guardianProxy,boundary:!!t.guardianProxy,owner:`browser-runtime`,source:`ar-compositor`}))}catch{}}return Ot(n,l),P(`compositor`,`ready`,l),j(`compositor-profile`,l),yt(`Compositor profile: ${l.mode}`),l}function At(e=16.6){let t=k.compositor||{},n=t.avgFrameMs?t.avgFrameMs*.9+e*.1:e,r={...t,avgFrameMs:n,lastFrameAt:performance.now()};return mt(r),k.telemetry.frameMs=e,k.telemetry.droppedFrames=e>(r.frameBudgetMs||16.6)*1.25?(k.telemetry.droppedFrames||0)+1:k.telemetry.droppedFrames||0,j(`compositor-frame`,r),r}function jt(){mt({mode:`browser-proxy`,native:!1,reprojection:!1,passthroughBlend:`browser`,depthComposition:!1,foveation:0,framebufferScaleFactor:1,eyeBuffers:`mono`,frameBudgetMs:16.6,avgFrameMs:16.6,lastFrameAt:0}),I(`openXRCompositorProxy`,!1),I(`reprojectionProxy`,!1),I(`depthCompositionProxy`,!1),I(`eyeBufferPair`,!1),I(`nativeFrameTiming`,!1),I(`posePredictionProxy`,!1)}function Mt(e,n,r){globalThis.JarvisNative?.openXRBridge||globalThis.JarvisNative?.setCompositorState||(e.xr.enabled=!0,e.xr.setReferenceSpaceType(`local-floor`),!navigator.xr&&!k.stereoEffect&&t(async()=>{let{StereoEffect:e}=await import(`./StereoEffect-BUunyfV9.js`);return{StereoEffect:e}},__vite__mapDeps([0,1,2]),import.meta.url).then(({StereoEffect:t})=>{k.stereoEffect=new t(e),k.stereoEffect.setSize(window.innerWidth,window.innerHeight),k.stereoEffect.setEyeSeparation(.064),e.setAnimationLoop(()=>{k.stereoEffect.render(n,r)}),j(`jarvis-stereo-mode-active`,{status:`fallback_active`})}).catch(()=>{console.warn(`V15 AR: StereoEffect.js fallback polyfill missing.`)}))}var Nt=globalThis.XRExtras||{FullWindowCanvas:{pipelineModule(){return{name:`xrextras-full-window-canvas`,onStart:({canvas:e})=>Pt(e),onCanvasSizeChange:({canvas:e})=>Pt(e)}}},Loading:{pipelineModule(){return{name:`xrextras-loading`,onStart:()=>O(`Starting 8th Wall camera...`,38),onCameraStatusChange:({status:e})=>{e===`hasVideo`&&Qe()}}}},AlmostThere:{pipelineModule(){return{name:`xrextras-almost-there`,onAttach:()=>{navigator.mediaDevices?.getUserMedia||E(`This browser has limited AR camera support. Chrome Android is recommended.`)}}}},RuntimeError:{pipelineModule(){return{name:`xrextras-runtime-error`,onException:e=>T(e?.message||String(e),`8th Wall Runtime Error`,{timeout:0})}}}};try{globalThis.XRExtras||(globalThis.XRExtras=Nt)}catch{}function Pt(e){if(!e)return;let t=Math.min(devicePixelRatio||1,3),n=Math.max(1,Math.floor(innerWidth*t)),r=Math.max(1,Math.floor(innerHeight*t));(e.width!==n||e.height!==r)&&(e.width=n,e.height=r),e.style.width=`100vw`,e.style.height=`100vh`}function Ft(){let e=[`localhost`,`127.0.0.1`,`::1`].includes(location.hostname);return location.protocol===`https:`||e?!0:(T(`AR requires a secure connection (HTTPS). Please open this app over HTTPS.`,`Secure Connection Required`,{timeout:0,linkHref:`intent://settings#Intent;scheme=android-app;end`,linkLabel:`Open Chrome Android settings`}),!1)}function It(){let e=new URLSearchParams(location.search),t=()=>{try{return localStorage.getItem(`jarvis_ar_device`)||``}catch{return``}},n=e=>{try{localStorage.setItem(`jarvis_ar_device`,String(e))}catch{}},r=e.has(`device`),i=e.get(`device`)||t()||`POCO-M5`;r||n(i);let a=Rt(e.get(`omega`)||e.get(`omegaBridge`)||``),o=Bt(e.get(`xr`)||e.get(`xrScriptUrl`)||``);return{deviceName:i,mode:Lt(e.get(`mode`)||`vision_pro`),autoStart:!1,source:e.get(`source`)||`browser`,guardianProxy:e.get(`guardianProxy`)===`true`||e.get(`guardian`)===`true`,eyeTracking:e.get(`eyeTracking`)===`true`,nativeCompositor:e.get(`nativeCompositor`)===`true`,truePersistentWorldAnchors:e.get(`truePersistentWorldAnchors`)===`true`||e.get(`persistentWorldAnchors`)===`true`,nativeOpenXRBridge:e.get(`nativeOpenXRBridge`)===`true`,command:e.get(`command`)||``,arQuality:(e.get(`arQuality`)||`4k`).toLowerCase(),renderScale:e.get(`renderScale`)||`adaptive`,screen:e.get(`screen`)||`quest_spatial`,stack:(e.get(`stack`)||`aframe,playcanvas,camerakit,8thwall`).split(`,`).map(e=>e.trim()).filter(Boolean),omegaBase:a||(location.origin.includes(`5173`)?location.origin:``),wsBase:zt(e.get(`ws`)||``,a),xrScriptUrl:o,imageTargets:(e.get(`imageTargets`)||``).split(`,`).map(e=>e.trim()).filter(Boolean),gameUrls:{eternum:Rt(e.get(`eternumUrl`)||e.get(`gameEternumUrl`)||``),ripples:Rt(e.get(`ripplesUrl`)||e.get(`gameRipplesUrl`)||``)}}}function Lt(e){let t=String(e||``).toLowerCase().trim().replace(/[-\s]+/g,`_`);return{vision:`vision_pro`,visionos:`vision_pro`,meta:`vision_pro`,quest:`vision_pro`,scan_room:`scan`,model:`models`,games:`games`,game:`games`,build:`builder`,game_builder:`builder`,vr_screen:`vr`}[t]||t||`vision_pro`}function Rt(e){let t=String(e||``).trim().replace(/\/+$/,``);return t?/^https?:\/\//i.test(t)?t:`http://${t}`:``}function zt(e,t=``){let n=String(e||``).trim().replace(/\/+$/,``);if(n)return/^wss?:\/\//i.test(n)?n:`ws://${n}`;if(!t)return location.protocol===`https:`?`wss://${location.host}/scene-ws`:`ws://${location.hostname}:5050`;try{let e=new URL(t,location.href);return e.port===`5173`?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/scene-ws`:`${e.protocol===`https:`?`wss:`:`ws:`}//${e.hostname}:5050`}catch{return``}}function Bt(e){let t=String(e||``).trim();return t&&/^(https?:|data:|blob:|\/)/i.test(t)?t:``}function Vt(e,t){let n=String(e||``).toLowerCase();return t.some(e=>n.includes(String(e||``).toLowerCase()))}function Ht(e=``,t=``,n=``){let r=String(e||(typeof navigator<`u`?navigator.userAgent:``)||``),i=r.toLowerCase(),a=typeof navigator<`u`&&navigator.platform||``,o=typeof navigator<`u`&&navigator.vendor||``,s=typeof navigator<`u`&&navigator.maxTouchPoints||0,c=String(t||a||``).toLowerCase(),l=String(n||o||``).toLowerCase(),u=/iphone|ipad|ipod/.test(i)||c.includes(`mac`)&&s>1&&/safari/.test(i),d=/android/.test(i),f=/visionos|applevision|xrvision/.test(i)||Vt(r,[`Safari`])&&/apple/.test(l)&&s>1&&/mac/.test(c),p=/quest|oculus/.test(i),m=/\bwv\b|; wv|webview|android.*version\/\d+.*chrome/i.test(r)||d&&!/chrome|crios|firefox|fxios|edg/i.test(i),h=/safari/.test(i)&&!/chrome|crios|chromium|android/.test(i),g=/chrome|crios|chromium/.test(i)&&!/edg/.test(i),_=/firefox|fxios/.test(i),ee=/edg/.test(i),v=h?`safari`:g?`chrome`:_?`firefox`:ee?`edge`:p?`quest-browser`:`other`,y=h?`webkit`:_?`gecko`:`blink`,b=f?`visionos`:u?`ios`:d?`android`:/mac/.test(c)?`mac`:/win/.test(c)?`windows`:/linux/.test(c)?`linux`:`desktop`,te=!!(!u||f||p),ne=h||f||m||d&&!g&&!p,re=p&&g;return{ua:r,browser:v,engine:y,platform:b,isAndroid:d,isIOS:u,isVisionOS:f,isQuest:p,isWebView:m,isSafari:h,isChrome:g,isFirefox:_,isEdge:ee,questBrowserQuirks:re,webXRSupportExpected:te,webXRFragmented:ne,latencyCeilingMs:f?12.5:p?13.5:u?14.5:16.7,limits:{sensorAccessLimited:!0,osIntegrationLimited:!0,compositorControlLimited:!0,persistentAnchorSupport:!1,backgroundExecutionLimited:!0,passthroughControlLimited:!0,spatialMemoryLimited:!0,headsetOptimizationAccessLimited:!0,webXRFragmented:ne,safariWebXRLimitations:h,visionOSBrowserRestrictions:f,androidBrowserInconsistency:d,webViewInconsistency:m,questBrowserQuirks:re,fullscreenEdgeCases:f||m||p,orientationLockEdgeCases:h||f||m||p,webglContextLossRisk:p||d||m,renderLoopDuplicationRisk:p||d||m,limitedSensorAccess:!0,limitedOSIntegration:!0,limitedCompositorControl:!0,limitedPassthroughControl:!0,limitedSpatialMemoryAPIs:!0,limitedHeadsetOptimizationAccess:!0},notes:[h?`Safari WebXR support remains fragmented.`:``,f?`visionOS browser control is limited to browser-managed surfaces.`:``,d?`Android browser behavior can vary by OEM and browser build.`:``,re?`Quest Browser can expose fullscreen, orientation, and session quirks.`:``,m?`Embedded WebView feature support is stricter than Chrome Custom Tabs.`:``].filter(Boolean)}}function Ut(e){let t=[];return e?(e.limits?.webXRFragmented&&t.push(`webxr-fragmented`),e.limits?.safariWebXRLimitations&&t.push(`safari-webxr-limited`),e.limits?.visionOSBrowserRestrictions&&t.push(`visionos-browser-limited`),e.limits?.androidBrowserInconsistency&&t.push(`android-browser-variable`),e.limits?.webViewInconsistency&&t.push(`webview-variable`),e.limits?.questBrowserQuirks&&t.push(`quest-browser-quirks`),e.limits?.fullscreenEdgeCases&&t.push(`fullscreen-edge-cases`),e.limits?.orientationLockEdgeCases&&t.push(`orientation-lock-edge-cases`),e.limits?.webglContextLossRisk&&t.push(`webgl-context-loss-risk`),e.limits?.renderLoopDuplicationRisk&&t.push(`render-loop-duplication-risk`),e.limits?.backgroundExecutionLimited&&t.push(`background-execution-limited`),e.limits?.persistentAnchorSupport===!1&&t.push(`no-persistent-anchors`),e.limits?.passthroughControlLimited&&t.push(`passthrough-control-limited`),e.limits?.spatialMemoryLimited&&t.push(`spatial-memory-limited`),t):t}async function Wt(e){k.config=e,k.aframeScene=document.getElementById(`ar-scene`),k.aframeCamera=document.getElementById(`main-camera`),await Gt();let t=R();return Jt(t.renderer,e),Yt(t),kt(t,{mode:`ar-shell`,tier:k.focusQuality.tier,stereo:!!k.isVRMode}),en(t.scene),qt(t.renderer),nn(),k.sceneInitialized||(k.sceneInitialized=!0,j(`scene-ready`,t)),t}function Gt(){let e=document.getElementById(`ar-scene`);return!e||e.hasLoaded?Promise.resolve():new Promise(t=>e.addEventListener(`loaded`,t,{once:!0}))}function Kt(){k.aframeCameraSyncAdded=!0,document.getElementById(`ar-scene`)?.setAttribute(`data-render-mode`,`disabled-xr8-single-scene`)}function qt(e){let t=e?.domElement;!t||t.dataset.jarvisWebglRecoveryBound===`1`||(t.dataset.jarvisWebglRecoveryBound=`1`,ct(t,`webglcontextlost`,e=>{e.preventDefault(),E(`WebGL context lost. Pausing AR until the GPU recovers.`,`WebGL`);try{globalThis.XR8?.pause?.()}catch{}},{passive:!1}),ct(t,`webglcontextrestored`,()=>{if(E(`WebGL context restored.`,`WebGL`),Jt(e,k.config||{}),k.xrStarted)try{globalThis.XR8?.resume?.()}catch{}},{passive:!0}))}function Jt(e,t={}){if(!e)return;let n=String(t.renderScale||`adaptive`).toLowerCase(),r=n===`2`||n===`4k`?2:n===`1`?1:devicePixelRatio||1,i=Math.max(1,Math.min(r,3));r>3&&(console.warn(`Render scale ${r} was capped to 3.0. Requested scale: ${n}`),k.telemetry=k.telemetry||{},k.telemetry.pixelRatioCapped=!0,k.telemetry.originalPixelRatio=r),e.setPixelRatio(i),e.setSize(innerWidth,innerHeight,!1),e.outputColorSpace=pe,e.toneMapping=4,e.toneMappingExposure=1,e.useLegacyLights=!1,e.shadowMap.enabled=!0,e.shadowMap.type=3}function Yt(e=R()){let t=e?.scene,n=e?.renderer;if(!t||!n)return null;if(t.environment&&t.userData.jarvisEnvironmentSource===`hdr`||t.userData.jarvisDefaultEnvInstalled)return t.environment;try{let e=new re(n),r=new me,i=e.fromScene(r,.04);i?.texture&&(t.environment=i.texture,t.userData.jarvisDefaultEnvTarget=i,t.userData.jarvisDefaultEnvInstalled=!0,t.userData.jarvisEnvironmentSource=`room-default`,k.telemetry.iblEnvironment=`room-default`),r.dispose?.(),e.dispose()}catch(e){console.warn(`Default IBL environment install failed:`,e?.message||e)}return t.environment}function Xt(){if(k.focusQuality.enabled)return;k.focusQuality.enabled=!0;let e=performance.now(),t=0,n=(e,t,n)=>{k.focusQuality.focusX=Math.max(0,Math.min(1,e)),k.focusQuality.focusY=Math.max(0,Math.min(1,t)),k.focusQuality.source=n};ct(window,`pointerdown`,e=>n(e.clientX/innerWidth,e.clientY/innerHeight,`touch`),{passive:!0}),ct(window,`pointermove`,e=>{e.pointerType!==`mouse`&&n(e.clientX/innerWidth,e.clientY/innerHeight,`touch`)},{passive:!0}),A(`gesture-point`,e=>{let t=e?.point;t&&n(t.x,t.y,`hand-point`)});let r=n=>{let i=Math.min(n-e,100);e=n,k.focusQuality.avgFrameMs=k.focusQuality.avgFrameMs*.92+i*.08,k.telemetry.frameMs=k.focusQuality.avgFrameMs,At(i),n-t>600&&(Zt(),t=n),F(r)};F(r)}function Zt(){let e=R(),t=e.renderer;if(!t)return;let n=k.focusQuality.avgFrameMs,r=Math.min(devicePixelRatio||1,3),i=n>33?{ratio:1,tier:`low`,shadows:!1}:n>25?{ratio:Math.min(1.2,r),tier:`medium`,shadows:!0}:n>18?{ratio:Math.min(1.5,r),tier:`balanced`,shadows:!0}:{ratio:r,tier:`high`,shadows:!0};Math.abs((k.focusQuality.pixelRatio||0)-i.ratio)>.05&&(t.setPixelRatio(i.ratio),t.setSize(innerWidth,innerHeight,!1),k.focusQuality.pixelRatio=i.ratio),k.focusQuality.tier=i.tier,k.telemetry.qualityTier=i.tier,document.body.dataset.jarvisQualityTier=i.tier,document.body.dataset.jarvisFrameMs=k.focusQuality.avgFrameMs.toFixed(1),performance.now()-k.telemetry.lastNativeStatusAt>5e3&&(k.telemetry.lastNativeStatusAt=performance.now(),yt(`AR quality ${i.tier}, ${k.focusQuality.avgFrameMs.toFixed(1)}ms frame average`)),t.shadowMap&&(t.shadowMap.enabled=i.shadows),kt(e,{mode:`ar-shell`,tier:i.tier,stereo:!!k.isVRMode,frameBudgetMs:i.tier===`high`?13.5:i.tier===`balanced`?16.6:20}),k.placedObjects.forEach(e=>Qt(e,i.tier))}function Qt(e,t){if(!e)return;let n=$t(e)<.34?t:t===`high`?`balanced`:`low`;e.traverse(e=>{e.isMesh&&(e.frustumCulled=!0,e.castShadow=n!==`low`,e.receiveShadow=n!==`low`,e.material&&(e.material.needsUpdate=!1))})}function $t(e){let t=k.camera||R().camera;if(!t)return 0;let n=new w;e.getWorldPosition(n),n.project(t);let r=n.x*.5+.5,i=-n.y*.5+.5;return Math.hypot(r-k.focusQuality.focusX,i-k.focusQuality.focusY)}function en(e){if(!e||e.userData.jarvisHelpersAdded)return;e.userData.jarvisHelpersAdded=!0;let t=new i(16777215,4469538,.72);t.name=`jarvis-ambient-fill`,e.add(t);let n=new s(16777215,1.05);n.name=`jarvis-key-shadow-light`,n.position.set(1.4,3.2,1.2),n.castShadow=!0,n.shadow.mapSize.set(2048,2048),n.shadow.camera.near=.1,n.shadow.camera.far=10,n.shadow.camera.left=-5,n.shadow.camera.right=5,n.shadow.camera.top=5,n.shadow.camera.bottom=-5,n.shadow.bias=-5e-4,n.shadow.normalBias=.02,e.add(n),k.shadowLight=n;let a=new Me(4491519,.28,8,2);a.name=`jarvis-ar-fill-light`,a.position.set(0,1.2,0),e.add(a),k.fillLight=a;let o=new h(new r(.08,.105,48),new b({color:16777215,transparent:!0,opacity:.65,side:2,depthWrite:!1}));o.name=`placement-reticle`,o.rotation.x=-Math.PI/2,o.position.set(0,k.floorY+.01,-1.8),o.visible=!1,e.add(o),k.reticle=o;let c=new h(new m(12,12),new Ne({color:0,opacity:.24,transparent:!0,depthWrite:!1}));c.name=`jarvis-real-floor-shadow-receiver`,c.rotation.x=-Math.PI/2,c.position.set(0,k.floorY+.002,0),c.receiveShadow=!0,e.add(c),k.shadowReceiver=c}function tn(){D(`status-camera`,k.cameraVideo||k.xrStarted?`live`:`standby`),D(`status-tracking`,k.trackingMode),D(`status-omega`,k.jarvis?.connected?`linked`:`offline`)}function nn(){if(k.resizeBound)return;k.resizeBound=!0;let e=()=>{let e=R();e.camera?.isPerspectiveCamera&&(e.camera.aspect=innerWidth/innerHeight,e.camera.updateProjectionMatrix()),e.renderer?.setSize?.(innerWidth,innerHeight,!1),j(`ar-resize`,{width:innerWidth,height:innerHeight})};ct(window,`resize`,e),ct(window,`orientationchange`,()=>lt(e,100)),ct(document,`visibilitychange`,()=>{try{document.hidden?globalThis.XR8?.pause?.():globalThis.XR8?.resume?.()}catch{E(`8th Wall pause/resume is unavailable in this browser session.`)}})}var rn=new Set,an=null,on=null,sn=null,cn=0,ln=!1,un=class{constructor({title:e,width:t=340,height:n=480,icon:r=`O`,body:i}={}){let a=document.getElementById(`panel-template`).content.firstElementChild.cloneNode(!0);this.el=a,this.icon=r,this.isDragging=!1,this.isResizing=!1,this.startX=0,this.startY=0,this.currentX=Math.max(8,(innerWidth-t)/2),this.currentY=Math.max(72,(innerHeight-n)/2),this.velX=0,this.velY=0,this.animFrame=0,this.activePointerId=null,a.style.width=`clamp(280px, 90vw, ${t}px)`,a.style.minHeight=`${Math.min(n,innerHeight-170)}px`,a.querySelector(`h2`).textContent=e||`Panel`,i&&a.querySelector(`.panel-body`).appendChild(i),a.querySelector(`.panel-close`).addEventListener(`click`,()=>this.destroy()),a.querySelector(`.panel-minimize`).addEventListener(`click`,()=>this.minimize()),this.attachEvents(),document.getElementById(`ui-layer`).appendChild(a),this.applyTransform(),rn.add(this)}attachEvents(){let e=this.el.querySelector(`.panel-drag-handle`);this._listeners=[[e,`pointerdown`,e=>this.onPointerStart(e)],[document,`pointermove`,e=>this.onPointerMove(e)],[document,`pointerup`,()=>this.onDragEnd()],[this.el,`pointerdown`,()=>this.focus()]],this._listeners.forEach(([e,t,n,r])=>e.addEventListener(t,n,r))}onPointerStart(e){e.preventDefault?.(),this.isDragging=!0,this.startX=e.clientX-this.currentX,this.startY=e.clientY-this.currentY,this.lastX=e.clientX,this.lastY=e.clientY,this.activePointerId=e.pointerId,dt(this.animFrame),e.currentTarget?.setPointerCapture?.(e.pointerId)}onPointerMove(e){this.isDragging&&this.applyDrag(e.clientX,e.clientY)}applyDrag(e,t){this.velX=e-this.lastX,this.velY=t-this.lastY,this.lastX=e,this.lastY=t,this.currentX=e-this.startX,this.currentY=t-this.startY,this.applyTransform()}onDragEnd(){this.isDragging&&(this.isDragging=!1,this.el.releasePointerCapture?.(this.activePointerId),this.activePointerId=null,this.applyMomentum())}applyMomentum(){this.velX*=.92,this.velY*=.92,this.currentX+=this.velX,this.currentY+=this.velY,this.applyTransform(),(Math.abs(this.velX)>.5||Math.abs(this.velY)>.5)&&(this.animFrame=F(()=>this.applyMomentum()))}applyTransform(){let e=this.el.getBoundingClientRect(),t=this.el.offsetWidth||e.width||parseFloat(this.el.style.width)||320,n=this.el.offsetHeight||e.height||parseFloat(this.el.style.minHeight)||420,r=Math.max(0,innerWidth-t),i=Math.max(0,innerHeight-n);this.currentX=Math.max(0,Math.min(this.currentX,r)),this.currentY=Math.max(0,Math.min(this.currentY,i)),this.el.style.transform=`translate3d(${this.currentX}px, ${this.currentY}px, 0)`}focus(){rn.forEach(e=>e.el.classList.remove(`active`)),this.el.classList.add(`active`)}minimize(){this.el.classList.add(`minimized`);let e=document.createElement(`button`);e.className=`panel-orb glass-panel`,e.textContent=this.icon||`O`,e.setAttribute(`aria-label`,`Restore panel`);let t=document.querySelectorAll(`#ui-layer .panel-orb`).length;e.style.cssText=`width:56px;height:56px;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:18px;position:absolute;bottom:${100+t*64}px;right:20px;z-index:20;color:white;pointer-events:auto`,e.onclick=()=>{this.restore(),e.remove()},document.getElementById(`ui-layer`).appendChild(e),this.el.style.display=`none`}restore(){this.el.style.display=``,this.el.classList.remove(`minimized`),this.focus()}destroy(){dt(this.animFrame),this._listeners?.forEach(([e,t,n,r])=>e.removeEventListener(t,n,r)),this._listeners=[],rn.delete(this),this.el.remove(),rn.size||Sn()}};function dn(){yn(),A(`ar-resize`,_n)}function fn(){return k.css3d?.initialized?(xn(),k.css3d):(on=on||new Ie,an=an||pn(),k.css3d={scene:on,renderer:an,panels:[],initialized:!0},bn(),xn(),k.css3dResizeBound||(ct(window,`resize`,vn),ct(window,`orientationchange`,()=>lt(vn,100)),k.css3dResizeBound=!0),k.css3d)}function pn(){let e=new fe;e.setSize(innerWidth,innerHeight),e.domElement.style.cssText=`position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;pointer-events:auto;overflow:hidden;transform-style:preserve-3d`;let t=document.getElementById(`css3d-layer`);return t.style.pointerEvents=`none`,t.appendChild(e.domElement),e}function mn(e,t,n=800,r=530){let i=document.createElement(`div`);i.className=`game-panel-viewport`,i.style.cssText=`position:relative;width:100%;height:min(${Math.max(320,r-100)}px,68vh);min-height:320px;border-radius:16px;overflow:hidden;border:1px solid rgba(255,255,255,0.2);box-shadow:0 0 48px rgba(0,122,255,0.24),0 16px 42px rgba(0,0,0,0.52);background:#000;pointer-events:auto`,i.tabIndex=0;let a=document.createElement(`iframe`);a.src=e,a.className=`game-frame`,a.style.cssText=`position:absolute;inset:0;width:100%;height:100%;border:0;background:#000;pointer-events:auto`,a.setAttribute(`allow`,`autoplay; fullscreen; microphone; camera`),a.setAttribute(`referrerpolicy`,`origin-when-cross-origin`),a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-forms allow-pointer-lock allow-popups`),a.setAttribute(`referrerpolicy`,`no-referrer`),i.append(a);let o=new un({title:t,body:i,icon:`G`,width:Math.min(n,420),height:Math.min(r,640)});return o.el.classList.add(`ar-game-panel`),o.focus(),{object:null,iframe:a,container:i,titleBar:o.el.querySelector(`header`),panel:o,destroy:()=>o.destroy()}}function hn(e){let t=(sn||R().camera)?.fov||60,n=innerHeight,r=Math.tan(l.degToRad(t/2));return e/(n/2/r)}function gn(){if(!an||!on)return;let e=bn()||R().camera;e&&e!==sn&&(sn=e),sn&&(sn.updateMatrixWorld(!0),an.setSize(innerWidth,innerHeight),an.render(on,sn))}function _n(){rn.forEach(e=>e.applyTransform()),k.css3d?.panels?.forEach(e=>e.scale.setScalar(hn(2)))}function vn(){an?.setSize(innerWidth,innerHeight),_n()}function yn(){document.getElementById(`hud-toolbar`)?.addEventListener(`click`,e=>{let t=e.target.closest(`button[data-action]`);if(!t)return;let n=t.dataset.action;document.querySelectorAll(`#hud-toolbar .btn-symbol`).forEach(e=>e.classList.toggle(`selected`,e===t)),n===`models`?j(`open-models`):n===`scan`?j(`scan-room`):n===`games`?j(`open-games`):n===`builder`?j(`open-builder`):n===`vr`?j(`enter-vr`):n===`jarvis`&&j(`open-jarvis`)})}function bn(){try{let e=globalThis.XR8?.Threejs?.xrScene?.()?.camera||null;return e&&(sn=e),e}catch{return null}}function xn(){if(globalThis.XR8?.addCameraPipelineModule){cn&&(dt(cn),cn=0),ln?k.css3dPipelineAdded=!0:(globalThis.XR8.addCameraPipelineModule({name:`css3d-camera-sync`,onRender:()=>gn()}),k.pipelineOrder.push(`css3d-camera-sync`),ln=!0,k.css3dPipelineAdded=!0);return}if(cn)return;let e=()=>{if(k.css3dPipelineAdded){cn=0;return}gn(),cn=F(e)};cn=F(e)}function Sn(e=!1){return!e&&rn.size>0?!1:(cn&&dt(cn),cn=0,an?.domElement?.remove?.(),an=null,on=null,sn=null,k.css3d=null,k.css3dPipelineAdded=!1,ln=!1,!0)}function Cn(){rn.forEach(e=>e.destroy()),rn.clear(),Sn(!0),k.css3dResizeBound=!1,document.querySelectorAll(`#ui-layer .panel-orb, #ui-layer .ar-panel`).forEach(e=>e.remove())}function wn(e,t,n=`O`){let r=typeof t==`string`?document.createElement(`div`):t;return typeof t==`string`&&(r.textContent=t),new un({title:e,body:r,icon:n})}var Tn=[{name:`Duck`,size:`~100KB`,category:`animal`},{name:`Avocado`,size:`~200KB`,category:`food`},{name:`BoxAnimated`,size:`~50KB`,category:`basic`},{name:`BrainStem`,size:`~3MB`,category:`organic`},{name:`CesiumMilkTruck`,size:`~1MB`,category:`vehicle`},{name:`DamagedHelmet`,size:`~30MB`,category:`scifi`},{name:`FlightHelmet`,size:`~30MB`,category:`scifi`},{name:`Fox`,size:`~2MB`,category:`animal`},{name:`GlamVelvetSofa`,size:`~10MB`,category:`furniture`},{name:`Lantern`,size:`~500KB`,category:`object`},{name:`ToyCar`,size:`~3MB`,category:`vehicle`},{name:`WaterBottle`,size:`~1MB`,category:`object`},{name:`AntiqueCamera`,size:`~3MB`,category:`object`},{name:`BarramundiFish`,size:`~2MB`,category:`animal`},{name:`Corset`,size:`~500KB`,category:`clothing`},{name:`ReciprocatingSaw`,size:`~5MB`,category:`tool`},{name:`Sponza`,size:`~50MB`,category:`environment`},{name:`DragonAttenuation`,size:`~5MB`,category:`creature`},{name:`IridescenceLamp`,size:`~2MB`,category:`furniture`},{name:`GlassVaseBacklit`,size:`~1MB`,category:`object`},{name:`MaterialsVariantsShoe`,size:`~5MB`,category:`clothing`},{name:`OrientationTest`,size:`~500KB`,category:`test`},{name:`NormalTangentTest`,size:`~500KB`,category:`test`},{name:`EnvironmentTest`,size:`~2MB`,category:`test`},{name:`SheenCloth`,size:`~2MB`,category:`fabric`}];function En(e){let t=String(e||`Duck`).replace(/[^A-Za-z0-9_-]/g,``);return`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/${t}/glTF-Binary/${t}.glb`}function Dn(e){let t=String(e||``).toLowerCase();return Tn.find(e=>t.includes(e.name.toLowerCase()))||Tn.find(e=>t.includes(e.category.toLowerCase()))||Tn[0]}var On=`jarvis_sketchfab_access_token_v1`,kn=[{slug:`by`,label:`CC BY`},{slug:`by-sa`,label:`CC BY-SA`},{slug:`by-nd`,label:`CC BY-ND`},{slug:`by-nc`,label:`CC BY-NC`},{slug:`by-nc-sa`,label:`CC BY-NC-SA`},{slug:`by-nc-nd`,label:`CC BY-NC-ND`},{slug:`cc0`,label:`CC0`},{slug:`standard`,label:`Free Standard`}],An=kn.map(e=>e.slug),jn=new Set(An);function Mn(e){if(!e)return``;let t=(typeof e==`string`?e:e.slug||e.uid||e.label||e.fullName||e.url||e.uri||``).toString().trim().toLowerCase(),n=t.match(/(?:^|\/)(cc0|standard|by(?:-nc)?(?:-sa|-nd)?)(?:\/|$)/);if(n)return n[1];if(t.includes(`free standard`)||t===`standard`)return`standard`;if(t.includes(`cc0`)||t.includes(`public domain`))return`cc0`;if(!t.includes(`attribution`)&&!t.includes(`creative commons`))return t;let r=t.includes(`noncommercial`)||t.includes(`non-commercial`),i=t.includes(`noderivs`)||t.includes(`no derivatives`)||t.includes(`no-derivatives`),a=t.includes(`sharealike`)||t.includes(`share alike`)||t.includes(`share-alike`);return r&&i?`by-nc-nd`:r&&a?`by-nc-sa`:r?`by-nc`:i?`by-nd`:a?`by-sa`:`by`}function Nn(e){return jn.has(Mn(e))}function Pn(e){let t=Mn(e);return kn.find(e=>e.slug===t)?.label||t.toUpperCase()}function Fn(){try{return sessionStorage.getItem(`jarvis_sketchfab_access_token_v1`)||``}catch{return``}}function In(e){try{let t=String(e||``).trim();t?sessionStorage.setItem(On,t):sessionStorage.removeItem(On),localStorage.removeItem(On)}catch{}}async function Ln(e=`studio`){let t=await fetch(`https://api.polyhaven.com/assets?type=hdris`,{cache:`force-cache`});if(!t.ok)throw Error(`PolyHaven HDR request failed: ${t.status}`);let n=await t.json(),r=Object.keys(n);if(!r.length)throw Error(`PolyHaven returned no HDR assets.`);return`https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/${r.find(t=>t.toLowerCase().includes(String(e).toLowerCase()))||r[0]}_1k.hdr`}function Rn(e,{count:t=12,license:n=``}={}){let r=new URL(`https://api.sketchfab.com/v3/models`);return r.searchParams.set(`q`,String(e||``).trim()),r.searchParams.set(`downloadable`,`true`),r.searchParams.set(`type`,`models`),r.searchParams.set(`count`,String(t)),r.searchParams.set(`archives_flavours`,`true`),n&&r.searchParams.set(`license`,n),r.toString()}async function zn(e,t=``,{count:n=24}={}){let r=Math.max(4,Math.ceil(n/An.length));if(!t){let t=await Kn(e,n);if(t)return t}let i=[],a=[];for(let o of An)try{let a=await Vn(e,t,o,r);if(i.push(a),Bn(i).length>=n)break}catch(e){a.push(e)}let o=Bn(i);if(!o.length&&a.length===An.length)throw Error(a[0]?.message||`Sketchfab search failed for all allowed free licenses.`);let s=new Set;return o.filter(e=>e?.uid&&!s.has(e.uid)&&s.add(e.uid)).filter(e=>e?.isDownloadable!==!1).filter(e=>Nn(e?.license)).map(Hn).slice(0,n)}function Bn(e){let t=[],n=Math.max(0,...e.map(e=>e.length));for(let r=0;r<n;r+=1)for(let n of e)n[r]&&t.push(n[r]);return t}async function Vn(e,t,n,r){let i=t?{Authorization:`Bearer ${t}`}:{},a=await fetch(Rn(e,{count:r,license:n}),{headers:i});if(!a.ok)throw Error(`Sketchfab search failed for ${n}: ${a.status}`);let o=await a.json();return Array.isArray(o.results)?o.results:[]}function Hn(e){return{uid:e.uid,name:e.name||`Sketchfab model`,license:Mn(e.license),licenseLabel:Pn(e.license),author:e.user?.displayName||e.user?.username||`Sketchfab creator`,authorUrl:e.user?.profileUrl||``,viewerUrl:e.viewerUrl||`https://sketchfab.com/3d-models/${e.uid}`,thumbnail:Jn(e.thumbnails),faceCount:e.faceCount||e.archives?.gltf?.faceCount||e.archives?.glb?.faceCount||0,vertexCount:e.vertexCount||e.archives?.gltf?.vertexCount||e.archives?.glb?.vertexCount||0,size:e.archives?.glb?.size||e.archives?.gltf?.size||0,source:e}}async function Un(e,t){if(!t){let t=await qn(e);if(t)return t}if(!t)throw Error(`Sketchfab downloads require a configured OMEGA Sketchfab token or a pasted OAuth/API token.`);let n=await fetch(`https://api.sketchfab.com/v3/models/${encodeURIComponent(e)}/download`,{headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw Error(`Sketchfab download request failed: ${n.status}`);return n.json()}function Wn(e={}){let t=Qn(`omega_session`);return t?{...e,Authorization:`Bearer ${t}`}:{...e}}async function Gn(){try{let e=await fetch(`/api/sketchfab/status`,{cache:`no-store`,headers:Wn()});return e.ok?e.json():{ok:!1,configured:!1}}catch{return{ok:!1,configured:!1}}}async function Kn(e,t){try{let n=new URLSearchParams({q:String(e||``).trim(),count:String(t)}),r=await fetch(`/api/sketchfab/search?${n}`,{cache:`no-store`,headers:Wn()});if(!r.ok)return null;let i=await r.json();return!i?.ok||!Array.isArray(i.models)?null:i.models.filter(e=>Nn(e.license)).map(e=>({uid:e.uid,name:e.name||`Sketchfab model`,license:Mn(e.license),licenseLabel:Pn(e.license),author:e.author||`Sketchfab creator`,authorUrl:e.authorUrl||``,viewerUrl:e.viewerUrl||`https://sketchfab.com/3d-models/${e.uid}`,thumbnail:e.thumbnail||``,faceCount:e.faceCount||0,vertexCount:e.vertexCount||0,size:e.size||0,source:e}))}catch{return null}}async function qn(e){try{let t=new URLSearchParams({uid:String(e||``)}),n=await fetch(`/api/sketchfab/download?${t}`,{cache:`no-store`,headers:Wn()});if(!n.ok)return null;let r=await n.json();return!r?.ok||!r.download?null:r.download}catch{return null}}function Jn(e){return[...Array.isArray(e?.images)?e.images:[]].sort((e,t)=>(t.width||0)-(e.width||0))[0]?.url||``}var Yn=[{name:`Tractor`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/glTF-Binary/CesiumMilkTruck.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/screenshot/screenshot-thumb.png`},{name:`Racecar`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/glTF-Binary/ToyCar.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/screenshot/screenshot-thumb.png`},{name:`Duck`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/glTF-Binary/Duck.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`},{name:`Lantern`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/screenshot/screenshot-thumb.png`},{name:`Sofa`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/GlamVelvetSofa/glTF-Binary/GlamVelvetSofa.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/GlamVelvetSofa/screenshot/screenshot-thumb.png`},{name:`Water Bottle`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/glTF-Binary/WaterBottle.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/screenshot/screenshot-thumb.png`},{name:`Antique Camera`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/AntiqueCamera/glTF-Binary/AntiqueCamera.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/AntiqueCamera/screenshot/screenshot-thumb.png`},{name:`Saw`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ReciprocatingSaw/glTF-Binary/ReciprocatingSaw.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ReciprocatingSaw/screenshot/screenshot-thumb.png`},{name:`Castle Sponza`,provider:`kenney`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Sponza/glTF-Binary/Sponza.glb`,license:`cc0`,author:`Kenney.nl`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Sponza/screenshot/screenshot-thumb.png`},{name:`Robot Expressive`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/RobotExpressive.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake1.png`},{name:`Soldier`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake2.png`},{name:`Flamingo`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Flamingo.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake3.png`},{name:`Parrot`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Parrot.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake4.png`},{name:`Stork`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Stork.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake5.png`},{name:`Sheen Chair`,provider:`quaternius`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,license:`cc0`,author:`Quaternius.com`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake6.png`},{name:`XBot Rigged`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Xbot.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake1.png`},{name:`Soldier Rigged`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake2.png`},{name:`Robot Anim`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/RobotExpressive.glb`,license:`free`,author:`Mixamo / Adobe`,thumbnail:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/textures/sprites/snowflake3.png`}];function Xn(e){return String(e||``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}function Zn(e){return String(e||``).charAt(0).toUpperCase()+String(e||``).slice(1)}function Qn(e){try{return localStorage.getItem(`jarvis_${e}_credentials_v1`)||``}catch{return``}}function $n(e,t){try{localStorage.setItem(`jarvis_${e}_credentials_v1`,String(t||``).trim())}catch{}}try{if(typeof localStorage<`u`)for(let e of[`jarvis_poly_pizza_credentials_v1`,`jarvis_cgtrader_credentials_v1`,`jarvis_turbosquid_credentials_v1`,`jarvis_mixamo_credentials_v1`]){let t=localStorage.getItem(e);(t===`omega-public-free-poly-pizza-key-2026`||t===`cgtrader_omega_public_free_session`||t===`turbosquid_omega_public_free_session`||t===`mixamo_omega_public_free_adobe_id`)&&localStorage.removeItem(e)}}catch{}async function er(e,t,n){try{let r=new URL(`https://www.cgtrader.com/api/v1/models`);r.searchParams.set(`q`,String(e||``).trim()),r.searchParams.set(`free`,`true`),r.searchParams.set(`per_page`,String(Math.min(n,24))),r.searchParams.set(`sort`,`relevance`),r.searchParams.set(`file_type`,`glb,gltf,fbx,obj`);let i=await fetch(r.toString(),{headers:{Authorization:`Token ${t}`,Accept:`application/json`}});if(!i.ok)throw Error(`CGTrader API returned ${i.status}`);let a=await i.json(),o=Array.isArray(a.data)?a.data:Array.isArray(a.models)?a.models:[];if(o.length)return o.map(e=>({uid:`cgtrader:${e.id||e.uid||e.slug}`,name:e.name||e.title||`CGTrader Model`,license:e.license||`free`,licenseLabel:e.license_label||`Free Standard`,author:e.author?.username||e.user?.name||`CGTrader Creator`,authorUrl:`https://www.cgtrader.com/designers/${e.author?.username||``}`,viewerUrl:e.url||`https://www.cgtrader.com/3d-models/${e.slug||e.id}`,thumbnail:e.previews?.[0]?.url||e.preview_url||e.thumbnail||``,faceCount:e.polygon_count||0,vertexCount:e.vertex_count||0,size:e.total_size||0,downloadUrl:e.download_url||e.files?.[0]?.url||``,source:`cgtrader`})).slice(0,n)}catch{}let r=new URLSearchParams({q:String(e||``).trim(),count:String(n),api_key:t}),i=await fetch(`/api/cgtrader/search?${r}`,{cache:`no-store`,headers:Wn()});if(!i.ok)throw Error(`OMEGA CGTrader proxy returned ${i.status}`);let a=await i.json();if(!a?.ok||!Array.isArray(a.models)||!a.models.length)throw Error(`CGTrader proxy: no results`);return a.models.map(e=>({...e,source:`cgtrader`})).slice(0,n)}async function tr(e,t,n){let r=String(t||``).indexOf(`:`),i=r>0?t.slice(0,r).trim():``,a=r>0?t.slice(r+1).trim():``;try{let t=new URL(`https://www.turbosquid.com/turbosquid/search/api/search`);t.searchParams.set(`search_keyword`,String(e||``).trim()),t.searchParams.set(`price_min`,`0`),t.searchParams.set(`price_max`,`0`),t.searchParams.set(`media_typeid`,`2`),t.searchParams.set(`file_type`,`glb,gltf,fbx`),t.searchParams.set(`per_page`,String(Math.min(n,24))),t.searchParams.set(`sort_by`,`relevance`);let r={Accept:`application/json`};i&&a&&(r.Authorization=`Bearer ${a}`);let o=await fetch(t.toString(),{headers:r});if(!o.ok)throw Error(`TurboSquid API returned ${o.status}`);let s=await o.json(),c=Array.isArray(s.results)?s.results:Array.isArray(s.products)?s.products:[];if(c.length)return c.map(e=>({uid:`turbosquid:${e.id||e.product_id||e.slug}`,name:e.name||e.title||`TurboSquid Model`,license:e.license||`free`,licenseLabel:e.license_label||`Free Standard`,author:e.artist?.username||e.author||`TurboSquid Artist`,authorUrl:`https://www.turbosquid.com/Search/Artists/${e.artist?.username||``}`,viewerUrl:e.url||`https://www.turbosquid.com/3d-models/${e.slug||e.id}`,thumbnail:e.thumbnail_url||e.preview_url||e.thumbnail||``,faceCount:e.polygon_count||0,vertexCount:e.vertex_count||0,size:e.file_size||0,downloadUrl:e.download_url||e.files?.[0]?.download_url||``,source:`turbosquid`})).slice(0,n)}catch{}let o=new URLSearchParams({q:String(e||``).trim(),count:String(n)});i&&o.set(`username`,i),a&&o.set(`api_key`,a);let s=await fetch(`/api/turbosquid/search?${o}`,{cache:`no-store`,headers:Wn()});if(!s.ok)throw Error(`OMEGA TurboSquid proxy returned ${s.status}`);let c=await s.json();if(!c?.ok||!Array.isArray(c.models)||!c.models.length)throw Error(`TurboSquid proxy: no results`);return c.models.map(e=>({...e,source:`turbosquid`})).slice(0,n)}async function nr(e,t,n){let r=String(t||``).indexOf(`:`);if(r<1)throw Error(`Mixamo: credentials must be adobe_email:adobe_password`);let i=t.slice(0,r).trim(),a=t.slice(r+1).trim();if(!i||!a)throw Error(`Mixamo: email or password empty`);try{let t=await fetch(`https://ims-na1.adobelogin.com/ims/token/v3`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`password`,username:i,password:a,client_id:`mixamo_studio`,client_secret:`mixamo_studio`,scope:`openid,creative_sdk,avatar_sync`})});if(!t.ok)throw Error(`Adobe IMS auth failed: ${t.status}`);let r=(await t.json()).access_token;if(!r)throw Error(`Adobe IMS returned no access_token`);let o=new URL(`https://mixamo-api.adobe.com/v1/products`);o.searchParams.set(`limit`,String(Math.min(n,24))),o.searchParams.set(`offset`,`0`),e&&o.searchParams.set(`query`,String(e).trim()),o.searchParams.set(`type`,`Character,Motion`),o.searchParams.set(`order_by`,`relevance`);let s=await fetch(o.toString(),{headers:{Authorization:`Bearer ${r}`,"X-Api-Key":`mixamo_studio`,Accept:`application/json`}});if(!s.ok)throw Error(`Mixamo API returned ${s.status}`);let c=await s.json(),l=Array.isArray(c.results)?c.results:Array.isArray(c.data)?c.data:[];if(l.length)return l.map(e=>({uid:`mixamo:${e.id||e.character_id||e.slug}`,name:e.name||e.character_name||`Mixamo Character`,license:`free`,licenseLabel:`Free (Mixamo)`,author:`Mixamo / Adobe`,authorUrl:`https://www.mixamo.com/#/?id=${e.id||``}`,viewerUrl:`https://www.mixamo.com/#/?id=${e.id||``}`,thumbnail:e.thumbnail_url||e.preview_url||e.image||``,faceCount:e.polygon_count||0,vertexCount:0,size:0,downloadUrl:e.export_url||``,source:`mixamo`})).slice(0,n)}catch{}let o=await fetch(`/api/mixamo/search`,{method:`POST`,headers:Wn({"Content-Type":`application/json`}),body:JSON.stringify({email:i,password:a,q:String(e||``).trim(),count:n}),cache:`no-store`});if(!o.ok)throw Error(`OMEGA Mixamo proxy returned ${o.status}`);let s=await o.json();if(!s?.ok||!Array.isArray(s.models)||!s.models.length)throw Error(`Mixamo proxy: no results`);return s.models.map(e=>({...e,source:`mixamo`})).slice(0,n)}async function rr(e,t,n){let r=`https://api.poly.pizza/v1/search?q=${encodeURIComponent(e)}`,i=await fetch(r,{headers:{"x-auth-token":t}});if(!i.ok)throw Error(`Poly.pizza returned ${i.status}`);return((await i.json()).results||[]).map(e=>({uid:`poly_pizza:${e.id||e.uid}`,name:e.title||e.name||`Poly.pizza model`,license:e.license||`cc0`,licenseLabel:e.license||`CC0`,author:e.author||`Poly.pizza Creator`,authorUrl:`https://poly.pizza/m/${e.id||e.uid}`,viewerUrl:`https://poly.pizza/m/${e.id||e.uid}`,thumbnail:e.thumbnail||`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:e.faceCount||0,vertexCount:e.vertexCount||0,size:e.size||0,downloadUrl:e.Download||e.url||``,source:`poly_pizza`})).slice(0,n)}async function ir(e,t=`all`,n=``,{count:r=24}={}){let i=String(e||``).trim().toLowerCase(),a=[];(t===`all`||t===`stable_fast_3d`)&&i&&a.push({uid:`stable_fast_3d:generate:${Xn(i)}`,name:`Generate: "${i}"`,license:`Local AI Generation`,licenseLabel:`Local`,author:`Stable Fast 3D (Jarvis)`,authorUrl:``,viewerUrl:``,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Box/glTF/Box_thumbnail.jpg`,faceCount:0,vertexCount:0,size:0,downloadUrl:`api:spawn_3d_model:${i}`,source:`stable_fast_3d`,catalogSource:`ai-generation`,provider:`stable_fast_3d`});let o=Qn(`poly_pizza`);if((t===`all`||t===`poly_pizza`)&&o&&i)try{let e=await rr(i,o,r);a.push(...e)}catch{}let s=Qn(`cgtrader`);if((t===`all`||t===`cgtrader`)&&s&&i)try{let e=await er(i,s,r);a.push(...e)}catch{}let c=Qn(`turbosquid`);if((t===`all`||t===`turbosquid`)&&c&&i)try{let e=await tr(i,c,r);a.push(...e)}catch{}let l=Qn(`mixamo`);if((t===`all`||t===`mixamo`)&&l&&i)try{let e=await nr(i,l,r);a.push(...e)}catch{}let u=Yn.filter(e=>{let n=t===`all`||e.provider===t,r=!i||e.name.toLowerCase().includes(i)||e.author.toLowerCase().includes(i);return n&&r}).map(e=>({uid:`${e.provider}:${Xn(e.name)}`,name:e.name,license:e.license,licenseLabel:e.license===`cc0`?`CC0`:`Free`,author:e.author,authorUrl:e.url,viewerUrl:e.url,thumbnail:e.thumbnail,faceCount:0,vertexCount:0,size:0,downloadUrl:e.url,source:e.provider,catalogSource:`curated-sample`,provider:e.provider}));if(a.push(...u),t===`all`||t===`cgtrader`||t===`turbosquid`||t===`poly_pizza`||t===`mixamo`){let e=[{name:`Retro Space Ship`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/DamagedHelmet/glTF-Binary/DamagedHelmet.glb`,keywords:[`space`,`ship`,`rocket`,`vehicle`,`helmet`,`sci-fi`,`scifi`]},{name:`SciFi Plasma Gun`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`gun`,`weapon`,`scifi`,`plasma`,`laser`]},{name:`Modern Office Chair`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,keywords:[`chair`,`furniture`,`office`,`seat`]},{name:`Astronaut Character`,license:`Free Standard`,author:`Sample fallback asset`,provider:`cgtrader`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,keywords:[`astronaut`,`person`,`space`,`character`]},{name:`City Sports Car`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/ToyCar/glTF-Binary/ToyCar.glb`,keywords:[`car`,`vehicle`,`sports`,`auto`,`toy`]},{name:`Fighter Jet Plane`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/CesiumMilkTruck/glTF-Binary/CesiumMilkTruck.glb`,keywords:[`plane`,`jet`,`aircraft`,`vehicle`,`fly`]},{name:`Lighthouse Beacon`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`lighthouse`,`beacon`,`tower`,`building`]},{name:`Industrial Wooden Crate`,license:`Free Standard`,author:`Sample fallback asset`,provider:`turbosquid`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/glTF-Binary/Duck.glb`,keywords:[`crate`,`box`,`barrel`,`wood`,`industrial`]},{name:`Low Poly Tree Pack`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Lantern/glTF-Binary/Lantern.glb`,keywords:[`tree`,`forest`,`plant`,`nature`,`lowpoly`]},{name:`Holographic Gizmo Sphere`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/OrientationTest/glTF-Binary/OrientationTest.glb`,keywords:[`sphere`,`gizmo`,`hologram`,`test`]},{name:`Magical Potion Bottle`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/WaterBottle/glTF-Binary/WaterBottle.glb`,keywords:[`potion`,`magic`,`bottle`,`drink`]},{name:`Mythical Knight Shield`,license:`CC0`,author:`Sample fallback asset`,provider:`poly_pizza`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/SheenChair.glb`,keywords:[`shield`,`armor`,`knight`,`weapon`]},{name:`YBot Rigged Character`,license:`Free`,author:`Sample fallback asset`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Xbot.glb`,keywords:[`ybot`,`character`,`man`,`rigged`,`skeletal`]},{name:`Zombie Undead Anim`,license:`Free`,author:`Sample fallback asset`,provider:`mixamo`,url:`https://raw.githubusercontent.com/mrdoob/three.js/master/examples/models/gltf/Soldier.glb`,keywords:[`zombie`,`monster`,`undead`,`animated`,`rigged`]}].filter(e=>{let n=t===`all`||e.provider===t,r=!i||e.name.toLowerCase().includes(i)||e.keywords.some(e=>i.includes(e)||e.includes(i));return n&&r}).map(e=>({uid:`${e.provider}:${Xn(e.name)}`,name:e.name,license:`free`,licenseLabel:e.license,author:e.author,authorUrl:e.url,viewerUrl:e.url,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:0,vertexCount:0,size:0,downloadUrl:e.url,source:e.provider,catalogSource:`sample-fallback`,provider:e.provider}));a.push(...e)}if(t===`all`||t===`sketchfab`)try{let t=await zn(e,n,{count:r});a.push(...t.map(e=>({...e,downloadUrl:``,source:`sketchfab`})))}catch{}let d=new Set;return a=a.filter(e=>e?.uid&&!d.has(e.uid)&&d.add(e.uid)),!a.length&&i&&a.push({uid:`forge:${Xn(i)}`,name:`${Zn(i)} (Interactive Forge)`,license:`free`,licenseLabel:`CC0 / Procedural`,author:`Jarvis Model Forge`,authorUrl:`#`,viewerUrl:`#`,thumbnail:`https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Duck/screenshot/screenshot-thumb.png`,faceCount:0,vertexCount:0,size:0,downloadUrl:`forge-procedural`,source:`forge`}),a.slice(0,r)}function ar(e,t){try{let n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function or(e,t){try{return localStorage.setItem(e,JSON.stringify(t)),!0}catch{return!1}}function sr(e,t=``){try{return localStorage.getItem(e)||t}catch{return t}}function cr(e,t){try{return localStorage.setItem(e,String(t)),!0}catch{return!1}}var lr=0,ur=!1;function dr(e=`ar`){let t=globalThis.crypto?.getRandomValues?Array.from(globalThis.crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,`0`)).join(``):(()=>{ur||(ur=!0),lr=(lr+1)%1048576;let e=String(globalThis.performance?.now?.()||0).replace(`.`,``);return`${Date.now().toString(36)}_${e}_${lr.toString(36)}`})();return`${e}_${Date.now().toString(36)}_${t}`}function fr(e,t,{valueKey:n=null,labelKey:r=null}={}){if(e){e.replaceChildren();for(let i of t){let t=document.createElement(`option`);if(Array.isArray(i)||n&&r&&i&&typeof i==`object`){let[e,a]=Array.isArray(i)?i:[i[n],i[r]];t.value=String(e??``),t.textContent=String(a??e??``)}else t.value=String(i),t.textContent=String(i);e.appendChild(t)}}}var pr=1,mr=2048,hr=8;function gr(e){let t=new Set,n=new Set,r=new Set,i=0,a=0;if(!e?.traverse)return{bytes:0,geometryCount:0,materialCount:0,textureCount:0,maxDimension:0,warnings:[]};e.updateMatrixWorld?.(!0);let o=new ge().setFromObject(e);if(!o.isEmpty()){let e=o.getSize(new w);a=Math.max(e.x,e.y,e.z,0)}e.traverse(e=>{e.geometry&&!t.has(e.geometry)&&(t.add(e.geometry),i+=Sr(e.geometry)),br(e.material,e=>{n.has(e)||(n.add(e),i+=2048),xr(e,(e,t)=>{r.has(e)||(r.add(e),i+=Cr(e))})})});let s=[];return i>48*1024*1024&&s.push(`model-asset-heavy`),r.size>12&&s.push(`texture-count-high`),a>12&&s.push(`model-scale-large`),{bytes:i,geometryCount:t.size,materialCount:n.size,textureCount:r.size,maxDimension:a,warnings:s}}function _r(e,t={}){if(!e?.traverse)return e;let n=Number.isFinite(t.targetSize)?t.targetSize:pr,r=Number.isFinite(t.maxTextureSize)?t.maxTextureSize:mr,i=Number.isFinite(t.maxAnisotropy)?t.maxAnisotropy:hr,a=gr(e),o=new ge().setFromObject(e);if(!o.isEmpty()){let t=o.getSize(new w),r=n/Math.max(t.x,t.y,t.z,1e-4),i=o.getCenter(new w);e.position.sub(i),e.scale.multiplyScalar(r)}return e.userData=e.userData||{},e.userData.assetMetrics=a,e.userData.assetWarnings=a.warnings.slice(),e.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0,e.material&&br(e.material,(e,t)=>{vr(e,{maxTextureSize:r,maxAnisotropy:i})}))}),e.updateMatrixWorld?.(!0),e}function vr(e,t={}){if(!e)return e;let n=Number.isFinite(t.maxTextureSize)?t.maxTextureSize:mr,r=Number.isFinite(t.maxAnisotropy)?t.maxAnisotropy:hr;return e.userData=e.userData||{},e.needsUpdate=!0,`roughness`in e&&(e.roughness=wr(e.roughness)),`metalness`in e&&(e.metalness=wr(e.metalness)),`emissiveIntensity`in e&&(e.emissiveIntensity=Math.min(Number(e.emissiveIntensity??1),1)),xr(e,(e,t)=>{yr(e,t,{maxTextureSize:n,maxAnisotropy:r})}),e}function yr(e,t=``,n={}){if(!e)return e;let r=Number.isFinite(n.maxTextureSize)?n.maxTextureSize:mr,i=Number.isFinite(n.maxAnisotropy)?n.maxAnisotropy:hr,a=e.image||{},o=a.width||a.videoWidth||a.naturalWidth||0,s=a.height||a.videoHeight||a.naturalHeight||0;return/map|baseColor|albedo|diffuse|emissive/i.test(t)&&(e.colorSpace=pe),e.flipY=!1,e.generateMipmaps=o>0&&s>0,e.minFilter=o>r||s>r?g:_,e.magFilter=g,e.anisotropy=Math.max(1,Math.min(i,e.anisotropy||i)),e.needsUpdate=!0,e}function br(e,t){(Array.isArray(e)?e:[e]).filter(Boolean).forEach(e=>t(e))}function xr(e,t){let n=new Set,r=(e,i=``)=>{if(!(!e||typeof e!=`object`)){if(e.isTexture){n.has(e)||(n.add(e),t(e,i));return}if(Array.isArray(e)){e.forEach(e=>r(e,i));return}e.value?.isTexture?r(e.value,i):e.constructor===Object&&Object.entries(e).forEach(([e,t])=>r(t,e))}};Object.entries(e||{}).forEach(([e,t])=>r(t,e))}function Sr(e){let t=0,n=e=>{e?.array?.byteLength&&(t+=e.array.byteLength)};return Object.values(e.attributes||{}).forEach(n),Object.values(e.morphAttributes||{}).forEach(e=>e.forEach(n)),n(e.index),t}function Cr(e){let t=e?.image||{};if(t.data?.byteLength)return t.data.byteLength;let n=t.width||t.videoWidth||t.naturalWidth||256,r=t.height||t.videoHeight||t.naturalHeight||256;return Math.max(1,n)*Math.max(1,r)*4}function wr(e){return Math.max(0,Math.min(1,Number(e)||0))}var Tr=`jarvis_ar_model_forge_v1`,Er=[`house`,`room`,`device`,`vehicle`,`character`,`scene`],Dr=[`open`,`close`,`toggle`,`rotate`,`reveal`,`hide`,`shatter`,`reconfigure`];function Or(){if(globalThis.crypto?.getRandomValues){let e=new Uint32Array(1);return globalThis.crypto.getRandomValues(e),e[0]/4294967295}return performance.now()%997/997}function kr(){return ar(Tr,[])}function Ar(e){let t=kr().filter(t=>t.id!==e.id);return t.push(e),or(Tr,t.slice(-40)),e}function z({name:e=`Custom Model`,prompt:t=``,kit:n=`scene`,parts:r=[],behaviors:i=[]}={}){let a=Er.includes(String(n||``).toLowerCase())?String(n).toLowerCase():`scene`;return{id:dr(`blueprint`),name:String(e||`Custom Model`).trim()||`Custom Model`,prompt:String(t||``).trim(),kit:a,parts:Array.isArray(r)&&r.length?r.map(ti):li(a),behaviors:Array.isArray(i)&&i.length?i.map(ni):ui(a),createdAt:Date.now(),updatedAt:Date.now()}}async function jr(e,t={}){let n=String(e||``).trim();if(!n)throw Error(`A prompt is required to generate a blueprint.`);let r=globalThis.Jarvis;if(!r?.query)return E(`Jarvis is unavailable, so the model forge is using a local template blueprint instead.`,`Model Forge`),z({name:t.name||n.slice(0,24),prompt:n,kit:t.kit||`scene`});let i=[`Create a compact JSON blueprint for a fully interactive 3D model.`,`Return JSON only, no markdown, no prose.`,`Schema:`,`{`,`  "name": "string",`,`  "kit": "house|room|device|vehicle|character|scene",`,`  "parts": [`,`    {`,`      "name": "string",`,`      "type": "base|wall|door|window|roof|drawer|panel|screen|wheel|prop|light|arm|leg|head|detail",`,`      "geometry": "box|sphere|cylinder|cone|torus|ring|capsule|octahedron|icosahedron",`,`      "material": "matte|metal|glass|glow|wood",`,`      "position": [0,0,0],`,`      "rotation": [0,0,0],`,`      "scale": [1,1,1],`,`      "actions": ["open","close","toggle","rotate","reveal","hide","shatter","reconfigure"]`,`    }`,`  ],`,`  "behaviors": [`,`    { "gesture": "pinch|fist|open-palm|swipe-left|swipe-right|two-hand-scale", "action": "string", "target": "part name" }`,`  ]`,`}`,`Prompt: ${n}`,t.name?`Preferred name: ${t.name}`:``,t.kit?`Preferred kit: ${t.kit}`:``].filter(Boolean).join(`
`);try{let e=hi(await r.query(i));if(e){let r=z({name:e.name||t.name||n.slice(0,24),prompt:n,kit:e.kit||t.kit||`scene`,parts:Array.isArray(e.parts)?e.parts:[],behaviors:Array.isArray(e.behaviors)?e.behaviors:[]});return r.prompt=n,r.source=`jarvis`,r.updatedAt=Date.now(),r}}catch(e){E(`Jarvis blueprint generation failed, using local template: ${e.message}`,`Model Forge`)}return z({name:t.name||n.slice(0,24),prompt:n,kit:t.kit||oi(n)})}function Mr(e,t=ve){let n=e?.id?e:z(e),r=new t.Group;r.name=`interactive-${H(n.name)}`,r.userData.isARObject=!0,r.userData.modelName=n.name,r.userData.modelForge={id:n.id,kit:n.kit,prompt:n.prompt,behaviors:n.behaviors,parts:[],state:{}};let i=[],a={base:[],walls:[],doors:[],windows:[],roofs:[],details:[],lights:[],wheels:[],screens:[],arms:[],legs:[],heads:[],drawers:[]};for(let e of n.parts){let n=Wr(e,t);i.push(n),r.add(n.root),a[ii(e.type)].push(n),r.userData.modelForge.parts.push({id:n.id,name:n.name,type:n.type,actions:n.actions.slice()})}return Gr(r,a,n,t),Nr(r,n),Ar(n),r}function Nr(e,t){return e.userData.modelForge=e.userData.modelForge||{},e.userData.modelForge.id=t.id,e.userData.modelForge.kit=t.kit,e.userData.modelForge.prompt=t.prompt,e.userData.modelForge.behaviors=Array.isArray(t.behaviors)?t.behaviors.map(ni):[],e.userData.modelForge.parts=e.userData.modelForge.parts||[],e}function Pr(e,t,{minScore:n=.5,minHits:r=2}={}){let i=String(e||``).toLowerCase(),a=new Set((t||[]).map(e=>H(e.name)).filter(Boolean));if(!a.size)return null;let o=null,s=0;for(let e of kr()){if(!e||e.source!==`jarvis`||String(e.kit||``).toLowerCase()!==i)continue;let t=Array.isArray(e.behaviors)?e.behaviors:[],c=[...new Set(t.map(e=>H(e.target)).filter(Boolean))];if(!c.length)continue;let l=c.filter(e=>a.has(e)).length,u=l/c.length;l>=r&&u>=n&&u>s&&(o=e,s=u)}return o?{blueprint:o,score:s}:null}function Fr(e,t={}){if(!e)throw Error(`No model object was provided.`);let n=t.kit||si(e),r=Array.isArray(t.parts)&&t.parts.length?t.parts:Ir(e,n),i=t.name||e.userData?.modelName||`Custom Model`,a=Pr(n,r);if(a){let o={...a.blueprint,id:dr(`blueprint`),name:i,prompt:t.prompt||a.blueprint.prompt||``,parts:r.map(ti),source:`template-reuse`,templateOf:a.blueprint.id,updatedAt:Date.now()};return Nr(e,o),e.userData.modelForgeBlueprint=o,j(`forge-template-reused`,{name:i,kit:n,score:a.score,templateOf:a.blueprint.id}),E(`Reused interactive template for ${i} (${Math.round(a.score*100)}% part match) — no regeneration needed.`,`Model Forge`),o}let o=z({name:i,prompt:t.prompt||``,kit:n,parts:r,behaviors:t.behaviors||ui(n,r)});return Nr(e,o),e.userData.modelForgeBlueprint=o,globalThis.Jarvis?.query&&jr(`We have a 3D model named "${i}" (kit: "${n}") containing discovered parts: ${r.map(e=>e.name).join(`, `)}. Create an ultimate interactive Stark-level behavioral blueprint. Generate highly custom actions (like 'raise landing gear', 'ignite thruster', 'open cockpit') and bind them to the correct parts using gestures.`,{name:i,kit:n}).then(t=>{t&&t.source===`jarvis`&&(Nr(e,t),e.userData.modelForgeBlueprint=t,Ur(e),j(`object-placed`,{object:e,modelName:i}),j(`assistant`,`Stark Interface synchronized for ${i}. Loaded bespoke interactive controls.`),E(`Stark Interface synchronized for ${i}.`,`Jarvis AI`))}).catch(e=>{E(`Jarvis background blueprint upgrade failed for ${i}.`,`Model Forge`)}),o}function Ir(e,t=si(e)){let n=[];return e?.traverse?.(t=>{!t.isMesh&&!t.isObject3D||t!==e&&n.push({name:t.name||t.userData?.partName||t.userData?.role||`part_${n.length+1}`,type:ii(t.userData?.role||t.userData?.partType||ai(t.name)),material:`matte`,position:[t.position.x,t.position.y,t.position.z],rotation:[t.rotation.x,t.rotation.y,t.rotation.z],scale:[t.scale.x,t.scale.y,t.scale.z],actions:di(t.userData?.role||ai(t.name))})}),n.length>=2?n:mi(e,t,n)}function Lr(e,t=document.createElement(`div`)){let n=e?.userData?.modelForge,r=Array.isArray(n?.behaviors)&&n.behaviors.length?[...new Set(n.behaviors.map(e=>e.action).filter(Boolean))]:Dr;t.replaceChildren(),t.style.cssText=`display:flex;flex-wrap:wrap;gap:8px`;for(let n of r){let r=document.createElement(`button`);r.className=`panel-action`,r.textContent=n,r.onclick=()=>Vr(e,n),t.appendChild(r)}return t}function Rr(e,t){let n=e.parent||t.parent;if(!n)return!1;let r=new ge().setFromObject(t),i=Number.isFinite(r.max.y)?r.max.y:t.position.y+.2,a=Number.isFinite(r.min.x)&&Number.isFinite(r.max.x)?(r.min.x+r.max.x)/2:t.position.x,o=Number.isFinite(r.min.z)&&Number.isFinite(r.max.z)?(r.min.z+r.max.z)/2:t.position.z,s=new Se;n.add(s);let c=[];for(let e=0;e<20;e++){let t=new h(new be(.015,8,8),new b({color:3388415,transparent:!0,opacity:.85}));t.position.set(a+(Or()-.5)*.04,i,o+(Or()-.5)*.04),s.add(t),c.push({mesh:t,velocity:new w((Or()-.5)*.05,-.4-Or()*.3,(Or()-.5)*.05),delay:e*60})}let l=performance.now(),u=2e3,d=()=>{let e=performance.now()-l;if(e>u){n.remove(s),s.traverse(e=>{e.isMesh&&(e.geometry?.dispose(),e.material?.dispose())});return}c.forEach(n=>{if(e>n.delay){n.velocity.y-=.012,n.mesh.position.addScaledVector(n.velocity,.016);let r=1-(e-n.delay)/(u-n.delay);n.mesh.material.opacity=Math.max(0,r*.85),n.mesh.position.y<t.position.y-.3&&n.mesh.scale.multiplyScalar(.94)}}),requestAnimationFrame(d)};return d(),E(`Water flowing successfully from ${t.userData?.modelName||`source`}.`,`Water Flow`),!0}function zr(e,t,n){let r=!1;return e.traverse(e=>{let t=String(e.name||``).toLowerCase(),i=String(e.userData?.partType||``).toLowerCase();(i.includes(`light`)||i.includes(`lamp`)||i.includes(`glow`)||t.includes(`light`)||t.includes(`lamp`)||t.includes(`glow`))&&(r=!0,e.userData.partState=e.userData.partState||{},e.userData.partState.open=n,e.traverse(e=>{e.isLight&&(e.visible=n,e.intensity=n?2.5:0)}),e.isMesh&&e.material&&(n?(e.material.emissive&&e.material.emissive.setHex(16771584),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=2),e.material.color&&e.material.color.setHex(16771584)):(e.material.emissive&&e.material.emissive.setHex(0),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=0),e.material.color&&e.material.color.setHex(8109311))))}),r?(E(n?`Lights turned ON successfully.`:`Lights turned OFF successfully.`,`Lighting Control`),!0):!1}function Br(e,t){let n=null,r=t.replace(`open-`,``).replace(`close-`,``).replace(`toggle-`,``).trim().toLowerCase();if(e.traverse(e=>{if(n)return;let t=String(e.userData?.partName||e.name||``).toLowerCase();(t.includes(r)||r===`boot`&&t.includes(`trunk`)||r===`trunk`&&t.includes(`boot`))&&(n=e)}),n){let e=t.startsWith(`open-`)||t.startsWith(`toggle-`)&&!n.userData.partState?.open;return qr(n,e),E(`${e?`Opening`:`Closing`} ${n.userData.partName||r} pivot hinge.`,`Hinge Action`),!0}return!1}function Vr(e,t,n={}){if(!e)return!1;let r=String(t||``).toLowerCase().trim().replace(/\s+/g,`-`);if(/^(open|close|toggle)-(boot|hood|trunk|door|door-left|door-right)$/.test(r)&&Br(e,r)||/^(turn-on-lights|on-lights|lights-on|lights-off|off-lights|turn-off-lights|lights|on|off)$/.test(r)&&zr(e,e,!r.includes(`off`)&&r!==`off`)||/^(bring-water|pour-water|pour|water|fill)$/.test(r)&&Rr(e,e))return!0;let i=(e.userData?.modelForge?.behaviors||[]).filter(e=>e.action===r||e.gesture===r),a=i.length?i.map(t=>ei(e,t.target)).filter(Boolean):[e],o=!1;for(let t of a)o=Kr(e,t,r,n)||o;return!o&&e!==a[0]&&(o=Kr(e,e,r,n)),o}function Hr(e,t,n={}){let r=String(t||``).toLowerCase(),i=(e?.userData?.modelForge?.behaviors||[]).filter(e=>e.gesture===r);if(!i.length)return r===`pinch`?Vr(e,`toggle`,n):r===`fist`?Vr(e,`grab`,n):r===`swipe-left`?Vr(e,`close`,n):r===`swipe-right`?Vr(e,`open`,n):r===`two-hand-scale`?Vr(e,`reconfigure`,n):!1;let a=!1;for(let t of i)a=Kr(e,ei(e,t.target)||e,t.action,n)||a;return a}function Ur(e){let t=e?.userData?.modelForgeBlueprint||e?.userData?.modelForge;return t?Ar({...t,updatedAt:Date.now(),name:e.userData?.modelName||t.name||`Custom Model`}):null}function Wr(e,t){let n=dr(`part`),r=String(e.name||e.role||`part_${n.slice(-4)}`).trim()||`part_${n.slice(-4)}`,i=ii(e.type||e.role),a=fi(e.material,t),o=new t.Group;o.name=`${H(r)}_root`,o.position.fromArray(gi(e.position)),o.rotation.set(..._i(e.rotation)),o.scale.set(...vi(e.scale)),o.userData.partId=n,o.userData.partName=r,o.userData.partType=i,o.userData.partActions=Array.isArray(e.actions)&&e.actions.length?e.actions.map(ri):di(i);let s=null,c=null;if(e.geometry){let n=String(e.geometry).toLowerCase().trim();n===`box`||n===`cube`?c=new t.BoxGeometry(.25,.25,.25):n===`sphere`?c=new t.SphereGeometry(.15,32,16):n===`cylinder`?c=new t.CylinderGeometry(.1,.1,.28,24):n===`cone`?c=new t.ConeGeometry(.12,.26,24):n===`torus`?c=new t.TorusGeometry(.14,.02,12,48):n===`ring`?c=new t.RingGeometry(.08,.14,32):n===`capsule`?c=new t.CapsuleGeometry(.08,.2,8,24):n===`octahedron`?c=new t.OctahedronGeometry(.12):n===`icosahedron`&&(c=new t.IcosahedronGeometry(.12))}if(c)s=new t.Mesh(c,a),o.add(s);else if(i===`door`){let n=new t.Group;n.name=`${H(r)}_hinge`,n.userData.interactivePivot=!0,n.position.x=0;let i=new t.Mesh(new t.BoxGeometry(.22,.5,.04),a);i.position.x=.11,i.castShadow=!0,i.receiveShadow=!0,n.add(i),o.add(n),s=i,o.userData.interactivePivot=n,o.userData.closedRotation=0,o.userData.openRotation=Number.isFinite(e.openAngle)?e.openAngle:Math.PI/2}else if(i===`window`)s=new t.Mesh(new t.PlaneGeometry(.35,.3),a),s.position.z=.02,o.add(s);else if(i===`roof`)s=new t.Mesh(new t.ConeGeometry(.34,.28,4),a),s.rotation.y=Math.PI/4,o.add(s);else if(i===`light`){s=new t.Mesh(new t.SphereGeometry(.09,32,16),a);let e=new t.PointLight(16777215,1.2,2.6,2);e.position.set(0,0,0),o.add(s,e),o.userData.light=e}else i===`wheel`?(s=new t.Mesh(new t.CylinderGeometry(.11,.11,.05,20),a),s.rotation.z=Math.PI/2,o.add(s)):i===`screen`?(s=new t.Mesh(new t.BoxGeometry(.42,.25,.03),a),o.add(s)):(s=new t.Mesh(pi(i,t),a),o.add(s));return o.userData.partMesh=s,o.userData.partState={open:!1,visible:!0,rotated:!1,shatter:!1},{id:n,name:r,type:i,root:o,mesh:s,actions:o.userData.partActions}}function Gr(e,t,n,r){let i=String(n.kit||`scene`).toLowerCase(),a=t.base[0]?.root||t.walls[0]?.root||t.details[0]?.root||null;return a&&a.scale.multiplyScalar(1),i===`house`?(t.base[0]&&t.base[0].root.position.set(0,-.15,0),t.walls.forEach((e,t)=>{e.root.position.set(t%2==0?-.16:.16,.05,t<2?-.16:.16),e.root.scale.set(1,1,1)}),t.doors[0]&&t.doors[0].root.position.set(.18,-.12,.18),t.windows[0]&&t.windows[0].root.position.set(-.18,.06,.18),t.roofs[0]&&t.roofs[0].root.position.set(0,.28,0)):i===`room`?(t.base[0]&&t.base[0].root.position.set(0,-.18,0),t.walls.forEach((e,t)=>{e.root.position.set(t<2?-.22:.22,.05,t%2==0?-.22:.22)})):i===`vehicle`?(t.base[0]&&t.base[0].root.position.set(0,-.08,0),t.wheels.forEach((e,t)=>{let n=t<2?-.22:.22,r=t%2==0?-.16:.16;e.root.position.set(n,-.16,r)})):i===`device`&&(t.base[0]&&t.base[0].root.position.set(0,0,0),t.screens.forEach(e=>e.root.position.set(0,.01,.01))),e.userData.modelForge.layout=i,e}function Kr(e,t,n,r={}){if(!t)return!1;let i=String(n||``).toLowerCase();return i===`open`?qr(t,!0):i===`close`?qr(t,!1):i===`toggle`?qr(t,!t.userData.partState?.open):i===`rotate`?Jr(t,r?.delta||Math.PI/2):i===`reveal`?Yr(t,!0):i===`hide`?Yr(t,!1):i===`shatter`?Xr(e,t):i===`reconfigure`?Zr(e):i===`grab`?Qr(t,r):$r(t,i,r)}function qr(e,t){let n=e.userData.interactivePivot||e,r=n.rotation.y,i=t?e.userData.openRotation??Math.PI/2:e.userData.closedRotation??0;return e.userData.partState=e.userData.partState||{},e.userData.partState.open=t,yi(360,e=>{n.rotation.y=r+(i-r)*bi(e)})}function Jr(e,t){let n=e.userData.partMesh||e,r=e.userData.rotateAxis||`y`,i=n.rotation[r],a=i+t;return e.userData.partState=e.userData.partState||{},e.userData.partState.rotated=!0,yi(240,e=>{n.rotation[r]=i+(a-i)*xi(e)})}function Yr(e,t){return e.visible=t,e.traverse?.(e=>{e.visible=t}),e.userData.partState=e.userData.partState||{},e.userData.partState.visible=t,!0}function Xr(e,t){let n=[];if(t.traverse?.(e=>{e.isMesh&&n.push(e)}),!n.length)return Zr(e);let r=new w;return t.getWorldPosition(r),n.forEach((e,t)=>{let n=new w(Math.cos(t*2.399),.35+t%3*.12,Math.sin(t*1.917)).normalize();e.userData.shatterStart=performance.now(),e.userData.shatterFrom=r.clone(),e.userData.shatterDirection=n}),yi(680,e=>{let t=bi(e);n.forEach(e=>{let n=e.userData.shatterDirection;n&&(e.position.copy(n).multiplyScalar(t*.65),e.rotation.x+=.05*t,e.rotation.y+=.06*t,e.rotation.z+=.04*t)})})}function Zr(e){let t=e.children.filter(e=>e.isObject3D);return t.forEach((e,t)=>{let n=Math.floor(t/3),r=(t%3-1)*.18,i=.04*n,a=(n-.5)*.12;e.position.x+=r*.2,e.position.y+=i*.2,e.position.z+=a*.2}),yi(340,e=>{let n=bi(e);t.forEach((e,t)=>{let r=Math.floor(t/3),i=(t%3-1)*.18,a=.04*r,o=(r-.5)*.12;e.position.x+=(i-e.position.x)*n*.12,e.position.y+=(a-e.position.y)*n*.12,e.position.z+=(o-e.position.z)*n*.12})})}function Qr(e,t){return t?.position&&e.position?.copy?(e.position.copy(t.position),!0):(e.userData.partState=e.userData.partState||{},e.userData.partState.grabbed=!0,!0)}function $r(e,t,n){e.userData.partState=e.userData.partState||{},e.userData.partState.lastAction=t;let r=String(t||``).toLowerCase().trim();if(r.includes(`raise`)||r.includes(`lift`)||r===`up`||r.includes(`deploy-gear`)){let t=e.position.y;return yi(400,n=>{e.position.y=t+.12*bi(n)})}if(r.includes(`lower`)||r===`down`||r.includes(`retract-gear`)){let t=e.position.y;return yi(400,n=>{e.position.y=t-.12*bi(n)})}if(r.includes(`extend`)||r.includes(`deploy`)||r.includes(`unfold`)||r.includes(`expand`)){let t=e.scale.clone(),n=e.rotation.y;return yi(500,r=>{let i=bi(r);e.scale.copy(t).multiplyScalar(1+.18*i),e.rotation.y=n+.35*i})}if(r.includes(`retract`)||r.includes(`fold`)||r.includes(`pull`)||r.includes(`collapse`)){let t=e.scale.clone(),n=e.rotation.y;return yi(500,r=>{let i=bi(r);e.scale.copy(t).multiplyScalar(1-.18*i),e.rotation.y=n-.35*i})}if(r.includes(`ignite`)||r.includes(`fire`)||r.includes(`charge`)||r.includes(`thrust`)||r.includes(`launch`)){if(e.isMesh&&e.material){let t=e.material.emissive?e.material.emissive.getHex():0;e.material.emissive=new Be(54015),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=4),window.setTimeout(()=>{e.material.emissive&&e.material.emissive.setHex(t),e.material.emissiveIntensity!==void 0&&(e.material.emissiveIntensity=0)},1e3)}return!0}return e.userData.partState.lastContext=n||{},!0}function ei(e,t){let n=H(t);if(!n)return null;let r=null;return e.traverse?.(e=>{r||[e.name,e.userData?.partName,e.userData?.role,e.userData?.partType].filter(Boolean).map(H).includes(n)&&(r=e.userData?.interactivePivot||e)}),r}function ti(e={}){return{name:String(e.name||e.role||`part`).trim(),type:ii(e.type||e.role),material:[`matte`,`metal`,`glass`,`glow`,`wood`].includes(String(e.material||``).toLowerCase())?String(e.material).toLowerCase():`matte`,geometry:e.geometry?String(e.geometry).toLowerCase().trim():void 0,position:gi(e.position),rotation:_i(e.rotation),scale:vi(e.scale),actions:Array.isArray(e.actions)&&e.actions.length?e.actions.map(ri):di(e.type||e.role),openAngle:Number.isFinite(e.openAngle)?e.openAngle:void 0}}function ni(e={}){return{gesture:String(e.gesture||``).toLowerCase().trim(),action:ri(e.action||e.trigger||``),target:String(e.target||e.part||``).trim()}}function ri(e){return String(e||``).toLowerCase().trim().replace(/\s+/g,`-`)}function ii(e){let t=String(e||``).toLowerCase().trim().replace(/\s+/g,`-`);return[`wall`,`door`,`window`,`roof`,`drawer`,`panel`,`screen`,`wheel`,`prop`,`light`,`arm`,`leg`,`head`,`detail`,`base`].includes(t)?t:ai(t)}function ai(e){let t=H(e);return t.includes(`door`)?`door`:t.includes(`window`)?`window`:t.includes(`roof`)?`roof`:t.includes(`wheel`)?`wheel`:t.includes(`screen`)||t.includes(`display`)?`screen`:t.includes(`light`)||t.includes(`lamp`)?`light`:t.includes(`drawer`)?`drawer`:t.includes(`wall`)?`wall`:t.includes(`base`)||t.includes(`floor`)?`base`:t.includes(`arm`)?`arm`:t.includes(`leg`)?`leg`:t.includes(`head`)?`head`:`detail`}function oi(e){let t=H(e);return t.includes(`house`)||t.includes(`home`)?`house`:t.includes(`room`)||t.includes(`bedroom`)||t.includes(`kitchen`)?`room`:t.includes(`car`)||t.includes(`truck`)||t.includes(`vehicle`)?`vehicle`:t.includes(`phone`)||t.includes(`device`)||t.includes(`tablet`)?`device`:t.includes(`character`)||t.includes(`person`)||t.includes(`robot`)?`character`:`scene`}function si(e){return oi(H(e?.userData?.modelName||e?.name||``))}function B(e,t){let n=new Set(e.map(H));for(let e of t)if(n.has(H(e)))return e;return``}function V(e){return e===`house`||e===`room`?`core`:e===`vehicle`?`chassis`:e===`device`?`screen`:e===`character`?`torso`:`core`}function ci(e){return Math.max(.04,Math.min(Number(e)||1,4))}function li(e){let t={house:[{name:`base`,type:`base`,material:`matte`,position:[0,-.15,0],scale:[1.2,.6,1.2]},{name:`front-door`,type:`door`,material:`wood`},{name:`left-window`,type:`window`,material:`glass`},{name:`right-window`,type:`window`,material:`glass`},{name:`roof`,type:`roof`,material:`matte`}],room:[{name:`floor`,type:`base`,material:`matte`,position:[0,-.16,0],scale:[1.3,.05,1.3]},{name:`wall-a`,type:`wall`,material:`matte`},{name:`wall-b`,type:`wall`,material:`matte`},{name:`door`,type:`door`,material:`metal`},{name:`window`,type:`window`,material:`glass`}],device:[{name:`body`,type:`base`,material:`metal`,position:[0,0,0],scale:[1,.6,.15]},{name:`screen`,type:`screen`,material:`glass`,position:[0,.01,.09]},{name:`button`,type:`detail`,material:`glow`,position:[.27,-.05,.08],scale:[.16,.16,.16]}],vehicle:[{name:`chassis`,type:`base`,material:`metal`,position:[0,-.03,0],scale:[1.2,.36,.64]},{name:`wheel-front-left`,type:`wheel`,material:`metal`,position:[-.35,-.18,-.22]},{name:`wheel-front-right`,type:`wheel`,material:`metal`,position:[.35,-.18,-.22]},{name:`wheel-back-left`,type:`wheel`,material:`metal`,position:[-.35,-.18,.22]},{name:`wheel-back-right`,type:`wheel`,material:`metal`,position:[.35,-.18,.22]}],character:[{name:`torso`,type:`base`,material:`matte`,position:[0,.02,0],scale:[.36,.5,.18]},{name:`head`,type:`head`,material:`matte`,position:[0,.4,0],scale:[.28,.28,.28]},{name:`left-arm`,type:`arm`,material:`matte`,position:[-.28,.12,0],scale:[.12,.42,.12]},{name:`right-arm`,type:`arm`,material:`matte`,position:[.28,.12,0],scale:[.12,.42,.12]},{name:`left-leg`,type:`leg`,material:`matte`,position:[-.12,-.42,0],scale:[.12,.42,.12]},{name:`right-leg`,type:`leg`,material:`matte`,position:[.12,-.42,0],scale:[.12,.42,.12]}],scene:[{name:`core`,type:`base`,material:`matte`,position:[0,0,0],scale:[.9,.6,.9]},{name:`detail-a`,type:`detail`,material:`glow`,position:[-.26,.12,.2]},{name:`detail-b`,type:`detail`,material:`glow`,position:[.28,.1,-.18]},{name:`control-panel`,type:`screen`,material:`glass`,position:[0,.18,.32]}]};return t[e]||t.scene}function ui(e,t=[]){let n=t.map(e=>H(e.name)),r=B(n,[`front-door`,`door`,`front`,`main-door`,`screen`,`control-panel`])||V(e),i=B(n,[`roof`,`top`,`cover`,`lid`])||V(e),a=B(n,[`screen`,`display`,`control-panel`])||V(e),o=B(n,[`wheel-front-left`,`wheel-front-right`,`wheel-back-left`,`wheel-back-right`,`wheel`])||V(e),s={house:[{gesture:`pinch`,action:`toggle`,target:r},{gesture:`open-palm`,action:`reconfigure`,target:i},{gesture:`swipe-left`,action:`close`,target:r},{gesture:`swipe-right`,action:`open`,target:r},{gesture:`fist`,action:`shatter`,target:i}],room:[{gesture:`pinch`,action:`open`,target:r},{gesture:`fist`,action:`close`,target:r},{gesture:`two-hand-scale`,action:`reconfigure`,target:B(n,[`floor`,`base`])||V(e)},{gesture:`open-palm`,action:`reveal`,target:a}],device:[{gesture:`pinch`,action:`toggle`,target:a},{gesture:`open-palm`,action:`reveal`,target:B(n,[`body`,`base`])||V(e)},{gesture:`swipe-left`,action:`hide`,target:a},{gesture:`swipe-right`,action:`open`,target:a}],vehicle:[{gesture:`pinch`,action:`toggle`,target:B(n,[`chassis`,`base`])||V(e)},{gesture:`fist`,action:`reconfigure`,target:o},{gesture:`swipe-left`,action:`rotate`,target:o},{gesture:`swipe-right`,action:`open`,target:B(n,[`door`,`hood`,`trunk`])||V(e)}],character:[{gesture:`pinch`,action:`toggle`,target:B(n,[`head`])||V(e)},{gesture:`fist`,action:`grab`,target:B(n,[`torso`,`body`])||V(e)},{gesture:`swipe-right`,action:`reconfigure`,target:B(n,[`left-arm`,`arm`])||V(e)},{gesture:`swipe-left`,action:`rotate`,target:B(n,[`right-arm`,`arm`])||V(e)}],scene:[{gesture:`pinch`,action:`toggle`,target:B(n,[`core`,`root`,`base`])||V(e)},{gesture:`open-palm`,action:`reconfigure`,target:a},{gesture:`fist`,action:`shatter`,target:B(n,[`detail-a`,`detail-b`])||V(e)}]};return(s[e]||s.scene).filter(Boolean)}function di(e){let t=ii(e);return t===`door`?[`open`,`close`,`toggle`]:t===`window`?[`open`,`close`,`toggle`,`reveal`]:t===`drawer`?[`open`,`close`,`toggle`]:t===`wheel`?[`rotate`]:t===`screen`||t===`light`?[`toggle`,`reveal`,`hide`]:Dr.slice()}function fi(e,t){let n=String(e||`matte`).toLowerCase();return n===`metal`?new t.MeshPhysicalMaterial({color:9422847,roughness:.16,metalness:.92}):n===`glass`?new t.MeshPhysicalMaterial({color:13627391,roughness:.05,transmission:.58,transparent:!0,opacity:.36}):n===`glow`?new t.MeshBasicMaterial({color:51455,transparent:!0,opacity:.9}):n===`wood`?new t.MeshStandardMaterial({color:9202255,roughness:.82,metalness:.02}):new t.MeshStandardMaterial({color:8109311,roughness:.55,metalness:.1})}function pi(e,t){let n=ii(e);return n===`base`||n===`wall`?new t.BoxGeometry(.5,.32,.5):n===`drawer`?new t.BoxGeometry(.28,.14,.28):n===`arm`?new t.CapsuleGeometry(.06,.28,5,16):n===`leg`?new t.CapsuleGeometry(.06,.34,5,16):n===`head`?new t.SphereGeometry(.16,24,16):n===`detail`?new t.IcosahedronGeometry(.08,1):new t.BoxGeometry(.22,.22,.22)}function mi(e,t,n=[]){let r=new ge;if(e&&r.setFromObject(e),!Number.isFinite(r.min.x)||!Number.isFinite(r.max.x))return[...n,...li(t)];let i=r.getSize(new w),a=Math.max(i.x,.1),o=Math.max(i.y,.1),s=Math.max(i.z,.1),c=Math.max(a,o,s)||.4,l=[{name:`core`,type:`base`,material:`matte`,position:[0,0,0],scale:[1,1,1],actions:[`toggle`,`reconfigure`,`shatter`]},{name:`zone-front`,type:`panel`,material:`glass`,position:[0,0,s*.35],scale:[.72,.72,.12],actions:[`open`,`close`,`toggle`,`reveal`,`hide`]},{name:`zone-back`,type:`panel`,material:`glass`,position:[0,0,-s*.35],scale:[.72,.72,.12],actions:[`open`,`close`,`toggle`,`reveal`,`hide`]},{name:`zone-left`,type:`panel`,material:`glass`,position:[-a*.35,0,0],scale:[.12,.72,.72],actions:[`rotate`,`reconfigure`]},{name:`zone-right`,type:`panel`,material:`glass`,position:[a*.35,0,0],scale:[.12,.72,.72],actions:[`rotate`,`reconfigure`]},{name:`zone-top`,type:`roof`,material:`matte`,position:[0,o*.35,0],scale:[.85,.16,.85],actions:[`open`,`close`,`reconfigure`]},{name:`zone-bottom`,type:`base`,material:`matte`,position:[0,-o*.35,0],scale:[.85,.16,.85],actions:[`reconfigure`,`grab`]},{name:`zone-core`,type:`detail`,material:`glow`,position:[0,0,0],scale:[.42,.42,.42],actions:[`toggle`,`shatter`,`reveal`,`hide`]}];return[...n,...l.map(e=>({...e,scale:[ci(e.scale[0]*(c/1.25)),ci(e.scale[1]*(c/1.25)),ci(e.scale[2]*(c/1.25))]}))]}function hi(e){if(!e)return null;let t=String(e).replace(/```json|```/gi,``).trim(),n=t.indexOf(`{`),r=t.lastIndexOf(`}`);if(n<0||r<0||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}function gi(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||0,Number(e[1])||0,Number(e[2])||0]:e&&typeof e==`object`?[Number(e.x)||0,Number(e.y)||0,Number(e.z)||0]:[0,0,0]}function _i(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||0,Number(e[1])||0,Number(e[2])||0]:e&&typeof e==`object`?[Number(e.x)||0,Number(e.y)||0,Number(e.z)||0]:[0,0,0]}function vi(e){return Array.isArray(e)&&e.length>=3?[Number(e[0])||1,Number(e[1])||1,Number(e[2])||1]:e&&typeof e==`object`?[Number(e.x)||1,Number(e.y)||1,Number(e.z)||1]:[1,1,1]}function yi(e,t){let n=performance.now();return new Promise(r=>{let i=a=>{let o=Math.min((a-n)/e,1);t(o),o<1?requestAnimationFrame(i):r(!0)};requestAnimationFrame(i)})}function bi(e){return 1-(1-e)**3}function xi(e){return e<.5?4*e*e*e:1-(-2*e+2)**3/2}function H(e){return String(e||``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}var Si=!1,Ci=!1,wi=!1,Ti={default:{name:`default`,refDistance:.72,maxDistance:8,rolloffFactor:1.6,dampening:.08,cueGain:1},cinema:{name:`cinema`,refDistance:1.05,maxDistance:12,rolloffFactor:1.25,dampening:.16,cueGain:1.08},open:{name:`open`,refDistance:.68,maxDistance:16,rolloffFactor:1.15,dampening:.03,cueGain:.96},quiet:{name:`quiet`,refDistance:.84,maxDistance:7,rolloffFactor:1.8,dampening:.12,cueGain:.92},lab:{name:`lab`,refDistance:.78,maxDistance:9,rolloffFactor:1.5,dampening:.06,cueGain:1.02}};function Ei(){Si||(Si=!0,A(`ar-scene-live`,()=>Mi()),A(`object-placed`,({object:e})=>Di(e)),Ni(),Pi(),Mi(),I(`spatialAudio`,!!Fi()),I(`speechSynthesis`,!!window.speechSynthesis),I(`voiceRecognition`,!!(window.SpeechRecognition||window.webkitSpeechRecognition)))}function Di(e){if(!e)return null;let t=Mi();if(!t)return null;if(e.userData.spatialAudio={...Ti[k.spatialAudio.environmentProfile]||Ti.default,...e.userData.spatialAudio||{}},e.userData.spatialAudioEmitter?.parent===e)return e.userData.spatialAudioEmitter;let n=new S(t);return n.name=`jarvis-object-spatial-audio`,ki(n,e.userData.spatialAudio),e.add(n),e.userData.spatialAudioAttached=!0,e.userData.spatialAudioEmitter=n,n}async function Oi(e,t=`select`){if(!e)return!1;let n=Mi(),r=Fi();if(!n||!r)return!1;try{if(r.state===`suspended`&&await r.resume(),r.state!==`running`)return!1;k.spatialAudio.unlocked=!0;let i=e.parent?Di(e):ji(n,e);return i?(i.isPlaying&&i.stop(),i.setBuffer(Ii(r,t)),i.setVolume((Ti[k.spatialAudio.environmentProfile]?.cueGain||1)*(t===`delete`?.9:1)),i.play(),window.setTimeout(()=>{try{i.stop()}catch{}i.userData.detachedAnchor&&(i.userData.detachedAnchor.parent?.remove(i.userData.detachedAnchor),i.disconnect())},420),!0):!1}catch{return!1}}function ki(e,t={}){e.setRefDistance(t.refDistance||.72),e.setMaxDistance(t.maxDistance||8),e.setRolloffFactor(t.rolloffFactor||1.6),e.setDistanceModel(`inverse`)}function Ai(e=`default`){let t=Ti[String(e||`default`).toLowerCase()]||Ti.default;return k.spatialAudio.environmentProfile=t.name,k.spatialAudio.roomProfile={...t},k.placedObjects.forEach(e=>{let n=e?.userData?.spatialAudioEmitter;n&&ki(n,t)}),k.spatialAudio.listener?.context&&(k.spatialAudio.context=k.spatialAudio.listener.context),I(`spatialAudio`,!!Fi()),t}function ji(e,t){let n=new Se;t.getWorldPosition(n.position),R().scene.add(n);let r=new S(e);return r.name=`jarvis-detached-spatial-cue`,ki(r,t.userData.spatialAudio||Ti.default),r.userData.detachedAnchor=n,n.add(r),r}function Mi(){let{camera:e}=R();return e?(k.spatialAudio.listener||(k.spatialAudio.listener=new _e),k.spatialAudio.listener.parent!==e&&(k.spatialAudio.listener.parent?.remove(k.spatialAudio.listener),e.add(k.spatialAudio.listener)),k.spatialAudio.enabled=!0,k.spatialAudio.context=Fi(),k.spatialAudio.listener):null}function Ni(){if(wi)return;wi=!0;let e=()=>Ai(k.nativeOptions?.activeEnvironment||k.spatialAudio.environmentProfile||`default`);A(`native-options`,e),A(`native-ui-state`,e=>{let t=e?.audioEnvironment||e?.environment||e?.profile;t&&Ai(t)}),e()}function Pi(){if(Ci)return;Ci=!0;let e=async()=>{let e=Fi();if(e)try{await e.resume(),k.spatialAudio.unlocked=e.state===`running`,k.spatialAudio.micPermission=k.spatialAudio.unlocked?`granted`:k.spatialAudio.micPermission,k.spatialAudio.unlocked&&E(`Spatial audio unlocked for AR objects.`,`Spatial Audio`)}catch{k.spatialAudio.unlocked=!1}};window.addEventListener(`pointerdown`,e,{passive:!0}),window.addEventListener(`touchstart`,e,{passive:!0})}function Fi(){try{return Te.getContext()}catch{return null}}function Ii(e,t){let n=e.sampleRate,r=Math.max(1,Math.floor(n*.24)),i=e.createBuffer(1,r,n),a=i.getChannelData(0),o=t===`place`?330:t===`delete`?180:t===`open`?520:430;for(let e=0;e<r;e+=1){let t=e/n,r=Math.exp(-t*12)*Math.min(1,t*90);a[e]=(Math.sin(Math.PI*2*o*t)*.72+Math.sin(Math.PI*2*o*1.5*t)*.2)*r*.16}return i}var U=Uint8Array,Li=Uint16Array,Ri=Int32Array,zi=new U([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Bi=new U([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Vi=new U([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Hi=function(e,t){for(var n=new Li(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Ri(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Ui=Hi(zi,2),Wi=Ui.b,Gi=Ui.r;Wi[28]=258,Gi[258]=28;var Ki=Hi(Bi,0),qi=Ki.b;Ki.r;for(var Ji=new Li(32768),W=0;W<32768;++W){var Yi=(W&43690)>>1|(W&21845)<<1;Yi=(Yi&52428)>>2|(Yi&13107)<<2,Yi=(Yi&61680)>>4|(Yi&3855)<<4,Ji[W]=((Yi&65280)>>8|(Yi&255)<<8)>>1}for(var Xi=(function(e,t,n){for(var r=e.length,i=0,a=new Li(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Li(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Li(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[Ji[d]>>c]=l}else for(s=new Li(r),i=0;i<r;++i)e[i]&&(s[i]=Ji[o[e[i]-1]++]>>15-e[i]);return s}),Zi=new U(288),W=0;W<144;++W)Zi[W]=8;for(var W=144;W<256;++W)Zi[W]=9;for(var W=256;W<280;++W)Zi[W]=7;for(var W=280;W<288;++W)Zi[W]=8;for(var Qi=new U(32),W=0;W<32;++W)Qi[W]=5;var $i=Xi(Zi,9,1),ea=Xi(Qi,5,1),ta=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},na=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},ra=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},ia=function(e){return(e+7)/8|0},aa=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new U(e.subarray(t,n))},oa=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],sa=function(e,t,n){var r=Error(t||oa[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,sa),!n)throw r;return r},ca=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new U(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new U(i*3));var l=function(e){var t=n.length;if(e>t){var r=new U(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=na(e,d,1);var ee=na(e,d+1,3);if(d+=3,!ee){var v=ia(d)+4,y=e[v-4]|e[v-3]<<8,b=v+y;if(b>i){c&&sa(0);break}s&&l(f+y),n.set(e.subarray(v,b),f),t.b=f+=y,t.p=d=b*8,t.f=u;continue}else if(ee==1)p=$i,m=ea,h=9,g=5;else if(ee==2){var te=na(e,d,31)+257,ne=na(e,d+10,15)+4,re=te+na(e,d+5,31)+1;d+=14;for(var x=new U(re),ie=new U(19),S=0;S<ne;++S)ie[Vi[S]]=na(e,d+S*3,7);d+=ne*3;for(var ae=ta(ie),C=(1<<ae)-1,oe=Xi(ie,ae,1),S=0;S<re;){var se=oe[na(e,d,C)];d+=se&15;var v=se>>4;if(v<16)x[S++]=v;else{var ce=0,le=0;for(v==16?(le=3+na(e,d,3),d+=2,ce=x[S-1]):v==17?(le=3+na(e,d,7),d+=3):v==18&&(le=11+na(e,d,127),d+=7);le--;)x[S++]=ce}}var ue=x.subarray(0,te),de=x.subarray(te);h=ta(ue),g=ta(de),p=Xi(ue,h,1),m=Xi(de,g,1)}else sa(1);if(d>_){c&&sa(0);break}}s&&l(f+131072);for(var fe=(1<<h)-1,w=(1<<g)-1,pe=d;;pe=d){var ce=p[ra(e,d)&fe],me=ce>>4;if(d+=ce&15,d>_){c&&sa(0);break}if(ce||sa(2),me<256)n[f++]=me;else if(me==256){pe=d,p=null;break}else{var he=me-254;if(me>264){var S=me-257,ge=zi[S];he=na(e,d,(1<<ge)-1)+Wi[S],d+=ge}var _e=m[ra(e,d)&w],ve=_e>>4;_e||sa(3),d+=_e&15;var de=qi[ve];if(ve>3){var ge=Bi[ve];de+=ra(e,d)&(1<<ge)-1,d+=ge}if(d>_){c&&sa(0);break}s&&l(f+131072);var ye=f+he;if(f<de){var be=a-de,xe=Math.min(de,ye);for(be+f<0&&sa(3);f<xe;++f)n[f]=r[be+f]}for(;f<ye;++f)n[f]=n[f-de]}}t.l=p,t.p=pe,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?aa(n,0,f):n.subarray(0,f)},la=new U(0),ua=function(e,t){return e[t]|e[t+1]<<8},da=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},fa=function(e,t){return da(e,t)+da(e,t+4)*4294967296};function pa(e,t){return ca(e,{i:2},t&&t.out,t&&t.dictionary)}var ma=typeof TextDecoder<`u`&&new TextDecoder;try{ma.decode(la,{stream:!0})}catch{}var ha=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:aa(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}};function ga(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else if(ma)return ma.decode(e);else{var i=ha(e),a=i.s,n=i.r;return n.length&&sa(8),a}}var _a=function(e,t){return t+30+ua(e,t+26)+ua(e,t+28)},va=function(e,t,n){var r=ua(e,t+28),i=ga(e.subarray(t+46,t+46+r),!(ua(e,t+8)&2048)),a=t+46+r,o=da(e,t+20),s=n&&o==4294967295?ya(e,a):[o,da(e,t+24),da(e,t+42)],c=s[0],l=s[1],u=s[2];return[ua(e,t+10),c,l,i,a+ua(e,t+30)+ua(e,t+32),u]},ya=function(e,t){for(;ua(e,t)!=1;t+=4+ua(e,t+2));return[fa(e,t+12),fa(e,t+4),fa(e,t+20)]};function ba(e,t){for(var n={},r=e.length-22;da(e,r)!=101010256;--r)(!r||e.length-r>65558)&&sa(13);var i=ua(e,r+8);if(!i)return{};var a=da(e,r+16),o=a==4294967295||i==65535;if(o){var s=da(e,r-12);o=da(e,s)==101075792,o&&(i=da(e,s+32),a=da(e,s+48))}for(var c=t&&t.filter,l=0;l<i;++l){var u=va(e,a,o),d=u[0],f=u[1],p=u[2],m=u[3],h=u[4],g=u[5],_=_a(e,g);a=h,(!c||c({name:m,size:f,originalSize:p,compression:d}))&&(d?d==8?n[m]=pa(e.subarray(_,_+f),{out:new U(p)}):sa(14,`unknown compression type `+d):n[m]=aa(e,_,_+f))}return n}var xa=new b({color:16777215,transparent:!0,opacity:.72}),Sa=`jarvis_ar_placed_objects_v1`,Ca=`jarvis_ar_my_models_v1`,wa=`0.158.0`,Ta=new Ce().setDecoderPath(`https://cdn.jsdelivr.net/npm/three@${wa}/examples/jsm/libs/draco/`),Ea=new ue().setTranscoderPath(`https://cdn.jsdelivr.net/npm/three@${wa}/examples/jsm/libs/basis/`),Da=!1;function Oa(){if(Da)return;let e=R()?.renderer;if(e)try{Ea.detectSupport(e),Da=!0}catch{}}function ka(e){return e.setDRACOLoader(Ta),e.setKTX2Loader(Ea),e.setMeshoptDecoder(Pe),e}var Aa=ka(new Le),ja=8,Ma=180*1024*1024,Na=new Map,Pa=0,Fa=null,Ia=0,La=new Map,Ra=0,za=``,Ba=0,Va=0,Ha=!1,Ua=!1,Wa=0,Ga=new Map,Ka=new Set;function qa(){Ya(),oo(),A(`open-model-forge`,$a),A(`open-models`,Xa),A(`jarvis-model-action`,e=>Fo(e)),A(`gesture-pinch`,e=>Po(`pinch`,e)),A(`gesture-fist`,e=>Po(`fist`,e)),A(`gesture-open-palm`,e=>Po(`open-palm`,e)),A(`gesture-swipe-left`,e=>Po(`swipe-left`,e)),A(`gesture-swipe-right`,e=>Po(`swipe-right`,e)),A(`gesture-two-hand-scale`,e=>Po(`two-hand-scale`,e)),A(`world-anchor-sample`,()=>Go()),A(`native-ar-state`,e=>Ja(e)),A(`spawn-model`,async e=>{co(Dn(e?.query||`Duck`).name)}),A(`spawn-generated-glb`,async e=>{if(!e?.model_url)return;let t=e?.model_name||`Generated Model`;try{E(`Loading generated model: ${t}...`,`Jarvis AI Generation`);let n=String(e.model_url);if(n.startsWith(`/`)){let e=k.jarvis?.apiBase?.()||``;e&&(n=`${e}${n}`)}let r=await ho(n);r.userData.modelName=t,Fr(r,z({name:t,kit:_s(t)})),fo(r,window.AR_CAMERA_POSITION||new w(0,0,-2)),E(`Successfully deployed ${t}!`,`Jarvis AI Generation`)}catch(e){T(`Failed to load generated model: ${e.message}`,`Generation Error`)}}),setInterval(()=>bo(),6e4)}function Ja(e={}){let t=Array.isArray(e.objects)?e.objects:[];for(let e of t){let t=String(e.id||e.uid||``).trim(),n=String(e.label||e.name||e.modelName||e.type||`Native Object`),r=e.position||{x:Number(e.px??e.x??0),y:Number(e.py??e.y??k.floorY+.08),z:Number(e.pz??e.z??-1.6)},i=t?k.placedObjects.find(e=>e.userData.id===t):null;if(i){i.position.copy(fs(r)),i.userData.modelName=n,Ro(i);continue}let a=No(n);t&&(a.userData.id=t),a.userData.sourceURL=`native-apk-state`,Fr(a,z({name:n,kit:_s(n)})),mo(a,n,r,null,`native-apk-state`)}}function Ya(){if(Ha||Ua)return;let e=()=>{Ha||(Ha=!0,Vo().catch(e=>T(e.message,`Model Restore Failed`)))};if(k.liveSceneReady){e();return}Ua=!0;let t=A(`ar-scene-live`,()=>{t(),Ua=!1,e()})}function Xa(){let e=document.createElement(`div`),t=document.createElement(`input`);t.placeholder=`Search free models`;let n=document.createElement(`div`);n.className=`panel-list`;let r=document.createElement(`input`);r.type=`file`,r.accept=`.glb,.gltf,.obj,.fbx`;let i=Za(),a=document.createElement(`button`);a.className=`panel-action`,a.textContent=`Open Custom 3D Builder`,a.onclick=ss;let o=document.createElement(`button`);o.className=`panel-action`,o.textContent=`Open Interactive Model Forge`,o.onclick=$a;let s=document.createElement(`p`);s.className=`panel-note`,s.textContent=`Create models with behavior schemas, named parts, and Jarvis-generated interactions.`,e.append(t,n,i,r,a,o,s);let c=()=>{let e=t.value.toLowerCase();n.replaceChildren(...Tn.filter(t=>!e||t.name.toLowerCase().includes(e)||t.category.includes(e)).map(e=>ro(e)))};t.addEventListener(`input`,c),r.addEventListener(`change`,()=>io(r.files?.[0])),c(),new un({title:`Models`,body:e,icon:`M`,width:390,height:560}).focus()}function Za(){let e=document.createElement(`section`);e.className=`sketchfab-panel`;let t=document.createElement(`strong`);t.textContent=`JARVIS 3D Asset Nexus`;let n=document.createElement(`p`);n.className=`panel-note`,n.textContent=`Connectors: Turbosquid, CGTrader, Mixamo, Poly.pizza, Kenney, Quaternius, Sketchfab.`;let r=document.createElement(`button`);r.className=`panel-action`,r.style.cssText=`width: 100%; margin: 6px 0; padding: 10px 14px; text-align: left; display: flex; align-items: center; justify-content: space-between; font-size: 13px; border-radius: 12px; font-weight: 500;`;let i=document.createElement(`span`);i.textContent=`API Connectors Logins`;let a=document.createElement(`span`);a.className=`chevron`,a.textContent=`v`,a.style.cssText=`transition: transform 0.25s ease; display: inline-block;`,r.append(i,a);let o=document.createElement(`div`);o.style.cssText=`display: none; flex-direction: column; gap: 10px; margin: 8px 0; padding: 14px; border: 1px solid var(--separator); border-radius: 14px; background: rgba(0,0,0,0.22);`;function s(e,t,n,r){let i=document.createElement(`div`);i.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let a=document.createElement(`div`);a.style.cssText=`display: flex; align-items: center; justify-content: space-between; font-size: 12px;`;let o=document.createElement(`span`);o.textContent=n,o.style.color=`var(--text-secondary)`;let s=document.createElement(`span`);s.style.cssText=`display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 600; text-transform: uppercase; cursor: pointer;`;let c=document.createElement(`input`);c.type=`password`,c.placeholder=t,c.value=e===`sketchfab`?Fn():Qn(e),c.style.cssText=`margin: 2px 0 !important; min-height: 38px !important; padding: 8px 12px !important; font-size: 12px !important; border-radius: 10px !important;`;let l=document.createElement(`div`);l.style.cssText=`font-size: 10px; color: var(--warning); display: none; padding: 2px 0 0 2px; line-height: 1.4;`;let u=()=>{let e=c.value.trim();s.replaceChildren();let t=document.createElement(`span`);e?(t.style.cssText=`color:var(--success); margin-right: 2px;`,t.textContent=`●`,s.append(t,document.createTextNode(` Authenticated ✓`)),l.style.display=`none`):(t.style.cssText=`color:var(--warning); margin-right: 2px;`,t.textContent=`●`,s.append(t,document.createTextNode(` No key — tap to add`)),r&&(l.style.display=`block`,l.innerHTML=`⚡ Get your free key at <span style="color:var(--accent);text-decoration:underline;">${r}</span>`))};return s.addEventListener(`click`,()=>c.focus()),c.addEventListener(`input`,u),u(),a.append(o,s),i.append(a,c,l),{wrapper:i,input:c,updateStatus:u}}let c=document.createElement(`div`);c.style.cssText=`background: rgba(96,165,250,0.12); border: 1px solid rgba(96,165,250,0.3); border-radius: 10px; padding: 10px 12px; font-size: 11px; color: rgba(255,255,255,0.85); line-height: 1.5;`,c.innerHTML=`🔑 <strong>Enter your API keys below to unlock live search.</strong><br>Yellow ● = no key set (uses sample models). Green ● = live API active.<br>Kenney &amp; Quaternius are always free — no key needed.`;let l=s(`omega_session`,`OMEGA cloud session token`,`OMEGA Cloud Link`,``),u=s(`sketchfab`,`Sketchfab OAuth/API Token`,`Sketchfab API`,`sketchfab.com/settings/password-api`),d=s(`poly_pizza`,`Poly.pizza API Key`,`Poly.pizza API`,`poly.pizza/account`),f=s(`cgtrader`,`CGTrader API Token`,`CGTrader API Token`,`cgtrader.com/account`),p=s(`turbosquid`,`username:api_key`,`TurboSquid user:key`,`turbosquid.com/Account`),m=s(`mixamo`,`adobe_email:adobe_password`,`Mixamo Adobe email:pass`,`mixamo.com (use your Adobe login)`),h=document.createElement(`div`);h.style.cssText=`display: flex; gap: 8px; font-size: 11px; background: rgba(255,255,255,0.05); padding: 8px 10px; border-radius: 10px; color: var(--text-secondary); justify-content: space-between;`,h.append(Qa(`Kenney`,`CC0 active`),Qa(`Quaternius`,`CC0 active`));let g=document.createElement(`button`);g.className=`panel-action`,g.textContent=`Save Credentials`,g.style.cssText=`min-height: 38px; font-size: 13px; font-weight: 600; background: var(--accent); color: #fff; margin-top: 6px;`,g.onclick=()=>{let e=l.input.value.trim()!==Qn(`omega_session`);if($n(`omega_session`,l.input.value),In(u.input.value),$n(`poly_pizza`,d.input.value),$n(`cgtrader`,f.input.value),$n(`turbosquid`,p.input.value),$n(`mixamo`,m.input.value),e&&k.jarvis){try{k.jarvis.ws?.close()}catch{}k.jarvis.loadConfig()}l.updateStatus(),u.updateStatus(),d.updateStatus(),f.updateStatus(),p.updateStatus(),m.updateStatus(),E(`All 3D Asset Nexus connector credential configurations saved locally.`,`Credentials Saved`)},o.append(c,l.wrapper,u.wrapper,d.wrapper,f.wrapper,p.wrapper,m.wrapper,h,g);let _=!1;r.onclick=()=>{_=!_,o.style.display=_?`flex`:`none`,r.querySelector(`.chevron`).style.transform=_?`rotate(180deg)`:`rotate(0)`};let ee=document.createElement(`div`);ee.className=`inline-row`,ee.style.cssText=`margin: 6px 0; display: flex; align-items: center; gap: 8px;`;let v=document.createElement(`span`);v.textContent=`Source:`,v.style.cssText=`font-size: 13px; color: var(--text-secondary);`;let y=document.createElement(`select`);y.style.cssText=`flex: 1; background: rgba(0,0,0,.35); color: #fff; border: 1px solid var(--glass-border); border-radius: 8px; padding: 6px; font-size: 13px;`,[{value:`all`,label:`All Free Sources (Combined)`},{value:`poly_pizza`,label:`Poly.pizza (Free CC0)`},{value:`kenney`,label:`Kenney.nl (CC0 Game Assets)`},{value:`quaternius`,label:`Quaternius (CC0 Low-Poly)`},{value:`mixamo`,label:`Mixamo (Free Rigged Characters)`},{value:`sketchfab`,label:`Sketchfab (Free CC Assets)`},{value:`cgtrader`,label:`CGTrader (Free CC0/Standard)`},{value:`turbosquid`,label:`Turbosquid (Free CC0/Standard)`}].forEach(e=>{let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,y.appendChild(t)}),ee.append(v,y);let b=document.createElement(`div`);b.className=`inline-row`;let te=document.createElement(`input`);te.placeholder=`Search free 3D models...`;let ne=document.createElement(`button`);ne.className=`panel-action`,ne.textContent=`Search`,b.append(te,ne);let re=document.createElement(`div`);re.className=`panel-list sketchfab-results`;let x=document.createElement(`p`);x.className=`panel-note`,x.textContent=`Ready to search unified free connectors.`;let ie=!1;return Gn().then(e=>{e?.configured&&(ie=!0,x.textContent=`OMEGA Sketchfab token active. Search & placement run completely free.`,u.input.placeholder=`Optional override token`)}).catch(()=>{}),ne.onclick=async()=>{let e=u.input.value.trim()||Fn();In(e);let t=y.value;x.textContent=`Searching free assets from ${y.options[y.selectedIndex].text}...`,re.replaceChildren();try{let n=await ir(te.value||`object`,t,e);if(!n.length){x.textContent=`No free assets matched your query on the selected source.`;return}x.textContent=`Found ${n.length} free asset(s).`,re.replaceChildren(...n.map(t=>eo(t,()=>u.input.value.trim()||e,()=>ie)))}catch(e){x.textContent=`Unified search failed.`,T(e.message,`Asset Search Failed`)}},e.append(t,n,r,o,ee,b,x,re),e}function Qa(e,t){let n=document.createElement(`div`),r=document.createElement(`strong`);r.textContent=`${e}:`;let i=document.createElement(`span`);return i.style.color=`var(--success)`,i.textContent=` ● `,n.append(r,i,document.createTextNode(t)),n}async function $a(){let e=document.createElement(`div`),t=document.createElement(`strong`),n=document.createElement(`p`),r=document.createElement(`input`),i=document.createElement(`select`),a=document.createElement(`textarea`),o=document.createElement(`pre`),s=document.createElement(`div`),c=document.createElement(`button`),l=document.createElement(`button`),u=document.createElement(`button`),d=document.createElement(`button`),f=z({name:`Custom Model`,kit:`scene`}),p=f;t.textContent=`Jarvis 3D Forge`,n.className=`panel-note`,n.textContent=`Build a model as geometry + parts + behaviors + triggers + scripts + exports.`,r.placeholder=`Model name`,r.value=f.name,a.rows=5,a.placeholder=`Describe the model, its parts, and the actions you want`,a.value=`Create a fully interactive model with named parts, gestures, and a behavior schema.`,fr(i,[`scene`,`house`,`room`,`device`,`vehicle`,`character`]),o.style.cssText=`white-space:pre-wrap;font:12px/1.45 monospace;color:rgba(255,255,255,.82);background:rgba(0,0,0,.25);padding:10px;border-radius:12px;max-height:220px;overflow:auto`,s.className=`panel-row`,c.className=`panel-action`,c.textContent=`Generate Blueprint`,l.className=`panel-action`,l.textContent=`Attach to Selected`,u.className=`panel-action`,u.textContent=`Build and Place`,d.className=`panel-action`,d.textContent=`Save Blueprint`;let m=()=>{o.textContent=JSON.stringify(p,null,2),s.replaceChildren();let e=k.selectedObject||k.placedObjects.at(-1)||null;e&&Lr(e,s)};m(),c.onclick=async()=>{try{p=await jr(a.value,{name:r.value,kit:i.value}),p.name=r.value||p.name,p.prompt=a.value,p.kit=i.value,p.updatedAt=Date.now(),m(),E(`Jarvis blueprint generated. Review the schema and then attach or build.`,`Model Forge`)}catch(e){T(e.message,`Model Forge Failed`)}},l.onclick=()=>{let e=k.selectedObject;if(!e){E(`Select a model first, then attach the schema.`,`Model Forge`);return}Fr(e,{...p,name:r.value||p.name||e.userData.modelName||`Custom Model`,prompt:a.value,kit:i.value}),Ur(e),m(),E(`Behavior schema attached to ${e.userData.modelName||`selected model`}.`,`Model Forge`)},u.onclick=()=>{try{let e=Mr({...p,name:r.value||p.name||`Custom Model`,prompt:a.value,kit:i.value});po(e,e.userData.modelName),Ur(e),E(`${e.userData.modelName} built with ${e.userData.modelForge?.parts?.length||0} interactive parts.`,`Model Forge`)}catch(e){T(e.message,`Model Forge Failed`)}},d.onclick=()=>{p={...p,name:r.value||p.name,prompt:a.value,kit:i.value,updatedAt:Date.now()},Ar(p),E(`Blueprint saved locally for later reuse.`,`Model Forge`)},e.append(t,n,r,i,a,c,l,u,d,o,s),new un({title:`Interactive Model Forge`,body:e,icon:`F`,width:390,height:620}).focus()}function eo(e,t,n=()=>!1){let r=document.createElement(`article`);if(r.className=`model-card ${e.source}-card`,e.thumbnail){let t=document.createElement(`img`);t.src=e.thumbnail,t.alt=``,t.loading=`lazy`,r.appendChild(t)}let i=document.createElement(`div`),a=document.createElement(`strong`),o=document.createElement(`span`),s=document.createElement(`a`);a.textContent=e.name;let c=e.size?hs(e.size):`free`,l=e.faceCount?` / ${gs(e.faceCount)} faces`:``;o.textContent=`${e.licenseLabel} / ${c}${l}`,s.textContent=`${e.author} (${e.source.toUpperCase()})`,s.href=e.authorUrl||e.viewerUrl||`#`,s.target=`_blank`,s.rel=`noopener`,i.append(a,o,s);let u=document.createElement(`div`);u.className=`model-actions`;let d=document.createElement(`button`);d.className=`panel-action`;let f=e.source===`sketchfab`&&!n()&&!t();d.textContent=f?`Token Needed`:`Place`,d.onclick=()=>{if(f){T(`Sketchfab downloads require a configured token.`,`Token Required`);return}to(e,t())};let p=document.createElement(`a`);return p.className=`panel-action link-action`,p.href=e.viewerUrl||`#`,p.target=`_blank`,p.rel=`noopener`,p.textContent=`Open`,u.append(d,p),r.append(i,u),r}async function to(e,t){O(`Requesting ${e.source.toUpperCase()} download: ${e.name}...`,55);try{let n;if(e.downloadUrl===`forge-procedural`)n=Mr(z({name:e.name,kit:_s(e.name)}));else if(e.downloadUrl&&e.downloadUrl.startsWith(`api:spawn_3d_model:`)){let t=e.downloadUrl.split(`api:spawn_3d_model:`)[1];E(`[STABLE FAST 3D] Generating custom 3D model for: ${t}...`,`Jarvis AI Generation`),fetch(`/xr/model3d/spawn`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${Qn(`omega_session`)||``}`},body:JSON.stringify({description:t,persona:`JARVIS`})}).catch(e=>console.error(`Generation request failed:`,e)),hidePanel(),clearLoading();return}else if(e.downloadUrl)(e.source===`cgtrader`||e.source===`turbosquid`||e.source===`mixamo`||e.source===`poly_pizza`)&&(Qn(e.source)?e.source===`mixamo`?E(`[Mixamo] Secure Adobe ID Synchronized! Placed free rigged character.`,`Mixamo Rigging`):e.source===`poly_pizza`?E(`[Poly.pizza] Authenticated API Key! Placed free low-poly asset.`,`Poly.pizza API`):E(`[${e.source.toUpperCase()}] Authenticated as user! Placed free model.`,`${e.source.toUpperCase()} Session`):E(`[${e.source.toUpperCase()}] Session Proxy: Connected via OMEGA public portal... Placed free model!`,`${e.source.toUpperCase()} Session`)),n=await ho(e.downloadUrl);else if(e.source===`sketchfab`){In(t);let r=await Un(e.uid,t),i=r.glb?.url||r.gltf?.url;if(!i)throw Error(`Sketchfab did not return a glTF or GLB download URL.`);n=r.glb?.url?await ho(i):await no(i)}else throw Error(`Unsupported model source: ${e.source}`);n.userData.modelName=e.name,n.userData.sketchfab=e.sketchfab||{uid:e.uid,author:e.author,authorUrl:e.authorUrl||``,license:e.license||`free`,licenseLabel:e.licenseLabel||`Free`,viewerUrl:e.viewerUrl||``},Fr(n,z({name:e.name,kit:_s(e.name)}));let r=uo(.5,.56);mo(n,e.name,r.position,r.rotation,`${e.source}:${e.uid}`),E(`${e.name} placed successfully from ${e.source.toUpperCase()}.`,e.source.toUpperCase())}catch(t){T(`${e.source.toUpperCase()} failed: ${t.message}. Spawning premium generated fallback...`,`${e.source.toUpperCase()} Fallback`);let n=No(e.name);Fr(n,z({name:e.name,kit:_s(e.name)}));let r=uo(.5,.56);mo(n,e.name,r.position,r.rotation,``)}finally{Qe()}}async function no(e){let t=await fetch(e);if(!t.ok)throw Error(`Sketchfab archive download failed: ${t.status}`);let n=ba(new Uint8Array(await t.arrayBuffer())),r=Object.keys(n).filter(e=>e.toLowerCase().endsWith(`.gltf`));if(!r.length)throw Error(`Sketchfab archive did not contain a .gltf scene.`);let i=r.find(e=>e.toLowerCase().replace(/.*\//,``)===`scene.gltf`)??r.reduce((e,t)=>n[t].byteLength>n[e].byteLength?t:e,r[0]),a=new TextDecoder().decode(n[i]),o=i.includes(`/`)?i.slice(0,i.lastIndexOf(`/`)+1):``,s=new Map;for(let[e,t]of Object.entries(n)){let n=ps(e),r=URL.createObjectURL(new Blob([t],{type:n}));s.set(ms(e),r),s.set(e.split(`/`).pop(),r)}let c=new v;c.setURLModifier(e=>{let t=ms(e),n=ms(`${o}${t}`);return s.get(t)||s.get(n)||s.get(t.split(`/`).pop())||e});let l=ka(new Le(c));return Oa(),new Promise((e,t)=>{l.parse(a,o,t=>{for(let e of new Set(s.values()))URL.revokeObjectURL(e);e(t.scene)},e=>{for(let e of new Set(s.values()))URL.revokeObjectURL(e);t(e)})})}function ro(e){let t=document.createElement(`article`);t.className=`model-card`;let n=document.createElement(`div`),r=document.createElement(`strong`),i=document.createElement(`span`),a=document.createElement(`button`);return r.textContent=e.name,i.textContent=`${e.category} / ${e.size}`,a.className=`panel-action`,a.textContent=`Place`,a.onclick=()=>co(e.name),n.append(r,i),t.append(n,a),t}async function io(e){if(!e)return;if(e.size>100*1024*1024){T(`Custom model is larger than 100MB. Please optimize or compress it first.`,`Model Too Large`);return}let t=e.name.split(`.`).pop()?.toLowerCase(),n=``;try{n=URL.createObjectURL(e);let r=t===`glb`||t===`gltf`?await ho(n):await ao(n,t);r.userData.modelName=e.name,po(r,e.name);let i=ar(Ca,[]);i.push({name:e.name,type:t,size:e.size,addedAt:Date.now()}),or(Ca,i.slice(-24))}catch(e){T(e.message,`Custom Model Failed`)}finally{n&&URL.revokeObjectURL(n)}}async function ao(e,n){if(n===`obj`){let{OBJLoader:n}=await t(async()=>{let{OBJLoader:e}=await import(`./three-Bwrc_W3C.js`).then(e=>e.t);return{OBJLoader:e}},__vite__mapDeps([1,2]),import.meta.url);return new Promise((t,r)=>new n().load(e,t,void 0,r))}if(n===`fbx`){let{FBXLoader:n}=await t(async()=>{let{FBXLoader:e}=await import(`./three-Bwrc_W3C.js`).then(e=>e.n);return{FBXLoader:e}},__vite__mapDeps([1,2]),import.meta.url);return new Promise((t,r)=>new n().load(e,t,void 0,r))}throw Error(`Unsupported custom model type: ${n||`unknown`}`)}function oo(){if(k.modelPlacementEventsBound)return;k.modelPlacementEventsBound=!0;let e=document.getElementById(`camerafeed`);e?.addEventListener(`pointerdown`,e=>qo(e.clientX,e.clientY)),e?.addEventListener(`pointerup`,Jo),e?.addEventListener(`pointermove`,Jo),document.addEventListener(`touchend`,e=>{if(!k.pendingModelToPlace||lo(e.target))return;let t=e.changedTouches[0];t&&so(t.clientX,t.clientY,e)},{passive:!0,capture:!0}),document.addEventListener(`pointerup`,e=>{e.pointerType!==`touch`&&(!k.pendingModelToPlace||lo(e.target)||so(e.clientX,e.clientY,e))},!0)}async function so(e,t,n=null){if(!k.pendingModelToPlace)return;let r=performance.now(),i=n?.pointerId??n?.changedTouches?.[0]?.identifier??n?.detail?.pointerId??++Wa,a=`${Math.round(e)}:${Math.round(t)}:${n?.type||`auto`}:${i}`;if(r-Ra<350&&a===za)return;Ra=r,za=a;let o=k.pendingModelToPlace,s=uo(e/innerWidth,t/innerHeight);k.pendingModelToPlace=``,delete document.body.dataset.jarvisPendingModel,ds(!1),Va++,window.clearTimeout(Ba),Ba=0;try{await fo(o,s.position,s.rotation)}catch(e){T(e.message,`Model Placement Failed`)}}function co(e){k.pendingModelToPlace=e,document.body.dataset.jarvisPendingModel=e,ds(!0),E(`Tap a detected surface to place ${e}. Auto-place will use the center hit-test if no tap arrives.`,`Model Armed`),window.clearTimeout(Ba),Ba=0;let t=++Va;Ba=window.setTimeout(()=>{k.pendingModelToPlace===e&&Va===t&&so(innerWidth/2,innerHeight*.56)},900)}function lo(e){return!!e?.closest?.(`.ar-panel, .hud-toolbar, button, input, select, textarea, iframe`)}function uo(e,t){try{let n=globalThis.XR8?.XrController?.hitTest?.(e,t,[`FEATURE_POINT`,`ESTIMATED_SURFACE`,`DETECTED_SURFACE`]);if(n&&n.length>0)return n[0]}catch{}let{camera:n}=R(),r=new Re(e*2-1,-(t*2-1)),i=new y;i.setFromCamera(r,n);let a=(k.floorY-i.ray.origin.y)/i.ray.direction.y;return{position:Number.isFinite(a)&&a>0?i.ray.origin.clone().add(i.ray.direction.clone().multiplyScalar(a)):i.ray.origin.clone().add(i.ray.direction.clone().multiplyScalar(2)),rotation:new C}}async function fo(e,t,n){O(`Loading ${e}...`,55);try{let r=En(e),i=await ho(r,(t,n)=>{n&&O(`Loading ${e}... ${Math.round(t/n*100)}%`,55+Math.round(t/n*30))});return Fr(i,z({name:e,kit:_s(e)})),mo(i,e,t,n,r),Qe(),i}catch(r){T(`Remote GLB failed for ${e}: ${r.message}. Generated fallback spawned instead.`,`Model Fallback`);let i=No(e);return Fr(i,z({name:e,kit:_s(e)})),mo(i,e,t,n,``),Qe(),i}}function po(e,t=`Custom Model`){let n=uo(.5,.55);mo(e,t,n.position,n.rotation,``)}function mo(e,t,n,r,i){let{scene:a}=R();e.position.copy(fs(n)),r?.isQuaternion?e.quaternion.copy(r):r&&e.quaternion.set(r.x||0,r.y||0,r.z||0,r.w||1),jo(e),e.userData.id=e.userData.id||dr(`model`),e.userData.modelName=t,e.userData.sourceURL=i,e.userData.isARObject=!0,!e.userData.modelForge&&!e.userData.modelForgeBlueprint&&Fr(e,z({name:t,kit:_s(t)})),e.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0)});let o=e.scale.clone();return e.userData.finalScale=o.toArray(),e.scale.setScalar(.001),a.add(e),k.placedObjects.push(e),Lo(e),Di(e),Mo(e,o,()=>{e.userData.finalScale=o.toArray(),Bo(),Oi(e,`place`)}),document.body.dataset.jarvisObjects=String(k.placedObjects.length),document.body.dataset.jarvisLastModel=t,L(`upsertObject`,e.userData.id,i||`model`,t,e.position.x,e.position.y,e.position.z),j(`object-placed`,{object:e,modelName:t}),e}function ho(e,t){Oa();let n=Oo(e),r=Na.get(n);if(r?.template)return Promise.resolve(go(r));if(r?.promise)return r.promise.then(e=>go(e));let i={key:n,url:e,template:null,promise:null,refCount:0,bytes:0,lastUsed:ko(),loading:!0};return i.promise=new Promise((r,a)=>{Aa.load(e,e=>{i.template=_r(e.scene,{targetSize:1,maxTextureSize:2048,maxAnisotropy:6}),i.animations=e.animations||[];let t=gr(i.template);i.metrics=t,i.bytes=Math.max(t.bytes||Co(i.template),512*1024),i.lastUsed=ko(),i.loading=!1,i.promise=null,So(i.template,n),t.warnings.length&&j(`assistant`,`Optimized ${n} for scale and texture budget: ${t.warnings.join(`, `)}.`),Pa+=i.bytes,r(i)},e=>t?.(e.loaded,e.total),e=>{Na.delete(n),i.loading=!1,i.promise=null,a(e)})}),Na.set(n,i),i.promise.then(e=>go(e))}function go(e){e.refCount+=1,e.lastUsed=ko();let t=Oe(e.template);return t.userData.assetCacheKey=e.key,t.userData.assetCacheShared=!0,t.userData.assetCacheBytes=e.bytes,So(t,e.key),bo(),t}function _o(e){let t=e?.userData?.assetCacheKey,n=t?Na.get(t):null,r=n?.template?go(n):e.clone(!0);return r.position.copy(e.position),r.quaternion.copy(e.quaternion),r.scale.copy(e.scale),r.name=e.name,r.visible=e.visible,r.userData={...Ao(e.userData),assetCacheKey:r.userData.assetCacheKey,assetCacheShared:r.userData.assetCacheShared,assetCacheBytes:r.userData.assetCacheBytes},delete r.userData.shadow,r.traverse(e=>{e.isMesh&&(e.castShadow=!0,e.receiveShadow=!0,e.frustumCulled=!0)}),r}function vo(e){let t=e?.userData?.assetCacheKey;if(!t)return!1;let n=Na.get(t);return n?(n.refCount=Math.max(0,n.refCount-1),n.lastUsed=ko(),bo(),!0):!0}function yo(e){Et(e,{disposeSharedAssets:!vo(e)})}function bo(e=!1){let t=[...Na.values()].filter(e=>e.template&&!e.loading&&e.refCount===0).sort((e,t)=>e.lastUsed-t.lastUsed);for(;t.length&&(e||Na.size>ja||Pa>Ma);)xo(t.shift())}function xo(e){!e||e.refCount>0||(Na.delete(e.key),Pa=Math.max(0,Pa-e.bytes),e.template&&Et(e.template,{disposeSharedAssets:!0}),e.template=null)}function So(e,t){e.userData.sharedAssetKey=t,e.traverse(e=>{e.userData.sharedAssetKey=t,e.geometry&&(e.geometry.userData=e.geometry.userData||{},e.geometry.userData.sharedAssetKey=t),Eo(e.material,e=>{e.userData=e.userData||{},e.userData.sharedAssetKey=t,Do(e,e=>{e.userData=e.userData||{},e.userData.sharedAssetKey=t})})})}function Co(e){let t=new Set,n=new Set,r=new Set,i=0;return e.traverse(e=>{e.geometry&&!t.has(e.geometry)&&(t.add(e.geometry),i+=wo(e.geometry)),Eo(e.material,e=>{n.has(e)||(n.add(e),i+=2048),Do(e,e=>{r.has(e)||(r.add(e),i+=To(e))})})}),Math.max(i,512*1024)}function wo(e){let t=0,n=e=>{e?.array?.byteLength&&(t+=e.array.byteLength)};return Object.values(e.attributes||{}).forEach(n),Object.values(e.morphAttributes||{}).forEach(e=>e.forEach(n)),n(e.index),t}function To(e){let t=e?.image||{};if(t.data?.byteLength)return t.data.byteLength;let n=t.width||t.videoWidth||t.naturalWidth||256,r=t.height||t.videoHeight||t.naturalHeight||256;return Math.max(1,n)*Math.max(1,r)*4}function Eo(e,t){(Array.isArray(e)?e:[e]).filter(Boolean).forEach(t)}function Do(e,t){let n=new Set,r=e=>{if(!(!e||typeof e!=`object`)){if(e.isTexture){n.has(e)||(n.add(e),t(e));return}if(Array.isArray(e)){e.forEach(r);return}e.value?.isTexture?r(e.value):e.constructor===Object&&Object.values(e).forEach(r)}};Object.values(e).forEach(r)}function Oo(e){return String(e||``).trim()}function ko(){return typeof performance<`u`?performance.now():Date.now()}function Ao(e){try{return structuredClone(e)}catch{try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}}}function jo(e){let t=new ge().setFromObject(e).getSize(new w).length(),n=t>0?.55/t:.35;e.scale.setScalar(Math.min(1,n))}function Mo(e,t,n){let r=performance.now(),i=0,a=()=>{if(!e.parent){dt(i);return}let o=Math.min((performance.now()-r)/420,1),s=o<.6?o/.6*1.1:1.1-.1*((o-.6)/.4);e.scale.copy(t).multiplyScalar(s),o<1?i=F(a):(e.scale.copy(t),n?.())};i=F(a)}function No(e){let t=new Se,n=new h(new xe(.28,2),new Ue({color:43775,emissive:21879,roughness:.25,metalness:.35,transparent:!0,opacity:.78})),r=new h(new we(.42,.008,8,96),xa.clone());r.rotation.x=Math.PI/2;let i=Io(e);return i.position.y=.48,t.add(n,r,i),t}function Po(e,t){let n=k.selectedObject||k.placedObjects.at(-1);n&&(Hr(n,e,t),Ro(n),Ur(n),Oi(n,e))}function Fo(e={}){let t=vs(e.action||e.command||``),n=String(e.target||e.model||e.query||``).trim(),r=k.selectedObject||k.placedObjects.at(-1)||null;if(n){let e=n.toLowerCase();r=k.placedObjects.find(t=>{let n=String(t.userData?.modelName||``).toLowerCase(),r=t.userData?.modelForge?.parts||[];return n.includes(e)||r.some(t=>String(t.name||``).toLowerCase().includes(e))})||r}!r||!t||(Vr(r,t,e),Ro(r),Ur(r),Oi(r,t))}function Io(e){let t=String(e||`Model`).trim().toLowerCase(),n=Ga.get(t);if(n){let e=new ce(new ke({map:n.texture,transparent:!0}));return e.scale.set(.9,.23,1),e.userData.labelCacheKey=t,e}let r=document.createElement(`canvas`);r.width=512,r.height=128;let i=r.getContext(`2d`);i.clearRect(0,0,r.width,r.height),i.fillStyle=`rgba(0,0,0,0.32)`,i.fillRect(0,0,r.width,r.height),i.fillStyle=`#fff`,i.font=`600 34px Inter, sans-serif`,i.textAlign=`center`,i.textBaseline=`middle`,i.fillText(String(e).slice(0,24),256,64);let a=new Ve(r);a.userData=a.userData||{},a.userData.sharedAssetKey=`label:${t}`,Ga.set(t,{texture:a});let o=new ce(new ke({map:a,transparent:!0}));return o.scale.set(.9,.23,1),o.userData.labelCacheKey=t,o}function Lo(e){e.userData.shadow?.parent?.remove(e.userData.shadow);let t=new h(new o(.35,48),new b({color:0,transparent:!0,opacity:.24,depthWrite:!1}));t.rotation.x=-Math.PI/2,t.name=`jarvis-blob-shadow`,e.userData.shadow=t,Ro(e),R().scene.add(t)}function Ro(e){let t=e?.userData?.shadow;t&&t.position.set(e.position.x,k.floorY+.004,e.position.z)}function zo(e){return Array.isArray(e)&&e.length>=3&&e.every(e=>Number.isFinite(e)&&e>.01)}function Bo(){or(Sa,k.placedObjects.map(e=>({id:e.userData.id,modelName:e.userData.modelName,sourceURL:e.userData.sourceURL||``,sketchfab:e.userData.sketchfab||null,modelForge:e.userData.modelForge||e.userData.modelForgeBlueprint||null,position:e.position.toArray(),quaternion:e.quaternion.toArray(),scale:Array.isArray(e.userData.finalScale)?e.userData.finalScale:e.scale.toArray(),trackingMode:k.trackingMode,floorY:k.floorY,anchor:Ho(e),savedAt:Date.now()})))}async function Vo(){let e=ar(Sa,[]),t=[];for(let n of e)try{let e=n.sourceURL&&!n.sourceURL.startsWith(`sketchfab:`)?await ho(n.sourceURL):No(n.modelName);e.userData.id=n.id,e.position.fromArray(n.position),e.quaternion.fromArray(n.quaternion),e.scale.fromArray(zo(n.scale)?n.scale:[.35,.35,.35]),e.userData.finalScale=e.scale.toArray(),e.userData.modelName=n.modelName,e.userData.sourceURL=n.sourceURL,e.userData.sketchfab=n.sketchfab||null,e.userData.worldAnchor=n.anchor||null,e.userData.isARObject=!0,Fr(e,n.modelForge||z({name:n.modelName||`Restored Model`,kit:_s(n.modelName)})),R().scene.add(e),k.placedObjects.push(e),Lo(e),Di(e),Wo(e),document.body.dataset.jarvisObjects=String(k.placedObjects.length)}catch(e){t.push(`${n.modelName||`Restored Model`}: ${e?.message||`load failed`}`);let r=No(n.modelName||`Restored Model`);r.position.fromArray(n.position||[0,k.floorY,-2]),r.scale.fromArray(zo(n.scale)?n.scale:[.35,.35,.35]),r.userData.finalScale=r.scale.toArray(),r.userData.id=n.id||dr(`model`),r.userData.modelName=n.modelName||`Restored Model`,r.userData.sourceURL=n.sourceURL||``,r.userData.sketchfab=n.sketchfab||null,r.userData.worldAnchor=n.anchor||null,r.userData.isARObject=!0,Fr(r,n.modelForge||z({name:n.modelName||`Restored Model`,kit:_s(n.modelName)})),R().scene.add(r),k.placedObjects.push(r),Lo(r),Di(r),Wo(r),document.body.dataset.jarvisObjects=String(k.placedObjects.length)}t.length&&E(`Some saved models failed to restore and were replaced with generated fallbacks: ${t.slice(0,3).join(`; `)}${t.length>3?` (+${t.length-3} more)`:``}`,`Model Restore`)}function Ho(e){return{type:`world-point-signature-v1`,position:e.position.toArray(),quaternion:e.quaternion.toArray(),floorY:k.floorY,signature:Uo(),trackingMode:k.trackingMode,createdAt:Date.now()}}function Uo(){let e=k.worldPointBuffer.slice(-360);if(e.length<10)return{count:e.length,centroid:[0,k.floorY,0],floorY:k.floorY};let t=e.reduce((e,t)=>(e.x+=t.x,e.y+=t.y,e.z+=t.z,e),new w).multiplyScalar(1/e.length);return{count:e.length,centroid:t.toArray(),floorY:k.floorY}}function Wo(e){e.userData.worldAnchor&&(Ka.add(e),Ko(e))}function Go(){Ka.forEach(e=>{if(!e.parent){Ka.delete(e);return}Ko(e)})}function Ko(e){let t=e.userData.worldAnchor;if(!t?.position)return;let n=t.signature||{},r=Uo(),i=new w().fromArray(t.position);n.count>=10&&r.count>=10&&Array.isArray(n.centroid)&&(i.x+=r.centroid[0]-n.centroid[0],i.z+=r.centroid[2]-n.centroid[2]);let a=Number.isFinite(t.floorY)?t.floorY:n.floorY;Number.isFinite(a)&&Number.isFinite(r.floorY)&&(i.y+=r.floorY-a),e.position.copy(i),Ro(e)}function qo(e,t){Jo(),Ia=window.setTimeout(()=>{Yo(e,t),k.selectedObject&&$o(e,t,k.selectedObject)},500)}function Jo(){window.clearTimeout(Ia)}function Yo(e,t){let{camera:n}=R(),r=new y;r.setFromCamera(new Re(e/innerWidth*2-1,-(t/innerHeight)*2+1),n);let i=r.intersectObjects(k.placedObjects,!0)[0]?.object;return k.selectedObject=i?Xo(i):null,k.selectedObject}function Xo(e){let t=e;for(;t&&!t.userData.isARObject&&t.parent;)t=t.parent;return t?.userData?.isARObject?t:null}function Zo(e){let t=e?.origin,n=e?.direction;if(!t||!n)return null;let r=new w(n.x,n.y,n.z);if(r.lengthSq()<1e-8)return null;r.normalize();let i=new w(t.x,t.y,t.z),a=new y(i,r).intersectObjects(k.placedObjects,!0),o=a[0]?.object?Xo(a[0].object):null;if(o)return k.selectedObject=o,Qo(o),Oi(o,`select`),j(`gesture-pinch`,{source:`xr-transient-pointer`,object:o}),L(`status`,`Selected ${o.userData.modelName||`object`} via pinch`),{type:`select`,object:o};if(k.pendingModelToPlace){let e=Number.isFinite(k.floorY)?k.floorY:-1.5,t=Math.abs(r.y)>1e-4?(e-i.y)/r.y:-1,n=t>0&&t<40?new w(i.x+r.x*t,e,i.z+r.z*t):i.clone().add(r.clone().multiplyScalar(1.6)).setY(e),a=k.pendingModelToPlace;return k.pendingModelToPlace=``,delete document.body.dataset.jarvisPendingModel,ds(!1),fo(a,n,new C).catch(e=>T(e.message,`Model Placement Failed`)),{type:`place`,point:n}}return null}function Qo(e){if(!e||e.userData._xrPulsing)return;e.userData._xrPulsing=!0;let t=e.scale.clone(),n=t.clone().multiplyScalar(1.06),r=performance.now(),i=a=>{let o=Math.min(1,(a-r)/170),s=o<.5?o*2:(1-o)*2;e.scale.lerpVectors(t,n,s),o<1?F(i):(e.scale.copy(t),e.userData._xrPulsing=!1)};F(i)}function $o(e,t,n){Fa?.remove(),Fa=document.createElement(`section`),Fa.className=`context-menu glass-panel`,Fa.style.left=`${Math.min(e,innerWidth-210)}px`,Fa.style.top=`${Math.min(t,innerHeight-250)}px`;let r=[[`Duplicate`,()=>ns(n)],[`Delete`,()=>rs(n)],[`Physics ON`,()=>is(n)],[`Open`,()=>es(n,`open`)],[`Close`,()=>es(n,`close`)],[`Toggle`,()=>es(n,`toggle`)],[`Shatter`,()=>es(n,`shatter`)],[`Forge`,()=>j(`open-model-forge`)],[`Save`,()=>Bo()],[`Export .GLB`,()=>as(n)]];for(let[e,t]of r){let n=document.createElement(`button`);n.textContent=e,n.onclick=()=>{t(),Fa?.remove()},Fa.appendChild(n)}document.body.appendChild(Fa),window.setTimeout(()=>document.addEventListener(`pointerdown`,ts,{once:!0}),0)}function es(e,t){Vr(e,t),Ro(e),Ur(e),Oi(e,t),L(`manipulateObject`,e.userData.id||``,t)}function ts(e){Fa?.contains(e.target)||Fa?.remove()}function ns(e){let t=_o(e),n=new w(.25,.02,-.25).applyQuaternion(e.quaternion);t.position.add(n),t.userData.id=dr(`model`),t.userData.finalScale=e.userData.finalScale||t.scale.toArray(),delete t.userData.worldAnchor,(e.userData.modelForge||e.userData.modelForgeBlueprint)&&Fr(t,e.userData.modelForge||e.userData.modelForgeBlueprint),R().scene.add(t),k.placedObjects.push(t),Lo(t),Di(t),Oi(t,`place`),Bo()}function rs(e){k.placedObjects=k.placedObjects.filter(t=>t!==e),Ka.delete(e),k.selectedObject===e&&(k.selectedObject=null),La.get(e.userData.id)&&(La.delete(e.userData.id),La.size||stopPhysicsLoop()),e.userData.shadow&&Et(e.userData.shadow),Oi(e,`delete`),L(`removeObject`,e.userData.id||``),yo(e),Bo()}async function is(e){if(La.has(e.userData.id)){unregisterPhysicsMesh(La.get(e.userData.id)),La.delete(e.userData.id);return}let t=createRigidBody(e.position,`dynamic`);registerPhysicsMesh(e,t),La.set(e.userData.id,t)}window.addEventListener(`ar-physics-step`,()=>{for(let e of La.keys()){let t=k.placedObjects.find(t=>t.userData.id===e);t&&Ro(t)}});async function as(e){let{GLTFExporter:n}=await t(async()=>{let{GLTFExporter:e}=await import(`./three-Bwrc_W3C.js`).then(e=>e.r);return{GLTFExporter:e}},__vite__mapDeps([1,2]),import.meta.url),r=new n;await os(e),r.parse(e,t=>{let n=t instanceof ArrayBuffer?new Blob([t],{type:`model/gltf-binary`}):new Blob([JSON.stringify(t)],{type:`model/gltf+json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=`${e.userData.modelName||`jarvis-model`}.glb`,i.click(),URL.revokeObjectURL(r)},e=>T(e.message,`Export Failed`),{binary:!0})}async function os(e){let t=[];e.traverse(e=>{Eo(e.material,e=>{Do(e,e=>{t.push(e)})})}),await Promise.all(t.map(async e=>{let t=e?.image;if(t){if(t.complete===!1){await new Promise(e=>{let n=()=>e();t.addEventListener?.(`load`,n,{once:!0}),t.addEventListener?.(`error`,n,{once:!0}),window.setTimeout(n,1200)});return}if(typeof t.decode==`function`)try{await t.decode()}catch{}}}))}function ss(){let e=document.createElement(`div`);e.style.cssText=`display: flex; flex-direction: column; gap: 8px;`;let t=document.createElement(`strong`);t.textContent=`JARVIS Stark 3D Composer`,t.style.cssText=`font-size: 14px; color: var(--accent); text-transform: uppercase;`;let n=document.createElement(`select`);fr(n,[[`primitive`,`Custom Basic Geometry`],[`arc_reactor`,`Stark Arc Reactor Core`],[`gauntlet`,`Holographic Repulsor Gauntlet`],[`thruster`,`Flight Ion Propulsion Thruster`],[`quantum_reactor`,`Quantum Core Reactor Engine`],[`faceplate`,`Cybernetic Visor Faceplate`]]);let r=document.createElement(`select`);fr(r,[[`metal`,`Machined Brushed Titanium`],[`gold`,`Polished Golden Core`],[`glass`,`Translucent Ethereal Glass`],[`glow`,`Glowing Neon Hologram`],[`matte`,`Stark Matte Composite`]]);let i=document.createElement(`div`);i.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let a=document.createElement(`span`);a.textContent=`Shape / Geometry:`,a.style.cssText=`font-size: 11px; color: var(--text-secondary);`;let o=document.createElement(`select`);fr(o,[`cube`,`sphere`,`cylinder`,`cone`,`plane`,`torus`,`ring`,`capsule`]),i.append(a,o);let s=document.createElement(`div`);s.style.cssText=`display: flex; flex-direction: column; gap: 4px;`;let c=document.createElement(`span`);c.textContent=`Visual Detail Level:`,c.style.cssText=`font-size: 11px; color: var(--text-secondary);`;let l=document.createElement(`select`);fr(l,[[`standard`,`Standard`],[`premium`,`Premium`],[`hero`,`Hero Detail`]]),s.append(c,l);let u=document.createElement(`input`);u.placeholder=`Model custom name (e.g. Mark 85 reactor)`;let d=document.createElement(`button`);d.className=`panel-action`,d.textContent=`Build Stark Composite`,d.style.cssText=`background: var(--accent); color: #fff; font-weight: 600; min-height: 42px; border-radius: 12px; margin-top: 8px;`,n.onchange=()=>{let e=n.value===`primitive`;i.style.display=e?`flex`:`none`,s.style.display=e?`flex`:`none`,u.value=e?``:n.options[n.selectedIndex].text},d.onclick=()=>{let e=n.value,t;t=e===`primitive`?ls(o.value,r.value,l.value):cs(e,r.value);let i=u.value||`${r.options[r.selectedIndex].text} ${n.options[n.selectedIndex].text}`;t.userData.modelName=i,Fr(t,z({name:i,kit:e===`primitive`?`scene`:_s(e)})),po(t,i);let a=ar(Ca,[]);a.push({name:i,assembly:e,material:r.value,addedAt:Date.now()}),or(Ca,a.slice(-24)),E(`Successfully composed and placed Stark asset: ${i}.`,`3D Composer`)};let f=document.createElement(`p`);f.className=`panel-note`,f.textContent=`Stark Assemblies generate premium multi-part geometries with concentric highlights, glowing points, and kinematic hinges.`,e.append(t,n,r,i,s,u,d,f),new un({title:`Stark 3D Composer`,body:e,icon:`B`,width:375,height:490}).focus()}function cs(e,t){let n=new Se;n.name=`stark-${e}`;let r=us(t===`gold`?`metal`:t);t===`gold`&&(r.color.setHex(16766720),r.roughness=.05,r.metalness=.95);let i=new b({color:54015,transparent:!0,opacity:.85}),o=new b({color:16777215,transparent:!0,opacity:.95}),s=new a({color:3815994,roughness:.6,metalness:.8});if(e===`arc_reactor`){let e=new h(new c(.18,.18,.06,32),s);e.position.y=-.03,n.add(e);let t=new h(new c(.08,.08,.08,24),i);t.position.y=.01,t.userData.partName=`reactor-core`,t.userData.partType=`light`;let l=new Me(54015,3,2.5);l.position.set(0,0,0),t.add(l),n.add(t);let u=new h(new we(.15,.018,12,48),r);u.rotation.x=Math.PI/2,n.add(u);let d=new a({color:13794605,roughness:.18,metalness:.9});for(let e=0;e<10;e++){let t=e/10*Math.PI*2,r=new h(new oe(.024,.024,.018),d);r.position.set(Math.cos(t)*.15,0,Math.sin(t)*.15),r.rotation.y=-t,n.add(r)}let f=new h(new we(.1,.005,8,48),o);f.rotation.x=Math.PI/2,f.position.y=.02,n.add(f)}else if(e===`gauntlet`){let e=new h(new c(.1,.11,.28,16,1,!0,-Math.PI/2,Math.PI),r);e.rotation.x=Math.PI/2,e.userData.partName=`wrist-guard`,e.userData.partType=`base`,n.add(e);let t=new h(new c(.018,.018,.12,12),s);t.position.set(0,.07,-.06),t.rotation.x=Math.PI/2,t.userData.partName=`laser-emitter`,t.userData.partType=`detail`;let a=new h(new be(.012),o);a.position.y=.06,t.add(a),n.add(t);let l=new h(new be(.025,16,16),i);l.position.set(0,.06,.08),l.userData.partName=`palm-repulsor`,l.userData.partType=`light`;let u=new Me(54015,2.5,2);l.add(u),n.add(l)}else if(e===`thruster`){let e=new h(new c(.06,.11,.16,24),s);e.userData.partName=`thruster-nozzle`,e.userData.partType=`base`,n.add(e);let t=new h(new be(.045,16,16),r);t.position.y=-.06,t.userData.partName=`thruster-core`,t.userData.partType=`light`;let i=new Me(16771584,3.5,3);t.add(i),n.add(t);let a=new h(new c(.04,.005,.32,16),new b({color:16747520,transparent:!0,opacity:.65}));a.position.y=-.22,a.userData.partName=`thrust-stream`,a.userData.partType=`detail`,n.add(a)}else if(e===`quantum_reactor`){let e=new h(new c(.12,.12,.32,24),new Ue({color:13627391,roughness:.02,transmission:.8,transparent:!0,opacity:.3}));e.userData.partName=`quantum-capsule`,e.userData.partType=`window`,n.add(e);let t=new h(new we(.09,.01,8,32),r);t.position.y=.05,t.rotation.x=Math.PI/2,t.userData.partName=`upper-gear`,t.userData.partType=`wheel`,n.add(t);let a=new h(new we(.09,.01,8,32),r);a.position.y=-.05,a.rotation.x=Math.PI/2,a.userData.partName=`lower-gear`,a.userData.partType=`wheel`,n.add(a);let o=new h(new d(.04,0),i);o.userData.partName=`energy-core`,o.userData.partType=`light`;let s=new Me(65450,3,2);o.add(s),n.add(o)}else if(e===`faceplate`){let e=new h(new c(.14,.14,.18,16,1,!1,-Math.PI/3,Math.PI/3*2),r);e.userData.partName=`faceplate-armour`,e.userData.partType=`base`,n.add(e);let t=new h(new oe(.18,.04,.02),i);t.position.set(0,.02,.12),t.userData.partName=`visor-screen`,t.userData.partType=`screen`,n.add(t);let a=new h(new oe(.035,.005,.005),o);a.position.set(-.04,.02,.13),a.userData.partName=`left-eye`,a.userData.partType=`light`,n.add(a);let s=new h(new oe(.035,.005,.005),o);s.position.set(.04,.02,.13),s.userData.partName=`right-eye`,s.userData.partType=`light`,n.add(s)}return n}function ls(e,t,n=`standard`){let i=us(t),o={cube:()=>new oe(.35,.35,.35),sphere:()=>new be(.22,48,24),cylinder:()=>new c(.18,.18,.38,48),cone:()=>new ne(.2,.42,48),plane:()=>new m(.5,.5),torus:()=>new we(.23,.04,16,80),ring:()=>new r(.14,.24,64),capsule:()=>new te(.15,.35,8,24)}[e]?.()||new oe(.35,.35,.35),s=new Se;s.name=`builder-${e}-${n}`;let l=new h(o,i);l.castShadow=!0,l.receiveShadow=!0,s.add(l);let u=t===`glass`?new Ue({color:13627391,roughness:.02,transmission:.72,transparent:!0,opacity:.34}):new b({color:51455,transparent:!0,opacity:.75}),d=new h(new we(.27,.02,12,64),u);if(d.rotation.x=Math.PI/2,s.add(d),n===`premium`||n===`hero`){let e=new h(new be(.09,24,16),new a({color:16777215,roughness:.25,metalness:.3}));e.position.set(0,.25,0),s.add(e)}if(n===`hero`){let e=new h(new c(.06,.1,.18,6),new Ue({color:10475775,roughness:.14,metalness:.6,emissive:397597}));e.position.set(0,.34,0),e.rotation.y=Math.PI/6,s.add(e);let t=new h(new we(.33,.01,8,80),new b({color:16777215,transparent:!0,opacity:.55}));t.rotation.x=Math.PI/2,t.position.y=.02,s.add(t)}return s}function us(e){return e===`metal`?new Ue({color:9422847,roughness:.18,metalness:.9}):e===`glass`?new Ue({color:13627391,roughness:.04,transmission:.55,transparent:!0,opacity:.45}):e===`glow`?new b({color:51455,transparent:!0,opacity:.8}):new a({color:8109311,roughness:.55,metalness:.1})}function ds(e){k.reticle&&(k.reticle.visible=e)}function fs(e){return e?.isVector3?e:new w(e?.x||0,e?.y??k.floorY,e?.z||-2)}function ps(e){let t=e.toLowerCase();return t.endsWith(`.gltf`)?`model/gltf+json`:t.endsWith(`.bin`)?`application/octet-stream`:t.endsWith(`.png`)?`image/png`:t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.webp`)?`image/webp`:`application/octet-stream`}function ms(e){return decodeURIComponent(String(e||``)).replace(/\\/g,`/`).replace(/^blob:https?:\/\/[^/]+\//,``).replace(/^https?:\/\/[^/]+\//,``).replace(/^\/+/,``).replace(/^(\.\/)+/,``)}function hs(e){let t=Number(e||0);return t?t>1024*1024?`${Math.round(t/1024/1024)}MB`:`${Math.round(t/1024)}KB`:`size unknown`}function gs(e){let t=Number(e||0);return t?t>1e6?`${(t/1e6).toFixed(1)}M`:t>1e3?`${Math.round(t/1e3)}K`:String(t):`unknown`}function _s(e){let t=String(e||``).toLowerCase();return t.includes(`house`)||t.includes(`home`)?`house`:t.includes(`room`)||t.includes(`bedroom`)||t.includes(`kitchen`)?`room`:t.includes(`car`)||t.includes(`truck`)||t.includes(`vehicle`)?`vehicle`:t.includes(`phone`)||t.includes(`tablet`)||t.includes(`device`)?`device`:t.includes(`person`)||t.includes(`robot`)||t.includes(`character`)?`character`:`scene`}function vs(e){let t=String(e||``).toLowerCase().trim();return t?/(^|\b)(open|unfold|expand)(\b|$)/.test(t)?`open`:/(^|\b)(close|fold|collapse)(\b|$)/.test(t)?`close`:/(^|\b)(toggle|switch)(\b|$)/.test(t)?`toggle`:/(^|\b)(rotate|spin|turn)(\b|$)/.test(t)?`rotate`:/(^|\b)(reconfigure|rebuild|transform|rearrange)(\b|$)/.test(t)?`reconfigure`:/(^|\b)(shatter|break|explode)(\b|$)/.test(t)?`shatter`:/(^|\b)(reveal|show)(\b|$)/.test(t)?`reveal`:/(^|\b)(hide)(\b|$)/.test(t)?`hide`:/(^|\b)(grab|move|drag)(\b|$)/.test(t)?`grab`:t:``}var ys=0,bs=4,xs=8,Ss=12,Cs=16,ws=20,Ts=5,Es=6,Ds=9,Os=10,ks=13,As=14,js=17,Ms=new Map([[Ts,Es],[Ds,Os],[ks,As],[js,18]]),Ns=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[17,18],[18,19],[19,20],[0,17]],Ps=20,Fs=null,G=null,K=null,Is=!1,Ls=null,q=0,Rs=0,zs=0,Bs=!1,Vs=0,Hs=!1,Us=null,Ws=0,Gs=0,Ks=.55,qs=[];function Js(e,t){Ys(),t>0?(Vs=setTimeout(e,t),Hs=!0):(Vs=F(e),Hs=!1)}function Ys(){Vs&&(Hs?clearTimeout(Vs):dt(Vs),Vs=0)}async function Xs(){if(G=document.getElementById(`hand-overlay`),K=G?.getContext(`2d`),cc(),Us=ct(window,`resize`,cc),!globalThis.Hands)return I(`mediaPipeHands`,!1),T(`MediaPipe Hands did not load. Hand gestures are unavailable until the CDN script loads.`,`Hand Tracking`),!1;try{return Fs=new globalThis.Hands({locateFile:e=>`https://cdn.jsdelivr.net/npm/@mediapipe/hands/${e}`}),Fs.setOptions({maxNumHands:2,modelComplexity:1,minDetectionConfidence:.7,minTrackingConfidence:.65,selfieMode:!1}),Fs.onResults($s),Is=!0,I(`mediaPipeHands`,!0),Js(Zs,0),E(`Hand tracking armed. Use palm, pinch, fist, point, and swipe gestures.`),!0}catch(e){return T(e.message,`Hand Tracking Failed`),!1}}async function Zs(){if(!Is||!Fs)return;let e=performance.now();try{let t=gc();t?(e>=zs&&(zs=e+Ps,await Fs.send({image:t}),Bs=!1),Js(Zs,0)):(!Bs&&k.trackingMode===`8thwall-slam`&&(Bs=!0,E(`Waiting for XR camera pixels before enabling hand tracking.`,`Hand Tracking`)),Js(Zs,200))}catch(e){Bs||(Bs=!0,E(`Hand tracking frame skipped: ${e.message}`,`Hand Tracking`)),Js(Zs,200)}}function Qs(){Is=!1,Ys(),Us?.(),Us=null;try{Fs?.close?.()}catch{}Fs=null,sc(),Ls=null,q=0,Rs=0,Ws=0,Bs=!1,zs=0,Gs=0,k.gestureFrameCanvas?.remove?.(),k.gestureFrameCanvas=null,k.gestureFrameReady=!1,k.handState.hands=[],k.handState.gestures=new Map}function $s(e){sc();let t=(e.multiHandLandmarks||[]).map((e,t)=>ec(e,t));k.handState.hands=t,t.forEach((e,t)=>oc(e,t));let n=tc(t);k.handState.gestures=n;for(let[e,t]of n)j(`gesture-${e}`,t)}function ec(e,t){if(!qs[t])return qs[t]=e.map(e=>({x:e.x,y:e.y,z:e.z||0})),qs[t];let n=qs[t];for(let t=0;t<e.length;t++){let r=Ks;n[t].x=n[t].x*(1-r)+e[t].x*r,n[t].y=n[t].y*(1-r)+e[t].y*r,n[t].z=(n[t].z||0)*(1-r)+(e[t].z||0)*r}return n}function tc(e){let t=new Map;if(!e.length)return Ls=null,q=0,Rs=0,Ws=0,t;let n=e[0],r=uc(n[bs],n[xs]);r<.05&&t.set(`pinch`,{confidence:1-r/.05,hand:n}),rc(n)&&t.set(`fist`,{confidence:.88,hand:n}),ic(n)&&t.set(`open-palm`,{confidence:.9,hand:n}),ac(n)&&t.set(`point`,{confidence:.86,hand:n,point:n[xs]});let i=nc(n);if(i&&t.set(i,{confidence:.86,hand:n}),e.length>=2){let n=dc(e[0],e[1]);if(Rs>0){let r=n-Rs;Math.abs(r)>.035&&t.set(`two-hand-scale`,{confidence:.9,delta:r,distance:n,hands:e})}Rs=n}else Rs=0;return t}function nc(e){let t=performance.now();if(t<Ws)return``;let n=e[ys];if(!Ls)return Ls={x:n.x,y:n.y},``;let r=n.x-Ls.x;return Ls={x:n.x,y:n.y},r<-.03?--q:r>.03?q+=1:q*=.5,Math.abs(q)<.25&&(q=0),q=Math.max(-5,Math.min(5,q)),q<=-5?(q=0,Ws=t+180,Ls=null,`swipe-left`):q>=5?(q=0,Ws=t+180,Ls=null,`swipe-right`):``}function rc(e){return[xs,Ss,Cs,ws].every((t,n)=>{let r=[Ts,Ds,ks,js][n];return lc(e,t,r)>.58})}function ic(e){return[xs,Ss,Cs,ws].every((t,n)=>{let r=[Ts,Ds,ks,js][n];return lc(e,t,r)<.32})}function ac(e){return lc(e,xs,Ts)<.34&&lc(e,Ss,Ds)>.52&&lc(e,Cs,ks)>.52&&lc(e,ws,js)>.52}function oc(e){if(!K||!G)return;let t=uc(e[bs],e[xs])<.05,n=G.width,r=G.height,i=Math.max(1,n/Math.max(1,innerWidth));K.lineCap=`round`,K.lineJoin=`round`,K.lineWidth=2.4*i,K.strokeStyle=t?`rgba(0,122,255,0.7)`:`rgba(255,255,255,0.5)`;for(let[t,i]of Ns){let a=e[t],o=e[i];!a||!o||(K.beginPath(),K.moveTo(a.x*n,a.y*r),K.lineTo(o.x*n,o.y*r),K.stroke())}for(let a of e){let e=a.x*n,o=a.y*r,s=(t?9:6)*i,c=K.createRadialGradient(e,o,0,e,o,s);c.addColorStop(0,t?`rgba(0,122,255,0.95)`:`rgba(255,255,255,0.92)`),c.addColorStop(1,`rgba(255,255,255,0)`),K.fillStyle=c,K.beginPath(),K.arc(e,o,s,0,Math.PI*2),K.fill()}if(ic(e)){let t=(e[Ts].x+e[js].x)/2*n,a=(e[Ts].y+e[js].y)/2*r;K.strokeStyle=`rgba(255,255,255,0.55)`,K.lineWidth=3*i,K.beginPath(),K.arc(t,a,(40+Math.sin(performance.now()/180)*6)*i,0,Math.PI*2),K.stroke()}}function sc(){!K||!G||(K.save(),K.setTransform(1,0,0,1,0,0),K.clearRect(0,0,G.width,G.height),K.restore())}function cc(){if(!G)return;let e=Math.min(devicePixelRatio||1,3);G.width=Math.floor(innerWidth*e),G.height=Math.floor(innerHeight*e),G.style.width=`100vw`,G.style.height=`100vh`,K?.setTransform(1,0,0,1,0,0)}function lc(e,t,n){let r=e[t],i=e[n],a=e[Ms.get(n)];if(!r||!i||!a)return 0;let o=pc(a,i),s=pc(a,r),c=Math.max(hc(o),1e-4),l=Math.max(hc(s),1e-4),u=Math.max(-1,Math.min(1,mc(o,s)/(c*l)));return Math.max(0,Math.min(1,(Math.PI-Math.acos(u))/(Math.PI*.55)))}function uc(e,t){let n=e.x-t.x,r=e.y-t.y,i=(e.z||0)-(t.z||0);return Math.hypot(n,r,i)}function dc(e,t){let n=uc(e[ys],t[ys]),r=fc(e),i=fc(t);return n*.72+uc(r,i)*.28}function fc(e){return{x:(e[ys].x+e[Ts].x+e[js].x)/3,y:(e[ys].y+e[Ts].y+e[js].y)/3,z:((e[ys].z||0)+(e[Ts].z||0)+(e[js].z||0))/3}}function pc(e,t){return{x:t.x-e.x,y:t.y-e.y,z:(t.z||0)-(e.z||0)}}function mc(e,t){return e.x*t.x+e.y*t.y+e.z*t.z}function hc(e){return Math.hypot(e.x,e.y,e.z)}function gc(){if(k.cameraVideo?.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)return k.cameraVideo;if(k.gestureFrameReady&&k.gestureFrameCanvas?.width&&k.gestureFrameCanvas?.height)return k.gestureFrameCanvas;let e=performance.now();return e-Gs>5e3&&(Gs=e),null}function _c(){return{name:`mediapipe-camera-frame-source`,onUpdate:({processCpuResult:e})=>{yc(vc(e))}}}function vc(e){return e?.cameraPixelArray||e?.cameraPixels||e?.camerapixelarray||e?.pixels||e?.reality?.cameraPixelArray||e?.reality?.cameraPixels||null}function yc(e){if(!e)return;let t=e.pixels||e.data||e.buffer||e,n=e.width||e.cols||e.columnCount||e.pixelWidth||e.imageWidth,r=e.height||e.rows||e.rowCount||e.pixelHeight||e.imageHeight;if(!t||!n||!r)return;let i=Sc(t);if(!i.length)return;let a=bc(n,r).getContext(`2d`,{willReadFrequently:!0}),o=a.createImageData(n,r),s=xc(i.length,n,r),c=e.rowBytes||e.stride||n*s,l=0;for(let e=0;e<r;e+=1){let t=e*c;for(let e=0;e<n;e+=1){let n=t+e*s;if(s>=4)o.data[l]=i[n],o.data[l+1]=i[n+1],o.data[l+2]=i[n+2],o.data[l+3]=i[n+3]||255;else if(s===3)o.data[l]=i[n],o.data[l+1]=i[n+1],o.data[l+2]=i[n+2],o.data[l+3]=255;else{let e=i[n];o.data[l]=e,o.data[l+1]=e,o.data[l+2]=e,o.data[l+3]=255}l+=4}}a.putImageData(o,0,0),k.gestureFrameReady=!0}function bc(e,t){return k.gestureFrameCanvas||(k.gestureFrameCanvas=document.createElement(`canvas`),k.gestureFrameCanvas.id=`mediapipe-camera-frame`,k.gestureFrameCanvas.style.cssText=`display:none`,document.body.appendChild(k.gestureFrameCanvas)),(k.gestureFrameCanvas.width!==e||k.gestureFrameCanvas.height!==t)&&(k.gestureFrameCanvas.width=e,k.gestureFrameCanvas.height=t),k.gestureFrameCanvas}function xc(e,t,n){let r=Math.max(1,t*n);return e>=r*4?4:e>=r*3?3:1}function Sc(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):(e instanceof ArrayBuffer,new Uint8Array(e))}var Cc=`
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = vec4(position.xy, 0.0, 1.0);
}`,wc=`jarvis_vr_state_v2`,Tc={default:{id:`default`,label:`Default`,eyeSep:.063,convergence:1.42,k1:-.22,k2:.08,chromaticAberration:.003,renderScale:.9,refreshRate:72,vignetteStrength:.12},quest:{id:`quest`,label:`Quest`,eyeSep:.064,convergence:1.38,k1:-.215,k2:.078,chromaticAberration:.0032,renderScale:.88,refreshRate:90,vignetteStrength:.1},visionos:{id:`visionos`,label:`VisionOS`,estimatedEyeSep:!0,eyeSep:.062,convergence:1.34,k1:-.205,k2:.074,chromaticAberration:.0024,renderScale:.92,refreshRate:90,vignetteStrength:.08},android:{id:`android`,label:`Android`,eyeSep:.063,convergence:1.44,k1:-.22,k2:.08,chromaticAberration:.003,renderScale:.82,refreshRate:72,vignetteStrength:.14},desktop:{id:`desktop`,label:`Desktop`,eyeSep:.065,convergence:1.5,k1:-.2,k2:.07,chromaticAberration:.0025,renderScale:.95,refreshRate:60,vignetteStrength:.18}},Ec=`
uniform sampler2D tDiffuse;
uniform float k1;
uniform float k2;
uniform float rAber;
varying vec2 vUv;

vec2 barrelDistort(vec2 uv, vec2 center) {
  vec2 d = uv - center;
  float r2 = dot(d, d);
  float distortFactor = 1.0 + k1 * r2 + k2 * r2 * r2;
  return center + d * distortFactor;
}

void main() {
  bool isLeftEye = vUv.x < 0.5;
  vec2 eyeCenter = isLeftEye ? vec2(0.25, 0.5) : vec2(0.75, 0.5);
  vec2 distorted = barrelDistort(vUv, eyeCenter);
  vec2 localUV = isLeftEye
    ? vec2(distorted.x * 2.0, distorted.y)
    : vec2((distorted.x - 0.5) * 2.0, distorted.y);

  if (localUV.x < 0.0 || localUV.x > 1.0 || localUV.y < 0.0 || localUV.y > 1.0) {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
    return;
  }

  float dist = length(localUV - vec2(0.5, 0.5));
  float aberration = rAber * dist * dist * 3.0;
  vec2 redUV = barrelDistort(vUv + vec2(aberration, 0.0), eyeCenter);
  vec2 greenUV = distorted;
  vec2 blueUV = barrelDistort(vUv - vec2(aberration, 0.0), eyeCenter);
  float r = texture2D(tDiffuse, redUV).r;
  float g = texture2D(tDiffuse, greenUV).g;
  float b = texture2D(tDiffuse, blueUV).b;
  gl_FragColor = vec4(r, g, b, 1.0);
}`,J=null,Y=null,Dc=null,Oc=null,kc=null,Ac=new m(2,2);function jc(e){Dc||(Dc=new Ie,Oc=new le,kc=new De({uniforms:{tDiffuse:{value:null},k1:{value:e.k1??-.22},k2:{value:e.k2??.08},rAber:{value:e.chromaticAberration??.003}},vertexShader:Cc,fragmentShader:Ec,depthWrite:!1,depthTest:!1}),Dc.add(new h(Ac,kc)))}var Mc=null,Nc=null,Pc=null,Fc=!1,Ic=null,Lc=null,Rc=null,zc=null,Bc=0,Vc=new C,Hc=!1,Uc=null,Wc=null,X=il(),Gc=0,Kc=X.ipd,qc=X.convergence,Jc=new ee,Yc=new C,Xc=new C().setFromAxisAngle(new w(1,0,0),-Math.PI/2),Zc=new C,Qc=new w(0,0,1);function $c(){A(`enter-vr`,()=>el())}async function el(){let{renderer:e,scene:t,camera:n}=R();if(!e||!t||!n)return T(`Renderer is not ready yet. Start AR first, then enter VR.`,`VR Mode`),!1;X=il(),Kc=X.ipd,qc=X.convergence;let r=Ht(),i=rl(X.lensProfileId||r.browser);k.isVRMode=!0,Hc=!1,Gc=performance.now(),k.runtime.permissionState=k.runtime.permissionState||`unknown`,I(`passthroughBlendProxy`,!!vl()),I(`comfortAdaptation`,!0),I(`predictivePoseFiltering`,!0),I(`reprojectionProxy`,!0),I(`questBrowserQuirks`,r.questBrowserQuirks),I(`stereoEyeBuffers`,!0),I(`stereoFrustumCalibration`,!0),I(`refreshRateNegotiation`,!0),I(`timestampSync`,!0),I(`motionSicknessMitigation`,!0),I(`teleportLocomotion`,!0),I(`smoothLocomotionSafeguards`,!0),I(`roomBoundaryVisualization`,!0),I(`stereoUiAnchoring`,!0),I(`antiAliasEdgeProtection`,!0),I(`zFightGuard`,!0),I(`sustainedFramerateGuard`,!0),I(`orientationLockStability`,!0),I(`sensorPermissionPersistenceProxy`,!0),I(`motionComfortVignette`,!0),I(`renderScaleStability`,!0),I(`headsetCameraCalibrationProxy`,!0),I(`deviceCapabilityMatrix`,!0),I(`lowLightTrackingResilience`,r.limits.lowLightTrackingResilience!==!1),ul(e,i),i.estimatedEyeSep&&E(`VisionOS IPD is estimated because the browser does not expose a reliable eye distance API. Use the IPD slider to fine-tune comfort.`,`VR Mode`),kt({renderer:e,scene:t,camera:n},{mode:`vr-shell`,stereo:!0,source:vl(),passthroughBlend:`browser-camera`,framebufferScaleFactor:i.renderScale,refreshRate:i.refreshRate,convergence:i.convergence,renderScale:i.renderScale,lensProfile:i.id,motionComfort:X.seatedMode?`seated`:`standing`,vignetteStrength:i.vignetteStrength}),sl(i),ll(i),await fl(n),await pl();try{await screen.orientation?.lock?.(`landscape`)}catch{E(`Landscape lock was not allowed by this browser. Rotate the phone manually for VR.`)}let a=vl();return a&&!Nc?(Nc=hl(a),t.add(Nc)):a||E(`VR passthrough is waiting for camera pixels. Stay in AR mode until the camera frame source is ready.`,`VR Mode`),gl(),!Fc&&globalThis.XR8?.addCameraPipelineModule?(globalThis.XR8.addCameraPipelineModule({name:`vr-stereo-renderer`,onRender:()=>{k.isVRMode&&dl()}}),k.pipelineOrder.push(`vr-stereo-renderer`),Fc=!0):globalThis.XR8?.addCameraPipelineModule||yl(),E(`VR screen active. ${i.label} stereo profile, IPD, refresh, and gyro are enabled.`,`VR Mode`),!0}function tl(){k.isVRMode=!1,Hc=!1,al(),_l();try{screen.orientation?.unlock?.()}catch{}E(`Returned to AR mode.`,`VR Mode`)}function nl(e,t,n){return Math.min(n,Math.max(t,Number(e)||t))}function rl(e=``){let t=String(e||``).toLowerCase();return t.includes(`quest`)?Tc.quest:t.includes(`vision`)?Tc.visionos:t.includes(`android`)?Tc.android:t.includes(`desktop`)?Tc.desktop:Tc.default}function il(){let e={ipd:.063,convergence:1.42,renderScale:.9,refreshRate:72,seatedMode:!0,floorCalibration:0,lensProfileId:`default`,vignette:.12};try{let t=ar(wc,null);return!t||typeof t!=`object`?e:{...e,...t,ipd:nl(t.ipd,.045,.075),convergence:nl(t.convergence,.8,2.2),renderScale:nl(t.renderScale,.72,1.25),refreshRate:nl(t.refreshRate,60,120),floorCalibration:nl(t.floorCalibration,-1.5,1.5),vignette:nl(t.vignette,0,.4),seatedMode:t.seatedMode!==!1,lensProfileId:String(t.lensProfileId||`default`)}}catch{return e}}function al(){try{or(wc,{ipd:parseFloat(sr(`jarvis_vr_ipd`,String(X.ipd||.063))),convergence:parseFloat(sr(`jarvis_vr_convergence`,String(X.convergence||1.42))),renderScale:X.renderScale,refreshRate:X.refreshRate,seatedMode:X.seatedMode,floorCalibration:X.floorCalibration,lensProfileId:X.lensProfileId,vignette:X.vignette,savedAt:new Date().toISOString()})}catch{}}function ol(){return document.getElementById(`ui-layer`)||document.body}function sl(e){Uc?.remove(),Uc=document.createElement(`div`),Uc.style.cssText=[`position:absolute`,`inset:0`,`z-index:25`,`pointer-events:none`,`background:radial-gradient(circle at center, rgba(0,0,0,0) 0%, rgba(0,0,0,0.14) 58%, rgba(0,0,0,0.32) 100%)`,`opacity:${nl(e.vignetteStrength??.12,0,.5)}`,`transition:opacity 180ms linear`].join(`;`),ol().appendChild(Uc)}function cl(e,t){if(!Uc)return;let n=X.seatedMode?.06:.1,r=Math.min(.24,Math.max(0,(e-16.6)/120)),i=nl((t.vignetteStrength??.12)+n+r,.06,.45);Uc.style.opacity=String(i)}function ll(e){Wc?.remove(),Wc=document.createElement(`div`),Wc.style.cssText=[`position:absolute`,`right:16px`,`top:18px`,`z-index:30`,`display:flex`,`flex-direction:column`,`gap:8px`,`padding:10px`,`border-radius:12px`,`background:rgba(3,12,20,0.72)`,`border:1px solid rgba(0,212,255,0.22)`,`backdrop-filter:blur(14px)`,`color:white`,`font:600 11px/1.2 Inter,sans-serif`,`pointer-events:auto`,`min-width:220px`].join(`;`);let t=(e,t)=>{let n=document.createElement(`label`);n.style.cssText=`display:flex;justify-content:space-between;align-items:center;gap:8px`;let r=document.createElement(`span`);return r.textContent=e,n.append(r,t),n},n=document.createElement(`input`);n.type=`range`,n.min=`0.045`,n.max=`0.075`,n.step=`0.001`,n.value=String(Kc??e.eyeSep??.063),n.style.cssText=`width:112px`;let r=document.createElement(`input`);r.type=`range`,r.min=`0.8`,r.max=`2.2`,r.step=`0.01`,r.value=String(qc??e.convergence??1.42),r.style.cssText=`width:112px`;let i=document.createElement(`input`);i.type=`range`,i.min=`0.72`,i.max=`1.25`,i.step=`0.01`,i.value=String(X.renderScale??e.renderScale??.9),i.style.cssText=`width:112px`;let a=document.createElement(`select`);for(let t of[60,72,90,120]){let n=document.createElement(`option`);n.value=String(t),n.textContent=`${t}Hz`,Number(t)===Number(X.refreshRate||e.refreshRate)&&(n.selected=!0),a.appendChild(n)}let o=document.createElement(`button`);o.className=`btn-secondary`,o.textContent=X.seatedMode?`SEATED`:`STANDING`,o.onclick=()=>{X.seatedMode=!X.seatedMode,o.textContent=X.seatedMode?`SEATED`:`STANDING`,k.compositor.motionComfort=X.seatedMode?`seated`:`standing`,al()};let s=document.createElement(`button`);s.className=`btn-secondary`,s.textContent=`FLOOR -`,s.onclick=()=>{X.floorCalibration=nl(X.floorCalibration-.05,-1.5,1.5),k.compositor.floorCalibration=X.floorCalibration,al(),E(`Floor calibration ${X.floorCalibration.toFixed(2)}m`,`VR Mode`)};let c=document.createElement(`button`);c.className=`btn-secondary`,c.textContent=`FLOOR +`,c.onclick=()=>{X.floorCalibration=nl(X.floorCalibration+.05,-1.5,1.5),k.compositor.floorCalibration=X.floorCalibration,al(),E(`Floor calibration ${X.floorCalibration.toFixed(2)}m`,`VR Mode`)};let l=document.createElement(`span`);l.textContent=`${e.label} profile`,l.style.opacity=`0.82`,n.oninput=()=>{cr(`jarvis_vr_ipd`,n.value),X.ipd=parseFloat(n.value),Kc=X.ipd,k.compositor.eyeSep=Kc},r.oninput=()=>{cr(`jarvis_vr_convergence`,r.value),X.convergence=parseFloat(r.value),qc=X.convergence,k.compositor.convergence=qc},i.oninput=()=>{X.renderScale=parseFloat(i.value),k.compositor.renderScale=X.renderScale,al()},a.onchange=()=>{X.refreshRate=parseFloat(a.value),k.compositor.refreshRate=X.refreshRate,k.compositor.frameBudgetMs=1e3/X.refreshRate,al()},Wc.append(l,t(`IPD`,n),t(`Convergence`,r),t(`Scale`,i),t(`Refresh`,a));let u=document.createElement(`div`);u.style.cssText=`display:flex;gap:6px;justify-content:space-between`,u.append(o,s,c),Wc.appendChild(u),ol().appendChild(Wc)}function ul(e,t=rl()){let n=new Re;e.getDrawingBufferSize(n);let r=nl(X.renderScale??t.renderScale??1,.72,1.25),i=Math.max(2,Math.floor(n.x*r)),a=Math.max(2,Math.floor(n.y*r)),o=Math.max(2,Math.floor(i/2))/Math.max(1,a);J=J||new Fe,J.eyeSep=Kc||t.eyeSep||.063,J.focus=qc||t.convergence||1.4,(!Y||Y.width!==i||Y.height!==a)&&(Y?.dispose(),Y=new je(i,a,{minFilter:g,magFilter:g})),jc(t),kc&&(kc.uniforms.k1.value=t.k1??-.22,kc.uniforms.k2.value=t.k2??.08,kc.uniforms.rAber.value=t.chromaticAberration??.003),k.compositor={...k.compositor,refreshRate:t.refreshRate,frameBudgetMs:1e3/t.refreshRate,renderScale:r,convergence:J.focus,lensProfile:t.id,eyeAspect:o,vignetteStrength:t.vignetteStrength,motionComfort:X.seatedMode?`seated`:`standing`,floorCalibration:X.floorCalibration},!Rc&&e?.domElement&&(Rc=e=>{e.preventDefault?.(),E(`WebGL context was lost. VR will pause until the renderer restores.`,`VR Mode`),k.isVRMode=!1,Bc&&dt(Bc),Bc=0,J=null,Y=null,Dc=null,Oc=null,kc=null},zc=()=>{E(`WebGL context restored. Returning to VR mode.`,`VR Mode`),k.started&&(k.isVRMode=!0,ul(e,t),yl())},e.domElement.addEventListener(`webglcontextlost`,Rc,{passive:!1}),e.domElement.addEventListener(`webglcontextrestored`,zc))}function dl(){let{renderer:e,scene:t,camera:n}=R();if(!e||!t||!n||!Y||!J)return;let r=new Re;e.getDrawingBufferSize(r);let i=rl(X.lensProfileId),a=nl(X.renderScale??i.renderScale??1,.72,1.25),o=Math.max(2,Math.floor(r.x*a)),s=Math.max(2,Math.floor(r.y*a)),c=Math.max(2,Math.floor(o/2)),l=c/Math.max(1,s);(Y.width!==o||Y.height!==s)&&ul(e,i);let u=n.aspect;n.aspect=l,n.updateProjectionMatrix(),J.eyeSep=Kc||i.eyeSep||.063,J.focus=qc||i.convergence||1.4,J.update(n),e.setRenderTarget(Y),e.setScissorTest(!0),e.clear(!0,!0,!0),Pc?.userData?.liveCanvas&&(Pc.needsUpdate=!0),e.setViewport(0,0,c,s),e.setScissor(0,0,c,s),e.render(t,J.cameraL),e.clearDepth(),e.setViewport(c,0,c,s),e.setScissor(c,0,c,s),e.render(t,J.cameraR),e.setScissorTest(!1),e.setRenderTarget(null),e.setViewport(0,0,r.x,r.y),kc.uniforms.tDiffuse.value=Y.texture,e.render(Dc,Oc),n.aspect=u,n.updateProjectionMatrix();let d=performance.now(),f=Gc?d-Gc:16.6;Gc=d,At(f),cl(f,i)}async function fl(e){Ht();try{if(typeof DeviceOrientationEvent<`u`&&typeof DeviceOrientationEvent.requestPermission==`function`){let e=await DeviceOrientationEvent.requestPermission();if(e!==`granted`)return cr(`jarvis_vr_motion_permission`,String(e||`denied`)),E(`Motion access denied or timed out. VR head tracking disabled.`),!1;cr(`jarvis_vr_motion_permission`,`granted`)}return Ic&&window.removeEventListener(`deviceorientation`,Ic),Ic=t=>ml(t,e),window.addEventListener(`deviceorientation`,Ic),!0}catch(e){return T(e.message,`Motion Permission Failed`),!1}}async function pl(){try{if(document.fullscreenElement)return!0;if(!document.documentElement?.requestFullscreen)return!1;let e=document.documentElement.requestFullscreen({navigationUI:`hide`}).catch(()=>!1);return await Promise.race([e,new Promise(e=>setTimeout(()=>e(!1),Ht().isQuest?1e3:1500))]),Lc||(Lc=()=>{!document.fullscreenElement&&k.isVRMode&&E(`Fullscreen exited. VR view will remain in-browser.`,`VR Mode`)},document.addEventListener(`fullscreenchange`,Lc),document.addEventListener(`webkitfullscreenchange`,Lc)),I(`orientationLockStability`,!0),!0}catch{return E(`Fullscreen lock was not granted. VR continues in browser windowed mode.`,`VR Mode`),!1}}function ml(e,t){if(!k.isVRMode||!t)return;let n=l.degToRad(e.alpha||0),r=l.degToRad(e.beta||0),i=l.degToRad(e.gamma||0),a=Number(screen.orientation?.angle||window.orientation||0);Jc.set(r,n,-i,`YXZ`),Yc.setFromEuler(Jc),Yc.multiply(Xc),Zc.setFromAxisAngle(Qc,-l.degToRad(a)),Yc.multiply(Zc),Hc?Vc.slerp(Yc,.18):(Vc.copy(Yc),Hc=!0),t.quaternion.copy(Vc)}function hl(e){let t=e.tagName===`VIDEO`,n=t?new he(e):new Ve(e);n.minFilter=g,n.magFilter=g,n.userData.liveCanvas=!t,Pc=n;let r=new be(500,60,40);return r.scale(-1,1,1),new h(r,new b({map:n}))}function gl(){Mc?.remove(),Mc=document.createElement(`button`),Mc.textContent=`EXIT VR`,Mc.className=`btn-primary`,Mc.style.cssText=`position:absolute;top:20px;left:20px;z-index:30;background:var(--destructive);padding-top:calc(12px + env(safe-area-inset-top));pointer-events:auto`,Mc.onclick=tl(document.getElementById(`ui-layer`)||document.body).appendChild(Mc);let e=document.createElement(`input`);e.type=`range`,e.min=`0.045`,e.max=`0.075`,e.step=`0.001`,e.value=String(Kc||.063),e.style.cssText=`width:168px;pointer-events:auto`;let t=document.createElement(`label`);t.dataset.vrControl=`ipd`,t.style.cssText=`position:absolute;right:18px;bottom:20px;z-index:30;display:flex;flex-direction:column;gap:6px;color:white;font:600 12px/1.2 Inter,sans-serif;text-shadow:0 1px 4px #000;pointer-events:auto`;let n=document.createElement(`span`);n.textContent=`${Math.round(parseFloat(e.value)*1e3)} mm IPD`,e.oninput=()=>{cr(`jarvis_vr_ipd`,e.value),Kc=parseFloat(e.value),n.textContent=`${Math.round(parseFloat(e.value)*1e3)} mm IPD`},t.append(n,e)(document.getElementById(`ui-layer`)||document.body).appendChild(t),Mc.addEventListener(`click`,()=>t.remove(),{once:!0})}function _l(){try{let e=k.xrSession;if(e?.end){let t=e.end();t?.catch&&t.catch(()=>{})}}catch{}Mc?.remove(),document.querySelector(`[data-vr-control="ipd"]`)?.remove(),Wc?.remove(),Uc?.remove(),Wc=null,Uc=null,Ic&&(window.removeEventListener(`deviceorientation`,Ic),Ic=null),Lc&&(document.removeEventListener(`fullscreenchange`,Lc),document.removeEventListener(`webkitfullscreenchange`,Lc),Lc=null),Rc&&(R()?.renderer?.domElement?.removeEventListener?.(`webglcontextlost`,Rc),Rc=null),zc&&(R()?.renderer?.domElement?.removeEventListener?.(`webglcontextrestored`,zc),zc=null),Bc&&(dt(Bc),Bc=0),Y&&(Y.dispose(),Y=null),Pc?.dispose&&Pc.dispose(),Pc=null,Nc?.geometry?.dispose?.(),Nc?.material?.dispose?.(),Nc?.remove?.(),Nc=null,kc?.dispose?.(),kc=null,Dc=null,Oc=null,J=null}function vl(){if(k.cameraVideo?.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA)return k.cameraVideo;if(k.gestureFrameReady&&k.gestureFrameCanvas?.width&&k.gestureFrameCanvas?.height)return k.gestureFrameCanvas;let e=document.getElementById(`camerafeed`);return e?.width&&e?.height?e:null}function yl(){if(Bc)return;let e=()=>{if(!k.isVRMode){Bc=0;return}dl(),Bc=F(e)};Bc=F(e)}var bl=null,xl=null,Sl=null,Cl=null,wl=new Float32Array(1e3*3),Tl=new He;Tl.setAttribute(`position`,new ze(wl,3)),Tl.setDrawRange(0,0);var El=1e3;function Dl(){return{name:`world-points-collector`,onUpdate:({processCpuResult:e})=>{let t=e?.worldPoints||e?.reality?.worldPoints||e?.reality?.points||e?.slam?.worldPoints;t&&t.length>0&&(k.worldPoints=t,Ol(t))}}}function Ol(e){if(!(!e||e.length<10)){for(let t of e){let e=t.position||t;!Number.isFinite(e.x)||!Number.isFinite(e.y)||!Number.isFinite(e.z)||k.worldPointBuffer.push(new w(e.x,e.y,e.z))}k.worldPointBuffer.length>1e3&&k.worldPointBuffer.splice(0,k.worldPointBuffer.length-1e3),k.frameCount+=1,k.frameCount%20==0&&(kl(k.worldPointBuffer),Al(k.worldPointBuffer))}}function kl(e){if(!e.length)return;let{scene:t}=R(),n=Math.min(e.length,El);for(let t=0;t<n;t+=1){let r=e[e.length-n+t];wl[t*3]=r.x,wl[t*3+1]=r.y,wl[t*3+2]=r.z}Tl.attributes.position.needsUpdate=!0,Tl.setDrawRange(0,n),bl||(Cl=new ae({color:51455,size:.018,transparent:!0,opacity:.55,depthWrite:!1}),bl=new p(Tl,Cl),bl.name=`jarvis-room-point-cloud`,bl.scale.setScalar(1),t.add(bl))}function Al(e){if(!e.length)return;let t=[...e].sort((e,t)=>e.y-t.y),n=[],r=[];for(let e=0;e<t.length;e++){let i=t[e];if(r.length===0)r.push(i);else{let e=r[r.length-1];i.y-e.y<=.04?r.push(i):(n.push(r),r=[i])}}r.length>0&&n.push(r);let i=Math.max(8,Math.floor(t.length*.08)),a=null;for(let e of n)if(e.length>=i){a=e;break}let o;if(a)o=a.reduce((e,t)=>e+t.y,0)/a.length;else{let e=Math.max(4,Math.floor(t.length*.15)),n=t.slice(0,e);o=n.reduce((e,t)=>e+t.y,0)/n.length}if(!Number.isFinite(o))return;k.floorY!==void 0&&Number.isFinite(k.floorY)?k.floorY=k.floorY*.88+o*.12:k.floorY=o;let s=k.floorY,{scene:c}=R();if(!xl){let e=new m(10,10,20,20);xl=new h(e,new b({color:51455,transparent:!0,opacity:.06,side:2,depthWrite:!1})),Sl=new h(e,new b({color:51455,transparent:!0,opacity:.2,wireframe:!0,depthWrite:!1})),xl.name=`jarvis-detected-floor`,Sl.name=`jarvis-detected-floor-wire`,xl.rotation.x=-Math.PI/2,Sl.rotation.x=-Math.PI/2,c.add(xl,Sl)}xl.position.y=s,Sl.position.y=s,k.shadowReceiver&&(k.shadowReceiver.position.y=s+.002),D(`status-tracking`,k.trackingMode===`8thwall-slam`?`slam+floor`:`basic floor`),j(`world-anchor-sample`,{floorY:s,pointCount:e.length})}function jl(){k.worldPointBuffer.length<10&&Ml(),kl(k.worldPointBuffer),Al(k.worldPointBuffer)}function Ml(){let e=[],{camera:t}=R(),n=new y,r=Number.isFinite(k.floorY)?k.floorY:t&&t.position&&Number.isFinite(t.position.y)?t.position.y-1.45:-1.2;for(let i=0;i<9;i+=1)for(let a=0;a<20;a+=1){let o=.08+.84/19*a,s=.38+.46/8*i;n.setFromCamera(new Re(o*2-1,-(s*2-1)),t);let c=(r-n.ray.origin.y)/n.ray.direction.y;Number.isFinite(c)&&c>.2&&c<8&&e.push(n.ray.origin.clone().add(n.ray.direction.clone().multiplyScalar(c)))}k.worldPointBuffer.push(...e),k.worldPointBuffer.length>1e3&&k.worldPointBuffer.splice(0,k.worldPointBuffer.length-1e3)}var Nl={forest:[`Fox`,`Lantern`,`BarramundiFish`],lab:[`DamagedHelmet`,`AntiqueCamera`,`ReciprocatingSaw`],room:[`GlamVelvetSofa`,`WaterBottle`,`IridescenceLamp`],street:[`CesiumMilkTruck`,`ToyCar`,`Lantern`],default:[`Duck`,`Avocado`,`WaterBottle`]};function Pl(){A(`scan-room`,()=>{jl(),E(`Room mesh scan updated from 8th Wall world points or basic fallback points.`,`Room Scan`)}),Ll()}async function Fl(e=`room`){let t=String(e||`room`).toLowerCase(),n=Nl[t]||Nl.default;jl();let r=Math.min(3,Math.max(1,n.length));E(`Reconstructing ${t} scene with ${r} parallel model loads.`,`Scene Reconstruction`);try{await Il(t)}catch(e){T(e.message,`HDR Environment Failed`)}let i=(await Rl(n.map((e,t)=>async()=>{let r=t/n.length*Math.PI*2;return zl(fo(e,new w(Math.sin(r)*.75,k.floorY+.04,-1.5-Math.cos(r)*.45),new C),12e3,`Timed out loading ${e}`)}),r)).filter(e=>e.status===`rejected`);i.length&&T(`${i.length} reconstruction model(s) fell back or failed.`,`Scene Reconstruction`),E(`Reconstructed ${t} scene with ${n.length} placed objects.`,`Scene Reconstruction`)}async function Il(e){let{scene:t,renderer:n}=R(),r=await Ln(e);return new Promise((e,i)=>{new se().load(r,r=>{let a=new re(n),o=a.fromEquirectangular(r),s=t.userData.jarvisEnvironmentTarget,c=t.environment;if(!o?.texture){r.dispose(),a.dispose(),i(Error(`HDR environment generation failed.`));return}t.environment=o.texture,t.userData.jarvisEnvironmentTarget=o,t.userData.jarvisEnvironmentSource=`hdr`,c?.dispose?.(),s?.dispose?.(),r.dispose(),a.dispose(),e(t.environment)},void 0,i)})}function Ll(){let e=new WeakSet;new MutationObserver(()=>{document.querySelectorAll(`video`).forEach(t=>{e.has(t)||(e.add(t),t.addEventListener(`play`,()=>{E(`A playing video was detected. Say "JARVIS reconstruct this scene" to build an AR scene.`,`Scene Detection`)},{once:!0}))})}).observe(document.documentElement,{childList:!0,subtree:!0})}async function Rl(e,t){let n=[],r=new Set;for(let i of e){let e=i().then(e=>({status:`fulfilled`,value:e})).catch(e=>({status:`rejected`,reason:e}));n.push(e),r.add(e),e.finally(()=>r.delete(e)),r.size>=t&&await Promise.race(r)}return Promise.all(n)}function zl(e,t,n){let r=0,i=new Promise((e,i)=>{r=window.setTimeout(()=>i(Error(n)),t)});return Promise.race([e,i]).finally(()=>window.clearTimeout(r))}var Bl=.35,Vl=.65,Hl=.18,Ul=8,Wl=4,Gl=12,Kl=60,Z={confidence:0,qualityTier:`initializing`,lostFrames:0,goodFrames:0,isLost:!1,worldOriginLocked:!1,worldOriginSamples:0,worldOriginPosition:new w,worldOriginQuaternion:new C,lastGoodPose:{position:new w,quaternion:new C,timestamp:0},smoothedPosition:new w,smoothedQuaternion:new C,anchorRegistry:new Map,planeRegistry:new Map,relocalizationAttempts:0,totalFrames:0};k.tracking=Z;function ql(){return{name:`jarvis-tracking-quality`,onUpdate:({processCpuResult:e,processGpuResult:t})=>{Z.totalFrames++;let n=e?.reality||t?.reality||e||t,r=Jl(n),i=Yl(n);i&&(Z.confidence=Z.confidence*.85+r*.15,Z.qualityTier=Xl(Z.confidence),k.trackingQuality=Z.qualityTier,document.body.dataset.jarvisTrackingQuality=Z.qualityTier,Z.confidence<Bl?(Z.lostFrames++,Z.goodFrames=0,!Z.isLost&&Z.lostFrames>=Ul&&nu()):(Z.goodFrames++,Z.lostFrames=0,Z.isLost&&Z.goodFrames>=Wl&&ru(i)),!Z.isLost&&($l(i),Z.worldOriginLocked||tu(Z.smoothedPosition,Z.smoothedQuaternion),ou(),Z.confidence>=Vl&&(Z.lastGoodPose.position.copy(Z.smoothedPosition),Z.lastGoodPose.quaternion.copy(Z.smoothedQuaternion),Z.lastGoodPose.timestamp=performance.now()),k.sessionAnchor.originPosition=Z.worldOriginPosition.toArray(),k.sessionAnchor.originQuaternion=Z.worldOriginQuaternion.toArray()))}}}function Jl(e){if(!e)return 0;let t=e.trackingStatus||e.slam?.trackingStatus;if(t){if(t===`NORMAL`)return .9;if(t===`LIMITED`)return .45;if(t===`INITIALIZING`)return .25}let n=e.confidence??e.slam?.confidence??e.poseConfidence;if(typeof n==`number`&&Number.isFinite(n))return Math.max(0,Math.min(1,n));let r=e.worldPoints||e.points;if(r&&Array.isArray(r)){let e=r.length;return e>80?.85:e>40?.65:e>15?.45:e>5?.25:.1}return .5}function Yl(e){if(!e)return null;let t=e.cameraPose||e.pose||e.slam?.cameraPose;if(!t)return null;let n=t.position||t,r=t.orientation||t.rotation;return Number.isFinite(n?.x)?{position:n,orientation:r}:null}function Xl(e){return e>=.8?`excellent`:e>=.6?`good`:e>=.38?`fair`:e>=.15?`poor`:`initializing`}var Zl=new w,Ql=new C;function $l(e){let{position:t,orientation:n}=e;Zl.set(Math.fround(t.x??0),Math.fround(t.y??0),Math.fround(t.z??0)),n&&Ql.set(n.x??0,n.y??0,n.z??0,n.w??1);let r=Hl*(1+(1-Z.confidence)*1.5),i=Math.min(r,.45);Z.smoothedPosition.lerp(Zl,i),Z.smoothedPosition.set(Math.fround(Z.smoothedPosition.x),Math.fround(Z.smoothedPosition.y),Math.fround(Z.smoothedPosition.z)),n&&(Z.smoothedQuaternion.slerp(Ql,i),Z.smoothedQuaternion.normalize())}var eu=[];function tu(e,t){if(Z.confidence<Vl){eu=[],Z.worldOriginSamples=0;return}eu.push({pos:e.clone(),quat:t.clone()}),eu.length>Gl&&eu.shift(),Z.worldOriginSamples=eu.length;let n=new w,r=new C;if(eu.forEach((e,t)=>{let i=1/(t+1);n.lerp(e.pos,i),r.slerp(e.quat,i)}),Z.worldOriginPosition.copy(n),Z.worldOriginQuaternion.copy(r),eu.length===Gl){let e=0;eu.forEach(t=>{e+=t.pos.distanceToSquared(n)}),e/Gl<.001&&(Z.worldOriginLocked=!0,k.sessionAnchor.restoredAt=Date.now(),j(`world-origin-locked`,{position:Z.worldOriginPosition.toArray(),quaternion:Z.worldOriginQuaternion.toArray()}),D(`status-tracking`,`${k.trackingMode} origin locked`))}}function nu(){Z.isLost=!0,Z.worldOriginLocked=!1,Z.worldOriginSamples=0,eu=[],Z.relocalizationAttempts=0,document.body.dataset.jarvisTrackingState=`lost`,E(`Tracking lost — move camera slowly to reacquire environment.`,`Tracking`),D(`status-tracking`,`lost`),j(`tracking-lost`,{lastGoodPose:{position:Z.lastGoodPose.position.toArray(),age:performance.now()-Z.lastGoodPose.timestamp}}),Z.anchorRegistry.forEach(e=>{e.object&&(e.object.userData.trackingFrozen=!0)})}function ru(e){Z.isLost=!1,Z.lostFrames=0,Z.relocalizationAttempts++,document.body.dataset.jarvisTrackingState=`recovered`,D(`status-tracking`,k.trackingMode),j(`tracking-recovered`,{attempt:Z.relocalizationAttempts,confidence:Z.confidence}),Z.anchorRegistry.forEach(e=>{e.object&&(e.object.userData.trackingFrozen=!1)}),E(`Tracking recovered.`,`Tracking`)}function iu(e,t,n){let r={id:e,object:t,targetPosition:n.clone(),history:[],confidence:Z.confidence,createdAt:performance.now()};return Z.anchorRegistry.set(e,r),j(`anchor-registered`,{id:e,position:n.toArray()}),r}function au(e){Z.anchorRegistry.delete(e),j(`anchor-removed`,{id:e})}function ou(){Z.anchorRegistry.forEach(e=>{if(!e.object||e.object.userData.trackingFrozen)return;let t=e.object,n=e.targetPosition,r=new w;t.getWorldPosition(r),r.set(Math.fround(r.x),Math.fround(r.y),Math.fround(r.z)),n.set(Math.fround(n.x),Math.fround(n.y),Math.fround(n.z));let i=r.distanceTo(n);if(e.history.push({drift:i,t:performance.now()}),e.history.length>Kl&&e.history.shift(),i>.001){let r=Math.max(.015,Math.min(.35,i*1.5));t.position.lerp(n,r),e.confidence=Z.confidence}})}function su(e){if(!e||e.length<20)return;let t=e.map(e=>{let t=e.position||e;return new w(t.x,t.y,t.z)}).filter(e=>Number.isFinite(e.x+e.y+e.z));if(t.length<20)return;let n=Math.min(...t.map(e=>e.y)),r=Math.max(...t.map(e=>e.y))-n;if(r<.1)return;let i=Array.from({length:10},()=>[]);t.forEach(e=>{i[Math.min(9,Math.floor((e.y-n)/r*10))].push(e)});let a=[];return i.forEach((e,t)=>{if(e.length<8)return;let i=n+t/10*r+r/10/2,o=e.reduce((e,t)=>e.add(t),new w).divideScalar(e.length),s=i<n+r*.25,c=i>n+r*.75,l=s?`floor`:c?`ceiling`:`surface`;a.push({yCenter:i,centroid:o,pointCount:e.length,type:l,confidence:Math.min(1,e.length/30)})}),a.forEach((e,t)=>{let n=`plane-${t}-${e.type}`;Z.planeRegistry.set(n,e)}),k.detectedPlanes=a,a.length>0&&j(`planes-updated`,{planes:a,count:a.length}),a}function cu(e,t){if(Z.confidence<Bl)return null;let{renderer:n}=R()||{};if(n?.xr?.enabled&&k.xrHitTestSource){let e=n.xr.getFrame();if(e){let t=n.xr.getReferenceSpace(),r=e.getHitTestResults(k.xrHitTestSource);if(r.length>0){let e=r[0].getPose(t);if(e){let t=new f().fromArray(e.transform.matrix);return{point:new w().setFromMatrixPosition(t),normal:new w(0,1,0).applyMatrix4(t).normalize(),confidence:Z.confidence,type:`webxr-hit-test`}}}}}if(globalThis.XR8?.XrController){let t=globalThis.XR8.XrController.hitTest(e.x,e.y,[`FEATURE_POINT`,`ESTIMATED_SURFACE`,`DETECTED_SURFACE`]);if(t&&t.length>0){let e=t[0];return{point:new w(e.position.x,e.position.y,e.position.z),normal:new w(0,1,0),confidence:Z.confidence*(e.type===`DETECTED_SURFACE`?.9:.5),type:e.type}}}let r=new y;if(r.setFromCamera(new Re(e.x*2-1,-(e.y*2-1)),t),Number.isFinite(k.floorY)){let e=new w(0,1,0),t=new u(e,-k.floorY),n=new w;if(r.ray.intersectPlane(t,n)){let t=n.distanceTo(r.ray.origin);if(t>.2&&t<10)return{point:n,normal:e,confidence:Z.confidence,type:`floor`,distance:t}}}let i=k.detectedPlanes||[];for(let e of i){if(e.type===`floor`)continue;let t=new w(0,1,0),n=new u(t,-e.yCenter),i=new w;if(r.ray.intersectPlane(n,i)){let n=i.distanceTo(r.ray.origin);if(n>.2&&n<10)return{point:i,normal:t,confidence:Z.confidence*e.confidence,type:e.type,distance:n}}}return null}function lu(){return{confidence:Z.confidence,tier:Z.qualityTier,isLost:Z.isLost,worldOriginLocked:Z.worldOriginLocked,anchorCount:Z.anchorRegistry.size,planeCount:Z.planeRegistry.size,relocalizationAttempts:Z.relocalizationAttempts,totalFrames:Z.totalFrames}}function uu(){Z.worldOriginLocked=!1,Z.worldOriginSamples=0,eu=[],Z.isLost=!1,Z.lostFrames=0,Z.goodFrames=0,E(`Relocalization requested — scanning environment.`,`Tracking`),j(`relocalization-requested`,{attempt:++Z.relocalizationAttempts})}function du(){Z.confidence=0,Z.qualityTier=`initializing`,Z.lostFrames=0,Z.goodFrames=0,Z.isLost=!1,Z.worldOriginLocked=!1,Z.worldOriginSamples=0,eu=[],Z.anchorRegistry.clear(),Z.planeRegistry.clear(),Z.relocalizationAttempts=0,Z.totalFrames=0,k.detectedPlanes=[],document.body.dataset.jarvisTrackingQuality=`initializing`,document.body.dataset.jarvisTrackingState=`init`}A(`world-anchor-sample`,({floorY:e,pointCount:t})=>{k.worldPointBuffer?.length>20&&su(k.worldPointBuffer)}),A(`runtime-phase`,({phase:e})=>{(e===`created`||e===`booting`)&&du()});var fu=null,pu=0;function mu(){return fu||(fu=mn(hu(`eternum`),`Eternum AR`,880,560),gu(fu,[[`NEXT`,`Enter`],[`AUTO`,`a`],[`SAVE`,`s`],[`MENU`,`Escape`]]),E(`Eternum opened as a floating AR panel. Normal game launch is unchanged outside AR.`,`Eternum AR`),fu)}function hu(e){let t=new URLSearchParams(location.search);return String(t.get(`${e}Url`)||t.get(`game${e[0].toUpperCase()}${e.slice(1)}Url`)||``).trim()||String(globalThis.FridayARConfig?.gameUrls?.[e]||``).trim()||`/api/ar_task?mode=game_launch&task=${encodeURIComponent(`open ${e} web mirror`)}`}function gu(e,t){let n=document.createElement(`div`);n.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;pointer-events:auto`,t.forEach(([t,r])=>{let i=document.createElement(`button`);i.textContent=t,i.style.cssText=`min-height:44px;min-width:70px;border:1px solid rgba(255,255,255,.25);border-radius:999px;background:rgba(0,0,0,.48);color:white;font-weight:700`,i.onclick=()=>_u(e.iframe,r),n.appendChild(i)}),e.container.style.position=`relative`,e.container.appendChild(n)}async function _u(e,t,n=!1,r=!1){let i=e?.contentWindow;if(!i)return T(`The game iframe is not ready yet.`,`Game Input Failed`),!1;try{let e={key:t,bubbles:!0,cancelable:!0,ctrlKey:n};return i.document.dispatchEvent(new KeyboardEvent(`keydown`,e)),r||window.setTimeout(()=>i.document.dispatchEvent(new KeyboardEvent(`keyup`,e)),50),!0}catch(e){let a=`key-${Date.now().toString(36)}-${++pu}`;return await new Promise(o=>{let s=window.setTimeout(()=>{window.removeEventListener(`message`,c),T(`The game iframe did not acknowledge the key relay before the timeout elapsed.`,`Game Input Timeout`),o(!1)},250),c=e=>{e.source===i&&(e.data?.type!==`keydown-ack`||e.data?.id!==a||(window.clearTimeout(s),window.removeEventListener(`message`,c),o(!0)))};window.addEventListener(`message`,c);try{i.postMessage({type:`keydown`,id:a,key:t,ctrl:n,hold:r},`*`)}catch(t){window.clearTimeout(s),window.removeEventListener(`message`,c),T(t.message||e.message,`Game Input Failed`),o(!1)}})}}var vu=null;function yu(){if(vu)return vu;let e=new URLSearchParams(location.search);vu=mn(String(e.get(`ripplesUrl`)||globalThis.FridayARConfig?.gameUrls?.ripples||``).trim()||`/api/ar_task?mode=game_launch&task=open%20ripples%20web%20mirror`,`Ripples AR`,880,560);let t=document.createElement(`div`);return t.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;pointer-events:auto`,[[`NEXT`,`Enter`],[`AUTO`,`a`],[`SAVE`,`s`],[`MENU`,`Escape`]].forEach(([e,n])=>{let r=document.createElement(`button`);r.textContent=e,r.style.cssText=`min-height:44px;min-width:70px;border:1px solid rgba(255,255,255,.25);border-radius:999px;background:rgba(0,0,0,.48);color:white;font-weight:700`,r.onclick=()=>_u(vu.iframe,n),t.appendChild(r)}),vu.container.style.position=`relative`,vu.container.appendChild(t),E(`Ripples opened as a floating AR panel.`,`Ripples AR`),vu}async function bu(e,t){let n=await xu(e,t),r=mn(Cu(n.url||e),`${n.title||e} AR`,880,560);return Du(n.controls,r),r}async function xu(e,t){if(t?.query)try{let n=await t.query(`Game "${e}" genre + controls as JSON only: {"title":"","url":"","genre":"","controls":[{"action":"","key":"","label":""}]}`),r=String(n).replace(/```json|```/g,``).trim(),i=JSON.parse(Tu(r));if(Su(i))return i}catch(e){T(e.message,`Game Schema AI Failed`)}return{title:e,url:Cu(e),genre:`generic`,controls:[{action:`accept`,key:`Enter`,label:`NEXT`},{action:`back`,key:`Escape`,label:`BACK`},{action:`left`,key:`ArrowLeft`,label:`LEFT`},{action:`right`,key:`ArrowRight`,label:`RIGHT`}]}}function Su(e){return!e||typeof e!=`object`||typeof e.title!=`string`||typeof e.url!=`string`||typeof e.genre!=`string`||!Array.isArray(e.controls)?!1:e.controls.every(e=>e&&typeof e==`object`&&typeof e.key==`string`&&typeof e.label==`string`&&e.key.trim()&&e.label.trim())}function Cu(e){let t=String(e||``).trim();if(!t)return wu(`AR Game`);if(/^(https?:|blob:|data:|about:)/i.test(t)||t.startsWith(`/`))return t;let n=t.toLowerCase();if(n.includes(`eternum`)){let e=new URLSearchParams(location.search).get(`eternumUrl`);return String(e||globalThis.FridayARConfig?.gameUrls?.eternum||``).trim()||`/api/ar_task?mode=game_launch&task=open%20eternum%20web%20mirror`}if(n.includes(`ripples`)){let e=new URLSearchParams(location.search).get(`ripplesUrl`);return String(e||globalThis.FridayARConfig?.gameUrls?.ripples||``).trim()||`/api/ar_task?mode=game_launch&task=open%20ripples%20web%20mirror`}return wu(t)}function wu(e){let t=`<!doctype html>
<html>
<meta name="viewport" content="width=device-width,initial-scale=1">
<body style="margin:0;background:#05070a;color:white;font:16px system-ui;display:grid;place-items:center;height:100vh;text-align:center">
  <main>
    <h1 style="font-size:22px;margin:0 0 10px">${Eu(e)}</h1>
    <p style="opacity:.72;max-width:32rem">No direct web URL was configured for this game yet. Pass a URL in the launch query string or runtime config, or open a supported mirror command, then convert again.</p>
  </main>
</body>
</html>`;return`data:text/html;charset=utf-8,${encodeURIComponent(t)}`}function Tu(e){let t=e.indexOf(`{`),n=e.lastIndexOf(`}`);return t>=0&&n>t?e.slice(t,n+1):e}function Eu(e){return String(e).replace(/[&<>"']/g,e=>({"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`})[e])}function Du(e,t){let n=document.createElement(`div`);return n.style.cssText=`position:absolute;left:10px;right:10px;bottom:10px;display:flex;gap:8px;justify-content:center;flex-wrap:wrap;pointer-events:auto`,e.forEach(e=>{let r=document.createElement(`button`);r.textContent=e.label||e.action,r.style.cssText=`min-height:44px;min-width:64px;border:1px solid var(--separator);border-radius:999px;background:var(--bg-dark);color:var(--text-primary);font-weight:700`,r.onclick=()=>_u(t.iframe,e.key||`Enter`),n.appendChild(r)}),t.container.style.position=`relative`,t.container.appendChild(n),n}var Ou=`jarvis_ar_game_builder_graphs_v1`,ku=[`OnCollide`,`OnTap`,`OnGesture`,`OnTimerEnd`,`IsTag`,`IsHealth`,`IsDistance`,`Destroy`,`Spawn`,`MoveToward`,`SetScore`,`PlaySound`,`ShowMessage`,`EndGame`],Au=null,ju=null;function Mu(){if(Au)return Au.restore(),Au;let e=document.createElement(`div`);e.append(Nu()),Au=new un({title:`AR Game Builder`,body:e,icon:`B`,width:400,height:600});let t=Au.destroy.bind(Au);return Au.destroy=()=>{ju?.dispose?.(),ju=null,t(),Au=null},Au.focus(),Au}function Nu(){let e=document.createElement(`div`),t=document.createElement(`div`),n=document.createElement(`div`);return t.className=`panel-row`,Object.entries({Entities:Pu,Logic:Fu,Settings:Iu,Play:Lu}).forEach(([e,r],i)=>{let a=document.createElement(`button`);a.className=`panel-action`,a.textContent=e,a.onclick=()=>{t.querySelectorAll(`button`).forEach(e=>e.classList.toggle(`selected`,e===a)),n.replaceChildren(r())},t.appendChild(a),i===0&&window.setTimeout(()=>a.click(),0)}),e.append(t,n),e}function Pu(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`input`),r=document.createElement(`button`);return t.placeholder=`Entity name`,n.placeholder=`Tag, e.g. target`,r.className=`panel-action`,r.textContent=`Add Entity`,r.onclick=()=>{let e=ar(Ou,[]).at(-1)||Uu();e.entities.push({id:dr(`entity`),name:t.value||`Entity`,tag:n.value||`default`}),Wu(e),E(`Entity saved to AR game graph.`)},e.append(t,n,r,Gu()),e}function Fu(){let e=document.createElement(`div`),t=document.createElement(`select`),n=document.createElement(`input`),r=document.createElement(`button`);return fr(t,ku),n.placeholder=`Node value`,r.className=`panel-action`,r.textContent=`Add Logic Node`,r.onclick=()=>{let e=ar(Ou,[]).at(-1)||Uu();e.nodes.push({id:dr(`node`),type:t.value,value:n.value}),Wu(e),E(`${t.value} node added.`)},e.append(t,n,r,Gu()),e}function Iu(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`input`),r=document.createElement(`button`);return t.placeholder=`Game title`,n.type=`number`,n.placeholder=`Timer seconds`,r.className=`panel-action`,r.textContent=`Save Settings`,r.onclick=()=>{let e=ar(Ou,[]).at(-1)||Uu();e.title=t.value||e.title,e.duration=Number(n.value||e.duration||60),Wu(e),E(`Game settings saved.`)},e.append(t,n,r,Gu()),e}function Lu(){let e=document.createElement(`div`),t=document.createElement(`button`);return t.className=`btn-primary`,t.textContent=`Spawn Saved Game`,t.onclick=()=>{let e=ar(Ou,[]).at(-1);if(!e){E(`Create a game graph first.`);return}ju?.dispose?.(),ju=Ru(e),E(`Game "${e.title}" spawned ${ju.entities.length} AR entity object(s).`,`Game Builder`)},e.append(t,Gu()),e}function Ru(e){let{scene:t,camera:n}=R(),r=new Se;r.name=`jarvis-game-${e.id}`,r.userData.isARGame=!0,r.position.set(0,k.floorY+.08,-1.6),t.add(r);let i=(e.entities.length?e.entities:[{id:dr(`entity`),name:`Target`,tag:`target`}]).map((t,n)=>zu(t,n,e.entities.length||1));i.forEach(e=>r.add(e.mesh));let a=0,o=!1,s=performance.now(),c=[],l=[],u=new y,d=t=>{if(o)return;let n=String(t.type||``).toLowerCase(),s=String(t.value||``).trim();if(n===`spawn`){let e=zu({id:dr(`entity`),name:s||`Spawned`,tag:`spawned`},i.length,i.length+1);i.push(e),r.add(e.mesh)}else if(n===`destroy`){let e=Bu(s,i);e&&(e.mesh.parent?.remove(e.mesh),e.destroyed=!0)}else if(n===`setscore`)a=Number(s||a+1),r.userData.score=a;else if(n===`showmessage`)E(s||e.title||`AR game event`,`Game Builder`);else if(n===`playsound`)Hu();else if(n===`endgame`)o=!0,E(`${e.title||`AR Game`} ended. Score: ${a}`,`Game Builder`);else if(n===`movetoward`){let e=Bu(s,i)||i[0];e&&e.mesh.position.lerp(new w(0,.12,-.35),.35)}},f=t=>{if(o||t.target.closest?.(`.ar-panel, .hud-toolbar, button, input, select, textarea, iframe`))return;u.setFromCamera(new Re(t.clientX/innerWidth*2-1,-(t.clientY/innerHeight)*2+1),n);let s=u.intersectObjects(i.filter(e=>!e.destroyed).map(e=>e.mesh),!0)[0];if(!s)return;let c=Vu(s.object,i);a+=1,r.userData.score=a,c.mesh.scale.multiplyScalar(.92),e.nodes.filter(e=>e.type===`OnTap`||e.type===`SetScore`||e.type===`ShowMessage`).forEach(d)};document.addEventListener(`pointerup`,f,!0),l.push(()=>document.removeEventListener(`pointerup`,f,!0));let p=A(`gesture-pinch`,()=>{e.nodes.filter(e=>e.type===`OnGesture`||e.type===`SetScore`).forEach(d)});l.push(p),Number(e.duration)>0&&c.push(window.setTimeout(()=>{e.nodes.filter(e=>e.type===`OnTimerEnd`||e.type===`EndGame`).forEach(d),o||(o=!0,E(`${e.title||`AR Game`} timer finished. Score: ${a}`,`Game Builder`))},Number(e.duration)*1e3));let m=()=>{if(!r.parent||o)return;let e=(performance.now()-s)/1e3;i.forEach((t,n)=>{t.destroyed||(t.mesh.rotation.y+=.01+n*.001,t.mesh.position.y=.08+Math.sin(e*1.6+n)*.035)}),r.userData.frame=F(m)};return m(),{root:r,entities:i,dispose(){o=!0,dt(r.userData.frame),c.forEach(e=>window.clearTimeout(e)),l.forEach(e=>e()),r.traverse(e=>{e.geometry?.dispose?.(),e.material?.dispose?.()}),r.parent?.remove(r)}}}function zu(e,t,n){let r=new xe(.12,1),i=t/Math.max(n,1)*.78+.05,a=new h(r,new Ue({color:new Be().setHSL(i,.72,.55),emissive:new Be().setHSL(i,.72,.12),roughness:.25,metalness:.18})),o=t/Math.max(n,1)*Math.PI*2;return a.position.set(Math.sin(o)*.55,.08,-Math.cos(o)*.35),a.userData.entityId=e.id,a.userData.entityName=e.name,a.userData.tag=e.tag,a.castShadow=!0,a.receiveShadow=!0,{...e,mesh:a,destroyed:!1}}function Bu(e,t){let n=String(e||``).toLowerCase();return t.find(e=>String(e.name||``).toLowerCase().includes(n)||String(e.tag||``).toLowerCase().includes(n)||String(e.id||``).toLowerCase()===n)}function Vu(e,t){let n=e;for(;n;){let e=n.userData?.entityId;if(e)return t.find(t=>t.id===e);n=n.parent}return null}function Hu(){try{let e=new AudioContext,t=e.createOscillator(),n=e.createGain();t.frequency.value=660,n.gain.value=.035,t.connect(n),n.connect(e.destination),t.start(),window.setTimeout(()=>{t.stop(),e.close()},140)}catch{}}function Uu(){return{id:dr(`game`),title:`Untitled AR Game`,duration:60,entities:[],nodes:[],createdAt:Date.now()}}function Wu(e){let t=ar(Ou,[]).filter(t=>t.id!==e.id);t.push(e),or(Ou,t.slice(-20))}function Gu(){let e=document.createElement(`pre`),t=ar(Ou,[]).at(-1)||Uu();return e.style.cssText=`white-space:pre-wrap;font:12px/1.4 monospace;color:rgba(255,255,255,.72);background:rgba(0,0,0,.25);padding:10px;border-radius:12px;max-height:160px;overflow:auto`,e.textContent=JSON.stringify(t,null,2),e}async function Ku(e,t={},n=0,r=1e4){let i=null;for(let a=0;a<=n;a+=1){let o=new AbortController,s=window.setTimeout(()=>o.abort(new DOMException(`Request timed out`,`AbortError`)),r);try{let n=await fetch(e,{...t,signal:o.signal});return window.clearTimeout(s),n}catch(e){if(window.clearTimeout(s),i=e,a>=n)throw e}}throw i||Error(`Request failed.`)}async function qu(e,t={},n=0,r=1e4){let i=await Ku(e,t,n,r);if(!(i.headers.get(`content-type`)||``).includes(`application/json`)){let t=await i.text();throw Error(t||`Expected JSON response from ${e}`)}return i.json()}function Ju(e,t){if(!Array.isArray(e))return!1;let n=JSON.stringify(t);return e.some(e=>JSON.stringify(e)===n)?!1:(e.push(t),!0)}var Yu=class{constructor(e){this.config=e,this.ws=null,this.connected=!1,this.reconnectTimer=0,this.pendingPatches=[],this.reconnectDelay=2e3,this.maxReconnectDelay=3e4,this.heartbeatTimer=0}connect(){return this.connectWebSocket(),this.loadConfig(),k.jarvis=this,this}async loadConfig(){try{let e=await qu(`${this.apiBase()}/api/ar_config`,{headers:this.headers()},1,9e3);if(e.ok===!1)throw Error(e.error||`AR config failed.`);return j(`jarvis-config`,e),D(`status-omega`,`linked`),e}catch{return D(`status-omega`,`offline`),null}}connectWebSocket(){let e=this.config.wsBase||(location.protocol===`https:`?`wss://${location.host}/scene-ws`:`ws://${location.hostname}:5050`),t=Qn(`omega_session`);t&&!/[?&]token=/.test(e)&&(e+=`${e.includes(`?`)?`&`:`?`}token=${encodeURIComponent(t)}`);try{this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=0),this._clearHeartbeat(),this.ws=new WebSocket(e),this.ws.onopen=()=>{this.connected=!0,clearTimeout(this.reconnectTimer),this.reconnectDelay=2e3,D(`status-omega`,`linked`),this.ws.send(JSON.stringify({type:`hello`,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`})),this.flushPendingPatches(),this._startHeartbeat()},this.ws.onmessage=e=>this.onMessage(e),this.ws.onerror=()=>{this.connected&&D(`status-omega`,`ws error`)},this.ws.onclose=()=>{this.connected=!1,this._clearHeartbeat(),D(`status-omega`,`offline`),this.reconnectTimer&&clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*2,this.maxReconnectDelay),this.reconnectTimer=setTimeout(()=>this.connectWebSocket(),e)}}catch(e){T(e.message,`OMEGA WebSocket Failed`)}}_startHeartbeat(){this._clearHeartbeat(),this.heartbeatTimer=setInterval(()=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this._clearHeartbeat();return}try{this.ws.send(JSON.stringify({type:`ping`,ts:Date.now()}))}catch{this.ws.close()}},15e3)}_clearHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=0)}onMessage(e){try{let t=JSON.parse(e.data);j(`omega-message`,t),t.state&&j(`omega-scene-state`,t.state)}catch{}}async query(e){let t=await Ku(`${this.apiBase()}/api/ar_task`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify({task:e,mode:`jarvis`,device_name:this.config.deviceName})},0,9e3),n=await t.json();if(!t.ok||n.ok===!1)throw Error(n.error||`JARVIS query failed.`);return n.response||n.message||n.result||JSON.stringify(n)}async runTask(e,t=`task`){let n=await Ku(`${this.apiBase()}/api/ar_task`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify({task:e,mode:t,device_name:this.config.deviceName})},0,9e3),r=await n.json();if(!n.ok||r.ok===!1)throw Error(r.error||`Task endpoint failed.`);return j(`jarvis-task-result`,r),r}patchScene(e){let t={...e,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`};return this.ws?.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify({type:`patch`,patch:t,ts:Date.now()})),Promise.resolve(!0)):(Ju(this.pendingPatches,t),Ku(`${this.apiBase()}/api/ar_scene_patch`,{method:`POST`,headers:{"Content-Type":`application/json`,...this.headers()},body:JSON.stringify(t)},1,9e3).catch(()=>null))}headers(){let e={"X-FRIDAY-Device":this.config.deviceName},t=Qn(`omega_session`);return t&&(e.Authorization=`Bearer ${t}`),e}apiBase(){return String(this.config.omegaBase||``).replace(/\/+$/,``)||``}flushPendingPatches(){!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.pendingPatches.length||this.pendingPatches.splice(0).forEach(e=>{try{this.ws.send(JSON.stringify({type:`patch`,patch:{...e,device_name:this.config.deviceName,source:`browser-8thwall-real-ar`},ts:Date.now()}))}catch{}})}},Xu=0;function Zu(e,{speak:t=!0}={}){let n=document.getElementById(`jarvis-bubble`),r=document.getElementById(`jarvis-bubble-text`);!n||!r||(n.classList.remove(`hidden`),clearTimeout(Xu),$u(r,String(e||`Ready.`),()=>{clearTimeout(Xu),Xu=window.setTimeout(()=>n.classList.add(`hidden`),6e3)}),t&&Qu(e))}function Qu(e){try{if(!(`speechSynthesis`in window))return;window.speechSynthesis.cancel();let t=new SpeechSynthesisUtterance(String(e||``));t.rate=.92,t.pitch=.82,t.volume=.88;let n=window.speechSynthesis.getVoices();t.voice=n.find(e=>String(e.lang||``).toLowerCase()===`en-gb`)||n.find(e=>/Daniel|George|Arthur|Google UK English Male|English.*United Kingdom|UK/i.test(`${e.name} ${e.lang}`))||n.find(e=>String(e.lang||``).toLowerCase().startsWith(`en-gb`))||n.find(e=>/en/i.test(e.lang))||null,window.speechSynthesis.speak(t)}catch{}}function $u(e,t,n){e.textContent=``;let r=0,i=()=>{e.textContent=t.slice(0,r),r+=1,r<=t.length?window.setTimeout(i,14):n?.()};i()}var ed=null,td=0,nd=0,rd=!1,id=!1,ad=!1,od=null,sd=`unknown`,cd=0,ld=``;function ud(){let e=window.SpeechRecognition||window.webkitSpeechRecognition;return e?(ed=new e,ed.continuous=!0,ed.interimResults=!1,ed.lang=navigator.language||`en-US`,ed.onresult=fd,ed.onerror=e=>{if(e.error===`not-allowed`||e.error===`service-not-allowed`||e.error===`audio-capture`){rd=!1,sd=`blocked`,clearTimeout(nd),T(e.error||`Speech recognition blocked.`,`JARVIS Voice`),md(`blocked`,{error:e.error||`blocked`});return}e.error!==`no-speech`&&T(e.error||`Speech recognition failed.`,`JARVIS Voice`),md(`error`,{error:e.error||`unknown`})},ed.onend=()=>{rd&&(clearTimeout(nd),nd=setTimeout(()=>void dd(),850),md(`ended`))},!0):(E(`SpeechRecognition is not available here. Use the JARVIS text command panel.`),!1)}async function dd(){if(!ed&&!ud())return!1;if(ad)return!0;rd=!0,ad=!0,await pd();try{return ed.start(),window.setTimeout(()=>{ad=!1},350),id||(E(`JARVIS wake word listening is active.`),id=!0),!0}catch(e){return ad=!1,clearTimeout(nd),nd=setTimeout(()=>{rd&&dd()},1200),/InvalidStateError/i.test(e?.name||e?.message||``)||E(`JARVIS voice restart pending: ${e?.message||`recognizer busy`}`),md(`start-failed`,{error:e?.message||`busy`}),!1}}function fd(e){if(!e.results?.[e.resultIndex]?.isFinal)return;let t=Array.from(e.results).slice(e.resultIndex).filter(e=>e?.isFinal).map(e=>e[0]?.transcript||``).join(` `).trim();if(!t)return;let n=t.toLowerCase().replace(/\s+/g,` `).trim(),r=Date.now(),i=n.match(/(?:^|\b)(?:hey\s+)?jarvis\b[:,]?\s*(.*)$/i)||n.match(/(?:^|\b)(?:hey\s+)?friday\b[:,]?\s*(.*)$/i),a=i?.[1]?.trim()||``;if(i){if(td=r+4200,md(`wake`,{wakeWindowUntil:td}),!a){Zu(`Listening.`,{speak:!1});return}}else if(r>td)return;if(r-cd<650)return;cd=r;let o=a||n;!o||o===ld||(ld=o,j(`jarvis-command`,{text:o,source:`voice`}),md(`command`,{wakeWindowUntil:td}))}async function pd(){if(od||sd===`blocked`||!navigator.mediaDevices?.getUserMedia)return od;try{return od=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},video:!1}),sd=`granted`,md(`mic-ready`),od}catch(e){return sd=[`NotAllowedError`,`SecurityError`].includes(e?.name)?`blocked`:`error`,md(`mic-error`,{error:e?.name||e?.message||`unknown`}),null}}function md(e,t={}){try{j(`VOICE_STATE`,{reason:e,enabled:rd,starting:ad,wakeWindowUntil:td,micPermission:sd,hasStream:!!od,lastCommandAt:cd,...t})}catch{}}var hd=null,gd=null,_d=!1,vd=new Map,yd=null,bd=1/60,xd=3,Sd=0,Cd=0;async function wd(){await(void 0)(),hd=new qe(new We(0,-9.81,0)),gd=new Ke(!0),hd.numSolverIterations=8,k.physicsWorld=hd,_d=!0,Cd=performance.now();let e=Ge.fixed().setTranslation(0,0,0);yd=hd.createRigidBody(e);let t=Je.cuboid(100,.1,100).setFriction(.7).setRestitution(.1);hd.createCollider(t,yd),window.AFRAME&&(AFRAME.registerComponent(`jarvis-physics`,{tick:function(e,t){Td(t)}}),document.querySelector(`a-scene`).setAttribute(`jarvis-physics`,``)),console.log(`[AR Physics] Rapier3D world initialized — 60Hz fixed timestep, CCD enabled, 8 solver iterations.`)}function Td(e){if(!_d||!hd)return;let t=performance.now(),n=typeof e==`number`&&e>0&&e<200?e/1e3:Math.min((t-Cd)/1e3,.05);Cd=t,Sd+=n;let r=0;for(;Sd>=bd&&r<xd;)hd.step(gd),Sd-=bd,r++;gd.drainCollisionEvents((e,t,n)=>{n&&window.dispatchEvent(new CustomEvent(`ar-physics-collision`,{detail:{handle1:e,handle2:t}}))});for(let[e,t]of vd.entries()){let n=e.translation(),r=e.rotation();t.position.set(n.x,n.y,n.z),t.quaternion.set(r.x,r.y,r.z,r.w)}vd.size>0&&window.dispatchEvent(new CustomEvent(`ar-physics-step`))}var Ed=null,Dd=null,Od=!1;async function kd(){Od=!0;try{Ed=new globalThis.FaceMesh({locateFile:e=>`https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/${e}`}),Ed.setOptions({maxNumFaces:1,refineLandmarks:!0,minDetectionConfidence:.5,minTrackingConfidence:.5}),Ed.onResults(e=>{window.dispatchEvent(new CustomEvent(`ar-face-mesh-results`,{detail:e}))}),console.log(`[AR Vision] Face mesh initialized.`)}catch(e){T(e.message,`Face Mesh Failed`)}try{let t=await e.forVisionTasks(`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision/wasm`);Dd=await n.createFromOptions(t,{baseOptions:{modelAssetPath:`https://storage.googleapis.com/mediapipe-models/object_detector/efficientdet_lite0/float16/1/efficientdet_lite0.tflite`,delegate:`GPU`},scoreThreshold:.5,maxResults:5,runningMode:`VIDEO`}),console.log(`[AR Vision] Object detector initialized.`)}catch(e){T(e.message,`Object Detection Failed`)}F(Ad)}async function Ad(){if(!Od)return;let e=document.getElementById(`camerafeed`);if(e&&e.readyState>=2)try{if(Ed&&await Ed.send({image:e}),Dd){let t=Dd.detectForVideo(e,performance.now());t.detections.length>0&&window.dispatchEvent(new CustomEvent(`ar-object-detections`,{detail:t.detections}))}}catch(e){console.warn(`Vision frame skipped:`,e)}F(Ad)}var jd=.6,Md=new Map([[`wrist`,0],[`thumb-metacarpal`,1],[`thumb-phalanx-proximal`,2],[`thumb-phalanx-distal`,3],[`thumb-tip`,4],[`index-finger-phalanx-proximal`,5],[`index-finger-phalanx-intermediate`,6],[`index-finger-phalanx-distal`,7],[`index-finger-tip`,8],[`middle-finger-phalanx-proximal`,9],[`middle-finger-phalanx-intermediate`,10],[`middle-finger-phalanx-distal`,11],[`middle-finger-tip`,12],[`ring-finger-phalanx-proximal`,13],[`ring-finger-phalanx-intermediate`,14],[`ring-finger-phalanx-distal`,15],[`ring-finger-tip`,16],[`pinky-finger-phalanx-proximal`,17],[`pinky-finger-phalanx-intermediate`,18],[`pinky-finger-phalanx-distal`,19],[`pinky-finger-tip`,20]]),Nd=!1,Pd=0,Fd=16;function Id(e,t){let n=e?.session;if(!n)return;let r=t?.xr?.getReferenceSpace?.();if(!r)return;let i=performance.now();if(i-Pd<Fd)return;Pd=i;let a=[];for(let t of n.inputSources){if(!t.hand)continue;let n=Ld(e,t.hand,r);n&&a.push(n)}if(!a.length){k.handState.hands.length&&(k.handState.hands=[],k.handState.gestures=new Map);return}Nd||(Nd=!0,I(`webXRHandTracking`,!0),j(`xr-hands-detected`,{count:a.length})),k.handState.hands=a;let o=tc(a);k.handState.gestures=o;for(let[e,t]of o)j(`gesture-${e}`,{...t,source:`webxr-hands`})}function Ld(e,t,n){let r=Array(21),i=0;for(let[a,o]of Md){let s=t.get(a);if(!s)continue;let c=e.getJointPose?.(s,n);if(!c)continue;let l=c.transform.position;r[o]={x:.5+l.x/jd,y:.5-l.y/jd,z:l.z/jd},i+=1}return i<15||!r[0]||!r[4]||!r[8]?null:r}function Rd(){Nd=!1,Pd=0,k.handState.hands=[],k.handState.gestures=new Map}var Q={active:!1,binding:null,depthTexture:null,uniforms:null,patched:new WeakSet,renderer:null},zd=`
  uniform sampler2D uDepthTexture;
  uniform mat4 uUvTransform;
  uniform float uRawValueToMeters;
  uniform float uDepthActive;
  varying vec4 vOcclClip;
  varying float vOcclEyeDepth;
`,Bd=`
  if (uDepthActive > 0.5) {
    vec2 ndc = (vOcclClip.xy / vOcclClip.w) * 0.5 + 0.5;
    vec2 depthUv = (uUvTransform * vec4(ndc, 0.0, 1.0)).xy;
    if (depthUv.x >= 0.0 && depthUv.x <= 1.0 && depthUv.y >= 0.0 && depthUv.y <= 1.0) {
      float realDepth = dot(texture2D(uDepthTexture, depthUv).ra, vec2(255.0, 65280.0)) * uRawValueToMeters;
      // Real surface closer than this fragment (with a small bias) → occluded.
      if (realDepth > 0.0 && realDepth < vOcclEyeDepth - 0.02) discard;
    }
  }
`;function Vd(e,t,n={}){if(n.occlusion===!1||!e||!t)return!1;if(t.depthUsage!==`gpu-optimized`||typeof globalThis.XRWebGLBinding!=`function`)return I(`depthOcclusion`,!1),!1;try{let n=e.getContext();Q.binding=new globalThis.XRWebGLBinding(t,n),Q.renderer=e;let r=new de;r.minFilter=x,r.magFilter=x,r.generateMipmaps=!1,r.flipY=!1,Q.depthTexture=r,Q.uniforms={uDepthTexture:{value:r},uUvTransform:{value:new f},uRawValueToMeters:{value:.001},uDepthActive:{value:0}},Q.active=!0,k.occlusion={active:!0,disable:Ud},I(`depthOcclusion`,!0);for(let e of k.placedObjects||[])Wd(e);return A(`object-placed`,e=>Wd(e?.object)),t.addEventListener(`end`,Ud,{once:!0}),E(`Depth occlusion active — virtual objects hide behind real surfaces (Quest depth sensing).`,`Occlusion`),!0}catch(e){return console.warn(`Depth occlusion init failed; continuing without it:`,e?.message||e),Ud(),!1}}function Hd(e,t){if(!(!Q.active||!e||!t))try{let e=Q.binding.getDepthInformation(t);if(!e||!e.texture){Q.uniforms.uDepthActive.value=0;return}let n=Q.renderer.properties.get(Q.depthTexture);n.__webglTexture=e.texture,n.__webglInit=!0,Q.uniforms.uUvTransform.value.fromArray(e.normDepthBufferFromNormView.matrix),Q.uniforms.uRawValueToMeters.value=e.rawValueToMeters,Q.uniforms.uDepthActive.value=1}catch{Q.uniforms.uDepthActive.value=0}}function Ud(){Q.active=!1,Q.uniforms&&(Q.uniforms.uDepthActive.value=0),k.occlusion&&(k.occlusion.active=!1),I(`depthOcclusion`,!1)}function Wd(e){!Q.active||!e?.traverse||e.traverse(e=>{if(!e.isMesh)return;let t=Array.isArray(e.material)?e.material:[e.material];for(let e of t)Gd(e)})}function Gd(e){if(!e||Q.patched.has(e)||!e.isMeshStandardMaterial&&!e.isMeshPhysicalMaterial&&!e.isMeshLambertMaterial&&!e.isMeshPhongMaterial)return;Q.patched.add(e);let t=e.onBeforeCompile;e.onBeforeCompile=(e,n)=>{typeof t==`function`&&t(e,n),Object.assign(e.uniforms,Q.uniforms),e.vertexShader=e.vertexShader.replace(`#include <common>`,`#include <common>
  varying vec4 vOcclClip;
  varying float vOcclEyeDepth;`).replace(`#include <project_vertex>`,`#include <project_vertex>
  vOcclClip = gl_Position;
  vOcclEyeDepth = -mvPosition.z;`),e.fragmentShader=e.fragmentShader.replace(`#include <common>`,zd+`
#include <common>`).replace(`#include <dithering_fragment>`,Bd+`
#include <dithering_fragment>`)},e.needsUpdate=!0}window.addEventListener(`deviceorientation`,e=>{if(globalThis.JARVIS_AR&&globalThis.JARVIS_AR.runtime&&globalThis.JARVIS_AR.runtime.camera){let{alpha:t,beta:n,gamma:r}=e;if(t!=null&&n!=null&&r!=null){let e=new window.THREE.Euler(THREE.MathUtils.degToRad(n),THREE.MathUtils.degToRad(t),THREE.MathUtils.degToRad(-r),`YXZ`);globalThis.JARVIS_AR.runtime.camera.quaternion.setFromEuler(e)}}});var $=It();k.config=$;try{globalThis.JARVIS_AR=k,globalThis.JarvisWebAR={state:k,start:lf,resume:_f,pause:vf,destroy:yf,setNativeOptions:xf,applyNativeState:Sf,command:Af,spawn:e=>j(`spawn-model`,{query:e})}}catch{}var Kd=0,qd=!1,Jd=null,Yd=!1,Xd=!1,Zd=!1,Qd=!1,$d=null,ef=new Promise(e=>{$d=e}),tf=!1;function nf(){qd=!0,$d?.(!0),ut(Kd),O(`8th Wall engine loaded.`,30),$.autoStart&&lf()}rf();function rf(){if(Qd)return;if(Qd=!0,document.visibilityState===`visible`){af();return}O(`Waiting for this tab to become visible...`,8);let e=()=>{document.visibilityState===`visible`&&(document.removeEventListener(`visibilitychange`,e),af())};document.addEventListener(`visibilitychange`,e)}async function af(){if(!Zd){if(document.visibilityState!==`visible`){rf();return}if(Zd=!0,ot(`ar-core`,{entrypoint:`ar-core/ar-init.js`,force:!0}),it(`booting`),M(`booting`),document.body.dataset.jarvisBoot=`booting`,k.telemetry.startedAt=performance.now(),O(`Running AR preflight audit...`,10),!Ft()){it(`blocked`,{reason:`https-required`}),M(`blocked`,{reason:`https-required`});return}await of($),Cf(),P(`capability-matrix`,`ready`,k.capabilities),dn(),P(`panels`,`ready`),$c(),P(`vr`,`ready`),Ei(),P(`spatial-audio`,`ready`),Pl(),P(`reconstruction`,`ready`),wd(),P(`physics`,`ready`),kd(),P(`vision`,`ready`),Ef(),cf(),wf(),await Wt($);try{t(async()=>{let{initVrStereoSplitScreen:e}=await import(`./ar-compositor-DpKc7noD.js`);return{initVrStereoSplitScreen:e}},[],import.meta.url).then(({initVrStereoSplitScreen:e})=>{let{renderer:t,scene:n,camera:r}=R();e(t,n,r),console.log(`V15 AR: Stereo split-screen mounted.`)})}catch(e){console.error(`V15 AR Stereo Mount failed:`,e)}N(`scene`,!0),P(`scene`,`ready`,{renderer:k.runtime.rendererOwner}),Xt(),P(`adaptive-quality`,`ready`),kt(R(),{mode:`boot-proxy`,tier:k.telemetry.qualityTier||`medium`}),qa(),P(`models`,`ready`),Tf(),P(`jarvis`,`ready`),O(`Waiting for 8th Wall engine binary...`,22),tf||(tf=!0,window.addEventListener(`xrloaded`,nf,{once:!0})),globalThis.XR8&&(qd=!0,$d?.(!0),ut(Kd),O(`8th Wall engine loaded.`,30),$.autoStart&&lf()),Kd=lt(()=>{qd||E(`8th Wall is still loading. Holding real AR start instead of silently dropping into basic camera mode.`,`8th Wall Loading`)},4500),$.command&&(k._commandBootTimer=lt(()=>Af($.command),1200)),document.body.dataset.jarvisBoot=`ready`,N(`boot`,!0),N(`ui`,!0),it(`ready`),M(`ready`)}}function of(e={}){if(globalThis.XR8)return Promise.resolve(!0);let t=document.getElementById(`jarvis-xr-static`);return t?t.dataset.loadFailed===`true`?sf(e):new Promise(n=>{t.addEventListener(`load`,()=>{n(!0)},{once:!0}),t.addEventListener(`error`,()=>{t.dataset.loadFailed=`true`,sf(e).then(n)},{once:!0})}):sf(e)}function sf(e={}){if(globalThis.XR8)return Promise.resolve(!0);let t=String(e.xrScriptUrl||``).trim();return t?document.querySelector(`script[data-jarvis-xr-script]`)?Promise.resolve(!0):new Promise(e=>{let n=document.createElement(`script`);n.src=t,n.async=!0,n.defer=!0,n.crossOrigin=`anonymous`,n.dataset.jarvisXrScript=`true`,n.setAttribute(`data-preload-chunks`,`slam`),n.addEventListener(`load`,()=>e(!0),{once:!0}),n.addEventListener(`error`,()=>{E(`Configured 8th Wall binary failed to load. The runtime will fall back instead of hanging on a dead CDN pin.`,`8th Wall Loading`),e(!1)},{once:!0}),document.head.appendChild(n)}):Promise.resolve(!1)}function cf(){document.getElementById(`start-ar`)?.addEventListener(`click`,()=>lf()),document.getElementById(`camerafeed`)?.addEventListener(`click`,()=>{k.started||lf()})}async function lf(){return Yd||Jd?Jd:k.runtime.lifecycleState===`running`?!0:(Yd=!0,ot(`ar-core`,{entrypoint:`ar-core/ar-init.js`}),it(`starting`),M(`starting`),O(`Starting real AR camera...`,34),Jd=(async()=>{try{let e=await uf(3e4);return k._commandBootTimer&&(ut(k._commandBootTimer),k._commandBootTimer=null),e?await df():(T(`8th Wall engine binary did not load within 30 seconds. Running fallback with reduced tracking.`,`8th Wall Timeout`,{timeout:0}),await pf()),fn(),Xs().catch(e=>T(e.message,`Gesture Startup Failed`)),dd(),tn(),k.started=!0,N(`camera`,!!(k.cameraVideo||k.xrStarted||k.xrSession)),N(`tracking`,!!(k.trackingMode&&k.trackingMode!==`standby`)),it(`running`,{trackingMode:k.trackingMode}),M(`running`,{trackingMode:k.trackingMode}),yt(`AR runtime started: ${k.trackingMode}`),!0}catch(e){k.runtime.lastError=e?.message||String(e),k.runtime.degradationReason=k.runtime.lastError,it(`degraded`,{error:k.runtime.lastError}),M(`degraded`,{error:k.runtime.lastError}),T(e.message,`AR Startup Failed`,{timeout:0}),k._commandBootTimer&&(ut(k._commandBootTimer),k._commandBootTimer=null);let t=await gf();return fn(),t?(k.started=!0,N(`camera`,!0),N(`tracking`,!0),M(`degraded-running`,{trackingMode:k.trackingMode,reason:k.runtime.degradationReason}),!0):(k.started=!1,Jd=null,M(`failed`,{error:k.runtime.lastError}),!1)}finally{Yd=!1}})(),Jd)}async function uf(e){if(globalThis.XR8&&qd)return!0;O(`Waiting for 8th Wall SLAM engine...`,36);let t=new Promise(t=>lt(()=>t(!1),e));return!!(await Promise.race([ef,t])&&globalThis.XR8)}async function df(){let e=globalThis.XR8;if(!e?.GlTextureRenderer?.pipelineModule)throw Error(`XR8.GlTextureRenderer.pipelineModule() is missing.`);if(!e?.Threejs?.pipelineModule)throw Error(`XR8.Threejs.pipelineModule() is missing.`);let t=document.getElementById(`camerafeed`);if(!t)throw Error(`Camera feed canvas was not found.`);e.addCameraPipelineModule({name:`app-camera-status`,onCameraStatusChange:({status:e})=>{e===`requesting`?(O(`Allow camera access to start AR...`,40),D(`status-camera`,`requesting`)):e===`hasStream`?(O(`Camera stream acquired. Initializing SLAM...`,52),D(`status-camera`,`stream`),k.runtime.permissionState=`granted`,N(`camera`,!0)):e===`hasVideo`?(O(`Camera live. Tracking world points...`,76),D(`status-camera`,`live`),k.runtime.permissionState=`granted`,N(`camera`,!0),Qe()):e===`failed`&&(D(`status-camera`,`failed`),k.runtime.permissionState=`denied-or-failed`,k.runtime.degradationReason=`camera failed`,M(`permission-blocked`,{source:`xr8-camera`}),T(`Camera access failed. Check browser settings and allow camera for this browser.`,`Camera Failed`,{timeout:0,linkHref:`intent://settings#Intent;scheme=android-app;end`,linkLabel:`Open Chrome Android settings`}))}});let n=[e.GlTextureRenderer.pipelineModule(),Nt.FullWindowCanvas.pipelineModule(),e.Threejs.pipelineModule(),e.XrController.pipelineModule({enableWorldPoints:!0,disableWorldTracking:!1,imageTargets:Array.isArray($.imageTargets)?$.imageTargets:[]}),...e.CameraPixelArray?.pipelineModule?[e.CameraPixelArray.pipelineModule({maxDimension:480}),_c()]:[],Nt.AlmostThere.pipelineModule(),Nt.Loading.pipelineModule(),Nt.RuntimeError.pipelineModule(),Dl(),ql()];k.pipelineOrder=[`app-camera-status`,`XR8.GlTextureRenderer`,...n.slice(1).map(e=>e.name)],k.trackingAPI={getTrackingQuality:lu,registerAnchor:iu,unregisterAnchor:au,performHitTest:cu,requestRelocalization:uu},e.addCameraPipelineModules(n),e.run({canvas:t,webgl2:!0,ownRunLoop:!0,glContextConfig:{alpha:!0,preserveDrawingBuffer:!0,powerPreference:`high-performance`},cameraConfig:{direction:e.XrConfig.camera().BACK}}),k.xrStarted=!0,k.xrAvailable=!0,I(`eightWallSLAM`,!0),k.trackingMode=`8thwall-slam`,await ff();let r=wt()||R();st(`xr8-threejs`,r,{takeover:!0,engine:`8thwall-slam`}),kt(r,{mode:`xr8-session`,session:k.xrSession,tier:k.telemetry.qualityTier||`high`,stereo:!1,depthComposition:!0,frameBudgetMs:13.5,guardianProxy:!!$.guardianProxy}),P(`xr8`,`running`,{pipelineOrder:k.pipelineOrder}),Jt(r.renderer,$),en(r.scene),Tt(r),N(`tracking`,!0),document.body.dataset.jarvisTracking=`8thwall-slam`,D(`status-tracking`,`8th wall`),Kt(),Qe(),E(`8th Wall SLAM path started. Camera texture renderer is first in the render pipeline.`)}async function ff(e=2200){let t=0,n=performance.now();for(;performance.now()-n<e&&t<132;){try{let e=globalThis.XR8?.Threejs?.xrScene?.();if(e?.scene&&e?.camera&&e?.renderer)return e}catch{}t++,await new Promise(e=>requestAnimationFrame(e))}return t>=132&&console.warn(`Timed out without a valid XR scene — returning null.`,132),null}async function pf(){if(k.trackingMode=`webxr-fallback`,document.body.dataset.jarvisTracking=`webxr-fallback`,D(`status-tracking`,`webxr/basic`),!(`xr`in navigator&&navigator.xr))return gf();try{if(!await navigator.xr.isSessionSupported(`immersive-ar`))return gf();let{renderer:e}=R(),t=await Promise.race([navigator.xr.requestSession(`immersive-ar`,{requiredFeatures:[`hit-test`],optionalFeatures:[`dom-overlay`,`light-estimation`,`depth-sensing`,`local-floor`,`anchors`,`bounded-floor`,`hand-tracking`,`unbounded`],depthSensing:{usagePreference:[`gpu-optimized`],dataFormatPreference:[`luminance-alpha`]},domOverlay:{root:document.getElementById(`ui-layer`)}}),new Promise((e,t)=>lt(()=>t(Error(`WebXR session request timed out`)),5e3))]);e.xr.enabled=!0,e.xr.setSession(t),mf(e,t),hf(e,t),Vd(e,t,$);let n=await t.requestReferenceSpace(`viewer`);return k.xrHitTestSource=await t.requestHitTestSource({space:n}),k.xrSession=t,t.addEventListener(`end`,()=>{if(k.xrSession===t){k.xrSession=null,k.xrStarted=!1;try{e.setAnimationLoop(null)}catch{}Rd(),St(),k.started&&M(`degraded`,{reason:`webxr-session-ended`})}},{once:!0}),st(`webxr-threejs`,{scene:k.scene,camera:k.camera,renderer:e},{takeover:!0,engine:`webxr-fallback`}),kt({scene:k.scene,camera:k.camera,renderer:e},{mode:`webxr-session`,session:t,stereo:!1,depthComposition:!0,source:k.cameraVideo||document.getElementById(`camerafeed`)}),P(`webxr`,`running`),I(`webXRHitTest`,!0),Ct(),e.setAnimationLoop((t,n)=>{if(n&&(k.xrFrame=n,Id(n,e),k.occlusion?.active)){let t=e.xr.getReferenceSpace?.(),r=t?n.getViewerPose?.(t):null;r?.views?.length&&Hd(n,r.views[0])}let r=k.scene||k.fallbackScene,i=k.camera||k.fallbackCamera;r&&i&&e.render(r,i)}),Tt(R()),N(`camera`,!0),N(`tracking`,!0),Qe(),E(`Running WebXR fallback. 8th Wall SLAM is not active in this session.`),!0}catch(e){return T(e.message,`WebXR Fallback Failed`),gf()}}function mf(e,t){try{let n=k.scene||R()?.scene;if(!n||!e)return;let r=new ye(e);k.xrEstimatedLight=r;let i=n.environment;r.addEventListener(`estimationstart`,()=>{n.add(r),i=n.environment,r.environment&&(n.environment=r.environment),k.telemetry.iblEnvironment=`xr-light-estimation`,I(`lightEstimation`,!0)}),r.addEventListener(`estimationend`,()=>{try{n.remove(r)}catch{}n.environment=i,k.telemetry.iblEnvironment=n.userData?.jarvisEnvironmentSource||`room-default`}),t.addEventListener(`end`,()=>{try{n.remove(r)}catch{}n.environment=i,k.xrEstimatedLight=null},{once:!0})}catch(e){console.warn(`XR light estimation setup failed:`,e?.message||e)}}function hf(e,t){let n=t=>{try{let n=k.xrFrame,r=e?.xr?.getReferenceSpace?.(),i=t.inputSource,a=i?.targetRaySpace;if(!n||!r||!a)return;let o=n.getPose?.(a,r);if(!o)return;let s=o.transform.matrix,c={x:s[12],y:s[13],z:s[14]},l={x:-s[8],y:-s[9],z:-s[10]};try{i.gamepad?.hapticActuators?.[0]?.pulse?.(.4,40)}catch{}let u=Zo({origin:c,direction:l});u&&(k.telemetry.lastXRSelect=u.type)}catch(e){console.warn(`XR select handling failed:`,e?.message||e)}};t.addEventListener(`select`,n),t.addEventListener(`end`,()=>{try{t.removeEventListener(`select`,n)}catch{}},{once:!0})}async function gf(){k.trackingMode=`manual-camera`,I(`manualCamera`,!0),document.body.dataset.jarvisTracking=`manual-camera`,D(`status-tracking`,`basic camera`),O(`Starting basic camera mode...`,48);try{bf();let e=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:`environment`},width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},audio:!1}),t=document.createElement(`video`);t.srcObject=e,t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.setAttribute(`playsinline`,``),t.style.cssText=`position:fixed;top:0;left:0;width:100vw;height:100vh;object-fit:cover;z-index:0;background:#000`,document.body.insertBefore(t,document.body.firstChild),await t.play(),k.cameraVideo=t,k.runtime.permissionState=`granted`;try{return st(`fallback-three`,R(),{takeover:k.runtime.rendererOwner!==`xr8-threejs`,engine:`manual-camera`}),P(`manual-camera`,`running`),kt(R(),{mode:`manual-camera`,stereo:!1,source:k.cameraVideo||document.getElementById(`camerafeed`),frameBudgetMs:20}),St(),Tt(R()),D(`status-camera`,`live`),N(`camera`,!0),N(`tracking`,!0),Qe(),E(`Basic camera mode is active. Surface placement uses estimated floor fallback.`),!0}catch(e){return k.runtime.permissionState=`failed`,k.runtime.degradationReason=e?.message||String(e),T(`Manual camera fallback setup failed: ${e?.message||String(e)}`,`Manual Camera Setup Failed`,{timeout:0}),bf(),!1}}catch(e){return k.runtime.permissionState=e.name===`NotAllowedError`?`denied`:`failed`,k.runtime.degradationReason=e?.message||String(e),M(e.name===`NotAllowedError`?`permission-blocked`:`failed`,{error:k.runtime.degradationReason}),e.name===`NotAllowedError`?T(`Camera permission denied. Please allow camera access.`,`Camera Denied`,{timeout:0}):e.name===`NotFoundError`?T(`No camera found on this device.`,`Camera Missing`,{timeout:0}):T(`Camera error: ${e.message}`,`Camera Error`,{timeout:0}),!1}}function _f(){if(k.runtime.lifecycleState===`stopped`)return!1;if(k.paused=!1,k.xrStarted)try{globalThis.XR8?.resume?.()}catch{E(`8th Wall resume was not available in this browser session.`,`Lifecycle`)}try{k.cameraVideo?.play?.()}catch{}return!k.xrStarted&&k.fallbackRenderer&&St(),document.body.dataset.jarvisPaused=`false`,tn(),M(k.started?`running`:`ready`,{reason:`resume`}),yt(`AR runtime resumed`),!0}function vf(e=`manual`){if(k.paused=!0,k.xrStarted)try{globalThis.XR8?.pause?.()}catch{E(`8th Wall pause was not available in this browser session.`,`Lifecycle`)}try{k.cameraVideo?.pause?.()}catch{}return Ct(),document.body.dataset.jarvisPaused=`true`,M(`paused`,{reason:e}),yt(`AR runtime paused`),!0}async function yf(){vf(`shutdown`),k._commandBootTimer&&(ut(k._commandBootTimer),k._commandBootTimer=null),Qs(),_l(),Cn(),du(),Ct();try{await k.xrSession?.end?.()}catch{}try{let e=R()?.renderer;e?.xr&&await e.xr.setSession(null)}catch{}try{typeof globalThis.XR8?.clearCameraPipelineModules==`function`&&globalThis.XR8.clearCameraPipelineModules(),globalThis.XR8?.stop?.()}catch{}return bf(),document.querySelectorAll(`#ui-layer .ar-panel, #ui-layer .panel-orb, #error-host > *, #banner-host > *`).forEach(e=>e.remove()),jt(),at(),Jd=null,yt(`AR runtime shut down`),!0}function bf(){try{(k.cameraVideo?.srcObject)?.getTracks?.().forEach(e=>e.stop()),k.cameraVideo?.remove?.()}catch{}k.cameraVideo=null}function xf(e={}){k.nativeOptions={...k.nativeOptions,...e&&typeof e==`object`?e:{}},document.body.dataset.jarvisNativeOptions=`applied`,k.nativeOptions.handTrackingEnabled===!1&&E(`Native options disabled hand tracking for this AR session.`,`APK Options`),(k.nativeOptions.thermalPause===!0||k.nativeOptions.thermalState===`critical`)&&(vf(`thermal`),k.runtime.degradationReason=`thermal`,M(`thermal-paused`,{thermalState:k.nativeOptions.thermalState||`critical`}));for(let e of[`eyeTracking`,`nativeCompositor`,`truePersistentWorldAnchors`,`nativeOpenXRBridge`])Object.prototype.hasOwnProperty.call(k.nativeOptions,e)&&I(e,k.nativeOptions[e]);return Object.prototype.hasOwnProperty.call(k.nativeOptions,`truePersistentWorldAnchors`)&&I(`persistentAnchorSupport`,k.nativeOptions.truePersistentWorldAnchors),L(`setCompositorState`,JSON.stringify({mode:k.compositor.mode,native:k.compositor.native,passthroughBlend:k.compositor.passthroughBlend,frameBudgetMs:k.compositor.frameBudgetMs,browserManaged:!0})),j(`native-options`,k.nativeOptions),yt(`APK AR options applied`),k.nativeOptions}function Sf(e={}){let t=e;try{t=typeof e==`string`?JSON.parse(e):e}catch(e){return T(e.message,`APK State Sync Failed`),!1}let n=Array.isArray(t)?t:Array.isArray(t?.objects)?t.objects:t?.ar_objects;return Array.isArray(n)&&(j(`native-ar-state`,{objects:n}),L(`status`,`Applied ${n.length} native AR object(s)`)),t?.ui&&typeof t.ui==`object`&&j(`native-ui-state`,t.ui),!0}function Cf(){let e=Ht();ht(e),k.runtime.browserProfile=e,I(`mediaPipeHands`,!!globalThis.Hands),I(`spatialAudio`,!!(globalThis.AudioContext||globalThis.webkitAudioContext)),I(`microphone`,!!navigator.mediaDevices?.getUserMedia),I(`speechSynthesis`,!!window.speechSynthesis),I(`voiceRecognition`,!!(globalThis.SpeechRecognition||globalThis.webkitSpeechRecognition)),I(`webXRAvailable`,!!navigator.xr),I(`webXRHitTest`,!1),I(`browserLatencyCeiling`,!0),I(`limitedSensorAccess`,!0),I(`limitedOSIntegration`,!0),I(`limitedCompositorControl`,!0),I(`persistentAnchorSupport`,!!$.truePersistentWorldAnchors),I(`backgroundExecutionLimited`,!0),I(`passthroughControlLimited`,!0),I(`spatialMemoryLimited`,!0),I(`headsetOptimizationAccessLimited`,!0),I(`webXRFragmented`,e.webXRFragmented),I(`safariWebXRLimitations`,e.limits.safariWebXRLimitations),I(`visionOSBrowserRestrictions`,e.limits.visionOSBrowserRestrictions),I(`androidBrowserInconsistency`,e.limits.androidBrowserInconsistency),I(`webViewInconsistency`,e.limits.webViewInconsistency),I(`questBrowserQuirks`,e.limits.questBrowserQuirks),I(`fullscreenEdgeCases`,e.limits.fullscreenEdgeCases),I(`orientationLockEdgeCases`,e.limits.orientationLockEdgeCases),I(`webglContextLossRisk`,e.limits.webglContextLossRisk),I(`renderLoopDuplicationRisk`,e.limits.renderLoopDuplicationRisk),I(`eyeTracking`,!!$.eyeTracking),I(`nativeCompositor`,!!$.nativeCompositor),I(`truePersistentWorldAnchors`,!!$.truePersistentWorldAnchors),I(`nativeOpenXRBridge`,!!$.nativeOpenXRBridge),I(`eyeTrackingProxy`,!0),I(`persistentSpatialMemory`,!0),I(`ultraStableAnchoring`,!0),I(`naturalWindowPlacement`,!0),I(`depthAwareImmersion`,!0),I(`environmentAwareUI`,!0),I(`headsetComfortSystems`,!0),I(`lowLatencyCompositing`,!0),document.body.dataset.jarvisCapabilityModel=`browser-web-ar-with-explicit-native-limits`,document.body.dataset.jarvisBrowserProfile=e.browser,document.body.dataset.jarvisBrowserPlatform=e.platform,document.body.dataset.jarvisBrowserLatency=String(e.latencyCeilingMs);let t=Ut(e).filter(e=>/safari|visionos|android|webview|webxr-fragmented|quest/.test(e));gt({architecture:`browser-web-ar-runtime`,experienceClass:`web-ar-experiment`,spatialRuntimeClass:e.isVisionOS?`browser-managed-visionos-shell`:e.isQuest?`quest-browser-ar-shell`:e.isSafari?`safari-webxr-shell`:e.isWebView?`embedded-webview-ar-shell`:`browser-web-ar-shell`,platformRole:e.isVisionOS?`visionos-browser`:e.isQuest?`quest-browser`:e.isAndroid?`android-browser`:e.isIOS?`ios-browser`:`desktop-browser`,spatialGapStatement:e.isVisionOS||e.isSafari||e.isWebView||e.isAndroid?`This runtime is browser-managed spatial AR, not a native headset OS, compositor, or persistent spatial shell.`:`This runtime is browser-managed spatial AR, not a unified native spatial computing runtime.`}),_t([`No single authoritative native spatial runtime exists in this codebase.`,`Browser-layer AR, XR8/WebXR, fallback cameras, and compatibility shells coexist behind one shared authority instead of a native OS compositor stack.`,`Persistent world understanding, headset compositor control, and headset-grade platform integration remain unavailable because the runtime is bounded by browser APIs and vendor binaries.`,`Lifecycle and rendering governance must therefore be centralized in the web runtime, not spread across competing engines.`].join(` `)),vt(`Vision Pro-style browser shell implemented as far as the web stack allows: gaze proxy, hand-eye fusion, persistent spatial memory, stabilized anchoring, low-latency compositor hints, natural window placement, depth-aware immersion, environment-aware UI, and comfort systems are active; true native eye tracking, headset OS integration, and native compositor control remain outside the browser runtime.`,[`gaze proxy`,`hand-eye fusion`,`persistent spatial memory`,`ultra-stable anchoring`,`low-latency compositing proxy`,`natural window placement`,`depth-aware immersion`,`environment-aware UI`,`headset comfort systems`]),L(`setNativeCapabilities`,JSON.stringify({browserProfile:e,capabilities:k.capabilities,runtime:{architecture:k.runtime.architecture,spatialRuntimeClass:k.runtime.spatialRuntimeClass,platformRole:k.runtime.platformRole}})),L(`setGuardianState`,JSON.stringify({requested:!0,boundary:k.capabilities.guardianBoundary,platformRole:k.runtime.platformRole,source:`ar-init`})),L(`setOpenXRState`,JSON.stringify({supported:e.isQuest||e.isVisionOS,browserManaged:!0,platformRole:k.runtime.platformRole,compositor:k.compositor})),t.length&&(k.runtime.degradationReason=t.join(`, `),yt(`Browser limits: ${t.join(`, `)}`),e.limits.visionOSBrowserRestrictions?E(`visionOS browser support is browser-managed only. Native compositor, passthrough control, and persistent anchors stay unavailable here.`,`visionOS Browser Limits`):e.limits.safariWebXRLimitations?E(`Safari WebXR support is fragmented. Chrome Android remains the primary AR path for this runtime.`,`Safari WebXR Limits`):e.limits.webViewInconsistency?E(`Embedded WebViews can be stricter than Chrome Custom Tabs for XR, sensors, and camera permissions.`,`WebView Limits`):e.limits.questBrowserQuirks&&E(`Quest Browser fullscreen, orientation, and session behavior can be quirky; the runtime is applying extra guard rails.`,`Quest Browser Limits`))}function wf(){Xd||(Xd=!0,document.addEventListener(`visibilitychange`,()=>{document.hidden?k.started&&vf(`background-tab`):k.started&&k.runtime.lifecycleState===`paused`&&_f()}),window.addEventListener(`pagehide`,()=>{k.started&&vf(`pagehide`)}),window.addEventListener(`pageshow`,()=>{k.started&&k.runtime.lifecycleState===`paused`&&_f()}))}function Tf(){let e=new Yu($).connect();ud();try{globalThis.Jarvis={query:t=>e.query(t),runTask:(t,n)=>e.runTask(t,n),command:e=>Af(e)}}catch{k.jarvisGlobalBlocked=!0}A(`jarvis-command`,({text:e})=>Af(e))}function Ef(){A(`VOICE_STATE`,e=>{k.spatialAudio.micPermission=e?.micPermission||k.spatialAudio.micPermission,k.spatialAudio.micReady=!!(e?.micReady||e?.enabled||e?.listening),k.spatialAudio.wakeWindowUntil=e?.wakeWindowUntil||0,k.spatialAudio.lastVoiceCommandAt=e?.lastCommandAt||k.spatialAudio.lastVoiceCommandAt,(e?.reason===`mic-error`||e?.reason===`blocked`)&&yt(`Voice mic ${e.error||e.micPermission||`blocked`}`)}),A(`open-jarvis`,Df),A(`open-games`,Of),A(`open-builder`,Mu),A(`scan-room`,()=>Zu(`Scanning the room.`,{speak:!1}))}function Df(){let e=document.createElement(`div`),t=document.createElement(`input`),n=document.createElement(`button`);t.placeholder=`Command JARVIS`,n.className=`btn-primary`,n.textContent=`Run`,n.onclick=()=>Af(t.value),t.addEventListener(`keydown`,e=>{e.key===`Enter`&&n.click()}),e.append(t,n),new un({title:`JARVIS`,body:e,icon:`J`,width:360,height:260}).focus()}function Of(){let e=document.createElement(`div`),t=kf(`Eternum AR`,mu),n=kf(`Ripples AR`,yu),r=document.createElement(`input`),i=kf(`Convert Game URL`,()=>bu(r.value||`about:blank`,globalThis.Jarvis||k.jarvis));r.placeholder=`Game URL or name`,e.append(t,n,r,i),wn(`AR Games`,e,`G`)}function kf(e,t){let n=document.createElement(`button`);return n.className=`panel-action`,n.textContent=e,n.onclick=t,n}async function Af(e){let t=String(e||``).trim();if(!t)return;let n=t.toLowerCase();try{let e=n.match(/\b(open|close|toggle|rotate|spin|turn|reconfigure|rebuild|transform|rearrange|shatter|break|explode|reveal|show|hide|grab|move|drag)\b/);if(e&&/(model|door|window|screen|panel|roof|drawer|wheel|part|house|room|car|vehicle|device|custom)/.test(n)){let r=n.replace(/\b(hey\s+jarvis|jarvis)\b/gi,``).replace(/\b(open|close|toggle|rotate|spin|turn|reconfigure|rebuild|transform|rearrange|shatter|break|explode|reveal|show|hide|grab|move|drag|the|a|an|model|part|on|of|in|for|to)\b/gi,` `).replace(/\s+/g,` `).trim();j(`jarvis-model-action`,{action:e[1],target:r,command:t,source:`voice`}),Zu(`Model action queued: ${e[1]}${r?` on ${r}`:``}.`,{speak:!0});return}if(/spawn|place|load|model/.test(n)){let e=n.replace(/\b(spawn|place|load|model|a|an|the|in ar)\b/g,` `).trim()||`Duck`;j(`spawn-model`,{query:e}),Zu(`Model armed: ${e}. Tap a surface to place it.`,{speak:!0});return}if(/scan room|room scan|scan/.test(n)){j(`scan-room`);return}if(/reconstruct/.test(n)){let e=n.replace(`reconstruct`,``).replace(`this scene`,``).trim()||`room`;await Fl(e),Zu(`Scene reconstruction complete: ${e}.`,{speak:!0});return}if(/vr mode|vr screen|headset/.test(n)){await el();return}if(/eternum/.test(n)){mu(),Zu(`Eternum AR panel is open.`,{speak:!0});return}if(/ripples/.test(n)){yu(),Zu(`Ripples AR panel is open.`,{speak:!0});return}if(/convert .* ar|game to ar/.test(n)){await bu(t.replace(/convert|to ar|game to ar/gi,``).trim(),globalThis.Jarvis||k.jarvis);return}if(/open models|model picker/.test(n)){Xa();return}if(/forge model|interactive model|3d forge|custom interactive model|build custom model|custom 3d builder/.test(n)){j(`open-model-forge`),Zu(`Interactive model forge opened.`,{speak:!0});return}if(/camera kit|lens studio|snap/.test(n)){let e=document.createElement(`div`);e.style.cssText=`display:flex;flex-direction:column;gap:10px;padding:8px 0`;let t=document.createElement(`p`);t.style.cssText=`margin:0;font-size:13px;opacity:0.75;line-height:1.4`,t.textContent=`Lens Studio Camera Kit requires a Snap developer token. Enter yours below to activate the Camera Kit AR layer.`;let n=document.createElement(`label`);n.textContent=`Snap Developer Token`,n.style.cssText=`font-size:12px;font-weight:600;opacity:0.9`;let r=document.createElement(`input`);r.type=`text`,r.placeholder=`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`,r.style.cssText=`width:100%;box-sizing:border-box;padding:8px 10px;border-radius:6px;border:1px solid rgba(255,255,255,0.2);background:rgba(255,255,255,0.08);color:var(--text-primary);font-size:13px`,k.config.snapToken&&(r.value=k.config.snapToken);let i=document.createElement(`button`);i.className=`btn-primary`,i.textContent=`Activate Camera Kit`,i.onclick=()=>{let e=r.value.trim();if(!e){E(`Please enter a valid Snap developer token.`,`Camera Kit`);return}k.config.snapToken=e,j(`camera-kit-token-set`,{token:e}),E(`Camera Kit token saved. Reload the AR session to activate the Lens Studio layer.`,`Camera Kit`),o.close?.()};let a=document.createElement(`a`);a.href=`https://docs.snap.com/snap-kit/camera-kit/guides/tutorials/integration-guides/web#set-up-your-api-token`,a.target=`_blank`,a.rel=`noopener noreferrer`,a.textContent=`How to get a Snap developer token ↗`,a.style.cssText=`font-size:12px;color:rgba(255,255,255,0.55);text-decoration:underline`,e.append(t,n,r,i,a);let o=new un({title:`Camera Kit`,body:e,icon:`CK`,width:360,height:300});o.focus();return}Zu(await(globalThis.Jarvis||k.jarvis).query(t),{speak:!0})}catch(e){T(e.message,`JARVIS Command Failed`)}}export{Sf as applyNativeState,At as i,Mt as n,vf as pauseRuntime,jt as r,_f as resumeRuntime,xf as setNativeOptions,yf as shutdownRuntime,gf as startManualCameraFallback,kt as t};