@liveroom-tech/react-immersive 6.2.0 → 6.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/DownloadedEnvironment-NHM4U2LJ.mjs +1 -0
  2. package/dist/{SequencesTab-ODR5IGDX.mjs → SequencesTab-VZKEKAUG.mjs} +1 -1
  3. package/dist/StreamingTilesModel-6Z7SIC2J.mjs +16 -0
  4. package/dist/binding-builder.css +1 -1
  5. package/dist/binding-builder.d.mts +3 -3
  6. package/dist/binding-builder.d.ts +3 -3
  7. package/dist/binding-builder.js +59 -58
  8. package/dist/binding-builder.mjs +1 -1
  9. package/dist/chunk-25WC5KDO.mjs +50 -0
  10. package/dist/chunk-2AJK643D.mjs +1 -0
  11. package/dist/chunk-3OCHN3CA.mjs +1 -0
  12. package/dist/{chunk-3XZKDTB2.mjs → chunk-7OVEHDDE.mjs} +1 -1
  13. package/dist/chunk-KFLS7GI6.mjs +1 -0
  14. package/dist/{chunk-EWNN4BBR.mjs → chunk-KYXJG3TX.mjs} +1 -1
  15. package/dist/{chunk-2CUPPOBW.mjs → chunk-LD7QWHB4.mjs} +2 -2
  16. package/dist/{chunk-GXY3VML4.mjs → chunk-NMRTI3NQ.mjs} +1 -1
  17. package/dist/chunk-RKDATTUM.mjs +1 -0
  18. package/dist/chunk-RXZ4Q7CY.mjs +1 -0
  19. package/dist/chunk-TUYVYSN5.mjs +1 -0
  20. package/dist/{chunk-IOLT2VXU.mjs → chunk-UAZ6I25Y.mjs} +1 -1
  21. package/dist/chunk-UCD76KQ6.mjs +1 -0
  22. package/dist/chunk-UHRJ2RBF.mjs +1 -0
  23. package/dist/chunk-UTVFRMYW.mjs +47 -0
  24. package/dist/chunk-YKDDNX2D.mjs +69 -0
  25. package/dist/exportSceneMesh-YJFOLFHS.mjs +1 -0
  26. package/dist/hosted.css +1 -1
  27. package/dist/hosted.d.mts +3 -3
  28. package/dist/hosted.d.ts +3 -3
  29. package/dist/hosted.js +58 -57
  30. package/dist/hosted.mjs +1 -1
  31. package/dist/index.css +1 -1
  32. package/dist/index.d.mts +4 -4
  33. package/dist/index.d.ts +4 -4
  34. package/dist/index.js +52 -51
  35. package/dist/index.mjs +1 -1
  36. package/dist/meshFormats-4C6NHYOA.mjs +1 -0
  37. package/dist/modelFileResolver-CVmON8hg.d.mts +1724 -0
  38. package/dist/modelFileResolver-CVmON8hg.d.ts +1724 -0
  39. package/dist/modelViewerProps-BBnZTFO-.d.ts +949 -0
  40. package/dist/modelViewerProps-CIY4nsNY.d.mts +949 -0
  41. package/dist/{publicProps-Cmh9JtzJ.d.ts → publicProps-BARVwXu7.d.ts} +1 -1
  42. package/dist/{publicProps-TMARX628.d.mts → publicProps-n0Yvr_Km.d.mts} +1 -1
  43. package/dist/simple-model-viewer.css +1 -1
  44. package/dist/simple-model-viewer.d.mts +22 -4
  45. package/dist/simple-model-viewer.d.ts +22 -4
  46. package/dist/simple-model-viewer.js +5 -5
  47. package/dist/simple-model-viewer.mjs +1 -1
  48. package/dist/utils.d.mts +4 -4
  49. package/dist/utils.d.ts +4 -4
  50. package/dist/utils.js +2 -2
  51. package/dist/utils.mjs +1 -1
  52. package/dist/xrRuntime-5S7KYUVB.mjs +1 -0
  53. package/package.json +1 -1
  54. package/dist/chunk-3MIILDHB.mjs +0 -83
  55. package/dist/chunk-6Q6YZ7O5.mjs +0 -1
  56. package/dist/chunk-7MN2TMY6.mjs +0 -47
  57. package/dist/chunk-X4WRTDO6.mjs +0 -50
  58. package/dist/modelFileResolver-ChKYsF21.d.mts +0 -495
  59. package/dist/modelFileResolver-ChKYsF21.d.ts +0 -495
  60. package/dist/modelViewerProps-Ch6pIZIE.d.ts +0 -2159
  61. package/dist/modelViewerProps-HazR2IE_.d.mts +0 -2159
package/dist/utils.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Ro=Object.create;var Fe=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Vo=(e,t)=>{for(var o in t)Fe(e,o,{get:t[o],enumerable:!0})},Ut=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Po(t))!Eo.call(e,r)&&r!==o&&Fe(e,r,{get:()=>t[r],enumerable:!(n=Io(t,r))||n.enumerable});return e};var _t=(e,t,o)=>(o=e!=null?Ro(Bo(e)):{},Ut(t||!e||!e.__esModule?Fe(o,"default",{value:e,enumerable:!0}):o,e)),Do=e=>Ut(Fe({},"__esModule",{value:!0}),e);var Nr={};Vo(Nr,{ACTION_CATALOG:()=>Ve,DEFAULT_MODEL_VIEWER_LABELS:()=>jt,DEFAULT_SCENE_CONFIG:()=>be,DEFAULT_SECTION_CONFIG:()=>on,MATERIAL_BLENDING_MODES:()=>nn,MATERIAL_SIDES:()=>tn,MAX_VIEWER_STATE_BYTES:()=>me,MEASUREMENT_UNITS:()=>xt,SEQUENCE_EASINGS:()=>bt,SEQUENCE_OBJECT_PROPERTIES:()=>gt,applyIsolation:()=>Yt,applyProductOptions:()=>In,applyStyleRules:()=>Wt,buildBindingsFromNodes:()=>en,calibrateMeasurements:()=>gn,chooseMaterialVariant:()=>qe,collectObjectHierarchy:()=>_n,colorScaleValue:()=>at,compareViewerConfigurations:()=>jo,copyBindingStyle:()=>zn,createARHandoffUrl:()=>Ao,createDefaultBinding:()=>dt,decodeProductSelections:()=>Cn,defaultProductSelections:()=>Te,defineObjectBindings:()=>zt,encodeProductSelections:()=>kt,evaluateProductConfiguration:()=>ae,exportConfiguredUSDZ:()=>bo,findCatalogAction:()=>Zt,formatProductPrice:()=>An,generateProductSkus:()=>kn,groundAsset:()=>cn,inferType:()=>ut,inspectAsset:()=>qn,isolatedBindingKeys:()=>ct,material:()=>qt,measurementResult:()=>At,measurementScale:()=>Mt,measurementValue:()=>Xe,measurementsToCsv:()=>hn,parseAssetTransform:()=>je,parseMeasurements:()=>we,parseProductConfiguration:()=>Rn,parseProductDefinition:()=>Ct,parseSceneProduct:()=>Ze,parseSectionConfig:()=>De,parseSelectionSets:()=>Ye,parseSequences:()=>Oe,parseViewerState:()=>Re,pasteBindingStyle:()=>Fn,patchBindings:()=>$e,patchSceneConfig:()=>Gt,prepareViewerState:()=>Qe,productCheckoutUrl:()=>vn,productDefinitionWarnings:()=>On,productOptionStates:()=>jn,productPriceFromDefinition:()=>Mn,readARHandoffUrl:()=>vo,resolveProductSelections:()=>Je,sampleSequenceTrack:()=>We,sceneLight:()=>Ht,sectionSnapshot:()=>rn,selectBindingKeys:()=>Q,selectBindings:()=>$t,serializeMeasurements:()=>bn,serializeProductConfiguration:()=>Tn,serializeViewerState:()=>Un,snapAssetToGrid:()=>an,upsertSequenceKeyframe:()=>sn});module.exports=Do(Nr);function zt(e){return e}function it(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Be(e,t){if(!it(t))return t;let o=it(e)?{...e}:{};for(let n of Object.keys(t)){let r=t[n];o[n]=it(r)?Be(o[n],r):r}return o}function Ft(e,t){if(e[t])return t;let o=Object.entries(e).find(([,r])=>r.id===t)?.[0];return o||(Object.entries(e).find(([,r])=>r.modelObjectId===t)?.[0]??null)}function No(e){return typeof e=="object"&&!Array.isArray(e)}function Lo(e,t){return"group"in t?e.group===t.group:"tag"in t?e.tags?.includes(t.tag)??!1:(e.type??"other")===t.type}function Q(e,t){if(No(t))return Object.entries(e).filter(([,r])=>Lo(r,t)).map(([r])=>r);let n=(typeof t=="string"?[t]:t).map(r=>Ft(e,r)).filter(r=>r!==null);return[...new Set(n)]}function $t(e,t){return Q(e,t).map(o=>e[o]).filter(o=>o!==void 0)}function Uo(e){return Array.isArray(e)&&e.length>0&&typeof e[0]!="string"}function $e(e,t,o){let n=Uo(t)?t:[{ids:t,patch:o??{}}],r=e;for(let s of n)for(let a of Q(r,s.ids)){let i=r[a];if(!i)continue;let c=Be(i,s.patch);r===e&&(r={...e}),r[a]=c}return r}function qt(e){return{style:{material:e}}}function Gt(e,t){return Be(e,t)}var _o={type:"point",color:"#ffffff",intensity:1,position:[0,0,0],distance:0,decay:2,attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0};function Ht(e){return{..._o,...e}}var zo="#ff3b30",Fo=Object.freeze({}),Kt=e=>e;function $o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e,t){let o=e.metadata;for(let n of t.split(".")){if(!$o(o))return;o=o[n]}return o}function Go(e,t){if("metric"in t){let o=e.metrics?.[t.metric];return!(typeof o!="number"||!Number.isFinite(o)||t.above!==void 0&&!(o>t.above)||t.below!==void 0&&!(o<t.below))}if("status"in t){let o=e.status??"normal";return Array.isArray(t.status)?t.status.includes(o):t.status===o}return qo(e,t.metadata)===t.equals}function Ho(e){let t=e.trim().replace(/^#/,""),o=t.length===3?t.split("").map(n=>n+n).join(""):t;return/^[0-9a-f]{6}$/i.test(o)?[0,2,4].map(n=>parseInt(o.slice(n,n+2),16)):null}var st=e=>`#${e.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`;function at(e,t){let o=e.map(([c,l])=>({at:c,rgb:Ho(l)})).filter(c=>Number.isFinite(c.at)&&c.rgb!==null).sort((c,l)=>c.at-l.at);if(o.length===0||!Number.isFinite(t))return null;if(t<=o[0].at)return st(o[0].rgb);let n=o[o.length-1];if(t>=n.at)return st(n.rgb);let r=o.findIndex(c=>c.at>=t),s=o[r-1],a=o[r],i=a.at===s.at?1:(t-s.at)/(a.at-s.at);return st(s.rgb.map((c,l)=>c+(a.rgb[l]-c)*i))}function Wt(e,t){if(!t?.length)return{bindings:e,pulses:Fo,sourceOf:Kt};let o=new Map,n={};for(let a of t){let i=a.target?Q(e,a.target):Object.keys(e),c=a.when?Array.isArray(a.when)?a.when:[a.when]:[];for(let l of i){let u=e[l];if(!c.every(p=>Go(u,p)))continue;let d={...a.material};if(a.colorScale){let p=u.metrics?.[a.colorScale.metric],f=typeof p=="number"?at(a.colorScale.stops,p):null;f&&(d={...d,[a.colorScale.channel??"baseColor"]:f})}if(a.pulse){let p=a.pulse===!0?{}:a.pulse;n[l]={color:p.color??zo,speed:p.speed!==void 0&&p.speed>0?p.speed:1};let f=d.emissiveIntensity??o.get(l)?.emissiveIntensity??u.style?.material?.emissiveIntensity;f!==void 0&&f>0||(d.emissiveIntensity=1)}Object.keys(d).length>0&&o.set(l,{...o.get(l),...d})}}if(o.size===0)return{bindings:e,pulses:n,sourceOf:Kt};let r={...e},s=new WeakMap;for(let[a,i]of o){let c=e[a],l={...c,style:{...c.style,material:{...c.style?.material,...i}}};r[a]=l,s.set(l,c)}return{bindings:r,pulses:n,sourceOf:a=>s.get(a)??a}}function qe(e,t,o){let n=o.find(s=>s.variants.some(a=>a.name===t)),r=new Set(n?.variants.map(s=>s.name)??[t]);return[...e.filter(s=>!r.has(s)),t]}var Ko=.12,Xt=new Set;function ct(e,t){return t?new Set(Q(e,t.target)):Xt}function Yt(e,t){let o=ct(e.bindings,t);if(!t||o.size===0)return{...e,setAside:Xt};let n=Math.min(Math.max(t.ghostOpacity??Ko,0),1),r={...e.bindings},s=new WeakMap,a=new Set;for(let[i,c]of Object.entries(e.bindings)){if(o.has(i))continue;a.add(i);let l=t.mode==="hide"?{...c,visible:!1}:{...c,style:{...c.style,material:{...c.style?.material,opacity:Math.min(c.style?.material?.opacity??1,n)}}};r[i]=l,s.set(l,e.sourceOf(c))}return{bindings:r,pulses:e.pulses,sourceOf:i=>s.get(i)??e.sourceOf(i),setAside:a}}var Wo=require("three"),lt=Symbol("react-immersive.model-node-id");function Xo(e,t){Object.defineProperty(e,lt,{value:t,configurable:!0})}function Ge(e){let t=new Map;e.traverse(c=>{if(!c.name)return;let l=t.get(c.name);l?l.push(c):t.set(c.name,[c])});let o=Object.create(null),n=new WeakMap,r=new Map,s=new Set(Array.from(t,([c,l])=>l.length===1?c:null).filter(c=>c!==null)),a=new Set,i=(c,l)=>{Xo(c,l),o[l]=c,n.set(c,l),a.add(l)};for(let[c,l]of t)l.length===1&&i(l[0],c);for(let[c,l]of t){if(l.length<2)continue;let u=[];l.forEach((d,p)=>{let f=`${c} [${p+1}]`,C=f,R=2;for(;s.has(C)||a.has(C);)C=`${f}.${R++}`;i(d,C),u.push(C)}),r.set(c,u)}return{nodesById:o,idByNode:n,duplicateNames:r}}function Ee(e){return e[lt]??e.name??null}function Jt(e,t){let o=null,n=[];return e.traverse(r=>{r[lt]===t&&(o=r),r.name===t&&n.push(r)}),o??(n.length===1?n[0]:null)}var Ve=Object.freeze([{id:"change-color",label:"Change Color",handling:"viewer",description:"Opens a color picker docked under the action and commits the result to style.material.baseColor."},{id:"change-material",label:"Change Material",handling:"viewer",description:"Opens the material picker so the viewer can swap the object's texture."},{id:"add-text",label:"Add Text",handling:"viewer",description:"Opens a text box docked under the action; the viewer's user types, clicks the object to place it, and can resize, turn, move, or remove it. Saved to the binding's decals."},{id:"add-image",label:"Add Image",handling:"viewer",description:"Lets the viewer's user choose an image, click the object to place it, and resize, turn, move, or remove it. Saved to the binding's decals."},{id:"toggle-visibility",label:"Toggle Visibility",handling:"viewer",description:"Flips the binding's visible flag."},{id:"toggle-light",label:"Toggle Light",handling:"viewer",description:"Turns the scene lights attached to this object on or off, or the object's own glow when none is attached."},{id:"change-light-color",label:"Change Light Color",handling:"viewer",description:"Opens a color picker docked under the action for the scene lights attached to this object, or the object's own glow."},{id:"set-brightness",label:"Set Brightness",handling:"viewer",description:"Opens a brightness slider docked under the action for the scene lights attached to this object, or the object's own glow."}]);function Zt(e){return Ve.find(t=>t.id===e)}var ni=Ve.filter(e=>e.handling==="viewer").map(e=>e.id),oi=new Set(["","New Action",...Ve.map(e=>e.label)]);var ge=require("three");function He(e){return Number.isFinite(e)&&e>0?e:1}function Qt(e){return e?.loopMode??"repeat"}function Yo(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}function Jo(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ut(e){let t=e.toLowerCase();return t.includes("light")?"light":t.includes("wheel")||t.includes("rim")||t.includes("tire")?"wheel":t.includes("glass")||t.includes("window")||t.includes("windshield")||t.includes("sunroof")?"glass":t.includes("seat")||t.includes("dashboard")||t.includes("console")||t.includes("doorpanel")?"interior":t.includes("floor")?"floor":t.includes("wall")?"wall":t.includes("door")?"door":t.includes("chair")||t.includes("table")||t.includes("sofa")||t.includes("bed")?"furniture":"other"}function Zo(e,t=!0){return e==="light"||e.endsWith("light")?[{id:"toggle-light",label:"Toggle Light",type:"command"},{id:"change-light-color",label:"Change Light Color",type:"command"},{id:"set-brightness",label:"Set Brightness",type:"command"}]:[{id:"change-color",label:"Change Color",type:"command"},...t?[{id:"change-material",label:"Change Material",type:"command"}]:[],{id:"toggle-visibility",label:"Toggle Visibility",type:"command"}]}function dt(e,t=!0){let o=ut(e);return{id:Yo(e),modelObjectId:e,type:o,label:Jo(e),status:"normal",selectable:!0,hoverable:!0,visible:!0,style:{},actions:Zo(o,t),metrics:{},metadata:{}}}function en(e,t){return Object.fromEntries(e.map(o=>[o,dt(o,!t?.has(o))]))}var tn=["front","back","double"],nn=["normal","additive"];var on={enabled:!1,axis:"y",position:.5,flip:!1},Qo={clips:[],autoplayClip:null},er={autofocus:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6,target:[0,0,0],mouse:!0,debug:0,manual:!1,smoothTime:.25},toneMapping:{enabled:!1,mode:"aces",exposure:1,resolution:256,whitePoint:4,middleGrey:.6,minLuminance:.01,averageLuminance:1,adaptationRate:1},brightnessContrast:{enabled:!1,brightness:0,contrast:0},hueSaturation:{enabled:!1,hue:0,saturation:0},colorAverage:{enabled:!1},dotScreen:{enabled:!1,angle:Math.PI/2,scale:1},glitch:{enabled:!1,mode:"sporadic",delay:[1.5,3.5],duration:[.6,1],strength:[.3,1],chromaticAberrationOffset:[0,0],columns:.05,ratio:.85},ssao:{enabled:!1,samples:30,rings:4,intensity:8,radius:.25,bias:.025,luminanceInfluence:.6,fade:.01,minRadiusScale:.33,worldDistanceThreshold:20,worldDistanceFalloff:5,worldProximityThreshold:6,worldProximityFalloff:3},bloom:{enabled:!1,intensity:.3,luminanceThreshold:.9,luminanceSmoothing:.2,mipmapBlur:!0,radius:0,levels:8},godRays:{enabled:!1,sunPosition:[5,10,5],samples:60,density:.96,decay:.9,weight:.4,exposure:.6,clampMax:1,blur:!0,kernelSize:"small"},grid:{enabled:!1,scale:1,lineWidth:0},noise:{enabled:!1,opacity:1,premultiply:!1},depthOfField:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6},chromaticAberration:{enabled:!1,offsetX:.002,offsetY:.002,radialModulation:!1,modulationOffset:.15},lensflare:{enabled:!1,lensPosition:[-25,6,-60],smoothTime:.07,glareSize:.2,flareSize:.01,flareSpeed:.01,flareShape:.01,animated:!0,anamorphic:!1,colorGain:"#141414",haloScale:.5,secondaryGhosts:!0,aditionalStreaks:!0,ghostScale:0,opacity:1,starBurst:!1},vignette:{enabled:!1,offset:.3,darkness:.3,eskil:!1},smaa:{enabled:!1},sepia:{enabled:!1,intensity:0},scanline:{enabled:!1,density:1.25},pixelation:{enabled:!1,granularity:5},outline:{enabled:!1,selectionLayer:10,edgeStrength:2.5,pulseSpeed:0,visibleEdgeColor:"#ffffff",hiddenEdgeColor:"#22090a",kernelSize:"large",blur:!1,xRay:!0},selectiveBloom:{enabled:!1,selectionLayer:10,intensity:1,luminanceThreshold:.9,luminanceSmoothing:.025,kernelSize:"large",mipmapBlur:!0,inverted:!1,ignoreBackground:!1},ramp:{enabled:!1,rampType:"linear",rampStart:[.5,.5],rampEnd:[1,1],startColor:"#000000",endColor:"#ffffff",opacity:.5,rampBias:.5,rampGain:.5,rampMask:!1,rampInvert:!1}},be={model:{rotation:[0,0,0],showAdvancedRotation:!1,renderer:"pbr",shading:"lit",autoRotate:!1,autoRotateSpeed:1},camera:{fieldOfView:50,showAdvancedSettings:!1},lighting:{ambient:{intensity:.25,color:"#ffffff"},lights:[{id:"light-hemi",type:"hemisphere",color:"#ffffff",intensity:.3,position:[0,1,0],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0},{id:"light-key",type:"directional",color:"#ffffff",intensity:2.5,position:[6,12,6],attachedToCamera:!1,castShadow:!0,shadowBias:-5e-4,visible:!0},{id:"light-fill",type:"directional",color:"#ffffff",intensity:0,position:[-6,8,-6],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0}]},shadows:{enabled:!0,mapSize:2048,bias:-5e-4,normalBias:.02,radius:3},environment:{source:"preset",preset:"apartment",customEnvironmentUrl:"",intensity:.25,rotation:0,shadowLight:{enabled:!1,intensity:2.5,bias:-5e-4}},wireframe:{enabled:!1,color:"#000000",opacity:1},background:{enabled:!1,type:"color",color:"#1c1c1d",imageUrl:""},groundShadows:{enabled:!1,mode:"shadowCatcher",intensity:.7,borderFade:1,height:0,size:10},postProcessing:er,animations:Qo,annotations:[]};function De(e){let t=u=>{throw new Error(`Invalid section: ${u}`)},o=u=>u&&typeof u=="object"&&!Array.isArray(u)?u:t("expected an object"),n=u=>typeof u=="string"&&u.trim().length>0&&u.length<=200?u:t("expected a nonempty name or id (up to 200 characters)"),r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0&&u<=1?u:t("position must be between 0 and 1"),s=u=>!Array.isArray(u)||u.length!==3||!u.every(d=>typeof d=="number"&&Number.isFinite(d))||Math.hypot(...u)<1e-8?t("normal must be a finite, nonzero vector"):[...u],a=u=>{let d=o(u);return!["x","y","z"].includes(d.axis)||typeof d.enabled!="boolean"||typeof d.flip!="boolean"?t("invalid plane"):{enabled:d.enabled,axis:d.axis,position:r(d.position),flip:d.flip,...d.normal!==void 0?{normal:s(d.normal)}:{}}},i=u=>{let d=o(u),p=a(d);if(d.mode!==void 0){if(!["plane","planes","box"].includes(d.mode))return t("invalid mode");p.mode=d.mode}if(d.planes!==void 0){if(!Array.isArray(d.planes)||d.planes.length>6)return t("at most six planes are supported");let f=new Set;p.planes=d.planes.map(C=>{let R=o(C),S=n(R.id);return f.has(S)?t("duplicate plane id"):(f.add(S),{...a(R),id:S,name:n(R.name)})})}if(d.activePlaneId!==void 0&&(p.activePlaneId=n(d.activePlaneId)),d.invertBox!==void 0){if(typeof d.invertBox!="boolean")return t("invalid box inversion");p.invertBox=d.invertBox}if(d.box!==void 0){let f=o(d.box),C=w=>!Array.isArray(w)||w.length!==3?t("invalid box bounds"):w.map(r),R=C(f.min),S=C(f.max);if(R.some((w,A)=>w>=S[A]))return t("box minimum must be below its maximum on every axis");p.box={min:R,max:S}}return p},c=o(e),l=i(c);if(c.presets!==void 0){if(!Array.isArray(c.presets)||c.presets.length>32)return t("at most 32 presets are supported");let u=new Set;l.presets=c.presets.map(d=>{let p=o(d),f=n(p.id);return u.has(f)?t("duplicate preset id"):(u.add(f),{id:f,name:n(p.name),settings:i(p.settings)})})}return l}function rn(e){let{presets:t,...o}=De(e);return o}var ft=require("three"),gt=["position","rotation","scale","visible","baseColor","emissive","opacity","roughness","metalness","emissiveIntensity"],bt=["linear","ease-in","ease-out","ease-in-out","step"],tr=new Set(["position","rotation","scale"]),nr=new Set(["baseColor","emissive"]),ye=e=>typeof e=="string"&&e.length>0&&e.length<=256,xe=e=>typeof e=="number"&&Number.isFinite(e),mt=e=>Array.isArray(e)&&e.length===3&&e.every(xe);function Ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Se(e){throw new Error(`Invalid sequences: ${e}`)}function or(e){return e.kind==="object"?JSON.stringify([e.kind,e.objectId,e.property]):e.kind==="clip"?JSON.stringify([e.kind,e.clip]):"camera"}function rr(e,t){if(t.kind==="camera")return Ne(e)&&mt(e.position)&&mt(e.target)&&(e.fov===null||xe(e.fov)&&e.fov>0&&e.fov<180)&&xe(e.zoom)&&e.zoom>0;if(t.kind==="clip")return xe(e)&&e>=0;let o=t.property;return tr.has(o)?mt(e)&&(o!=="scale"||e.every(n=>n!==0)):nr.has(o)?typeof e=="string"&&/^#[\da-f]{6}$/i.test(e):o==="visible"?typeof e=="boolean":xe(e)&&e>=0&&(o==="emissiveIntensity"||e<=1)}function Oe(e){(!Array.isArray(e)||e.length>64)&&Se("expected up to 64 sequences.");let t=new Set,o=0;return e.map(n=>{(!Ne(n)||!ye(n.id)||t.has(n.id)||!(typeof n.name=="string"&&ye(n.name.trim()))||!xe(n.duration)||n.duration<.1||n.duration>3600||typeof n.loop!="boolean"||typeof n.autoPlay!="boolean"||!Array.isArray(n.tracks)||n.tracks.length>128)&&Se("each sequence needs a unique id, name, 0.1\u20133600 second duration, loop/autoplay flags and up to 128 tracks."),t.add(n.id);let r=new Set,s=new Set,a=n.tracks.map(i=>{(!Ne(i)||!ye(i.id)||r.has(i.id)||!(typeof i.name=="string"&&ye(i.name.trim()))||!Ne(i.target)||!Array.isArray(i.keyframes)||i.keyframes.length>2048||i.muted!==void 0&&typeof i.muted!="boolean")&&Se("invalid or duplicate track."),r.add(i.id);let c;i.target.kind==="camera"?c={kind:"camera"}:i.target.kind==="clip"&&ye(i.target.clip)?c={kind:"clip",clip:i.target.clip}:i.target.kind==="object"&&ye(i.target.objectId)&&gt.includes(i.target.property)?c={kind:"object",objectId:i.target.objectId,property:i.target.property}:Se("unknown track target or property.");let l=or(c);s.has(l)&&Se("only one track may own each target property in a sequence."),s.add(l);let u=new Set,d=new Set,p=i.keyframes.map(f=>{++o>2e4&&Se("too many keyframes."),(!Ne(f)||!ye(f.id)||u.has(f.id)||!xe(f.time)||f.time<0||f.time>n.duration||d.has(f.time)||f.easing!==void 0&&!bt.includes(f.easing)||!rr(f.value,c))&&Se("keyframes need unique ids/times, valid values and times inside the sequence."),u.add(f.id),d.add(f.time);let C=f.value,R=c.kind==="camera"?{position:[...C.position],target:[...C.target],fov:C.fov,zoom:C.zoom}:Array.isArray(f.value)?[...f.value]:f.value;return{id:f.id,time:f.time,value:R,...f.easing?{easing:f.easing}:{}}}).sort((f,C)=>f.time-C.time);return{id:i.id,name:i.name.trim(),target:c,keyframes:p,...i.muted!==void 0?{muted:i.muted}:{}}});return{id:n.id,name:n.name.trim(),duration:n.duration,loop:n.loop,autoPlay:n.autoPlay,tracks:a}})}function ir(e,t="ease-in-out"){let o=Math.max(0,Math.min(1,e));return t==="step"?0:t==="ease-in"?o*o:t==="ease-out"?1-(1-o)**2:t==="ease-in-out"?o*o*(3-2*o):o}var Ke=(e,t,o)=>e+(t-e)*o,pt=(e,t,o)=>e.map((n,r)=>Ke(n,t[r],o));function We(e,t){if(e.muted||!e.keyframes.length||!Number.isFinite(t))return null;let o=e.keyframes;if(t<o[0].time)return null;let n=o[0],r;for(let c of o)if(c.time<=t)n=c;else{r=c;break}if(!r||typeof n.value=="boolean")return structuredClone(n.value);let s=ir((t-n.time)/(r.time-n.time),n.easing);if(typeof n.value=="number"&&typeof r.value=="number")return Ke(n.value,r.value,s);if(typeof n.value=="string"&&typeof r.value=="string")return`#${new ft.Color(n.value).lerp(new ft.Color(r.value),s).getHexString()}`;if(Array.isArray(n.value)&&Array.isArray(r.value))return pt(n.value,r.value,s);let a=n.value,i=r.value;return{position:pt(a.position,i.position,s),target:pt(a.target,i.target,s),fov:a.fov!==null&&i.fov!==null?Ke(a.fov,i.fov,s):a.fov,zoom:Ke(a.zoom,i.zoom,s)}}function sn(e,t){return{...e,keyframes:[...e.keyframes.filter(o=>o.id!==t.id&&Math.abs(o.time-t.time)>1e-6),t].sort((o,n)=>o.time-n.time)}}var ee=require("three");function ht(e){return e.id??e.url}function je(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected an asset transform object.");let t={};for(let o of["position","rotation","scale"]){let n=e[o];if(n!==void 0){if(!Array.isArray(n)||n.length!==3||!n.every(r=>typeof r=="number"&&Number.isFinite(r))||o==="scale"&&n.some(r=>r===0))throw new Error(`Invalid asset ${o}: expected three finite ${o==="scale"?"nonzero ":""}numbers.`);t[o]=[...n]}}return t}function an(e,t){if(!Number.isFinite(t)||t<=0)throw new Error("Grid size must be positive.");let o=je(e),[n,r,s]=o.position??[0,0,0];return{...o,position:[Math.round(n/t)*t,r,Math.round(s/t)*t]}}function cn(e,t){let o=je(e),n=o.position??[0,0,0],r=new ee.Matrix4().compose(new ee.Vector3(...n),new ee.Quaternion().setFromEuler(new ee.Euler(...o.rotation??[0,0,0])),new ee.Vector3(...o.scale??[1,1,1])),s=new ee.Box3(new ee.Vector3(...t.min),new ee.Vector3(...t.max)).applyMatrix4(r);if(!Number.isFinite(s.min.y))throw new Error("Cannot place an asset with empty bounds.");return{...o,position:[n[0],n[1]-s.min.y,n[2]]}}var ue=require("three"),sr=new Map,yt={color:"#93c5fd",intensity:.07},Si=new ue.Color(yt.color).multiplyScalar(yt.intensity),xi=new ue.Color(yt.color);var ar=new Map;function ln(e){return ar.get(e)}function un(e){for(let t of sr.values())if(t.texture.source===e.source&&(!t.loaded||t.failed))return!0;return!1}var H=require("three");function dn(e){if(e.length!==3)return null;let t=new H.Vector3(...e[0]).sub(new H.Vector3(...e[1])),o=new H.Vector3(...e[2]).sub(new H.Vector3(...e[1]));return t.lengthSq()===0||o.lengthSq()===0?null:Math.acos(Math.max(-1,Math.min(1,t.normalize().dot(o.normalize()))))*180/Math.PI}function mn(e,t){if(!e.normal)return null;let o=new H.Vector3(...e.normal);if(o.lengthSq()===0)return null;o.normalize();let n=new H.Vector3(...t),r=n.clone().sub(new H.Vector3(...e.position)).dot(o);return{distance:Math.abs(r),projection:n.addScaledVector(o,-r).toArray()}}function pn(e){if(e.length<3)return{error:"Pick at least three points to finish the area."};let t=new H.Vector3(...e[0]),o=e.map(S=>new H.Vector3(...S).sub(t)),n=Math.max(...o.map(S=>S.length()));if(n===0)return{error:"Area points must be distinct."};let r=new H.Vector3;for(let S=1;S<o.length-1;S+=1){let w=o[S].clone().cross(o[S+1]);w.lengthSq()>r.lengthSq()&&r.copy(w)}if(r.length()<=n*n*1e-10)return{error:"Area points must not lie on one straight line."};r.normalize();let s=Math.max(n*1e-5,Number.EPSILON*Math.max(...e.flat().map(Math.abs))*32);if(o.some(S=>Math.abs(S.dot(r))>s))return{error:"Area points must lie on one plane."};let a=o.find(S=>S.length()>n*1e-10).clone().normalize(),i=r.clone().cross(a).normalize(),c=o.map(S=>new H.Vector2(S.dot(a),S.dot(i))),l=(S,w,A)=>(w.x-S.x)*(A.y-S.y)-(w.y-S.y)*(A.x-S.x),u=n*n*1e-10,d=(S,w,A)=>Math.abs(l(S,w,A))<=u&&A.x>=Math.min(S.x,w.x)-n*1e-10&&A.x<=Math.max(S.x,w.x)+n*1e-10&&A.y>=Math.min(S.y,w.y)-n*1e-10&&A.y<=Math.max(S.y,w.y)+n*1e-10;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length];if(w.distanceTo(A)<=n*1e-10)return{error:"Area points must be distinct."};for(let h=S+1;h<c.length;h+=1){if(h===S+1||S===0&&h===c.length-1)continue;let x=c[h],M=c[(h+1)%c.length],E=l(w,A,x),j=l(w,A,M),D=l(x,M,w),g=l(x,M,A);if(E*j<0&&D*g<0||d(w,A,x)||d(w,A,M)||d(x,M,w)||d(x,M,A))return{error:"Area edges must not cross or touch each other."}}}let p=0,f=0,C=0;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length],h=w.x*A.y-A.x*w.y;p+=h,f+=(w.x+A.x)*h,C+=(w.y+A.y)*h}if(Math.abs(p)<=u)return{error:"The polygon has no measurable area."};let R=t.clone().addScaledVector(a,f/(3*p)).addScaledVector(i,C/(3*p));return{area:Math.abs(p)/2,center:R.toArray(),triangles:H.ShapeUtils.triangulateShape(c,[])}}function fn(e,t){if(e.length<2)return 0;let o=0;for(let n=1;n<e.length;n+=1)o+=new H.Vector3(...e[n]).distanceTo(new H.Vector3(...e[n-1]));return t&&(o+=new H.Vector3(...e[e.length-1]).distanceTo(new H.Vector3(...e[0]))),o}var xt=["m","cm","mm","in","ft"],St={m:1,cm:.01,mm:.001,in:.0254,ft:.3048},cr=["distance","angle","area","pointToPlane","wrap","wrapHorizontal"];function wt(e){return xt.includes(e)}function Mt(e={},t="m"){let o=e.displayUnit??t,n=e.metersPerUnit??St[e.sourceUnit??"m"];if(!Number.isFinite(n)||n<=0)throw new Error("Measurement scale must be a positive finite number.");return{displayUnit:o,metersPerUnit:n,factor:wt(o)?n/St[o]:1}}function gn(e,t,o,n={}){if(!wt(o)||!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)throw new Error("Calibration needs two distinct points and a positive known distance.");let r=t*St[o]/e;if(!Number.isFinite(r)||r<=0)throw new Error("Calibration scale is outside the supported range.");return{...n,metersPerUnit:r}}function Xe(e,t){let o=t.map(n=>n.position);if(e==="angle"){let n=dn(o);return n===null?null:{value:n,dimension:0}}if(e==="area"){let n=pn(o);return"error"in n?null:{value:n.area,dimension:2}}if(e==="pointToPlane"){let n=t.length===2?mn(t[0],t[1].position):null;return n?{value:n.distance,dimension:1}:null}return t.length<(e==="distance"?2:3)?null:{value:fn(o,e!=="distance"),dimension:1}}function At(e,t={},o="m",n=e.points,r=e.approximate?"approximate":"ready"){let s=Xe(e.tool,n),{factor:a,displayUnit:i}=Mt(t,o),c=r==="ready"||r==="approximate",l=c&&s?s.value*a**s.dimension:null;return{id:e.id,status:c?s&&l!==null&&Number.isFinite(l)?r:"invalid":r,rawValue:c&&s&&Number.isFinite(s.value)?s.value:null,value:l!==null&&Number.isFinite(l)?l:null,unit:e.tool==="angle"?"\xB0":e.tool==="area"?`${i}\xB2`:i}}function we(e){function t(){throw new Error("Invalid measurements: expected settings and valid named measurements with finite points.")}let o=i=>!!i&&typeof i=="object"&&!Array.isArray(i),n=i=>Array.isArray(i)&&i.length===3&&i.every(c=>typeof c=="number"&&Number.isFinite(c));typeof e=="string"&&(e.length>5*1024*1024&&t(),e=JSON.parse(e)),(!o(e)||e.version!==void 0&&e.version!==1||!o(e.settings)||!Array.isArray(e.items)||e.items.length>256)&&t();let r={};for(let i of["sourceUnit","displayUnit"])e.settings[i]!==void 0&&(wt(e.settings[i])||t(),r[i]=e.settings[i]);e.settings.metersPerUnit!==void 0&&((typeof e.settings.metersPerUnit!="number"||!Number.isFinite(e.settings.metersPerUnit)||e.settings.metersPerUnit<=0)&&t(),r.metersPerUnit=e.settings.metersPerUnit);let s=new Set,a=e.items.map(i=>{(!o(i)||typeof i.id!="string"||!i.id||s.has(i.id)||typeof i.name!="string"||!i.name.trim()||typeof i.modelId!="string"||!i.modelId||!cr.includes(i.tool)||!Array.isArray(i.points)||i.points.length>8192||typeof i.createdAt!="string"||!Number.isFinite(Date.parse(i.createdAt)))&&t(),s.add(i.id),i.tilesetUrl!==void 0&&i.tilesetUrl!==null&&typeof i.tilesetUrl!="string"&&t(),(i.visible!==void 0&&typeof i.visible!="boolean"||i.approximate!==void 0&&typeof i.approximate!="boolean")&&t();let c=new Set,l=i.points.map(d=>{if((!o(d)||typeof d.id!="number"||!Number.isFinite(d.id)||!n(d.position))&&t(),c.has(d.id)&&t(),c.add(d.id),d.normal!==void 0&&!n(d.normal)&&t(),d.faceVertices!==void 0&&(!Array.isArray(d.faceVertices)||d.faceVertices.length!==3||!d.faceVertices.every(n))&&t(),d.snapped!==void 0&&!["vertex","edge"].includes(d.snapped)&&t(),d.anchor!==void 0){let f=d.anchor;(!o(f)||typeof f.nodeId!="string"||!f.nodeId||!n(f.localPosition)||typeof f.geometrySignature!="string"||typeof f.poseSignature!="string")&&t(),f.localNormal!==void 0&&!n(f.localNormal)&&t(),f.localFaceVertices!==void 0&&(!Array.isArray(f.localFaceVertices)||f.localFaceVertices.length!==3||!f.localFaceVertices.every(n))&&t(),f.instanceId!==void 0&&(!Number.isInteger(f.instanceId)||f.instanceId<0)&&t()}let p=d.anchor;return{id:d.id,position:[...d.position],...d.normal?{normal:[...d.normal]}:{},...d.faceVertices?{faceVertices:d.faceVertices.map(f=>[...f])}:{},...d.snapped?{snapped:d.snapped}:{},...p?{anchor:{nodeId:p.nodeId,localPosition:[...p.localPosition],geometrySignature:p.geometrySignature,poseSignature:p.poseSignature,...p.localNormal?{localNormal:[...p.localNormal]}:{},...p.localFaceVertices?{localFaceVertices:p.localFaceVertices.map(f=>[...f])}:{},...p.instanceId!==void 0?{instanceId:p.instanceId}:{}}}:{}}}),u={id:i.id,name:i.name,modelId:i.modelId,tool:i.tool,points:l,createdAt:i.createdAt,...i.tilesetUrl!==void 0?{tilesetUrl:i.tilesetUrl}:{},...i.visible!==void 0?{visible:i.visible}:{},...i.approximate!==void 0?{approximate:i.approximate}:{}};return Xe(u.tool,l)||t(),u});return{settings:r,items:a}}function bn(e){return JSON.stringify({version:1,...we(e)},null,2)}function hn(e,t,o="m"){let n=we(e),r=new Map(t?.map(a=>[a.id,a])),s=a=>{let i=String(a??"");return/^[=+@-]/.test(i)&&(i=`'${i}`),`"${i.replace(/"/g,'""')}"`};return[["id","name","modelId","type","status","value","unit","createdAt"],...n.items.map(a=>{let i=r.get(a.id)??At(a,n.settings,o);return[a.id,a.name,a.modelId,a.tool,i.status,i.value,i.unit,a.createdAt]})].map(a=>a.map(s).join(",")).join(`\r
2
- `)}function Ye(e){if(!Array.isArray(e)||e.length>128)throw new Error("Invalid selections: expected up to 128 named selection sets.");let t=new Set;return e.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||t.has(o.id)||typeof o.name!="string"||!o.name.trim()||o.name.length>200||!Array.isArray(o.objectIds)||o.objectIds.length>1e5||o.objectIds.some(n=>typeof n!="string"||!n))throw new Error("Invalid selections: each set needs a unique id, a name, and model object ids.");return t.add(o.id),{id:o.id,name:o.name.trim(),objectIds:[...new Set(o.objectIds)]}})}var Sn=new Set(["__proto__","constructor","prototype"]),vt=(e,t)=>e<t?-1:e>t?1:0;function _(e){throw new Error(`Invalid product: ${e}`)}var Y=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Le=e=>typeof e=="string"&&e.length>0&&e.length<=200&&!Sn.has(e),de=e=>typeof e=="string"&&e.trim().length>0&&e.length<=500;function xn(e){let t=0;function o(n,r){return(++t>1e5||r>32)&&_("definition is too complex."),n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)?n:Array.isArray(n)?n.map(s=>o(s,r+1)):(Y(n)||_("expected JSON data."),Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0).map(([s,a])=>(Sn.has(s)&&_("reserved property name."),[s,o(a,r+1)]))))}return o(e,0)}function lr(e){if(typeof e!="string"||e.length>2048)return!1;try{return["http:","https:"].includes(new URL(e.replace(/\{[a-zA-Z]+\}/g,"x")).protocol)}catch{return!1}}function Ct(e){let t=xn(typeof e=="string"?JSON.parse(e):e);(!Y(t)||!Le(t.id)||!de(t.label)||!Le(t.revision)||!Array.isArray(t.groups)||!t.groups.length||t.groups.length>64)&&_("id, label, revision, and 1\u201364 option groups are required.");let o=new Map;for(let r of t.groups){(!Y(r)||!Le(r.id)||o.has(r.id)||!de(r.label)||r.required!==void 0&&typeof r.required!="boolean"||!Array.isArray(r.options)||!r.options.length||r.options.length>128)&&_("groups need unique ids, labels, and 1\u2013128 options.");let s=new Set;o.set(r.id,s);for(let a of r.options)if((!Y(a)||!Le(a.id)||s.has(a.id)||!de(a.label)||a.sku!==void 0&&!de(a.sku))&&_("options need unique ids and labels."),s.add(a.id),a.description!==void 0&&!de(a.description)&&_("an option description must be text."),a.swatch!==void 0&&!(typeof a.swatch=="string"&&/^#[0-9a-f]{3,8}$/i.test(a.swatch))&&_("a swatch must be a hex color."),a.priceDeltaMinor!==void 0&&!Number.isSafeInteger(a.priceDeltaMinor)&&_("a price change must be a whole number of minor units."),a.variants!==void 0&&(!Array.isArray(a.variants)||a.variants.some(i=>!de(i)))&&_("variant names must be strings."),a.appearance!==void 0){(!Array.isArray(a.appearance)||a.appearance.length>128)&&_("invalid appearance edits.");for(let i of a.appearance){Y(i)||_("invalid appearance edit.");let c=i.target;typeof c=="string"&&c||Array.isArray(c)&&c.every(l=>typeof l=="string"&&!!l)||Y(c)&&Object.keys(c).length===1&&["group","tag","type"].some(l=>typeof c[l]=="string")||_("appearance needs an object id, id list, or selector."),i.visible!==void 0&&typeof i.visible!="boolean"&&_("visibility must be boolean."),i.material!==void 0&&!Y(i.material)&&_("material must be an object.");for(let l of Object.values(i.material??{}))typeof l=="string"||typeof l=="number"||typeof l=="boolean"||l===null||Y(l)&&typeof l.path=="string"&&(l.offset===void 0||Array.isArray(l.offset)&&l.offset.length===2&&l.offset.every(u=>typeof u=="number"))||_("invalid material field.")}}r.defaultOptionId!==void 0&&!s.has(r.defaultOptionId)&&_("a default must name an option in its group."),r.display!==void 0&&!["list","chips","swatches"].includes(r.display)&&_("a group's display must be list, chips or swatches.")}t.pricing!==void 0&&!(Y(t.pricing)&&/^[A-Z]{3}$/.test(t.pricing.currency)&&Number.isSafeInteger(t.pricing.basePriceMinor)&&t.pricing.basePriceMinor>=0)&&_("pricing needs a 3-letter currency and a base price of zero or more."),t.checkout!==void 0&&(!Y(t.checkout)||t.checkout.label!==void 0&&!de(t.checkout.label)||!lr(t.checkout.urlTemplate))&&_("a checkout link needs an http or https URL.");let n=r=>Y(r)&&typeof r.groupId=="string"&&typeof r.optionId=="string"&&!!o.get(r.groupId)?.has(r.optionId);if(t.rules!==void 0){(!Array.isArray(t.rules)||t.rules.length>2048)&&_("invalid rules.");let r=new Set;for(let s of t.rules){(!Y(s)||!Le(s.id)||r.has(s.id)||!n(s.when)||s.message!==void 0&&!de(s.message))&&_("rules need unique ids and valid option references."),r.add(s.id),["requires","excludes"].some(a=>Array.isArray(s[a])&&s[a].length>0)||_("a rule needs a requires or excludes constraint.");for(let a of["requires","excludes"])s[a]!==void 0&&(!Array.isArray(s[a])||s[a].length>128||!s[a].every(n))&&_("rule references must name existing options.")}}if(t.skus!==void 0){(!Array.isArray(t.skus)||t.skus.length>4096)&&_("invalid SKU table.");let r=new Set;for(let s of t.skus){(!Y(s)||!de(s.sku)||!Y(s.selections)||Object.keys(s.selections).length!==o.size)&&_("SKU mappings need one selection per group.");for(let[i,c]of Object.entries(s.selections))(!o.has(i)||c!==null&&!o.get(i).has(c))&&_("SKU mapping references an unknown option.");let a=JSON.stringify(Object.entries(s.selections).sort(([i],[c])=>vt(i,c)));r.has(a)&&_("a combination can map to only one SKU."),r.add(a)}}return{id:t.id,label:t.label,revision:t.revision,groups:t.groups.map(r=>({id:r.id,label:r.label,...r.required!==void 0?{required:r.required}:{},...r.defaultOptionId!==void 0?{defaultOptionId:r.defaultOptionId}:{},...r.display!==void 0?{display:r.display}:{},options:r.options.map(s=>({id:s.id,label:s.label,...s.sku!==void 0?{sku:s.sku}:{},...s.description!==void 0?{description:s.description}:{},...s.swatch!==void 0?{swatch:s.swatch}:{},...s.priceDeltaMinor!==void 0?{priceDeltaMinor:s.priceDeltaMinor}:{},...s.variants!==void 0?{variants:s.variants}:{},...s.appearance!==void 0?{appearance:s.appearance.map(a=>({target:a.target,...a.material!==void 0?{material:a.material}:{},...a.visible!==void 0?{visible:a.visible}:{}}))}:{}}))})),...t.rules!==void 0?{rules:t.rules.map(r=>({id:r.id,when:r.when,...r.requires?{requires:r.requires}:{},...r.excludes?{excludes:r.excludes}:{},...r.message?{message:r.message}:{}}))}:{},...t.skus!==void 0?{skus:t.skus.map(r=>({sku:r.sku,selections:r.selections}))}:{},...t.pricing!==void 0?{pricing:{currency:t.pricing.currency,basePriceMinor:t.pricing.basePriceMinor}}:{},...t.checkout!==void 0?{checkout:{urlTemplate:t.checkout.urlTemplate,...t.checkout.label!==void 0?{label:t.checkout.label}:{}}}:{}}}function Te(e){return Object.fromEntries(e.groups.map(t=>[t.id,t.defaultOptionId??null]))}function ur(e,t){let o=[];for(let n of e.groups){if(t[n.id]===null)continue;let r=n.options.find(s=>s.id===t[n.id])?.sku;if(!r)return null;o.push(r)}return o.length?o.join("-"):null}function ae(e,t=Te(e),o=1){if(!Number.isSafeInteger(o)||o<1||o>9999)throw new Error("Quantity must be an integer from 1 to 9999.");if(!Y(t)||Object.values(t).some(u=>u!==null&&typeof u!="string"))throw new Error("Product selections must map group ids to option ids or null.");let n=[],r=[...e.groups].sort((u,d)=>vt(u.id,d.id)),s=Object.fromEntries(r.map(u=>[u.id,!Object.prototype.hasOwnProperty.call(t,u.id)||t[u.id]===void 0?u.defaultOptionId??null:t[u.id]]));for(let u of Object.keys(t).sort())e.groups.some(d=>d.id===u)||n.push({code:"unknown-group",groupIds:[u],message:`Unknown option group: ${u}.`});let a=[];for(let u of r){let d=s[u.id],p=u.options.find(f=>f.id===d);d!==null&&!p?n.push({code:"unknown-option",groupIds:[u.id],message:`Unknown choice for ${u.label}: ${d}.`}):u.required&&d===null&&n.push({code:"required",groupIds:[u.id],message:`Choose ${u.label}.`}),p&&a.push({groupId:u.id,optionId:p.id,label:p.label,...p.sku?{sku:p.sku}:{}})}let i=u=>e.groups.find(d=>d.id===u.groupId)?.options.find(d=>d.id===u.optionId)?.label??u.optionId;for(let u of[...e.rules??[]].sort((d,p)=>vt(d.id,p.id)))if(s[u.when.groupId]===u.when.optionId){for(let d of u.requires??[])s[d.groupId]!==d.optionId&&n.push({code:"requires",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} requires ${i(d)}.`});for(let d of u.excludes??[])s[d.groupId]===d.optionId&&n.push({code:"excludes",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} cannot be combined with ${i(d)}.`})}let c=e.skus?.length?e.skus.find(u=>r.every(d=>u.selections[d.id]===s[d.id]))?.sku??null:ur(e,s);e.skus?.length&&!c&&!n.length&&n.push({code:"sku",groupIds:r.map(u=>u.id),message:"This combination has no product SKU."});let l=JSON.stringify({productId:e.id,revision:e.revision,quantity:o,selections:s});return{version:1,productId:e.id,revision:e.revision,key:l,quantity:o,selections:s,sku:c,items:a,valid:!n.length,issues:n}}var wn=new Set(["requires","excludes"]);function Je(e,t,o,n,r=1){let s={...ae(e,t,r).selections,[o]:n},a=new Set([JSON.stringify(s)]),i=[s];for(let c=0;c<i.length&&c<2e3;c++){let l=i[c],u=ae(e,l,r).issues.filter(d=>wn.has(d.code));if(!u.length)return l;for(let d of new Set(u.flatMap(p=>p.groupIds))){if(d===o)continue;let p=e.groups.find(f=>f.id===d);if(p)for(let f of[...p.options.map(C=>C.id),...p.required?[]:[null]]){let C={...l,[d]:f},R=JSON.stringify(C);a.has(R)||(a.add(R),i.push(C))}}}return null}function dr(e,t,o,n,r){let s=Je(e,t,o,n,r);return s?Object.entries(s).filter(([a,i])=>a!==o&&i!==t[a]&&i!==null).map(([a,i])=>({groupId:a,optionId:i})):null}function Mn(e,t){if(!e.pricing)return null;let o=e.pricing.basePriceMinor;for(let n of t.items)o+=e.groups.find(r=>r.id===n.groupId)?.options.find(r=>r.id===n.optionId)?.priceDeltaMinor??0;return{amountMinor:Math.max(0,o)*t.quantity,currency:e.pricing.currency}}function An(e,t,o=!1){try{let n=new Intl.NumberFormat(void 0,{style:"currency",currency:t,...o?{signDisplay:"exceptZero"}:{}});return n.format(e/10**(n.resolvedOptions().maximumFractionDigits??2))}catch{return`${e} ${t}`}}function vn(e,t){let o=e.checkout?.urlTemplate;if(!o||!t.valid||o.includes("{sku}")&&!t.sku)return null;let n={sku:t.sku??"",quantity:String(t.quantity),productId:e.id,revision:e.revision,selections:kt(t.selections)};return o.replace(/\{([a-zA-Z]+)\}/g,(r,s)=>Object.prototype.hasOwnProperty.call(n,s)?encodeURIComponent(n[s]):r)}function kt(e){return Object.entries(e).filter(([,t])=>t!==null).map(([t,o])=>`${encodeURIComponent(t)}:${encodeURIComponent(o)}`).join(",")}function Cn(e,t){let o={...Te(t)};for(let n of e.split(",")){let[r,s]=n.split(":");if(!r||!s)continue;let a,i;try{a=decodeURIComponent(r),i=decodeURIComponent(s)}catch{continue}t.groups.find(c=>c.id===a)?.options.some(c=>c.id===i)&&(o[a]=i)}return o}var yn=4096;function kn(e,t="-"){let o=[{}];for(let s of e.groups){let a=[...s.options.map(i=>i.id),...s.required?[]:[null]];if(o.length*a.length>yn*8)throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.");o=o.flatMap(i=>a.map(c=>({...i,[s.id]:c})))}let n={...e,skus:void 0},r=[];for(let s of o){if(ae(n,s).issues.length)continue;let a=e.groups.flatMap(i=>{let c=s[i.id];return c===null?[]:[i.options.find(l=>l.id===c)?.sku??null]});if(!(!a.length||a.includes(null))&&(r.push({sku:a.join(t),selections:s}),r.length>yn))throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.")}return r}function On(e,t={},o){let n=[],r=Te(e),s=ae({...e,skus:void 0},r).issues.filter(i=>wn.has(i.code));for(let i of s)n.push({code:"invalid-default",message:`The default choices conflict: ${i.message}`});e.checkout?.urlTemplate.includes("{sku}")&&!e.skus?.length&&e.groups.some(i=>i.options.some(c=>!c.sku))&&n.push({code:"missing-sku",message:"The buy link uses {sku}, but it won't appear until every option has an SKU."});let a=Object.keys(t).length>0;for(let i of e.groups)for(let c of i.options){let l=`${i.label} \u203A ${c.label}`,u={groupId:i.id,optionId:c.id};if(a)for(let p of c.appearance??[])Q(t,p.target).length||n.push({code:"no-objects",message:`${l} changes objects that aren't in this model.`,...u});if(o)for(let p of c.variants??[])o.includes(p)||n.push({code:"missing-variant",message:`${l} uses a material variant this model doesn't have: ${p}.`,...u});let d={...r,[i.id]:c.id};Je(e,d,i.id,c.id)||n.push({code:"unreachable",message:`The rules leave no way to choose ${l}.`,...u})}return n}function jn(e,t,o,n=1){return t=ae(e,t,n).selections,e.groups.flatMap(r=>r.options.map(s=>{let i=ae(e,{...t,[r.id]:s.id},n).issues.filter(u=>u.groupIds.includes(r.id)&&u.code!=="sku").map(u=>u.message),c=o?.options?.find(u=>u.groupId===r.id&&u.optionId===s.id);c?.available===!1&&i.push(c.reason??"Currently unavailable.");let l=i.length&&c?.available!==!1?dr(e,t,r.id,s.id,n):null;return{groupId:r.id,optionId:s.id,selected:t[r.id]===s.id,available:!i.length,...l?{fix:l}:{},reasons:[...new Set(i)]}}))}function Ze(e){Y(e)||_("expected a product definition and selections.");let t=Ct(e.definition),o=ae(t,e.selections??Te(t));return o.issues.some(n=>n.code==="unknown-group"||n.code==="unknown-option")&&_("selections reference unknown options."),{definition:t,selections:o.selections}}function Tn(e){return JSON.stringify({version:1,productId:e.productId,revision:e.revision,quantity:e.quantity,selections:e.selections})}function Rn(e,t){let o=xn(typeof e=="string"?JSON.parse(e):e);if(!Y(o)||o.version!==1||o.productId!==t.id||o.revision!==t.revision)throw new Error("This configuration belongs to a different product or revision.");if(!Y(o.selections)||!Number.isSafeInteger(o.quantity))throw new Error("Invalid product configuration selections or quantity.");let n=ae(t,o.selections,o.quantity);if(n.issues.some(r=>r.code==="unknown-group"||r.code==="unknown-option"))throw new Error("This configuration references unknown product options.");return n}function In(e,t,o=[],n=[]){let r=e,s=[...o];if(!t)return{objectBindings:r,activeVariants:s};for(let a of t.definition.groups){let i=a.options.find(c=>c.id===(t.selections[a.id]===void 0?a.defaultOptionId:t.selections[a.id]));if(i){for(let c of i.appearance??[])r=$e(r,c.target,{...c.material!==void 0?{style:{material:c.material}}:{},...c.visible!==void 0?{visible:c.visible}:{}});if(i.variants?.length){let c=new Set(a.options.flatMap(l=>l.variants??[]));s=s.filter(l=>!c.has(l));for(let l of i.variants)s=qe(s,l,n)}}}return{objectBindings:r,activeVariants:s}}var me=5*1024*1024,mr=["activeModelId","modelUrl","modelFormat","tilesetUrl","models","mergeModels","sceneConfig","isolation","multiSelectedKeys","activeAnnotation","annotationCategories","backgroundColor","shadows","cinematic","cameraControllerType","objectTransformSpace","arScaleMode","usdzUrl","measurements","measurementSettings","measurementUnit","measurementModelId"];function O(e,t){throw new Error(`Invalid viewer state at ${e}: ${t}`)}function W(e,t){(!e||typeof e!="object"||Array.isArray(e))&&O(t,"expected an object.")}function Ue(e,t){(!Array.isArray(e)||!e.every(o=>typeof o=="string"))&&O(t,"expected strings.")}function oe(e,t,o){(!Array.isArray(e)||e.length!==t||!e.every(n=>typeof n=="number"&&Number.isFinite(n)))&&O(o,`expected ${t} finite numbers.`)}function pr(e){let t=new Set,o=0;function n(r,s,a){if((++o>2e5||a>64)&&O(s,"configuration is too complex."),r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;(typeof r!="object"||!r)&&O(s,"expected JSON data (finite numbers, no functions)."),t.has(r)&&O(s,"cyclic data."),!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null&&O(s,"expected plain JSON data."),t.add(r);let i=Array.isArray(r)?[]:{};for(let[c,l]of Object.entries(r))["__proto__","constructor","prototype"].includes(c)&&O(`${s}.${c}`,"reserved property."),l!==void 0?i[c]=n(l,`${s}.${c}`,a+1):Array.isArray(r)&&O(s,"undefined array entry.");return t.delete(r),i}return n(e,"state",0)}function re(e,t,o,n,r=!1,s){let a=e[t];if(a==null||a==="")return;typeof a!="string"&&O(o,"expected a URL.");let i=r?ln(a)??a:a;if(i.trim().startsWith("blob:")){if(r&&s){s.set(a,{source:i,path:o});return}O(o,r?"this image is temporary. Use getStateAsync() for JSON or createShareUrl() to include it.":"upload this model/environment asset to a durable URL before saving or sharing.")}if(i!==a&&(a=i,e[t]=i),r&&/^data:image\//i.test(a))return;let c;try{c=new URL(a,n??"https://relative.invalid/")}catch{O(o,"invalid asset URL.")}["http:","https:"].includes(c.protocol)||O(o,"use an HTTP(S) asset URL."),n&&(e[t]=c.href)}function fr(e,t){W(e,t),oe(e.position,3,`${t}.position`),oe(e.target,3,`${t}.target`),(typeof e.zoom!="number"||e.zoom<=0)&&O(t,"zoom must be positive."),e.fov!==null&&(typeof e.fov!="number"||e.fov<=0||e.fov>=180)&&O(t,"fov must be null or between 0 and 180.");for(let o of["azimuthAngle","polarAngle"])e[o]!==void 0&&typeof e[o]!="number"&&O(t,`${o} must be a number.`)}function En(e,t,o,n){W(e,t),(typeof e.id!="number"||typeof e.title!="string"||typeof e.description!="string")&&O(t,"expected an annotation id, title and description.");for(let r of["worldPosition","localPosition"])oe(e[r],3,`${t}.${r}`);e.images!==void 0&&(Array.isArray(e.images)||O(t,"images must be an array."),e.images.forEach(r=>{W(r,t),re(r,"src",t,o,!0,n)})),e.links!==void 0&&(Array.isArray(e.links)||O(t,"links must be an array."),e.links.forEach(r=>{W(r,t),re(r,"href",t,o,!1,n)}))}function Vn(e,t){W(e,t),e.waypoints!==void 0&&(Array.isArray(e.waypoints)||O(t,"expected waypoints."),e.waypoints.forEach(o=>{W(o,t),oe(o.position,3,t),oe(o.target,3,t)}));for(let o of["enabled","loop","autoPlay"])e[o]!==void 0&&typeof e[o]!="boolean"&&O(t,`${o} must be boolean.`);e.duration!==void 0&&(typeof e.duration!="number"||e.duration<=0)&&O(t,"duration must be positive.")}function Ot(e,t,o){if(t!==null)if(Array.isArray(t))Array.isArray(e)||O(o,"expected an array."),t.length&&e.forEach(n=>Ot(n,t[0],o));else if(typeof t=="object"){W(e,o);for(let[n,r]of Object.entries(t))Ot(e[n],r,`${o}.${n}`)}else typeof e!=typeof t&&O(o,`expected ${typeof t}.`)}function Pn(e,t,o,n){if(Ot(e,be,t),e.measurements!==void 0&&(e.measurements=we(e.measurements)),e.sequences!==void 0&&(e.sequences=Oe(e.sequences)),e.selectionSets!==void 0&&(e.selectionSets=Ye(e.selectionSets)),e.product!==void 0&&(e.product=Ze(e.product),e.product.definition.groups.forEach(r=>r.options.forEach(s=>s.appearance?.forEach(a=>{for(let[i,c]of Object.entries(a.material??{}))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${t}.product.material.${i}.path`,o,!0,n)})))),oe(e.model.rotation,3,`${t}.model.rotation`),e.lighting.lights.forEach(r=>oe(r.position,3,`${t}.lighting.lights`)),e.annotations.forEach(r=>En(r,`${t}.annotations`,o,n)),e.animations.autoplayClip!==null&&typeof e.animations.autoplayClip!="string"&&O(t,"invalid autoplay clip."),e.animations.clips.forEach(r=>{W(r,t),(typeof r.sourceName!="string"||typeof r.displayName!="string"||typeof r.hidden!="boolean"||typeof r.speed!="number"||!["repeat","once","ping-pong"].includes(r.loopMode))&&O(t,"invalid animation clip settings.")}),e.cinematic!==void 0&&Vn(e.cinematic,`${t}.cinematic`),e.styleRules!==void 0&&!Array.isArray(e.styleRules)&&O(t,"styleRules must be an array."),re(e.environment,"customEnvironmentUrl",`${t}.environment`,o,!1,n),re(e.background,"imageUrl",`${t}.background`,o,!0,n),e.model.activeVariants!==void 0&&Ue(e.model.activeVariants,t),e.section!==void 0)try{e.section=De(e.section)}catch(r){O(`${t}.section`,r.message)}}function Dn(e,t,o,n){W(e,t);for(let[r,s]of Object.entries(e)){let a=`${t}.${r}`;W(s,a),(typeof s.id!="string"||typeof s.modelObjectId!="string")&&O(a,"expected binding id and modelObjectId.");for(let i of["label","group","type","status"])s[i]!==void 0&&typeof s[i]!="string"&&O(a,`${i} must be a string.`);s.tags!==void 0&&Ue(s.tags,a),s.metadata!==void 0&&W(s.metadata,`${a}.metadata`),s.metrics!==void 0&&(W(s.metrics,a),Object.values(s.metrics).some(i=>typeof i!="number")&&O(a,"metrics must be numbers.")),s.actions!==void 0&&(Array.isArray(s.actions)||O(a,"actions must be an array."),s.actions.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.label!="string"||i.type!=="command"||i.effects!==void 0&&!Array.isArray(i.effects))&&O(a,"invalid action.")}));for(let i of["visible","removed","selectable","hoverable"])s[i]!==void 0&&typeof s[i]!="boolean"&&O(a,`${i} must be boolean.`);if(s.transform!==void 0){W(s.transform,a);for(let i of["position","rotation","scale","shear"])s.transform[i]!==void 0&&oe(s.transform[i],3,`${a}.transform.${i}`);s.transform.pivot!==void 0&&(W(s.transform.pivot,a),oe(s.transform.pivot.point,3,a),oe(s.transform.pivot.offset,3,a))}if(s.style!==void 0&&(W(s.style,a),s.style.material!==void 0)){W(s.style.material,a);for(let[i,c]of Object.entries(s.style.material))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${a}.style.material.${i}.path`,o,!0,n)}s.decals!==void 0&&(Array.isArray(s.decals)||O(a,"decals must be an array."),s.decals.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.size!="number"||i.size<=0)&&O(a,"invalid decal."),oe(i.position,3,a),oe(i.normal,3,a),re(i,"image",a,o,!0,n)}))}}function Bn(e,t,o,n){Array.isArray(e)||O(t,"expected merge sources."),e.forEach(r=>{W(r,t),(typeof r.url!="string"||!r.url||typeof r.namePrefix!="string")&&O(t,"expected source URL and prefix."),re(r,"url",t,o,!1,n)})}function gr(e,t,o){W(e,"configuration");let n=Object.fromEntries(mr.filter(r=>e[r]!==void 0).map(r=>[r,e[r]]));(typeof n.modelUrl!="string"||!n.modelUrl)&&O("configuration.modelUrl","expected the active model URL.");for(let r of["modelUrl","tilesetUrl","usdzUrl"])re(n,r,`configuration.${r}`,t,!1,o);if(n.sceneConfig!==void 0&&Pn(n.sceneConfig,"configuration.sceneConfig",t,o),n.mergeModels!==void 0&&Bn(n.mergeModels,"configuration.mergeModels",t,o),n.models!==void 0){(!Array.isArray(n.models)||n.models.length===0)&&O("configuration.models","expected model entries.");let r=new Set,s=new Set;n.models.forEach(a=>{W(a,"model"),(typeof a.url!="string"||!a.url)&&O("model.url","expected a URL."),re(a,"url","model.url",t,!1,o),a.id!==void 0&&(typeof a.id!="string"||!a.id.trim())&&O("model.id","expected a nonempty instance ID.");let i=ht({id:a.id,url:a.url});s.has(i)&&O("configuration.models","instance identities must be unique; assign IDs when reusing a URL."),s.add(i),a.transform!==void 0&&(a.transform=je(a.transform)),a.visible!==void 0&&typeof a.visible!="boolean"&&O("model.visible","expected boolean."),r.add(a.url),Dn(a.objectBindings,"model.objectBindings",t,o),a.sceneConfig!==void 0&&Pn(a.sceneConfig,"model.sceneConfig",t,o),a.mergeModels!==void 0&&Bn(a.mergeModels,"model.mergeModels",t,o)}),n.activeModelId!==void 0&&(typeof n.activeModelId!="string"||!s.has(n.activeModelId))&&O("configuration.activeModelId","active instance is not in models."),n.activeModelId!==void 0&&n.models.find(a=>ht(a)===n.activeModelId)?.url!==n.modelUrl&&O("configuration.modelUrl","source does not match the active instance."),r.has(n.modelUrl)||O("configuration.modelUrl","active model is not in models.")}if(n.multiSelectedKeys!==void 0&&Ue(n.multiSelectedKeys,"configuration.multiSelectedKeys"),n.annotationCategories!==void 0&&n.annotationCategories!==null&&Ue(n.annotationCategories,"configuration.annotationCategories"),n.activeAnnotation!==void 0&&n.activeAnnotation!==null&&En(n.activeAnnotation,"configuration.activeAnnotation",t,o),n.measurements!==void 0||n.measurementSettings!==void 0){let r=we({items:n.measurements??[],settings:n.measurementSettings??{}});n.measurements!==void 0&&(n.measurements=r.items),n.measurementSettings!==void 0&&(n.measurementSettings=r.settings)}n.measurementModelId!==void 0&&typeof n.measurementModelId!="string"&&O("configuration.measurementModelId","expected a stable id."),n.measurementUnit!==void 0&&typeof n.measurementUnit!="string"&&O("configuration.measurementUnit","expected a unit label.");for(let r of["backgroundColor"])n[r]!==void 0&&typeof n[r]!="string"&&O(r,"expected a string.");n.shadows!==void 0&&typeof n.shadows!="boolean"&&O("shadows","expected boolean.");for(let[r,s]of Object.entries({modelFormat:["glb","gltf","obj","fbx","usdz","stl","ply"],cameraControllerType:["orbit","pointerLock"],objectTransformSpace:["world","local"],arScaleMode:["normalized","real-world"]}))n[r]!==void 0&&!s.includes(n[r])&&O(r,"unsupported value.");if(n.cinematic!==void 0&&Vn(n.cinematic,"cinematic"),n.isolation!==void 0&&n.isolation!==null){let{target:r,mode:s,ghostOpacity:a}=n.isolation;typeof r=="string"||Array.isArray(r)&&r.every(i=>typeof i=="string")||r&&typeof r=="object"&&["group","tag","type"].some(i=>typeof r[i]=="string")||O("configuration.isolation","invalid target."),s!==void 0&&!["ghost","hide"].includes(s)&&O("configuration.isolation","invalid mode."),a!==void 0&&(typeof a!="number"||a<0||a>1)&&O("configuration.isolation","opacity must be between 0 and 1.")}return n}function Nn(e,t,o,n){if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))r!=="metadata"&&(typeof s=="string"&&["url","modelUrl","tilesetUrl","usdzUrl","path","image","src","href","imageUrl","customEnvironmentUrl"].includes(r)?re(e,r,`${t}.${r}`,o,["path","image","src","imageUrl"].includes(r),n):Nn(s,`${t}.${r}`,o,n))}function Ln(e,t,o){typeof e=="string"&&(new TextEncoder().encode(e).length>me&&O("state","exceeds the 5 MiB limit."),e=JSON.parse(e));let n=pr(e);W(n,"state"),new TextEncoder().encode(JSON.stringify(n)).length>me&&O("state","exceeds the 5 MiB limit."),n.version!==void 0&&n.version!==1&&O("version","unsupported version."),n.version===void 0&&(n.objectBindings!==void 0||n.configuration!==void 0)&&O("version","full configurations require version 1.");let r={};return n.version!==void 0&&(r.version=1),n.camera!==void 0&&(fr(n.camera,"camera"),r.camera=n.camera),n.hidden!==void 0&&(Ue(n.hidden,"hidden"),r.hidden=n.hidden),n.selected!==void 0&&(n.selected!==null&&typeof n.selected!="string"&&O("selected","expected an object id or null."),r.selected=n.selected),n.objectBindings!==void 0&&(Dn(n.objectBindings,"objectBindings",t,o),r.objectBindings=n.objectBindings),n.configuration!==void 0&&(r.configuration=gr(n.configuration,t,o)),Nn(r,"state",t,o),new TextEncoder().encode(JSON.stringify(r)).length>me&&O("state","exceeds the 5 MiB limit."),r}function Un(e,t){return JSON.stringify(Re(e,t))}function Re(e,t){return Ln(e,t)}async function Qe(e,t){let o=new Map,n=Ln(e,t,o),r=new Map,s=new Map;for(let[i,{source:c,path:l}]of o){let u=r.get(c);u||(u=(async()=>{let d;try{d=await fetch(c)}catch{O(l,"this temporary image is no longer available. Reload or reselect it before saving.")}d.ok||O(l,"could not read the temporary image. Reload or reselect it before saving.");let p=await d.blob();p.size>me*3/4&&O(l,"embedded image exceeds the 5 MiB configuration limit. Use a hosted image URL.");let f=new Uint8Array(await p.arrayBuffer()),C=p.type.split(";")[0].toLowerCase(),R=C.startsWith("image/")?C:br(f);R||O(l,"temporary asset is not a supported image. Use a hosted asset URL.");let S="";for(let w=0;w<f.length;w+=32768)S+=String.fromCharCode(...f.subarray(w,w+32768));return`data:${R};base64,${btoa(S)}`})(),r.set(c,u)),s.set(i,await u)}function a(i){if(!(!i||typeof i!="object"))for(let[c,l]of Object.entries(i))c!=="metadata"&&(["path","image","src","imageUrl"].includes(c)&&typeof l=="string"&&s.has(l)?i[c]=s.get(l):a(l))}return a(n),Re(n,t)}function br(e){let t=(o,n)=>String.fromCharCode(...e.subarray(o,n));if(e[0]===137&&t(1,4)==="PNG")return"image/png";if(e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(t(0,3)==="GIF")return"image/gif";if(t(0,4)==="RIFF"&&t(8,12)==="WEBP")return"image/webp";if(t(4,8)==="ftyp"&&["avif","avis"].includes(t(8,12)))return"image/avif";if(/<svg[\s>]/i.test(new TextDecoder().decode(e.subarray(0,1024))))return"image/svg+xml"}var jt={verifyingLicense:"Verifying License",checkingYourLicenseKey:"Checking your license key...",createDevelopmentKey:"Create a free development key",invalidLicense:"Invalid License",licenseHasBeenRevokedOrHasExpired:"License has been revoked or has expired",failedToLoadPleaseContactTheSiteAdministrator:"Failed to load. Please contact the site administrator.",contextRestoringTitle:"Reloading viewer\u2026",contextLostTitle:"3D view interrupted",contextRestoringMessage:"Rebuilding the 3D view. Please wait\u2026",contextLostMessage:"The graphics connection was interrupted. The viewer will rebuild when it returns, or you can reload it now.",reloadViewer:"Reload viewer",texturePositioningHint:"Drag to move \xB7 Scroll to zoom \xB7 Click elsewhere to finish",texturePositioningStartHint:"Double-click to move or zoom",dismiss:"Dismiss",missingUVsAreShownInMagenta:"Missing UVs are shown in magenta.",viewThisModelInARWithAppleQuickLook:"View this model in AR with Apple Quick Look",sequencePlayer:"Sequence player",sequenceSelect:"Sequence",sequencePlay:"Play sequence",sequencePause:"Pause sequence",sequenceStop:"Stop and restore scene",sequencePlayhead:"Sequence playhead",sequenceTime:"Sequence time",sequenceIssues:"Unavailable sequence targets",arConfiguredButton:"AR handoff",arConfiguredTitle:"Take this configuration to AR",arConfiguredDescription:"Your current materials, visible models and placements are included.",arSnapshotStale:"Updating AR to include your latest changes\u2026",arPreparing:"Preparing your scene\u2026",arStart:"Start AR",arStarting:"Starting AR\u2026",arCheckingSupport:"Checking AR support\u2026",arUnavailable:"AR is unavailable in this browser. Open this link in an AR-capable browser on your phone.",arStartFailed:"Could not start AR. Check camera permissions and try again.",arAnimations:"AR animations",arAnimationSelect:"Animation",arAnimationSaved:"Default",arAnimationNone:"No animation",arAnimationClips:"Model clips",arAnimationSequences:"Sequences",arAnimationPlay:"Play animation",arAnimationPause:"Pause animation",arRefresh:"Refresh AR",arRetry:"Try again",arExportDetails:"Export details",arPrepare:"Prepare AR",arPrepareAgain:"Prepare again",arDownloadUSDZ:"Download USDZ for iPhone/iPad",arScanConfigured:"Scan to open this configuration on your phone.",arOpenConfiguredLink:"Open configuration link",viewInAR:"View in AR",openThisExperienceOnAPhoneForAR:"Open this experience on a phone for AR",openOnPhone:"Open on phone",viewThisModelInYourSpace:"View this model in your space",viewThisModelInVR:"View this model in VR",closePhoneHandoff:"Close phone handoff",arScanCode:"Scan the code and choose AR.",qrCodeToOpenThisModelOnAPhone:"QR code to open this model on a phone",disableUVChecker:"Disable UV checker",enableUVChecker:"Enable UV checker",explodedView:"Exploded view",explodeAmount:"Explode amount",removeSectionCut:"Remove section cut",sectionCut:"Section cut",sectionAxis:"Section axis",sectionPosition:"Section position",keepTheOtherSide:"Keep the other side",pauseCinematic:"Pause cinematic",playCinematic:"Play cinematic",stopCinematicAndResetCamera:"Stop cinematic and reset camera",cancel:"Cancel",annotationCategories:"Annotation categories",annotations:"Annotations",all:"All",uncategorized:"Uncategorized",decalDragHint:"Drag the decal on the object. Release to save; Escape to cancel.",showAll:"Show all",materialVariants:"Material variants",startGuidedTour:"Start guided tour",guidedTour:"Guided Tour",previousAnnotation:"Previous annotation",previous:"Prev",stopGuidedTour:"Stop guided tour",nextAnnotation:"Next annotation",next:"Next",exitFullscreen:"Exit fullscreen",enterFullscreen:"Enter fullscreen",resetCameraView:"Reset camera view",orbitControl:"Orbit Control",pointLock:"Pointer lock",cameraController:"Camera controller",cameraControllerSettings:"Camera controller settings",downloadGLB:"Download GLB",downloadGLBDescription:"All visible models, material edits and animations in one file. No annotations or separate editor model slots. Duplicate mesh names may change on reimport.",downloadCombinedGLB:"Download as one GLB",downloadSeparateGLBs:"Download separate GLBs",downloadSeparateGLBsDescription:"One GLB file per model",downloadPNG:"Download PNG",downloadUVLayout:"Download UV Layout",videoFormat:"Video format",auto:"Auto",recordTurntableVideo:"Record turntable video",recordCinematicVideo:"Record cinematic video",videoUnsupported:"Video recording is not supported in this browser.",downloadOptions:"Download options",exporting:"Exporting\u2026",download:"Download",annotationTitlePlaceholder:"Title *",description:"Description",ok:"OK",arRelocate:"Relocate",tapToPlace:"Tap to place",closeAnnotation:"Close annotation",learnMore:"Learn more",stopMeasuring:"Stop measuring",startMeasuring:"Start measuring",toggleBoundingDimensions:"Toggle bounding dimensions",measurementTool:"Measurement tool",distance:"Distance",angle:"Angle",area:"Area",pointToPlane:"Point to plane",wrap:"Circumference (Edge)",wrapHorizontal:"Circumference (Horizontal)",measurementSnapping:"Measurement snapping",noSnapping:"No snapping",snapAuto:"Snap: auto",snapVertex:"Snap: vertex",snapEdge:"Snap: edge",undoMeasurementPoint:"Undo measurement point",clearMeasurements:"Clear measurements",finishArea:"Finish area",savedMeasurements:"Saved measurements ({count})",noSavedMeasurements:"No saved measurements yet. Pick points in the preview, then save a measurement here.",measurementFiles:"Import / export",measurementSourceUnit:"Model units",measurementDisplayUnit:"Display units",measurementName:"Name",measurementNamePlaceholder:"e.g. Door width",saveMeasurement:"Save",knownMeasurementDistance:"Known length",calibrationUnit:"Calibration unit",calibrateMeasurement:"Calibrate",measurementCalibrationHint:"Pick two distance points, enter their known length, then calibrate.",measurementCalibratedScale:"Calibrated: 1 model unit = {scale} m",resetMeasurementCalibration:"Reset calibration",showSavedMeasurement:"Show {name}",renameSavedMeasurement:"Rename {name}",deleteSavedMeasurement:"Delete {name}",exportMeasurementJson:"Export JSON",exportMeasurementCsv:"Export CSV",importMeasurementJson:"Import JSON",measurementReady:"Ready",measurementApproximate:"Approximate LOD",measurementModelChanged:"Different model",measurementObjectMissing:"Object unavailable",measurementGeometryChanged:"Geometry changed \u2014 measure again",measurementPoseChanged:"Pose changed \u2014 measure again",measurementObjectHidden:"Object hidden",measurementInvalid:"Invalid measurement",measurementWaiting:"Waiting for model",openSceneObjectsPanel:"Open scene objects panel",sceneObjects:"Scene Objects",searchNodesLabels:"Search nodes, labels",closeSceneObjectsPanel:"Close scene objects panel",objectNavigator:"Objects in the 3D view",compareBefore:"Before",compareAfter:"After",compareDivider:"Comparison divider",viewIn3D:"View in 3D",objectNavigatorHint:"Arrow keys browse \xB7 Enter selects \xB7 Esc clears",selectionCleared:"Selection cleared",cameraKeyboardHelp:"3D view. Arrow keys orbit, Shift with Up or Down zooms, and W, A, S, D, Space and C move the camera.",isolate:"Isolate",hide:"Hide",show:"Show",closePanel:"Close panel",actions:"Actions",openPanel:"Open panel",close:"Close",position:"Position",decalNudgeHint:"Click to fine-tune \xB7 Hold to move",decalNudgeControls:"Move decal in small steps",text:"Text",yourText:"Your text",textToAdd:"Text to add",textColour:"Text color",addText:"Add text",image:"Image",chooseImage:"Choose image",imageToAdd:"Image to add",added:"Added",colour:"Color",size:"Size",turn:"Turn",rotation:"Rotation",dragTheDecalAcrossTheObjectsSurface:"Drag the decal across the object's surface",move:"Move",remove:"Remove",noneAddedYet:"None added yet",done:"Done",moveForward:"Move forward",moveLeft:"Move left",moveRight:"Move right",moveBackward:"Move backward",productOptions:"Options",productOptionsFor:"{product} options",productReset:"Reset",productOptional:"optional",productNone:"None",productAlsoChanges:"Also changes: {changes}",productUnavailable:"Currently unavailable.",productQuantity:"Quantity",productCheckingPrice:"Checking price and availability\u2026",productTotal:"Total",productAddToCart:"Add to cart",productAddingToCart:"Adding\u2026",productRequestQuote:"Request quote",productRequestingQuote:"Requesting\u2026",productRefresh:"Refresh",productBuy:"Buy now",productCopyLink:"Copy link",productLinkCopied:"Link copied",productShowOptions:"Show options",productHideOptions:"Hide options",productIssues:"Configuration issues",productRequestDone:"Request completed.",productSaved:"Saved: {id}",sceneSettings:"Scene Settings",background:"Background",backgroundColor:"Background Color",showEnvironmentAsBackground:"Show as background",backgroundBlur:"Background Blur",environmentPreset:"Preset",environmentIntensity:"Intensity",toneMapping:"Tone Mapping",toneMappingAces:"ACES Filmic",toneMappingAgx:"AgX",toneMappingNeutral:"Neutral",toneMappingNone:"None",ground:"Ground",groundShadow:"Ground Shadow",groundShadowOpacity:"Shadow Opacity",floorGrid:"Floor Grid",display:"Display",wireframe:"Wireframe",autoRotateSpeed:"Rotation Speed",fieldOfView:"Field of View",modelInfo:"Model",modelInfoObjects:"Objects",modelInfoTriangles:"Triangles",modelInfoMaterials:"Materials",resetSettings:"Reset Settings",environment:"Environment",autoRotate:"Auto Rotate",lighting:"Lighting",exposure:"Exposure",ambientLightIntensity:"Ambient Light Intensity",ambientLightColor:"Ambient Light Color",directLightIntensity:"Direct Light Intensity",directLightColor:"Direct Light Color",searchObjects:"Search objects",uploadedModel:"Uploaded model",clear:"Clear",chooseModel:"Choose model",loadingModel:"Loading model...",releaseToLoadYourModel:"Release to load your model",arFindSurface:"Move your device over a flat surface",arReleaseToPlace:"Release to place",arGestureHint:"Pinch to resize \xB7 Twist to rotate",angleFirstArmHint:"Pick the first arm",angleVertexHint:"Pick the angle's vertex",angleSecondArmHint:"Pick the second arm",angleNewHint:"Pick a point to start a new angle",areaNewHint:"Pick a point to start a new area",areaCornersHint:"Pick polygon corners in order, then Finish area",pointToPlaneFaceHint:"Pick the reference face",pointToPlanePointHint:"Pick a point to measure its perpendicular distance",pointToPlaneNewHint:"Pick a face to start a new measurement",distanceHint:"Pick points on the model to measure distances",wrapHint:"Click a point on the surface to measure its circumference, following the surface (best for limbs)",wrapHorizontalHint:"Click a point to measure a level circumference around it (best for the torso/waist)",visibleEntries:"{count} visible entries",objectCount:"{count} objects",annotationMarker:"Annotation {id}: {title}",recordingVideo:"Recording video \xB7 {progress}%",isolatedObjects:"Isolated: {count} objects",largeModelWarning:"Very large model ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the objects panel to select parts.",preparingLargeModel:"Preparing large model ({millions}M triangles) \u2014 the first display can take a while on this device...",enterAR:"Enter AR",enterVR:"Enter VR",decalImage:"Image {index}",decalText:"Text {index}",decalAdded:"{count} added",up:"up",down:"down",left:"left",right:"right",moveDecal:"Move decal {direction}",moveDecalOnSurface:"Move {direction} on the visible surface",showAllObject:"Show all {name}",isolateObject:"Isolate {name}",isolatedObject:"Isolated: {name}",hideObject:"Hide {name}",showObject:"Show {name}",objectSelected:"{name} selected",objectNavigatorPosition:"{position} of {count}",compareDividerValue:"{before} {percent}%, {after} {rest}%",bindingMismatchOne:"1 object binding doesn't match this model",bindingMismatchMany:"{count} object bindings don't match this model",simpleLargeModelWarning:"Very large model detected ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the scene objects panel to select parts.",dropModelHint:"Drag and drop {formats} here",retryModelLoad:"Retry loading model",loadErrorTitle:"This model couldn't be loaded",loadErrorNotFound:"Nothing was found at this address ({status}). Check that modelUrl points to the file.",loadErrorDenied:"The server refused access to the file ({status}). Check that the file is public, or that a signed URL hasn't expired.",loadErrorStatus:"The server responded with {status} when the file was requested.",loadErrorNetwork:"The download was blocked or failed. Check that the URL is correct and, if the file is on another domain, that its server allows cross-origin requests (CORS) from this site.",loadErrorHtml:"The server sent back a web page instead of a model. There's probably no file at this path: many servers answer a missing file with their index.html.",loadErrorInvalidFile:"The file couldn't be read as {format}. Check that it's a valid {format} file.",loadErrorInvalidExplicitFormat:"The file couldn't be read as {format}. Check that it's a valid {format} file and that modelFormat matches it.",loadErrorMissingFormat:"The file couldn't be read as {format}. The URL has no file extension, so set modelFormat to the file's format.",loadErrorPointCloud:"This PLY file is a point cloud: it has points but no faces, and the viewer shows meshes. Turn it into a mesh first, for example with MeshLab or Blender.",measurementReferenceFaceRequired:"Pick a triangle face to define the reference plane.",measurementTooManyPoints:"Finish or clear this measurement before adding more points.",measurementAngleDistinct:"Pick a point away from the angle's vertex.",areaMinimumPoints:"Pick at least three points to finish the area.",areaDistinctPoints:"Area points must be distinct.",areaStraightLine:"Area points must not lie on one straight line.",areaNotPlanar:"Area points must lie on one plane.",areaEdgesCross:"Area edges must not cross or touch each other.",areaZero:"The polygon has no measurable area.",decalSurfaceMissing:"Could not find a surface on this object for the decal.",decalDirectionMissing:"No visible surface in that direction. Try another arrow or rotate the view.",fullscreenExitFailed:"Could not exit fullscreen. Press Escape to exit.",fullscreenEnterFailed:"Could not enter fullscreen. Check your browser or iframe fullscreen permissions and try again.",uvCoordinatesMissing:"This model does not contain UV coordinates.",uvExportFailed:"Could not create the UV layout archive.",videoExportFailed:"Could not export the video.",videoNotReady:"Viewer not ready for video export.",videoExitXR:"Exit the XR session before recording a video.",videoAlreadyRecording:"A video export is already in progress.",videoPathRequired:"Enable a cinematic camera path before recording it.",videoDurationInvalid:"Video duration must be greater than 0 and at most 300 seconds.",videoFrameRateInvalid:"Video frame rate must be between 1 and 60.",videoBitrateInvalid:"Video bitrate must be a positive number.",videoContextLost:"Video export stopped because the WebGL context was lost.",videoTimedOut:"Video export timed out. Keep the viewer tab visible while recording.",videoEncodingFailed:"The browser could not encode the video.",videoEmpty:"The browser produced an empty video.",videoDidNotStart:"Video recording did not start.",videoWebMUnsupported:"Video recording as WEBM is not supported in this browser.",videoMP4Unsupported:"Video recording as MP4 is not supported in this browser.",videoGIFUnsupported:"Video recording as GIF is not supported in this browser.",videoGifWidthInvalid:"GIF width must be a whole number of pixels from 16 to 4096.",environmentApartment:"apartment",environmentCity:"city",environmentDawn:"dawn",environmentForest:"forest",environmentLobby:"lobby",environmentNight:"night",environmentPark:"park",environmentStudio:"studio",environmentSunset:"sunset",environmentWarehouse:"warehouse",color:"Color",material:"Material",texturePreview:"texture preview",noTextureApplied:"No texture applied",noTextureCoordinates:"This part has no texture coordinates, so an image can't be placed on it.",replaceImage:"Replace image",uploadImage:"Upload image",removeTexture:"Remove texture",texturePosition:"Texture position",offsetX:"Offset X",offsetY:"Offset Y",confirmTexturePosition:"Confirm this texture position and exit positioning mode",donePositioning:"Done positioning",textureOffsetHint:"Double-click the object in the preview to drag its texture directly (scroll to zoom), or edit its offset numerically.",actionToggleLight:"Toggle Light",actionChangeLightColor:"Change Light Color",actionSetBrightness:"Set Brightness",actionChangeColor:"Change Color",actionChangeMaterial:"Change Material",actionToggleVisibility:"Toggle Visibility"};var Ui=new Map(Object.entries(jt).map(([e,t])=>[t,e]));function _n(e){Ge(e);let t=[],o=[{node:e,path:"0",parentId:null}];for(;o.length;){let{node:r,path:s,parentId:a}=o.pop(),i=`node:${s}`,c=r.isMesh&&r.name?Ee(r):null;t.push({id:i,parentId:a,name:r.name||r.type||"Group",...c?{objectId:c}:{}});for(let l=r.children.length-1;l>=0;l--)o.push({node:r.children[l],path:`${s}/${l}`,parentId:i})}let n=new Set;for(let r=t.length-1;r>=0;r--){let s=t[r];(s.objectId||n.has(s.id))&&(n.add(s.id),s.parentId&&n.add(s.parentId))}return t.filter(r=>n.has(r.id))}function zn(e){return structuredClone(e.style??{})}function Fn(e,t,o){let n=Q(e,t).filter(s=>!e[s].removed);if(!n.length)return e;let r={...e};for(let s of n)r[s]={...e[s],style:structuredClone(o)};return r}var Me=require("three"),hr=new Set(["KHR_binary_glTF","KHR_draco_mesh_compression","KHR_lights_punctual","KHR_materials_clearcoat","KHR_materials_dispersion","KHR_materials_ior","KHR_materials_sheen","KHR_materials_specular","KHR_materials_transmission","KHR_materials_iridescence","KHR_materials_anisotropy","KHR_materials_unlit","KHR_materials_volume","KHR_texture_basisu","KHR_texture_transform","KHR_mesh_quantization","KHR_materials_emissive_strength","KHR_materials_variants","EXT_materials_bump","EXT_texture_webp","EXT_texture_avif","EXT_meshopt_compression","EXT_mesh_gpu_instancing"]),yr=new WeakMap;function Sr(e){let t=yr.get(e);return t?structuredClone(t):void 0}function $n(e){if(/^(blob|data):/i.test(e))return"Local resource";let t=e.split(/[?#]/,1)[0].replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).slice(0,300)||"Resource"}function xr(e){return/^(blob|data):/i.test(e)?"Local resource":e.split(/[?#]/,1)[0].replace(/\\/g,"/").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").replace(/^\/+/,"").slice(0,500)||"Resource"}function wr(e){let t=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:null;return{...e.format?{format:e.format}:{},...e.name?{name:$n(e.name)}:{},sourceBytes:t(e.sourceBytes),loadDurationMs:t(e.loadDurationMs),extensionsUsed:[...new Set(e.extensionsUsed??[])].sort(),extensionsRequired:[...new Set(e.extensionsRequired??[])].sort(),failedResources:[...new Set((e.failedResources??[]).map(xr))].slice(0,50)}}function Mr(e){let t=new Set(e.extensionsRequired);return[...new Set([...e.extensionsUsed??[],...t])].sort().map(o=>({name:o,required:t.has(o),recognized:hr.has(o)}))}function Ar(e,t){let o=e.image,n=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>0?l:null,r=n(o?.naturalWidth??o?.width),s=n(o?.naturalHeight??o?.height),a=!!e.isCompressedTexture,i=e.mipmaps.reduce((l,u)=>l+(u.data?.byteLength??0),0),c=r&&s?Math.ceil(r*s*4*(e.generateMipmaps?4/3:1)):null;return{name:e.name?$n(e.name):t,width:r,height:s,compressed:a,estimatedBytes:a?i||null:c!==null&&Number.isSafeInteger(c)?c:null}}function qn(e,t={}){let o=wr({...Sr(e),...t.source}),n=[],r=new Set,s=new Map,a=new Set,i=new Map,c=new Map,l=new Set,u=new Map,d=0,p=0,f=0,C=0,R=0,S=(g,m)=>{let b=u.get(g)??{count:0,names:[]};b.count++,b.names.length<20&&b.names.push(m||"Unnamed object"),u.set(g,b)},w=g=>{let m=g?.array??g?.data?.array;m?.buffer&&!l.has(m.buffer)&&(l.add(m.buffer),R+=m.buffer.byteLength)};e.traverse(g=>{let m=g;if(!m.isMesh||!m.geometry)return;d++,p+=m.isInstancedMesh?Number.isSafeInteger(m.count)?Math.max(0,m.count??0):0:1;let b=m.geometry,y=b.getAttribute("position"),k=b.getAttribute("uv"),I=m.material?Array.isArray(m.material)?m.material:[m.material]:[];if(!s.has(b)){let T=!!y&&(!Number.isSafeInteger(y.count)||y.count<0);for(let P=0;!T&&y&&P<y.count;P++)if(!Number.isFinite(y.getX(P))||!Number.isFinite(y.getY(P))||!Number.isFinite(y.getZ(P))){T=!0;break}s.set(b,T)}if(s.get(b)&&S("invalid-positions",g.name),y?.count||S("empty-geometry",g.name),k||S("missing-uv",g.name),b.getAttribute("normal")||S("missing-normals",g.name),b.boundingBox&&[...b.boundingBox.min.toArray(),...b.boundingBox.max.toArray()].some(T=>!Number.isFinite(T))&&S("invalid-bounds",g.name),!r.has(b)){r.add(b),f+=Number.isSafeInteger(y?.count)?Math.max(0,y?.count??0):0;let T=b.index?.count??y?.count??0;C+=Number.isSafeInteger(T)?Math.floor(Math.max(0,T)/3):0,Object.values(b.attributes).forEach(w),Object.values(b.morphAttributes).flat().forEach(w),w(b.index)}let N=!1;for(let T of I){a.add(T);let P=i.get(T);if(!P){P=Object.values(T).filter(F=>!!F&&F.isTexture===!0),i.set(T,P);for(let F of P)c.has(F)||c.set(F,`Texture ${c.size+1}`)}for(let F of P){let te=F.channel??0;b.getAttribute(te===0?"uv":`uv${te}`)||(N=!0)}}N&&S("textured-missing-uv",g.name)});let A=(g,m,b,y,k)=>{let I=u.get(g);I&&n.push({code:g,severity:m,title:b,detail:y,suggestion:k,count:I.count,objects:I.names})};A("empty-geometry","error","Empty mesh geometry","Some meshes have no position data.","Remove empty meshes or export their geometry again."),A("invalid-positions","error","Invalid vertex coordinates","Some vertices contain non-finite coordinates.","Repair NaN or infinite vertex positions in the source application, then re-export."),A("invalid-bounds","error","Invalid geometry bounds","Some cached bounds contain non-finite values.","Repair invalid coordinates in the source application and re-export."),A("textured-missing-uv","warning","Textures have no matching UV coordinates","A texture references a UV channel that its mesh does not contain.","Unwrap the affected meshes and export the UV channel used by each texture."),A("missing-uv","info","Meshes without UVs","Solid colors can work without UVs; image textures and surface decals need them.","Add a UV map before applying image textures or decals."),A("missing-normals","info","Meshes without normals","Some loaded meshes lack vertex normals; generated shading may differ from the source.","Export vertex normals to preserve hard edges and smooth surfaces."),d||n.push({code:"no-meshes",severity:"warning",title:"No mesh geometry found",detail:"This scene contains no loaded meshes.",suggestion:"Check that meshes were included in the export. Streamed scenes may still be loading."});let h=[...c].map(([g,m])=>Ar(g,m)),x=h.filter(g=>(g.width??0)>4096||(g.height??0)>4096);x.length&&n.push({code:"large-textures",severity:"warning",title:"Large texture dimensions",detail:"Some textures exceed 4096 pixels on one side.",suggestion:"Resize textures for the visible detail needed; use KTX2/Basis where appropriate.",count:x.length,objects:x.slice(0,20).map(g=>g.name)}),C>1e6&&n.push({code:"high-triangle-count",severity:"warning",title:"High geometry count",detail:"The loaded geometry contains more than one million unique triangles.",suggestion:"Simplify hidden detail, create lower-detail exports, or use streamed assets for large scenes."}),a.size>100&&n.push({code:"many-materials",severity:"warning",title:"Many material definitions",detail:"More than 100 materials can increase rendering work.",suggestion:"Reuse materials and atlas compatible textures; inspect runtime draw calls to confirm the cost."});let M=Mr(o);for(let g of M.filter(m=>!m.recognized))n.push({code:"unrecognized-extension",severity:g.required?"error":"warning",title:`${g.required?"Required":"Optional"} extension not recognized`,detail:g.name,suggestion:"Export with extensions supported by the bundled loader, or verify the asset's fallback appearance."});o.failedResources?.length&&n.push({code:"failed-resources",severity:"error",title:"Some resources failed to load",detail:"The model may be missing textures or other referenced resources.",suggestion:"Include sidecar files in the ZIP, correct their paths, and check HTTP access and CORS.",count:o.failedResources.length,objects:o.failedResources.slice(0,20)});let E=null,j=[...s.values()].some(Boolean)?new Me.Box3:new Me.Box3().setFromObject(e);!j.isEmpty()&&[...j.min.toArray(),...j.max.toArray(),...j.getSize(new Me.Vector3).toArray()].every(Number.isFinite)&&(E={min:j.min.toArray(),max:j.max.toArray(),center:j.getCenter(new Me.Vector3).toArray(),size:j.getSize(new Me.Vector3).toArray()}),t.scope==="resident-tiles"&&n.unshift({code:"partial-stream",severity:"info",title:"Loaded tiles only",detail:"Geometry and texture counts cover the current resident tiles, not the entire source asset.",suggestion:"Use the live cache/detail statistics to inspect streaming pressure. Rescan after moving the camera."});let D=g=>g.code==="partial-stream"?-1:g.severity==="error"?0:g.severity==="warning"?1:2;return n.sort((g,m)=>D(g)-D(m)),{version:1,status:"ready",scope:t.scope??"asset",source:o,units:o.format==="glb"||o.format==="gltf"?"meters (glTF convention)":"unknown",bounds:E,statistics:{meshes:d,instances:p,geometries:r.size,materials:a.size,textures:c.size,vertices:f,triangles:C,geometryBytes:R,estimatedTextureBytes:h.reduce((g,m)=>g+(m.estimatedBytes??0),0),unknownTextureSizes:h.filter(g=>g.estimatedBytes===null).length,meshesWithoutUvs:u.get("missing-uv")?.count??0,meshesWithoutNormals:u.get("missing-normals")?.count??0},textures:h,extensions:M,issues:n}}var vr=new WeakMap;function Gn(e){e.traverse(t=>{let o=vr.get(t);if(o)throw new Error(o)})}var z=require("three");var et=require("three");function Ie(e){return e.isSkinnedMesh===!0}function Hn(e){let t=[];return e.traverse(o=>{Ie(o)&&t.push(o)}),t}var Ae="reactImmersiveSkinFreeze";function Kn(e){return!!e.userData[Ae]}function tt(e,t,o=[t]){let n=e.userData,r=new et.Matrix4().copy(t).invert(),s=n[Ae];if(s){s.frozenInverse.copy(r),s.restWorldTransforms=o.map(c=>c.clone()),e.bindMatrixInverse.copy(r);return}let a={frozenInverse:r,restWorldTransforms:o.map(c=>c.clone()),previousOnBeforeRender:e.onBeforeRender,previousUpdateMatrixWorld:Object.prototype.hasOwnProperty.call(e,"updateMatrixWorld")?e.updateMatrixWorld:void 0};e.bindMatrixInverse.copy(r);let i=e.updateMatrixWorld;e.updateMatrixWorld=function(c){i.call(this,c),e.bindMatrixInverse.copy(a.frozenInverse)},e.onBeforeRender=function(c,l,u,d,p,f){a.previousOnBeforeRender.call(this,c,l,u,d,p,f),e.bindMatrixInverse.copy(a.frozenInverse)},n[Ae]=a}function _e(e){return e.userData[Ae]?.frozenInverse??null}function Wn(e){return e.userData[Ae]?.restWorldTransforms??null}function Xn(e){let t=e.userData,o=t[Ae];o&&(e.onBeforeRender=o.previousOnBeforeRender,o.previousUpdateMatrixWorld?e.updateMatrixWorld=o.previousUpdateMatrixWorld:delete e.updateMatrixWorld,delete t[Ae],e.updateMatrixWorld(!0))}function Yn(e){let t=e,o=_e(e);o&&t.bindMatrixInverse.copy(o),t.skeleton?.update?.();let n=t.geometry.clone(),r=n.getAttribute("position");if(r){let s=new et.Vector3;for(let a=0;a<r.count;a++)t.getVertexPosition(a,s),r.setXYZ(a,s.x,s.y,s.z);r.needsUpdate=!0}return n.deleteAttribute("skinIndex"),n.deleteAttribute("skinWeight"),n.morphAttributes={},n.morphTargetsRelative=!1,n.computeVertexNormals(),n.computeBoundingBox(),n.computeBoundingSphere(),n}var ie=require("three"),po=require("three/examples/jsm/utils/SkeletonUtils.js"),le=require("fflate");var pe=require("three");function Jn(e){let t=e._loopCount;return e.loop===pe.LoopPingPong&&(t&1)===1}function Cr(e){return Jn(e)?e.getClip().duration-e.time:e.time}function Zn({root:e,clips:t,getClipConfig:o,onChange:n}){let r=new pe.AnimationMixer(e),s=new Map;for(let{clip:m,sourceName:b}of t)s.set(b,r.clipAction(m));let a=new Map,i=new Set,c=new Map,l=1,u=m=>typeof m=="string",d=m=>u(m)?a.has(m)?[m]:[]:[...a.keys()],p=(m,b)=>{let y=Qt(o(b));y==="once"?m.setLoop(pe.LoopOnce,1):y==="ping-pong"?m.setLoop(pe.LoopPingPong,1/0):m.setLoop(pe.LoopRepeat,1/0),m.clampWhenFinished=y==="once"},f=m=>{m.action.setEffectiveTimeScale(m.reverse?-m.speed:m.speed)},C=m=>{let b=a.get(m);b&&(b.action.stop(),a.delete(m))},R=(m,b={})=>{let y=s.get(m);if(!y||o(m)?.hidden)return;let k=Number.isFinite(b.fade)&&b.fade>0?b.fade:0,I=b.reverse??!1;if(!b.alongside)for(let[F,te]of[...a])F!==m&&(k>0?(a.delete(F),te.action.fadeOut(k),i.add(te.action)):C(F));i.delete(y)&&y.stop();let N=y.getClip().duration,T=a.get(m),P=()=>{y.reset(),I&&(y.time=N),y.play()};if(!T)P(),k>0&&y.fadeIn(k);else{let F=I?y.time<=0:y.time>=N;T.finished&&F&&P(),y.paused=!1,y.enabled=!0,a.delete(m)}p(y,m),T={action:y,speed:o(m)?.speed??c.get(m)??l,reverse:I,finished:!1},T.speed=He(T.speed),f(T),a.set(m,T),n()},S=m=>{for(let b of d(m))a.get(b).action.paused=!0;n()},w=m=>{for(let b of d(m))C(b);if(!u(m)){for(let b of i)b.stop();i.clear()}n()},A=(m,b)=>{let y=He(m);u(b)?c.set(b,y):l=y;for(let k of d(b)){let I=a.get(k);c.set(k,y),I.speed=y,f(I)}n()},h=(m,b)=>{for(let y of d(b)){let k=a.get(y),I=k.action.getClip().duration,N=Math.min(Math.max(m,0),I);k.action.time=Jn(k.action)?I-N:N,k.finished&&(k.finished=!1,k.action.paused=!0)}r.update(0),n()},x=()=>{for(let[m,b]of[...a]){let y=o(m);if(y?.hidden){C(m);continue}p(b.action,m),y?.speed!==void 0&&(b.speed=He(y.speed),f(b))}n()},M=m=>{for(let b of a.values())b.action===m.action&&(b.finished=!0);n()};return r.addEventListener("finished",M),{play:R,pause:S,stop:w,setSpeed:A,seek:h,getState:()=>{let m=[...a].map(([y,k])=>({clip:y,status:k.finished?"finished":k.action.paused?"paused":"playing",time:Cr(k.action),duration:k.action.getClip().duration,speed:k.speed,reverse:k.reverse})),b=m[m.length-1];return{currentClip:b?.clip??null,isPlaying:m.some(y=>y.status==="playing"),speed:b?.speed??l,time:b?.time??0,duration:b?.duration??0,active:m}},applyClipConfigs:x,isRunning:()=>{if(i.size>0)return!0;for(let{action:m}of a.values())if(!m.paused&&m.enabled)return!0;return!1},update:m=>{r.update(m);for(let b of i)(!b.enabled||b.getEffectiveWeight()<=0)&&(b.stop(),i.delete(b))},dispose:()=>{r.removeEventListener("finished",M),r.stopAllAction(),r.uncacheRoot(e),a.clear(),i.clear()}}}var Pt=require("three");var nt=require("react"),Tt=require("three");function Qn(e){return[e.x,e.y,e.z]}function eo(e,t){let o=new Tt.Vector3,n=new Tt.Vector3;return t.getPosition(o),t.getTarget(n),{position:Qn(o),target:Qn(n),fov:"fov"in e&&typeof e.fov=="number"?e.fov:null,zoom:"zoom"in e&&typeof e.zoom=="number"?e.zoom:1,azimuthAngle:t.azimuthAngle,polarAngle:t.polarAngle}}var ce=require("three");function kr(e){return new ce.Matrix4().set(1,e[0],e[1],0,0,1,e[2],0,0,0,1,0,0,0,0,1)}function Rt(e,t){e.matrixAutoUpdate=!t,e.updateMatrix(),t&&(e.matrix.makeRotationFromQuaternion(e.quaternion).multiply(kr(t)).scale(e.scale).setPosition(e.position),e.matrixWorldNeedsUpdate=!0)}function to(e,t,o){let n=new ce.Vector3().setFromMatrixColumn(e,0),r=new ce.Vector3().setFromMatrixColumn(e,1),s=new ce.Vector3().setFromMatrixColumn(e,2),a=(C,R)=>{let S=C*(R<0?-1:1);return Math.abs(S-R)<1e-10?R:S},i=a(n.length(),t.x);if(Math.abs(i)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};n.divideScalar(i);let c=n.dot(r);r.addScaledVector(n,-c);let l=a(r.length(),t.y);if(Math.abs(l)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};r.divideScalar(l);let u=n.dot(s);s.addScaledVector(n,-u);let d=r.dot(s);s.addScaledVector(r,-d);let p=a(s.length(),t.z);if(Math.abs(p)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};s.divideScalar(p);let f=[c/l,u/p,d/p].map(C=>Math.abs(C)<1e-10?0:C);return{rotation:new ce.Quaternion().setFromRotationMatrix(new ce.Matrix4().makeBasis(n,r,s)).normalize(),scale:new ce.Vector3(i,l,p),shear:f.some(Boolean)?f:void 0}}var It=e=>e==="baseColor"?"color":e;function no(e){let t=new Set;return e.traverse(o=>{let n=o;if(n.isMesh)for(let r of Array.isArray(n.material)?n.material:[n.material])r&&t.add(r)}),[...t]}function oo({root:e,controls:t,animations:o,invalidate:n,cameraEnabled:r=()=>!0}){let s=new Map,a=new Map,i=new Map,c=new Set,l=new Map,u=null,d="",p=h=>e()?Jt(e(),h):null,f=h=>{if(h.kind==="camera"){let D=t();if(!D)return null;let g=eo(D.camera,D);return{position:g.position,target:g.target,fov:g.fov,zoom:g.zoom}}if(h.kind==="clip"){let D=o();return D?.clips.includes(h.clip)?D.getState?.().active.find(g=>g.clip===h.clip)?.time??0:null}let x=p(h.objectId);if(!x)return null;let M=h.property;if(M==="position"||M==="rotation"||M==="scale")return[x[M].x,x[M].y,x[M].z];if(M==="visible")return x.visible;let E=no(x).find(D=>D[It(M)]!==void 0),j=E?E[It(M)]:void 0;return j?.isColor?`#${j.getHexString()}`:typeof j=="number"?j:null},C=h=>{if(!r())return;let x=t();x&&(x.stop(),x.setLookAt(...h.position,...h.target,!1),h.fov!==null&&"fov"in x.camera&&(x.camera.fov=h.fov,x.camera.updateProjectionMatrix()),x.zoomTo(h.zoom,!1),x.update(0))},R=h=>{if(s.has(h))return;h.updateWorldMatrix(!0,!0);let x=h.matrixAutoUpdate?void 0:to(h.matrix,h.scale,h.quaternion).shear;s.set(h,{position:h.position.toArray(),rotation:[h.rotation.x,h.rotation.y,h.rotation.z],scale:h.scale.toArray(),matrix:h.matrix.clone(),auto:h.matrixAutoUpdate,shear:x});for(let M of Hn(h))Kn(M)||(tt(M,M.matrixWorld),c.add(M))},S=(h,x)=>{let M=o();M?.stop(h),x&&M&&(M.play(h,{alongside:!0,reverse:x.reverse}),M.setSpeed(x.speed,h),M.seek?.(x.time,h),x.status!=="playing"&&M.pause(h))};return{capture:f,restore:()=>{for(let[h,x]of l)S(h,x);l.clear();for(let[h,x]of s)h.position.fromArray(x.position),h.rotation.set(...x.rotation),h.scale.fromArray(x.scale),h.matrix.copy(x.matrix),h.matrixAutoUpdate=x.auto,h.matrixWorldNeedsUpdate=!0;s.clear(),a.forEach((h,x)=>x.visible=h),a.clear(),i.forEach((h,x)=>{h.forEach((M,E)=>{M instanceof Pt.Color?x[E].copy(M):x[E]=M}),x.needsUpdate=!0}),i.clear(),c.forEach(Xn),c.clear(),u&&C(u),u=null,d="",e()?.updateWorldMatrix(!0,!0),n()},inspect:h=>h.tracks.filter(x=>!x.muted&&x.keyframes.length&&(x.target.kind!=="camera"||r())&&f(x.target)===null).map(x=>`Unavailable target: ${x.name}.`),invalidate:n,apply:({sequence:h,time:x,playing:M})=>{let E=h.tracks.filter(g=>g.target.kind!=="camera"||r()).map(g=>({track:g,value:We(g,x)})).filter(g=>g.value!==null);for(let[g,m]of l)E.some(({track:b})=>b.target.kind==="clip"&&b.target.clip===g)||(S(g,m),l.delete(g));for(let{track:g}of E)if(g.target.kind==="object"&&["position","rotation","scale"].includes(g.target.property)){let m=p(g.target.objectId);m&&R(m)}let j=new Map([...i.keys()].map(g=>[g,g.transparent]));a.forEach((g,m)=>m.visible=g),s.forEach((g,m)=>{m.position.fromArray(g.position),m.rotation.set(...g.rotation),m.scale.fromArray(g.scale),Rt(m,g.shear)}),i.forEach((g,m)=>g.forEach((b,y)=>{b instanceof Pt.Color?m[y].copy(b):m[y]=b}));let D=o();for(let{track:g,value:m}of E){if(g.target.kind!=="clip"||!D?.seek||!D.clips.includes(g.target.clip))continue;let b=g.target.clip;l.has(b)||(l.set(b,D.getState?.().active.find(y=>y.clip===b)),D.play(b,{alongside:!0}),D.pause(b)),D.seek(m,b)}for(let{track:g,value:m}of E){let b=g.target;if(b.kind==="clip")continue;if(b.kind==="camera"){u||(u=f(b));let I=JSON.stringify(m);(M||I!==d)&&(C(m),d=I);continue}let y=p(b.objectId);if(!y)continue;let k=b.property;if(k==="visible")a.has(y)||a.set(y,y.visible),y.visible=m;else if(k==="position"||k==="rotation"||k==="scale")k==="rotation"?y.rotation.set(...m):y[k].fromArray(m),Rt(y,s.get(y)?.shear);else for(let I of no(y)){let N=It(k),T=I[N];if(T===void 0)continue;let P=i.get(I);if(P||(P=new Map,i.set(I,P)),j.has(I)||j.set(I,I.transparent),P.has(N)||P.set(N,T?.isColor?T.clone():T),T?.isColor?T.set(m):I[N]=m,k==="opacity"){P.has("transparent")||P.set("transparent",I.transparent);let F=m<1||P.get("transparent")===!0;I.transparent=F}}}u&&!E.some(({track:g})=>g.target.kind==="camera")&&(C(u),d=""),j.forEach((g,m)=>{g!==m.transparent&&(m.needsUpdate=!0)}),e()?.updateWorldMatrix(!0,!0)}}}function ro(e){let t=new Map;return e.map((o,n)=>{let s=o.name.trim()||`Animation ${n+1}`,a=t.get(s)??0;return t.set(s,a+1),{clip:o,sourceName:a===0?s:`${s} (${a+1})`,duration:o.duration}})}var X=require("three");function Or(e){let t=e.getAttribute("arSourceVertex"),o=e.getAttribute("arNormalSign");if(!t)return;let n=new Map,r=[],s=[];for(let i=0;i<t.count;i++){let c=`${t.getX(i)}:${o?.getX(i)??1}`,l=n.get(c);l===void 0&&(l=r.length,r.push(i),n.set(c,l)),s.push(l)}let a=e.index?Array.from(e.index.array,i=>s[i]):s;for(let[i,c]of Object.entries(e.attributes)){let l=new Float32Array(r.length*c.itemSize);r.forEach((u,d)=>{for(let p=0;p<c.itemSize;p++)l[d*c.itemSize+p]=c.getComponent(u,p)}),e.setAttribute(i,new X.BufferAttribute(l,c.itemSize))}e.setIndex(a)}function io(e,t,o,n){let r=[],s=[],a=new Map;for(let i of e){let c=i.source;if(!c.isSkinnedMesh)continue;let l=t.get(c),u=c.skeleton,d=JSON.stringify(u.bones.map((g,m)=>[g.uuid,u.boneInverses[m].elements])),p=a.get(d);if(!p){let g=new Map(u.bones.map((T,P)=>[T,P])),m=u.bones.map(T=>{for(let P=T.parent;P;P=P.parent)if(g.has(P))return g.get(P);return-1}),b=[],y=T=>{b.includes(T)||(m[T]>=0&&y(m[T]),b.push(T))};u.bones.forEach((T,P)=>y(P));let k=b.map(T=>b.indexOf(m[T])),I=[];b.forEach((T,P)=>I.push(`${k[P]<0?"":I[k[P]]+"/"}J_${T}`));let N={name:`${n}_${r.length}`,joints:I,parents:k,bones:b.map(T=>t.get(u.bones[T])),bindTransforms:b.map(T=>u.boneInverses[T].clone().invert()),restTransforms:[],worlds:b.map(()=>new X.Matrix4),referenceInverse:o.clone().invert(),frames:[]};if(N.bones.some(T=>!T))throw new Error("The AR skeleton has joints outside the exported scene.");p={rig:N,order:b},a.set(d,p),r.push(N)}Or(i.exported.geometry);let f=i.exported.geometry.getAttribute("arSourceVertex"),C=c.geometry.getAttribute("skinIndex"),R=c.geometry.getAttribute("skinWeight");if(!f||!C||!R||C.itemSize!==4||R.itemSize!==4)throw new Error("AR skeletal animation needs four joint indices and weights per vertex.");let S={target:i,node:l,rig:p.rig,reference:o,geomBind:c.bindMatrix.clone(),jointIndices:[],jointWeights:[],jointBounds:p.order.map(()=>new X.Box3),extent:new X.Box3},w=i.exported.geometry.getAttribute("position"),A=i.exported.geometry.getAttribute("normal"),h=c.geometry.getAttribute("normal"),x=i.exported.geometry.getAttribute("arNormalSign"),M=new X.Vector3,E=new X.Vector3,j=new Map(p.order.map((g,m)=>[g,m])),D=S.rig.bindTransforms.map(g=>g.clone().invert().multiply(c.bindMatrix));for(let g=0;g<f.count;g++){let m=f.getX(g);if(X.Mesh.prototype.getVertexPosition.call(c,m,M),w.setXYZ(g,M.x,M.y,M.z),h&&A){E.fromBufferAttribute(h,m);let y=E.clone();c.geometry.morphAttributes.normal?.forEach((k,I)=>{let N=c.morphTargetInfluences?.[I]??0;N&&E.addScaledVector(new X.Vector3().fromBufferAttribute(k,m).sub(c.geometry.morphTargetsRelative?new X.Vector3:y),N)}),E.normalize().multiplyScalar(x?.getX(g)??1),A.setXYZ(g,E.x,E.y,E.z)}let b=[0,1,2,3].reduce((y,k)=>y+R.getComponent(m,k),0);if(!Number.isFinite(b)||b<=0)throw new Error("The AR skin has a vertex without valid joint weights.");for(let y=0;y<4;y++){let k=R.getComponent(m,y)/b,I=k?j.get(C.getComponent(m,y))??-1:0;if(I<0||!Number.isFinite(k)||k<0)throw new Error("The AR skin has invalid joint indices or weights.");S.jointIndices.push(I),S.jointWeights.push(k),k&&S.jointBounds[I].expandByPoint(M.clone().applyMatrix4(D[I]))}}w.needsUpdate=!0,A?A.needsUpdate=!0:i.exported.geometry.computeVertexNormals(),i.exported.geometry.computeBoundingBox(),i.exported.matrixAutoUpdate=!1,i.exported.matrix.copy(Vt(S)),s.push(S)}return{rigs:r,skins:s}}function Vt(e){return e.node.matrixWorld.clone().multiply(e.node.bindMatrixInverse).multiply(e.reference)}function so(e,t,o){let n=new X.Vector3,r=new X.Quaternion,s=new X.Vector3,a=new X.Matrix4;for(let i of e){let c={time:o,translations:[],rotations:[],scales:[]};i.bones.forEach((l,u)=>i.worlds[u].multiplyMatrices(i.referenceInverse,l.matrixWorld)),i.worlds.forEach((l,u)=>{let d=i.parents[u],p=d<0?l.clone():i.worlds[d].clone().invert().multiply(l);p.decompose(n,r,s),r.normalize(),a.compose(n,r,s);let f=1e-5*Math.max(1,...p.elements.map(Math.abs));if(!p.elements.every(Number.isFinite)||p.elements.some((C,R)=>Math.abs(C-a.elements[R])>f)||Math.abs(p.determinant())<1e-15)throw new Error("The AR skeleton contains a sheared or zero-scale joint that Quick Look cannot preserve. Use arHandoff.createUSDZ for this rig.");c.translations.push(...n.toArray()),c.rotations.push(r.w,r.x,r.y,r.z),c.scales.push(...s.toArray()),i.frames.length||i.restTransforms.push(p)}),i.frames.push(c)}for(let i of t)i.jointBounds.forEach((c,l)=>{c.isEmpty()||i.extent.union(c.clone().applyMatrix4(i.rig.worlds[l]))})}var Dt=e=>String(Number(e.toPrecision(9))),Bt=e=>{let t=Array.isArray(e)?e:e.elements;return`(${[0,4,8,12].map(o=>`(${t.slice(o,o+4).map(Dt).join(", ")})`).join(", ")})`},Et=(e,t)=>Array.from({length:e.length/t},(o,n)=>`(${e.slice(n*t,(n+1)*t).map(Dt).join(", ")})`).join(", ");function ao(e){let t=(a,i,c=1e-7)=>Math.abs(a-i)>c*Math.max(1,Math.abs(a),Math.abs(i)),o=[["translations",3,"float3"],["rotations",4,"quatf"],["scales",3,"half3"]],n=e.frames[0],r=e.joints.map((a,i)=>i).filter(a=>o.some(([i,c])=>e.frames.some(l=>l[i].slice(a*c,(a+1)*c).some((u,d)=>t(u,n[i][a*c+d])))));r.length||(r=e.joints.map((a,i)=>i));let s=o.map(([a,i,c])=>{let l=e.frames.map(d=>r.flatMap(p=>d[a].slice(p*i,(p+1)*i)));return l.some(d=>d.some((p,f)=>t(p,l[0][f],c==="half3"?1e-4:1e-7)))?`${c}[] ${a}.timeSamples = {${e.frames.map((d,p)=>`${d.time}: [${Et(l[p],i)}]`).join(`,
1
+ "use strict";var Ro=Object.create;var Fe=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var Po=Object.getOwnPropertyNames;var Bo=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Vo=(e,t)=>{for(var o in t)Fe(e,o,{get:t[o],enumerable:!0})},Ut=(e,t,o,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Po(t))!Eo.call(e,r)&&r!==o&&Fe(e,r,{get:()=>t[r],enumerable:!(n=Io(t,r))||n.enumerable});return e};var _t=(e,t,o)=>(o=e!=null?Ro(Bo(e)):{},Ut(t||!e||!e.__esModule?Fe(o,"default",{value:e,enumerable:!0}):o,e)),Do=e=>Ut(Fe({},"__esModule",{value:!0}),e);var Nr={};Vo(Nr,{ACTION_CATALOG:()=>Ve,DEFAULT_MODEL_VIEWER_LABELS:()=>jt,DEFAULT_SCENE_CONFIG:()=>be,DEFAULT_SECTION_CONFIG:()=>on,MATERIAL_BLENDING_MODES:()=>nn,MATERIAL_SIDES:()=>tn,MAX_VIEWER_STATE_BYTES:()=>me,MEASUREMENT_UNITS:()=>xt,SEQUENCE_EASINGS:()=>bt,SEQUENCE_OBJECT_PROPERTIES:()=>gt,applyIsolation:()=>Yt,applyProductOptions:()=>In,applyStyleRules:()=>Wt,buildBindingsFromNodes:()=>en,calibrateMeasurements:()=>gn,chooseMaterialVariant:()=>qe,collectObjectHierarchy:()=>_n,colorScaleValue:()=>at,compareViewerConfigurations:()=>jo,copyBindingStyle:()=>zn,createARHandoffUrl:()=>Ao,createDefaultBinding:()=>dt,decodeProductSelections:()=>Cn,defaultProductSelections:()=>Te,defineObjectBindings:()=>zt,encodeProductSelections:()=>kt,evaluateProductConfiguration:()=>ae,exportConfiguredUSDZ:()=>bo,findCatalogAction:()=>Zt,formatProductPrice:()=>An,generateProductSkus:()=>kn,groundAsset:()=>cn,inferType:()=>ut,inspectAsset:()=>qn,isolatedBindingKeys:()=>ct,material:()=>qt,measurementResult:()=>At,measurementScale:()=>Mt,measurementValue:()=>Xe,measurementsToCsv:()=>hn,parseAssetTransform:()=>je,parseMeasurements:()=>we,parseProductConfiguration:()=>Rn,parseProductDefinition:()=>Ct,parseSceneProduct:()=>Ze,parseSectionConfig:()=>De,parseSelectionSets:()=>Ye,parseSequences:()=>Oe,parseViewerState:()=>Re,pasteBindingStyle:()=>Fn,patchBindings:()=>$e,patchSceneConfig:()=>Gt,prepareViewerState:()=>Qe,productCheckoutUrl:()=>vn,productDefinitionWarnings:()=>On,productOptionStates:()=>jn,productPriceFromDefinition:()=>Mn,readARHandoffUrl:()=>vo,resolveProductSelections:()=>Je,sampleSequenceTrack:()=>We,sceneLight:()=>Ht,sectionSnapshot:()=>rn,selectBindingKeys:()=>Q,selectBindings:()=>$t,serializeMeasurements:()=>bn,serializeProductConfiguration:()=>Tn,serializeViewerState:()=>Un,snapAssetToGrid:()=>an,upsertSequenceKeyframe:()=>sn});module.exports=Do(Nr);function zt(e){return e}function it(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Be(e,t){if(!it(t))return t;let o=it(e)?{...e}:{};for(let n of Object.keys(t)){let r=t[n];o[n]=it(r)?Be(o[n],r):r}return o}function Ft(e,t){if(e[t])return t;let o=Object.entries(e).find(([,r])=>r.id===t)?.[0];return o||(Object.entries(e).find(([,r])=>r.modelObjectId===t)?.[0]??null)}function No(e){return typeof e=="object"&&!Array.isArray(e)}function Lo(e,t){return"group"in t?e.group===t.group:"tag"in t?e.tags?.includes(t.tag)??!1:(e.type??"other")===t.type}function Q(e,t){if(No(t))return Object.entries(e).filter(([,r])=>Lo(r,t)).map(([r])=>r);let n=(typeof t=="string"?[t]:t).map(r=>Ft(e,r)).filter(r=>r!==null);return[...new Set(n)]}function $t(e,t){return Q(e,t).map(o=>e[o]).filter(o=>o!==void 0)}function Uo(e){return Array.isArray(e)&&e.length>0&&typeof e[0]!="string"}function $e(e,t,o){let n=Uo(t)?t:[{ids:t,patch:o??{}}],r=e;for(let s of n)for(let a of Q(r,s.ids)){let i=r[a];if(!i)continue;let c=Be(i,s.patch);r===e&&(r={...e}),r[a]=c}return r}function qt(e){return{style:{material:e}}}function Gt(e,t){return Be(e,t)}var _o={type:"point",color:"#ffffff",intensity:1,position:[0,0,0],distance:0,decay:2,attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0};function Ht(e){return{..._o,...e}}var zo="#ff3b30",Fo=Object.freeze({}),Kt=e=>e;function $o(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qo(e,t){let o=e.metadata;for(let n of t.split(".")){if(!$o(o))return;o=o[n]}return o}function Go(e,t){if("metric"in t){let o=e.metrics?.[t.metric];return!(typeof o!="number"||!Number.isFinite(o)||t.above!==void 0&&!(o>t.above)||t.below!==void 0&&!(o<t.below))}if("status"in t){let o=e.status??"normal";return Array.isArray(t.status)?t.status.includes(o):t.status===o}return qo(e,t.metadata)===t.equals}function Ho(e){let t=e.trim().replace(/^#/,""),o=t.length===3?t.split("").map(n=>n+n).join(""):t;return/^[0-9a-f]{6}$/i.test(o)?[0,2,4].map(n=>parseInt(o.slice(n,n+2),16)):null}var st=e=>`#${e.map(t=>Math.round(t).toString(16).padStart(2,"0")).join("")}`;function at(e,t){let o=e.map(([c,l])=>({at:c,rgb:Ho(l)})).filter(c=>Number.isFinite(c.at)&&c.rgb!==null).sort((c,l)=>c.at-l.at);if(o.length===0||!Number.isFinite(t))return null;if(t<=o[0].at)return st(o[0].rgb);let n=o[o.length-1];if(t>=n.at)return st(n.rgb);let r=o.findIndex(c=>c.at>=t),s=o[r-1],a=o[r],i=a.at===s.at?1:(t-s.at)/(a.at-s.at);return st(s.rgb.map((c,l)=>c+(a.rgb[l]-c)*i))}function Wt(e,t){if(!t?.length)return{bindings:e,pulses:Fo,sourceOf:Kt};let o=new Map,n={};for(let a of t){let i=a.target?Q(e,a.target):Object.keys(e),c=a.when?Array.isArray(a.when)?a.when:[a.when]:[];for(let l of i){let u=e[l];if(!c.every(p=>Go(u,p)))continue;let d={...a.material};if(a.colorScale){let p=u.metrics?.[a.colorScale.metric],f=typeof p=="number"?at(a.colorScale.stops,p):null;f&&(d={...d,[a.colorScale.channel??"baseColor"]:f})}if(a.pulse){let p=a.pulse===!0?{}:a.pulse;n[l]={color:p.color??zo,speed:p.speed!==void 0&&p.speed>0?p.speed:1};let f=d.emissiveIntensity??o.get(l)?.emissiveIntensity??u.style?.material?.emissiveIntensity;f!==void 0&&f>0||(d.emissiveIntensity=1)}Object.keys(d).length>0&&o.set(l,{...o.get(l),...d})}}if(o.size===0)return{bindings:e,pulses:n,sourceOf:Kt};let r={...e},s=new WeakMap;for(let[a,i]of o){let c=e[a],l={...c,style:{...c.style,material:{...c.style?.material,...i}}};r[a]=l,s.set(l,c)}return{bindings:r,pulses:n,sourceOf:a=>s.get(a)??a}}function qe(e,t,o){let n=o.find(s=>s.variants.some(a=>a.name===t)),r=new Set(n?.variants.map(s=>s.name)??[t]);return[...e.filter(s=>!r.has(s)),t]}var Ko=.12,Xt=new Set;function ct(e,t){return t?new Set(Q(e,t.target)):Xt}function Yt(e,t){let o=ct(e.bindings,t);if(!t||o.size===0)return{...e,setAside:Xt};let n=Math.min(Math.max(t.ghostOpacity??Ko,0),1),r={...e.bindings},s=new WeakMap,a=new Set;for(let[i,c]of Object.entries(e.bindings)){if(o.has(i))continue;a.add(i);let l=t.mode==="hide"?{...c,visible:!1}:{...c,style:{...c.style,material:{...c.style?.material,opacity:Math.min(c.style?.material?.opacity??1,n)}}};r[i]=l,s.set(l,e.sourceOf(c))}return{bindings:r,pulses:e.pulses,sourceOf:i=>s.get(i)??e.sourceOf(i),setAside:a}}var Wo=require("three"),lt=Symbol("react-immersive.model-node-id");function Xo(e,t){Object.defineProperty(e,lt,{value:t,configurable:!0})}function Ge(e){let t=new Map;e.traverse(c=>{if(!c.name)return;let l=t.get(c.name);l?l.push(c):t.set(c.name,[c])});let o=Object.create(null),n=new WeakMap,r=new Map,s=new Set(Array.from(t,([c,l])=>l.length===1?c:null).filter(c=>c!==null)),a=new Set,i=(c,l)=>{Xo(c,l),o[l]=c,n.set(c,l),a.add(l)};for(let[c,l]of t)l.length===1&&i(l[0],c);for(let[c,l]of t){if(l.length<2)continue;let u=[];l.forEach((d,p)=>{let f=`${c} [${p+1}]`,C=f,R=2;for(;s.has(C)||a.has(C);)C=`${f}.${R++}`;i(d,C),u.push(C)}),r.set(c,u)}return{nodesById:o,idByNode:n,duplicateNames:r}}function Ee(e){return e[lt]??e.name??null}function Jt(e,t){let o=null,n=[];return e.traverse(r=>{r[lt]===t&&(o=r),r.name===t&&n.push(r)}),o??(n.length===1?n[0]:null)}var Ve=Object.freeze([{id:"change-color",label:"Change Color",handling:"viewer",description:"Opens a color picker docked under the action and commits the result to style.material.baseColor."},{id:"change-material",label:"Change Material",handling:"viewer",description:"Opens the material picker so the viewer can swap the object's texture."},{id:"add-text",label:"Add Text",handling:"viewer",description:"Opens a text box docked under the action; the viewer's user types, clicks the object to place it, and can resize, turn, move, or remove it. Saved to the binding's decals."},{id:"add-image",label:"Add Image",handling:"viewer",description:"Lets the viewer's user choose an image, click the object to place it, and resize, turn, move, or remove it. Saved to the binding's decals."},{id:"toggle-visibility",label:"Toggle Visibility",handling:"viewer",description:"Flips the binding's visible flag."},{id:"toggle-light",label:"Toggle Light",handling:"viewer",description:"Turns the scene lights attached to this object on or off, or the object's own glow when none is attached."},{id:"change-light-color",label:"Change Light Color",handling:"viewer",description:"Opens a color picker docked under the action for the scene lights attached to this object, or the object's own glow."},{id:"set-brightness",label:"Set Brightness",handling:"viewer",description:"Opens a brightness slider docked under the action for the scene lights attached to this object, or the object's own glow."}]);function Zt(e){return Ve.find(t=>t.id===e)}var ni=Ve.filter(e=>e.handling==="viewer").map(e=>e.id),oi=new Set(["","New Action",...Ve.map(e=>e.label)]);var ge=require("three");function He(e){return Number.isFinite(e)&&e>0?e:1}function Qt(e){return e?.loopMode??"repeat"}function Yo(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/[^a-zA-Z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()}function Jo(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ut(e){let t=e.toLowerCase();return t.includes("light")?"light":t.includes("wheel")||t.includes("rim")||t.includes("tire")?"wheel":t.includes("glass")||t.includes("window")||t.includes("windshield")||t.includes("sunroof")?"glass":t.includes("seat")||t.includes("dashboard")||t.includes("console")||t.includes("doorpanel")?"interior":t.includes("floor")?"floor":t.includes("wall")?"wall":t.includes("door")?"door":t.includes("chair")||t.includes("table")||t.includes("sofa")||t.includes("bed")?"furniture":"other"}function Zo(e,t=!0){return e==="light"||e.endsWith("light")?[{id:"toggle-light",label:"Toggle Light",type:"command"},{id:"change-light-color",label:"Change Light Color",type:"command"},{id:"set-brightness",label:"Set Brightness",type:"command"}]:[{id:"change-color",label:"Change Color",type:"command"},...t?[{id:"change-material",label:"Change Material",type:"command"}]:[],{id:"toggle-visibility",label:"Toggle Visibility",type:"command"}]}function dt(e,t=!0){let o=ut(e);return{id:Yo(e),modelObjectId:e,type:o,label:Jo(e),status:"normal",selectable:!0,hoverable:!0,visible:!0,style:{},actions:Zo(o,t),metrics:{},metadata:{}}}function en(e,t){return Object.fromEntries(e.map(o=>[o,dt(o,!t?.has(o))]))}var tn=["front","back","double"],nn=["normal","additive"];var on={enabled:!1,axis:"y",position:.5,flip:!1},Qo={clips:[],autoplayClip:null},er={autofocus:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6,target:[0,0,0],mouse:!0,debug:0,manual:!1,smoothTime:.25},toneMapping:{enabled:!1,mode:"aces",exposure:1,resolution:256,whitePoint:4,middleGrey:.6,minLuminance:.01,averageLuminance:1,adaptationRate:1},brightnessContrast:{enabled:!1,brightness:0,contrast:0},hueSaturation:{enabled:!1,hue:0,saturation:0},colorAverage:{enabled:!1},dotScreen:{enabled:!1,angle:Math.PI/2,scale:1},glitch:{enabled:!1,mode:"sporadic",delay:[1.5,3.5],duration:[.6,1],strength:[.3,1],chromaticAberrationOffset:[0,0],columns:.05,ratio:.85},ssao:{enabled:!1,samples:30,rings:4,intensity:8,radius:.25,bias:.025,luminanceInfluence:.6,fade:.01,minRadiusScale:.33,worldDistanceThreshold:20,worldDistanceFalloff:5,worldProximityThreshold:6,worldProximityFalloff:3},bloom:{enabled:!1,intensity:.3,luminanceThreshold:.9,luminanceSmoothing:.2,mipmapBlur:!0,radius:0,levels:8},godRays:{enabled:!1,sunPosition:[5,10,5],samples:60,density:.96,decay:.9,weight:.4,exposure:.6,clampMax:1,blur:!0,kernelSize:"small"},grid:{enabled:!1,scale:1,lineWidth:0},noise:{enabled:!1,opacity:1,premultiply:!1},depthOfField:{enabled:!1,focusDistance:5,focusRange:5,focalLength:.02,bokehScale:6},chromaticAberration:{enabled:!1,offsetX:.002,offsetY:.002,radialModulation:!1,modulationOffset:.15},lensflare:{enabled:!1,lensPosition:[-25,6,-60],smoothTime:.07,glareSize:.2,flareSize:.01,flareSpeed:.01,flareShape:.01,animated:!0,anamorphic:!1,colorGain:"#141414",haloScale:.5,secondaryGhosts:!0,aditionalStreaks:!0,ghostScale:0,opacity:1,starBurst:!1},vignette:{enabled:!1,offset:.3,darkness:.3,eskil:!1},smaa:{enabled:!1},sepia:{enabled:!1,intensity:0},scanline:{enabled:!1,density:1.25},pixelation:{enabled:!1,granularity:5},outline:{enabled:!1,selectionLayer:10,edgeStrength:2.5,pulseSpeed:0,visibleEdgeColor:"#ffffff",hiddenEdgeColor:"#22090a",kernelSize:"large",blur:!1,xRay:!0},selectiveBloom:{enabled:!1,selectionLayer:10,intensity:1,luminanceThreshold:.9,luminanceSmoothing:.025,kernelSize:"large",mipmapBlur:!0,inverted:!1,ignoreBackground:!1},ramp:{enabled:!1,rampType:"linear",rampStart:[.5,.5],rampEnd:[1,1],startColor:"#000000",endColor:"#ffffff",opacity:.5,rampBias:.5,rampGain:.5,rampMask:!1,rampInvert:!1}},be={model:{rotation:[0,0,0],showAdvancedRotation:!1,renderer:"pbr",shading:"lit",autoRotate:!1,autoRotateSpeed:1},camera:{fieldOfView:50,showAdvancedSettings:!1},lighting:{ambient:{intensity:.25,color:"#ffffff"},lights:[{id:"light-hemi",type:"hemisphere",color:"#ffffff",intensity:.3,position:[0,1,0],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0},{id:"light-key",type:"directional",color:"#ffffff",intensity:2.5,position:[6,12,6],attachedToCamera:!1,castShadow:!0,shadowBias:-5e-4,visible:!0},{id:"light-fill",type:"directional",color:"#ffffff",intensity:0,position:[-6,8,-6],attachedToCamera:!1,castShadow:!1,shadowBias:-5e-4,visible:!0}]},shadows:{enabled:!0,mapSize:2048,bias:-5e-4,normalBias:.02,radius:3},environment:{source:"preset",preset:"neutral",customEnvironmentUrl:"",intensity:.25,rotation:0,shadowLight:{enabled:!1,intensity:2.5,bias:-5e-4}},wireframe:{enabled:!1,color:"#000000",opacity:1},background:{enabled:!1,type:"color",color:"#1c1c1d",imageUrl:""},groundShadows:{enabled:!1,mode:"shadowCatcher",intensity:.7,borderFade:1,height:0,size:10},postProcessing:er,animations:Qo,annotations:[]};function De(e){let t=u=>{throw new Error(`Invalid section: ${u}`)},o=u=>u&&typeof u=="object"&&!Array.isArray(u)?u:t("expected an object"),n=u=>typeof u=="string"&&u.trim().length>0&&u.length<=200?u:t("expected a nonempty name or id (up to 200 characters)"),r=u=>typeof u=="number"&&Number.isFinite(u)&&u>=0&&u<=1?u:t("position must be between 0 and 1"),s=u=>!Array.isArray(u)||u.length!==3||!u.every(d=>typeof d=="number"&&Number.isFinite(d))||Math.hypot(...u)<1e-8?t("normal must be a finite, nonzero vector"):[...u],a=u=>{let d=o(u);return!["x","y","z"].includes(d.axis)||typeof d.enabled!="boolean"||typeof d.flip!="boolean"?t("invalid plane"):{enabled:d.enabled,axis:d.axis,position:r(d.position),flip:d.flip,...d.normal!==void 0?{normal:s(d.normal)}:{}}},i=u=>{let d=o(u),p=a(d);if(d.mode!==void 0){if(!["plane","planes","box"].includes(d.mode))return t("invalid mode");p.mode=d.mode}if(d.planes!==void 0){if(!Array.isArray(d.planes)||d.planes.length>6)return t("at most six planes are supported");let f=new Set;p.planes=d.planes.map(C=>{let R=o(C),S=n(R.id);return f.has(S)?t("duplicate plane id"):(f.add(S),{...a(R),id:S,name:n(R.name)})})}if(d.activePlaneId!==void 0&&(p.activePlaneId=n(d.activePlaneId)),d.invertBox!==void 0){if(typeof d.invertBox!="boolean")return t("invalid box inversion");p.invertBox=d.invertBox}if(d.box!==void 0){let f=o(d.box),C=w=>!Array.isArray(w)||w.length!==3?t("invalid box bounds"):w.map(r),R=C(f.min),S=C(f.max);if(R.some((w,A)=>w>=S[A]))return t("box minimum must be below its maximum on every axis");p.box={min:R,max:S}}return p},c=o(e),l=i(c);if(c.presets!==void 0){if(!Array.isArray(c.presets)||c.presets.length>32)return t("at most 32 presets are supported");let u=new Set;l.presets=c.presets.map(d=>{let p=o(d),f=n(p.id);return u.has(f)?t("duplicate preset id"):(u.add(f),{id:f,name:n(p.name),settings:i(p.settings)})})}return l}function rn(e){let{presets:t,...o}=De(e);return o}var ft=require("three"),gt=["position","rotation","scale","visible","baseColor","emissive","opacity","roughness","metalness","emissiveIntensity"],bt=["linear","ease-in","ease-out","ease-in-out","step"],tr=new Set(["position","rotation","scale"]),nr=new Set(["baseColor","emissive"]),ye=e=>typeof e=="string"&&e.length>0&&e.length<=256,xe=e=>typeof e=="number"&&Number.isFinite(e),mt=e=>Array.isArray(e)&&e.length===3&&e.every(xe);function Ne(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Se(e){throw new Error(`Invalid sequences: ${e}`)}function or(e){return e.kind==="object"?JSON.stringify([e.kind,e.objectId,e.property]):e.kind==="clip"?JSON.stringify([e.kind,e.clip]):"camera"}function rr(e,t){if(t.kind==="camera")return Ne(e)&&mt(e.position)&&mt(e.target)&&(e.fov===null||xe(e.fov)&&e.fov>0&&e.fov<180)&&xe(e.zoom)&&e.zoom>0;if(t.kind==="clip")return xe(e)&&e>=0;let o=t.property;return tr.has(o)?mt(e)&&(o!=="scale"||e.every(n=>n!==0)):nr.has(o)?typeof e=="string"&&/^#[\da-f]{6}$/i.test(e):o==="visible"?typeof e=="boolean":xe(e)&&e>=0&&(o==="emissiveIntensity"||e<=1)}function Oe(e){(!Array.isArray(e)||e.length>64)&&Se("expected up to 64 sequences.");let t=new Set,o=0;return e.map(n=>{(!Ne(n)||!ye(n.id)||t.has(n.id)||!(typeof n.name=="string"&&ye(n.name.trim()))||!xe(n.duration)||n.duration<.1||n.duration>3600||typeof n.loop!="boolean"||typeof n.autoPlay!="boolean"||!Array.isArray(n.tracks)||n.tracks.length>128)&&Se("each sequence needs a unique id, name, 0.1\u20133600 second duration, loop/autoplay flags and up to 128 tracks."),t.add(n.id);let r=new Set,s=new Set,a=n.tracks.map(i=>{(!Ne(i)||!ye(i.id)||r.has(i.id)||!(typeof i.name=="string"&&ye(i.name.trim()))||!Ne(i.target)||!Array.isArray(i.keyframes)||i.keyframes.length>2048||i.muted!==void 0&&typeof i.muted!="boolean")&&Se("invalid or duplicate track."),r.add(i.id);let c;i.target.kind==="camera"?c={kind:"camera"}:i.target.kind==="clip"&&ye(i.target.clip)?c={kind:"clip",clip:i.target.clip}:i.target.kind==="object"&&ye(i.target.objectId)&&gt.includes(i.target.property)?c={kind:"object",objectId:i.target.objectId,property:i.target.property}:Se("unknown track target or property.");let l=or(c);s.has(l)&&Se("only one track may own each target property in a sequence."),s.add(l);let u=new Set,d=new Set,p=i.keyframes.map(f=>{++o>2e4&&Se("too many keyframes."),(!Ne(f)||!ye(f.id)||u.has(f.id)||!xe(f.time)||f.time<0||f.time>n.duration||d.has(f.time)||f.easing!==void 0&&!bt.includes(f.easing)||!rr(f.value,c))&&Se("keyframes need unique ids/times, valid values and times inside the sequence."),u.add(f.id),d.add(f.time);let C=f.value,R=c.kind==="camera"?{position:[...C.position],target:[...C.target],fov:C.fov,zoom:C.zoom}:Array.isArray(f.value)?[...f.value]:f.value;return{id:f.id,time:f.time,value:R,...f.easing?{easing:f.easing}:{}}}).sort((f,C)=>f.time-C.time);return{id:i.id,name:i.name.trim(),target:c,keyframes:p,...i.muted!==void 0?{muted:i.muted}:{}}});return{id:n.id,name:n.name.trim(),duration:n.duration,loop:n.loop,autoPlay:n.autoPlay,tracks:a}})}function ir(e,t="ease-in-out"){let o=Math.max(0,Math.min(1,e));return t==="step"?0:t==="ease-in"?o*o:t==="ease-out"?1-(1-o)**2:t==="ease-in-out"?o*o*(3-2*o):o}var Ke=(e,t,o)=>e+(t-e)*o,pt=(e,t,o)=>e.map((n,r)=>Ke(n,t[r],o));function We(e,t){if(e.muted||!e.keyframes.length||!Number.isFinite(t))return null;let o=e.keyframes;if(t<o[0].time)return null;let n=o[0],r;for(let c of o)if(c.time<=t)n=c;else{r=c;break}if(!r||typeof n.value=="boolean")return structuredClone(n.value);let s=ir((t-n.time)/(r.time-n.time),n.easing);if(typeof n.value=="number"&&typeof r.value=="number")return Ke(n.value,r.value,s);if(typeof n.value=="string"&&typeof r.value=="string")return`#${new ft.Color(n.value).lerp(new ft.Color(r.value),s).getHexString()}`;if(Array.isArray(n.value)&&Array.isArray(r.value))return pt(n.value,r.value,s);let a=n.value,i=r.value;return{position:pt(a.position,i.position,s),target:pt(a.target,i.target,s),fov:a.fov!==null&&i.fov!==null?Ke(a.fov,i.fov,s):a.fov,zoom:Ke(a.zoom,i.zoom,s)}}function sn(e,t){return{...e,keyframes:[...e.keyframes.filter(o=>o.id!==t.id&&Math.abs(o.time-t.time)>1e-6),t].sort((o,n)=>o.time-n.time)}}var ee=require("three");function ht(e){return e.id??e.url}function je(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected an asset transform object.");let t={};for(let o of["position","rotation","scale"]){let n=e[o];if(n!==void 0){if(!Array.isArray(n)||n.length!==3||!n.every(r=>typeof r=="number"&&Number.isFinite(r))||o==="scale"&&n.some(r=>r===0))throw new Error(`Invalid asset ${o}: expected three finite ${o==="scale"?"nonzero ":""}numbers.`);t[o]=[...n]}}return t}function an(e,t){if(!Number.isFinite(t)||t<=0)throw new Error("Grid size must be positive.");let o=je(e),[n,r,s]=o.position??[0,0,0];return{...o,position:[Math.round(n/t)*t,r,Math.round(s/t)*t]}}function cn(e,t){let o=je(e),n=o.position??[0,0,0],r=new ee.Matrix4().compose(new ee.Vector3(...n),new ee.Quaternion().setFromEuler(new ee.Euler(...o.rotation??[0,0,0])),new ee.Vector3(...o.scale??[1,1,1])),s=new ee.Box3(new ee.Vector3(...t.min),new ee.Vector3(...t.max)).applyMatrix4(r);if(!Number.isFinite(s.min.y))throw new Error("Cannot place an asset with empty bounds.");return{...o,position:[n[0],n[1]-s.min.y,n[2]]}}var ue=require("three"),sr=new Map,yt={color:"#93c5fd",intensity:.07},Si=new ue.Color(yt.color).multiplyScalar(yt.intensity),xi=new ue.Color(yt.color);var ar=new Map;function ln(e){return ar.get(e)}function un(e){for(let t of sr.values())if(t.texture.source===e.source&&(!t.loaded||t.failed))return!0;return!1}var H=require("three");function dn(e){if(e.length!==3)return null;let t=new H.Vector3(...e[0]).sub(new H.Vector3(...e[1])),o=new H.Vector3(...e[2]).sub(new H.Vector3(...e[1]));return t.lengthSq()===0||o.lengthSq()===0?null:Math.acos(Math.max(-1,Math.min(1,t.normalize().dot(o.normalize()))))*180/Math.PI}function mn(e,t){if(!e.normal)return null;let o=new H.Vector3(...e.normal);if(o.lengthSq()===0)return null;o.normalize();let n=new H.Vector3(...t),r=n.clone().sub(new H.Vector3(...e.position)).dot(o);return{distance:Math.abs(r),projection:n.addScaledVector(o,-r).toArray()}}function pn(e){if(e.length<3)return{error:"Pick at least three points to finish the area."};let t=new H.Vector3(...e[0]),o=e.map(S=>new H.Vector3(...S).sub(t)),n=Math.max(...o.map(S=>S.length()));if(n===0)return{error:"Area points must be distinct."};let r=new H.Vector3;for(let S=1;S<o.length-1;S+=1){let w=o[S].clone().cross(o[S+1]);w.lengthSq()>r.lengthSq()&&r.copy(w)}if(r.length()<=n*n*1e-10)return{error:"Area points must not lie on one straight line."};r.normalize();let s=Math.max(n*1e-5,Number.EPSILON*Math.max(...e.flat().map(Math.abs))*32);if(o.some(S=>Math.abs(S.dot(r))>s))return{error:"Area points must lie on one plane."};let a=o.find(S=>S.length()>n*1e-10).clone().normalize(),i=r.clone().cross(a).normalize(),c=o.map(S=>new H.Vector2(S.dot(a),S.dot(i))),l=(S,w,A)=>(w.x-S.x)*(A.y-S.y)-(w.y-S.y)*(A.x-S.x),u=n*n*1e-10,d=(S,w,A)=>Math.abs(l(S,w,A))<=u&&A.x>=Math.min(S.x,w.x)-n*1e-10&&A.x<=Math.max(S.x,w.x)+n*1e-10&&A.y>=Math.min(S.y,w.y)-n*1e-10&&A.y<=Math.max(S.y,w.y)+n*1e-10;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length];if(w.distanceTo(A)<=n*1e-10)return{error:"Area points must be distinct."};for(let h=S+1;h<c.length;h+=1){if(h===S+1||S===0&&h===c.length-1)continue;let x=c[h],M=c[(h+1)%c.length],E=l(w,A,x),j=l(w,A,M),D=l(x,M,w),g=l(x,M,A);if(E*j<0&&D*g<0||d(w,A,x)||d(w,A,M)||d(x,M,w)||d(x,M,A))return{error:"Area edges must not cross or touch each other."}}}let p=0,f=0,C=0;for(let S=0;S<c.length;S+=1){let w=c[S],A=c[(S+1)%c.length],h=w.x*A.y-A.x*w.y;p+=h,f+=(w.x+A.x)*h,C+=(w.y+A.y)*h}if(Math.abs(p)<=u)return{error:"The polygon has no measurable area."};let R=t.clone().addScaledVector(a,f/(3*p)).addScaledVector(i,C/(3*p));return{area:Math.abs(p)/2,center:R.toArray(),triangles:H.ShapeUtils.triangulateShape(c,[])}}function fn(e,t){if(e.length<2)return 0;let o=0;for(let n=1;n<e.length;n+=1)o+=new H.Vector3(...e[n]).distanceTo(new H.Vector3(...e[n-1]));return t&&(o+=new H.Vector3(...e[e.length-1]).distanceTo(new H.Vector3(...e[0]))),o}var xt=["m","cm","mm","in","ft"],St={m:1,cm:.01,mm:.001,in:.0254,ft:.3048},cr=["distance","angle","area","pointToPlane","wrap","wrapHorizontal"];function wt(e){return xt.includes(e)}function Mt(e={},t="m"){let o=e.displayUnit??t,n=e.metersPerUnit??St[e.sourceUnit??"m"];if(!Number.isFinite(n)||n<=0)throw new Error("Measurement scale must be a positive finite number.");return{displayUnit:o,metersPerUnit:n,factor:wt(o)?n/St[o]:1}}function gn(e,t,o,n={}){if(!wt(o)||!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0)throw new Error("Calibration needs two distinct points and a positive known distance.");let r=t*St[o]/e;if(!Number.isFinite(r)||r<=0)throw new Error("Calibration scale is outside the supported range.");return{...n,metersPerUnit:r}}function Xe(e,t){let o=t.map(n=>n.position);if(e==="angle"){let n=dn(o);return n===null?null:{value:n,dimension:0}}if(e==="area"){let n=pn(o);return"error"in n?null:{value:n.area,dimension:2}}if(e==="pointToPlane"){let n=t.length===2?mn(t[0],t[1].position):null;return n?{value:n.distance,dimension:1}:null}return t.length<(e==="distance"?2:3)?null:{value:fn(o,e!=="distance"),dimension:1}}function At(e,t={},o="m",n=e.points,r=e.approximate?"approximate":"ready"){let s=Xe(e.tool,n),{factor:a,displayUnit:i}=Mt(t,o),c=r==="ready"||r==="approximate",l=c&&s?s.value*a**s.dimension:null;return{id:e.id,status:c?s&&l!==null&&Number.isFinite(l)?r:"invalid":r,rawValue:c&&s&&Number.isFinite(s.value)?s.value:null,value:l!==null&&Number.isFinite(l)?l:null,unit:e.tool==="angle"?"\xB0":e.tool==="area"?`${i}\xB2`:i}}function we(e){function t(){throw new Error("Invalid measurements: expected settings and valid named measurements with finite points.")}let o=i=>!!i&&typeof i=="object"&&!Array.isArray(i),n=i=>Array.isArray(i)&&i.length===3&&i.every(c=>typeof c=="number"&&Number.isFinite(c));typeof e=="string"&&(e.length>5*1024*1024&&t(),e=JSON.parse(e)),(!o(e)||e.version!==void 0&&e.version!==1||!o(e.settings)||!Array.isArray(e.items)||e.items.length>256)&&t();let r={};for(let i of["sourceUnit","displayUnit"])e.settings[i]!==void 0&&(wt(e.settings[i])||t(),r[i]=e.settings[i]);e.settings.metersPerUnit!==void 0&&((typeof e.settings.metersPerUnit!="number"||!Number.isFinite(e.settings.metersPerUnit)||e.settings.metersPerUnit<=0)&&t(),r.metersPerUnit=e.settings.metersPerUnit);let s=new Set,a=e.items.map(i=>{(!o(i)||typeof i.id!="string"||!i.id||s.has(i.id)||typeof i.name!="string"||!i.name.trim()||typeof i.modelId!="string"||!i.modelId||!cr.includes(i.tool)||!Array.isArray(i.points)||i.points.length>8192||typeof i.createdAt!="string"||!Number.isFinite(Date.parse(i.createdAt)))&&t(),s.add(i.id),i.tilesetUrl!==void 0&&i.tilesetUrl!==null&&typeof i.tilesetUrl!="string"&&t(),(i.visible!==void 0&&typeof i.visible!="boolean"||i.approximate!==void 0&&typeof i.approximate!="boolean")&&t();let c=new Set,l=i.points.map(d=>{if((!o(d)||typeof d.id!="number"||!Number.isFinite(d.id)||!n(d.position))&&t(),c.has(d.id)&&t(),c.add(d.id),d.normal!==void 0&&!n(d.normal)&&t(),d.faceVertices!==void 0&&(!Array.isArray(d.faceVertices)||d.faceVertices.length!==3||!d.faceVertices.every(n))&&t(),d.snapped!==void 0&&!["vertex","edge"].includes(d.snapped)&&t(),d.anchor!==void 0){let f=d.anchor;(!o(f)||typeof f.nodeId!="string"||!f.nodeId||!n(f.localPosition)||typeof f.geometrySignature!="string"||typeof f.poseSignature!="string")&&t(),f.localNormal!==void 0&&!n(f.localNormal)&&t(),f.localFaceVertices!==void 0&&(!Array.isArray(f.localFaceVertices)||f.localFaceVertices.length!==3||!f.localFaceVertices.every(n))&&t(),f.instanceId!==void 0&&(!Number.isInteger(f.instanceId)||f.instanceId<0)&&t()}let p=d.anchor;return{id:d.id,position:[...d.position],...d.normal?{normal:[...d.normal]}:{},...d.faceVertices?{faceVertices:d.faceVertices.map(f=>[...f])}:{},...d.snapped?{snapped:d.snapped}:{},...p?{anchor:{nodeId:p.nodeId,localPosition:[...p.localPosition],geometrySignature:p.geometrySignature,poseSignature:p.poseSignature,...p.localNormal?{localNormal:[...p.localNormal]}:{},...p.localFaceVertices?{localFaceVertices:p.localFaceVertices.map(f=>[...f])}:{},...p.instanceId!==void 0?{instanceId:p.instanceId}:{}}}:{}}}),u={id:i.id,name:i.name,modelId:i.modelId,tool:i.tool,points:l,createdAt:i.createdAt,...i.tilesetUrl!==void 0?{tilesetUrl:i.tilesetUrl}:{},...i.visible!==void 0?{visible:i.visible}:{},...i.approximate!==void 0?{approximate:i.approximate}:{}};return Xe(u.tool,l)||t(),u});return{settings:r,items:a}}function bn(e){return JSON.stringify({version:1,...we(e)},null,2)}function hn(e,t,o="m"){let n=we(e),r=new Map(t?.map(a=>[a.id,a])),s=a=>{let i=String(a??"");return/^[=+@-]/.test(i)&&(i=`'${i}`),`"${i.replace(/"/g,'""')}"`};return[["id","name","modelId","type","status","value","unit","createdAt"],...n.items.map(a=>{let i=r.get(a.id)??At(a,n.settings,o);return[a.id,a.name,a.modelId,a.tool,i.status,i.value,i.unit,a.createdAt]})].map(a=>a.map(s).join(",")).join(`\r
2
+ `)}function Ye(e){if(!Array.isArray(e)||e.length>128)throw new Error("Invalid selections: expected up to 128 named selection sets.");let t=new Set;return e.map(o=>{if(!o||typeof o!="object"||typeof o.id!="string"||!o.id||t.has(o.id)||typeof o.name!="string"||!o.name.trim()||o.name.length>200||!Array.isArray(o.objectIds)||o.objectIds.length>1e5||o.objectIds.some(n=>typeof n!="string"||!n))throw new Error("Invalid selections: each set needs a unique id, a name, and model object ids.");return t.add(o.id),{id:o.id,name:o.name.trim(),objectIds:[...new Set(o.objectIds)]}})}var Sn=new Set(["__proto__","constructor","prototype"]),vt=(e,t)=>e<t?-1:e>t?1:0;function _(e){throw new Error(`Invalid product: ${e}`)}var Y=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Le=e=>typeof e=="string"&&e.length>0&&e.length<=200&&!Sn.has(e),de=e=>typeof e=="string"&&e.trim().length>0&&e.length<=500;function xn(e){let t=0;function o(n,r){return(++t>1e5||r>32)&&_("definition is too complex."),n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)?n:Array.isArray(n)?n.map(s=>o(s,r+1)):(Y(n)||_("expected JSON data."),Object.fromEntries(Object.entries(n).filter(([,s])=>s!==void 0).map(([s,a])=>(Sn.has(s)&&_("reserved property name."),[s,o(a,r+1)]))))}return o(e,0)}function lr(e){if(typeof e!="string"||e.length>2048)return!1;try{return["http:","https:"].includes(new URL(e.replace(/\{[a-zA-Z]+\}/g,"x")).protocol)}catch{return!1}}function Ct(e){let t=xn(typeof e=="string"?JSON.parse(e):e);(!Y(t)||!Le(t.id)||!de(t.label)||!Le(t.revision)||!Array.isArray(t.groups)||!t.groups.length||t.groups.length>64)&&_("id, label, revision, and 1\u201364 option groups are required.");let o=new Map;for(let r of t.groups){(!Y(r)||!Le(r.id)||o.has(r.id)||!de(r.label)||r.required!==void 0&&typeof r.required!="boolean"||!Array.isArray(r.options)||!r.options.length||r.options.length>128)&&_("groups need unique ids, labels, and 1\u2013128 options.");let s=new Set;o.set(r.id,s);for(let a of r.options)if((!Y(a)||!Le(a.id)||s.has(a.id)||!de(a.label)||a.sku!==void 0&&!de(a.sku))&&_("options need unique ids and labels."),s.add(a.id),a.description!==void 0&&!de(a.description)&&_("an option description must be text."),a.swatch!==void 0&&!(typeof a.swatch=="string"&&/^#[0-9a-f]{3,8}$/i.test(a.swatch))&&_("a swatch must be a hex color."),a.priceDeltaMinor!==void 0&&!Number.isSafeInteger(a.priceDeltaMinor)&&_("a price change must be a whole number of minor units."),a.variants!==void 0&&(!Array.isArray(a.variants)||a.variants.some(i=>!de(i)))&&_("variant names must be strings."),a.appearance!==void 0){(!Array.isArray(a.appearance)||a.appearance.length>128)&&_("invalid appearance edits.");for(let i of a.appearance){Y(i)||_("invalid appearance edit.");let c=i.target;typeof c=="string"&&c||Array.isArray(c)&&c.every(l=>typeof l=="string"&&!!l)||Y(c)&&Object.keys(c).length===1&&["group","tag","type"].some(l=>typeof c[l]=="string")||_("appearance needs an object id, id list, or selector."),i.visible!==void 0&&typeof i.visible!="boolean"&&_("visibility must be boolean."),i.material!==void 0&&!Y(i.material)&&_("material must be an object.");for(let l of Object.values(i.material??{}))typeof l=="string"||typeof l=="number"||typeof l=="boolean"||l===null||Y(l)&&typeof l.path=="string"&&(l.offset===void 0||Array.isArray(l.offset)&&l.offset.length===2&&l.offset.every(u=>typeof u=="number"))||_("invalid material field.")}}r.defaultOptionId!==void 0&&!s.has(r.defaultOptionId)&&_("a default must name an option in its group."),r.display!==void 0&&!["list","chips","swatches"].includes(r.display)&&_("a group's display must be list, chips or swatches.")}t.pricing!==void 0&&!(Y(t.pricing)&&/^[A-Z]{3}$/.test(t.pricing.currency)&&Number.isSafeInteger(t.pricing.basePriceMinor)&&t.pricing.basePriceMinor>=0)&&_("pricing needs a 3-letter currency and a base price of zero or more."),t.checkout!==void 0&&(!Y(t.checkout)||t.checkout.label!==void 0&&!de(t.checkout.label)||!lr(t.checkout.urlTemplate))&&_("a checkout link needs an http or https URL.");let n=r=>Y(r)&&typeof r.groupId=="string"&&typeof r.optionId=="string"&&!!o.get(r.groupId)?.has(r.optionId);if(t.rules!==void 0){(!Array.isArray(t.rules)||t.rules.length>2048)&&_("invalid rules.");let r=new Set;for(let s of t.rules){(!Y(s)||!Le(s.id)||r.has(s.id)||!n(s.when)||s.message!==void 0&&!de(s.message))&&_("rules need unique ids and valid option references."),r.add(s.id),["requires","excludes"].some(a=>Array.isArray(s[a])&&s[a].length>0)||_("a rule needs a requires or excludes constraint.");for(let a of["requires","excludes"])s[a]!==void 0&&(!Array.isArray(s[a])||s[a].length>128||!s[a].every(n))&&_("rule references must name existing options.")}}if(t.skus!==void 0){(!Array.isArray(t.skus)||t.skus.length>4096)&&_("invalid SKU table.");let r=new Set;for(let s of t.skus){(!Y(s)||!de(s.sku)||!Y(s.selections)||Object.keys(s.selections).length!==o.size)&&_("SKU mappings need one selection per group.");for(let[i,c]of Object.entries(s.selections))(!o.has(i)||c!==null&&!o.get(i).has(c))&&_("SKU mapping references an unknown option.");let a=JSON.stringify(Object.entries(s.selections).sort(([i],[c])=>vt(i,c)));r.has(a)&&_("a combination can map to only one SKU."),r.add(a)}}return{id:t.id,label:t.label,revision:t.revision,groups:t.groups.map(r=>({id:r.id,label:r.label,...r.required!==void 0?{required:r.required}:{},...r.defaultOptionId!==void 0?{defaultOptionId:r.defaultOptionId}:{},...r.display!==void 0?{display:r.display}:{},options:r.options.map(s=>({id:s.id,label:s.label,...s.sku!==void 0?{sku:s.sku}:{},...s.description!==void 0?{description:s.description}:{},...s.swatch!==void 0?{swatch:s.swatch}:{},...s.priceDeltaMinor!==void 0?{priceDeltaMinor:s.priceDeltaMinor}:{},...s.variants!==void 0?{variants:s.variants}:{},...s.appearance!==void 0?{appearance:s.appearance.map(a=>({target:a.target,...a.material!==void 0?{material:a.material}:{},...a.visible!==void 0?{visible:a.visible}:{}}))}:{}}))})),...t.rules!==void 0?{rules:t.rules.map(r=>({id:r.id,when:r.when,...r.requires?{requires:r.requires}:{},...r.excludes?{excludes:r.excludes}:{},...r.message?{message:r.message}:{}}))}:{},...t.skus!==void 0?{skus:t.skus.map(r=>({sku:r.sku,selections:r.selections}))}:{},...t.pricing!==void 0?{pricing:{currency:t.pricing.currency,basePriceMinor:t.pricing.basePriceMinor}}:{},...t.checkout!==void 0?{checkout:{urlTemplate:t.checkout.urlTemplate,...t.checkout.label!==void 0?{label:t.checkout.label}:{}}}:{}}}function Te(e){return Object.fromEntries(e.groups.map(t=>[t.id,t.defaultOptionId??null]))}function ur(e,t){let o=[];for(let n of e.groups){if(t[n.id]===null)continue;let r=n.options.find(s=>s.id===t[n.id])?.sku;if(!r)return null;o.push(r)}return o.length?o.join("-"):null}function ae(e,t=Te(e),o=1){if(!Number.isSafeInteger(o)||o<1||o>9999)throw new Error("Quantity must be an integer from 1 to 9999.");if(!Y(t)||Object.values(t).some(u=>u!==null&&typeof u!="string"))throw new Error("Product selections must map group ids to option ids or null.");let n=[],r=[...e.groups].sort((u,d)=>vt(u.id,d.id)),s=Object.fromEntries(r.map(u=>[u.id,!Object.prototype.hasOwnProperty.call(t,u.id)||t[u.id]===void 0?u.defaultOptionId??null:t[u.id]]));for(let u of Object.keys(t).sort())e.groups.some(d=>d.id===u)||n.push({code:"unknown-group",groupIds:[u],message:`Unknown option group: ${u}.`});let a=[];for(let u of r){let d=s[u.id],p=u.options.find(f=>f.id===d);d!==null&&!p?n.push({code:"unknown-option",groupIds:[u.id],message:`Unknown choice for ${u.label}: ${d}.`}):u.required&&d===null&&n.push({code:"required",groupIds:[u.id],message:`Choose ${u.label}.`}),p&&a.push({groupId:u.id,optionId:p.id,label:p.label,...p.sku?{sku:p.sku}:{}})}let i=u=>e.groups.find(d=>d.id===u.groupId)?.options.find(d=>d.id===u.optionId)?.label??u.optionId;for(let u of[...e.rules??[]].sort((d,p)=>vt(d.id,p.id)))if(s[u.when.groupId]===u.when.optionId){for(let d of u.requires??[])s[d.groupId]!==d.optionId&&n.push({code:"requires",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} requires ${i(d)}.`});for(let d of u.excludes??[])s[d.groupId]===d.optionId&&n.push({code:"excludes",ruleId:u.id,groupIds:[...new Set([u.when.groupId,d.groupId])],message:u.message??`${i(u.when)} cannot be combined with ${i(d)}.`})}let c=e.skus?.length?e.skus.find(u=>r.every(d=>u.selections[d.id]===s[d.id]))?.sku??null:ur(e,s);e.skus?.length&&!c&&!n.length&&n.push({code:"sku",groupIds:r.map(u=>u.id),message:"This combination has no product SKU."});let l=JSON.stringify({productId:e.id,revision:e.revision,quantity:o,selections:s});return{version:1,productId:e.id,revision:e.revision,key:l,quantity:o,selections:s,sku:c,items:a,valid:!n.length,issues:n}}var wn=new Set(["requires","excludes"]);function Je(e,t,o,n,r=1){let s={...ae(e,t,r).selections,[o]:n},a=new Set([JSON.stringify(s)]),i=[s];for(let c=0;c<i.length&&c<2e3;c++){let l=i[c],u=ae(e,l,r).issues.filter(d=>wn.has(d.code));if(!u.length)return l;for(let d of new Set(u.flatMap(p=>p.groupIds))){if(d===o)continue;let p=e.groups.find(f=>f.id===d);if(p)for(let f of[...p.options.map(C=>C.id),...p.required?[]:[null]]){let C={...l,[d]:f},R=JSON.stringify(C);a.has(R)||(a.add(R),i.push(C))}}}return null}function dr(e,t,o,n,r){let s=Je(e,t,o,n,r);return s?Object.entries(s).filter(([a,i])=>a!==o&&i!==t[a]&&i!==null).map(([a,i])=>({groupId:a,optionId:i})):null}function Mn(e,t){if(!e.pricing)return null;let o=e.pricing.basePriceMinor;for(let n of t.items)o+=e.groups.find(r=>r.id===n.groupId)?.options.find(r=>r.id===n.optionId)?.priceDeltaMinor??0;return{amountMinor:Math.max(0,o)*t.quantity,currency:e.pricing.currency}}function An(e,t,o=!1){try{let n=new Intl.NumberFormat(void 0,{style:"currency",currency:t,...o?{signDisplay:"exceptZero"}:{}});return n.format(e/10**(n.resolvedOptions().maximumFractionDigits??2))}catch{return`${e} ${t}`}}function vn(e,t){let o=e.checkout?.urlTemplate;if(!o||!t.valid||o.includes("{sku}")&&!t.sku)return null;let n={sku:t.sku??"",quantity:String(t.quantity),productId:e.id,revision:e.revision,selections:kt(t.selections)};return o.replace(/\{([a-zA-Z]+)\}/g,(r,s)=>Object.prototype.hasOwnProperty.call(n,s)?encodeURIComponent(n[s]):r)}function kt(e){return Object.entries(e).filter(([,t])=>t!==null).map(([t,o])=>`${encodeURIComponent(t)}:${encodeURIComponent(o)}`).join(",")}function Cn(e,t){let o={...Te(t)};for(let n of e.split(",")){let[r,s]=n.split(":");if(!r||!s)continue;let a,i;try{a=decodeURIComponent(r),i=decodeURIComponent(s)}catch{continue}t.groups.find(c=>c.id===a)?.options.some(c=>c.id===i)&&(o[a]=i)}return o}var yn=4096;function kn(e,t="-"){let o=[{}];for(let s of e.groups){let a=[...s.options.map(i=>i.id),...s.required?[]:[null]];if(o.length*a.length>yn*8)throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.");o=o.flatMap(i=>a.map(c=>({...i,[s.id]:c})))}let n={...e,skus:void 0},r=[];for(let s of o){if(ae(n,s).issues.length)continue;let a=e.groups.flatMap(i=>{let c=s[i.id];return c===null?[]:[i.options.find(l=>l.id===c)?.sku??null]});if(!(!a.length||a.includes(null))&&(r.push({sku:a.join(t),selections:s}),r.length>yn))throw new Error("This product has too many combinations to list. Use a pricing service to resolve SKUs instead.")}return r}function On(e,t={},o){let n=[],r=Te(e),s=ae({...e,skus:void 0},r).issues.filter(i=>wn.has(i.code));for(let i of s)n.push({code:"invalid-default",message:`The default choices conflict: ${i.message}`});e.checkout?.urlTemplate.includes("{sku}")&&!e.skus?.length&&e.groups.some(i=>i.options.some(c=>!c.sku))&&n.push({code:"missing-sku",message:"The buy link uses {sku}, but it won't appear until every option has an SKU."});let a=Object.keys(t).length>0;for(let i of e.groups)for(let c of i.options){let l=`${i.label} \u203A ${c.label}`,u={groupId:i.id,optionId:c.id};if(a)for(let p of c.appearance??[])Q(t,p.target).length||n.push({code:"no-objects",message:`${l} changes objects that aren't in this model.`,...u});if(o)for(let p of c.variants??[])o.includes(p)||n.push({code:"missing-variant",message:`${l} uses a material variant this model doesn't have: ${p}.`,...u});let d={...r,[i.id]:c.id};Je(e,d,i.id,c.id)||n.push({code:"unreachable",message:`The rules leave no way to choose ${l}.`,...u})}return n}function jn(e,t,o,n=1){return t=ae(e,t,n).selections,e.groups.flatMap(r=>r.options.map(s=>{let i=ae(e,{...t,[r.id]:s.id},n).issues.filter(u=>u.groupIds.includes(r.id)&&u.code!=="sku").map(u=>u.message),c=o?.options?.find(u=>u.groupId===r.id&&u.optionId===s.id);c?.available===!1&&i.push(c.reason??"Currently unavailable.");let l=i.length&&c?.available!==!1?dr(e,t,r.id,s.id,n):null;return{groupId:r.id,optionId:s.id,selected:t[r.id]===s.id,available:!i.length,...l?{fix:l}:{},reasons:[...new Set(i)]}}))}function Ze(e){Y(e)||_("expected a product definition and selections.");let t=Ct(e.definition),o=ae(t,e.selections??Te(t));return o.issues.some(n=>n.code==="unknown-group"||n.code==="unknown-option")&&_("selections reference unknown options."),{definition:t,selections:o.selections}}function Tn(e){return JSON.stringify({version:1,productId:e.productId,revision:e.revision,quantity:e.quantity,selections:e.selections})}function Rn(e,t){let o=xn(typeof e=="string"?JSON.parse(e):e);if(!Y(o)||o.version!==1||o.productId!==t.id||o.revision!==t.revision)throw new Error("This configuration belongs to a different product or revision.");if(!Y(o.selections)||!Number.isSafeInteger(o.quantity))throw new Error("Invalid product configuration selections or quantity.");let n=ae(t,o.selections,o.quantity);if(n.issues.some(r=>r.code==="unknown-group"||r.code==="unknown-option"))throw new Error("This configuration references unknown product options.");return n}function In(e,t,o=[],n=[]){let r=e,s=[...o];if(!t)return{objectBindings:r,activeVariants:s};for(let a of t.definition.groups){let i=a.options.find(c=>c.id===(t.selections[a.id]===void 0?a.defaultOptionId:t.selections[a.id]));if(i){for(let c of i.appearance??[])r=$e(r,c.target,{...c.material!==void 0?{style:{material:c.material}}:{},...c.visible!==void 0?{visible:c.visible}:{}});if(i.variants?.length){let c=new Set(a.options.flatMap(l=>l.variants??[]));s=s.filter(l=>!c.has(l));for(let l of i.variants)s=qe(s,l,n)}}}return{objectBindings:r,activeVariants:s}}var me=5*1024*1024,mr=["activeModelId","modelUrl","modelFormat","tilesetUrl","models","mergeModels","sceneConfig","isolation","multiSelectedKeys","activeAnnotation","annotationCategories","backgroundColor","shadows","cinematic","cameraControllerType","objectTransformSpace","arScaleMode","usdzUrl","measurements","measurementSettings","measurementUnit","measurementModelId"];function O(e,t){throw new Error(`Invalid viewer state at ${e}: ${t}`)}function W(e,t){(!e||typeof e!="object"||Array.isArray(e))&&O(t,"expected an object.")}function Ue(e,t){(!Array.isArray(e)||!e.every(o=>typeof o=="string"))&&O(t,"expected strings.")}function oe(e,t,o){(!Array.isArray(e)||e.length!==t||!e.every(n=>typeof n=="number"&&Number.isFinite(n)))&&O(o,`expected ${t} finite numbers.`)}function pr(e){let t=new Set,o=0;function n(r,s,a){if((++o>2e5||a>64)&&O(s,"configuration is too complex."),r===null||typeof r=="string"||typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r))return r;(typeof r!="object"||!r)&&O(s,"expected JSON data (finite numbers, no functions)."),t.has(r)&&O(s,"cyclic data."),!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null&&O(s,"expected plain JSON data."),t.add(r);let i=Array.isArray(r)?[]:{};for(let[c,l]of Object.entries(r))["__proto__","constructor","prototype"].includes(c)&&O(`${s}.${c}`,"reserved property."),l!==void 0?i[c]=n(l,`${s}.${c}`,a+1):Array.isArray(r)&&O(s,"undefined array entry.");return t.delete(r),i}return n(e,"state",0)}function re(e,t,o,n,r=!1,s){let a=e[t];if(a==null||a==="")return;typeof a!="string"&&O(o,"expected a URL.");let i=r?ln(a)??a:a;if(i.trim().startsWith("blob:")){if(r&&s){s.set(a,{source:i,path:o});return}O(o,r?"this image is temporary. Use getStateAsync() for JSON or createShareUrl() to include it.":"upload this model/environment asset to a durable URL before saving or sharing.")}if(i!==a&&(a=i,e[t]=i),r&&/^data:image\//i.test(a))return;let c;try{c=new URL(a,n??"https://relative.invalid/")}catch{O(o,"invalid asset URL.")}["http:","https:"].includes(c.protocol)||O(o,"use an HTTP(S) asset URL."),n&&(e[t]=c.href)}function fr(e,t){W(e,t),oe(e.position,3,`${t}.position`),oe(e.target,3,`${t}.target`),(typeof e.zoom!="number"||e.zoom<=0)&&O(t,"zoom must be positive."),e.fov!==null&&(typeof e.fov!="number"||e.fov<=0||e.fov>=180)&&O(t,"fov must be null or between 0 and 180.");for(let o of["azimuthAngle","polarAngle"])e[o]!==void 0&&typeof e[o]!="number"&&O(t,`${o} must be a number.`)}function En(e,t,o,n){W(e,t),(typeof e.id!="number"||typeof e.title!="string"||typeof e.description!="string")&&O(t,"expected an annotation id, title and description.");for(let r of["worldPosition","localPosition"])oe(e[r],3,`${t}.${r}`);e.images!==void 0&&(Array.isArray(e.images)||O(t,"images must be an array."),e.images.forEach(r=>{W(r,t),re(r,"src",t,o,!0,n)})),e.links!==void 0&&(Array.isArray(e.links)||O(t,"links must be an array."),e.links.forEach(r=>{W(r,t),re(r,"href",t,o,!1,n)}))}function Vn(e,t){W(e,t),e.waypoints!==void 0&&(Array.isArray(e.waypoints)||O(t,"expected waypoints."),e.waypoints.forEach(o=>{W(o,t),oe(o.position,3,t),oe(o.target,3,t)}));for(let o of["enabled","loop","autoPlay"])e[o]!==void 0&&typeof e[o]!="boolean"&&O(t,`${o} must be boolean.`);e.duration!==void 0&&(typeof e.duration!="number"||e.duration<=0)&&O(t,"duration must be positive.")}function Ot(e,t,o){if(t!==null)if(Array.isArray(t))Array.isArray(e)||O(o,"expected an array."),t.length&&e.forEach(n=>Ot(n,t[0],o));else if(typeof t=="object"){W(e,o);for(let[n,r]of Object.entries(t))Ot(e[n],r,`${o}.${n}`)}else typeof e!=typeof t&&O(o,`expected ${typeof t}.`)}function Pn(e,t,o,n){if(Ot(e,be,t),e.measurements!==void 0&&(e.measurements=we(e.measurements)),e.sequences!==void 0&&(e.sequences=Oe(e.sequences)),e.selectionSets!==void 0&&(e.selectionSets=Ye(e.selectionSets)),e.product!==void 0&&(e.product=Ze(e.product),e.product.definition.groups.forEach(r=>r.options.forEach(s=>s.appearance?.forEach(a=>{for(let[i,c]of Object.entries(a.material??{}))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${t}.product.material.${i}.path`,o,!0,n)})))),oe(e.model.rotation,3,`${t}.model.rotation`),e.lighting.lights.forEach(r=>oe(r.position,3,`${t}.lighting.lights`)),e.annotations.forEach(r=>En(r,`${t}.annotations`,o,n)),e.animations.autoplayClip!==null&&typeof e.animations.autoplayClip!="string"&&O(t,"invalid autoplay clip."),e.animations.clips.forEach(r=>{W(r,t),(typeof r.sourceName!="string"||typeof r.displayName!="string"||typeof r.hidden!="boolean"||typeof r.speed!="number"||!["repeat","once","ping-pong"].includes(r.loopMode))&&O(t,"invalid animation clip settings.")}),e.cinematic!==void 0&&Vn(e.cinematic,`${t}.cinematic`),e.styleRules!==void 0&&!Array.isArray(e.styleRules)&&O(t,"styleRules must be an array."),re(e.environment,"customEnvironmentUrl",`${t}.environment`,o,!1,n),re(e.background,"imageUrl",`${t}.background`,o,!0,n),e.model.activeVariants!==void 0&&Ue(e.model.activeVariants,t),e.section!==void 0)try{e.section=De(e.section)}catch(r){O(`${t}.section`,r.message)}}function Dn(e,t,o,n){W(e,t);for(let[r,s]of Object.entries(e)){let a=`${t}.${r}`;W(s,a),(typeof s.id!="string"||typeof s.modelObjectId!="string")&&O(a,"expected binding id and modelObjectId.");for(let i of["label","group","type","status"])s[i]!==void 0&&typeof s[i]!="string"&&O(a,`${i} must be a string.`);s.tags!==void 0&&Ue(s.tags,a),s.metadata!==void 0&&W(s.metadata,`${a}.metadata`),s.metrics!==void 0&&(W(s.metrics,a),Object.values(s.metrics).some(i=>typeof i!="number")&&O(a,"metrics must be numbers.")),s.actions!==void 0&&(Array.isArray(s.actions)||O(a,"actions must be an array."),s.actions.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.label!="string"||i.type!=="command"||i.effects!==void 0&&!Array.isArray(i.effects))&&O(a,"invalid action.")}));for(let i of["visible","removed","selectable","hoverable"])s[i]!==void 0&&typeof s[i]!="boolean"&&O(a,`${i} must be boolean.`);if(s.transform!==void 0){W(s.transform,a);for(let i of["position","rotation","scale","shear"])s.transform[i]!==void 0&&oe(s.transform[i],3,`${a}.transform.${i}`);s.transform.pivot!==void 0&&(W(s.transform.pivot,a),oe(s.transform.pivot.point,3,a),oe(s.transform.pivot.offset,3,a))}if(s.style!==void 0&&(W(s.style,a),s.style.material!==void 0)){W(s.style.material,a);for(let[i,c]of Object.entries(s.style.material))c&&typeof c=="object"&&!Array.isArray(c)&&"path"in c&&re(c,"path",`${a}.style.material.${i}.path`,o,!0,n)}s.decals!==void 0&&(Array.isArray(s.decals)||O(a,"decals must be an array."),s.decals.forEach(i=>{W(i,a),(typeof i.id!="string"||typeof i.size!="number"||i.size<=0)&&O(a,"invalid decal."),oe(i.position,3,a),oe(i.normal,3,a),re(i,"image",a,o,!0,n)}))}}function Bn(e,t,o,n){Array.isArray(e)||O(t,"expected merge sources."),e.forEach(r=>{W(r,t),(typeof r.url!="string"||!r.url||typeof r.namePrefix!="string")&&O(t,"expected source URL and prefix."),re(r,"url",t,o,!1,n)})}function gr(e,t,o){W(e,"configuration");let n=Object.fromEntries(mr.filter(r=>e[r]!==void 0).map(r=>[r,e[r]]));(typeof n.modelUrl!="string"||!n.modelUrl)&&O("configuration.modelUrl","expected the active model URL.");for(let r of["modelUrl","tilesetUrl","usdzUrl"])re(n,r,`configuration.${r}`,t,!1,o);if(n.sceneConfig!==void 0&&Pn(n.sceneConfig,"configuration.sceneConfig",t,o),n.mergeModels!==void 0&&Bn(n.mergeModels,"configuration.mergeModels",t,o),n.models!==void 0){(!Array.isArray(n.models)||n.models.length===0)&&O("configuration.models","expected model entries.");let r=new Set,s=new Set;n.models.forEach(a=>{W(a,"model"),(typeof a.url!="string"||!a.url)&&O("model.url","expected a URL."),re(a,"url","model.url",t,!1,o),a.id!==void 0&&(typeof a.id!="string"||!a.id.trim())&&O("model.id","expected a nonempty instance ID.");let i=ht({id:a.id,url:a.url});s.has(i)&&O("configuration.models","instance identities must be unique; assign IDs when reusing a URL."),s.add(i),a.transform!==void 0&&(a.transform=je(a.transform)),a.visible!==void 0&&typeof a.visible!="boolean"&&O("model.visible","expected boolean."),r.add(a.url),Dn(a.objectBindings,"model.objectBindings",t,o),a.sceneConfig!==void 0&&Pn(a.sceneConfig,"model.sceneConfig",t,o),a.mergeModels!==void 0&&Bn(a.mergeModels,"model.mergeModels",t,o)}),n.activeModelId!==void 0&&(typeof n.activeModelId!="string"||!s.has(n.activeModelId))&&O("configuration.activeModelId","active instance is not in models."),n.activeModelId!==void 0&&n.models.find(a=>ht(a)===n.activeModelId)?.url!==n.modelUrl&&O("configuration.modelUrl","source does not match the active instance."),r.has(n.modelUrl)||O("configuration.modelUrl","active model is not in models.")}if(n.multiSelectedKeys!==void 0&&Ue(n.multiSelectedKeys,"configuration.multiSelectedKeys"),n.annotationCategories!==void 0&&n.annotationCategories!==null&&Ue(n.annotationCategories,"configuration.annotationCategories"),n.activeAnnotation!==void 0&&n.activeAnnotation!==null&&En(n.activeAnnotation,"configuration.activeAnnotation",t,o),n.measurements!==void 0||n.measurementSettings!==void 0){let r=we({items:n.measurements??[],settings:n.measurementSettings??{}});n.measurements!==void 0&&(n.measurements=r.items),n.measurementSettings!==void 0&&(n.measurementSettings=r.settings)}n.measurementModelId!==void 0&&typeof n.measurementModelId!="string"&&O("configuration.measurementModelId","expected a stable id."),n.measurementUnit!==void 0&&typeof n.measurementUnit!="string"&&O("configuration.measurementUnit","expected a unit label.");for(let r of["backgroundColor"])n[r]!==void 0&&typeof n[r]!="string"&&O(r,"expected a string.");n.shadows!==void 0&&typeof n.shadows!="boolean"&&O("shadows","expected boolean.");for(let[r,s]of Object.entries({modelFormat:["glb","gltf","obj","fbx","usdz","stl","ply"],cameraControllerType:["orbit","pointerLock"],objectTransformSpace:["world","local"],arScaleMode:["normalized","real-world"]}))n[r]!==void 0&&!s.includes(n[r])&&O(r,"unsupported value.");if(n.cinematic!==void 0&&Vn(n.cinematic,"cinematic"),n.isolation!==void 0&&n.isolation!==null){let{target:r,mode:s,ghostOpacity:a}=n.isolation;typeof r=="string"||Array.isArray(r)&&r.every(i=>typeof i=="string")||r&&typeof r=="object"&&["group","tag","type"].some(i=>typeof r[i]=="string")||O("configuration.isolation","invalid target."),s!==void 0&&!["ghost","hide"].includes(s)&&O("configuration.isolation","invalid mode."),a!==void 0&&(typeof a!="number"||a<0||a>1)&&O("configuration.isolation","opacity must be between 0 and 1.")}return n}function Nn(e,t,o,n){if(!(!e||typeof e!="object"))for(let[r,s]of Object.entries(e))r!=="metadata"&&(typeof s=="string"&&["url","modelUrl","tilesetUrl","usdzUrl","path","image","src","href","imageUrl","customEnvironmentUrl"].includes(r)?re(e,r,`${t}.${r}`,o,["path","image","src","imageUrl"].includes(r),n):Nn(s,`${t}.${r}`,o,n))}function Ln(e,t,o){typeof e=="string"&&(new TextEncoder().encode(e).length>me&&O("state","exceeds the 5 MiB limit."),e=JSON.parse(e));let n=pr(e);W(n,"state"),new TextEncoder().encode(JSON.stringify(n)).length>me&&O("state","exceeds the 5 MiB limit."),n.version!==void 0&&n.version!==1&&O("version","unsupported version."),n.version===void 0&&(n.objectBindings!==void 0||n.configuration!==void 0)&&O("version","full configurations require version 1.");let r={};return n.version!==void 0&&(r.version=1),n.camera!==void 0&&(fr(n.camera,"camera"),r.camera=n.camera),n.hidden!==void 0&&(Ue(n.hidden,"hidden"),r.hidden=n.hidden),n.selected!==void 0&&(n.selected!==null&&typeof n.selected!="string"&&O("selected","expected an object id or null."),r.selected=n.selected),n.objectBindings!==void 0&&(Dn(n.objectBindings,"objectBindings",t,o),r.objectBindings=n.objectBindings),n.configuration!==void 0&&(r.configuration=gr(n.configuration,t,o)),Nn(r,"state",t,o),new TextEncoder().encode(JSON.stringify(r)).length>me&&O("state","exceeds the 5 MiB limit."),r}function Un(e,t){return JSON.stringify(Re(e,t))}function Re(e,t){return Ln(e,t)}async function Qe(e,t){let o=new Map,n=Ln(e,t,o),r=new Map,s=new Map;for(let[i,{source:c,path:l}]of o){let u=r.get(c);u||(u=(async()=>{let d;try{d=await fetch(c)}catch{O(l,"this temporary image is no longer available. Reload or reselect it before saving.")}d.ok||O(l,"could not read the temporary image. Reload or reselect it before saving.");let p=await d.blob();p.size>me*3/4&&O(l,"embedded image exceeds the 5 MiB configuration limit. Use a hosted image URL.");let f=new Uint8Array(await p.arrayBuffer()),C=p.type.split(";")[0].toLowerCase(),R=C.startsWith("image/")?C:br(f);R||O(l,"temporary asset is not a supported image. Use a hosted asset URL.");let S="";for(let w=0;w<f.length;w+=32768)S+=String.fromCharCode(...f.subarray(w,w+32768));return`data:${R};base64,${btoa(S)}`})(),r.set(c,u)),s.set(i,await u)}function a(i){if(!(!i||typeof i!="object"))for(let[c,l]of Object.entries(i))c!=="metadata"&&(["path","image","src","imageUrl"].includes(c)&&typeof l=="string"&&s.has(l)?i[c]=s.get(l):a(l))}return a(n),Re(n,t)}function br(e){let t=(o,n)=>String.fromCharCode(...e.subarray(o,n));if(e[0]===137&&t(1,4)==="PNG")return"image/png";if(e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(t(0,3)==="GIF")return"image/gif";if(t(0,4)==="RIFF"&&t(8,12)==="WEBP")return"image/webp";if(t(4,8)==="ftyp"&&["avif","avis"].includes(t(8,12)))return"image/avif";if(/<svg[\s>]/i.test(new TextDecoder().decode(e.subarray(0,1024))))return"image/svg+xml"}var jt={verifyingLicense:"Verifying License",checkingYourLicenseKey:"Checking your license key...",createDevelopmentKey:"Create a free development key",invalidLicense:"Invalid License",licenseHasBeenRevokedOrHasExpired:"License has been revoked or has expired",failedToLoadPleaseContactTheSiteAdministrator:"Failed to load. Please contact the site administrator.",contextRestoringTitle:"Reloading viewer\u2026",contextLostTitle:"3D view interrupted",contextRestoringMessage:"Rebuilding the 3D view. Please wait\u2026",contextLostMessage:"The graphics connection was interrupted. The viewer will rebuild when it returns, or you can reload it now.",reloadViewer:"Reload viewer",texturePositioningHint:"Drag to move \xB7 Scroll to zoom \xB7 Click elsewhere to finish",texturePositioningStartHint:"Double-click to move or zoom",dismiss:"Dismiss",missingUVsAreShownInMagenta:"Missing UVs are shown in magenta.",viewThisModelInARWithAppleQuickLook:"View this model in AR with Apple Quick Look",sequencePlayer:"Sequence player",sequenceSelect:"Sequence",sequencePlay:"Play sequence",sequencePause:"Pause sequence",sequenceStop:"Stop and restore scene",sequencePlayhead:"Sequence playhead",sequenceTime:"Sequence time",sequenceIssues:"Unavailable sequence targets",arConfiguredButton:"AR handoff",arConfiguredTitle:"Take this configuration to AR",arConfiguredDescription:"Your current materials, visible models and placements are included.",arSnapshotStale:"Updating AR to include your latest changes\u2026",arPreparing:"Preparing your scene\u2026",arStart:"Start AR",arStarting:"Starting AR\u2026",arCheckingSupport:"Checking AR support\u2026",arUnavailable:"AR is unavailable in this browser. Open this link in an AR-capable browser on your phone.",arStartFailed:"Could not start AR. Check camera permissions and try again.",arAnimations:"AR animations",arAnimationSelect:"Animation",arAnimationSaved:"Default",arAnimationNone:"No animation",arAnimationClips:"Model clips",arAnimationSequences:"Sequences",arAnimationPlay:"Play animation",arAnimationPause:"Pause animation",arRefresh:"Refresh AR",arRetry:"Try again",arExportDetails:"Export details",arPrepare:"Prepare AR",arPrepareAgain:"Prepare again",arDownloadUSDZ:"Download USDZ for iPhone/iPad",arScanConfigured:"Scan to open this configuration on your phone.",arOpenConfiguredLink:"Open configuration link",viewInAR:"View in AR",openThisExperienceOnAPhoneForAR:"Open this experience on a phone for AR",openOnPhone:"Open on phone",viewThisModelInYourSpace:"View this model in your space",viewThisModelInVR:"View this model in VR",closePhoneHandoff:"Close phone handoff",arScanCode:"Scan the code and choose AR.",qrCodeToOpenThisModelOnAPhone:"QR code to open this model on a phone",disableUVChecker:"Disable UV checker",enableUVChecker:"Enable UV checker",explodedView:"Exploded view",explodeAmount:"Explode amount",removeSectionCut:"Remove section cut",sectionCut:"Section cut",sectionAxis:"Section axis",sectionPosition:"Section position",keepTheOtherSide:"Keep the other side",pauseCinematic:"Pause cinematic",playCinematic:"Play cinematic",stopCinematicAndResetCamera:"Stop cinematic and reset camera",cancel:"Cancel",annotationCategories:"Annotation categories",annotations:"Annotations",all:"All",uncategorized:"Uncategorized",decalDragHint:"Drag the decal on the object. Release to save; Escape to cancel.",showAll:"Show all",materialVariants:"Material variants",startGuidedTour:"Start guided tour",guidedTour:"Guided Tour",previousAnnotation:"Previous annotation",previous:"Prev",stopGuidedTour:"Stop guided tour",nextAnnotation:"Next annotation",next:"Next",exitFullscreen:"Exit fullscreen",enterFullscreen:"Enter fullscreen",resetCameraView:"Reset camera view",orbitControl:"Orbit Control",pointLock:"Pointer lock",cameraController:"Camera controller",cameraControllerSettings:"Camera controller settings",downloadGLB:"Download GLB",downloadGLBDescription:"All visible models, material edits and animations in one file. No annotations or separate editor model slots. Duplicate mesh names may change on reimport.",downloadCombinedGLB:"Download as one GLB",downloadSeparateGLBs:"Download separate GLBs",downloadSeparateGLBsDescription:"One GLB file per model",downloadPNG:"Download PNG",downloadUVLayout:"Download UV Layout",videoFormat:"Video format",auto:"Auto",recordTurntableVideo:"Record turntable video",recordCinematicVideo:"Record cinematic video",videoUnsupported:"Video recording is not supported in this browser.",downloadOptions:"Download options",exporting:"Exporting\u2026",download:"Download",annotationTitlePlaceholder:"Title *",description:"Description",ok:"OK",arRelocate:"Relocate",tapToPlace:"Tap to place",closeAnnotation:"Close annotation",learnMore:"Learn more",stopMeasuring:"Stop measuring",startMeasuring:"Start measuring",toggleBoundingDimensions:"Toggle bounding dimensions",measurementTool:"Measurement tool",distance:"Distance",angle:"Angle",area:"Area",pointToPlane:"Point to plane",wrap:"Circumference (Edge)",wrapHorizontal:"Circumference (Horizontal)",measurementSnapping:"Measurement snapping",noSnapping:"No snapping",snapAuto:"Snap: auto",snapVertex:"Snap: vertex",snapEdge:"Snap: edge",undoMeasurementPoint:"Undo measurement point",clearMeasurements:"Clear measurements",finishArea:"Finish area",savedMeasurements:"Saved measurements ({count})",noSavedMeasurements:"No saved measurements yet. Pick points in the preview, then save a measurement here.",measurementFiles:"Import / export",measurementSourceUnit:"Model units",measurementDisplayUnit:"Display units",measurementName:"Name",measurementNamePlaceholder:"e.g. Door width",saveMeasurement:"Save",knownMeasurementDistance:"Known length",calibrationUnit:"Calibration unit",calibrateMeasurement:"Calibrate",measurementCalibrationHint:"Pick two distance points, enter their known length, then calibrate.",measurementCalibratedScale:"Calibrated: 1 model unit = {scale} m",resetMeasurementCalibration:"Reset calibration",showSavedMeasurement:"Show {name}",renameSavedMeasurement:"Rename {name}",deleteSavedMeasurement:"Delete {name}",exportMeasurementJson:"Export JSON",exportMeasurementCsv:"Export CSV",importMeasurementJson:"Import JSON",measurementReady:"Ready",measurementApproximate:"Approximate LOD",measurementModelChanged:"Different model",measurementObjectMissing:"Object unavailable",measurementGeometryChanged:"Geometry changed \u2014 measure again",measurementPoseChanged:"Pose changed \u2014 measure again",measurementObjectHidden:"Object hidden",measurementInvalid:"Invalid measurement",measurementWaiting:"Waiting for model",openSceneObjectsPanel:"Open scene objects panel",sceneObjects:"Scene Objects",searchNodesLabels:"Search nodes, labels",closeSceneObjectsPanel:"Close scene objects panel",objectNavigator:"Objects in the 3D view",compareBefore:"Before",compareAfter:"After",compareDivider:"Comparison divider",viewIn3D:"View in 3D",objectNavigatorHint:"Arrow keys browse \xB7 Enter selects \xB7 Esc clears",selectionCleared:"Selection cleared",cameraKeyboardHelp:"3D view. Arrow keys orbit, Shift with Up or Down zooms, and W, A, S, D, Space and C move the camera.",isolate:"Isolate",hide:"Hide",show:"Show",closePanel:"Close panel",actions:"Actions",openPanel:"Open panel",close:"Close",position:"Position",decalNudgeHint:"Click to fine-tune \xB7 Hold to move",decalNudgeControls:"Move decal in small steps",text:"Text",yourText:"Your text",textToAdd:"Text to add",textColour:"Text color",addText:"Add text",image:"Image",chooseImage:"Choose image",imageToAdd:"Image to add",added:"Added",colour:"Color",size:"Size",turn:"Turn",rotation:"Rotation",dragTheDecalAcrossTheObjectsSurface:"Drag the decal across the object's surface",move:"Move",remove:"Remove",noneAddedYet:"None added yet",done:"Done",moveForward:"Move forward",moveLeft:"Move left",moveRight:"Move right",moveBackward:"Move backward",productOptions:"Options",productOptionsFor:"{product} options",productReset:"Reset",productOptional:"optional",productNone:"None",productAlsoChanges:"Also changes: {changes}",productUnavailable:"Currently unavailable.",productQuantity:"Quantity",productCheckingPrice:"Checking price and availability\u2026",productTotal:"Total",productAddToCart:"Add to cart",productAddingToCart:"Adding\u2026",productRequestQuote:"Request quote",productRequestingQuote:"Requesting\u2026",productRefresh:"Refresh",productBuy:"Buy now",productCopyLink:"Copy link",productLinkCopied:"Link copied",productShowOptions:"Show options",productHideOptions:"Hide options",productIssues:"Configuration issues",productRequestDone:"Request completed.",productSaved:"Saved: {id}",sceneSettings:"Scene Settings",background:"Background",backgroundColor:"Background Color",showEnvironmentAsBackground:"Show as background",backgroundBlur:"Background Blur",environmentPreset:"Preset",environmentIntensity:"Intensity",toneMapping:"Tone Mapping",toneMappingAces:"ACES Filmic",toneMappingAgx:"AgX",toneMappingNeutral:"Neutral",toneMappingNone:"None",ground:"Ground",groundShadow:"Ground Shadow",groundShadowOpacity:"Shadow Opacity",floorGrid:"Floor Grid",display:"Display",wireframe:"Wireframe",autoRotateSpeed:"Rotation Speed",fieldOfView:"Field of View",modelInfo:"Model",modelInfoObjects:"Objects",modelInfoTriangles:"Triangles",modelInfoMaterials:"Materials",resetSettings:"Reset Settings",environment:"Environment",autoRotate:"Auto Rotate",lighting:"Lighting",exposure:"Exposure",ambientLightIntensity:"Ambient Light Intensity",ambientLightColor:"Ambient Light Color",directLightIntensity:"Direct Light Intensity",directLightColor:"Direct Light Color",searchObjects:"Search objects",uploadedModel:"Uploaded model",clear:"Clear",chooseModel:"Choose model",loadingModel:"Loading model...",releaseToLoadYourModel:"Release to load your model",arFindSurface:"Move your device over a flat surface",arReleaseToPlace:"Release to place",arGestureHint:"Pinch to resize \xB7 Twist to rotate",angleFirstArmHint:"Pick the first arm",angleVertexHint:"Pick the angle's vertex",angleSecondArmHint:"Pick the second arm",angleNewHint:"Pick a point to start a new angle",areaNewHint:"Pick a point to start a new area",areaCornersHint:"Pick polygon corners in order, then Finish area",pointToPlaneFaceHint:"Pick the reference face",pointToPlanePointHint:"Pick a point to measure its perpendicular distance",pointToPlaneNewHint:"Pick a face to start a new measurement",distanceHint:"Pick points on the model to measure distances",wrapHint:"Click a point on the surface to measure its circumference, following the surface (best for limbs)",wrapHorizontalHint:"Click a point to measure a level circumference around it (best for the torso/waist)",visibleEntries:"{count} visible entries",objectCount:"{count} objects",annotationMarker:"Annotation {id}: {title}",recordingVideo:"Recording video \xB7 {progress}%",isolatedObjects:"Isolated: {count} objects",largeModelWarning:"Very large model ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the objects panel to select parts.",preparingLargeModel:"Preparing large model ({millions}M triangles) \u2014 the first display can take a while on this device...",enterAR:"Enter AR",enterVR:"Enter VR",decalImage:"Image {index}",decalText:"Text {index}",decalAdded:"{count} added",up:"up",down:"down",left:"left",right:"right",moveDecal:"Move decal {direction}",moveDecalOnSurface:"Move {direction} on the visible surface",showAllObject:"Show all {name}",isolateObject:"Isolate {name}",isolatedObject:"Isolated: {name}",hideObject:"Hide {name}",showObject:"Show {name}",objectSelected:"{name} selected",objectNavigatorPosition:"{position} of {count}",compareDividerValue:"{before} {percent}%, {after} {rest}%",bindingMismatchOne:"1 object binding doesn't match this model",bindingMismatchMany:"{count} object bindings don't match this model",simpleLargeModelWarning:"Very large model detected ({millions}M triangles) \u2014 it may render and move slowly on this device, and click/hover selection on the model is disabled. Use the scene objects panel to select parts.",dropModelHint:"Drag and drop {formats} here",retryModelLoad:"Retry loading model",loadErrorTitle:"This model couldn't be loaded",loadErrorNotFound:"Nothing was found at this address ({status}). Check that modelUrl points to the file.",loadErrorDenied:"The server refused access to the file ({status}). Check that the file is public, or that a signed URL hasn't expired.",loadErrorStatus:"The server responded with {status} when the file was requested.",loadErrorNetwork:"The download was blocked or failed. Check that the URL is correct and, if the file is on another domain, that its server allows cross-origin requests (CORS) from this site.",loadErrorHtml:"The server sent back a web page instead of a model. There's probably no file at this path: many servers answer a missing file with their index.html.",loadErrorInvalidFile:"The file couldn't be read as {format}. Check that it's a valid {format} file.",loadErrorInvalidExplicitFormat:"The file couldn't be read as {format}. Check that it's a valid {format} file and that modelFormat matches it.",loadErrorMissingFormat:"The file couldn't be read as {format}. The URL has no file extension, so set modelFormat to the file's format.",loadErrorPointCloud:"This PLY file is a point cloud: it has points but no faces, and the viewer shows meshes. Turn it into a mesh first, for example with MeshLab or Blender.",measurementReferenceFaceRequired:"Pick a triangle face to define the reference plane.",measurementTooManyPoints:"Finish or clear this measurement before adding more points.",measurementAngleDistinct:"Pick a point away from the angle's vertex.",areaMinimumPoints:"Pick at least three points to finish the area.",areaDistinctPoints:"Area points must be distinct.",areaStraightLine:"Area points must not lie on one straight line.",areaNotPlanar:"Area points must lie on one plane.",areaEdgesCross:"Area edges must not cross or touch each other.",areaZero:"The polygon has no measurable area.",decalSurfaceMissing:"Could not find a surface on this object for the decal.",decalDirectionMissing:"No visible surface in that direction. Try another arrow or rotate the view.",fullscreenExitFailed:"Could not exit fullscreen. Press Escape to exit.",fullscreenEnterFailed:"Could not enter fullscreen. Check your browser or iframe fullscreen permissions and try again.",uvCoordinatesMissing:"This model does not contain UV coordinates.",uvExportFailed:"Could not create the UV layout archive.",videoExportFailed:"Could not export the video.",videoNotReady:"Viewer not ready for video export.",videoExitXR:"Exit the XR session before recording a video.",videoAlreadyRecording:"A video export is already in progress.",videoPathRequired:"Enable a cinematic camera path before recording it.",videoDurationInvalid:"Video duration must be greater than 0 and at most 300 seconds.",videoFrameRateInvalid:"Video frame rate must be between 1 and 60.",videoBitrateInvalid:"Video bitrate must be a positive number.",videoContextLost:"Video export stopped because the WebGL context was lost.",videoTimedOut:"Video export timed out. Keep the viewer tab visible while recording.",videoEncodingFailed:"The browser could not encode the video.",videoEmpty:"The browser produced an empty video.",videoDidNotStart:"Video recording did not start.",videoWebMUnsupported:"Video recording as WEBM is not supported in this browser.",videoMP4Unsupported:"Video recording as MP4 is not supported in this browser.",videoGIFUnsupported:"Video recording as GIF is not supported in this browser.",videoGifWidthInvalid:"GIF width must be a whole number of pixels from 16 to 4096.",environmentNeutral:"neutral",environmentApartment:"apartment",environmentCity:"city",environmentDawn:"dawn",environmentForest:"forest",environmentLobby:"lobby",environmentNight:"night",environmentPark:"park",environmentStudio:"studio",environmentSunset:"sunset",environmentWarehouse:"warehouse",color:"Color",material:"Material",texturePreview:"texture preview",noTextureApplied:"No texture applied",noTextureCoordinates:"This part has no texture coordinates, so an image can't be placed on it.",replaceImage:"Replace image",uploadImage:"Upload image",removeTexture:"Remove texture",texturePosition:"Texture position",offsetX:"Offset X",offsetY:"Offset Y",confirmTexturePosition:"Confirm this texture position and exit positioning mode",donePositioning:"Done positioning",textureOffsetHint:"Double-click the object in the preview to drag its texture directly (scroll to zoom), or edit its offset numerically.",actionToggleLight:"Toggle Light",actionChangeLightColor:"Change Light Color",actionSetBrightness:"Set Brightness",actionChangeColor:"Change Color",actionChangeMaterial:"Change Material",actionToggleVisibility:"Toggle Visibility"};var Ui=new Map(Object.entries(jt).map(([e,t])=>[t,e]));function _n(e){Ge(e);let t=[],o=[{node:e,path:"0",parentId:null}];for(;o.length;){let{node:r,path:s,parentId:a}=o.pop(),i=`node:${s}`,c=r.isMesh&&r.name?Ee(r):null;t.push({id:i,parentId:a,name:r.name||r.type||"Group",...c?{objectId:c}:{}});for(let l=r.children.length-1;l>=0;l--)o.push({node:r.children[l],path:`${s}/${l}`,parentId:i})}let n=new Set;for(let r=t.length-1;r>=0;r--){let s=t[r];(s.objectId||n.has(s.id))&&(n.add(s.id),s.parentId&&n.add(s.parentId))}return t.filter(r=>n.has(r.id))}function zn(e){return structuredClone(e.style??{})}function Fn(e,t,o){let n=Q(e,t).filter(s=>!e[s].removed);if(!n.length)return e;let r={...e};for(let s of n)r[s]={...e[s],style:structuredClone(o)};return r}var Me=require("three"),hr=new Set(["KHR_binary_glTF","KHR_draco_mesh_compression","KHR_lights_punctual","KHR_materials_clearcoat","KHR_materials_dispersion","KHR_materials_ior","KHR_materials_sheen","KHR_materials_specular","KHR_materials_transmission","KHR_materials_iridescence","KHR_materials_anisotropy","KHR_materials_unlit","KHR_materials_volume","KHR_texture_basisu","KHR_texture_transform","KHR_mesh_quantization","KHR_materials_emissive_strength","KHR_materials_variants","EXT_materials_bump","EXT_texture_webp","EXT_texture_avif","EXT_meshopt_compression","EXT_mesh_gpu_instancing"]),yr=new WeakMap;function Sr(e){let t=yr.get(e);return t?structuredClone(t):void 0}function $n(e){if(/^(blob|data):/i.test(e))return"Local resource";let t=e.split(/[?#]/,1)[0].replace(/\\/g,"/");return t.slice(t.lastIndexOf("/")+1).slice(0,300)||"Resource"}function xr(e){return/^(blob|data):/i.test(e)?"Local resource":e.split(/[?#]/,1)[0].replace(/\\/g,"/").replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*/i,"").replace(/^\/+/,"").slice(0,500)||"Resource"}function wr(e){let t=o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:null;return{...e.format?{format:e.format}:{},...e.name?{name:$n(e.name)}:{},sourceBytes:t(e.sourceBytes),loadDurationMs:t(e.loadDurationMs),extensionsUsed:[...new Set(e.extensionsUsed??[])].sort(),extensionsRequired:[...new Set(e.extensionsRequired??[])].sort(),failedResources:[...new Set((e.failedResources??[]).map(xr))].slice(0,50)}}function Mr(e){let t=new Set(e.extensionsRequired);return[...new Set([...e.extensionsUsed??[],...t])].sort().map(o=>({name:o,required:t.has(o),recognized:hr.has(o)}))}function Ar(e,t){let o=e.image,n=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>0?l:null,r=n(o?.naturalWidth??o?.width),s=n(o?.naturalHeight??o?.height),a=!!e.isCompressedTexture,i=e.mipmaps.reduce((l,u)=>l+(u.data?.byteLength??0),0),c=r&&s?Math.ceil(r*s*4*(e.generateMipmaps?4/3:1)):null;return{name:e.name?$n(e.name):t,width:r,height:s,compressed:a,estimatedBytes:a?i||null:c!==null&&Number.isSafeInteger(c)?c:null}}function qn(e,t={}){let o=wr({...Sr(e),...t.source}),n=[],r=new Set,s=new Map,a=new Set,i=new Map,c=new Map,l=new Set,u=new Map,d=0,p=0,f=0,C=0,R=0,S=(g,m)=>{let b=u.get(g)??{count:0,names:[]};b.count++,b.names.length<20&&b.names.push(m||"Unnamed object"),u.set(g,b)},w=g=>{let m=g?.array??g?.data?.array;m?.buffer&&!l.has(m.buffer)&&(l.add(m.buffer),R+=m.buffer.byteLength)};e.traverse(g=>{let m=g;if(!m.isMesh||!m.geometry)return;d++,p+=m.isInstancedMesh?Number.isSafeInteger(m.count)?Math.max(0,m.count??0):0:1;let b=m.geometry,y=b.getAttribute("position"),k=b.getAttribute("uv"),I=m.material?Array.isArray(m.material)?m.material:[m.material]:[];if(!s.has(b)){let T=!!y&&(!Number.isSafeInteger(y.count)||y.count<0);for(let P=0;!T&&y&&P<y.count;P++)if(!Number.isFinite(y.getX(P))||!Number.isFinite(y.getY(P))||!Number.isFinite(y.getZ(P))){T=!0;break}s.set(b,T)}if(s.get(b)&&S("invalid-positions",g.name),y?.count||S("empty-geometry",g.name),k||S("missing-uv",g.name),b.getAttribute("normal")||S("missing-normals",g.name),b.boundingBox&&[...b.boundingBox.min.toArray(),...b.boundingBox.max.toArray()].some(T=>!Number.isFinite(T))&&S("invalid-bounds",g.name),!r.has(b)){r.add(b),f+=Number.isSafeInteger(y?.count)?Math.max(0,y?.count??0):0;let T=b.index?.count??y?.count??0;C+=Number.isSafeInteger(T)?Math.floor(Math.max(0,T)/3):0,Object.values(b.attributes).forEach(w),Object.values(b.morphAttributes).flat().forEach(w),w(b.index)}let N=!1;for(let T of I){a.add(T);let P=i.get(T);if(!P){P=Object.values(T).filter(F=>!!F&&F.isTexture===!0),i.set(T,P);for(let F of P)c.has(F)||c.set(F,`Texture ${c.size+1}`)}for(let F of P){let te=F.channel??0;b.getAttribute(te===0?"uv":`uv${te}`)||(N=!0)}}N&&S("textured-missing-uv",g.name)});let A=(g,m,b,y,k)=>{let I=u.get(g);I&&n.push({code:g,severity:m,title:b,detail:y,suggestion:k,count:I.count,objects:I.names})};A("empty-geometry","error","Empty mesh geometry","Some meshes have no position data.","Remove empty meshes or export their geometry again."),A("invalid-positions","error","Invalid vertex coordinates","Some vertices contain non-finite coordinates.","Repair NaN or infinite vertex positions in the source application, then re-export."),A("invalid-bounds","error","Invalid geometry bounds","Some cached bounds contain non-finite values.","Repair invalid coordinates in the source application and re-export."),A("textured-missing-uv","warning","Textures have no matching UV coordinates","A texture references a UV channel that its mesh does not contain.","Unwrap the affected meshes and export the UV channel used by each texture."),A("missing-uv","info","Meshes without UVs","Solid colors can work without UVs; image textures and surface decals need them.","Add a UV map before applying image textures or decals."),A("missing-normals","info","Meshes without normals","Some loaded meshes lack vertex normals; generated shading may differ from the source.","Export vertex normals to preserve hard edges and smooth surfaces."),d||n.push({code:"no-meshes",severity:"warning",title:"No mesh geometry found",detail:"This scene contains no loaded meshes.",suggestion:"Check that meshes were included in the export. Streamed scenes may still be loading."});let h=[...c].map(([g,m])=>Ar(g,m)),x=h.filter(g=>(g.width??0)>4096||(g.height??0)>4096);x.length&&n.push({code:"large-textures",severity:"warning",title:"Large texture dimensions",detail:"Some textures exceed 4096 pixels on one side.",suggestion:"Resize textures for the visible detail needed; use KTX2/Basis where appropriate.",count:x.length,objects:x.slice(0,20).map(g=>g.name)}),C>1e6&&n.push({code:"high-triangle-count",severity:"warning",title:"High geometry count",detail:"The loaded geometry contains more than one million unique triangles.",suggestion:"Simplify hidden detail, create lower-detail exports, or use streamed assets for large scenes."}),a.size>100&&n.push({code:"many-materials",severity:"warning",title:"Many material definitions",detail:"More than 100 materials can increase rendering work.",suggestion:"Reuse materials and atlas compatible textures; inspect runtime draw calls to confirm the cost."});let M=Mr(o);for(let g of M.filter(m=>!m.recognized))n.push({code:"unrecognized-extension",severity:g.required?"error":"warning",title:`${g.required?"Required":"Optional"} extension not recognized`,detail:g.name,suggestion:"Export with extensions supported by the bundled loader, or verify the asset's fallback appearance."});o.failedResources?.length&&n.push({code:"failed-resources",severity:"error",title:"Some resources failed to load",detail:"The model may be missing textures or other referenced resources.",suggestion:"Include sidecar files in the ZIP, correct their paths, and check HTTP access and CORS.",count:o.failedResources.length,objects:o.failedResources.slice(0,20)});let E=null,j=[...s.values()].some(Boolean)?new Me.Box3:new Me.Box3().setFromObject(e);!j.isEmpty()&&[...j.min.toArray(),...j.max.toArray(),...j.getSize(new Me.Vector3).toArray()].every(Number.isFinite)&&(E={min:j.min.toArray(),max:j.max.toArray(),center:j.getCenter(new Me.Vector3).toArray(),size:j.getSize(new Me.Vector3).toArray()}),t.scope==="resident-tiles"&&n.unshift({code:"partial-stream",severity:"info",title:"Loaded tiles only",detail:"Geometry and texture counts cover the current resident tiles, not the entire source asset.",suggestion:"Use the live cache/detail statistics to inspect streaming pressure. Rescan after moving the camera."});let D=g=>g.code==="partial-stream"?-1:g.severity==="error"?0:g.severity==="warning"?1:2;return n.sort((g,m)=>D(g)-D(m)),{version:1,status:"ready",scope:t.scope??"asset",source:o,units:o.format==="glb"||o.format==="gltf"?"meters (glTF convention)":"unknown",bounds:E,statistics:{meshes:d,instances:p,geometries:r.size,materials:a.size,textures:c.size,vertices:f,triangles:C,geometryBytes:R,estimatedTextureBytes:h.reduce((g,m)=>g+(m.estimatedBytes??0),0),unknownTextureSizes:h.filter(g=>g.estimatedBytes===null).length,meshesWithoutUvs:u.get("missing-uv")?.count??0,meshesWithoutNormals:u.get("missing-normals")?.count??0},textures:h,extensions:M,issues:n}}var vr=new WeakMap;function Gn(e){e.traverse(t=>{let o=vr.get(t);if(o)throw new Error(o)})}var z=require("three");var et=require("three");function Ie(e){return e.isSkinnedMesh===!0}function Hn(e){let t=[];return e.traverse(o=>{Ie(o)&&t.push(o)}),t}var Ae="reactImmersiveSkinFreeze";function Kn(e){return!!e.userData[Ae]}function tt(e,t,o=[t]){let n=e.userData,r=new et.Matrix4().copy(t).invert(),s=n[Ae];if(s){s.frozenInverse.copy(r),s.restWorldTransforms=o.map(c=>c.clone()),e.bindMatrixInverse.copy(r);return}let a={frozenInverse:r,restWorldTransforms:o.map(c=>c.clone()),previousOnBeforeRender:e.onBeforeRender,previousUpdateMatrixWorld:Object.prototype.hasOwnProperty.call(e,"updateMatrixWorld")?e.updateMatrixWorld:void 0};e.bindMatrixInverse.copy(r);let i=e.updateMatrixWorld;e.updateMatrixWorld=function(c){i.call(this,c),e.bindMatrixInverse.copy(a.frozenInverse)},e.onBeforeRender=function(c,l,u,d,p,f){a.previousOnBeforeRender.call(this,c,l,u,d,p,f),e.bindMatrixInverse.copy(a.frozenInverse)},n[Ae]=a}function _e(e){return e.userData[Ae]?.frozenInverse??null}function Wn(e){return e.userData[Ae]?.restWorldTransforms??null}function Xn(e){let t=e.userData,o=t[Ae];o&&(e.onBeforeRender=o.previousOnBeforeRender,o.previousUpdateMatrixWorld?e.updateMatrixWorld=o.previousUpdateMatrixWorld:delete e.updateMatrixWorld,delete t[Ae],e.updateMatrixWorld(!0))}function Yn(e){let t=e,o=_e(e);o&&t.bindMatrixInverse.copy(o),t.skeleton?.update?.();let n=t.geometry.clone(),r=n.getAttribute("position");if(r){let s=new et.Vector3;for(let a=0;a<r.count;a++)t.getVertexPosition(a,s),r.setXYZ(a,s.x,s.y,s.z);r.needsUpdate=!0}return n.deleteAttribute("skinIndex"),n.deleteAttribute("skinWeight"),n.morphAttributes={},n.morphTargetsRelative=!1,n.computeVertexNormals(),n.computeBoundingBox(),n.computeBoundingSphere(),n}var ie=require("three"),po=require("three/examples/jsm/utils/SkeletonUtils.js"),le=require("fflate");var pe=require("three");function Jn(e){let t=e._loopCount;return e.loop===pe.LoopPingPong&&(t&1)===1}function Cr(e){return Jn(e)?e.getClip().duration-e.time:e.time}function Zn({root:e,clips:t,getClipConfig:o,onChange:n}){let r=new pe.AnimationMixer(e),s=new Map;for(let{clip:m,sourceName:b}of t)s.set(b,r.clipAction(m));let a=new Map,i=new Set,c=new Map,l=1,u=m=>typeof m=="string",d=m=>u(m)?a.has(m)?[m]:[]:[...a.keys()],p=(m,b)=>{let y=Qt(o(b));y==="once"?m.setLoop(pe.LoopOnce,1):y==="ping-pong"?m.setLoop(pe.LoopPingPong,1/0):m.setLoop(pe.LoopRepeat,1/0),m.clampWhenFinished=y==="once"},f=m=>{m.action.setEffectiveTimeScale(m.reverse?-m.speed:m.speed)},C=m=>{let b=a.get(m);b&&(b.action.stop(),a.delete(m))},R=(m,b={})=>{let y=s.get(m);if(!y||o(m)?.hidden)return;let k=Number.isFinite(b.fade)&&b.fade>0?b.fade:0,I=b.reverse??!1;if(!b.alongside)for(let[F,te]of[...a])F!==m&&(k>0?(a.delete(F),te.action.fadeOut(k),i.add(te.action)):C(F));i.delete(y)&&y.stop();let N=y.getClip().duration,T=a.get(m),P=()=>{y.reset(),I&&(y.time=N),y.play()};if(!T)P(),k>0&&y.fadeIn(k);else{let F=I?y.time<=0:y.time>=N;T.finished&&F&&P(),y.paused=!1,y.enabled=!0,a.delete(m)}p(y,m),T={action:y,speed:o(m)?.speed??c.get(m)??l,reverse:I,finished:!1},T.speed=He(T.speed),f(T),a.set(m,T),n()},S=m=>{for(let b of d(m))a.get(b).action.paused=!0;n()},w=m=>{for(let b of d(m))C(b);if(!u(m)){for(let b of i)b.stop();i.clear()}n()},A=(m,b)=>{let y=He(m);u(b)?c.set(b,y):l=y;for(let k of d(b)){let I=a.get(k);c.set(k,y),I.speed=y,f(I)}n()},h=(m,b)=>{for(let y of d(b)){let k=a.get(y),I=k.action.getClip().duration,N=Math.min(Math.max(m,0),I);k.action.time=Jn(k.action)?I-N:N,k.finished&&(k.finished=!1,k.action.paused=!0)}r.update(0),n()},x=()=>{for(let[m,b]of[...a]){let y=o(m);if(y?.hidden){C(m);continue}p(b.action,m),y?.speed!==void 0&&(b.speed=He(y.speed),f(b))}n()},M=m=>{for(let b of a.values())b.action===m.action&&(b.finished=!0);n()};return r.addEventListener("finished",M),{play:R,pause:S,stop:w,setSpeed:A,seek:h,getState:()=>{let m=[...a].map(([y,k])=>({clip:y,status:k.finished?"finished":k.action.paused?"paused":"playing",time:Cr(k.action),duration:k.action.getClip().duration,speed:k.speed,reverse:k.reverse})),b=m[m.length-1];return{currentClip:b?.clip??null,isPlaying:m.some(y=>y.status==="playing"),speed:b?.speed??l,time:b?.time??0,duration:b?.duration??0,active:m}},applyClipConfigs:x,isRunning:()=>{if(i.size>0)return!0;for(let{action:m}of a.values())if(!m.paused&&m.enabled)return!0;return!1},update:m=>{r.update(m);for(let b of i)(!b.enabled||b.getEffectiveWeight()<=0)&&(b.stop(),i.delete(b))},dispose:()=>{r.removeEventListener("finished",M),r.stopAllAction(),r.uncacheRoot(e),a.clear(),i.clear()}}}var Pt=require("three");var nt=require("react"),Tt=require("three");function Qn(e){return[e.x,e.y,e.z]}function eo(e,t){let o=new Tt.Vector3,n=new Tt.Vector3;return t.getPosition(o),t.getTarget(n),{position:Qn(o),target:Qn(n),fov:"fov"in e&&typeof e.fov=="number"?e.fov:null,zoom:"zoom"in e&&typeof e.zoom=="number"?e.zoom:1,azimuthAngle:t.azimuthAngle,polarAngle:t.polarAngle}}var ce=require("three");function kr(e){return new ce.Matrix4().set(1,e[0],e[1],0,0,1,e[2],0,0,0,1,0,0,0,0,1)}function Rt(e,t){e.matrixAutoUpdate=!t,e.updateMatrix(),t&&(e.matrix.makeRotationFromQuaternion(e.quaternion).multiply(kr(t)).scale(e.scale).setPosition(e.position),e.matrixWorldNeedsUpdate=!0)}function to(e,t,o){let n=new ce.Vector3().setFromMatrixColumn(e,0),r=new ce.Vector3().setFromMatrixColumn(e,1),s=new ce.Vector3().setFromMatrixColumn(e,2),a=(C,R)=>{let S=C*(R<0?-1:1);return Math.abs(S-R)<1e-10?R:S},i=a(n.length(),t.x);if(Math.abs(i)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};n.divideScalar(i);let c=n.dot(r);r.addScaledVector(n,-c);let l=a(r.length(),t.y);if(Math.abs(l)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};r.divideScalar(l);let u=n.dot(s);s.addScaledVector(n,-u);let d=r.dot(s);s.addScaledVector(r,-d);let p=a(s.length(),t.z);if(Math.abs(p)<1e-12)return{rotation:o.clone(),scale:t.clone(),shear:void 0};s.divideScalar(p);let f=[c/l,u/p,d/p].map(C=>Math.abs(C)<1e-10?0:C);return{rotation:new ce.Quaternion().setFromRotationMatrix(new ce.Matrix4().makeBasis(n,r,s)).normalize(),scale:new ce.Vector3(i,l,p),shear:f.some(Boolean)?f:void 0}}var It=e=>e==="baseColor"?"color":e;function no(e){let t=new Set;return e.traverse(o=>{let n=o;if(n.isMesh)for(let r of Array.isArray(n.material)?n.material:[n.material])r&&t.add(r)}),[...t]}function oo({root:e,controls:t,animations:o,invalidate:n,cameraEnabled:r=()=>!0}){let s=new Map,a=new Map,i=new Map,c=new Set,l=new Map,u=null,d="",p=h=>e()?Jt(e(),h):null,f=h=>{if(h.kind==="camera"){let D=t();if(!D)return null;let g=eo(D.camera,D);return{position:g.position,target:g.target,fov:g.fov,zoom:g.zoom}}if(h.kind==="clip"){let D=o();return D?.clips.includes(h.clip)?D.getState?.().active.find(g=>g.clip===h.clip)?.time??0:null}let x=p(h.objectId);if(!x)return null;let M=h.property;if(M==="position"||M==="rotation"||M==="scale")return[x[M].x,x[M].y,x[M].z];if(M==="visible")return x.visible;let E=no(x).find(D=>D[It(M)]!==void 0),j=E?E[It(M)]:void 0;return j?.isColor?`#${j.getHexString()}`:typeof j=="number"?j:null},C=h=>{if(!r())return;let x=t();x&&(x.stop(),x.setLookAt(...h.position,...h.target,!1),h.fov!==null&&"fov"in x.camera&&(x.camera.fov=h.fov,x.camera.updateProjectionMatrix()),x.zoomTo(h.zoom,!1),x.update(0))},R=h=>{if(s.has(h))return;h.updateWorldMatrix(!0,!0);let x=h.matrixAutoUpdate?void 0:to(h.matrix,h.scale,h.quaternion).shear;s.set(h,{position:h.position.toArray(),rotation:[h.rotation.x,h.rotation.y,h.rotation.z],scale:h.scale.toArray(),matrix:h.matrix.clone(),auto:h.matrixAutoUpdate,shear:x});for(let M of Hn(h))Kn(M)||(tt(M,M.matrixWorld),c.add(M))},S=(h,x)=>{let M=o();M?.stop(h),x&&M&&(M.play(h,{alongside:!0,reverse:x.reverse}),M.setSpeed(x.speed,h),M.seek?.(x.time,h),x.status!=="playing"&&M.pause(h))};return{capture:f,restore:()=>{for(let[h,x]of l)S(h,x);l.clear();for(let[h,x]of s)h.position.fromArray(x.position),h.rotation.set(...x.rotation),h.scale.fromArray(x.scale),h.matrix.copy(x.matrix),h.matrixAutoUpdate=x.auto,h.matrixWorldNeedsUpdate=!0;s.clear(),a.forEach((h,x)=>x.visible=h),a.clear(),i.forEach((h,x)=>{h.forEach((M,E)=>{M instanceof Pt.Color?x[E].copy(M):x[E]=M}),x.needsUpdate=!0}),i.clear(),c.forEach(Xn),c.clear(),u&&C(u),u=null,d="",e()?.updateWorldMatrix(!0,!0),n()},inspect:h=>h.tracks.filter(x=>!x.muted&&x.keyframes.length&&(x.target.kind!=="camera"||r())&&f(x.target)===null).map(x=>`Unavailable target: ${x.name}.`),invalidate:n,apply:({sequence:h,time:x,playing:M})=>{let E=h.tracks.filter(g=>g.target.kind!=="camera"||r()).map(g=>({track:g,value:We(g,x)})).filter(g=>g.value!==null);for(let[g,m]of l)E.some(({track:b})=>b.target.kind==="clip"&&b.target.clip===g)||(S(g,m),l.delete(g));for(let{track:g}of E)if(g.target.kind==="object"&&["position","rotation","scale"].includes(g.target.property)){let m=p(g.target.objectId);m&&R(m)}let j=new Map([...i.keys()].map(g=>[g,g.transparent]));a.forEach((g,m)=>m.visible=g),s.forEach((g,m)=>{m.position.fromArray(g.position),m.rotation.set(...g.rotation),m.scale.fromArray(g.scale),Rt(m,g.shear)}),i.forEach((g,m)=>g.forEach((b,y)=>{b instanceof Pt.Color?m[y].copy(b):m[y]=b}));let D=o();for(let{track:g,value:m}of E){if(g.target.kind!=="clip"||!D?.seek||!D.clips.includes(g.target.clip))continue;let b=g.target.clip;l.has(b)||(l.set(b,D.getState?.().active.find(y=>y.clip===b)),D.play(b,{alongside:!0}),D.pause(b)),D.seek(m,b)}for(let{track:g,value:m}of E){let b=g.target;if(b.kind==="clip")continue;if(b.kind==="camera"){u||(u=f(b));let I=JSON.stringify(m);(M||I!==d)&&(C(m),d=I);continue}let y=p(b.objectId);if(!y)continue;let k=b.property;if(k==="visible")a.has(y)||a.set(y,y.visible),y.visible=m;else if(k==="position"||k==="rotation"||k==="scale")k==="rotation"?y.rotation.set(...m):y[k].fromArray(m),Rt(y,s.get(y)?.shear);else for(let I of no(y)){let N=It(k),T=I[N];if(T===void 0)continue;let P=i.get(I);if(P||(P=new Map,i.set(I,P)),j.has(I)||j.set(I,I.transparent),P.has(N)||P.set(N,T?.isColor?T.clone():T),T?.isColor?T.set(m):I[N]=m,k==="opacity"){P.has("transparent")||P.set("transparent",I.transparent);let F=m<1||P.get("transparent")===!0;I.transparent=F}}}u&&!E.some(({track:g})=>g.target.kind==="camera")&&(C(u),d=""),j.forEach((g,m)=>{g!==m.transparent&&(m.needsUpdate=!0)}),e()?.updateWorldMatrix(!0,!0)}}}function ro(e){let t=new Map;return e.map((o,n)=>{let s=o.name.trim()||`Animation ${n+1}`,a=t.get(s)??0;return t.set(s,a+1),{clip:o,sourceName:a===0?s:`${s} (${a+1})`,duration:o.duration}})}var X=require("three");function Or(e){let t=e.getAttribute("arSourceVertex"),o=e.getAttribute("arNormalSign");if(!t)return;let n=new Map,r=[],s=[];for(let i=0;i<t.count;i++){let c=`${t.getX(i)}:${o?.getX(i)??1}`,l=n.get(c);l===void 0&&(l=r.length,r.push(i),n.set(c,l)),s.push(l)}let a=e.index?Array.from(e.index.array,i=>s[i]):s;for(let[i,c]of Object.entries(e.attributes)){let l=new Float32Array(r.length*c.itemSize);r.forEach((u,d)=>{for(let p=0;p<c.itemSize;p++)l[d*c.itemSize+p]=c.getComponent(u,p)}),e.setAttribute(i,new X.BufferAttribute(l,c.itemSize))}e.setIndex(a)}function io(e,t,o,n){let r=[],s=[],a=new Map;for(let i of e){let c=i.source;if(!c.isSkinnedMesh)continue;let l=t.get(c),u=c.skeleton,d=JSON.stringify(u.bones.map((g,m)=>[g.uuid,u.boneInverses[m].elements])),p=a.get(d);if(!p){let g=new Map(u.bones.map((T,P)=>[T,P])),m=u.bones.map(T=>{for(let P=T.parent;P;P=P.parent)if(g.has(P))return g.get(P);return-1}),b=[],y=T=>{b.includes(T)||(m[T]>=0&&y(m[T]),b.push(T))};u.bones.forEach((T,P)=>y(P));let k=b.map(T=>b.indexOf(m[T])),I=[];b.forEach((T,P)=>I.push(`${k[P]<0?"":I[k[P]]+"/"}J_${T}`));let N={name:`${n}_${r.length}`,joints:I,parents:k,bones:b.map(T=>t.get(u.bones[T])),bindTransforms:b.map(T=>u.boneInverses[T].clone().invert()),restTransforms:[],worlds:b.map(()=>new X.Matrix4),referenceInverse:o.clone().invert(),frames:[]};if(N.bones.some(T=>!T))throw new Error("The AR skeleton has joints outside the exported scene.");p={rig:N,order:b},a.set(d,p),r.push(N)}Or(i.exported.geometry);let f=i.exported.geometry.getAttribute("arSourceVertex"),C=c.geometry.getAttribute("skinIndex"),R=c.geometry.getAttribute("skinWeight");if(!f||!C||!R||C.itemSize!==4||R.itemSize!==4)throw new Error("AR skeletal animation needs four joint indices and weights per vertex.");let S={target:i,node:l,rig:p.rig,reference:o,geomBind:c.bindMatrix.clone(),jointIndices:[],jointWeights:[],jointBounds:p.order.map(()=>new X.Box3),extent:new X.Box3},w=i.exported.geometry.getAttribute("position"),A=i.exported.geometry.getAttribute("normal"),h=c.geometry.getAttribute("normal"),x=i.exported.geometry.getAttribute("arNormalSign"),M=new X.Vector3,E=new X.Vector3,j=new Map(p.order.map((g,m)=>[g,m])),D=S.rig.bindTransforms.map(g=>g.clone().invert().multiply(c.bindMatrix));for(let g=0;g<f.count;g++){let m=f.getX(g);if(X.Mesh.prototype.getVertexPosition.call(c,m,M),w.setXYZ(g,M.x,M.y,M.z),h&&A){E.fromBufferAttribute(h,m);let y=E.clone();c.geometry.morphAttributes.normal?.forEach((k,I)=>{let N=c.morphTargetInfluences?.[I]??0;N&&E.addScaledVector(new X.Vector3().fromBufferAttribute(k,m).sub(c.geometry.morphTargetsRelative?new X.Vector3:y),N)}),E.normalize().multiplyScalar(x?.getX(g)??1),A.setXYZ(g,E.x,E.y,E.z)}let b=[0,1,2,3].reduce((y,k)=>y+R.getComponent(m,k),0);if(!Number.isFinite(b)||b<=0)throw new Error("The AR skin has a vertex without valid joint weights.");for(let y=0;y<4;y++){let k=R.getComponent(m,y)/b,I=k?j.get(C.getComponent(m,y))??-1:0;if(I<0||!Number.isFinite(k)||k<0)throw new Error("The AR skin has invalid joint indices or weights.");S.jointIndices.push(I),S.jointWeights.push(k),k&&S.jointBounds[I].expandByPoint(M.clone().applyMatrix4(D[I]))}}w.needsUpdate=!0,A?A.needsUpdate=!0:i.exported.geometry.computeVertexNormals(),i.exported.geometry.computeBoundingBox(),i.exported.matrixAutoUpdate=!1,i.exported.matrix.copy(Vt(S)),s.push(S)}return{rigs:r,skins:s}}function Vt(e){return e.node.matrixWorld.clone().multiply(e.node.bindMatrixInverse).multiply(e.reference)}function so(e,t,o){let n=new X.Vector3,r=new X.Quaternion,s=new X.Vector3,a=new X.Matrix4;for(let i of e){let c={time:o,translations:[],rotations:[],scales:[]};i.bones.forEach((l,u)=>i.worlds[u].multiplyMatrices(i.referenceInverse,l.matrixWorld)),i.worlds.forEach((l,u)=>{let d=i.parents[u],p=d<0?l.clone():i.worlds[d].clone().invert().multiply(l);p.decompose(n,r,s),r.normalize(),a.compose(n,r,s);let f=1e-5*Math.max(1,...p.elements.map(Math.abs));if(!p.elements.every(Number.isFinite)||p.elements.some((C,R)=>Math.abs(C-a.elements[R])>f)||Math.abs(p.determinant())<1e-15)throw new Error("The AR skeleton contains a sheared or zero-scale joint that Quick Look cannot preserve. Use arHandoff.createUSDZ for this rig.");c.translations.push(...n.toArray()),c.rotations.push(r.w,r.x,r.y,r.z),c.scales.push(...s.toArray()),i.frames.length||i.restTransforms.push(p)}),i.frames.push(c)}for(let i of t)i.jointBounds.forEach((c,l)=>{c.isEmpty()||i.extent.union(c.clone().applyMatrix4(i.rig.worlds[l]))})}var Dt=e=>String(Number(e.toPrecision(9))),Bt=e=>{let t=Array.isArray(e)?e:e.elements;return`(${[0,4,8,12].map(o=>`(${t.slice(o,o+4).map(Dt).join(", ")})`).join(", ")})`},Et=(e,t)=>Array.from({length:e.length/t},(o,n)=>`(${e.slice(n*t,(n+1)*t).map(Dt).join(", ")})`).join(", ");function ao(e){let t=(a,i,c=1e-7)=>Math.abs(a-i)>c*Math.max(1,Math.abs(a),Math.abs(i)),o=[["translations",3,"float3"],["rotations",4,"quatf"],["scales",3,"half3"]],n=e.frames[0],r=e.joints.map((a,i)=>i).filter(a=>o.some(([i,c])=>e.frames.some(l=>l[i].slice(a*c,(a+1)*c).some((u,d)=>t(u,n[i][a*c+d])))));r.length||(r=e.joints.map((a,i)=>i));let s=o.map(([a,i,c])=>{let l=e.frames.map(d=>r.flatMap(p=>d[a].slice(p*i,(p+1)*i)));return l.some(d=>d.some((p,f)=>t(p,l[0][f],c==="half3"?1e-4:1e-7)))?`${c}[] ${a}.timeSamples = {${e.frames.map((d,p)=>`${d.time}: [${Et(l[p],i)}]`).join(`,
3
3
  `)}}`:`${c}[] ${a} = [${Et(l[0],i)}]`}).join(`
4
4
  `);return`#usda 1.0
5
5
  (
package/dist/utils.mjs CHANGED
@@ -1 +1 @@
1
- import{a as ce,b as se,c as pe}from"./chunk-F5QSXMME.mjs";import{$a as Se,Ba as z,Ca as Q,Ha as J,Ia as Y,Ka as Z,Oa as te,P as a,Pa as oe,Q as c,Qa as ne,R as s,Ra as re,S as p,Sa as ie,Wa as ae,X as u,Ya as ue,Z as d,Za as de,_ as m,_a as me,ab as le,ia as S,ka as l,ma as f,na as g,oa as C,pa as y,qa as x,ra as P,sa as A,ta as H,ua as F,va as K,wa as W}from"./chunk-X4WRTDO6.mjs";import{b as $,c as ee}from"./chunk-CCBFMNAU.mjs";import"./chunk-7OWHW66D.mjs";import{a as e,b as t,e as o,f as n,g as r}from"./chunk-LX3GXQNU.mjs";import{b,c as E,d as h,e as j,f as R,g as T,h as V,i as I,j as L,k as w,l as D,m as _,n as N,o as q,p as k,q as v,r as U,s as G}from"./chunk-7JCFNZJM.mjs";import{b as O,c as B}from"./chunk-GV4ZRXL6.mjs";import{E as X}from"./chunk-6Q6YZ7O5.mjs";import{a as i}from"./chunk-IOLT2VXU.mjs";import{c as M}from"./chunk-BNKTI3CY.mjs";import"./chunk-JR557W27.mjs";export{Y as ACTION_CATALOG,i as DEFAULT_MODEL_VIEWER_LABELS,c as DEFAULT_SCENE_CONFIG,a as DEFAULT_SECTION_CONFIG,de as MATERIAL_BLENDING_MODES,ue as MATERIAL_SIDES,H as MAX_VIEWER_STATE_BYTES,S as MEASUREMENT_UNITS,t as SEQUENCE_EASINGS,e as SEQUENCE_OBJECT_PROPERTIES,oe as applyIsolation,G as applyProductOptions,ee as applyStyleRules,ie as buildBindingsFromNodes,f as calibrateMeasurements,M as chooseMaterialVariant,me as collectObjectHierarchy,$ as colorScaleValue,ae as compareViewerConfigurations,Se as copyBindingStyle,z as createARHandoffUrl,re as createDefaultBinding,D as decodeProductSelections,j as defaultProductSelections,pe as defineObjectBindings,w as encodeProductSelections,R as evaluateProductConfiguration,J as exportConfiguredUSDZ,Z as findCatalogAction,I as formatProductPrice,_ as generateProductSkus,m as groundAsset,ne as inferType,X as inspectAsset,te as isolatedBindingKeys,E as material,C as measurementResult,l as measurementScale,g as measurementValue,P as measurementsToCsv,u as parseAssetTransform,y as parseMeasurements,U as parseProductConfiguration,h as parseProductDefinition,k as parseSceneProduct,s as parseSectionConfig,A as parseSelectionSets,o as parseSequences,K as parseViewerState,le as pasteBindingStyle,b as patchBindings,ce as patchSceneConfig,W as prepareViewerState,L as productCheckoutUrl,N as productDefinitionWarnings,q as productOptionStates,V as productPriceFromDefinition,Q as readARHandoffUrl,T as resolveProductSelections,n as sampleSequenceTrack,se as sceneLight,p as sectionSnapshot,O as selectBindingKeys,B as selectBindings,x as serializeMeasurements,v as serializeProductConfiguration,F as serializeViewerState,d as snapAssetToGrid,r as upsertSequenceKeyframe};
1
+ import{a as ce,b as se,c as pe}from"./chunk-F5QSXMME.mjs";import{$ as A,Da as ae,E as u,Fa as ue,G as d,Ga as de,H as m,Ha as me,Ia as Se,Ja as le,R as S,T as l,V as f,W as g,X as C,Y as y,Z as x,_ as P,aa as H,ba as F,ca as K,da as W,ia as z,ja as Q,oa as J,pa as Y,ra as Z,va as te,w as a,wa as oe,x as c,xa as ne,y as s,ya as re,z as p,za as ie}from"./chunk-25WC5KDO.mjs";import{a as e,b as t,e as o,f as n,g as r}from"./chunk-LX3GXQNU.mjs";import{b,c as E,d as h,e as j,f as R,g as T,h as V,i as I,j as L,k as w,l as D,m as _,n as N,o as q,p as k,q as v,r as U,s as G}from"./chunk-7JCFNZJM.mjs";import"./chunk-UHRJ2RBF.mjs";import{b as $,c as ee}from"./chunk-CCBFMNAU.mjs";import{b as O,c as B}from"./chunk-GV4ZRXL6.mjs";import"./chunk-7OWHW66D.mjs";import{e as X}from"./chunk-KFLS7GI6.mjs";import{a as i}from"./chunk-UAZ6I25Y.mjs";import{c as M}from"./chunk-BNKTI3CY.mjs";import"./chunk-UCD76KQ6.mjs";import"./chunk-RXZ4Q7CY.mjs";import"./chunk-JR557W27.mjs";export{Y as ACTION_CATALOG,i as DEFAULT_MODEL_VIEWER_LABELS,c as DEFAULT_SCENE_CONFIG,a as DEFAULT_SECTION_CONFIG,de as MATERIAL_BLENDING_MODES,ue as MATERIAL_SIDES,H as MAX_VIEWER_STATE_BYTES,S as MEASUREMENT_UNITS,t as SEQUENCE_EASINGS,e as SEQUENCE_OBJECT_PROPERTIES,oe as applyIsolation,G as applyProductOptions,ee as applyStyleRules,ie as buildBindingsFromNodes,f as calibrateMeasurements,M as chooseMaterialVariant,me as collectObjectHierarchy,$ as colorScaleValue,ae as compareViewerConfigurations,Se as copyBindingStyle,z as createARHandoffUrl,re as createDefaultBinding,D as decodeProductSelections,j as defaultProductSelections,pe as defineObjectBindings,w as encodeProductSelections,R as evaluateProductConfiguration,J as exportConfiguredUSDZ,Z as findCatalogAction,I as formatProductPrice,_ as generateProductSkus,m as groundAsset,ne as inferType,X as inspectAsset,te as isolatedBindingKeys,E as material,C as measurementResult,l as measurementScale,g as measurementValue,P as measurementsToCsv,u as parseAssetTransform,y as parseMeasurements,U as parseProductConfiguration,h as parseProductDefinition,k as parseSceneProduct,s as parseSectionConfig,A as parseSelectionSets,o as parseSequences,K as parseViewerState,le as pasteBindingStyle,b as patchBindings,ce as patchSceneConfig,W as prepareViewerState,L as productCheckoutUrl,N as productDefinitionWarnings,q as productOptionStates,V as productPriceFromDefinition,Q as readARHandoffUrl,T as resolveProductSelections,n as sampleSequenceTrack,se as sceneLight,p as sectionSnapshot,O as selectBindingKeys,B as selectBindings,x as serializeMeasurements,v as serializeProductConfiguration,F as serializeViewerState,d as snapAssetToGrid,r as upsertSequenceKeyframe};
@@ -0,0 +1 @@
1
+ import"./chunk-JR557W27.mjs";import{XR as Re,createXRStore as Ne}from"@react-three/xr";import{forwardRef as ne,useCallback as g,useEffect as H,useImperativeHandle as re,useMemo as Y,useRef as s}from"react";import{useXR as U,useXRHitTest as oe,useXRInputSourceEvent as ce}from"@react-three/xr";import{useFrame as se}from"@react-three/fiber";import{Matrix4 as ae,Vector3 as q}from"three";import{Fragment as pe,jsx as w,jsxs as Z}from"react/jsx-runtime";var ue=1,O=1,ie=.1,le=10;function de(t,n){let[r,m,o]=t.size,l=(t.min[0]+t.max[0])/2,d=(t.min[2]+t.max[2])/2,a=Math.max(r,m,o)||1;return{scale:n==="real-world"?1:ue/a,offset:[-l,-t.min[1],-d]}}function V(t){let n=t[0].clientX-t[1].clientX,r=t[0].clientY-t[1].clientY;return Math.hypot(n,r)}function W(t){let n=t[0].clientX-t[1].clientX,r=t[0].clientY-t[1].clientY;return Math.atan2(r,n)}var fe=ne(function({box:n,scaleMode:r,children:m,onARStateChange:o},l){let d=s(null),a=s(null),v=s(null),X=U(e=>e.session!=null),c=U(e=>e.mode==="immersive-ar"),b=Y(()=>n?de(n,r):null,[n,r]),L=s(new q(0,0,-O)),E=s(1),y=s(0),p=s(!0),S=s(!1),D=Y(()=>new ae,[]),A=s(new q),M=s(!1),x=s(null),h=s(!1),T=s(0),F=s(0),I=s(1),_=s(0),f=g(()=>{if(!o||!c)return;let e={canPlace:M.current,isPlacementMode:p.current,isModelPlaced:S.current},u=x.current;u&&u.canPlace===e.canPlace&&u.isPlacementMode===e.isPlacementMode&&u.isModelPlaced===e.isModelPlaced||(x.current=e,o(e))},[c,o]),P=g(()=>!c||!M.current?!1:(L.current.copy(A.current),S.current=!0,p.current=!1,f(),!0),[f,c]),B=g(()=>{c&&(p.current=!0,f())},[f,c]),C=g(()=>{let e=P();return!e&&c&&(p.current=!1,f()),e},[f,c,P]),G=g(()=>{c&&(p.current=!1,f())},[f,c]);re(l,()=>({placeCurrent:P,startPlacementMode:B,finishPlacementMode:C,cancelPlacementMode:G}),[G,C,P,B]),H(()=>{if(!X){L.current.set(0,0,-O),E.current=1,y.current=0,M.current=!1,h.current=!1,p.current=!0,S.current=!1,x.current=null;return}c&&(M.current=!1,h.current=!1,p.current=!0,S.current=!1,x.current=null,f())},[f,X,c]),oe((e,u)=>{if(!c||e.length===0){M.current&&(M.current=!1,f());return}u(D,e[0])&&(A.current.setFromMatrixPosition(D),M.current||(M.current=!0,f()))},"viewer"),ce("all","select",()=>{!c||h.current||!p.current||P()},[c,P]),H(()=>{if(!c)return;let e=i=>{i.touches.length===2&&(h.current=!0,T.current=V(i.touches),F.current=W(i.touches),I.current=E.current,_.current=y.current)},u=i=>{if(!h.current||i.touches.length!==2)return;i.preventDefault();let j=V(i.touches);if(T.current>0){let te=j/T.current;E.current=Math.min(le,Math.max(ie,I.current*te))}let ee=W(i.touches);y.current=_.current-(ee-F.current)},R=i=>{i.touches.length===0&&requestAnimationFrame(()=>{h.current=!1})};return window.addEventListener("touchstart",e),window.addEventListener("touchmove",u,{passive:!1}),window.addEventListener("touchend",R),window.addEventListener("touchcancel",R),()=>{window.removeEventListener("touchstart",e),window.removeEventListener("touchmove",u),window.removeEventListener("touchend",R),window.removeEventListener("touchcancel",R)}},[c]),se(()=>{let e=d.current,u=a.current;if(!e||!u)return;!X||!b?(e.visible=!0,e.position.set(0,0,0),e.rotation.set(0,0,0),u.scale.setScalar(1)):(e.visible=!c||S.current,e.position.copy(L.current),e.rotation.set(0,y.current,0),u.scale.setScalar(b.scale*E.current));let R=v.current;if(R){let i=c&&p.current&&M.current;R.visible=i,i&&R.position.copy(A.current)}});let $=X&&b?b.offset:[0,0,0];return Z(pe,{children:[Z("mesh",{ref:v,visible:!1,rotation:[-Math.PI/2,0,0],children:[w("ringGeometry",{args:[.05,.07,32]}),w("meshBasicMaterial",{color:"#22d3ee",transparent:!0,opacity:.95})]}),w("group",{ref:d,children:w("group",{ref:a,children:w("group",{position:$,children:m})})})]})}),me=fe;import{useFrame as K,useThree as k}from"@react-three/fiber";import{useXR as J}from"@react-three/xr";import{useEffect as N,useRef as z}from"react";function Q({renderMode:t,suspended:n=!1}){let{scene:r}=k(),m=k(a=>a.setFrameloop),o=J(a=>a.session!=null),l=J(a=>a.mode==="immersive-ar"),d=z(void 0);return N(()=>{m(n?"never":o?"always":t)},[o,t,n,m]),N(()=>{l?(d.current=r.background,r.background=null):d.current!==void 0&&(r.background=d.current,d.current=void 0)},[l,r]),K(()=>{l&&r.background!==null&&(r.background=null)}),null}function Me({onPresentingChange:t}){let n=k(o=>o.gl),r=z(null);N(()=>{let o=n.xr;if(!o)return;let l=v=>{v?(r.current=n.shadowMap.enabled,n.shadowMap.enabled=!1):r.current!==null&&(n.shadowMap.enabled=r.current,r.current=null),t(v)},d=()=>l(!0),a=()=>l(!1);return o.addEventListener("sessionstart",d),o.addEventListener("sessionend",a),l(o.isPresenting),()=>{o.removeEventListener("sessionstart",d),o.removeEventListener("sessionend",a)}},[n,t]);let m=z(0);return K(()=>{if(!n.xr.isPresenting)return;let o=performance.now();if(o-m.current<1e3)return;m.current=o;let l=n.xr}),null}import{jsx as he,jsxs as Pe}from"react/jsx-runtime";function Fe({store:t,renderMode:n,suspended:r,children:m}){return Pe(Re,{store:t,children:[he(Q,{renderMode:n,suspended:r}),m]})}export{me as XRModelPresenter,Me as XRPerformanceManager,Fe as XRScene,Ne as createXRStore};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liveroom-tech/react-immersive",
3
- "version": "6.2.0",
3
+ "version": "6.2.1",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",