@hatiolab/things-scene 10.1.106 → 10.1.107
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist-types/figure/figure-real-object.d.ts +2 -1
- package/dist-types/figure/figure-real-object.d.ts.map +1 -1
- package/dist-types/items/item.d.ts +11 -0
- package/dist-types/items/item.d.ts.map +1 -1
- package/package.json +1 -1
- package/things-scene-min.js +1 -1
- package/things-scene-min.js.map +1 -1
- package/things-scene-transfer.mjs +1 -1
- package/things-scene.mjs +1 -1
- package/things-scene.mjs.map +1 -1
package/things-scene-min.js
CHANGED
|
@@ -69,5 +69,5 @@ const jg=globalThis,$g=t=>t,Lg=jg.trustedTypes,Fg=Lg?Lg.createPolicy("lit-html",
|
|
|
69
69
|
</button>`:iy}
|
|
70
70
|
${n?ny`<button class="closable" @click=${this.closeContainer}>close</button>`:iy}
|
|
71
71
|
</div>
|
|
72
|
-
`,this.element)}catch(t){}}onchangeMinimized(){const{minimized:t}=this.state;t?this.setState("height",24):this.setState("height",this.get("height"))}}Ay=new WeakMap,uc.memoize(Cy.prototype,"bounds",!0),uc.register("container",Cy);const Oy=Math.sqrt(3),Py=2;function Iy(t,e,n,s,i){const o=5+i,r=n.x,a=n.y,c=s.x,l=s.y;if(Math.abs(r-c)>o&&Math.abs(a-l)>o){const n=(l-a)/(c-r),s=a-n*r;if(Math.abs(e-(n*t+s))>o)return!1}let h,d,u,p;return r>c?(d=r,h=c):(d=c,h=r),a>l?(p=a,u=l):(p=l,u=a),!(d+5<t)&&(!(h-5>t)&&(!(p+5<e)&&!(u-5>e)))}function Dy(t,e,n,s=2){for(let i=0;i<n.length-1;i++)if(Iy(t,e,n[i],n[i+1],s))return!0;return!1}function zy(t,e,n,s){if("arrow"!=t.slice(-5))return n;const i=Math.atan2(s.y-n.y,s.x-n.x),o=1.5*e;return{x:n.x+Math.cos(i)*o,y:n.y+Math.sin(i)*o}}function Ry(t,e,n){let{lineWidth:s=Py,strokeStyle:i="#000000",lineCap:o=!1,alpha:r=1,begin:a="none",end:c="none",beginSize:l="size5",endSize:h="size5"}=n;if(("none"!=a||"none"!=c)&&(s=Number(s)||Py,t.lineCap=o,t.lineWidth=s,t.strokeStyle=i,t.fillStyle=i,t.globalAlpha*=r,"none"!=a&&jy(t,e[0],e[1],s,a,$y(l,s)),"none"!=c)){const n=e.length;jy(t,e[n-1],e[n-2],s,c,$y(h,s))}}function jy(t,e,n,s,i,o){const{x:r,y:a}=e,c=Math.atan2(n.y-a,n.x-r);switch(t.beginPath(),t.translate(r,a),t.rotate(c),i){case"oval":t.ellipse(0,0,o.X,o.Y,0,0,2*Math.PI),t.fill();break;case"diamond":t.moveTo(-o.X,0),t.lineTo(0,-o.Y),t.lineTo(o.X,0),t.lineTo(0,o.Y),t.fill();break;case"arrow":t.moveTo(0,0),t.lineTo(Oy*o.X,-o.Y),t.lineTo(Oy*o.X,o.Y),t.fill();break;case"sharp-arrow":t.moveTo(0,0),t.lineTo(Oy*o.X,-o.Y),t.lineTo(-o.X/1.5+Oy*o.X,0),t.lineTo(Oy*o.X,o.Y),t.fill();break;case"open-arrow":t.moveTo(Oy*o.X+s,-o.Y),t.lineTo(s,0),t.lineTo(Oy*o.X+s,o.Y),t.stroke();break;case"cross":t.moveTo(-o.X,-o.Y),t.lineTo(o.X,o.Y),t.moveTo(o.X,-o.Y),t.lineTo(-o.X,o.Y),t.stroke()}t.rotate(-c),t.translate(-r,-a),t.closePath()}function $y(t,e){const n={X:0,Y:0};switch(e*=1.2,t){case"size1":n.X=e,n.Y=e;break;case"size2":n.X=1.5*e,n.Y=e;break;case"size3":n.X=2*e,n.Y=e;break;case"size4":n.X=e,n.Y=1.5*e;break;case"size5":default:n.X=1.5*e,n.Y=1.5*e;break;case"size6":n.X=2*e,n.Y=1.5*e;break;case"size7":n.X=e,n.Y=2*e;break;case"size8":n.X=1.5*e,n.Y=2*e;break;case"size9":n.X=2*e,n.Y=2*e}return n}const Ly="N",Fy="S",Ny="E",Hy="W";class By{constructor({component:t,anchor:e,position:n,self:s}){this.component=t,this._anchorName=e,this._position=n,this.self=s}get position(){const t=this.anchor;if(t){const{position:e}=t,n=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(n.x,n.y)}return this._position}set position({x:t,y:e}){this._position={x:t,y:e}}get anchor(){return this.component?.findAnchor(this._anchorName)}get direction(){const t=this.component.bounds,e=this.anchor;if(!e)return Ny;const n=e.position;return n.y<=t.top?Ly:n.y>=t.top+t.height?Fy:n.x<=t.left?Hy:Ny}get boundaryPosition(){const t=this.anchor;if(t){let{position:e}=t,n=0,s=0;switch(this.direction){case Fy:s=20;break;case Ly:s=-20;break;case Hy:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+s};const i=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(i.x,i.y)}}}class Gy extends uc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const s=t.get(n.component)||n.component;this.set(e,{...n,component:s})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._fromEnd=new By({component:s,fromto:"from",anchor:e,position:n,self:this})}return this._fromEnd}get from(){return this.getState("from")}set from(t){delete this._fromEnd,this.set("from",t)}get toEnd(){if(this.parent&&!this._toEnd){const{component:t,anchor:e,position:n}=this.getState("to")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._toEnd=new By({component:s,fromto:"to",anchor:e,position:n,self:this})}return this._toEnd}get to(){return this.getState("to")}set to(t){delete this._toEnd,this.set("to",t)}move({x:t,y:e},n){n&&(this.from={position:this._fromEnd?.position||this.getState("from")?.position||{x:0,y:0}},this.to={position:this._toEnd?.position||this.getState("to")?.position||{x:0,y:0}}),super.move({x:t,y:e})}render(t){const{begin:e="none",end:n="none",lineWidth:s,round:i=0}=this.state;let o=this.drawPath;Ry(t,o,this.state),t.beginPath();const r=zy(e,s,o[0],o[1]),a=zy(n,s,o[o.length-1],o[o.length-2]),c=o[0];o=[r,...o.slice(1,-1),a];let l={x:r.x,y:r.y};if(t.moveTo(r.x,r.y),o.length>=2&&zo(c)){const e=o[1],n=Lo(e,i),s=Math.sqrt((r.x-e.x)**2+(r.y-e.y)**2),a=0!==s?Math.atan2(r.x-e.x,r.y-e.y):0,l=Math.sin(a)*Math.min(n,s/2)+e.x,h=Math.cos(a)*Math.min(n,s/2)+e.y,d=Ro({x:r.x,y:r.y},{x:l,y:h},c.bulge);d&&t.arc(d.cx,d.cy,d.radius,d.startAngle,d.endAngle,d.clockwise)}for(let e=1;e<o.length;e++){const n=l;l=o[e];const s=o[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!s){t.lineTo(l.x,l.y);break}const r=Lo(l,i);let a=Math.sqrt((n.x-l.x)*(n.x-l.x)+(n.y-l.y)*(n.y-l.y)),c=0!==a?Math.atan2(n.x-l.x,n.y-l.y):0,h=Math.sin(c)*Math.min(r,a/2)+l.x,d=Math.cos(c)*Math.min(r,a/2)+l.y;const u=r>0||0!==a?{x:h,y:d}:l;a=Math.sqrt((s.x-l.x)*(s.x-l.x)+(s.y-l.y)*(s.y-l.y)),c=0!==a?Math.atan2(s.x-l.x,s.y-l.y):0,h=Math.sin(c)*Math.min(r,a/2)+l.x,d=Math.cos(c)*Math.min(r,a/2)+l.y;const p=r>0||0!==a?{x:h,y:d}:l;if(t.lineTo(u.x,u.y),r>0&&t.quadraticCurveTo(l.x,l.y,p.x,p.y),zo(l)){const e=Lo(s,i),n=Math.sqrt((l.x-s.x)**2+(l.y-s.y)**2),o=0!==n?Math.atan2(l.x-s.x,l.y-s.y):0,r=Math.sin(o)*Math.min(e,n/2)+s.x,a=Math.cos(o)*Math.min(e,n/2)+s.y,c=Ro({x:p.x,y:p.y},{x:r,y:a},l.bulge);c&&t.arc(c.cx,c.cy,c.radius,c.startAngle,c.endAngle,c.clockwise)}}this.drawStroke(t,void 0)}contains(t,e){const{lineWidth:n}=this.state;return Dy(t,e,this.drawPath,n)}get resizable(){return!1}get mutable(){return!0}get rotatable(){return!1}get path(){const{from:t,to:e}=this.state,{x1:n,y1:s,x2:i,y2:o}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:s},this.toEnd?.position||e?.position||{x:i,y:o}]}set path(t){const[e,n]=t,{from:s,to:i}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...s,position:e},to:{...i,position:n}})}get textBounds(){const t=this.drawPath;let e,n,s=0;for(let i=1;i<t.length;i++){const o=t[i-1],r=t[i],a=(o.x-r.x)*(o.x-r.x)+(o.y-r.y)*(o.y-r.y);a>s&&(s=Math.ceil(a),e=o,n=r)}let{paddingTop:i,paddingLeft:o,paddingRight:r,paddingBottom:a}=this.state;return a||=0,i||=0,o||=0,r||=0,{left:Math.min(e.x,n.x)+o,top:Math.min(e.y,n.y)+i,width:Math.max(Math.abs(e.x-n.x)-o-r,0),height:Math.max(Math.abs(e.y-n.y)-i-a,0)}}get decorators(){return this.app.isEditMode?["decotag"]:[]}}Gy.getTipNeckPos=zy,Gy.containedInPath=Dy,Gy.drawEndTips=Ry,uc.register("line",Gy);const Uy={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"angle",label:"start-angle",name:"startAngle",property:"startAngle"},{type:"angle",label:"end-angle",name:"endAngle",property:"endAngle"}],"value-property":"text"};class Vy extends(xm(pc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:s,ry:i,startAngle:o,endAngle:r,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(s),Math.abs(i),0,o||0,r||2*Math.PI,a),void 0!==o&&void 0!==r&&(t.lineTo(e,n),t.closePath())}get path(){const{cx:t,cy:e,rx:n,ry:s}=this.state;return[{x:t-n,y:e-s},{x:t+n,y:e-s},{x:t+n,y:e+s},{x:t-n,y:e+s}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2,rx:(n.x-e.x)/2,ry:(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s,rx:i,ry:o}=this.state,r=(t-n)/(2*i-.5),a=(e-s)/(2*o-.5);return r*r+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:s,rx:i,ry:o}=t.model,r=2*Math.PI*e,a=n+i*Math.cos(r),c=s+o*Math.sin(r);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:s,height:i}=t.bounds,o=e+s/2,r=n+i/2;return[{name:"TOP",position:{x:o,y:n}},{name:"RIGHT",position:{x:e+s,y:r}},{name:"BOTTOM",position:{x:o,y:n+i}},{name:"LEFT",position:{x:e,y:r}}]}(this)}get nature(){return Uy}}uc.memoize(Vy.prototype,"path",!1),uc.register("ellipse",Vy);const Wy={object:{fill:"rgba(180,180,180,0.18)",stroke:"#888888",icon:"?",label:"object"},transport:{fill:"rgba(100,180,255,0.18)",stroke:"#3a78c8",icon:"⇄",label:"transport"},facility:{fill:"rgba(160,140,220,0.18)",stroke:"#6b4ec8",icon:"◫",label:"facility"},vehicle:{fill:"rgba(120,200,140,0.18)",stroke:"#3a8c5e",icon:"⊙",label:"vehicle"},region:{fill:"rgba(220,200,100,0.18)",stroke:"#a0892a",icon:"▢",label:"region"},path:{fill:"rgba(200,140,160,0.18)",stroke:"#a0506a",icon:"⌐",label:"path"},"3d-asset":{fill:"rgba(255,180,80,0.18)",stroke:"#c87a2a",icon:"◈",label:"3D asset"}},Yy=[{type:"string",label:"placeholder-label",name:"placeholderLabel",description:'사용자에게 표시할 추가 라벨 (예: "Stocker A1")'},{type:"string",label:"hint",name:"placeholderHint",description:"구체화 시 참고 — 도면의 원본 식별자 / VLM 라벨 등"}];function qy(t,e,n,s,i){const{left:o,top:r,width:a,height:c}=e,l=Math.max(a,1),h=Math.max(c,1);t.save(),t.fillStyle=n.fill,t.fillRect(o,r,l,h),t.strokeStyle=n.stroke,t.lineWidth=1.5,t.setLineDash([4,3]),t.strokeRect(o,r,l,h),t.setLineDash([]),t.restore(),Math.min(l,h)>=24&&(t.save(),t.fillStyle=n.stroke,t.font=`bold ${Math.min(20,.4*Math.min(l,h))}px Arial`,t.textAlign="center",t.textBaseline="middle",t.fillText(n.icon,o+l/2,r+h/2),t.restore());const d=s?`${n.label}: ${s}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,o+l/2,r+h-4),t.restore()),i&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${i}`,o+l-4,r+4),t.restore())}const Xy={mutable:!1,resizable:!0,rotatable:!0,properties:[...Yy,{type:"placeholder-convert",label:"",name:"_convert"}],help:"scene/component/placeholder"};class Ky extends(mc(pc)){get nature(){return Xy}render(t){const{placeholderLabel:e,placeholderHint:n}=this.state;qy(t,this.bounds,Wy.object,e,n)}}uc.register("placeholder",Ky);const Jy=["placeholder"];function Qy(t,e=[]){return!!t&&(!!Jy.includes(t)||e.includes(t))}const Zy={ondragstart:function(t,e,n){n.mutatePath(null,function(n){n.splice(e+1,0,t)})},ondragmove:function(t,e,n){n.mutatePath(null,function(n){const s=n[e+1];n[e+1]={...s||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},tb={mutable:!0,resizable:!1,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/polygon"};class eb extends pc{is3dish(){return!0}get mutable(){return!0}get pathExtendable(){return!0}get cornerEditable(){return!0}get path(){return this.state.path??[]}set path(t){this.set("path",t)}contains(t,e){const n=this.path;let s=!1;return n.forEach((i,o)=>{const r=(o+n.length+1)%n.length,a=i.x,c=i.y,l=n[r].x,h=n[r].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}get controls(){const t=this.path;return t.map((e,n)=>{const s=t[n+1>=t.length?0:n+1];return{x:(e.x+s.x)/2,y:(e.y+s.y)/2,handler:Zy}})}get nature(){return tb}}uc.memoize(eb.prototype,"controls",!1),uc.register("polygon",eb);const nb=[];class sb extends(ql(eb)){constructor(t,e){super(t,e),this._components=[]}replaceRefids(t){this.components.forEach(e=>e.replaceRefids(t))}get showMoveHandle(){return!0}get showOverflow(){return!1}dispose(){this.components.slice().forEach(t=>t.dispose()),super.dispose()}isContainer(){return!0}containable(t){return t.isDescendible(this)}get hasTextProperty(){return!1}get components(){return this._components}get focusible(){return!0}get layout(){return xc.get(this.get("layout"))||Mc}reflow(){this.layout.reflow(this),this.components&&this.components.forEach(t=>{t.isContainer()&&t.reflow()})}get hierarchy(){const t=super.hierarchy;return this.components?.length&&(t.components=this.components.map(t=>t.hierarchy)),t}reparent(t,e={}){t&&t.parent!==this&&this.addComponent(t,{silent:!0})}addComponent(t,e=!1){const{ghost:n=!1,silent:s=!1}="boolean"==typeof e?{ghost:e}:e,i=t.parent;if(i){if(this===i)return;i.removeComponent(t,n||s)}const o=this._components.push(t)-1;s&&(t._silentAdd=!0),t.parent=this,t.added(this),n||s||this.trigger("add",this,t,o),t.delegate_on(this),s?(i&&this.root?._removeTraverse?.(t),this.trigger("add",this,t,o),t.trigger("added",this,t,o),delete t._silentAdd):n||t.trigger("added",this,t,o),this.root&&this.root.isReady&&t.invokeReady()}removeComponent(t,e=!1){const n=this._components.indexOf(t);-1!=n&&(this._components.splice(n,1),t.parent=null,t.removed(this),e||(this.trigger("remove",this,t),t.trigger("removed",this,t)),t.delegate_off(this))}insertComponentAt(t,e,n=!1){const s=t.parent;s&&s.removeComponent(t,n);const i=this._components.splice(0,e);this._components=i.concat(t,this._components),e=this._components.indexOf(t),t.parent=this,t.added(this),n||this.trigger("add",this,t,e),t.delegate_on(this),n||t.trigger("added",this,t,e)}add(t,e=!1){return t instanceof Array?(t.forEach(t=>{-1==this._components.indexOf(t)&&this.addComponent(t,e)}),this):this.add.call(this,[t],e)}remove(t,e=!1){return t instanceof Array?this._components?(t.forEach(t=>this.removeComponent(t,e)),this):this:this.remove.call(this,[t],e)}getAt(t){if(this._components)return this._components[t]}forEach(t,e){this._components&&this._components.forEach(t,e)}traverse(t,e){t.call(e,this),this._components&&this._components.forEach(n=>{n.isContainer()?n.traverse(t,e):t.call(e,n)})}indexOf(t){return(this._components||nb).indexOf(t)}size(){return(this._components||nb).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let s=this._components.splice(0,n);const i=this._components.splice(1);this._components=s.concat(i),t=Math.max(0,t),t=Math.min(t,this._components.length),s=this._components.splice(0,t),this._components=s.concat(e,this._components)}moveChildForward(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this._components[e]=this._components[e+1],this._components[e+1]=t)}moveChildBackward(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this._components[e]=this._components[e-1],this._components[e-1]=t)}moveChildToFront(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=n.concat(s,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=this._components.concat(n,s)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return Fa(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let s=this.components.length-1;s>=0;s--){const i=this.components[s].findAll(t,...e);i&&(n=n.concat(i))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return Fa(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const s=this.components[n].findFirst(t,...e);if(null!=s)return s}return t(this,...e)?this:void 0}}findById(t){return this.root.findAllById?.(t)?.[0]}findByRefid(t){return this.root.findByRefid?.(t)}capture(t,e,n){if(!this.app.isEditMode&&this.hidden)return!1;const s=this.fromParent(t,e);if(!this.contains(s.x,s.y))return!1;const i=this.bounds;s.x-=i.left,s.y-=i.top;const o=this.layout.capturables(this);for(let i=o.length-1;i>=0;i--){const r=o[i];let a;if(a="static"==r.position?r.capture(s.x,s.y,n):r.capture(t,e,n),a)return a}return this.capturable&&!n?.(this)&&this}capturePath(t,e){if(e){if(e.indexOf(this)>-1)return!1;for(let t=0;t<e.length;t++)if(!this.containable(e[t]))return!1}const n=[],{left:s,top:i,width:o,height:r}=this.bounds;for(let e=0;e<t.length;e++){const a=this.fromParent(t[e].x,t[e].y);if(a.x<s||a.x>s+o||a.y<i||a.y>i+r)return!1;a.x-=s,a.y-=i,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const s=a[t];if(!s.isContainer())continue;const i=s.capturePath(n,e);if(i)return i}return this.focusible&&this}render(t){"popup"!==this.position&&super.render(t)}postrender(t){if("popup"===this.position)return void super.postrender(t);const e=this.layout.drawables(this);if(e.length>0){let{left:n=0,top:s=0,width:i,height:o}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,s,i,o),t.clip(),t.closePath()),t.translate(n,s),e.forEach(e=>{const n=this.root?.transitionEffect;n?.isReparenting(e)||e.draw(this.position&&"static"!==this.position?t:this.getContext(e))}),t.translate(-n,-s),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>uc.memoize(sb.prototype,t,!1));const ib={ondragstart:function(t,e,n){n.mutatePath(null,function(n){n.splice(e,0,t)})},ondragmove:function(t,e,n){n.mutatePath(null,function(n){const s=n[e];n[e]={...s||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},ob={mutable:!1,resizable:!1,rotatable:!1,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/polyline"};class rb extends Gy{get pathExtendable(){return!0}get cornerEditable(){return!0}get path(){const{from:t,to:e}=this.state,{path:n}=this.state;return[this.fromEnd?.position||t?.position||n[0],...n.slice(1,-1),this.toEnd?.position||e?.position||n[n.length-1]]}set path(t){const{from:e,to:n}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...e,position:t[0]},to:{...n,position:t[t.length-1]},path:t})}get controls(){const t=this.path,e=[];for(let n=0;n<t.length-1;n++){const s=t[n],i=t[n+1];0==n&&e.push({x:s.x,y:s.y,handler:ib}),e.push({x:(s.x+i.x)/2,y:(s.y+i.y)/2,handler:ib}),n==t.length-2&&e.push({x:i.x,y:i.y,handler:ib})}return e}get nature(){return ob}}uc.register("polyline",rb);const ab={mutable:!1,resizable:!1,rotatable:!1,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/ortholine"};class cb extends Gy{get pathExtendable(){return!1}get drawPath(){const t=this.path[0],e=this.path[1],{component:n,direction:s,boundaryPosition:i=t}=this.fromEnd||{},{component:o,direction:r,boundaryPosition:a=e}=this.toEnd||{},c=[i,a],l=[];i&&l.push(i);let h,d=n?.bounds;d&&(h=n.toScene(d.left,d.top),h=this.transcoordT2P(h.x,h.y),d={...d,left:h.x,top:h.y});const u=d?{left:d.left-20,top:d.top-20,width:d.width+40,height:d.height+40}:{left:i.x,top:i.y,width:0,height:0};d=d||u;let p=o?.bounds;p&&(h=o.toScene(p.left,p.top),h=this.transcoordT2P(h.x,h.y),p={...p,left:h.x,top:h.y});const f=p?{left:p.left-20,top:p.top-20,width:p.width+40,height:p.height+40}:{left:a.x,top:a.y,width:0,height:0};p=p||f;const m=[u,f],g=u.left>f.left?f.left:u.left,y=u.top>f.top?f.top:u.top,b={left:g,top:y,width:u.left+u.width>f.left+f.width?u.left+u.width-g:f.left+f.width-g,height:u.top+u.height>f.top+f.height?u.top+u.height-y:f.top+f.height-y};let v,_,x,w,M,S,A,k,E,T,C=0,O=0;d.left+d.width<p.left?(w=0,M=1,E=s,T=r,v=(d.left+d.width+p.left)/2,C=p.left-v):p.left+p.width<d.left&&(w=1,M=0,E=r,T=s,v=(d.left+p.width+p.left)/2,C=d.left-v),d.top+d.height<p.top?(x=0,S=1,A=s,k=r,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,A=r,k=s,_=(d.top+p.height+p.top)/2,O=d.top-_);const P=[];if(v&&C>O){let t,e,n;switch(T){case Hy:switch(E){case Ny:P.push({x:v,y:c[w].y}),P.push({x:v,y:c[M].y});break;case Hy:t=m[w].top+m[w].height/2,e=t>c[M].y?Math.min(m[w].top,c[M].y):Math.max(m[w].top+m[w].height,c[M].y),P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:c[M].y});break;case Ly:case Fy:e=E===Fy?Math.max(c[w].y,c[M].y):Math.min(c[w].y,c[M].y),P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:c[M].y});break;default:return this.path}break;case Ny:switch(E){case Ny:e=c[w].y<c[M].y?Math.min(m[M].top,c[w].y):Math.max(m[M].top+m[M].height,c[w].y),n=e;break;case Hy:e=void 0!==_?_:c[w].y<c[M].y?b.top-.5*C:b.top+b.height+.5*C,n=e;break;case Fy:e=void 0!==_?Math.max(_,c[w].y):b.top+b.height,n=e;break;case Ly:e=_?Math.min(_,m[w].top):b.top,n=e;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;case Fy:switch(E){case Ny:e=c[w].y,n=c[w].y>c[M].y?c[w].y:m[M].top+m[M].height;break;case Hy:e=_?Math.max(_,m[M].top+m[M].height):b.top+b.height,n=e;break;case Fy:e=b.top+b.height,n=e;break;case Ly:e=_?Math.min(_,m[w].top):m[w].top,n=_?Math.max(_,m[M].top+m[M].height):m[M].top+m[M].height;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;case Ly:switch(E){case Ny:e=c[w].y,n=c[w].y<c[M].y?c[w].y:m[M].top;break;case Hy:e=_?Math.min(_,m[M].top):b.top,n=e;break;case Fy:e=void 0!==_?Math.max(_,c[w].y):c[w].y,n=void 0!==_?Math.min(_,c[M].y):c[M].y;break;case Ly:e=b.top,n=e;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;default:return this.path}l.push(...0===w?P:P.reverse())}else if(_){let t,e,n;switch(k){case Ly:switch(A){case Fy:P.push({x:c[x].x,y:_}),P.push({x:c[S].x,y:_});break;case Ly:t=m[x].left+m[x].width/2,e=t>c[S].x?Math.min(m[x].left,c[S].x):Math.max(m[x].left+m[x].width,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;case Hy:e=Math.min(c[x].x,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;case Ny:e=Math.max(c[x].x,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;default:return this.path}break;case Fy:switch(A){case Hy:e=b.left,n=e;break;case Ny:e=void 0!==v?Math.max(v,c[x].x):b.left+b.width,n=e;break;case Ly:e=void 0!==v?v:c[x].x<c[S].x?b.left-.5*O:b.left+b.width+.5*O,n=e;break;case Fy:e=c[x].x,n=c[x].x<c[S].x?Math.min(m[S].left,c[x].x):Math.max(m[S].left+m[S].width,c[x].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;case Ny:switch(A){case Hy:e=void 0!==v?Math.min(v,c[x].x):c[x].x,n=void 0!==v?Math.max(v,c[S].x):c[S].x;break;case Ny:e=b.left+b.width,n=e;break;case Ly:e=void 0!==v?Math.max(v,c[S].x):b.left+b.width,n=e;break;case Fy:e=c[x].x,n=Math.max(m[S].left+m[S].width,c[x].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;case Hy:switch(A){case Hy:e=b.left,n=e;break;case Ny:e=void 0!==v?Math.max(v,c[x].x):c[x].x,n=void 0!==v?Math.min(v,c[S].x):c[S].x;break;case Ly:e=b.left,n=e;break;case Fy:e=c[x].x<c[S].x?Math.min(m[S].left,c[x].x):c[x].x,n=Math.min(e,c[S].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;default:return this.path}l.push(...0===x?P:P.reverse())}else{let t,e;switch(s){case Ly:switch(r){case Ly:e=b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Fy:t=b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:b.top+b.height}),l.push({x:c[1].x,y:b.top+b.height});break;case Ny:t=c[1].y<c[0].y&&c[1].x<c[0].x?c[0].x:b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;case Hy:t=b.left,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;default:return this.path}break;case Fy:switch(r){case Ly:t=b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:b.top}),l.push({x:c[1].x,y:b.top});break;case Fy:case Ny:case Hy:e=b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;default:return this.path}break;case Hy:switch(r){case Ly:t=c[0].x>c[1].x&&c[0].y<c[1].y?c[1].x:b.left,e=c[0].x>c[1].x&&c[0].y<c[1].y?c[1].y:Math.min(b.top,c[0].y),l.push({x:t,y:c[0].y}),l.push({x:t,y:e}),l.push({x:c[1].x,y:e});break;case Fy:t=b.left,e=Math.max(b.top+b.height,c[0].y),l.push({x:t,y:c[0].y}),l.push({x:t,y:e}),l.push({x:c[1].x,y:e});break;case Ny:t=b.left+b.width,l.push({x:c[0].x,y:b.top}),l.push({x:t,y:b.top}),l.push({x:t,y:c[1].y});break;case Hy:t=b.left,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;default:return this.path}break;case Ny:switch(r){case Ly:e=c[0].y<c[1].y&&c[0].x<c[1].x?c[0].y:b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Fy:e=c[0].y>c[1].y&&c[0].x<c[1].x?c[0].y:b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Ny:case Hy:e=b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;default:return this.path}break;default:return this.path}}return a&&l.push(a),[t,...l,e].filter((t,e,n)=>{if(0===e)return!0;const s=n[e-1];return t.x!==s.x||t.y!==s.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const s=n[e-1],i=n[e+1];return!(t.x===s.x&&t.x===i.x||t.y===s.y&&t.y===i.y)})}get nature(){return ab}}uc.register("ortholine",cb);const lb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"image-selector",label:"image-src",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:"$base_url",defaultStorage:"scene-image",storageFilters:{type:Array,value:[{name:"category",value:"image"}]},useUpload:!0}},{type:"select",label:"cross-origin",name:"crossOrigin",property:{options:["","anonymous","use-credentials"]}}],"value-property":"src",help:"scene/component/image-view"};class hb extends(mc(pc)){static get noimage(){return hb.NOIMAGE||(hb.NOIMAGE=new Image,hb.NOIMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABIBAMAAAD7Se1QAAAAIVBMVEUAAABHcEwBAQEREREBAQEEBAQGBgYLCwsDAwMDAwMICAi6HF9tAAAAC3RSTlNNAEAERiMYCS41Eac10lYAAAEgSURBVHhe7dY9asQwEAXgh7DNertNiJy48pIitY3SB7bYdk0ukL1BDDmA9gZecoH4pmFQ3MQayUMguPBrNPD4wD9TCMvJmt3M/AtYwXOlXiWgqADVCUBD46MAnGhMBaCiUQmAm8VA/Eh/eWl9Fn5WcxD+OLuRrUYJDKLluwH2InACUgkoACSdADxQc50Bytadb9RkM0CT13TcvlCT1HFg8UTHvasuUVACCa3El6u2UdD8LFTlKhUFFgA+d3dj10aABkUN72N3jAADCrJq7PIIsPidcxBoTHIIAjMFmyCwmGYIAA1P9gFgfCANAOsDSccCDW+uLDB+kLGg94OkZoAGkwsDDAe2DOg5oPxAg03rBR88OHpBz4N8UVeHFSwma74BTW6Ge4rIRa4AAAAASUVORK5CYII="),hb.NOIMAGE}dispose(){super.dispose(),this._offcanvas=null,this._image=null}render(t){const{left:e,top:n,width:s,height:i,isGray:o=!1,alpha:r=1,src:a}=this.state;if(this.prepareIf(!this._image&&a),t.beginPath(),t.globalAlpha*=r,this._image&&this._image.complete)if(o&&this._offcanvas)t.drawImage(this._offcanvas,e,n,s,i);else try{t.drawImage(this._image,e,n,s,i)}catch(o){t.drawImage(hb.noimage,e,n,s,i)}else!this.app.isViewMode&&t.drawImage(hb.noimage,e,n,s,i)}get nature(){return lb}get hasTextProperty(){return!1}async ready(){await super.ready();const{src:t}=this.state;if(!this._image&&t){const e=this.root?.app?.loadTracker;if(e){const n=new Promise((t,e)=>{this.prepare(()=>t(),t=>e(t))});e.track(`image:${t}`,"image",t,n)}else this.prepareIf(!0)}}prepare(t,e){const{src:n,crossOrigin:s}=this.state;if(n){this._image=new Image;try{s&&(this._image.crossOrigin=s),this._image.src=this.app.url(n)||""}catch(t){return void e(t)}this._image.onload=()=>{if(this.get("isGray")){const t=this._image.width,e=this._image.height;this._offcanvas=uc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const s=function(t,e,n){let s;try{s=t.getImageData(0,0,e,n)}catch(t){return Fs("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const i=s.data;for(let t=0;t<e*n*4;t+=4){const e=i[t],n=i[t+1],o=i[t+2],r=Math.floor((e+n+o)/3);s.data[t]=r,s.data[t+1]=r,s.data[t+2]=r}return s}(n,t,e);n.putImageData(s,0,0)}t(this)},this._image.onerror=t=>{this._image&&!this._image.currentSrc&&(this._image=null),e(t)}}else t(this)}get src(){return this.get("src")}set src(t){this.set("src",t)}onchange(t,e){(t.hasOwnProperty("src")||t.hasOwnProperty("isGray"))&&(this._offcanvas=null,this._image=null,this.prepareIf(t.src))}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("image/"))return void(this.src=e[n])}}uc.register("image-view",hb);class db extends(Sy(mc(uc))){is3dish(){return!0}prerender(){}}var ub,pb,fb={},mb={},gb={};function yb(){if(pb)return mb;pb=1,Object.defineProperty(mb,"__esModule",{value:!0});var t=function(){if(ub)return gb;ub=1,Object.defineProperty(gb,"__esModule",{value:!0});var t=function(){function t(){}return t.bitsToNum=function(t){return t.reduce(function(t,e){return 2*t+e},0)},t.byteToBitArr=function(t){for(var e=[],n=7;n>=0;n--)e.push(!!(t&1<<n));return e},t.lzwDecode=function(t,e){for(var n,s,i=0,o=function(t){for(var n=0,s=0;s<t;s++)e.charCodeAt(i>>3)&1<<(7&i)&&(n|=1<<s),i++;return n},r=[],a=1<<t,c=a+1,l=t+1,h=[],d=function(){h=[],l=t+1;for(var e=0;e<a;e++)h[e]=[e];h[a]=[],h[c]=null};;)if(s=n,(n=o(l))!==a){if(n===c)break;if(n<h.length)s!==a&&h.push(h[s].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[s].concat(h[s][0]))}r.push.apply(r,h[n]),h.length===1<<l&&l<12&&l++}else d();return r},t}();return gb.SuperGifUtils=t,gb}(),e=function(){function e(t,e){this.stream=t,this.handler=e}return e.prototype.parseCT=function(t){for(var e=[],n=0;n<t;n++)e.push(this.stream.readBytes(3));return e},e.prototype.readSubBlocks=function(){var t,e;e="";do{t=this.stream.readByte(),e+=this.stream.read(t)}while(0!==t);return e},e.prototype.parseHeader=function(){var e={};if(e.sig=this.stream.read(3),e.ver=this.stream.read(3),"GIF"!==e.sig)throw new Error("Not a GIF file.");e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.gctFlag=n.shift(),e.colorRes=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.sorted=n.shift(),e.gctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.bgColor=this.stream.readByte(),e.pixelAspectRatio=this.stream.readByte(),e.gctFlag&&(e.gct=this.parseCT(1<<e.gctSize+1)),this.handler.hdr&&this.handler.hdr(e)},e.prototype.parseExt=function(e){var n=this;switch(e.label=this.stream.readByte(),e.label){case 249:e.extType="gce",function(e){n.stream.readByte();var s=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=s.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(s.splice(0,3)),e.userInput=s.shift(),e.transparencyGiven=s.shift(),e.delayTime=n.stream.readUnsigned(),e.transparencyIndex=n.stream.readByte(),e.terminator=n.stream.readByte(),n.handler.gce&&n.handler.gce(e)}(e);break;case 254:e.extType="com",function(t){t.comment=n.readSubBlocks(),n.handler.com&&n.handler.com(t)}(e);break;case 1:e.extType="pte",function(t){n.stream.readByte(),t.ptHeader=n.stream.readBytes(12),t.ptData=n.readSubBlocks(),n.handler.pte&&n.handler.pte(t)}(e);break;case 255:e.extType="app",function(t){n.stream.readByte(),t.identifier=n.stream.read(8),t.authCode=n.stream.read(3),"NETSCAPE"===t.identifier?function(t){n.stream.readByte(),t.unknown=n.stream.readByte(),t.iterations=n.stream.readUnsigned(),t.terminator=n.stream.readByte(),n.handler.app&&n.handler.app.NETSCAPE&&n.handler.app.NETSCAPE(t)}(t):function(t){t.appData=n.readSubBlocks(),n.handler.app&&n.handler.app[t.identifier]&&n.handler.app[t.identifier](t)}(t)}(e);break;default:e.extType="unknown",function(t){t.data=n.readSubBlocks(),n.handler.unknown&&n.handler.unknown(t)}(e)}},e.prototype.parseImg=function(e){e.leftPos=this.stream.readUnsigned(),e.topPos=this.stream.readUnsigned(),e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.lctFlag&&(e.lct=this.parseCT(1<<e.lctSize+1)),e.lzwMinCodeSize=this.stream.readByte();var s=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,s),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),s=t.length/e,i=function(s,i){var o=t.slice(i*e,(i+1)*e);n.splice.apply(n,[s*e,e].concat(o))},o=[0,4,2,1],r=[8,8,4,2],a=0,c=0;c<4;c++)for(var l=o[c];l<s;l+=r[c])i(l,a),a++;return n}(e.pixels,e.width)),this.handler.img&&this.handler.img(e)},e.prototype.parseBlock=function(){var t={};switch(t.sentinel=this.stream.readByte(),String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this.handler.eof&&this.handler.eof(t);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&setTimeout(this.parseBlock.bind(this),0)},e.prototype.parse=function(){this.parseHeader(),setTimeout(this.parseBlock.bind(this),0)},e}();return mb.SuperGifParser=e,mb}var bb,vb,_b={};var xb=function(){if(vb)return fb;vb=1,Object.defineProperty(fb,"__esModule",{value:!0});var t=yb(),e=function(){if(bb)return _b;bb=1,Object.defineProperty(_b,"__esModule",{value:!0});var t=function(){function t(t){this.data=t,this.position=0}return t.prototype.readByte=function(){if(this.position>=this.data.length)throw new Error("Attempted to read past end of stream.");return this.data instanceof Uint8Array?this.data[this.position++]:255&this.data.charCodeAt(this.position++)},t.prototype.readBytes=function(t){for(var e=[],n=0;n<t;n++)e.push(this.readByte());return e},t.prototype.read=function(t){for(var e="",n=0;n<t;n++)e+=String.fromCharCode(this.readByte());return e},t.prototype.readUnsigned=function(){var t=this.readBytes(2);return(t[1]<<8)+t[0]},t}();return _b.SuperGifStream=t,_b}(),n=function(){function n(t,e){var n=this;for(var s in this.gifImgElement=t,this.options={autoPlay:!0},this.loading=!1,this.ready=!1,this.transparency=null,this.delay=null,this.disposalMethod=null,this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,this.playing=!0,this.forward=!0,this.ctxScaled=!1,this.frames=[],this.frameOffsets=[],this.initialized=!1,this.currentFrameIndex=-1,this.iterationCount=0,this.stepping=!1,this.handler={hdr:this.withProgress(this.doHdr.bind(this)),gce:this.withProgress(this.doGCE.bind(this)),com:this.withProgress(this.doNothing.bind(this)),app:{NETSCAPE:this.withProgress(this.doNothing.bind(this))},img:this.withProgress(this.doImg.bind(this)),eof:function(){n.pushFrame(),n.canvas.width=n.hdr.width*n.getCanvasScale(),n.canvas.height=n.hdr.height*n.getCanvasScale(),n.playerInit(),n.loading=!1,n.ready=!0,n.loadCallback&&n.loadCallback(n.gifImgElement)}},e)this.options[s]=e[s];this.onEndListener=e.onEnd,this.loopDelay=e.loopDelay||0,this.overrideLoopMode=null!=e.loopMode?e.loopMode:"auto",this.drawWhileLoading=null==e.drawWhileLoading||e.drawWhileLoading}return n.prototype.init=function(){var t=this.gifImgElement.parentNode,e=document.createElement("div");this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"),this.tmpCanvas=document.createElement("canvas"),e.className=this.options.enclosingClass||"super-gif",e.appendChild(this.canvas),t&&(t.insertBefore(e,this.gifImgElement),t.removeChild(this.gifImgElement)),this.initialized=!0},n.prototype.loadSetup=function(t){return!this.loading&&(t&&(this.loadCallback=t),this.loading=!0,this.frames=[],this.clear(),this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,!0)},n.prototype.completeLoop=function(){this.onEndListener&&this.onEndListener(this.gifImgElement),this.iterationCount++,!1!==this.overrideLoopMode||this.iterationCount<0?this.doStep():(this.stepping=!1,this.playing=!1)},n.prototype.doStep=function(){if(this.stepping=this.playing,this.stepping){this.stepFrame(1);var t=10*this.frames[this.currentFrameIndex].delay;t||(t=100),0===this.getNextFrameNo()?(t+=this.loopDelay,setTimeout(this.completeLoop.bind(this),t)):setTimeout(this.doStep.bind(this),t)}},n.prototype.step=function(){this.stepping||setTimeout(this.doStep.bind(this),0)},n.prototype.putFrame=function(){var t;this.currentFrameIndex=parseInt(this.currentFrameIndex.toString(),10),this.currentFrameIndex>this.frames.length-1&&(this.currentFrameIndex=0),this.currentFrameIndex<0&&(this.currentFrameIndex=0),t=this.frameOffsets[this.currentFrameIndex],this.tmpCanvas.getContext("2d").putImageData(this.frames[this.currentFrameIndex].data,t.x,t.y),this.canvasContext.globalCompositeOperation="copy",this.canvasContext.drawImage(this.tmpCanvas,0,0)},n.prototype.playerInit=function(){this.loadErrorCause||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.options.autoPlay?this.step():(this.currentFrameIndex=0,this.putFrame()))},n.prototype.clear=function(){this.transparency=null,this.delay=null,this.lastDisposalMethod=this.disposalMethod,this.disposalMethod=null,this.frame=null},n.prototype.parseStream=function(e){try{new t.SuperGifParser(e,this.handler).parse()}catch(t){this.handleError("parse")}},n.prototype.setSizes=function(t,e){this.canvas.width=t*this.getCanvasScale(),this.canvas.height=e*this.getCanvasScale(),this.tmpCanvas.width=t,this.tmpCanvas.height=e,this.tmpCanvas.style.width=t+"px",this.tmpCanvas.style.height=e+"px",this.tmpCanvas.getContext("2d").setTransform(1,0,0,1,0,0)},n.prototype.drawError=function(){this.canvasContext.fillStyle="black",this.canvasContext.fillRect(0,0,this.hdr.width,this.hdr.height),this.canvasContext.strokeStyle="red",this.canvasContext.lineWidth=3,this.canvasContext.moveTo(0,0),this.canvasContext.lineTo(this.hdr.width,this.hdr.height),this.canvasContext.moveTo(0,this.hdr.height),this.canvasContext.lineTo(this.hdr.width,0),this.canvasContext.stroke()},n.prototype.handleError=function(t){this.loadErrorCause=t,this.hdr={width:this.gifImgElement.width,height:this.gifImgElement.height},this.frames=[],this.drawError()},n.prototype.doHdr=function(t){this.hdr=t,this.setSizes(this.hdr.width,this.hdr.height)},n.prototype.doGCE=function(t){this.pushFrame(),this.clear(),this.transparency=t.transparencyGiven?t.transparencyIndex:null,this.delay=t.delayTime,this.disposalMethod=t.disposalMethod},n.prototype.pushFrame=function(){this.frame&&(this.frames.push({data:this.frame.getImageData(0,0,this.hdr.width,this.hdr.height),delay:this.delay}),this.frameOffsets.push({x:0,y:0}))},n.prototype.doImg=function(t){var e=this;this.frame||(this.frame=this.tmpCanvas.getContext("2d"));var n=this.frames.length,s=t.lctFlag?t.lct:this.hdr.gct;n>0&&(3===this.lastDisposalMethod?null!==this.disposalRestoreFromIdx?this.frame.putImageData(frames[this.disposalRestoreFromIdx].data,0,0):this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height):this.disposalRestoreFromIdx=n-1,2===this.lastDisposalMethod&&this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height));var i=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(i.data[4*n+0]=s[t][0],i.data[4*n+1]=s[t][1],i.data[4*n+2]=s[t][2],i.data[4*n+3]=255)}),this.frame.putImageData(i,t.leftPos,t.topPos),this.ctxScaled||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.ctxScaled=!0),this.drawWhileLoading&&(this.canvasContext.drawImage(this.tmpCanvas,0,0),this.drawWhileLoading=this.options.autoPlay),this.lastImg=t},n.prototype.doNothing=function(){},n.prototype.withProgress=function(t){return function(e){t(e)}},n.prototype.getNextFrameNo=function(){var t=this.forward?1:-1;return(this.currentFrameIndex+t+this.frames.length)%this.frames.length},n.prototype.stepFrame=function(t){this.currentFrameIndex=this.currentFrameIndex+t,this.putFrame()},n.prototype.getCanvasScale=function(){return this.options.maxWidth&&this.hdr&&this.hdr.width>this.options.maxWidth?this.options.maxWidth/this.hdr.width:window.devicePixelRatio||1},n.prototype.play=function(){this.playing=!0,this.step()},n.prototype.pause=function(){this.playing=!1},n.prototype.isPlaying=function(){return this.playing},n.prototype.getCanvas=function(){return this.canvas},n.prototype.isLoading=function(){return this.loading},n.prototype.isReady=function(){return this.ready},n.prototype.isAutoPlay=function(){return this.options.autoPlay},n.prototype.getLength=function(){return this.frames.length},n.prototype.getCurrentFrame=function(){return this.currentFrameIndex},n.prototype.moveTo=function(t){this.currentFrameIndex=t,this.putFrame()},n.prototype.loadURL=function(t,n){var s=this;if(this.loadSetup(n)){var i=new XMLHttpRequest;i.open("GET",t,!0),"overrideMimeType"in i?i.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in i?i.responseType="arraybuffer":i.setRequestHeader("Accept-Charset","x-user-defined"),i.onloadstart=function(){s.initialized||s.init()},i.onload=function(){if(200===i.status){var t=i.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){s.parseStream(n)},0)}else s.handleError("xhr - response")},i.onerror=function(){s.handleError("xhr")},i.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return fb.SuperGif=n,fb}();const wb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"image-selector",label:"src",name:"src"},{type:"checkbox",label:"play",name:"play"}],"value-property":"src",help:"scene/component/gif-view"};class Mb extends db{async oncreate_element(t){const{src:e,play:n}=this.state;this.onchangesrc(e),this.onchangeplay(n)}buildImg(){const t=this.element;if(!t)return document.createElement("img");t.replaceChildren();const e=document.createElement("img");return e.style.width="100%",e.style.height="100%",t.appendChild(e),e}onchange(t,e){super.onchange(t,e),"src"in t&&this.onchangesrc(t.src),"play"in t&&this.onchangeplay(t.play)}setElementProperties(t){}onchangeplay(t){const e=this._superGif;e&&e.isReady()&&(t?e.play():e.pause())}onchangesrc(t){const e=this.buildImg();t||(t="data:image/gif;base64,R0lGODlhYABIAPcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/f4CAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKio+Pj5iYmKCgoKampqurq66urrCwsLGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrOzs7S0tLa2tre3t7m5ubu7u7+/v8DAwMHBwcPDw8XFxcfHx8vLy8/Pz9LS0tXV1dfX193d3eTk5Onp6fj4+Pz8/P7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v///////////////////////////////////////////////////////////////////////////////yH5BAkAAPUAIf47R2VuZXJhdGVkIGJ5IGpzZ2lmIChodHRwczovL2dpdGh1Yi5jb20vYW50aW1hdHRlcjE1L2pzZ2lmLykALAAAAABgAEgAAAj+AGcJHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmypMmR9VKqXMmypcuXMGPKnJkSIs2bOHPqZGlzp8+fQOv1DEq0KMyhRpMmRaq0KVCmTqPmhCq1qkyqLrFRSyYwGTVsVo1iZXmNa8Fk18ISHasSm1mDycCq/ck2JTWF1ObSfTjz7cFken3WFbow8M7BDA3rHOwXruKpfGXeTZg3qDVrUge7RRg3KLZjx+Q2HVyvLNy0QaMJjBaVdD2tZr2K/mmNIObRkR+n9AsYt0Pddg1WXppb8bWDx1CLLW74GcJnSl3TtDY8Zu2Et4tKl7n52eyWnxXvhl7+26jqrspbnlfIWjtz2gWPZV95neH8veU9NxZYfbfD3kFt99J6Bnmn0mQO9XfYezrVxxlmx0GUXIAM4hSeffsxBN1TFd5E4Ef3QZbfTg6CNJ5gHXJ3TEntLThiTh+KFCJNAqZU4kgAitjQTheepOBMNcZI0oQ6JpbTjSZtiNN2PZ400IxHpdiSc07G911M0iFZZYtAStnWilUeBGVLrlEZpmM0elmPlmfO8iOZXl4DZpsGEYmll2bSWWCXLwJXVY1+urhjoGEBSuiSah6K36CKtpZoo4s9CimielZq6aWYZqrpppx26umnoIZ6UkAAOw=="),e.src=t,e.setAttribute("rel:animated_src",t),e.setAttribute("rel:auto_play",String(0)),this._superGif=new xb.SuperGif(e,{autoPlay:!1}),this._superGif.init(),this.element&&Array.from(this.element.children).forEach(t=>{t.style.width="100%",t.style.height="100%"});const n=this._superGif.getCanvas();n.style.width="100%",n.style.height="100%",this._superGif.load(()=>{setTimeout(()=>{this._superGif.moveTo(0),this.play&&this._superGif.play()},100)})}ondropfile(t,e){for(let n=0;n<t.length;n++)if(/\.gif$/.test(t[n].name))return void(this.src=e[n])}get src(){return this.getState("src")}set src(t){this.set("src",t)}get play(){return this.getState("play")}set play(t){this.setState("play",t)}get nature(){return wb}get tagName(){return"div"}}uc.register("gif-view",Mb);const Sb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"attachment-selector",label:"src",name:"src",property:{category:"audio"}},{type:"checkbox",label:"started",name:"started"},{type:"checkbox",label:"loop",name:"loop"}],"value-property":"src",help:"scene/component/audio"};class Ab extends(mc(pc)){static get image(){return Ab.IMAGE||(Ab.IMAGE=new Image,Ab.IMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAMAAAC3Ycb+AAAAP1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACzJYIvAAAAFHRSTlMA8BAwgNBgQKB/wCBwUJDg37CvXyUlBK8AABFYSURBVHja7NsBkqIwFIThTiAQgyBq3/+sm6p1tnamZkaTMhJJf1f4S/JeEIiIiIiIiIiIiIiIiEhD7Hg4BH84TpAKjJ4f3NFCtjVd+InXz2RTs+FXlxGylYHfcVfIJmb+YFWSLUyGVJKKBJJKUo+Rd6w63l/qzLuCkryO5fe0l2xk5mMWbe+v0fNBRqf7S3je6CipQ2ACr+dWcYEpzBFS1plpguatsnomMgdIQSOTuQ5SjmE6/UgK8szgdJIUM/FG41YlFmYJ2kkKsY5ZzAwBurHDk3WGeRY0bvYrGa1+rqNI22f7dS32ZnUK1GMr0eSK3mEc9dhKMxp+ZTo8kT2emOXS5LQ1kCxbJBocSd2k5PaIjMVzjWcdJPk9ooBnmzx1t5XbIxqBKpJ4NGTgzwKiGpK4do72gb+ZUMIYtCPm9WCPMsYTE5k2hq2ZvzujlCE1iRmwf3dvmRyKsT0T7b9I7HEPCpqCiqT2IIqaT1pI0noQZdlFC8l/PbYPAnRORT56VBEE6FXkb49agmByKhJ71BME6FsvEntUFQTdqekisUdlQWCXhovEHtUFAWbTapHYo8YgmFybO3vsUWcQYGmxSOxRbRAMprkisUfFQVKmrX18sxt7VB0ENjT1xir2qDxIwkFi3v89e+xRfxAMzfzzIfZ4hyAYDR9zwVuLPd4jCDrTwoLYGb5LEFi3/+E3rweR6urX20c/Fvls2Pvwm9mDSGIPhv8YPyGf3/eo9Ye7O8B2FIShAAooakEttex/rbODad5/yTHIAjqn505IQPv+Xz06dz+4VXORHEZcgAcB8updM8F6e25jBzwIkE07l+x8amMnPDp6nsNJ+BoZ7Q6F8egqAda9VEuRNlZjBzwYkMskdXR73okd8GBAJiKYjBcZKKqG9OiKDbgdfxJ5VhsBPDiQZhaouD3p4hfw4EAmwxisz3MSHwAPEmQ1TB1N+SmXWoAHC7JbZsWl/IxLLcCDBplNo3lrfMLsmwAPGmShAxX5/1vOEzjEz3iyfQ/hI36W4TctsUesOAifPdrQg8M++KYl95iCBkjI1r8634betBAPHZDTPFAmD3zLiHgogVTziMsahz0eIh5aIGHGRSJ2mFtHPR4iHhQIP2UvWGMf8wk74qEIEib7rLjPiBfxiAcCwp8V+Nae3uMdRhAPDIR/J5f/Q2DTcC+hIB7qIGEq3Ti9bx+sryMeAAgS70OK8G2kBD8L8QBAoLWU3g3vUVIc6D0txAMAsY+4jBWowXHO64gHBGKfYJ2T5qY1BxcL98BB+PQ+XiS9xxh9EQ8ChA6C5UXWIUoE9MBB8LVHQoS7ib8/dRn3sAcJ6bQRSdH96RDxIEH4QEX+AHF4LxHEAwUh12xyr1V8lwjiQYDYF8kuf1jluUQQDwrEvkhW8Wc6LhHUgwfhi4QPlHm7LRHawx4kpE191Dq8lgjhAYDQa1cftYrPEiE8OJDb40uqyzdQCA8WhAzL4G/PT4c3WrgHD2IfllGl53V37zsgHg5ApPNvVvq4Fn4spx4oiH1W3CwtEV+PDhEPJyBSkVX4aa7emkM83ICEKWpGM7wdvYCCeDgCEYpcwhLxczhEPFyBCEUWnRL5T6X59SBASBF+9l28TL5F7uEORCZyCUvEx+S7yT0cgoRVb9JaXLR1qUdfgksQ0fTbgmhFB20d8HAKEha14+F8f1sHPNyCiL6EqK+n20/rgIdjkFC0Ho1s6Gndvcc9ICkr/ey8/rHO6vp9KawL8DAFOV6l9Fyub7IbflsCag1qRfVsXWvxHjxIejU+BHZV6uvHD1XiEb++Bw8i+dNd+Wv0eCQmhcPhRPwUUt2DB5G1sfa1aeyzAuyJj9x2HjyIdKzIKw5SI14ieFtvo3kIQERj3lVhkUOnRD7AnjV5369QkAOJZeCH+Jh41xOLs73dQwAifY6dpxCCbjTDzLf1Bm1Y93tAIDOWXcLPvrHyr2hVoEAceEAgDQzB4jetk0/c2OXRHB48EJCpa4dgpYh2ETxtrshz7zx4ICCzfuTSDn8p/EOS9OTjwgMB+cABP3yWYuOPIofs33LigYCULlpZNXJppVU30Vf14kGAUCLijf1D71lN9FW9eFiA9KgZ8FPpPUsSnufGA+8hvAg2Kpz0nrX//qp+PIgpC3i6xJRITOye9fn1VT15ICCrVlQG5rywo0H8x965bVkNwmCYQ2kR6Gmb939WXV65dFnI/tPdjPBfO7XMN4EkTUJtqZp4sCJ1+8jwkhMu0KpMxFXFA8hlVfQSMxGH5mDK1VKV8QCyvTVtUiYyo7V358VStfGoAEFMhGYhEwloxZy9WKo2Hjwg5iSOvFDXeUYd33+PuVfHgwnEBWLocDJp+IIa2fyvperjwQRiXCKGosyXqoA+YfsIELuYu4HAt+msMknfDK4jfQJIzOZ2IPAQWJtFOhQKivR2IDZ6Awis7V0iLxqBI7uEZo19dakTogLSwKvf8yk8Jq6CGK0GKvWlatG7b7kkUU/Lo1gdXWn7/4E0j0qeJDpqN/ABqQcgJgdqURb4chjQktIugDS6wFFiz3JgaJj7AGJmholAe9YKhoZLJ0Ca6smjwJ4VwVN96gVIE5GM71kHaGKxGyAtRDaB2NBhLVmpHyANRKzDO28W7FS3HQFpaIWa8TrfCXQwegJSL5k+8M9UJ+pm9QTEnCIZrR0MDQeQ9ua0iCcYQaBTV0CqNXQW/yiyYG7W1heQanPaCkciBXuH1BkQJzHcDQxmpgGkPatl4WkbCXO/bW9AqlNg4H0PPMi6A1IxkQmOZ8D0ousNSMVEEuyreTAQ6Q7IRJeCX2YZQHhv6SrBOmpkM+YUzN0BqSRQCupmTeCP9wdkhiOREwtEzgGEsWcF9BhK9R8fQDiN7A8DiR0CKXQlj/q9IM8OgXjIzcKBlAHkD6FulgNzJwPIHwpo8mQAkX3LiPq9dKUMAQk9AqmcqmjuBAJCPQIpA4guIAsKJA0gnwNy3A4kDyBIHCEPxAwgf8gPILqA5AFEF5CxZX0lIHYc6rqADLf380BmFMgxgIzUyf8MJKLTRelKHgKy9wgkjfS7LiA0gKgC8vQn3HUA4RQ5LKPIAQciWbqIEg0YkLNDIHYUyqkCsmKN5vg3+W0AYTRATaPY+uu1IwS6UMGAlO6AFPjSCQMStaNh53cdcPG7Hx1Uupo+rx+Bltn1BuTAj5BptEV/bHAAwbnJMICwRmtUDOSEA8s4Rmtw3nITGD6TwUNoG0Ca7xi2YKSPj2eKXQFxQWKA2QbGMWEMMGseOb7C7T47uJS1JyAzVbTjqZdU3zbHzMXWS+qp4Fgn8Ahy/QCRGqQcwU1vGnN7fylboWn8Bzg//hyjxltvdcl45bwFfYKzFyBy11UU9BnjuoqfWizVlQXulpzBTNbaB5Aid+VRrkBFB630AMS9BC8FK2ggE7u/FGy1kvfcB9TKQufX5uUXNWl3EjvWCi4k/u9A3Ddq1CpTIQGe6VN1qd8ArcvDQNw3S41Kn6qQmOq5e7pRr+8fAYLiIJtFrrvYRMYL0q06vj8EZLXUriJzRY8H1xEagOCK7gkghRg6RQYO0I6aWPwIEAru80AiMWSdzAeuDXUKyr+WqpAID8hMHC1Ct8F4mUsQ6W8pJMICki0JHCBczAFdBl38G3VE6ErQhhWlih4LWrCSLpaqjggHiGe9mVjRY0YPoelyqcqIcIDEe97rqJFFH7FcLlUZEQ6Qg5plvZiBFNhtri1VFREGEC/Eg4nZoU5vqi1VFREGkIXDQ8xAIhzoT/WlKiLCAFIYPOQMxOPdjfWlKiLCADJRm3YGj+pDE2xktmmpaogwgMz8d8GrumZ4xzpbvinqISJ+hiTWm7wEqoJdI9JEV9JChAEkS3xCZzKecLcgN6YwlRBhAGmweTsblg6qKMM7Vmh321UQ4QAp1VfwhqVJIh+Wm03W0qV0EOEAybXtivkCmWrKeH2EZ/xBaSBCV2L9Re+LYSqJJIxDu1ew07U0EGEBcTtmHty4JuPtQhvLh1BAhK7Uvvq0GK484QZST0GvvFDqeSJ1IA0r2mfDljvqBoJ//rVsq7yZCA6kXgVkJ2f4ijIGMjOfMVsCBBORB2Jy+sM6ijNvaBUqmw/cStZ8EiKciHwp6Rp++88qmxXQeTUxDiJWJ9wSISvBicgXW+dypn1PqWTznlwgwdZdfiLHr5OELEAEASKvJFRE5JCPKbh8OxHdQKJU0crEzRXrJ/IEkFms6tGyrUw9kQeALFRXvK2iSzsRAAi6BLxM+60xdsqJAEBuXMAMxDLVp+gmAgC57/UT4qvVj3TVRCAgSAYL91aXtyNLzUQAIFhAiP8m0/NHOp+ILiBtPFKrs6bgSOcT0QTEB8nO3QR1yKslggKRf+m11UB0HOl8IlqAeCvauXuo8HnfIqIDyCw6G8XMcGiplMingMzCnbuHFp/3LSLPA4nUpqm5YkWNzwsQeQxIDsKjH5wVSU5qJPIJIIt4jjpqNBAekQeBfJOeHWS81FQoo4/I7UDcS3wUh0liTzLqiEgDqddx4ZHDrNZAACIAEMw88HPYWb0GAhABgEDmgf9Vb5oNBCByOxD3uqWYbCHVBgIQuRlIsbfwMEG5gQBE7gSyHMDsOayrxJvHBRC5B0hOxJH1nK4SlUE6QOR+IG6ju3iYQEqDdIDIzUDyZu/jMRHpS/OiRG4FkiPRfTw8kbrvIAJEACAIDpyHC1/GQHhEbgKSXwTyqIeEur6kixEBgABHOTr7YSX1MSFAhA0E307wUU76Y0KACAsI/tvCRzkF+iIuL0AEAYLbR2QOfvhKJ/obRESBxNt5rPSFXN4f7dyNdqMgEIbhAXWwJErT/e7/Wreb5HTT07QVgWSAeW5g7b4n8qOSUCRPEId4HP93SXp5dDNGRJFcQTxihSH+NW1Bb1cXKpIryJAwnG/zhl8ZcSP6jiKZghwRaaWLnP/AkcSKKJIniEcUs8QfjFLdEmRvkSxB4lfn0QN6DY+lshQpHiT96Dlr6r5hxRUpHST9ZEY71X7DOmOZQVZLsd5Q8wzrPxYYJDiKNqOBG1ZCkZKzrNXu6lHvkjChSFqQsdTPg45ApXtYaUXKr9TNuPcvqO2pVMkitFXAL2a79/qr3HQvVSTXUtofCl79RDXh5CDpw3pwu6+9kRlvtiI5VtPhmHLltT4EKVQkfb8pcOHrXqk6nBAksUjgpKtuYsskaxGKYT0+84uYgziE4YQgMdx0m8PRfis2MbL33PMXoVjD6PEunI4HSjDjStiJP08vQk9hZzQ7oH/geoLYCUBDW4rf4FqCDFt7THUO6B+4jiDn2XNTW7zf4hqCMND4BOsGyw+yAmh0x+QeFh7EeqD5Ce8nLDrI8NpbDyIWHIQNruo4GyAPlhrEzuixBxHLDDJMnfYgYolBricHNfjIdgMWF+Qyu+pkgX4HCwuymL57ELGkIHZG7z2IWE6Q5VV7vGMhQewbtMcZiwhyHj26ne9+xs8PcvDQHnFFqCD7Au0RW4TK+fOKqw4eoOcqYqgU53HR3/5uShFPCfKey9hFDyJO/vAi7RDZnp7X5igyUH72xSDW1E2Pn4tMRCQgR8vLwbgii4gcmLvqQcSPGtIPX3M08wn6I4qYQ94cM/Yw9Xxhmw+X/59wHrtMlX1AmIkzdyaaAnLg1Nnw8WGYSk40X/BOh4+El6LMSBnN2Cd0tPq4w/LJXGrMbCX06PZ2dcM65yzlNertShSHf3SzRAyPM332IcSAHUKPi8EHmXU0l8Uglmni0yipDoi16s+jJKejhywLooz68yiMEcHr2qM4h81CJ++VPJfTu5UwBpv4Pp9DJSi6MJx0bvUwiw4ewgT8zNR0LHUL+OccOpY/3ElzyGKD5pBlMJpDlsOkMythRoNbXh95PJsdA67MrMtAEYbjeDqNo+7oKqWUUkoppZRSSimllFJKFfMXp4vmSjB8n6sAAAAASUVORK5CYII="),Ab.IMAGE}dispose(){super.dispose(),this.started=!1,delete this._audio}async ready(){super.ready(),this._audio=new Audio;const{src:t="",loop:e=!1,started:n=!1}=this.state;if(t){const e=this.root?.app?.loadTracker;if(e){const n=new Promise((e,n)=>{this._audio.addEventListener("canplay",()=>e(),{once:!0}),this._audio.addEventListener("error",()=>n(new Error(`Audio load failed: ${t}`)),{once:!0})});e.track(`audio:${t}`,"audio",t,n)}}this._audio.addEventListener("canplay",()=>{this.started&&this._audio.play()}),this.onchangeSrc(t),this.onchangeLoop(e),this.onchangeStarted(n)}render(t){const{left:e,top:n,width:s,height:i}=this.state;t.beginPath(),this.drawImage(t,Ab.image,e,n,s,i)}get nature(){return Sb}get hasTextProperty(){return!1}get src(){return this.get("src")}set src(t){this.set("src",t)}get started(){return!!this.get("started")}set started(t){this.set("started",t)}start(){this._audio&&(this._audio.classList.add("active"),this._audio.play())}pause(){this._audio&&(this._audio.classList.remove("active"),this._audio.pause())}onchangeSrc(t){try{"data"!==String(t).substring(0,4)?this._audio.crossOrigin="use-credentials":this._audio.crossOrigin=null,this._audio.src="string"==typeof t?this.app.url(t):t}catch(t){return void Fs(t)}}onchangeStarted(t){const e=this._audio;t?4==e.readyState&&e.play():e.pause()}onchangeLoop(t){this._audio.loop=t}onchange(t,e){"src"in t&&this.onchangeSrc(t.src),"started"in t&&this.onchangeStarted(t.started),"loop"in t&&this.onchangeLoop(t.loop)}ondblclick(t){this.started=!this.started}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("audio/"))return void(this.src=e[n])}}uc.register("audio",Ab);class kb extends(mc(uc)){is3dish(){return!0}}uc.register("text",kb);const Eb=["refid","left","top","width","height","rotation","animation","zPos"];class Tb extends Cy{isGroup(){return!0}is3dish(){return!0}get showMoveHandle(){return!1}get(t){return this._model[t]}set(t,e){if("string"==typeof t)return this.set({[t]:e});const n=Eb.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{});return super.set(n,void 0)}capture(t,e,n){const s=super.capture(t,e,n);if(s!==this)return s}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,s=t.height/e.height;this.path=this.path.map(i=>({x:t.left+(i.x-e.left)*n,y:t.top+(i.y-e.top)*s})),this.components&&this.components.forEach(t=>{if(t.mutable)t.mutatePath(null,function(t){return t.map(function(t){return{x:t.x*n,y:t.y*s}})});else{const e=t.bounds,i=t.center,o={x:i.x*(1-n),y:i.y*(1-s)},r=e.width*(1-n),a=e.height*(1-s),c=-(o.x-r/2),l=-(o.y-a/2);t.bounds={left:e.left+c,top:e.top+l,width:e.width*n,height:e.height*s}}})}get focusible(){return!1}get bounds(){return super.bounds}get hasTextProperty(){return!1}isIdentifiable(){return!1}calculateBounds(){this.clearCache(),this.__MUTATING__=!0,this.mutateBounds(function(t){const e=uc.union(this.components.map(t=>t.bounds));return this.components.forEach(t=>{const n=t.bounds;t.bounds={left:n.left-e.left,top:n.top-e.top,width:n.width,height:n.height}}),{left:t.left+e.left,top:t.top+e.top,width:e.width,height:e.height}},this),this.__MUTATING__=!1,this.parent.isGroup()&&this.parent.calculateBounds?.()}render(t){}postrender(t){const{top:e,left:n}=this.state;t.translate(n,e),this.layout.drawables(this).forEach(e=>{e.draw(t)}),t.translate(-n,-e)}}uc.memoize(Tb.prototype,"bounds",!0),uc.register("group",Tb);const Cb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"id-input",label:"ref",name:"ref"},{type:"select",label:"fit",name:"fit",property:{options:["","both","ratio"]}}],"value-property":"ref",help:"scene/component/local-ref"};class Ob extends(mc(pc)){get ref(){const t=this.getState("ref");return t&&"string"==typeof t?this.root.findById?.(t):null}set ref(t){this.setState("ref",t)}get refScale(){const t=this.ref;if(!t)return{x:1,y:1};const e=t.bounds,n=this.bounds,s=n.width/e.width,i=n.height/e.height;return"both"===this.model.fit?{x:s,y:i}:{x:Math.min(s,i),y:Math.min(s,i)}}draw(t){this._drawing||(this._drawing=!0,super.draw(t),this._drawing=!1)}prerender(t){if(super.prerender(t),this.ref){const e=this.ref.center,n=this.center,s=this.refScale;t.translate(n.x,n.y),t.scale(s.x,s.y),t.translate(-e.x,-e.y)}}postrender(t){if(this.ref)return this.ref.postrender(t);super.postrender(t)}render(t){if(this.ref)return this.ref.render(t);const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),t.rect(e,n,s,i)}get nature(){return Cb}get hasTextProperty(){return!1}}uc.memoize(Ob.prototype,"ref",!1),uc.memoize(Ob.prototype,"refScale",!1),uc.register("local-ref",Ob);class Pb extends(Sy(Kl)){render(t){}is3dish(){return!0}get layout(){return xc.get(this.get("layout"))||wc}}const Ib={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"board-selector",label:"scene-number",name:"ref",placeholder:"SCENE-1"},{type:"number",label:"round",name:"round",property:{min:0}},{type:"select",label:"fit",name:"fit",property:{options:["","both","ratio","width","height","none"]}},{type:"select",label:"mode",name:"mode",property:{options:["view","interaction"]}}],"value-property":"ref",help:"scene/component/global-ref"};class Db extends Pb{dispose(){this._releaseRef(),super.dispose()}get nature(){return Ib}get hasTextProperty(){return!1}get tagName(){return"div"}setElementProperties(t){const{mode:e="view",round:n=0}=this.state;t.style.pointerEvents="view"==e?"none":"inherit",t.style.borderRadius=n+"px"}async ready(){super.ready(),this.fetchRef()}reposition(){if(!this.element)return;super.reposition();const t=this._element_bounds,{offsetWidth:e,offsetHeight:n}=this.element;if(this._element_bounds={offsetWidth:e,offsetHeight:n},(!t||t.offsetWidth!=e||t.offsetHeight!=n)&&this.ref&&this.root.target_element){const{fit:t="ratio"}=this.state;this.ref.fit(t)}}async fetchRef(){this._releaseRef();const{ref:t,fit:e="ratio"}=this.state;if(!t)return;const n=this.app.refProvider;if(n&&t){const s=(async()=>{this.__ref=await n.get(t,!0),this.__ref.target=this.element,this.__ref.fit(e),this.__ref.data=this.data})();this.root?.app?.loadTracker?.track(`ref:${t}`,"ref-board",t,s);try{await s}catch(t){Fs(t)}}}get ref(){return this.__ref}set ref(t){this.setState("ref",t)}_releaseRef(){this.__ref&&this.__ref.release&&this.__ref.release(),delete this.__ref}onchange(t,e,n){super.onchange(t,e),"ref"in t&&this.fetchRef(),"fit"in t&&this.ref&&requestAnimationFrame(()=>{const{fit:t}=this.state;this.ref.fit(t)}),"data"in t&&this.ref&&requestAnimationFrame(()=>{this.ref.data=t.data})}}uc.register("global-ref",Db);const zb="center-middle",Rb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"board-selector",label:"board",name:"board"},{type:"checkbox",label:"modal",name:"modal"},{type:"checkbox",label:"closable",name:"closable"},{type:"checkbox",label:"draggable",name:"draggable"},{type:"checkbox",label:"minimizable",name:"minimizable"},{type:"checkbox",label:"show",name:"show"},{type:"select",label:"popup-position",name:"popupPosition",property:{options:["static","absolute"]}},{type:"select",label:"popup-origin",name:"origin",property:{options:["left-top","center-top","right-top","left-middle",zb,"right-middle","left-bottom","center-bottom","right-bottom","auto"]}},{type:"string",label:"title",name:"text"},{type:"data",label:"value",name:"value"},{type:"string",label:"container-ref",name:"containerRef",placeholder:"PopupContainer id (same board)"},{type:"textarea",label:"html-template",name:"htmlTemplate",property:{language:"html"}},{type:"string",label:"anchor-ref",name:"anchorRef",placeholder:"component id (3D-tracked anchor)"},{type:"select",label:"anchor-pin",name:"anchorPin",property:{options:[{display:"Top",value:"top"},{display:"Center",value:"center"},{display:"Bottom",value:"bottom"}]}},{type:"number",label:"anchor-offset-x",name:"anchorOffsetX"},{type:"number",label:"anchor-offset-y",name:"anchorOffsetY"},{type:"number",label:"anchor-offset-z",name:"anchorOffsetZ"},{type:"checkbox",label:"constant-size",name:"constantSize"},{type:"checkbox",label:"tether",name:"tether"},{type:"select",label:"off-screen",name:"offScreen",property:{options:[{display:"Hide",value:"hide"},{display:"Edge-pin",value:"edge-pin"},{display:"Keep last",value:"keep-last"}]}}],help:"scene/component/popup"};class jb extends(mc(pc)){static get image(){return jb._image||(jb._image=new Image,jb._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAABGCAMAAABG8BK2AAADJmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNy4xLWMwMDAgNzkuZGFiYWNiYiwgMjAyMS8wNC8xNC0wMDozOTo0NCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDIzLjAgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RkM4QzQxNUMzMzBEMTFFQ0JEMzZDMDUwQUI4MEI3QTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RkM4QzQxNUQzMzBEMTFFQ0JEMzZDMDUwQUI4MEI3QTAiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENjlENTQ3RjMzMDkxMUVDQkQzNkMwNTBBQjgwQjdBMCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENjlENTQ4MDMzMDkxMUVDQkQzNkMwNTBBQjgwQjdBMCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PsiUYSQAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAA51BMVEVHcEwzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzOguTm2AAAATHRSTlMARhB73r9B7YLrsqdE+0cq9Avzeg31eQx4aQ+Ks6aUd5DsYKixEX1w8vyT2VjoZ3YezY/cCEDvl+QTvRwJ0ifwK/5T/aw6+IuFuCImAcS6MQAAAeJJREFUWMPt2FlX2zAQhuHJYmOSFhIggbC0QNn3rS1dKXSH9///Hi58CJLxKIpEWi6YO8c5z4lG/nxGEXmu/1OVLGnhrFaSVQYg1SZetTTvUibqeFZ9QlfmvRWoV1VmCaCRzroXPpsuAjTV7gLUfPahBqD1OQMW/fazAWTKvQRI/ZgUSJR7U8CM/dHZ+/2VcatWdvdEZAaYUhiAwkerJXt0rnzXwdRKmHfDM0fHD5kxjTFyVLzVfvvirn7+cDJWjhy7c7XlYuwc6Urvu2tRhRypyhwAf1sKY+TIxfQA+H39q5wxc+RgVrcBduTmZTlj5khnDgH4IzKpMGaOVCbvyyvRGTNHGtPrKypjXirM5jb910I4k69oQeKY+77EMAcALEsck/+W6f71tyCma/ZFROTrJVwMy7wmf3bv6/MX+Dgkkysblvxps/dhOKZb6IvrTakzXXuPApnpYneDGOeKvJlaSXcDmA7AicQyW84VeTOnY+NdiWcG1uiZksFEHdyAlsJEjEkmkwGNsKHNZCJGSKtVTYC1tO022mnjwUBrMdXg8dreuOBhv7D/62/8lGZ1wLxXyZKOm+iUHIQintyny0TkaATHjYgcjeAoFpEje9R/nGPqIx2aw3NU9odCQI6e6x/VLY32cKQXVBnkAAAAAElFTkSuQmCC"),jb._image}async ready(){await super.ready(),this.show&&this.onchangeShow(!0)}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,jb.image,e,n,s,i)}onchange(t,e){"value"in t?this.show?this.onchangeShow(!0):this.show=!0:"show"in t&&this.onchangeShow(this.show)}onchangeShow(t){if(this.app.isEditMode)return;(this.getState("board")||this.getState("containerRef")||this.getState("htmlTemplate"))&&(t?this.openPopup(this.value):this.hidePopup())}openPopup(t,e){if(this.app.isEditMode)return;const n=this.getState("anchorRef"),s=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;Tp.show(this,this.getState("board"),{origin:this.getState("origin")||zb,modal:this.getState("modal"),closable:this.getState("closable")||!1,draggable:this.getState("draggable")||!1,minimizable:this.getState("minimizable")||!1,popupPosition:this.getState("popupPosition"),title:this.text,data:t||this.value,containerRef:this.getState("containerRef"),htmlTemplate:this.getState("htmlTemplate"),anchor:s,anchorPin:this.getState("anchorPin")||"top",anchorOffsetX:this.getState("anchorOffsetX")??0,anchorOffsetY:this.getState("anchorOffsetY")??0,anchorOffsetZ:this.getState("anchorOffsetZ")??0,constantSize:this.getState("constantSize")??!0,tether:this.getState("tether")??!1,offScreen:this.getState("offScreen")||"hide",...e})}hidePopup(){Tp.hide(this)}get board(){return this.getState("board")}set board(t){this.set("board",t)}get show(){return this.getState("show")}set show(t){this.setState("show",t)}get started(){return this.getState("show")}set started(t){this.setState("show",t)}get value(){return this.getState("value")}set value(t){this.setState("value",t)}get hasTextProperty(){return!1}get nature(){return Rb}}uc.register("popup",jb);const $b={mutable:!1,resizable:!0,rotatable:!1,properties:[{type:"layout",label:"layout",name:"layoutOption"},{type:"checkbox",label:"constant-size",name:"constantSize"},{type:"checkbox",label:"billboard",name:"billboard"},{type:"checkbox",label:"tether",name:"tether"},{type:"select",label:"off-screen",name:"offScreen",property:{options:[{display:"Hide",value:"hide"},{display:"Edge-pin",value:"edge-pin"},{display:"Keep last",value:"keep-last"}]}}],help:"scene/component/popup-container"};class Lb extends Cy{get nature(){return $b}isPopupContainer(){return!0}}uc.register("popup-container",Lb);class Fb extends uc{render(t){const{path:e=[]}=this.state;if(!(e.length<=1)){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let n=1;n<e.length;n++)t.lineTo(e[n].x,e[n].y);t.closePath(),this.drawStroke(t,void 0)}}get path(){return this.model.path}set path(t){this.set("path",t)}contains(t,e){const n=this.state.path;let s=!1;return n.forEach((i,o)=>{const r=(o+n.length+1)%n.length,a=i.x,c=i.y,l=n[r].x,h=n[r].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}}uc.register("path",Fb);const Nb={mutable:!0,resizable:!1,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/triangle"};class Hb extends pc{is3dish(){return!0}contains(t,e){const{x1:n,y1:s,x2:i,y2:o,x3:r,y3:a}=this.state,c=[n,s,i,o,r,a];let l=!1;for(let n=0;n<c.length;n+=2){const s=(n+2)%c.length,i=c[n],o=c[n+1],r=c[s+1];o>e!=r>e&&t<(c[s]-i)*(e-o)/(r-o)+i&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:s,x3:i,y3:o}=this.state;return[{x:t,y:e},{x:n,y:s},{x:i,y:o}]}set path(t){this.set({x1:t[0].x,y1:t[0].y,x2:t[1].x,y2:t[1].y,x3:t[2].x,y3:t[2].y})}get nature(){return Nb}}uc.memoize(Hb.prototype,"path",!1),uc.register("triangle",Hb);const Bb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"}],help:"scene/component/donut"},Gb={ondragmove:function(t,e,n){let{cx:s,rx:i}=n.model;i=Math.abs(i);let o=(n.fromParent(t.x,t.y).x-s)/i*100;o=o>=100||o<=-100?100:Math.abs(o),n.set({ratio:o})}};class Ub extends Vy{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:s,rx:i,ry:o,startAngle:r,endAngle:a,anticlockwise:c}=this.state;i=Math.abs(i),o=Math.abs(o),t.beginPath(),t.ellipse(n,s,i,o,0,r||0,a||2*Math.PI,c),t.moveTo(n+i/100*e,s),t.ellipse(n,s,i/100*e,o/100*e,0,r||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:s,rx:i,ry:o,ratio:r}=this.state;i=Math.abs(i),o=Math.abs(o);const a=(t-n)/(2*i-.5),c=(e-s)/(2*o-.5),l=(t-n)/(i/100*r*2-.5),h=(e-s)/(o/100*r*2-.5);let d=!1;return a*a+c*c<.25&&l*l+h*h>.25&&(d=!d),d}get controls(){let{cx:t,cy:e,rx:n,ratio:s}=this.state;return n=Math.abs(n),[{x:t+n/100*s,y:e,handler:Gb}]}get nature(){return Bb}}uc.memoize(Ub.prototype,"controls",!1),uc.register("donut",Ub);const Vb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"},{type:"number",label:"wing",name:"wing",property:"wing"}],help:"scene/component/star"},Wb={ondragmove:function(t,e,n){const{cy:s,ry:i}=n.model;let o=(n.fromParent(t.x,t.y).y-s)/i*100+100;o>=100?o=100:o<=0&&(o=0),n.set({ratio:o})}};class Yb extends Vy{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:s,cy:i,rx:o,ry:r}=this.state;if(n<3)return;const a=1.5707963267948966,c=2*Math.PI/n,l=o-e/100*o,h=r-e/100*r;t.save(),t.beginPath(),t.translate(s,i),t.moveTo(o*Math.cos(-a),r*Math.sin(-a)),t.lineTo((o-l)*(Math.cos(c-a)+Math.cos(0-a))/2,(r-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let e=1;e<n;e++)t.lineTo(o*Math.cos(c*e-a),r*Math.sin(c*e-a)),t.lineTo((o-l)*(Math.cos(c*(e+1)-a)+Math.cos(c*e-a))/2,(r-h)*(Math.sin(c*(e+1)-a)+Math.sin(c*e-a))/2);t.closePath(),t.restore()}get controls(){const{cx:t,cy:e,ry:n,ratio:s}=this.state;return[{x:t,y:e-n+n*(s/100),handler:Wb}]}get nature(){return Vb}}uc.memoize(Yb.prototype,"controls",!1),uc.register("star",Yb);const qb={mutable:!1,resizable:!1,rotatable:!1,properties:[]};class Xb extends(xm(pc)){is3dish(){return!1}isDescendible(){return!1}render(t){const{cx:e,cy:n,anticlockwise:s}=this.state,i=this.app?.scale||1;t.beginPath(),t.scale(1/i,1/i),t.ellipse(e,n,Math.abs(Xb.RADIUS),Math.abs(Xb.RADIUS),0,0,2*Math.PI,s),t.scale(i,i),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-Xb.RADIUS,y:e-Xb.RADIUS},{x:t+Xb.RADIUS,y:e-Xb.RADIUS},{x:t+Xb.RADIUS,y:e+Xb.RADIUS},{x:t-Xb.RADIUS,y:e+Xb.RADIUS}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s}=this.state,i=(t-n)/(2*Xb.RADIUS-.5),o=(e-s)/(2*Xb.RADIUS-.5);return i*i+o*o<.25}outline(t){const{cx:e,cy:n}=this.state;return this.toScene(e,n)}get nature(){return qb}}Xb.RADIUS=5,uc.memoize(Xb.prototype,"path",!1),uc.register("node",Xb);class Kb extends Du{getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds,n=this.component.state.depth||.5*Math.min(t,e),s=.15*Math.min(t,e,n),i=new _.RoundedBoxGeometry(1,1,1,4,s/Math.min(t,e,n));i.scale(t,n,e),this.object3d.geometry=i,this.object3d.material=new w.MeshStandardMaterial({color:"#5090d0",transparent:!0,opacity:.35,roughness:.6,metalness:.1,side:w.FrontSide,depthWrite:!1}),this.object3d.visible=!!this.component.app?.isEditMode}updateAlpha(){const t=this.object3d.material;t&&(t.opacity=this.component.app?.isEditMode?.35:0)}updateHidden(){this.object3d.visible=!!this.component.app?.isEditMode&&!this.component.state.hidden}updateDimension(){const{width:t,height:e}=this.component.bounds,n=this.component.state.depth||.5*Math.min(t,e);this.object3d.geometry.computeBoundingBox();const s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,o=s.max.y-s.min.y,r=s.max.z-s.min.z;this.setDimensionScale(t/i,n/o,e/r)}}updateFillStyle(){}updateStrokeStyle(){}updateText(){}clear(){return bu(this.object3d),super.clear()}}const Jb="data:image/svg+xml;base64,"+btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="#5090d0">\n <path d="M32 20a12 12 0 1 0 0 24 12 12 0 0 0 0-24zm0 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12z"/>\n <path d="M55.4 27.2l-3.6-.6c-.4-1.2-.8-2.4-1.4-3.4l2.2-3c.6-.8.4-2-.2-2.6l-3-3c-.8-.6-1.8-.8-2.6-.2l-3 2.2c-1.2-.6-2.2-1-3.4-1.4l-.6-3.6c-.2-1-1-1.6-2-1.6h-4.2c-1 0-1.8.6-2 1.6l-.6 3.6c-1.2.4-2.4.8-3.4 1.4l-3-2.2c-.8-.6-2-.4-2.6.2l-3 3c-.6.8-.8 1.8-.2 2.6l2.2 3c-.6 1.2-1 2.2-1.4 3.4l-3.6.6c-1 .2-1.6 1-1.6 2v4.2c0 1 .6 1.8 1.6 2l3.6.6c.4 1.2.8 2.4 1.4 3.4l-2.2 3c-.6.8-.4 2 .2 2.6l3 3c.8.6 1.8.8 2.6.2l3-2.2c1.2.6 2.2 1 3.4 1.4l.6 3.6c.2 1 1 1.6 2 1.6h4.2c1 0 1.8-.6 2-1.6l.6-3.6c1.2-.4 2.4-.8 3.4-1.4l3 2.2c.8.6 2 .4 2.6-.2l3-3c.6-.8.8-1.8.2-2.6l-2.2-3c.6-1.2 1-2.2 1.4-3.4l3.6-.6c1-.2 1.6-1 1.6-2v-4.2c0-1-.6-1.8-1.6-2z"/>\n</svg>');class Qb extends(mc(uc)){static get icon(){return Qb._defaultIcon||(Qb._defaultIcon=new Image,Qb._defaultIcon.src=Jb),Qb._defaultIcon}get serviceName(){}get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Kb(this)}render(t){if(this.app?.isViewMode)return;const{left:e,top:n,width:s,height:i}=this.bounds,o=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,o,e,n,s,i),t.globalAlpha=1}added(t){super.added(t);const e=this.serviceName;e&&(this._registeredRoot=this.root,this._registeredRoot?.registerService?.(e,this))}removed(t){const e=this.serviceName;e&&this._registeredRoot&&(this._registeredRoot.unregisterService?.(e),this._registeredRoot=void 0),super.removed(t)}get controls(){return[]}}function Zb(t){return class extends t{animOnValueChange(t,e=!1,n){if(t==this._lastValue)return;if(this.root?.app?.suppressAnimations)return this._lastValue=t,this._anim_alpha=0,void this.invalidate();let s;s=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-s,this.animate({step:t=>{this._anim_alpha=s*(t-1),this.invalidate()},duration:1e3,delta:"circ",options:{x:1},ease:"out"}).start()}dispose(){super.dispose(),delete this._value_substitutor}onchange(t,e){t.hasOwnProperty("value")&&delete this._value_substitutor}get animAlpha(){return this._anim_alpha||0}get animValue(){return(this._lastValue||0)+(this._anim_alpha||0)}defaultValueSubstitutor(){return this.getState("value")}get valueSubstitutor(){return this._value_substitutor||(this._value_substitutor=Oo(this.getState("value"),this,void 0)||this.defaultValueSubstitutor),this._value_substitutor}get value(){return Number(this.valueSubstitutor())||0}set value(t){delete this._value_substitutor,this.setState("value",Number(ls(t)))}}}function tv(t){return class extends t{_convertDataFormat(t,e){let n;if("json"===e)n=JSON.parse(t);else n=t;return n}isDataSource(){return!0}}}function ev(t){var e;return(e=class extends t{is3dish(){return!0}get hasTextProperty(){return!1}get capturable(){return!1}render(t){}}).raycastTargetDefault=!1,e.requires3d=!0,e}const nv="$base_url",sv=[{type:"gltf-preset",label:"preset",name:"preset"},{type:"gltf-selector",label:"url",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:nv,defaultStorage:"3d-model",storageFilters:{type:Array,value:[{name:"category",value:"image"}]},useUpload:!0,category:"application"},observe:function(t){const e=this.parentNode?.querySelector("[name=gltfInfo]");e&&(e.src=t);const n=this.parentNode?.querySelector("[name=fillStyleTargets]");n&&(n.src=t);const s=this.parentNode?.querySelector("[name=playTargets]");s&&(s.src=t)}},{type:"gltf-info",label:"",name:"gltfInfo",readonly:!0,property:{action:(t,e)=>{t._ratioLocking=!0;try{t.set(e)}finally{t._ratioLocking=!1}}},editor:{fullwidth:!0}},{type:"gltf-fill-targets",label:"fill-targets",name:"fillStyleTargets",editor:{fullwidth:!0}},{type:"gltf-play-targets",label:"play-targets",name:"playTargets",editor:{fullwidth:!0}}];function iv(t){return class extends t{constructor(){super(...arguments),this._snapshotLoading=!1,this._ratioLocking=!1}is3dish(){return!0}get hasTextProperty(){return!1}get controls(){return[]}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath();const o=this._topViewSnapshot;if(o)return void t.drawImage(o,e,n,s,i);this._ensureTopViewSnapshot(),t.rect(e,n,s,i),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const r=this.getState("src"),a=r&&r.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(s,i));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+s/2,n+i/2,.9*s)}onchange(t,e){super.onchange?.(t,e),"src"in t&&(this._topViewSnapshot=void 0)}_ensureTopViewSnapshot(){if(this._snapshotLoading)return;const t=this.getState("src");if(!t)return;const e=Nu.getTopViewCache(t);if(e)return this._topViewSnapshot=e,void this.invalidate();this._snapshotLoading=!0;const n=this.app.url(t);Nu.loadGLTF(n).then(e=>{if(this._snapshotLoading=!1,this.getState("src")!==t)return;const n=Nu.getTopViewCache(t);if(n)return this._topViewSnapshot=n,void this.invalidate();const s=Nu.renderTopView(e.scene);Nu.setTopViewCache(t,s),this._topViewSnapshot=s,this.invalidate()}).catch(()=>{this._snapshotLoading=!1})}buildRealObject(){return new Nu(this)}get source(){return this.getState("src")}set source(t){this.setState("src",t)}get play(){return!1!==this.getState("play")}set play(t){this.setState("play",t)}get nodes(){return this.getState("nodes")}set nodes(t){this.setState("nodes",t)}get animations(){return this.getState("animations")}set animations(t){this.setState("animations",t)}get playTargets(){return this.getState("playTargets")}set playTargets(t){this.setState("playTargets",t)}get fillStyleTargets(){return this.getState("fillStyleTargets")}set fillStyleTargets(t){this.setState("fillStyleTargets",t)}get nodeNames(){const t=this.realObject;return t?.nodeNames??[]}get animationNames(){const t=this.realObject;return t?.animationNames??[]}set dimension(t){const{width:e=1,height:n=1,depth:s=1}=t;this.setState({width:e,height:n,depth:s}),this.realObject?.updateDimension()}_applyRatioLock(t){if(!("width"in t||"height"in t||"depth"in t))return t;const e=this.state.width||1,n=this.state.height||1,s=this.state.depth||1,i=Bf([(t.width??e)/e,(t.height??n)/n,(t.depth??s)/s]);return i?{...t,width:Math.round(e*i),height:Math.round(n*i),depth:Math.round(s*i)}:t}set(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.set(t)}finally{this._ratioLocking=!1}}setState(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.setState(t)}finally{this._ratioLocking=!1}}}}function ov(t){return function(e){return Array.isArray(t)?t.forEach(t=>{uc.register(t,e)}):uc.register(t,e),e}}function rv(t){return!!t&&"function"==typeof t.capacity&&"function"==typeof t.available}function av(t){if(rv(t)){const e=t.capacity(),n=t.available();return{capacity:e,available:n,isFull:0===n}}if("function"==typeof t?.slotIds){const e=t.slotIds().length,n="function"==typeof t.emptySlotIds?t.emptySlotIds().length:e;return{capacity:e,available:n,isFull:0===n}}const e=t?.state?.capacity,n=Array.isArray(t?.state?.data)?t.state.data.length:0;if("number"==typeof e){const t=Math.max(0,e-n);return{capacity:e,available:t,isFull:0===t}}return{capacity:1/0,available:1/0,isFull:!1}}class cv{constructor(){this.wasFull=!1,this.availableListeners=[],this.fullListeners=[]}notify(t){const e=0===t;if(e&&!this.wasFull){this.wasFull=!0;for(const t of this.fullListeners)try{t()}catch(t){}}else if(!e&&this.wasFull){this.wasFull=!1;for(const t of this.availableListeners)try{t()}catch(t){}}}onAvailable(t){return this.availableListeners.push(t),()=>{const e=this.availableListeners.indexOf(t);e>=0&&this.availableListeners.splice(e,1)}}onFull(t){return this.fullListeners.push(t),()=>{const e=this.fullListeners.indexOf(t);e>=0&&this.fullListeners.splice(e,1)}}dispose(){this.availableListeners=[],this.fullListeners=[]}}function lv(t,e){if(!t||!e)return()=>{};if("function"!=typeof t.pauseEmit||"function"!=typeof t.resumeEmit)return()=>{};if("function"!=typeof e.onFull||"function"!=typeof e.onAvailable)return()=>{};const n=e.onFull(()=>t.pauseEmit()),s=e.onAvailable(()=>t.resumeEmit());return av(e).isFull&&t.pauseEmit(),()=>{n?.(),s?.()}}class hv{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,s){const i=e.maxCount??1/0;if(t<0||t>=i)return null;const o=this.owner?.state?.width??0,r=this.owner?.state?.height??0,a=s?.state?.width??0,c=s?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(r-c)/2),z:0}:{x:Math.max(0,(o-a)/2),y:t*this.itemSpacing,z:0}}capacity(t){return t.maxCount??1/0}}function dv(t,e,n,s,i,o,r){const a=n.w,c=n.h,l=s.w,h=s.h,d=s.d,u=[],p=l+i,f=h+i,m=Math.max(1,Math.floor((a+i)/p)),g=Math.max(1,Math.floor((c+i)/f)),y=m*g,b=o&&o>0?Math.floor(o):4;if("row"===t||"column"===t){const n=r?.advanceAlongX??!1,s=r?.reverse??!1,i=n?m:g,o=n?g:m,l=(t,e,s)=>((t,e,n)=>u.push({x:-a/2+(t+.5)*p,y:n*d+d/2,z:-c/2+(e+.5)*f}))(n?t:e,n?e:t,s);let h=0;for(let n=0;n<i&&h<e;n++){const r=s?i-1-n:n;if("column"===t)for(let t=0;t<o&&h<e;t++)for(let n=0;n<b&&h<e;n++)l(r,t,n),h++;else for(let t=0;t<b&&h<e;t++)for(let n=0;n<o&&h<e;n++)l(r,n,t),h++}return u}if("pyramid"===t){let t=e,n=0;for(;t>0;){const e=Math.max(1,m-n),s=Math.max(1,g-n),i=e*s,r=Math.min(t,i);for(let t=0;t<r;t++){const i=t%e,o=Math.floor(t/e),r=-a/2+(i+(m-e)/2+.5)*p,l=-c/2+(o+(g-s)/2+.5)*f;u.push({x:r,y:n*d+d/2,z:l})}if(t-=r,n++,1===e&&1===s){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(o&&n>=o)break}return u}if("pile"===t){const t=t=>(43758.5453*Math.sin(12.9898*t)%1+1)%1;for(let n=0;n<e;n++){const e=Math.floor(n/y),s=n%y,i=s%m,r=Math.floor(s/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(i+.5)*p+g,_=-c/2+(r+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),o&&e>=o-1&&s===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(o&&e>=o)break;const s=n%y,i=s%m,r=Math.floor(s/m);let l=-a/2+(i+.5)*p;const h=-c/2+(r+.5)*f;"staggered"===t&&e%2==1&&(l+=p/2),u.push({x:l,y:e*d+d/2,z:h})}return u}class uv{constructor(t,e={}){this.pattern=t,this.defaults=e}layout(t,e,n,s={}){const i=s.gap??this.defaults.gap??0,o=s.heightLimit??this.defaults.heightLimit,r=s.fill??this.defaults.fill;return dv(this.pattern,t,e,n,i,o,r).map(t=>({position:t}))}}class pv{constructor(t,e,n={}){this.cols=t,this.rows=e,this.defaults=n}layout(t,e,n,s={}){const i=Math.max(1,this.cols),o=Math.max(1,this.rows),r=i*o,a=s.gap??this.defaults.gap??0,c=n.w+a,l=n.h+a,h=[];for(let e=0;e<t;e++){const t=Math.floor(e/r),s=e%r,a=s%i,d=Math.floor(s/i);h.push({position:{x:(a-(i-1)/2)*c,z:(d-(o-1)/2)*l,y:t*n.d+n.d/2}})}return h}}class fv{constructor(t=.1,e=!1,n=!1){this.gapRatio=t,this.fillFromFar=e,this.sliceFirst=n}grid(t,e){const n=e.w*this.gapRatio,s=e.h*this.gapRatio;return{cols:Math.max(1,Math.floor((t.w-n)/(e.w+n))),rows:Math.max(1,Math.floor((t.h-s)/(e.h+s))),pitchX:e.w+n,pitchZ:e.h+s}}capacity(t,e,n){const{cols:s,rows:i}=this.grid(t,e);return s*i*Math.max(1,Math.floor(n))}layout(t,e,n,s={}){const{cols:i,rows:o,pitchX:r,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=s.heightLimit?Math.max(1,Math.floor(s.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=i*o,p=i*(h?l:1),f=i*o*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,s,l;if(d){const n=Math.floor(t/p),o=t%p;e=o%i,l=Math.floor(o/i),s=n}else{l=Math.floor(t/u);const n=t%u;e=n%i,s=Math.floor(n/i)}this.fillFromFar&&(s=o-1-s),g.push({position:{x:(e-(i-1)/2)*r,z:(s-(o-1)/2)*a,y:l*c+n.d/2}})}return g}}function mv(t,e,n,s=0){for(let i=0;i<e.length;i++){const o=e[i],r=n[i];o&&r&&(o.parent!==t&&t.attach(o),o.position.set(r.position.x,s+r.position.y,r.position.z),r.rotation?o.quaternion.set(r.rotation.x,r.rotation.y,r.rotation.z,r.rotation.w):o.quaternion.identity())}}function gv(t,e,n,s=.12){const i=e.left+e.width/2,o=e.top+e.height/2,r=Math.min(n.w,n.h)*s,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let s=a.get(t);s||(s={x:i+e.position.x-n.w/2+r,y:o+e.position.z-n.h/2+r,w:n.w-2*r,h:n.h-2*r,count:0},a.set(t,s)),s.count++}return[...a.values()]}function yv(t){return{id:t?.state?.id??t?.id??t?.refid,type:t?.state?.type??t?.type}}const bv=new w.Euler;function vv(t,e){bv.setFromQuaternion(new w.Quaternion(e.x,e.y,e.z,e.w),"YXZ"),t.rotationX=bv.x,t.rotation=-bv.y,t.rotationY=bv.z}const _v="_transferSlotId",xv=new Set(["left","top","width","height","depth","zPos","rotation","rotationX","rotationY","rotationZ","scale","translate","material3d","fillStyle","strokeStyle","lineWidth","lineDash","alpha","opacity","hidden","text","fontColor","fontSize","fontFamily","bold","italic","textAlign","textBaseline","shadow","border","cssText","object3d","_realObject","refid","id"]);function wv(t){return class extends t{constructor(){super(...arguments),this._itemIssues=[],this._itemsStale=!1,this._lastItemIds=new Set}_itemsFromData(){return!0}_currentKeyOf(t){const e=this._keyedById()?t?.state?.id:t?.[_v];return null!=e?String(e):null}get itemIssues(){return this._itemIssues}get itemsStale(){return this._itemsStale}_sayItemIssues(t,e){const n=this._itemIssues.length>0||this._itemsStale;this._itemIssues=t,this._itemsStale=e,(n||t.length>0||e)&&this.trigger?.("item-issues",this,t,e)}_keyedById(){return!1}async ready(){if(await super.ready(),!this._itemsFromData())return;const t=this.state?.data;Array.isArray(t)&&0===this._items.length&&!this.isRecordStorage&&this._reconcileItems(t)}set data(t){if(Array.isArray(t)&&this._itemsFromData()){if(this.isRecordStorage){const e=this.setState;return void("function"==typeof e&&e.call(this,{data:t}))}this._reconcileItems(t)}else this.setState?.({data:t})}get data(){if(!this._itemsFromData())return this.state?.data;if(this.isRecordStorage)return this.state?.data??[];const t=this._exportSlotRecords();return 0===t.length?this.state?.data:t}_reconcileItems(t){if(this._keyedById())return this._reconcileItemsById(t);const e=new Map;for(const n of t){const t=this._recordKey(n);t&&e.set(t,n)}const n=new Map;for(const t of this._items){const e=this._currentKeyOf(t);null!=e&&n.set(e,t)}for(const[t,s]of n)if(!e.has(t)){try{this.removeItem(s,!0)}catch{}ph(s);try{s?.dispose?.()}catch{}}for(const[t,s]of e){if(n.has(t))continue;if(null==s.itemId)continue;const e=this._createItemFromRecord(s);if(e){e[_v]=t;try{this.handoverIn(e)}catch{}}}for(const[t,s]of e){const e=n.get(t);if(e&&s.itemState&&"function"==typeof e.setState)try{e.setState(s.itemState)}catch{}}}_reconcileItemsById(t){const e=new Map;t.forEach((t,n)=>{const s=this._recordKey(t);s&&(e.get(s)??e.set(s,[]).get(s)).push(n)});const n=[...e].filter(([,t])=>t.length>1);if(n.length>0)return void this._sayItemIssues(n.map(([t,e])=>({code:"item-duplicate",id:t,at:e})),!0);const s=new Map;for(const e of t)s.set(this._recordKey(e),e);const i=new Map;for(const t of this._items){const e=this._currentKeyOf(t);null!=e&&i.set(e,t)}const o=this._lastItemIds,r=this.root,a=[];for(const[t,e]of i)s.has(t)||setTimeout(()=>{if(e.parent===this){try{this.removeItem(e,!0)}catch{}ph(e);try{e?.dispose?.()}catch{}}},0);for(const[t,e]of s){if(i.has(t))continue;const n=dh(r,t);let s,c=!1;if(n&&n.parent!==this){if(o.has(t)){const e=n.parent?.state?.id;a.push({code:"item-repeat-report",id:t,holder:null!=e?String(e):null});continue}s=n,c=!!n.parent}else s=this._createItemFromRecord(e);if(!s)continue;s[_v]=e.slotId;const l=c?this.itemMoveAnimation():null,h={...e.slotId?{slotId:e.slotId}:{},...l?{animated:!0,...l}:{}};try{this.handoverIn(s,Object.keys(h).length?h:void 0)}catch{}}for(const[t,e]of s){const n=i.get(t);if(n){if(e.itemState&&"function"==typeof n.setState)try{n.setState(e.itemState)}catch{}if(e.itemType&&n.state?.type!==e.itemType&&"function"==typeof n.setState)try{n.setState({type:e.itemType})}catch{}if(n[_v]!==e.slotId){n[_v]=e.slotId;try{this.handoverIn(n,e.slotId?{slotId:e.slotId}:void 0)}catch{}}}}this._orderItemsAs([...s.keys()]),this._lastItemIds=new Set(s.keys()),this._sayItemIssues(a,!1)}itemMoveAnimation(){return null}_orderItemsAs(t){const e=new Map(t.map((t,e)=>[t,e])),n=this._items.filter(t=>e.has(this._currentKeyOf(t)??"")),s=[...n].sort((t,n)=>e.get(this._currentKeyOf(t))-e.get(this._currentKeyOf(n)));if(s.every((t,e)=>t===n[e]))return;let i=0;for(let t=0;t<this._items.length;t++)e.has(this._currentKeyOf(this._items[t])??"")&&(this._items[t]=s[i++]);const o=this.seatHeldItem;if("function"==typeof o)for(const t of s)o.call(this,t,{slotId:t[_v]})}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,s=[];for(const t of this._items){const e=t[_v];null!=e?n.set(String(e),t):s.push(t)}for(const s of t){const t=n.get(s)??null;e.push(this._slotRecordOf(s,t))}for(const t of s)e.push(this._slotRecordOf("",t));for(const[s,i]of n)t.includes(s)||e.push(this._slotRecordOf(s,i));return e}_recordKey(t){return this._keyedById()?null!=t.itemId?String(t.itemId):"":t.slotId??t.cellId??""}_slotRecordOf(t,e){if(!e)return{slotId:t,itemId:null};const n=e?.state?.id;return{slotId:t,itemId:null!=n?String(n):null,itemType:e?.state?.type,itemState:this._extractItemState(e)}}_extractItemState(t){const e=t?.state;if(!e||"object"!=typeof e)return;const n=this._businessFields?.();if(Array.isArray(n)){if(0===n.length)return;const t={};for(const s of n)s in e&&void 0!==e[s]&&(t[s]=e[s]);return Object.keys(t).length>0?t:void 0}const s={};for(const t of Object.keys(e))xv.has(t)||t.startsWith("_")||(s[t]=e[t]);return Object.keys(s).length>0?s:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=uc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}const Mv=new Map;function Sv(t){return t.userData.__bankOwned=!0,t}const Av={primitive(t){const e="primitive::"+function(t){switch(t.kind){case"cylinder":return`cylinder|${t.segments??0}`;case"sphere":return`sphere|${t.segments??0}|${t.heightSegments??0}`;default:return t.kind}}(t);let n=Mv.get(e);return n||Mv.set(e,n=Sv(function(t){switch(t.kind){case"box":return new w.BoxGeometry(1,1,1);case"plane":return new w.PlaneGeometry(1,1);case"cylinder":return new w.CylinderGeometry(.5,.5,1,t.segments??16);case"sphere":return new w.SphereGeometry(.5,t.segments??16,t.heightSegments??Math.max(2,Math.round((t.segments??16)/2)))}}(t))),n},shaped(t,e){const n="shaped::"+t;let s=Mv.get(n);return s||Mv.set(n,s=Sv(e())),s},owns:t=>!0===t.userData?.__bankOwned,get size(){return Mv.size},has:t=>Mv.has("primitive::"+t)||Mv.has("shaped::"+t),dispose(){for(const t of Mv.values())t.dispose();Mv.clear()}};let kv=null;const Ev=new Set;let Tv=null;function Cv(){for(const t of[...Ev]){const e=t.deref();e?e.refreshLook():Ev.delete(t)}}function Ov(t){Tv?.(),kv=t,Tv=t?t.subscribe(Cv):null,Cv()}function Pv(t){return kv?.dimsOf(t)??null}const Iv=t=>Number(t.component.state.depth)||t.depth,Dv="#9e9e9e";class zv extends(mc(pc)){constructor(){super(...arguments),this._look=null,this._lookKey=null,this._seatDims=null}get itemTypeCode(){return this.state.type}get drawnAsItem(){return!0}get isItem(){return!0}is3dish(){return!0}get lookNow(){return this._look}get look(){this._lookRef||Ev.add(this._lookRef=new WeakRef(this));const t=kv?.keyFor(this)??null;return(t!==this._lookKey||t&&!this._look)&&(this._look?.dispose(),this._look=t?kv?.lookFor(this)??null:null,this._lookKey=this._look?t:null,this.fitLook()),this._look}get seatDims(){return this._seatDims}takeSeatDims(t){((t,e)=>t===e||!!t&&!!e&&t.width===e.width&&t.depth===e.depth&&t.height===e.height)(t,this._seatDims)||(this._seatDims=t?{...t}:null,this.sized||(this.fitLook(),this._realObject?.rebuildLook?.(),this.invalidate?.()))}fitLook(){this._look&&!this.sized&&this._seatDims&&this._look.fitTo(this._seatDims)}refreshLook(){const t=kv?.keyFor(this)??null;if(t===this._lookKey&&(!t||this._look))return;this._look?.dispose(),this._look=null,this._lookKey=null;const e=this._realObject;if(e&&e instanceof Rv!==this.drawnAsItem){const t=this.parent;t?.trigger?.("item-remake",t,this),t?._reseatSlot?.(this[_v])}else e?.rebuildLook?.();this.invalidate?.()}onchange(t,e){super.onchange?.(t,e),"type"in t&&(this.refreshLook(),this.parent?._reseatSlot?.(this[_v])),"data"in t&&this._look&&this._look.component.set("data",t.data)}get sized(){const{width:t=0,height:e=0,depth:n=0}=this.state;return t>0&&e>0&&n>0}get shownSize(){if(this.sized){const{width:t,height:e,depth:n}=this.state;return{width:t,height:e,depth:n}}const t=rh(this).mmPerUnit;if(this._seatDims)return{width:this._seatDims.width/t,height:this._seatDims.depth/t,depth:this._seatDims.height/t};const e=this.look;if(e)return{width:Number(e.component.state.width)||0,height:Number(e.component.state.height)||0,depth:Iv(e)};const n=200/t;return{width:n,height:n,depth:n}}get bounds(){const{left:t=0,top:e=0,width:n=0,height:s=0}=this.state;if(n>0&&s>0)return super.bounds;const i=this.shownSize;return{left:t,top:e,width:i.width,height:i.height}}render(t){const{left:e,top:n,width:s,height:i}=this.bounds,o=this.look;if(o){const r=o.component,a={left:e+(s-(Number(r.state.width)||0))/2,top:n+(i-(Number(r.state.height)||0))/2};return r.state.left===a.left&&r.state.top===a.top||r.set(a),void r.render(t)}t.save(),t.fillStyle=this.state.fillStyle||Dv,t.strokeStyle=this.state.strokeStyle||"#616161",t.lineWidth=1,this.sized||t.setLineDash([4,3]),t.beginPath(),t.rect(e,n,s,i),this.sized&&t.fill(),t.stroke(),t.restore()}buildRealObject(){return this.drawnAsItem?new Rv(this):void 0}dispose(){this._lookRef&&Ev.delete(this._lookRef),this._look?.dispose(),this._look=null,super.dispose()}}class Rv extends Du{constructor(){super(...arguments),this.box=null,this.shown=null}getObject3dInstance(){return new w.Group}build(){super.build(),this.rebuildLook()}rebuildLook(){this.box&&(this.object3d.remove(this.box),this.box.material.dispose(),this.box=null),this.shown&&(this.object3d.remove(this.shown),this.shown=null);const t=this.component,e=t.look,n=t.shownSize;if(e){const t=e.component.realObject,s=t?.object3d;if(!t||!s)return;return t.suppressTransform=!0,s.position.set(0,(Iv(e)-n.depth)/2,0),s.quaternion.identity(),this.object3d.add(s),void(this.shown=s)}const s=new w.Mesh(Av.primitive({kind:"box"}),new w.MeshStandardMaterial({color:t.state.fillStyle||Dv,wireframe:!t.sized&&!t.seatDims}));s.scale.set(n.width,n.depth,n.height),this.object3d.add(s),this.box=s}dispose(){const t=this.component.lookNow,e=t?.component._realObject;e&&(e.dispose(),t.component._realObject=void 0),super.dispose(),this.component._realObject===this&&(this.component._realObject=void 0)}clear(){return this.box=null,this.shown=null,super.clear()}}const jv=["x","y","z"],$v=["Capacity","Holdable","Transferable","FlowNode"],Lv=/^[a-z0-9][a-z0-9-]*\.[A-Za-z][A-Za-z0-9]*$/,Fv=t=>"string"==typeof t&&Lv.test(t),Nv=t=>$v.includes(t)||Fv(t),Hv=Object.freeze({Transferable:["Capacity","FlowNode"]}),Bv=100,Gv=["S","M","L","XL"],Uv=[8,12,16,24,32,48],Vv=Object.freeze({x:"size.x",y:"size.y",z:"size.z"}),Wv=8192;function Yv(t,e){const n="shape"in t?t.shape:void 0,s=n?.extrusion?.section,i="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===s?.kind||"rectangle"===s?.kind&&Object.values(s.corner??{}).some(t=>t>0));if(!i||"full"===e)return t.segments;const o=t.segments??12,r=Math.ceil(o/("medium"===e?2:4));return Math.min(o,Uv.find(t=>t>=r)??o)}function qv(t,e){if("full"===e)return t;let n=!1;const s=t.geometry.map(t=>{const s=Yv(t,e);return s===t.segments?t:(n=!0,{...t,segments:s})});return n?{...t,geometry:s}:t}class Xv extends Error{code;path;details;constructor(t,e,n,s){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==s&&(this.details=s)}}const Kv=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),Jv=1e-6,Qv=256,Zv=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function t_(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const e_=t=>Kv[t],n_=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function s_(t,e){const[n,s]=e_(e);if("rectangle"===t.kind){const e=[];for(const i of[n,s]){const n=t.size[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`size.${i}`})}if(!t.corner)return e;for(const i of[n,s]){const n=t.corner[i];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:i}):Number.isFinite(t.size[i])&&n>t.size[i]/2+Jv&&e.push({code:"CORNER_TOO_LARGE",axis:i,max:t.size[i]/2}):e.push({code:"NON_FINITE",at:`corner.${i}`})}return e.length||t.corner[n]>0==t.corner[s]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:s}),e}if("ellipse"===t.kind){const e=[];for(const i of[n,s]){const n=t.radius[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`radius.${i}`})}return e}return function(t,e){const[n,s]=e_(e),i=[],o=new Set;for(const e of t){"string"==typeof e.id&&Zv.test(e.id)?o.has(e.id)?i.push({code:"DUPLICATE_POINT_ID",point:e.id}):o.add(e.id):i.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,s])"number"==typeof e[t]&&Number.isFinite(e[t])||i.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&i.push({code:"TOO_FEW_POINTS",count:t.length});t.length>Qv&&i.push({code:"TOO_MANY_POINTS",count:t.length,limit:Qv});if(i.length)return i;const r=t.length,a=function(t,e){const[n,s]=e_(e);return t.map(t=>[t[n],t[s]])}(t,e),c=e=>t_(t[e].id,t[(e+1)%r].id),l=Jv,h=a.map((t,e)=>Math.hypot(a[(e+1)%r][0]-t[0],a[(e+1)%r][1]-t[1]));if(h.forEach((t,e)=>{t<=l&&i.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),i.length)return i;for(let t=0;t<r;t++){const e=a[t],n=a[(t+1)%r],s=a[(t+2)%r],o=(n[0]-e[0])*(s[1]-n[1])-(n[1]-e[1])*(s[0]-n[0]),d=(n[0]-e[0])*(s[0]-n[0])+(n[1]-e[1])*(s[1]-n[1]);Math.abs(o)<=l*h[t]&&d<0&&i.push({code:"SIDES_FOLD",sides:[c(t),c((t+1)%r)]})}for(let t=0;t<r;t++)for(let e=t+1;e<r;e++){if(e===t+1||0===t&&e===r-1)continue;const n=r_(a[t],a[(t+1)%r],a[e],a[(e+1)%r],l);n&&i.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(i.length)return i;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[s,i]=t[n],[o,r]=t[(n+1)%t.length];e+=s*r-o*i}return e}(a))/2<=l&&i.push({code:"ZERO_AREA"});return i}(t.points,e)}const i_=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function o_(t,e,n){const s=n[0]-e[0],i=n[1]-e[1],o=s*s+i*i,r=o?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*i)/o)):0;return Math.hypot(t[0]-e[0]-r*s,t[1]-e[1]-r*i)}function r_(t,e,n,s,i){const o=i_(n,s,t),r=i_(n,s,e),a=i_(t,e,n),c=i_(t,e,s),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>i*n&&e<-i*n||t<-i*n&&e>i*n;if(h(o,r,Math.hypot(s[0]-n[0],s[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(o_(t,n,s),o_(e,n,s),o_(n,t,e),o_(s,t,e))<=i?"touch":null}function a_(t,e){const[n,s]=e_(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,i]=[n,s].sort(),o=[e,i].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!n_(t))return o;const r=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${i}${n}`,shape:"curved"})));return[...o,...r]}const i=t.points;return i.map((t,e)=>{const n=i[(e+1)%i.length];return{id:t_(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function c_(t,e,n){const[s,i]=e_(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const o=[s,i].flatMap(t=>[`${t}-`,`${t}+`]);for(const t of o){const e=n[t];if("number"!=typeof e||!Number.isFinite(e))return{refused:"NON_FINITE",side:t};if(!(e>0))return{refused:"WALL_NOT_POSITIVE",side:t}}const r=t=>n[t],a=(t,e)=>e-r(`${t}-`)-r(`${t}+`),c={[s]:(r(`${s}-`)-r(`${s}+`))/2,[i]:(r(`${i}-`)-r(`${i}+`))/2};if("rectangle"===t.kind){const e={[s]:a(s,t.size[s]),[i]:a(i,t.size[i])};if(!(e[s]>0&&e[i]>0))return{refused:"NO_ROOM_INSIDE"};if(!n_(t))return{section:{kind:"rectangle",size:e},centre:c};const n=e=>Math.max(t.corner[e]-Math.max(r(`${e}-`),r(`${e}+`)),0),o={[s]:n(s),[i]:n(i)};return{section:{kind:"rectangle",size:e,...o[s]>0&&o[i]>0?{corner:o}:{}},centre:c}}const l={[s]:a(s,2*t.radius[s])/2,[i]:a(i,2*t.radius[i])/2};return l[s]>0&&l[i]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const l_=(t,e)=>Object.fromEntries(jv.map(n=>[n,n===t?e:0]));function h_(t,e,n){const[s,i]=Kv[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return l_(t,n.id.endsWith("+")?1:-1)}const o=t.points.find(t=>t.id===n.from),r=t.points.find(t=>t.id===n.to),a=r[s]-o[s],c=r[i]-o[i],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[s]=c/l||0,h[i]=-a/l||0,h}const d_=(t,e,n,s)=>{throw new Xv(t,e,n,s)},u_=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],p_=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),f_=["rectangle","ellipse","polygon","portal"],m_=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function g_(t,e){const n=t??{},s=n.axis;jv.includes(s)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const i=n.section;f_.includes(i)||d_("PARAM",e,`section is ${f_.join(", ")}, not ${String(n.section)}`);const o=[...Kv[s]].sort(),[r,a]=o,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===i||d_("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===i?String(n.points??"").split("."):[];"polygon"===i?((l.length<3||l.some(t=>!m_.test(t)))&&d_("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&d_("PARAM",e,"a point is named twice")):void 0!==n.points&&d_("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==i&&"ellipse"!==i&&"portal"!==i||(u.across={[r]:d(),[a]:d()}),c&&(u.corner={[r]:d(),[a]:d()}),"portal"===i&&(u.jamb=d(),u.head=d()),"polygon"===i&&(u.point=Object.fromEntries(l.map(t=>[t,{[r]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==i&&"ellipse"!==i&&d_("SECTION_KIND",e,`a ${i} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const s=n[t];return"open"!==s&&"closed"!==s&&d_("PARAM",e,`${t} is open or closed`),s};p={id:n.cavity,start:t("cavity-start"),end:t("cavity-end")},u.wall=Object.fromEntries([r,a].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>[t,d()])),"closed"===p.start&&(u.startClosed=d()),"closed"===p.end&&(u.endClosed=d())}else void 0===n["cavity-start"]&&void 0===n["cavity-end"]||d_("PARAM",e,"the ends of an inside need the inside");return{axis:s,plane:o,section:i,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const y_=(t,e=1)=>[{arg:t,k:e}];function b_(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const s=t.args?.[0],i=t.args?.[1],o=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(s));return"mul@1"!==o?.op||2!==o.args.length||o.args[0]!==i||-.5!==e.constants.find(t=>t.id===o.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function v_(t,e){const n=g_(t.params,t.id),[s,i]=n.plane,o={},r={},a={},[c,l]=p_[n.axis],h=b_(t,e);if(o[n.axis]=y_(1),r[n.axis]={arg:1,k:1},a[c]={axis:n.axis,normal:-1,plane:h.lo},a[l]={axis:n.axis,normal:1,plane:h.hi},"polygon"===n.section){for(const t of[s,i])o[t]="profile",r[t]={refused:"SECTION_CORNERS"};return{measure:o,edit:r,faces:a,kind:"polygon"}}const d=n.arg.across,u="ellipse"===n.section?2:1;for(const t of[s,i])o[t]=y_(d[t],u),r[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[s]]&&t.args[d[s]]===t.args[d[i]]&&(r[i]={arg:d[i],k:u,sameAs:s}),"portal"===n.section){const[t,e]=p_[s],[c,l]=p_[i];return a[t]={axis:s,normal:-1,plane:[{arg:d[s],k:-.5}]},a[e]={axis:s,normal:1,plane:[{arg:d[s],k:.5}]},a[c]={axis:i,normal:-1,plane:[]},a[l]={axis:i,normal:1,plane:[{arg:d[i],k:1}]},a[`opening-${t}`]={axis:s,normal:1,plane:[{arg:d[s],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:s,normal:-1,plane:[{arg:d[s],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:i,normal:-1,plane:[{arg:d[i],k:1},{arg:n.arg.head,k:-1}]},{measure:o,edit:r,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[s,i]){const[e,n]=p_[t];a[e]={axis:t,normal:-1,plane:[{arg:d[t],k:-p}],...f},a[n]={axis:t,normal:1,plane:[{arg:d[t],k:p}],...f}}if(n.cavity){const t=n.arg.wall;for(const e of[s,i]){const[n,s]=p_[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${s}`]={axis:e,normal:-1,plane:[{arg:d[e],k:p},{arg:t[`${e}+`],k:-1}],...f}}void 0!==n.arg.startClosed&&(a[`inside-${c}`]={axis:n.axis,normal:1,plane:[...h.lo,{arg:n.arg.startClosed,k:1}]}),void 0!==n.arg.endClosed&&(a[`inside-${l}`]={axis:n.axis,normal:-1,plane:[...h.hi,{arg:n.arg.endClosed,k:-1}]})}return{measure:o,edit:r,faces:a,kind:n.section}}function __(t,e){const n=t??{},s=n.axis;return jv.includes(s)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&d_("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:s,profile:n.profile,count:"taper"===n.profile?4:2}}function x_(t,e){const n=__(t.params,t.id),[s,i]=[...Kv[n.axis]].sort(),o={},r={};if("half-ellipse"===n.profile)return o[n.axis]=y_(1,2),r[n.axis]={arg:1,k:2},o[s]=o[i]=y_(0,2),r[s]={arg:0,k:2},r[i]={arg:0,k:2,sameAs:s},{measure:o,edit:r,faces:{},kind:"sphere"};const[a,c]=p_[n.axis];o[n.axis]=y_(1),r[n.axis]={arg:1,k:1};o[s]=o[i]=[{arg:2,k:2},{arg:3,k:2}],r[s]={arg:3,k:2,with:[2]},r[i]={arg:3,k:2,with:[2],sameAs:s};const l=b_(t,e);return{measure:o,edit:r,faces:{[a]:{axis:n.axis,normal:-1,plane:l.lo},[c]:{axis:n.axis,normal:1,plane:l.hi}},kind:"taper"}}function w_(t,e){const n=t??{};"polygon"!==n.section&&d_("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||d_("PARAM",e,"a loft has no corners and no inside");const s=g_(n,e),[i,o]=s.plane;return{...s,apex:{[i]:s.count,[o]:s.count+1},count:s.count+2}}function M_(t,e){const n=w_(t.params,t.id),s={},i={},[o]=p_[n.axis];s[n.axis]=y_(1),i[n.axis]={arg:1,k:1};for(const t of n.plane)s[t]="profile",i[t]={refused:"SECTION_CORNERS"};return{measure:s,edit:i,faces:{[o]:{axis:n.axis,normal:-1,plane:b_(t,e).lo}},kind:"pyramid"}}const S_=["glb"],A_={m:1e3,mm:1},k_=/^sha256-([0-9a-f]{64})$/,E_=new RegExp(`^mm${"_(-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e-?\\d+)?)".repeat(6)}$`),T_=/^n(\d+)$/,C_=/^node-(\d+)$/;function O_(t,e){const n=t??{},s=k_.exec(n.asset??"")?.[1];s||d_("PARAM",e,"asset is sha256- and the file's 64 lower-case hex digits"),S_.includes(n.format)||d_("PARAM",e,`format is ${S_.join(" or ")}, not ${String(n.format)}`),Object.hasOwn(A_,n.unit??"")||d_("PARAM",e,`unit is ${Object.keys(A_).join(" or ")}, not ${String(n.unit)}`);const i=void 0===n.node?void 0:C_.exec(n.node)?.[1];void 0!==n.node&&void 0===i&&d_("PARAM",e,"node, when given, is node- and its place in the file");const o=E_.exec(n.bounds??""),r=(o??[]).slice(1).map(Number);o&&6===r.length&&r.every(Number.isFinite)||d_("PARAM",e,"bounds are mm_ and six numbers: min x, y, z, then max x, y, z");const a={x:{min:r[0],max:r[3]},y:{min:r[1],max:r[4]},z:{min:r[2],max:r[5]}};jv.some(t=>!(a[t].max>=a[t].min))&&d_("PARAM",e,"each bound's max is at least its min");const c=n.axis;jv.includes(c)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const l=t=>a[t].max-a[t].min;l(c)>0&&!jv.some(t=>l(t)>l(c))||d_("PARAM",e,"axis is the one the bounds reach furthest along, and it has a reach");const h=t=>{const s=Number(T_.exec(n[t]??"")?.[1]);return Number.isSafeInteger(s)||d_("PARAM",e,`${t} is n and a count`),s};return{asset:s,format:n.format,...void 0!==i?{node:Number(i)}:{},unit:n.unit,bounds:a,axis:c,triangles:h("triangles"),primitives:h("primitives")}}function P_(t){const e=O_(t.params,t.id),n=e.bounds[e.axis].max-e.bounds[e.axis].min,s={},i={},o={};for(const t of jv){const r=(e.bounds[t].max-e.bounds[t].min)/n;s[t]=[{arg:0,k:r}],i[t]=t===e.axis?{arg:0,k:1}:{refused:r>0?"MESH_UNIFORM":"NO_MEASURE"};const[a,c]=p_[t];o[a]={axis:t,normal:-1,plane:[{arg:0,k:e.bounds[t].min/n}],contact:"bounds"},o[c]={axis:t,normal:1,plane:[{arg:0,k:e.bounds[t].max/n}],contact:"bounds"}}return{measure:s,edit:i,faces:o,kind:"mesh"}}function I_(t,e){return"extrude@1"===t?.op?v_(t,e):"revolve@1"===t?.op?x_(t,e):"loft@1"===t?.op?M_(t,e):"mesh@1"===t?.op?P_(t):void 0}const D_=(t,e)=>Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{axis:n.axis,normal:n.normal,at:n.plane.reduce((t,n)=>t+n.k*e[n.arg],0)}]));function z_(t,e,n){const s=jv.find(t=>t!==e&&t!==n),[i,o]=Kv[s];let r=0;for(let e=0;e<t.length;e++){const n=t[e],s=t[(e+1)%t.length];r+=n[i]*s[o]-s[i]*n[o]}return r>0?t:[t[0],...t.slice(1).reverse()]}function R_(t,e){const[n,s]=Kv[e];let i=0;const o=t.points;for(let t=0;t<o.length;t++){const e=o[t],r=o[(t+1)%o.length];i+=e[n]*r[s]-r[n]*e[s]}return i}function j_(t,e,n){const s=g_(n.params,e),[i,o]=s.plane,r=t[0],a=t[1];a>0||d_("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:r,length:a};let l;if("polygon"===s.section){const e=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[o]:t[s.arg.point[e][o]]}));e.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${o}`]=t[o]}),l={kind:"polygon",points:e}}else if("portal"===s.section){const n=t[s.arg.across[i]],r=t[s.arg.across[o]],a=t[s.arg.jamb],h=t[s.arg.head];n>0&&r>0&&a>0&&h>0&&2*a<n&&h<r||d_("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${i}`]:n,[`size.${o}`]:r,jamb:a,head:h}),l=function(t,e,n,s,i,o){const r=-n/2,a=n/2,c=r+i,l=a-i,h=s-o,d=(n,s,i)=>({id:n,[t]:s,[e]:i});return{kind:"polygon",points:z_([d("p1",r,0),d("p2",r,s),d("p3",a,s),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(i,o,n,r,a,h)}else{const e={[i]:t[s.arg.across[i]],[o]:t[s.arg.across[o]]},n="ellipse"===s.section?"radius":"size";if(c[`${n}.${i}`]=e[i],c[`${n}.${o}`]=e[o],"ellipse"===s.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},s.rounded){const n={[i]:t[s.arg.corner[i]],[o]:t[s.arg.corner[o]]};c[`corner.${i}`]=n[i],c[`corner.${o}`]=n[o],(n[i]>0||n[o]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=s_(l,s.axis);h.length&&d_("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`,{reason:"section-invalid",issues:h}),"polygon"!==l.kind||"polygon"!==s.section||R_(l,s.axis)>0||d_("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:s.axis,section:l,start:r,end:r+a};let u;if(s.cavity){const n=Object.fromEntries(Object.entries(s.arg.wall).map(([e,n])=>[e,t[n]]));u={id:s.cavity.id,wall:n,start:"open"===s.cavity.start?"open":{closed:t[s.arg.startClosed]},end:"open"===s.cavity.end?"open":{closed:t[s.arg.endClosed]}};for(const[t,e]of Object.entries(n))c[`wall.${t}`]=e;"open"!==u.start&&(c["closed.start"]=u.start.closed),"open"!==u.end&&(c["closed.end"]=u.end.closed);const i=function(t,e=[]){const{axis:n,section:s,start:i,end:o}=t;if(!(o-i>0))return{refused:{code:"SPAN_NOT_POSITIVE"}};if(e.length>1)return{refused:{code:"CAVITY_COUNT",count:e.length}};const r=e[0];let a;if(r){const t=c_(s,n,r.wall);if("refused"in t)return{refused:{code:"CAVITY",cavity:r.id,refused:t.refused,...t.side?{side:t.side}:{}}};a=t.section;const e=t=>"open"===t?0:t.closed;for(const t of["start","end"]){const e=r[t];if("open"!==e&&!(e.closed>0))return{refused:{code:"CAVITY_END_NOT_POSITIVE",cavity:r.id,end:t}}}if(!(o-i-e(r.start)-e(r.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:r.id}}}const c=a_(s,n),l=[{id:"start-face",kind:"plane",normal:l_(n,-1),..."open"===r?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:l_(n,1),..."open"===r?.end?{open:!0}:{}}];for(const t of c)l.push("flat"===t.shape?{id:`side-face:${t.id}`,kind:"plane",normal:h_(s,n,t)}:{id:`side-face:${t.id}`,kind:"curved"}),l.push({id:`edge:start:${t.id}`,kind:"edge"},{id:`edge:end:${t.id}`,kind:"edge"});if("polygon"===s.kind)for(const t of s.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===s.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...Kv[n]].sort();for(const n of["-","+"])for(const s of["-","+"])l.push({id:`edge:${t}${n}${e}${s}`,kind:"edge"})}if(r&&a){for(const t of a_(a,n)){const e=`cavity-wall:${r.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const s=h_(a,n,t);l.push({id:e,kind:"plane",normal:{x:-s.x||0,y:-s.y||0,z:-s.z||0}})}}"open"!==r.start&&l.push({id:`cavity-start:${r.id}`,kind:"plane",normal:l_(n,1)}),"open"!==r.end&&l.push({id:`cavity-end:${r.id}`,kind:"plane",normal:l_(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in i&&d_("GEOMETRY_DOMAIN",e,`the inside is not valid: ${i.refused.code}${"refused"in i.refused?` ${i.refused.refused}`:""}`,{reason:"inside-invalid",refusal:i.refused})}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:D_(v_(n).faces,t)}}function $_(t,e,n){const s=__(n.params,e),i=D_(x_(n).faces,t);if("half-ellipse"===s.profile){const[n,o]=t;return n>0&&o>0||d_("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:o},revolution:{axis:s.axis,profile:{kind:"half-ellipse",radial:n,axial:o}},faces:i}}const[o,r,a,c]=t;return r>0&&a>=0&&c>=0&&a+c>0||d_("GEOMETRY_DOMAIN",e,"a positive length and radii of 0 or more, not both 0, required"),{provider:"revolve",dimensions:{start:o,length:r,startRadius:a,endRadius:c},revolution:{axis:s.axis,profile:{kind:"taper",start:o,end:o+r,startRadius:a,endRadius:c}},faces:i}}function L_(t,e,n){const s=w_(n.params,e),[i,o]=s.plane,r=t[0],a=t[1];a>0||d_("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:r,length:a},l=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[o]:t[s.arg.point[e][o]]}));l.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${o}`]=t[o]});const h={kind:"polygon",points:l},d=s_(h,s.axis);d.length&&d_("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`,{reason:"section-invalid",issues:d}),R_(h,s.axis)>0||d_("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[i]:t[s.apex[i]],[o]:t[s.apex[o]]};return Number.isFinite(u[i])&&Number.isFinite(u[o])||d_("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${i}`]=u[i],c[`apex.${o}`]=u[o],{provider:"loft",dimensions:c,loft:{axis:s.axis,section:h,start:r,end:r+a,apex:u},faces:D_(M_(n).faces,t)}}function F_(t,e,n){const s=O_(n.params,e),i=t[0];i>0||d_("GEOMETRY_DOMAIN",e,`a mesh of positive size required, not ${i}`);const o=i/(s.bounds[s.axis].max-s.bounds[s.axis].min),r=Object.fromEntries(jv.map(t=>[t,{min:s.bounds[t].min*o,max:s.bounds[t].max*o}]));return{provider:"mesh",dimensions:{size:i},mesh:{asset:s.asset,format:s.format,...void 0!==s.node?{node:s.node}:{},unit:s.unit,scale:A_[s.unit]*o,bounds:r,triangles:s.triangles,primitives:s.primitives},faces:D_(P_(n).faces,t)}}function N_(t,e,n){return{kind:"shape",provider:t,frame:e.params.frame,faces:Object.fromEntries(Object.entries(n).map(([t,e])=>[t,e.contact?[e.axis,e.normal,e.contact]:[e.axis,e.normal]]))}}const H_={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const s=g_(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a ${s.section} push takes ${s.count} lengths, not ${t.length}`),[N_("extrude",n,v_(n).faces)]},run:(t,e,n)=>[j_(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const s=__(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a ${s.profile} turn takes ${s.count} lengths, not ${t.length}`),[N_("revolve",n,x_(n).faces)]},run:(t,e,n)=>[$_(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const s=w_(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a loft of ${s.points.length} points takes ${s.count} lengths, not ${t.length}`),[N_("loft",n,M_(n).faces)]},run:(t,e,n)=>[L_(t,e,n)]},"mesh@1":{ports:["shape"],params:["frame","asset","format","unit","bounds","axis","triangles","primitives"],optionalParams:["node"],types:(t,e,n)=>(1===t.length&&t.every(u_)||d_("TYPE",e,`a mesh takes one length, its size, not ${t.length}`),[N_("mesh",n,P_(n).faces)]),run:(t,e,n)=>[F_(t,e,n)]}};function B_(t){if(t.mesh)return Object.fromEntries(jv.map(e=>[e,{...t.mesh.bounds[e]}]));const e={};if(t.extrusion){const n=t.extrusion,[s,i]=Kv[n.axis];e[n.axis]={min:n.start,max:n.end};const o=n.section;for(const t of[s,i])if("rectangle"===o.kind)e[t]={min:-o.size[t]/2,max:o.size[t]/2};else if("ellipse"===o.kind)e[t]={min:-o.radius[t],max:o.radius[t]};else{const n=o.points.map(e=>e[t]);e[t]={min:Math.min(...n),max:Math.max(...n)}}return e}if(t.loft){const n=t.loft;e[n.axis]={min:n.start,max:n.end};for(const t of Kv[n.axis]){const s=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...s),max:Math.max(...s)}}return e}const n=t.revolution,[s,i]=Kv[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[s,i])e[t]={min:-n.profile.radial,max:n.profile.radial}}else{const t=Math.max(n.profile.startRadius,n.profile.endRadius);e[n.axis]={min:n.profile.start,max:n.profile.end};for(const n of[s,i])e[n]={min:-t,max:t}}return e}function G_(t,e){const n=I_(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}const U_=1e4,V_=(t,e,n,s)=>{throw new Xv(t,e,n,s)},W_={mm:[[1,0,0],1],cm:[[1,0,0],10],m:[[1,0,0],1e3],rad:[[0,1,0],1],deg:[[0,1,0],Math.PI/180],s:[[0,0,1],1],ratio:[[0,0,0],1],percent:[[0,0,0],.01]},Y_=[1,0,0],q_=[0,0,0],X_=[0,1,0],K_={kind:"count"},J_={kind:"flag"};W_.count=[K_,1];const Q_=(t,e)=>Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((t,n)=>t===e[n]):JSON.stringify(t)===JSON.stringify(e);function Z_(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||V_("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||V_("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||V_("SCHEMA",s,`unknown ${i}`)}function tx(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||V_("ID",e,"invalid id"),t}function ex(t,e){return"number"==typeof t&&Number.isFinite(t)||V_("NON_FINITE",e,String(t)),t}function nx(t,e){return Object.hasOwn(W_,t)||V_("UNIT",e,String(t)),W_[t]}function sx(t,e,n){(t.length!==e.length||t.some((t,n)=>!Q_(t,e[n])))&&V_("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}Object.freeze(Object.keys(W_));const ix={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&Q_(t[0],t[1])||V_("TYPE",e,"addition needs same scalar dimensions"),[t[0]]),run:([t,e])=>[t+e]},"mul@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)||V_("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e+t[1][n])]),run:([t,e])=>[t*e]},"div@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)||V_("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&V_("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>(sx(t,[X_],e),[q_]),run:([t])=>[Math.sin(t)]},"geomean@1":{ports:["value"],types:(t,e)=>((t.length<2||t.length>3||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&V_("DOMAIN",e,"geometric mean of a negative value"),[Math.pow(t.reduce((t,e)=>t*e,1),1/t.length)])},"curve@1":{ports:["value"],types(t,e){(t.length<5||t.length%2==0||!t.every(Array.isArray))&&V_("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)Q_(t[n],t[0])||V_("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),Q_(t[n+1],t[2])||V_("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],s=(t.length-1)/2,i=e=>t[1+2*e],o=e=>t[2+2*e];for(let t=1;t<s;t++)i(t)>i(t-1)||V_("DOMAIN",e,`keys out of order: at[${t}] = ${i(t)} is not after at[${t-1}] = ${i(t-1)}`);if(n<=i(0))return[o(0)];if(n>=i(s-1))return[o(s-1)];let r=0;for(;r<s-2&&i(r+1)<=n;)r++;const a=(n-i(r))/(i(r+1)-i(r));return[o(r)+(o(r+1)-o(r))*a]}},"at-least@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&Q_(t[0],t[1])||V_("TYPE",e,"at-least compares two scalars of the same dimension"),[J_]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.max(...t)]},"hypot@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.hypot(...t)]},"min@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.min(...t)]},"between@1":{ports:["length","center"],types:(t,e)=>(sx(t,[Y_,Y_,Y_,Y_],e),[Y_,Y_]),run:([t,e,n,s],i)=>{(n<0||s<0)&&V_("DOMAIN",i,"negative margin");const o=e-t-n-s;return o>0||V_("NO_SPACE",i,`available=${e-t}; margins=${n+s}; deficit=${Math.max(0,-o)}; positive length required`),[o,(t+e+n-s)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>(sx(t,[Y_,Y_,Y_],e),Array(6).fill(Y_)),run:([t,e,n],s)=>([t,e,n].some(t=>!(t>0))&&V_("GEOMETRY_DOMAIN",s,"positive width,height,depth required"),[-t/2,t/2,-e/2,e/2,-n/2,n/2]),geometry:([t,e,n])=>({provider:"box@1",dimensions:{width:t,height:e,depth:n}})},"cylinder@1":{ports:["start","end","radialMin","radialMax"],types:(t,e)=>(sx(t,[Y_,Y_],e),Array(4).fill(Y_)),run:([t,e],n)=>(t>0&&e>0||V_("GEOMETRY_DOMAIN",n,"positive radius,length required"),[-e/2,e/2,-t,t]),geometry:([t,e])=>({provider:"cylinder@1",axis:"Y",dimensions:{radius:t,length:e}})}},ox=(t,e)=>({kind:"transform",from:t,to:e}),rx=()=>[[1,0,0],[0,1,0],[0,0,1]],ax=t=>t[0].map((e,n)=>t.map(t=>t[n])),cx=(t,e)=>t.reduce((t,n,s)=>t+n*e[s],0),lx=(t,e,n,s)=>0+t[0]*e+t[1]*n+t[2]*s,hx=(t,e)=>3===t.length&&3===e.length?[lx(t[0],e[0],e[1],e[2]),lx(t[1],e[0],e[1],e[2]),lx(t[2],e[0],e[1],e[2])]:t.map(t=>cx(t,e)),dx=(t,e)=>{if(3!==t.length||3!==e.length||t.some(t=>3!==t.length)||e.some(t=>3!==t.length))return t.map(t=>ax(e).map(e=>cx(t,e)));const[n,s,i]=e;return t.map(t=>[lx(t,n[0],s[0],i[0]),lx(t,n[1],s[1],i[1]),lx(t,n[2],s[2],i[2])])},ux=(t,e)=>3===t.length&&3===e.length?[t[0]+e[0],t[1]+e[1],t[2]+e[2]]:t.map((t,n)=>t+e[n]),px=(t,e)=>({r:dx(t.r,e.r),t:ux(hx(t.r,e.t),t.t)}),fx=t=>{const e=ax(t.r);return{r:e,t:hx(e,t.t.map(t=>-t))}};function mx(t,e,n=[]){Z_(t.params,e,n,t.id);for(const s of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])tx(t.params[s],t.id)}function gx(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&V_("TYPE",e,"rigid transforms required")}Object.assign(ix,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>(sx(t,[Y_,Y_,Y_,Y_,Y_,q_,K_],e),[{kind:"layout"}]),run:([t,e,n,s,i,o,r],a)=>{t>=0&&e>=0&&n>=0&&s>0&&i>0&&o>=0&&o<=1&&Number.isSafeInteger(r)&&r>=0&&r<=1e4||V_("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<s?0:1+Math.floor((c-s)/i);l>r&&V_("RESOURCE_LIMIT",a,`count=${l}, limit=${r}`,{reason:"copies-over-limit",count:l,limit:r});const h=l?c-s-(l-1)*i:0;return[{centers:Array.from({length:l},(t,n)=>e+s/2+o*h+n*i),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>(sx(t,[K_,Y_,Y_,Y_,Y_,q_,K_],e),[{kind:"layout"}]),run:([t,e,n,s,i,o,r],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(r)&&r>=0&&r<=1e4&&e>=0&&n>=0&&s>=0&&i>0&&o>=0&&o<=1||V_("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>r&&V_("RESOURCE_LIMIT",a,"fixed count exceeds limit",{reason:"copies-over-limit",count:t,limit:r}),!t)return[{centers:[],count:0}];const c=e-n-s-i;return(c<0||t>1&&c/(t-1)<i)&&V_("NO_SPACE",a,"fixed count non-overlapping items do not fit",{reason:"row-does-not-fit",count:t,length:e-n-s,extent:i}),[{centers:1===t?[n+i/2+o*c]:Array.from({length:t},(e,s)=>n+i/2+s*c/(t-1)),count:t}]}},"assembly@1":{ports:["assembly"],types:(t,e)=>(t.length&&!t.some(e=>"placed"!==e.kind&&"collection"!==e.kind||e.frame!==t[0].frame)||V_("FRAME_TYPE",e,"assembly members need one common frame"),[{kind:"assembly",frame:t[0].frame}]),run:(t,e,n)=>[{members:t.flatMap((t,e)=>t.items?t.items.map(t=>({key:t.key,path:t.path,shape:t.shape,pose:t.pose})):[{key:n.args[e],...t}])}]},"repeat@1":{ports:["collection"],params:["axis"],optionalParams:["riseAxis","within"],types(t,e,n){["x","y","z"].includes(n.params.axis)||V_("AXIS",e,n.params.axis);const s=4===t.length;return!s||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&Q_(t[3],Y_)||V_("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!s||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&V_("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,s],i,o)=>{t.count*e.members.length>U_&&V_("RESOURCE_LIMIT",i,"expanded geometry count > 10000",{reason:"geometry-over-limit",count:t.count*e.members.length,limit:U_});const r=["x","y","z"].indexOf(o.params.axis),a=["x","y","z"].indexOf(o.params.riseAxis),c=[];for(let i=0;i<t.count;i++)for(const l of e.members){const e=[0,0,0];e[r]=t.centers[i],void 0!==s&&(e[a]=i*s);const h=[o.id,i,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:i,shape:l.shape,pose:px(px(n,{r:rx(),t:e}),l.pose)})}return[{items:c}]},geometry:(t,e,n)=>n.params.within?[]:e[0].items},"select-item@1":{ports:["placed"],params:["member"],types:(t,e)=>(2===t.length&&"collection"===t[0].kind&&Q_(t[1],K_)||V_("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,s)=>{const i=t.items.find(t=>t.index===e&&t.key===s.params.member);return i||V_("TARGET_ABSENT",n,`${s.params.member}[${e}]`),[{shape:i.shape,pose:i.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[Y_,Y_,Y_,X_,X_,X_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s,i,o])=>{const r=Math.cos(s),a=Math.sin(s),c=Math.cos(i),l=Math.sin(i),h=Math.cos(o),d=Math.sin(o);return[{r:dx(dx([[1,0,0],[0,r,-a],[0,a,r]],[[c,0,l],[0,1,0],[-l,0,c]]),[[h,-d,0],[d,h,0],[0,0,1]]),t:[t,e,n]}]}},"axis-turn@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[q_,q_,q_,X_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const o=Math.hypot(t,e,n);Math.abs(o-1)>1e-6&&V_("AXIS",i,"unit axis required");const r=t/o,a=e/o,c=n/o,l=Math.cos(s),h=Math.sin(s),d=1-l;return[{r:[[l+r*r*d,r*a*d-c*h,r*c*d+a*h],[a*r*d+c*h,l+a*a*d,a*c*d-r*h],[c*r*d-a*h,c*a*d+r*h,l+c*c*d]],t:[0,0,0]}]}},"axis-slide@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[q_,q_,q_,Y_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const o=Math.hypot(t,e,n);return Math.abs(o-1)>1e-6&&V_("AXIS",i,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/o*s,e/o*s,n/o*s]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(gx(t,e,2),t[1].to!==t[0].from&&V_("FRAME_TYPE",e,"composition intermediate frame mismatch"),[ox(t[1].from,t[0].to)]),run:([t,e])=>[px(t,e)]},"attach@1":{ports:["pose"],types(t,e){gx(t,e,3);const[n,s,i]=t;return n.from===s.to&&s.from===i.from||V_("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[ox(i.to,n.to)]},run:([t,e,n])=>[px(px(t,e),fx(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>(sx(t,[Y_,Y_,Y_],e),[{kind:"point",frame:n.params.frame}]),run:t=>[t]},"map-point@1":{ports:["point"],types:(t,e)=>(2===t.length&&"transform"===t[0].kind&&"point"===t[1].kind&&t[0].from===t[1].frame||V_("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[ux(hx(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&Q_(t[0],t[1])||V_("FRAME_TYPE",e,"distance requires points in same frame"),[Y_]),run:([t,e])=>[Math.hypot(...t.map((t,n)=>t-e[n]))]},"feature@1":{ports:["pose"],params:["frame","name"],types(t,e,n){1===t.length&&"shape"===t[0].kind&&t[0].faces||V_("TYPE",e,"shape required");const s=Object.keys(t[0].faces);return[...s,"centre",..."revolve"!==t[0].provider||s.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||V_("UNKNOWN_FEATURE",e,n.params.name),[ox(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const s=function(t,e){const n=B_(t),s=jv.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return s;const i=t.faces[e],o={x:0,y:1,z:2};if(i){const n=[...s];if(n[o[i.axis]]=i.at,t.loft)for(const e of Kv[t.loft.axis]){const s=t.loft.section.points.map(t=>t[e]);n[o[e]]=(Math.min(...s)+Math.max(...s))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,r=t.cavity,a=r.wall;for(const t of Kv[e.axis])t!==i.axis&&(n[o[t]]=s[o[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(i.axis!==e.axis){const t=e.start+("open"===r.start?0:r.start.closed),s=e.end-("open"===r.end?0:r.end.closed);n[o[e.axis]]=(t+s)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(p_).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]),i=t.find(([t])=>t===e);if(!i)return;const r=[...s];return r[o[i[1]]]=i[2]<0?n[i[1]].min:n[i[1]].max,r}}(t,n.params.name);return s||V_("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:s}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||V_("FRAME_TYPE",e,"shape local frame mismatch"),[{kind:"placed",frame:t[1].to}]),run:([t,e])=>[{shape:t,pose:e}],geometry:([t,e])=>({shape:t,pose:e})}}),ix["member@1"]={...ix["place@1"],geometry:void 0},Object.assign(ix,H_);for(const[t,e]of Object.entries(ix))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const yx=[];for(const[t,e]of Object.entries(ix))e.pure=!yx.includes(t);const bx=["add@1","mul@1","div@1","sin@1","geomean@1","curve@1","at-least@1","max@1","min@1","hypot@1","between@1","assembly@1","repeat@1","select-item@1","rigid@1","axis-turn@1","axis-slide@1","compose@1","attach@1","point@1","map-point@1","distance@1","place@1","member@1"];for(const[t,e]of Object.entries(ix))e.pure&&bx.includes(t)&&(e.poseForm="run");function vx(t,e,n){return Array.isArray(e)?ex(t,n):"flag"===e.kind?("boolean"!=typeof t&&V_("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&V_("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&Sx(t)?kx(t,n):"placed"===e.kind&&Mx(t,"shape","pose")&&Tx.has(t.shape)&&Sx(t.pose)?kx(t.pose,n):(Ex(t,n),"shape"===e.kind&&t&&"object"==typeof t&&Tx.add(t)),t)}function _x(t){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;if(Object.freeze(t),Array.isArray(t))for(let e=0;e<t.length;e++)_x(t[e]);else for(const e in t)_x(t[e]);return t}function xx(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(Sx(t)){const e=new Array(t.r.length);for(let n=0;n<e.length;n++)e[n]=Object.freeze(t.r[n].slice());n={r:Object.freeze(e),t:Object.freeze(t.t.slice())}}else if(Array.isArray(t)){n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=xx(t[s],e)}else{n={};for(const s in t)n[s]=xx(t[s],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(ix).filter(t=>!ix[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(ix).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(ix).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(ix));const wx=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],Mx=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let s=0;for(const i in t)if(Object.hasOwn(t,i)){if(s>1||i!==(0===s?e:n))return!1;s++}return 2===s},Sx=t=>Mx(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function Ax(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const s=t[n];"number"==typeof s?Number.isFinite(s)||V_("NON_FINITE",e,String(s)):Ex(s,e)}}function kx(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const s=t.r[n];Array.isArray(s)?Ax(s,e):Ex(s,e)}Ax(t.t,e)}function Ex(t,e){if("number"==typeof t)Number.isFinite(t)||V_("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&Ex(t[n],e);else if(t&&"object"==typeof t){const n=Object.keys(t);if(!(n.length<=2&&Array.isArray(t[n[0]])&&(n.length<2||Array.isArray(t[n[1]])))&&Tx.has(t))return;for(let s=0;s<n.length;s++)Ex(t[n[s]],e)}}const Tx=new WeakSet,Cx=["transform","placed","assembly","collection","point"],Ox=t=>Array.isArray(t)||Cx.includes(t?.kind)?void 0:String(t?.kind??"value");function Px(t){return function(t){Z_(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||V_("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||V_("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,s=new Map,i=new Map,o=new Map,r=[],a=[],c=(t,e)=>{tx(t,e),n.has(t)&&V_("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)Z_(t,["id","unit"],["min","max","role"],"input"),c(t.id,"input"),s.set(t.id,nx(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&V_("SCHEMA",t.id,"unknown input role"),"state"===t.role&&i.set(t.id,new Set([t.id])),"state"!==t.role||void 0!==t.min&&void 0!==t.max||V_("SCHEMA",t.id,"a state input has a range"),void 0!==t.min&&ex(t.min,t.id),void 0!==t.max&&ex(t.max,t.id),void 0!==t.min&&void 0!==t.max&&t.min>t.max&&V_("RANGE",t.id,"min > max"),"count"===t.unit&&(void 0!==t.min&&vx(t.min,K_,t.id),void 0!==t.max&&vx(t.max,K_,t.id));for(const t of e.constants)Z_(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),s.set(t.id,nx(t.unit,t.id)[0]),vx(t.value,s.get(t.id),t.id);for(const t of e.nodes){Z_(t,["id","op","args","outputs"],["params"],"node"),tx(t.id,"node"),o.has(t.id)&&V_("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(ix,t.op)||V_("OPERATOR",t.id,t.op),ix[t.op].params?mx(t,ix[t.op].params,ix[t.op].optionalParams):Object.hasOwn(t,"params")&&V_("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||V_("SCHEMA",t.id,"args array required"),t.args.forEach(e=>tx(e,t.id)),Z_(t.outputs,ix[t.op].ports,[],t.id);for(const e of Object.values(t.outputs))c(e,t.id);o.set(t.id,t)}const l=new Set,h=new Set,d=[],u=t=>{h.has(t)&&V_("CYCLE",t,[...a,t].join(" -> ")),a.push(t),h.add(t),d.push({n:o.get(t),at:0,inputTypes:[]})};for(const t of o.keys())if(!l.has(t))for(u(t);d.length;){const t=d[d.length-1],e=t.n;if(t.at<e.args.length){const i=e.args[t.at];if(n.has(i)||V_("UNKNOWN_REFERENCE",e.id,i),!s.has(i)){u(n.get(i));continue}t.inputTypes.push(s.get(i)),t.at++;continue}const o=ix[e.op],c=o.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of i.get(t)??[])p.add(e);p.size&&(void 0===o.state&&V_("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===o.state&&V_("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),o.ports.forEach((t,n)=>s.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>i.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),r.push(e)}let p;const f=new Map,m=new Set(e.inputs.map(t=>t.id));function g(t){t&&"object"==typeof t&&!Array.isArray(t)||V_("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||V_("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||V_("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=ex(e,t.id);return(n<(t.min??-1/0)||n>(t.max??1/0))&&V_("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`,{reason:"value-outside-range",input:t.id,value:n,...void 0!==t.min?{min:t.min}:{},...void 0!==t.max?{max:t.max}:{}}),vx(n*nx(t.unit,t.id)[1],s.get(t.id),t.id)}function b(t,n){g(t);const i=new Map,o=[],a=new Map,c=new Set;for(const n of e.inputs)i.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)i.set(t.id,ex(t.value*nx(t.unit,t.id)[1],t.id));for(const t of r){const e=ix[t.op],n=t.args.map(t=>i.get(t)),r=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{i.set(t.outputs[e],vx(r[n],s.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const s=wx(e.geometry(n,r,t),t.id);a.set(t.id,s),o.push(...s)}}return{result:{values:Object.fromEntries(i),geometry:o},kept:{input:{...t},values:i,bodies:a}}}return{outputTypes:Object.fromEntries([...s].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...i].map(([t,e])=>[t,[...e].sort()])),order:r.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,s=0,i=[],o=0;const r=(t,e)=>{const n=e||t.length!==i.length||t.some((t,e)=>t!==i[e]);return n&&s++,i=t,n},a=(t,e)=>(r(t.geometry.map(t=>t.id),e),t),c=t=>{o++;const n=e;if(e=void 0,!n)return e=_(b(t).kept),a({values:{...e.values},geometry:e.geometry.slice()},!0);const s=A(t,n,!0);return e=n,a(s,!1)},l=(t,n)=>{const i=++o,a=e;e=void 0;const c=a?.fast;let l;a?(l=A(t,a,!1),e=a):(e=_(b(t).kept,!1),l=h().shapes);const d=e,u=[],p=[],f=[],m=[],g=new Int32Array(h().nodes.length);for(const t of h().shapes){g[t]=u.length;for(const e of d.bodies[t]??[])u.push(e.id),p.push(e.key),f.push(e.path?Object.freeze(e.path.slice()):void 0),m.push(e.index)}const y=r(u,!a),v=y?h().shapes:c?.wrote.size?[...new Set([...l,...c.wrote])].sort((t,e)=>t-e):l;let x=0;for(const t of v)x+=d.bodies[t]?.length??0;const w=new Int32Array(x),M=new Float64Array(12*x),S=new Array(x);let k=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[k]=g[t]+n,S[k]=e.shape??null;const s=12*k;if(e.pose){const t=e.pose.r,n=e.pose.t;M[s]=t[0][0],M[s+1]=t[0][1],M[s+2]=t[0][2],M[s+3]=t[1][0],M[s+4]=t[1][1],M[s+5]=t[1][2],M[s+6]=t[2][0],M[s+7]=t[2][1],M[s+8]=t[2][2],M[s+9]=n[0],M[s+10]=n[1],M[s+11]=n[2]}else M.fill(NaN,s,s+12);k++});const E=d.epoch,T=()=>{o!==i&&V_("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:s,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{T();const e=h().slot.get(t);return void 0===e&&V_("TARGET_ABSENT",t,"no such value"),xx(d.slots[e],new Map)},changed:t=>{T();const e=h().slot.get(t);return void 0!==e&&(y||d.mark[e]===E||!!c?.moved.has(e))}}},h=()=>v();return{evaluate:c,advance(i,r){if(e&&!r){const r=++o,a=e;e=void 0;const h=S(i,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{o!==r&&V_("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:s,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(i,h.why);return{kind:"evaluation",result:c(i),generation:s,why:h.why}}const a={code:!!e?r:"NOT_BOUND"};if(t.changes)return l(i,a);return{kind:"evaluation",result:c(i),generation:s,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||V_("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&V_("TARGET_ABSENT",t,"no such value");const s=e.fast;if(!s)return xx(e.slots[n],new Map);const i=h().nodes.find(t=>t.outs.includes(n));if(i&&s.wrote.has(i.index)&&!s.moved.has(n)){const t=i.op.run(i.args.map(t=>s.slots[t]),i.n.id,i.n);return xx(t[i.outs.indexOf(n)],new Map)}return xx(s.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],i=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>i(t.id)),e.constants.forEach(t=>i(t.id));const o=r.map((e,n)=>{const o=ix[e.op];return o.ports.forEach(t=>i(e.outputs[t])),{n:e,op:o,index:n,args:e.args.map(e=>t.get(e)),outs:o.ports.map(n=>t.get(e.outputs[n])),types:o.ports.map(t=>s.get(e.outputs[t]))}}),a=n.map(()=>[]);for(const t of o)for(const e of t.args)a[e].push(t.index);const c=t=>{const e=new Uint8Array(o.length),n=[...t];for(;n.length;){const t=n.pop();for(const s of a[t])e[s]||(e[s]=1,n.push(...o[s].outs))}const s=[];return e.forEach((t,e)=>t&&s.push(e)),s},l=o.filter(t=>!t.op.pure),h=[...new Set([...l.map(t=>t.index),...c(l.flatMap(t=>t.outs))])].sort((t,e)=>t-e);return p={keys:n,slot:t,nodes:o,readers:a,reach:e.inputs.map((t,e)=>c([e])),always:h,shapes:o.filter(t=>t.op.geometry).map(t=>t.index),shapeSlot:n.map(t=>"shape"===s.get(t)?.kind)},p}function _(t,n=!0){const s=v(),i=s.keys.map(e=>t.values.get(e));i.forEach((t,e)=>s.shapeSlot[e]&&_x(t));const o=s.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of s.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:o,shown:o.map(()=>{}),values:n,geometry:[],mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set(s.shapes.filter(t=>o[t])),slots:new Set(s.keys.keys())}}}const r=new Map,a=o.map(t=>t?.map(t=>xx(t,r))),c={};s.keys.forEach((t,e)=>c[t]=xx(i[e],r));const l=[];for(const t of s.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:o,shown:a,values:c,geometry:l,mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),i=f.get(n);if(i)return i;const o=v(),r=t.forbidden??{},a=new Set(t.external??[]),c=e.inputs.map((t,e)=>{const n=Ox(s.get(t.id));if(n)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:n};if(Object.hasOwn(r,t.id))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:r[t.id]};for(const n of o.reach[e]){const e=o.nodes[n];if(!e.op.poseForm)return{fast:!1,code:"UNSUPPORTED_OPERATOR",input:t.id,node:e.n.id,op:e.n.op};for(const[n,s]of e.outs.entries()){const i=Ox(e.types[n]);if(i)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:i};const a=o.keys[s];if(Object.hasOwn(r,a))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:r[a]}}}return{fast:!0}}),l=o.nodes.map(t=>"repeat@1"===t.n.op&&!t.n.params?.within&&t.outs.every(t=>!o.readers[t].length&&!a.has(o.keys[t]))),h={inputs:c,terminal:l,visits:new Map};return f.set(n,h),h}function w(t,e){const n=v();if(1===t.length)return n.reach[t[0]];const s=t.join();let i=e.visits.get(s);if(!i){const o=new Set;for(const e of t)for(const t of n.reach[e])o.add(t);i=[...o].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(s,i)}return i}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let s=0;for(const i of e.shapes)n[i]=s,s+=t.bodies[i]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:s,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,s){const i=v();g(t);const o=n.fast?.raw??n.raw,r=[],a=[];for(let n=0;n<e.inputs.length;n++){const s=e.inputs[n],i=t[s.id];i!==o[n]&&(a.push(y(s,i)),r.push(n))}for(const t of r)if(!s.inputs[t].fast)return{why:s.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;r.forEach((n,s)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[s],c.mark[n]=l});const h=w(r,s),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,s=e.t,i=12*p;d[p++]=t,u[i]=n[0][0],u[i+1]=n[0][1],u[i+2]=n[0][2],u[i+3]=n[1][0],u[i+4]=n[1][1],u[i+5]=n[1][2],u[i+6]=n[2][0],u[i+7]=n[2][1],u[i+8]=n[2][2],u[i+9]=s[0],u[i+10]=s[1],u[i+11]=s[2]};for(const t of h){const e=i.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const o=new Array(e.args.length);for(let t=0;t<e.args.length;t++)o[t]=c.slots[e.args[t]];if(s.terminal[t]){const[n,s,i,r]=o,a=["x","y","z"].indexOf(e.n.params.axis),h=["x","y","z"].indexOf(e.n.params.riseAxis);let d=c.mark[e.args[2]]!==l&&(void 0===e.args[3]||c.mark[e.args[3]]!==l)?c.prefix.get(t):void 0;if(!d){d=[];for(let t=0;t<n.count;t++){const e=[0,0,0];e[a]=n.centers[t],void 0!==r&&(e[h]=t*r),d.push(px(i,{r:rx(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of s.members){const s=px(d[t],n.pose);Ex(s,e.n.id),f(u++,s)}c.wrote.add(t);continue}const r=e.op.run(o,e.n.id,e.n);if(e.outs.forEach((t,n)=>{c.slots[t]=vx(r[n],e.types[n],e.n.id),c.mark[t]=l,c.moved.add(t)}),e.op.geometry){const n=e.op.geometry(o,r,e.n),s=Array.isArray(n)?n:[n];let i=c.start[t];for(const t of s)f(i++,t.pose);c.wrote.add(t)}}const m={kind:"poses",generation:0,bodies:d.slice(0,p),poses:u.slice(0,12*p),read:t=>{const e=i.slot.get(t);return void 0===e&&V_("TARGET_ABSENT",t,"no such value"),xx(c.slots[e],new Map)},changed:t=>{const e=i.slot.get(t);return void 0!==e&&c.mark[e]===l}};return{result:m}}function A(t,n,s){const i=v();g(t),n.fast=void 0;const o=++n.epoch,r=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,s)=>{const i=t[e.id];i!==n.raw[s]&&(n.slots[s]=y(e,i),n.raw[s]=i,n.mark[s]=o,r.push(s),c>=0&&(l=!0),c=s)}),l||i.always.length){const t=[];for(const e of[...r.map(t=>i.reach[t]),i.always])for(const s of e)n.ran[s]!==o&&(n.ran[s]=o,t.push(s));a=t.sort((t,e)=>t-e)}else a=c>=0?i.reach[c]:[];const h=[];for(const t of a){const e=i.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===o))continue;const s=e.args.map(t=>n.slots[t]),a=e.op.run(s,e.n.id,e.n);e.outs.forEach((t,s)=>{n.slots[t]=vx(a[s],e.types[s],e.n.id),i.shapeSlot[t]&&_x(n.slots[t]),n.mark[t]=o,r.push(t)}),e.op.geometry&&(n.bodies[t]=wx(e.op.geometry(s,a,e.n),e.n.id),n.pending.nodes.add(t),h.push(t))}for(const t of r)n.pending.slots.add(t);if(!s){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of r)n.values[i.keys[t]]=void 0;return h}return k(n),{values:{...n.values},geometry:n.geometry.slice()}}function k(t){const e=v(),{nodes:n,slots:s}=t.pending;if(!n.size&&!s.size)return;const i=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>xx(t,i));for(const n of s)t.values[e.keys[n]]=xx(t.slots[n],i);if(n.size){const n=[];for(const s of e.shapes){const e=t.shown[s];e&&n.push(...e)}t.geometry=n}n.clear(),s.clear()}}(t)}const Ix="0.12.1",Dx=Object.freeze({x:"size.x",y:"size.y",z:"size.z"}),zx=["meet","flush","centre"],Rx=["revolute","prismatic"],jx=["seat","child-face","child-centre"];function $x(t){const e=t.mimic;return e&&"object"==typeof e?Object.hasOwn(e,"sum")?Array.isArray(e.sum)?e.sum:[]:[{motion:e.motion,multiplier:e.multiplier}]:[]}const Lx=t=>{const e=Fx(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)};function Fx(t){if(!t||"object"!=typeof t)return;if(Object.hasOwn(t,"sum")){const e=t;return{terms:e.sum,plus:e.plus??0,sum:!0}}const e=t;return{terms:[{from:e.from,...void 0!==e.times?{times:e.times}:{}}],plus:e.plus??0,sum:!1}}const Nx=(t,e,n,s)=>{throw new Xv(t,e,n,s)},Hx=(t,e)=>t.nodes.find(t=>t.id===e),Bx=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function Gx(t,e){const n=(t,e)=>({terms:[...t.terms,...e.terms],c:t.c+e.c}),s=e=>t.constants.find(t=>t.id===e&&"ratio"===t.unit)?.value,i=(e,o,r)=>{const a=(e=>t.constants.find(t=>t.id===e)?.value)(e);if(void 0!==a)return{terms:[],c:a*o};const c=r<256?Bx(t,e):void 0;if("add@1"===c?.op)return c.args.reduce((t,e)=>n(t,i(e,o,r+1)),{terms:[],c:0});if("mul@1"===c?.op){const[t,e]=c.args;if(void 0!==s(e))return i(t,o*s(e),r+1);if(void 0!==s(t))return i(e,o*s(t),r+1)}return{terms:[{ref:e,k:o}],c:0}},o=e.terms.reduce((t,e)=>n(t,i(e.ref,e.k,0)),{terms:[],c:e.c}),r=new Map;for(const t of o.terms)r.set(t.ref,(r.get(t.ref)??0)+t.k);return{terms:[...r].filter(([,t])=>0!==t).map(([t,e])=>({ref:t,k:e})),c:o.c}}function Ux(t,e){const n=Hx(t,e);if("member@1"!==n?.op||Hx(t,`${e}.repeat`))return;const s=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return s?String(s.id).replace(/\.assembly$/,""):void 0}function Vx(t,e,n){const s=Hx(t,e),i="member@1"===s?.op&&(!!Hx(t,`${e}.repeat`)||void 0!==Ux(t,e));s&&("place@1"===s.op||i)||Nx("TARGET_ABSENT",n,`${e} is not a placed part`);const o=Bx(t,s.args[0]);o||Nx("TARGET_ABSENT",n,`${e} has no shape`);const r=Hx(t,`${e}.pose`);return r&&"rigid@1"===r.op||Nx("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:s,shape:o,pose:r}}function Wx(t,e){const n=new Set([...t.nodes.map(t=>t.id),...t.nodes.flatMap(t=>Object.values(t.outputs)),...t.constants.map(t=>t.id),...t.inputs.map(t=>t.id)]);return t=>{let s=`${e}.${t}`;for(let i=2;n.has(s)||n.has(`${s}.value`);i++)s=`${e}.${t}.${i}`;return n.add(s),n.add(`${s}.value`),s}}function Yx(t,e,n,s){const i=t.constants.find(t=>t.unit===e&&t.value===n);if(i)return i.id;const o=`${s}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:o,unit:e,value:n}),o}function qx(t,e,n,s,i,o){let r=n;if(1!==s){const n=e(`${o}.times`);t.nodes.push({id:n,op:"mul@1",args:[r,Yx(t,"ratio",s,"k")],outputs:{value:`${n}.value`}}),r=`${n}.value`}if(0!==i){const n=e(`${o}.plus`);t.nodes.push({id:n,op:"add@1",args:[r,Yx(t,"mm",i,"d")],outputs:{value:`${n}.value`}}),r=`${n}.value`}return r}function Xx(t,e,n,s,i,o){if(void 0===s)return Yx(t,"mm",0,"d");if("number"==typeof s)return Number.isFinite(s)||Nx("SCHEMA",o,"a finite length is required"),Yx(t,"mm",s,"d");s&&"object"==typeof s&&(Object.hasOwn(s,"sum")||s.from)||Nx("SCHEMA",o,"a length is a number of millimetres, or something to follow");const{terms:r,plus:a,sum:c}=Fx(s),l=Kx(t,e,r,a,o);return c?qx(t,n,Jx(t,n,l,`${i}.sum`),1,a,i):qx(t,n,l[0].ref,l[0].k,a,i)}function Kx(t,e,n,s,i){return Array.isArray(n)&&n.length||Nx("SCHEMA",i,"a sum has one term or more"),Number.isFinite(s)||Nx("SCHEMA",i,"finite times and plus required"),n.map((s,o)=>{const r=n.length>1?`${i}.sum.${o}`:i;return s&&"object"==typeof s&&s.from||Nx("SCHEMA",r,"a length is a number of millimetres, or something to follow"),Number.isFinite(s.times??1)||Nx("SCHEMA",r,"finite times and plus required"),{ref:Qx(t,e,s.from,r),k:s.times??1}})}function Jx(t,e,n,s){const i=n.filter(t=>0!==t.k);if(!i.length)return Yx(t,"mm",0,"d");let o="";for(const[n,r]of i.entries()){const i=qx(t,e,r.ref,r.k,0,`${s}.${n}`);if(o){const r=e(`${s}.${n}.sum`);t.nodes.push({id:r,op:"add@1",args:[o,i],outputs:{value:`${r}.value`}}),o=`${r}.value`}else o=i}return o}function Qx(t,e,n,s){if(n&&"object"==typeof n||Nx("SCHEMA",s,"a dimension source is required"),"instance"===n.of){const i=`size.${n.axis}`;return t.inputs.some(t=>t.id===i)||Nx("TARGET_ABSENT",s,`the instance has no ${i}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const s=Hx(t,`sizing.size.${e}`);return s||Nx("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),s.outputs.value}(t,n.axis,s):i}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||Nx("TARGET_ABSENT",s,`${n.input} is not an input of this asset`),"state"===e.role&&Nx("EDIT_TARGET",s,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?Zx(t,n.part,n.axis,s):Nx("SCHEMA",s,`${String(n.of)} is not a dimension source`)}function Zx(t,e,n,s){const i=Vx(t,e,s).shape,o=I_(i);if(o){const r=o.edit[n];if("refused"in r)return Nx("EDIT_TARGET",s,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(r.sameAs)return Zx(t,e,r.sameAs,s);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(Hx(t,a))return c;const l=i.args[r.arg],h=Yx(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),i.args=i.args.map(t=>t===l?c:t);const d=Hx(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return Nx("EDIT_TARGET",s,`${e} is a ${i.op}; it is not a shape with measures`)}const tw=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role),ew=t=>new Set([...cw(t.mountingFace),...cw(t.document.capabilities),...cw(t.joints)]);let nw;const sw=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function iw(t,e,n){const s=t.document.model,i=nw&&nw.asset===t?nw.declared:void 0,o=i??ew(t);if(i&&sw){const n=ew(t);if(n.size!==i.size||[...n].some(t=>!i.has(t)))throw new Error(`the names held for the joint rewrite went stale at ${e}`)}const r=t=>s.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||o.has(t);if(r(e))return;const a=s.inputs.findIndex(t=>t.id===e);if(a>=0){if(e!==n)return;return s.inputs.splice(a,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const c=Bx(s,e);if(c&&"place@1"!==c.op&&!Object.values(c.outputs).some(t=>t!==e&&r(t))){s.nodes=s.nodes.filter(t=>t!==c);for(const e of c.args)iw(t,e)}}function ow(t,e){if(!Hx(t,`${e}.chain`)&&!Hx(t,`${e}.repeat`))return null;const n=Hx(t,`${e}.seat.rigid`)??Hx(t,`${e}.motion`),s=/^(.*)\.local$/.exec(String(n?.params?.to));return s&&s[1]!==e?s[1]:null}const rw=t=>Math.round(1e6*t)/1e6,aw=(t,e)=>t.inputs.find(t=>t.id===Dx[e]),cw=t=>{const e=[],n=t=>{if("string"==typeof t)e.push(t);else if(Array.isArray(t))for(const e of t)n(e);else if(t&&"object"==typeof t)for(const e of Object.values(t))n(e)};return n(t),e},lw=t=>!Array.isArray(t);function hw(t,e){const n="loft@1"===t.op?w_(t.params,t.id):g_(t.params,t.id),s=Object.values(n.arg.point??{}).map(t=>t[e]).filter(t=>void 0!==t),i=n.apex?.[e];return[...s,...void 0!==i?[i]:[]].map(e=>({ref:t.args[e],k:1}))}function dw(t,e,n){const{shape:s}=Vx(t,e,n),i=I_(s);if(i){const t={};for(const o of jv){const r=i.edit[o];if("refused"in r)return Nx("EDIT_TARGET",n,`${e} is a drawn section; its reach across is its points, not a measure this command can read`);t[o]={ref:s.args[r.arg],k:r.k}}return t}return Nx("EDIT_TARGET",n,`${e} is a ${s.op}; it is not a shape this command can measure`)}function uw(t,e,n){const[s,i]=vw[n].map(t=>e?.[t]);if(!s||!i||s.plane.length>1||i.plane.length>1)return;const[o,r]=[ww(t,s),ww(t,i)];if(JSON.stringify(o)===JSON.stringify(yw(r)))return;const a=(t,e)=>t[0]??{ref:e[0].ref,k:0};return o.length||r.length?[a(o,r),a(r,o)]:void 0}function pw(t,e,n){const s=t.constants.find(t=>t.id===n);if(s)return s.value;const i=t.inputs.find(t=>t.id===n);return i&&"state"!==i.role?e.designInputs[n]??null:null}function fw(t,e,n,s,i){const o=function(t,e,n,s){return Vx(t,n,s).pose.args.slice(3,6).map(n=>pw(t,e,n))}(t,e,n,s);if(o.every(t=>0===t))return[[1,0,0],[0,1,0],[0,0,1]];o.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&Nx("EDIT_TARGET",s,`${n} is turned (${(t=>jv.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", "))(o)}); only quarter turns keep its faces level with the axes`);const r=mw(o);if(i){const i=Vx(t,n,s).pose,r=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...o.map(e=>Yx(t,"deg",e,"a"))];for(const s of r)iw(e,s,tw(t,n,s)?s:void 0)}return r}function mw(t){const[e,n,s]=t.map(t=>t*Math.PI/180),i=t=>Math.round(Math.cos(t)),o=t=>Math.round(Math.sin(t)),r=[[1,0,0],[0,i(e),-o(e)],[0,o(e),i(e)]],a=[[i(n),0,o(n)],[0,1,0],[-o(n),0,i(n)]],c=[[i(s),-o(s),0],[o(s),i(s),0],[0,0,1]];return gw(gw(r,a),c)}const gw=(t,e)=>t.map(t=>e[0].map((n,s)=>t.reduce((t,n,i)=>t+n*e[i][s],0)));const yw=t=>t.map(t=>({ref:t.ref,k:-t.k})),bw=t=>t.map(t=>({ref:t.ref,k:t.k/2})),vw={x:["left","right"],y:["bottom","top"],z:["back","front"]};function _w(t,e,n){const{shape:s}=Vx(t,e,n),i=G_(s,t);return i||Nx("EDIT_TARGET",n,`${e} is a ${s.op}; it has no flat face to fasten by`),{shape:s,faces:i}}function xw(t,e){const n=jv.indexOf(t),s=0===n?1:0,i=3-n-s,o=(n+1)%3===s?1:-1,r=e*Math.PI/180,a=[0,0,0];return a[s]=Math.cos(r),a[i]=o*Math.sin(r),a}const ww=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function Mw(t,e,n){const{shape:s,faces:i}=_w(t,e,n),o={},r=I_(s,t).measure;for(const t of jv){const[e,n]=vw[t].map(t=>i[t]),a=r[t],c=a&&"profile"!==a?ww(s,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?ww(s,e):[...ww(s,n),...yw(c)],h=n?ww(s,n):[...ww(s,e),...c];o[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(yw(h))}}return o}const Sw=[[1,0,0],[0,1,0],[0,0,1]],Aw=t=>t[0].map((e,n)=>t.map(t=>t[n])),kw=(t,e)=>t.map(t=>t.reduce((t,n,s)=>t+n*e[s],0)),Ew={x:["y","z"],y:["z","x"],z:["x","y"]};function Tw(t){return gw(gw(Cw("z",t.z??0),Cw("y",t.y??0)),Cw("x",t.x??0))}function Cw(t,e){const n=Math.cos(e*Math.PI/180),s=Math.sin(e*Math.PI/180),[i,o]=Ew[t].map(t=>jv.indexOf(t)),r=[[1,0,0],[0,1,0],[0,0,1]];return r[i][i]=n,r[i][o]=-s,r[o][i]=s,r[o][o]=n,r}function Ow(t,e=!1){const n=t=>{const n=e?Math.round(180*t/Math.PI*1e12)/1e12:rw(180*t/Math.PI);return 0===n?0:n},s=Math.max(-1,Math.min(1,t[0][2]));return Math.abs(s)<1-1e-12?[n(Math.atan2(-t[1][2],t[2][2])),n(Math.asin(s)),n(Math.atan2(-t[0][1],t[0][0]))]:[n(Math.atan2(t[2][1],t[1][1])),n(Math.asin(s)),0]}(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const s of[0,90,180,270]){const i=mw([e,n,s]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===i[e][n])))||t.push(i)}})();const Pw=1e-12,Iw=t=>Math.abs(t)<Pw?0:Math.round(1e12*t)/1e12;function Dw(t){const e=new Map;for(const n of t)e.set(n.ref,(e.get(n.ref)??0)+n.k);return[...e].map(([t,e])=>({ref:t,k:Iw(e)})).filter(t=>0!==t.k)}const zw=(t,e=0)=>({terms:Dw(t),constant:Iw(e)}),Rw=t=>"terms"in t;function jw(t,e){return 1===e?t:Rw(t)?zw(t.terms.map(t=>({ref:t.ref,k:t.k*e})),t.constant*e):"add"in t?$w(...t.add.map(t=>jw(t,e))):"scaled"in t?jw(t.scaled,t.k*e):{scaled:t,k:Iw(e)}}function $w(...t){const e=t.flatMap(t=>"add"in t?t.add:[t]),n=e.filter(Rw),s=zw(n.flatMap(t=>t.terms),n.reduce((t,e)=>t+e.constant,0)),i=[],o=new Map;for(const t of e.filter(t=>!Rw(t))){const[e,n]="scaled"in t?[t.scaled,t.k]:[t,1];if(!("geomean"in e)){i.push(t);continue}const s=JSON.stringify(e);o.set(s,{part:e,k:(o.get(s)?.k??0)+n})}for(const t of o.values())0!==Iw(t.k)&&i.push(1===Iw(t.k)?t.part:{scaled:t.part,k:Iw(t.k)});return i.length?{add:[...s.terms.length||s.constant?[s]:[],...i]}:s}function Lw(t){const e=new Map(t.map(t=>[JSON.stringify(t),t])),n=[...e.values()];return 1===n.length?n[0]:{max:n}}function Fw(t,e){const n=t=>e[jv.indexOf(t)];if("box"===t.kind)return $w(...jv.filter(t=>Math.abs(n(t))>=Pw).map(e=>jw(n(e)>0?t.hi[e]:t.lo[e],n(e))));if("sphere"===t.kind){const e=Math.hypot(...jv.filter(e=>e!==t.axis).map(n));return Vw(t.radial,t.axial,e,n(t.axis))}const s=n(t.axis),i=e=>jw(t.ends[e],s);if("taper"===t.kind){const e=Math.hypot(...jv.filter(e=>e!==t.axis).map(n));return Lw([$w(i("lo"),jw(t.radii[0],e)),$w(i("hi"),jw(t.radii[1],e))])}const[o,r]=t.plane,a=n(o),c=n(r),l=([t,e])=>$w(jw(t,a),jw(e,c));if("loft"===t.kind){const e=t.points.map(t=>$w(l(t),i("lo"))),n=$w(i("hi"),l(t.apex));return Math.abs(a)<Pw&&Math.abs(c)<Pw?s>0?n:e[0]:Lw([...e,n])}const h=i(s>0?"hi":"lo");if("rounded"===t.kind){const e=$w(jw(t.across[0],Math.abs(a)/2),jw(t.corner[0],-Math.abs(a)),jw(t.across[1],Math.abs(c)/2),jw(t.corner[1],-Math.abs(c)));return $w(h,e,Vw(t.corner[0],t.corner[1],a,c))}return"ellipse"===t.kind?$w(h,Vw(t.radius[0],t.radius[1],a,c)):$w(h,Lw(t.points.map(l)))}function Nw(t,e,n,s){const i=Uw(t,e,s);if("taper"===i.kind)return{not:"taper"};if("rounded"===i.kind)return{not:"rounded"};if("sphere"!==i.kind&&"ellipse"!==i.kind)return{not:"flat"};const o="sphere"===i.kind?Object.fromEntries(jv.map(t=>[t,t===i.axis?i.axial:i.radial])):{[i.plane[0]]:i.radius[0],[i.plane[1]]:i.radius[1]},r=jv.filter(t=>o[t]&&Math.abs(n[jv.indexOf(t)])>1e-12),a=new Set(r.map(e=>(e=>{const n=Gx(t,Rw(e)?{terms:e.terms,c:e.constant}:{terms:[],c:NaN});return JSON.stringify([[...n.terms].sort((t,e)=>t.ref<e.ref?-1:t.ref>e.ref?1:0),n.c])})(o[e]))).size<=1,c={hypot:r.map(t=>jw(o[t],n[jv.indexOf(t)]))},l=Object.fromEntries(jv.map((t,e)=>r.includes(t)?[t,a?jw(o[t],n[e]):{quotient:[jw({product:[o[t],o[t]]},n[e]),c]}]:[t,zw([])]));return{point:l,..."ellipse"===i.kind?{push:{axis:i.axis,...i.ends}}:{}}}function Hw(t){if(Rw(t))return t.terms.map(t=>t.ref);if("scaled"in t)return Hw(t.scaled);return("add"in t?t.add:"max"in t?t.max:"hypot"in t?t.hypot:"product"in t?t.product:"quotient"in t?t.quotient:t.geomean).flatMap(Hw)}function Bw(t,e,n,s){return Fw(Uw(t,e,s),n)}function Gw(t,e){const n=function(t){const e=t=>zw([],t),n=()=>{const n=B_(t);return{kind:"box",lo:Object.fromEntries(jv.map(t=>[t,e(n[t].min)])),hi:Object.fromEntries(jv.map(t=>[t,e(n[t].max)]))}};if(t.extrusion){const s=t.extrusion,i=[...Kv[s.axis]],o={lo:e(s.start),hi:e(s.end)},r=s.section;if("rectangle"===r.kind){const[t,a]=i.map(t=>r.corner?.[t]??0);return t||a?{kind:"rounded",axis:s.axis,plane:i,ends:o,across:[e(r.size[i[0]]),e(r.size[i[1]])],corner:[e(t),e(a)]}:n()}return"ellipse"===r.kind?{kind:"ellipse",axis:s.axis,plane:i,ends:o,radius:[e(r.radius[i[0]]),e(r.radius[i[1]])]}:{kind:"polygon",axis:s.axis,plane:i,ends:o,points:r.points.map(t=>[e(t[i[0]]),e(t[i[1]])])}}if(t.loft){const n=t.loft,s=[...Kv[n.axis]];return{kind:"loft",axis:n.axis,plane:s,ends:{lo:e(n.start),hi:e(n.end)},points:n.section.points.map(t=>[e(t[s[0]]),e(t[s[1]])]),apex:[e(n.apex[s[0]]??0),e(n.apex[s[1]]??0)]}}if(t.revolution){const n=t.revolution;return"half-ellipse"===n.profile.kind?{kind:"sphere",axis:n.axis,radial:e(n.profile.radial),axial:e(n.profile.axial)}:{kind:"taper",axis:n.axis,ends:{lo:e(n.profile.start),hi:e(n.profile.end)},radii:[e(n.profile.startRadius),e(n.profile.endRadius)]}}return n()}(t),s=e.map(t=>-t);return{max:Ww(Fw(n,e),{}),min:-Ww(Fw(n,s),{})}}function Uw(t,e,n){const{shape:s}=Vx(t,e,n),i=I_(s,t),o=t=>zw([{ref:s.args[t],k:1}]),r=G_(s,t)??{},a=t=>{const[e,n]={x:["left","right"],y:["bottom","top"],z:["back","front"]}[t],i=[{ref:s.args[0],k:1}];return{lo:zw(r[e]?ww(s,r[e]):i),hi:zw(r[n]?ww(s,r[n]):[...i,{ref:s.args[1],k:1}])}},c=()=>{const s=Mw(t,e,n);return{kind:"box",lo:Object.fromEntries(jv.map(t=>[t,zw(s[t].lo)])),hi:Object.fromEntries(jv.map(t=>[t,zw(s[t].hi)]))}},l=t=>{const[e,n]=t.plane;return t.points.map(s=>[o(t.arg.point[s][e]),o(t.arg.point[s][n])])};if("extrude@1"===s.op){const t=g_(s.params,s.id),e=t.plane,n=a(t.axis);if("portal"===t.section||"rectangle"===t.section&&!t.rounded)return c();const i=()=>[o(t.arg.across[e[0]]),o(t.arg.across[e[1]])];return"rectangle"===t.section?{kind:"rounded",axis:t.axis,plane:e,ends:n,across:i(),corner:[o(t.arg.corner[e[0]]),o(t.arg.corner[e[1]])]}:"ellipse"===t.section?{kind:"ellipse",axis:t.axis,plane:e,ends:n,radius:i()}:{kind:"polygon",axis:t.axis,plane:e,ends:n,points:l(t)}}if("loft@1"===s.op){const t=w_(s.params,s.id),e=t.plane;return{kind:"loft",axis:t.axis,plane:e,ends:a(t.axis),points:l(t),apex:[o(t.apex[e[0]]),o(t.apex[e[1]])]}}if("revolve@1"===s.op){const t=s.params.axis;return"sphere"===i?.kind?{kind:"sphere",axis:t,radial:o(0),axial:o(1)}:{kind:"taper",axis:t,ends:a(t),radii:[o(2),o(3)]}}return c()}function Vw(t,e,n,s){return JSON.stringify(t)===JSON.stringify(e)?jw(t,Math.hypot(n,s)):function(t){const e=t.filter(t=>!(Rw(t)&&!t.terms.length&&!t.constant));if(1===e.length&&Rw(e[0])){const t=e[0];return zw(t.terms.map(t=>({ref:t.ref,k:Math.abs(t.k)})),Math.abs(t.constant))}return e.length?{hypot:e}:zw([])}([jw(t,n),jw(e,s)])}function Ww(t,e){if(Rw(t))return t.constant+t.terms.reduce((t,n)=>t+n.k*e[n.ref],0);if("scaled"in t)return t.k*Ww(t.scaled,e);if("product"in t)return Ww(t.product[0],e)*Ww(t.product[1],e);if("quotient"in t)return Ww(t.quotient[0],e)/Ww(t.quotient[1],e);if("geomean"in t)return Math.sqrt(Ww(t.geomean[0],e)*Ww(t.geomean[1],e));const n=("add"in t?t.add:"max"in t?t.max:t.hypot).map(t=>Ww(t,e));return"add"in t?n.reduce((t,e)=>t+e,0):"max"in t?Math.max(...n):Math.hypot(...n)}function Yw(t,e,n,s){const i=(n,s,i)=>{const o=e(i);return t.nodes.push({id:o,op:n,args:s,outputs:{value:`${o}.value`}}),`${o}.value`},o=(e,n)=>{if(Rw(e)){const s=e.terms.map((e,s)=>1===e.k?e.ref:i("mul@1",[e.ref,Yx(t,"ratio",e.k,"k")],`${n}.t${s}`));return!e.constant&&s.length||s.push(Yx(t,"mm",e.constant,"d")),1===s.length?s[0]:s.slice(1).reduce((t,e,s)=>i("add@1",[t,e],`${n}.s${s}`),s[0])}if("scaled"in e)return i("mul@1",[o(e.scaled,`${n}.x`),Yx(t,"ratio",e.k,"k")],n);if("product"in e)return i("mul@1",[o(e.product[0],`${n}.p0`),o(e.product[1],`${n}.p1`)],n);if("quotient"in e)return i("div@1",[o(e.quotient[0],`${n}.q0`),o(e.quotient[1],`${n}.q1`)],n);if("geomean"in e)return i("geomean@1",[o(e.geomean[0],`${n}.g0`),o(e.geomean[1],`${n}.g1`)],n);const s="add"in e?"add@1":"max"in e?"max@1":"hypot@1",r=("add"in e?e.add:"max"in e?e.max:e.hypot).map((t,e)=>o(t,`${n}.${e}`));return"add@1"===s?r.slice(1).reduce((t,e,s)=>i("add@1",[t,e],`${n}.a${s}`),r[0]):i(s,r,n)};return o(n,s)}const qw=(t,e)=>t.motion?.[e]?.id??(0===e?t.id:`${t.id}.${e+1}`);function Xw(t){return(Array.isArray(t.motion)?t.motion:[]).map((e,n)=>({...e,id:qw(t,n)}))}const Kw=t=>t.state?.id??t.id,Jw=(t,e)=>0===e?`${t}.motion`:`${t}.motion.${e+1}`;function Qw(t){return(t??[]).flatMap(t=>Xw(t).map((e,n)=>({joint:t,motion:e,k:n})))}const Zw=(t,e)=>jv.map(n=>n===t?e:0);function tM(t,e,n){const s=t.document.model,i=e.body1.part,o=n.path,r=e.body0,a=e.origin??{},c=a.facing??"meet";zx.includes(c)||Nx("JOINT_SCHEMA",`${o}.origin.facing`,`${String(c)} is not a facing; ${zx.join(", ")}`);const l="plane"in r,h=Wx(s,`${i}.on.${l?"plane":r.part}`);let d,u,p;const f={};let m,g;if("surface"in r){r.part===i&&Nx("ATTACH_CYCLE",o,"a part cannot be fastened to itself"),g=function(t,e,n,s){const i=`${s}.body0.surface`,{shape:o}=Vx(t,e,s),r=function(t,e,n){const{shape:s}=Vx(t,e,n);return"extrude@1"===s.op&&"ellipse"===s.params?.section?"around":"revolve@1"===s.op&&"half-ellipse"===s.params?.profile?"toward":void 0}(t,e,s),a="around"===r,c="toward"===r,l="revolve@1"===o.op?"a frustum, whose side turns with its slope (not taken yet, ADR-0140 3.9) -- fasten to its top or bottom":"flat faces only -- fasten to a face";a||c||Nx("ATTACH_FACE",i,`${e} has no curved surface to fasten to: ${l}`);const h=t=>{const e=Math.hypot(...t);return t.map(t=>t/e)},d=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]];let u,p;if("toward"in n){c||Nx("ATTACH_FACE",i,`${e} is a cylinder: a point on its side is { around, along }`),u=h(jv.map(t=>n.toward[t]??0));const t=jv.reduce((t,e,n)=>Math.abs(u[n])<Math.abs(u[t])-1e-12?n:t,0);p=h(jv.map((e,n)=>(n===t?1:0)-u[t]*u[n]))}else{a||Nx("ATTACH_FACE",i,`${e} is round: a point on it is { toward }`);const t=o.params.axis;u=h(xw(t,n.around)),p=Zw(t,1)}const f=d(p,u),m=jv.map((t,e)=>[p[e],u[e],f[e]].map(t=>Math.abs(t)<1e-12?0:t)),g=Nw(t,e,u,s);"not"in g&&Nx("ATTACH_FACE",i,`${e} has no curved surface to fasten to: ${l}`);const{point:y,push:b}=g;return{frame:m,point:y,along:{x:"along"in n?n.along:"centre",z:"centre"},...b?{push:b}:{}}}(s,r.part,r.surface,o),d="y",u=1,p=[];const t=g.push;t&&(f.x={lo:t.lo.terms,hi:t.hi.terms})}else if(l){const e=XS(t);d="wall"===e?"z":"y",u=1,p=[],"wall"===e&&"meet"!==c&&Nx("ATTACH_FACE",o,`the figure hangs on a wall; ${i} stands out of it (meet), not ${c}`),"centre"===c&&Nx("JOINT_SCHEMA",`${o}.origin.facing`,"a part stands on the mounting plane or hangs from it; its middle is not on it");for(const e of jv.filter(t=>t!==d))if(aw(s,e)){const n=Qx(s,t,{of:"instance",axis:e},o);f[e]={lo:[{ref:n,k:-.5}],hi:[{ref:n,k:.5}]}}}else{r.part===i&&Nx("ATTACH_CYCLE",o,"a part cannot be fastened to itself");const t=_w(s,r.part,o),e=Object.hasOwn(t.faces,String(r.face))?t.faces[r.face]:void 0;e||Nx("SCHEMA",o,`${r.part} has no face ${String(r.face)}; it has ${Object.keys(t.faces).join(", ")}`),"line"===e.contact&&Nx("ATTACH_FACE",o,`${r.part}'s ${String(r.face)} is the curved side of a cylinder; fasten to a point on it -- surface: { around, along } (ADR-0140 3.9)`),d=e.axis,u=e.normal,p=ww(t.shape,e);const n=Mw(s,r.part,o);for(const t of jv.filter(t=>t!==d))n[t]&&(f[t]={lo:n[t].lo,hi:n[t].hi});m=function(t,e,n,s){const{shape:i}=Vx(t,e,s),o=G_(i,t)?.[n],r=Uw(t,e,s);if(!o||"ellipse"!==r.kind&&"taper"!==r.kind||o.axis!==r.axis)return;if("ellipse"===r.kind)return{[r.plane[0]]:r.radius[0],[r.plane[1]]:r.radius[1]};const a=r.radii[o.normal<0?0:1];return Object.fromEntries(jv.filter(t=>t!==r.axis).map(t=>[t,a]))}(s,r.part,String(r.face),o)}const y=a.childRotate??{},b=g?gw(Aw(g.frame),Tw(y)):Tw(y),v=t=>Bw(s,i,kw(Aw(b),t),o),_=void 0===a.gap?zw([]):zw([{ref:Xx(s,t,h,a.gap,`gap.${d}`,o),k:1}]),[x,w]=[v(Zw(d,-u)),v(Zw(d,u))],M={},S={},A=zw(p);M[d]=$w(A,"meet"===c?jw($w(_,x),u):"flush"===c?jw($w(_,w),-u):jw($w(_,jw($w(x,jw(w,-1)),.5)),u)),S[d]="centre"===c?$w(M[d],jw($w(v(Zw(d,1)),jw(v(Zw(d,-1)),-1)),.5)):A;const k=jv.filter(t=>t!==d),E=t=>g?g.along[t]??"centre":a.align?.[t]??"centre",T=t=>"object"==typeof t&&!!t&&Object.hasOwn(t,"mm"),C={},O=e=>{const n=E(e);return C[e]??=T(n)?zw([{ref:Xx(s,t,h,n.mm,`align.${e}`,o),k:1}]):zw([])},P=m&&function(t,e,n,s,i,o,r){const{child:a,part:c,face:l,C:h,reach:d,path:u}=r,p=s.filter(t=>"min"===i(t)||"max"===i(t));if(!p.length)return;const f=`${c}'s ${l} is a disc`;2===p.length&&Nx("ATTACH_FACE",u,`${f}: ${a} touches its rim lined up on one axis, min or max; the other is the centre or a measured offset (ADR-0140 3.9)`);const m=p[0],g=s.find(t=>t!==m);"mesh@1"===Vx(e,a,u).shape.op&&Nx("ATTACH_FACE",u,`${f}: a mesh's footprint is not known, so ${a} cannot be lined up with its rim -- give the centre or a measured offset (ADR-0140 3.9)`);const y=jv.find(t=>!s.includes(t)),b=t=>kw(Aw(h),Zw(t,1)),v=zw([]),_=JSON.stringify(o(g))===JSON.stringify(v)?v:{max:[o(g),jw(o(g),-1)]},[x,w]=[n[m],n[g]],M=JSON.stringify(x)===JSON.stringify(w),S=(t,e)=>({geomean:[{max:[$w(t,jw(e,-1)),v]},$w(t,e)]});let A,k;if(function(t,e,n,s){const i=Uw(t,e,s);return("sphere"===i.kind||"taper"===i.kind||"ellipse"===i.kind&&JSON.stringify(i.radius[0])===JSON.stringify(i.radius[1]))&&Math.abs(Math.abs(n[jv.indexOf(i.axis)])-1)<1e-9}(e,a,b(y),u)){M||Nx("ATTACH_FACE",u,`${f} of two radii: a round part touches its rim at no closed-form place -- give the centre or a measured offset (ADR-0140 3.9)`);const t=$w(x,jw(d(Zw(m,1)),-1));A=[t,_],k=S(t,_)}else{const t=[0,1,2].some(t=>[m,g].some(e=>Math.abs(Math.abs(h[jv.indexOf(e)][t])-1)<1e-9));t||Nx("ATTACH_FACE",u,`${f}: ${a} is turned about its axis by other than a right angle, so its corners are not where its reaches say -- give the centre or a measured offset (ADR-0140 3.9)`);const e=t=>jw($w(d(Zw(t,1)),d(Zw(t,-1))),.5),n=$w(_,e(g));A=[w,n];const s=S(w,n);k=$w(M?s:{product:[{quotient:[x,w]},s]},jw(e(m),-1))}const E=function(t,e,n){const s=new Map,i=t=>{const n=Bx(e,t);if(n&&!s.has(n.id)){s.set(n.id,n);for(const t of n.args??[])i(t)}};for(const t of n.flatMap(Hw))i(t);return Px({...e,nodes:[...s.values()]}).evaluate({...t.designInputs,...t.stateDefaults}).values}(t,e,[...A,...M?[]:[x]]),[T,C]=A.map(t=>Ww(t,E));T-C>=-1e-9||Nx("ATTACH_FACE",u,`${f}: ${a} is wider than the disc where it would touch its rim (${Math.round(C)} mm across from its middle, ${Math.round(T)} mm there) -- give the centre or a measured offset (ADR-0140 3.9)`);return{middle:k}}(t,s,m,k,E,O,{child:i,part:String(r.part),face:String(r.face),C:b,reach:v,path:o});for(const t of k){const[e,n]=[v(Zw(t,1)),v(Zw(t,-1))],s=jw($w(e,jw(n,-1)),.5),a=E(t),c=f[t];if("min"!==a&&"max"!==a){if("centre"===a||T(a)){const e=zw(c?[...bw(c.lo),...bw(c.hi)]:[]);M[t]=$w(e,O(t),jw(s,-1))}else Nx("SCHEMA",o,`${String(a)} is not an alignment`);S[t]=$w(M[t],s)}else{if(c||Nx(l?"SCHEMA":"ATTACH_FACE",o,l?`the plane has no edges to line ${i} up with on ${t}; declare the figure's size, or give the centre or a measured offset`:`${r.part} has no edges along ${t} to line ${i} up with; give the centre or a measured offset`),P){const i=zw([...bw(c.lo),...bw(c.hi)]),o="min"===a?-1:1;M[t]=$w(i,jw(P.middle,o),jw(s,-1)),S[t]=$w(M[t],"min"===a?jw(n,-1):e);continue}M[t]="min"===a?$w(zw(c.lo),n):$w(zw(c.hi),jw(e,-1)),S[t]=zw("min"===a?c.lo:c.hi)}}const I=n.pivot??"seat";if("child-centre"===I)for(const t of jv)S[t]=$w(M[t],jw($w(v(Zw(t,1)),jw(v(Zw(t,-1)),-1)),.5));if("child-face"===I){const t=kw(Aw(b),Zw(d,-u)),e=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9),n="meet"===c&&e>=0?Mw(s,i,o):{},a=e>=0?n[jv[e]]:void 0;a||Nx("JOINT_SCHEMA",`${o}.origin.pivot`,`${i} meets ${l?"the plane":g?`${r.part}'s surface`:`${r.part}'s ${r.face}`} at a point or a line${"meet"===c?"":` (${c})`}, not by a face of its own; child-face has no face to turn about -- child-centre or seat`);const h=jv.map((s,i)=>i===e?t[e]>0?a.hi:a.lo:n[s]?[...bw(n[s].lo),...bw(n[s].hi)]:[]);jv.forEach((t,e)=>{S[t]=$w(M[t],...jv.map((t,n)=>zw(h[n].map(t=>({ref:t.ref,k:t.k*b[e][n]})))))})}const D=jv.map(t=>$w(M[t],jw(S[t],-1))),z=n.offset??{},R=t=>jv.map((e,n)=>$w(...jv.map((e,s)=>jw(t[s],g.frame[n][s])))),j=g?R(jv.map(t=>S[t])).map((t,e)=>$w(g.point[jv[e]],t)):jv.map(t=>S[t]),$=g?R(D):D,L=jv.map((e,n)=>void 0===z[e]||0===z[e]?j[n]:$w(j[n],zw([{ref:Xx(s,t,h,z[e],`offset.${e}`,`${o}.origin.offset.${e}`),k:1}]))),F=(t,e)=>Yw(s,h,t,e);nM(t,i,l?t.document.capabilities.assetFrame:`${r.part}.local`,{seat:L.map((t,e)=>F(t,`seat.${jv[e]}`)),pose:$.map((t,e)=>F(t,`pose.${jv[e]}`))});const{pose:N}=Vx(s,i,o),H=N.args.slice(3,6);N.args=[...N.args.slice(0,3),...Ow(g?Tw(y):b,!0).map(t=>Yx(s,"deg",t,"a"))];for(const e of H)iw(t,e,tw(s,i,e)?e:void 0);jv.some(t=>0!==(n.parentRotate?.[t]??0))&&eM(t,i,Tw(n.parentRotate),n.parentRotate,Sw)}function eM(t,e,n,s,i){const o=t.document.model,r=Hx(o,`${e}.seat.rigid`),a=t=>String(rw(t)).replace("-","m").replace(".","_"),c=(t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)))(i)?"":`.in.${Ow(Aw(i)).map(a).join("_")}`,l=`rotate.${jv.map(t=>a(s[t]??0)).join("_")}${c}`,h=Ow(n,!0),d=r.args.slice(3,6);r.args=[...r.args.slice(0,3),...jv.map((t,e)=>{const n=`${l}.${t}`;return o.constants.some(t=>t.id===n)||o.constants.push({id:n,unit:"deg",value:h[e]}),n})];for(const e of d)iw(t,e)}function nM(t,e,n,s){const i=t.document.model,{place:o,pose:r}=Vx(i,e,e),a=s?r.args.slice(0,3):[];s&&(r.args=[...s.pose,...r.args.slice(3)]),r.params={...r.params,to:`${e}.seat`};const c=sM(i,e),l=c.length>0,h=Yx(i,"mm",0,"d"),d=Yx(i,"deg",0,"a");let u=Hx(i,`${e}.seat.rigid`);u||(u={id:`${e}.seat.rigid`,op:"rigid@1",args:[h,h,h,d,d,d],outputs:{pose:`${e}.seat.value`},params:{}},i.nodes.push(u));const p=s?u.args.slice(0,3):[];s&&(u.args=[...s.seat,...u.args.slice(3)]),u.params={from:l?`${e}.joint`:`${e}.seat`,to:n};const f=function(t,e,n,s){const i=n.length,o=new Set,r=e=>{o.add(e.id);const n=Hx(t,e.id);return n?Object.assign(n,e):t.nodes.push(e),e.outputs.pose};let a=s;for(let t=i-1;t>=0;t--){const{motion:s,through:o,back:c}=n[t],l=t===i-1?`${e}.seat`:`${e}.joint.${t+1}`,h=0===t?`${e}.joint`:`${e}.joint.${t}`;let d=s.outputs.pose;if(o&&c){c.params={from:l,to:`${s.id}.axis`},s.params={...s.params,from:`${s.id}.axis`,to:`${s.id}.moved`},o.params={from:`${s.id}.moved`,to:h};const t=r({id:`${s.id}.about.turned`,op:"compose@1",args:[s.outputs.pose,c.outputs.pose],outputs:{pose:`${s.id}.about.turned.value`}});d=r({id:`${s.id}.about`,op:"compose@1",args:[o.outputs.pose,t],outputs:{pose:`${s.id}.about.value`}})}else s.params={...s.params,from:l,to:h};a=r({id:0===t?`${e}.turned`:`${e}.turned.${t+1}`,op:"compose@1",args:[d,a],outputs:{pose:(0===t?`${e}.turned`:`${e}.turned.${t+1}`)+".value"}})}const c=t=>t===`${e}.turned`||t.startsWith(`${e}.turned.`)||/\.about(\.turned)?$/.test(t)&&t.startsWith(`${e}.motion`);return t.nodes=t.nodes.filter(t=>!c(t.id)||o.has(t.id)),i?a:void 0}(i,e,c,r.outputs.pose);let m=Hx(i,`${e}.chain`);m||(m={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},i.nodes.push(m)),m.args=[u.outputs.pose,f??r.outputs.pose];const g=/^(.*)\.local$/.exec(n);let y=Hx(i,`${e}.world`);if(g&&g[1]!==e){const t=Hx(i,`${g[1]}.world`)?.outputs?.pose??Hx(i,`${g[1]}.chain`)?.outputs?.pose??Hx(i,`${g[1]}.turned`)?.outputs?.pose??Hx(i,`${g[1]}.pose`).outputs.pose;y?y.args=[t,m.outputs.pose]:(y={id:`${e}.world`,op:"compose@1",args:[t,m.outputs.pose],outputs:{pose:`${e}.world.value`}},i.nodes.push(y)),o.args=[o.args[0],y.outputs.pose]}else y&&(i.nodes=i.nodes.filter(t=>t!==y)),o.args=[o.args[0],m.outputs.pose];for(const n of[...a,...p])iw(t,n,tw(i,e,n)?n:void 0)}function sM(t,e){const n=[];for(let s=0,i=Hx(t,Jw(e,s));i;i=Hx(t,Jw(e,++s)))n.push({motion:i,through:Hx(t,`${i.id}.through`),back:Hx(t,`${i.id}.back`)});return n}function iM(t,e,n,s=1,i={k:0}){const o=t.document.model,r=e.part;Vx(o,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&Nx("SCHEMA",r,"a slide or a turn is required"),jv.includes(e.motion.axis)||Nx("SCHEMA",r,`${String(e.motion.axis)} is not an axis`),0===i.k&&Hx(o,`${e.part}.motion`),0===i.k&&Hx(o,`${e.part}.motion`)&&oM(t,{part:e.part});const a=Jw(e.part,i.k),c=e.motion.frame??"attachment",l=((t,e)=>{const n=ow(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame})(t,e.part);"asset"===c&&l!==t.document.capabilities.assetFrame?Nx("MOTION_FRAME",r,`${e.part} is fastened into ${l}; an axis in the asset frame would have to be re-expressed there, which this command does not do`):"attachment"!==c&&"asset"!==c&&Nx("SCHEMA",r,`${String(c)} is not a frame for the axis`);const h=e.state,d=Wx(o,a);let u=h?.id;if(n){if(n.sum)for(const[t,e]of n.terms.entries()){const n=d(`mimic.${t}`);if(o.nodes.push({id:n,op:"mul@1",args:[e.of,Yx(o,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=d(`mimic.${t}.sum`);o.nodes.push({id:e,op:"add@1",args:[u,`${n}.value`],outputs:{value:`${e}.value`}}),u=`${e}.value`}else u=`${n}.value`}else{const t=d("mimic");o.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,Yx(o,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),u=`${t}.value`}if(n.c){const t=d("mimic.offset"),s="slide"===e.motion.kind?"mm":"deg";o.nodes.push({id:t,op:"add@1",args:[u,Yx(o,s,n.c,"d")],outputs:{value:`${t}.value`}}),u=`${t}.value`}}else{h&&"string"==typeof h.id&&h.id.trim()||Nx("SCHEMA",r,"a state input id is required");const n=o.inputs.find(t=>t.id===h.id&&"state"===t.role&&t.unit===h.unit&&t.min===h.min&&t.max===h.max);if(n);else if(o.inputs.some(t=>t.id===h.id)){const e=o.nodes.some(t=>t.args.includes(h.id))||(t.drivers??[]).some(t=>t.state===h.id)||t.appearance.some(t=>t.visibility===h.id);if(e&&Nx("DUPLICATE_WRITER",r,`${h.id} already exists`),o.inputs=o.inputs.filter(t=>t.id!==h.id),delete t.stateDefaults[h.id],t.stateInputs?.[h.id]){const{[h.id]:e,...n}=t.stateInputs;t.stateInputs=n}}const s="turn"===e.motion.kind?["deg"]:["mm","ratio"];s.includes(h.unit)||Nx("SCHEMA",r,`a ${e.motion.kind} takes a ${s.join(" or ")} control, not ${String(h.unit)}`),Number.isFinite(h.min)&&Number.isFinite(h.max)&&h.max>h.min||Nx("SCHEMA",r,"a range with max above min is required");const i=h.start??h.min;i>=h.min&&i<=h.max||Nx("SCHEMA",r,"the starting value is outside the range"),n||(o.inputs.push({id:h.id,unit:h.unit,min:h.min,max:h.max,role:"state"}),t.stateDefaults[h.id]=i),void 0===h.label&&void 0===h.sweep||(t.stateInputs={...t.stateInputs??{}},t.stateInputs[h.id]={...void 0!==h.label?{label:h.label}:{},...void 0!==h.sweep?{sweep:h.sweep}:{}})}if("slide"===e.motion.kind&&"ratio"===h.unit){e.travel||Nx("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let s;if(Object.hasOwn(n,"sum")){const e=n.plus??0;s=qx(o,d,Jx(o,d,Kx(o,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?Qx(o,t,n.source,r):Yx(o,"mm",n.plus??0,"d");s=n.source?qx(o,d,e,n.times??1,n.plus??0,"travel"):e}const i=d("distance");o.nodes.push({id:i,op:"mul@1",args:[u,s],outputs:{value:`${i}.value`}}),u=`${i}.value`}else"slide"===e.motion.kind&&e.travel&&Nx("SCHEMA",r,"a mm control is the distance; travel would say it twice");const p=Array.isArray(s)?s.map(t=>Yx(o,"ratio",t,"axis")):jv.map(t=>Yx(o,"ratio",t===e.motion.axis?s:0,"axis"));o.nodes.push({id:a,op:"slide"===e.motion.kind?"axis-slide@1":"axis-turn@1",args:[...p,u],outputs:{pose:`${a}.value`},params:{from:`${e.part}.seat`,to:l}});const f=jv.map(t=>i.through?.[t]);if(f.some(t=>void 0!==t&&0!==t)){const e=f.map((e,n)=>Xx(o,t,d,e,`through.${jv[n]}`,`${i.path??r}.through.${jv[n]}`)),n=Yx(o,"deg",0,"a"),s=(t,e)=>o.nodes.push({id:`${a}.${t}`,op:"rigid@1",args:[...e,n,n,n],outputs:{pose:`${a}.${t}.value`},params:{}});s("through",e),s("back",e.map((t,e)=>Jx(o,d,[{ref:t,k:-1}],`back.${jv[e]}`)))}if(nM(t,e.part,l),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||Nx("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||Nx("SCHEMA",r,"a clip runs for a positive number of seconds"),t.drivers=[...t.drivers??[],{id:`${e.part}/${n.name}`,clip:n.name,state:h.id,time:{unit:"s",duration:n.duration},keys:structuredClone(n.keys),interpolation:"linear",loop:n.loop??"wrap",accumulates:n.accumulates??!1}]}return t}function oM(t,e){const n=t.document.model,s=sM(n,e.part);s.length||Nx("EDIT_TARGET",e.part,`${e.part} does not move`);const i=Hx(n,`${e.part}.seat.rigid`)?.params?.to??s[0].motion.params.to,o=s.map(({motion:t})=>{const e=t.args[3],s=n.inputs.find(t=>t.id===e&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(Bx(n,e)?.args??[]).includes(t.id));return{quantity:e,state:s}}),r=s.flatMap(({through:t,back:e})=>[t,e].filter(Boolean)),a=new Set([...s.map(t=>t.motion),...r]);n.nodes=n.nodes.filter(t=>!a.has(t)),nM(t,e.part,i);for(const e of r)for(const n of e.args)iw(t,n);for(const{quantity:e,state:s}of o)iw(t,e,e),s&&!n.nodes.some(t=>t.args.includes(s.id))&&(n.inputs=n.inputs.filter(t=>t!==s),delete t.stateDefaults[s.id],t.stateInputs&&delete t.stateInputs[s.id],t.drivers&&(t.drivers=t.drivers.filter(t=>t.state!==s.id)),t.drivers&&!t.drivers.length&&delete t.drivers,t.stateInputs&&!Object.keys(t.stateInputs).length&&delete t.stateInputs);return t}const rM={joint:((...t)=>t)("id","body0","body1","origin","motion","repeat"),motion:((...t)=>t)("id","type","axis","through","lowerLimit","upperLimit","travel","state","mimic"),body0:((...t)=>t)("part","face","surface","plane","at"),surface:((...t)=>t)("toward","around","along"),body1:((...t)=>t)("part","at"),origin:((...t)=>t)("facing","gap","align","childRotate","pivot","offset","parentRotate"),axes:((...t)=>t)("x","y","z"),alignment:((...t)=>t)("mm"),measure:((...t)=>t)("from","times","plus","sum"),term:((...t)=>t)("from","times"),source:((...t)=>t)("of","axis","input","part"),travel:((...t)=>t)("source","times","plus","sum"),state:((...t)=>t)("id","label","start","sweep"),mimic:((...t)=>t)("motion","multiplier","offset","sum"),leader:((...t)=>t)("motion","multiplier"),repeat:((...t)=>t)("axis","pitch","count","rise"),rise:((...t)=>t)("axis","mm")};const aM=t=>!!t.body0&&"at"in t.body0;function cM(t,e){if(!t||"object"!=typeof t)return;const n=jv.map(e=>t[e]);n.every(t=>"number"==typeof t&&Number.isFinite(t))||Nx("JOINT_SCHEMA",`${e}.axis`,"an axis vector is three finite numbers { x, y, z }");const s=Math.hypot(...n);return s>1e-9||Nx("JOINT_SCHEMA",`${e}.axis`,"an axis vector is not zero"),n.map(t=>t/s)}const lM=t=>jv.some(e=>0!==(t.origin?.parentRotate?.[e]??0));function hM(t,e){const n=t.origin??{},s=t.body0,i=t.body1;if("at"in s&&"origin"!==s.at&&Nx("JOINT_SCHEMA",`${e}.body0`,`${String(s.at)} is not a place on a part; at: 'origin' is`),"at"in i&&"origin"!==i.at&&Nx("JOINT_SCHEMA",`${e}.body1`,`${String(i.at)} is not a place on a part; at: 'origin' is`),"at"in s&&("face"in s||"plane"in s||"surface"in s)&&Nx("JOINT_SCHEMA",`${e}.body0`,"a joint hangs at a part's origin or on a face, not both"),"surface"in s&&function(t,e){const n=t.body0.surface,s=`${e}.body0.surface`;n&&"object"==typeof n||Nx("JOINT_SCHEMA",s,"a place on a surface is { toward } or { around, along }");const i="toward"in n&&void 0!==n.toward;if(i===("around"in n&&void 0!==n.around||"along"in n&&void 0!==n.along)&&Nx("JOINT_SCHEMA",s,"a place on a surface is { toward } on a round surface or { around, along } on a side, one of them"),i){const t=jv.map(t=>n.toward?.[t]??0);t.every(t=>"number"==typeof t&&Number.isFinite(t))||Nx("JOINT_SCHEMA",`${s}.toward`,"toward is three finite numbers { x, y, z }");const e=Math.hypot(...t);e>1e-9||Nx("JOINT_SCHEMA",`${s}.toward`,"toward is the outward normal there; a zero vector points nowhere"),Math.abs(e-1)>1e-5&&Nx("JOINT_SCHEMA",`${s}.toward`,`toward is a unit vector; this one is ${rw(e)} long`)}else"number"==typeof n.around&&Number.isFinite(n.around)||Nx("JOINT_SCHEMA",`${s}.around`,"around is the normal's angle about the push axis, in degrees"),void 0===n.along&&Nx("JOINT_SCHEMA",`${s}.along`,"along says where on the push: 'centre', 'min', 'max' or { mm }");void 0!==t.origin?.align&&Object.values(t.origin.align).some(t=>void 0!==t)&&Nx("JOINT_SCHEMA",`${e}.origin.align`,"on a surface the place is the surface's own words (toward, around, along), not align"),lM(t)&&Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,"on a surface the joint frame is the surface's there; it is not turned again")}(t,e),aM(t))for(const t of["align","gap","facing","childRotate","pivot"])void 0!==n[t]&&Nx("JOINT_SCHEMA",`${e}.origin.${t}`,`${t} places a part on a face; ${s.part}'s origin is a point and a frame, placed by offset and parentRotate`);else"at"in i&&Nx("JOINT_SCHEMA",`${e}.body1`,`a child is placed by its origin only at its parent's origin; ${"plane"in s?"the mounting plane":"surface"in s?`${s.part}'s surface`:`${s.part}'s ${String(s.face)}`} is a face`);if(void 0===n.pivot||jx.includes(n.pivot)||Nx("JOINT_SCHEMA",`${e}.origin.pivot`,`${String(n.pivot)} is not a pivot; ${jx.join(", ")}`),"child-face"===n.pivot&&"centre"===n.facing&&Nx("JOINT_SCHEMA",`${e}.origin.pivot`,`${i.part} is fastened by its middle, not by a face; child-face has no face to turn about -- it turns about its middle already (child-centre)`),void 0!==n.parentRotate){n.parentRotate&&"object"==typeof n.parentRotate&&!Object.values(n.parentRotate).some(t=>"number"!=typeof t||!Number.isFinite(t))||Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,"a rotation is degrees about x, y and z");const t=jv.filter(t=>"min"===n.align?.[t]||"max"===n.align?.[t]);t.length&&!(t=>t.every(t=>t.every(t=>Math.abs(t)<1e-9||Math.abs(Math.abs(t)-1)<1e-9)))(Tw(n.parentRotate))&&Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,`the joint frame is turned by other than quarter turns; ${i.part}'s sides are not level with the edges it is lined up with (${t.join(", ")}) -- place it by the centre or a distance`)}void 0===n.offset||n.offset&&"object"==typeof n.offset||Nx("JOINT_SCHEMA",`${e}.origin.offset`,"an offset is a length along x, y and z")}function dM(t,e){const n=t.document.model,s=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||Nx("JOINT_SCHEMA","joints","a joint has an id"),function(t,e){const n=(t,e,n)=>{if(t&&"object"==typeof t&&!Array.isArray(t))for(const[s,i]of Object.entries(t))void 0===i||e.includes(s)||Nx("JOINT_SCHEMA",n,`${s} is a field this kernel does not know`)},s=(t,e)=>n(t,rM.source,e),i=(t,e)=>{if(t&&"object"==typeof t&&(n(t,rM.measure,e),s(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[i,o]of t.sum.entries())n(o,rM.term,`${e}.sum.${i}`),s(o?.from,`${e}.sum.${i}.from`)};n(t,rM.joint,e),n(t.body0,rM.body0,`${e}.body0`);const o=t.body0?.surface;n(o,rM.surface,`${e}.body0.surface`),o&&"object"==typeof o&&(n(o.toward,rM.axes,`${e}.body0.surface.toward`),n(o.along,rM.alignment,`${e}.body0.surface.along`),i(o.along?.mm,`${e}.body0.surface.along.mm`)),n(t.body1,rM.body1,`${e}.body1`);const r=t.origin;if(n(r,rM.origin,`${e}.origin`),r&&"object"==typeof r){i(r.gap,`${e}.origin.gap`),n(r.childRotate,rM.axes,`${e}.origin.childRotate`),n(r.parentRotate,rM.axes,`${e}.origin.parentRotate`),n(r.offset,rM.axes,`${e}.origin.offset`);for(const[t,n]of Object.entries(r.offset&&"object"==typeof r.offset?r.offset:{}))i(n,`${e}.origin.offset.${t}`);n(r.align,rM.axes,`${e}.origin.align`);for(const[t,s]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(s,rM.alignment,`${e}.origin.align.${t}`),i(s?.mm,`${e}.origin.align.${t}.mm`)}void 0===t.motion||Array.isArray(t.motion)||Nx("JOINT_SCHEMA",`${e}.motion`,"a motion is a list of axes");for(const[o,r]of(Array.isArray(t.motion)?t.motion:[]).entries()){const t=`${e}.motion.${o}`;if(n(r,rM.motion,t),r&&"object"==typeof r){n(r.axis,rM.axes,`${t}.axis`),n(r.through,rM.axes,`${t}.through`);for(const[e,n]of Object.entries(r.through&&"object"==typeof r.through?r.through:{}))i(n,`${t}.through.${e}`);if(r.travel&&"object"==typeof r.travel&&(n(r.travel,rM.travel,`${t}.travel`),s(r.travel.source,`${t}.travel.source`),Array.isArray(r.travel.sum)&&i({sum:r.travel.sum},`${t}.travel`)),n(r.state,rM.state,`${t}.state`),n(r.mimic,rM.mimic,`${t}.mimic`),Array.isArray(r.mimic?.sum))for(const[e,s]of r.mimic.sum.entries())n(s,rM.leader,`${t}.mimic.sum.${e}`)}}n(t.repeat,rM.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(i(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,rM.rise,`${e}.repeat.rise`))}(e,s),e.body1&&"string"==typeof e.body1.part||Nx("JOINT_SCHEMA",s,"a joint carries a part (body1)"),Vx(n,e.body1.part,s),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||Nx("JOINT_SCHEMA",s,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&Vx(n,e.body0.part,s),hM(e,s);const i=(t.joints??[]).filter(t=>t.id!==e.id),o=i.find(t=>t.body1.part===e.body1.part);if(o&&Nx("JOINT_TREE",s,`${e.body1.part} already hangs from ${"part"in o.body0?o.body0.part:"the mounting plane"} by ${o.id}; a part has one joint above it`),"part"in e.body0){const t=t=>i.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&Nx("ATTACH_CYCLE",s,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const i=t(n);n=i&&"part"in i?i.part:void 0}}!function(t,e,n){const s=Xw(e),i=Qw(t).map(t=>t.motion),o=new Set([...i.map(t=>t.id),...t.map(t=>t.id)]);for(const[t,i]of s.entries()){const s=`${n}.motion.${t}`,r=e.motion[t];r&&"object"==typeof r||Nx("JOINT_SCHEMA",s,"an axis is { type, axis }"),Rx.includes(i.type)||Nx("JOINT_SCHEMA",s,`${String(i.type)} is not a motion; ${Rx.join(", ")}`),void 0===r.id||"string"==typeof r.id&&r.id.trim()||Nx("JOINT_SCHEMA",`${s}.id`,"an axis id is a name"),o.has(i.id)&&Nx("JOINT_SCHEMA",`${s}.id`,`${i.id} names another axis already; an axis id is unique among every joint's axes`),o.add(i.id),["X","Y","Z"].includes(i.axis)||cM(i.axis,s)||Nx("JOINT_SCHEMA",s,`a ${i.type} axis is X, Y or Z, or a vector { x, y, z }`);for(const[t,e]of Object.entries(i.through??{}))void 0===e||("number"==typeof e?Number.isFinite(e):Lx(e))||Nx("JOINT_SCHEMA",`${s}.through.${t}`,"the point an axis passes is millimetres, or a length that follows something");void 0!==i.travel&&"prismatic"!==i.type&&Nx("JOINT_SCHEMA",s,"only a prismatic axis travels a length");const a=void 0!==i.lowerLimit||void 0!==i.upperLimit;if("prismatic"===i.type&&i.travel&&!a&&(r.lowerLimit=0,r.upperLimit=1),!i.mimic&&(a||"prismatic"===i.type)){const[t,e]=[r.lowerLimit,r.upperLimit];Number.isFinite(t)&&Number.isFinite(e)&&t<e||Nx("JOINT_SCHEMA",s,`a ${i.type} axis has both limits, lower below upper`)}}for(const[t,e]of s.entries()){if(!e.mimic)continue;const o=`${n}.motion.${t}`;!Object.hasOwn(e.mimic,"sum")||Array.isArray(e.mimic.sum)&&e.mimic.sum.length||Nx("JOINT_SCHEMA",o,"a mimic sum follows one axis or more");const r=new Set;for(const t of $x(e)){const n=[...i,...s].find(n=>n.id===t?.motion&&n.id!==e.id);n||Nx("JOINT_SCHEMA",o,`${String(t?.motion)} is not a moving axis to follow`),r.has(n.id)&&Nx("JOINT_SCHEMA",o,`${n.id} is followed twice; a sum names each axis once`),r.add(n.id),n.mimic&&Nx("JOINT_SCHEMA",o,`${n.id} follows another axis; follow the one it follows`),"prismatic"===n.type!=("prismatic"===e.type)&&Nx("JOINT_SCHEMA",o,`${n.id} ${"prismatic"===n.type?"slides":"turns"}; an axis follows ones that move the same way: a slide a slide, a turn a turn`),Number.isFinite(t.multiplier)||Nx("JOINT_SCHEMA",o,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||Nx("JOINT_SCHEMA",o,"a mimic's offset is a number in the axis's unit")}}(i,e,s),void 0===e.origin?.childRotate||e.origin.childRotate&&"object"==typeof e.origin.childRotate&&!Object.values(e.origin.childRotate).some(t=>!Number.isFinite(t))||Nx("JOINT_SCHEMA",`${s}.origin.childRotate`,"a pose is degrees about x, y and z");const r=[...i,e],a=t=>r.find(e=>e.body1.part===t&&"part"in e.body0),c=t=>{for(let e=a(t);e;e=a(e.body0.part))if(e.repeat)return e};if(e.repeat){const t=e=>r.filter(t=>"part"in t.body0&&t.body0.part===e).flatMap(e=>[e.body1.part,...t(e.body1.part)]),n=[];for(let t=("part"in e.body0?c(e.body0.part):void 0);t;t="part"in t.body0?c(t.body0.part):void 0)n.push(t);const i=t(e.body1.part).map(t=>r.find(e=>e.body1.part===t)).filter(t=>t.repeat),o=[...n,...i].find(t=>t.repeat.axis===e.repeat.axis);o&&Nx("JOINT_SCHEMA",`${s}.repeat`,`${o.body1.part}'s row runs along ${o.repeat.axis} too; a row inside a row runs along another axis`,{reason:"row-same-axis",part:e.body1.part,outer:o.body1.part,axis:o.repeat.axis.toLowerCase()})}if(e.repeat){const n=e.repeat,i=`${s}.repeat`;"part"in e.body0||Nx("JOINT_SCHEMA",i,"a row fills the part it is fastened to; the mounting plane has no length to fill"),"surface"in e.body0&&Nx("JOINT_SCHEMA",i,"a row runs across a flat face, from edge to edge; one on a curved surface is not covered yet (ADR-0140 3.9)"),aM(e)&&Nx("JOINT_SCHEMA",i,"a row runs across the face it is fastened to; a joint placed at an origin has none");for(const t of["offset","parentRotate"])void 0!==e.origin?.[t]&&Nx("JOINT_SCHEMA",i,`a row with its joint frame moved or turned (origin.${t}) is not covered yet`);"seat"!==(e.origin?.pivot??"seat")&&Nx("JOINT_SCHEMA",i,`a row turning about ${e.origin.pivot} is not covered yet; its copies turn where they are fastened`),["X","Y","Z"].includes(n.axis)||Nx("JOINT_SCHEMA",i,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===function(t,e,n){if("plane"in n.body0)return"wall"===XS(e)?"z":"y";const s=t.nodes.find(t=>t.id===`${n.body0.part}.shape`);if("surface"in n.body0){const t=n.body0.surface;let e;return e="toward"in t?jv.map(e=>t.toward[e]??0):xw(s?.params?.axis??"y",t.around),jv.reduce((t,n,s)=>Math.abs(e[s])>Math.abs(e[jv.indexOf(t)])+1e-9?n:t,jv[0])}return"face"in n.body0?G_(s,t)?.[n.body0.face]?.axis??void 0:void 0}(t.document.model,t,e)&&Nx("JOINT_SCHEMA",i,`a row runs across the face it is fastened to; ${n.axis} is out of that face`),("number"==typeof n.pitch?Number.isFinite(n.pitch)&&n.pitch>0:Lx(n.pitch))||Nx("GEOMETRY_DOMAIN",i,"a row has a positive pitch, or one that follows a length"),void 0===n.count||Number.isSafeInteger(n.count)&&n.count>=1&&n.count<=Bv||Nx("GEOMETRY_DOMAIN",i,"a row has 1 to 100 copies",{reason:"row-copies-out-of-range",count:n.count,min:1,max:Bv}),void 0!==n.rise&&(n.rise&&["X","Y","Z"].includes(n.rise.axis)&&n.rise.axis!==n.axis||Nx("JOINT_SCHEMA",`${i}.rise`,`a row rises along X, Y or Z other than the one it runs along (${n.axis})`),Number.isFinite(n.rise.mm)&&0!==n.rise.mm||Nx("GEOMETRY_DOMAIN",`${i}.rise`,"a rise is a length in mm, not zero"))}}function uM(t,e){if(aM(e))return function(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,o=`joints.${e.id}`,{pose:r}=Vx(n,s,s),a=Yx(n,"deg",0,"a"),c=r.args.slice(3,6);r.args=[...r.args.slice(0,3),a,a,a];for(const e of c)iw(t,e,tw(n,s,e)?e:void 0);const l=Wx(n,`${s}.on.${i}`),h=Yx(n,"mm",0,"d"),d=t=>{if("at"in e.body1)return h;const i=e=>Bw(n,s,jv.map(n=>n===t?e:0),o);return Yw(n,l,jw($w(i(1),jw(i(-1),-1)),-.5),`own-centre.${t}`)},u=e.origin?.offset??{},p=jv.map(e=>void 0===u[e]?h:Xx(n,t,l,u[e],`offset.${e}`,`${o}.origin.offset.${e}`));nM(t,s,`${i}.local`,{seat:p,pose:jv.map(d)}),lM(e)&&eM(t,s,Tw(e.origin.parentRotate),e.origin.parentRotate,Sw)}(t,e),pM(t,e,Sw);tM(t,e,{pivot:e.origin?.pivot,offset:e.origin?.offset,parentRotate:e.origin?.parentRotate,path:`joints.${e.id}`}),pM(t,e,Sw)}function pM(t,e,n){const s=t.document.model,i=e.body1.part,o="part"in e.body0?e.body0.part:void 0,r=`joints.${e.id}`,a=Xw(e).map((t,e)=>({a:t,k:e})).sort((t,e)=>Number(!!t.a.mimic)-Number(!!e.a.mimic)||t.k-e.k);for(const{a:e,k:c}of a){const a=`${r}.motion.${c}`,l="prismatic"===e.type?"slide":"turn",h="prismatic"===e.type?e.travel?"ratio":"mm":"deg",d=void 0!==e.lowerLimit&&void 0!==e.upperLimit?{min:e.lowerLimit,max:e.upperLimit}:"revolute"===e.type?{min:-180,max:180}:{min:0,max:1},u=$x(e).map(e=>({leader:fM(t,e.motion),k:e.multiplier})),p=cM(e.axis,a),f=kw(n,p??jv.map(t=>t===e.axis.toLowerCase()?1:0)),m=p?0:f.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);m<0&&Nx("JOINT_SCHEMA",a,`${o} stands twisted; the axis ${e.axis} is not level with an axis in it`);const g=p?f.map(t=>Math.abs(t)<1e-12?0:Math.round(1e12*t)/1e12):f[m]>0?1:-1;iM(t,{part:i,motion:{kind:l,axis:jv[m]},state:{id:Kw(e),unit:h,min:d.min,max:d.max,start:e.state?.start??Math.min(d.max,Math.max(d.min,0)),...void 0!==e.state?.label?{label:e.state.label}:{},...void 0!==e.state?.sweep?{sweep:e.state.sweep}:{}},...e.travel?{travel:e.travel}:{}},e.mimic?{terms:u.map(({leader:t,k:e})=>({of:Hx(s,Jw(t.joint.body1.part,t.k))?.args[3]??Kw(t.motion),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,g,{k:c,through:e.through,path:a})}e.repeat&&function(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,o=`joints.${e.id}.repeat`,r=e.repeat.axis.toLowerCase(),a=jv.indexOf(r),c=Mw(n,i,o)[r];c||Nx("EDIT_TARGET",o,`${i} has no two faces along ${r}; there is no length to fill`);const l=Tw(e.origin?.childRotate??{}),h=t=>Bw(n,s,kw(Aw(l),jv.map(e=>e===r?t:0)),o),[d,u]=[h(1),h(-1)],{place:p,pose:f}=Vx(n,s,o),m=Hx(n,`${s}.seat.rigid`),g=Wx(n,`${s}.row`),y=Yx(n,"mm",0,"d");m.args=m.args.map((t,e)=>e===a?Jx(n,g,c.lo,"start"):t);const b=Yw(n,g,jw($w(d,jw(u,-1)),-.5),"own-centre");f.args=f.args.map((t,e)=>e===a?b:t);const v=Jx(n,g,[...c.hi,...yw(c.lo)],"length"),_=Yw(n,g,$w(d,u),"extent"),x=Yx(n,"ratio",.5,"k"),w=Yx(n,"count",Bv,"limit"),M=e.repeat.count;n.nodes.push(void 0===M?{id:`${s}.layout`,op:"fit-pitch@1",args:[v,y,y,_,Xx(n,t,g,e.repeat.pitch,"pitch",o),x,w],outputs:{layout:`${s}.layout.value`}}:{id:`${s}.layout`,op:"fixed-count@1",args:[Yx(n,"count",M,"count"),v,y,y,_,x,w],outputs:{layout:`${s}.layout.value`}}),p.op="member@1",p.args=[p.args[0],Hx(n,`${s}.turned`)?.outputs?.pose??f.outputs.pose],n.nodes.push({id:`${s}.assembly`,op:"assembly@1",args:[p.outputs.placed],outputs:{assembly:`${s}.assembly.value`}});const S=Hx(n,`${i}.world`)?.outputs?.pose??Hx(n,`${i}.chain`)?.outputs?.pose??Hx(n,`${i}.turned`)?.outputs?.pose??Hx(n,`${i}.pose`)?.outputs?.pose;let A=m.outputs.pose;S&&(n.nodes.push({id:`${s}.row`,op:"compose@1",args:[S,m.outputs.pose],outputs:{pose:`${s}.row.value`}}),A=`${s}.row.value`);n.nodes=n.nodes.filter(t=>t.id!==`${s}.chain`&&t.id!==`${s}.world`);const k=e.repeat.rise;n.nodes.push({id:`${s}.repeat`,op:"repeat@1",args:[`${s}.layout.value`,`${s}.assembly.value`,A,...k?[Yx(n,"mm",k.mm,"rise")]:[]],outputs:{collection:`${s}.repeat.value`},params:{axis:r,...k?{riseAxis:k.axis.toLowerCase()}:{}}})}(t,e)}const fM=(t,e)=>Qw(t.joints).find(t=>t.motion.id===e);function mM(t,e){const n=t.document.model,s=e.body1.part;!function(t,e){const n=t.document.model,s=Hx(n,e);if("member@1"!==s?.op||!Hx(n,`${e}.repeat`))return;const i=Hx(n,`${e}.layout`),o=Hx(n,`${e}.repeat`)?.args[3],r=new Set([`${e}.layout`,`${e}.assembly`,`${e}.repeat`,`${e}.row`]),a=n.nodes.filter(t=>r.has(t.id)||t.id.startsWith(`${e}.row.`));n.nodes=n.nodes.filter(t=>!a.includes(t)),s.op="place@1";for(const e of[...i?.args??[],...o?[o]:[]])iw(t,e)}(t,s),Hx(n,`${s}.motion`)&&oM(t,{part:s});const{pose:i,place:o}=Vx(n,s,s),r=new Set([`${s}.seat.rigid`,`${s}.chain`,`${s}.world`,`${s}.turned`]);n.nodes=n.nodes.filter(t=>!r.has(t.id)&&!t.id.startsWith(`${s}.on.`));const a=Yx(n,"mm",0,"d"),c=i.args.slice(0,3);i.args=[a,a,a,...i.args.slice(3)],i.params={...i.params,to:t.document.capabilities.assetFrame};for(const e of c)iw(t,e,tw(n,s,e)?e:void 0);o.args=[o.args[0],i.outputs.pose]}function gM(t){const e=[];void 0!==t.origin?.gap&&e.push({at:"gap",get:()=>t.origin.gap,set:e=>t.origin.gap=e}),t.repeat&&e.push({at:"pitch",get:()=>t.repeat.pitch,set:e=>t.repeat.pitch=e});for(const[n,s]of(t.motion??[]).entries()){if(s.travel){const t=s.travel;e.push({at:`motion.${n}.travel`,get:()=>Object.hasOwn(t,"sum")?{sum:t.sum,...void 0!==t.plus?{plus:t.plus}:{}}:t.source?{from:t.source,...void 0!==t.times?{times:t.times}:{},...void 0!==t.plus?{plus:t.plus}:{}}:t.plus??0,set:t=>{const e=Fx(t);s.travel=e?e.sum?{sum:e.terms,...e.plus?{plus:e.plus}:{}}:{source:e.terms[0].from,...void 0!==e.terms[0].times?{times:e.terms[0].times}:{},...void 0!==t.plus?{plus:t.plus}:{}}:{plus:t}}})}for(const t of Object.keys(s.through??{}))void 0!==s.through[t]&&e.push({at:`motion.${n}.through.${t}`,get:()=>s.through[t],set:e=>s.through[t]=e})}for(const n of Object.keys(t.origin?.align??{})){const s=t.origin.align[n];s&&"object"==typeof s&&Object.hasOwn(s,"mm")&&e.push({at:`align.${n}`,get:()=>s.mm,set:t=>s.mm=t})}for(const n of Object.keys(t.origin?.offset??{}))void 0!==t.origin.offset[n]&&e.push({at:`offset.${n}`,get:()=>t.origin.offset[n],set:e=>t.origin.offset[n]=e});return e}function yM(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:s}of gM(n))for(const i of Fx(s())?.terms??[])"part"===i?.from?.of&&Zx(t.document.model,i.from.part,i.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],s=new Map(t.map(t=>[t.body1.part,t])),i=new Map(Qw(t).map(t=>[t.motion.id,t.joint.id]));for(;n.length<t.length;){const o=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?s.get(t.body0.part):void 0,o=Xw(t).flatMap(t=>$x(t).map(t=>i.get(t.motion)));return(!n||e.has(n.id))&&o.every(n=>n===t.id||e.has(n))});o.length||Nx("JOINT_TREE","joints","the joints do not make a tree");for(const t of o)e.add(t.id),n.push(t)}return n}(e),s={...t.stateDefaults};!function(t,e){const n=nw;nw={asset:t,declared:ew(t)};try{e()}finally{nw=n}}(t,()=>{for(const e of t.document.model.nodes)"member@1"!==e.op||Hx(t.document.model,`${e.id}.repeat`)||(e.op="place@1");const i=t.document.model,o=new Set(i.nodes.filter(t=>e.some(e=>t.id.startsWith(`${e.body1.part}.on.`))).flatMap(t=>t.args));for(const e of[...n].reverse())mM(t,e);for(const e of n)uM(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const s=Hx(n,`${t.body1.part}.assembly`),i=o=>{for(const r of e.filter(t=>"part"in t.body0&&t.body0.part===o)){if(r.repeat){const e=Hx(n,`${r.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},s.args.push(e.outputs.collection);continue}const e=Hx(n,r.body1.part);e.op="member@1",s.args.push(e.outputs.placed),i(r.body1.part)}};i(t.body1.part)}}(t,e);for(const e of o){const n=i.nodes.find(t=>"place@1"===t.op&&e.startsWith(`${t.id}.`))?.id;n&&tw(i,n,e)&&iw(t,e,e)}for(const{motion:e}of Qw(n))e.mimic||void 0===s[Kw(e)]||(t.stateDefaults[Kw(e)]=s[Kw(e)])})}const bM=(t,e,n,s)=>{throw new Xv(t,e,n,s)},vM={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]};function _M(t,e,n){const{types:s,writers:i,model:o,assetFrame:r}=t;e&&"object"==typeof e&&!Array.isArray(e)||bM("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||bM("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||bM("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||bM("SCHEMA",n,"nonempty string required"),Object.hasOwn(s,t)||bM("TARGET_ABSENT",n,t),s[t]),c=a(e.placement),l=a(e.feature),h=i.get(e.placement),d=i.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=i.get(h.args[0]),e="repeat@1"===t?.op?i.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||bM("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=i.get(h.params.member),"member@1"!==p?.op&&bM("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),o.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&bM("TARGET_STATE",n,"binding target index must not change as animation state"),u={collection:h.args[0],index:h.args[1],member:h.params.member}}else"place@1"!==h?.op&&bM("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required","member@1"===h?.op?{reason:"surface-on-row",part:h.id,at:n}:void 0);"feature@1"!==d?.op&&bM("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===r&&"transform"===l.kind||bM("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&bM("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=s[d.args[0]].provider,m=d.params.name,g=s[d.args[0]].faces,y=g?.[m];y||bM("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&bM("SURFACE_UNSUPPORTED",n,"feature touches a curved side along a line; it is not a surface to hold things on");const b=["x","y","z"].map(t=>t===y[0]?y[1]:0);return{...e,geometryId:u?null:h.id,selection:u,provider:f,face:m,frame:l.from,normal:b}}function xM(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const wM="holder",MM=t=>"number"==typeof t&&Number.isFinite(t),SM=t=>MM(t)&&t>0,AM=t=>Number.isSafeInteger(t)&&t>0;function kM(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])SM(s[t])||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(xM("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||AM(t.stackLimit)||t.stackLimit===1/0||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||MM(t.rotation)||n.push(xM("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(xM("ARRAY_REQUIRED",`${e}.accepts`))}function EM(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[xM("TIERS_REQUIRED","tiers")];const s=e.anchors?new Set(e.anchors):null,i=new Set;return t.tiers.forEach((t,e)=>{const o=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(xM("OBJECT_REQUIRED",o));if(AM(t.tierNo)?i.has(t.tierNo)?n.push(xM("TIER_NUMBER_DUPLICATE",`${o}.tierNo`,{tierNo:t.tierNo})):i.add(t.tierNo):n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?s&&!s.has(t.anchorId)&&n.push(xM("ANCHOR_UNKNOWN",`${o}.anchorId`,{anchorId:t.anchorId})):n.push(xM("ANCHOR_REQUIRED",`${o}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(xM("MOUNT_INVALID",`${o}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])MM(t.position[e])||n.push(xM("FINITE_NUMBER_REQUIRED",`${o}.position.${e}`));else n.push(xM("OBJECT_REQUIRED",`${o}.position`));MM(t.rotation)||n.push(xM("FINITE_NUMBER_REQUIRED",`${o}.rotation`));const r=t.layout;switch(r?.pattern){case"SINGLE":kM(r.slot,`${o}.layout.slot`,n);break;case"ROW":AM(r.count)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.count`)),SM(r.pitch)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch`)),"X"!==r.axis&&"Z"!==r.axis&&n.push(xM("AXIS_INVALID",`${o}.layout.axis`)),kM(r.slot,`${o}.layout.slot`,n);break;case"GRID":AM(r.rows)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.rows`)),AM(r.cols)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.cols`)),SM(r.pitch?.x)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch.x`)),SM(r.pitch?.z)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch.z`)),kM(r.slot,`${o}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(r.slots)){n.push(xM("ARRAY_REQUIRED",`${o}.layout.slots`));break}r.slots.length||n.push(xM("SLOTS_REQUIRED",`${o}.layout.slots`));const t=new Set;r.slots.forEach((e,s)=>{const i=`${o}.layout.slots[${s}]`;AM(e?.slotNo)?t.has(e.slotNo)?n.push(xM("SLOT_NUMBER_DUPLICATE",`${i}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(xM("POSITIVE_INTEGER_REQUIRED",`${i}.slotNo`)),MM(e?.offset?.x)&&MM(e?.offset?.z)||n.push(xM("FINITE_NUMBER_REQUIRED",`${i}.offset`)),kM(e,i,n)});break}default:n.push(xM("PATTERN_INVALID",`${o}.layout.pattern`))}}),n}function TM(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(xM("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}function CM(t){switch(t.pattern){case"SINGLE":return 1;case"ROW":return t.count;case"GRID":return t.rows*t.cols;case"CUSTOM":return t.slots.length}}function OM(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:CM(t)},(t,e)=>e+1)}function PM(t,e,n,s,i="ROW_MAJOR"){switch(i){case"ROW_MAJOR":return(n-1)*e+s;case"COL_MAJOR":return(s-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?s:e-s+1);case"SERPENTINE_COL":return(s-1)*t+(s%2==1?n:t-n+1)}}function IM(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const DM=(t,e)=>e&&0!==t?-t:t;function zM(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!AM(e.slot))return null;const i=s.layout;let o,r,a;switch(i.pattern){case"SINGLE":if(1!==e.slot)return null;o=i.slot,r={x:0,z:0};break;case"ROW":{if(e.slot>i.count)return null;const t=DM((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);o=i.slot,r="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>i.rows*i.cols)return null;const{r:t,c:n}=IM(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};o=i.slot,r={x:DM((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:DM((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;o=t,r={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,anchorId:s.anchorId,mount:s.mount,tierPosition:{...s.position},tierRotation:s.rotation,offset:r,allowed:{...o.allowed},accepts:o.accepts?[...o.accepts]:void 0,stackLimit:o.stackLimit??n.defaultStackLimit??1,rotation:o.rotation??0}}function RM(t){return`t${t.tier}_s${t.slot}`}function jM(t){const e="string"==typeof t?/^t(\d+)_s(\d+)$/.exec(t):null;return e?{tier:Number(e[1]),slot:Number(e[2])}:null}function*$M(t){for(const e of t?.tiers??[])for(const t of OM(e.layout))yield{tier:e.tierNo,slot:t}}function LM(t,e,n){if(!n)return{x:t,z:e};const s=n*Math.PI/180,i=Math.cos(s),o=Math.sin(s),r=t=>Math.round(1e9*t)/1e9;return{x:r(t*i+e*o),z:r(-t*o+e*i)}}function FM(t){const e=LM(t.offset.x,t.offset.z,t.tierRotation);return{position:{x:t.tierPosition.x+e.x,y:t.tierPosition.y,z:t.tierPosition.z+e.z},rotation:t.tierRotation+t.rotation}}const NM=.05,HM=t=>!!t&&SM(t.width)&&SM(t.depth)&&SM(t.height);function BM(t,e){const n=e*Math.PI/180,s=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),o=t=>Math.round(1e9*t)/1e9;return{width:o(t.width*s+t.depth*i),depth:o(t.width*i+t.depth*s)}}function GM(t,e,n=0,s=.05){if(!HM(t))return null;if(!MM(n)||!MM(s)||s<0||s>=1)return null;const i=BM(t,e.rotation),o=Math.min(1,Math.min(e.allowed.width/i.width,e.allowed.depth/i.depth)*(1-s)),r=t.height*o;return{position:{x:0,y:("HANG"===e.mount?-1:1)*(n+r/2),z:0},rotation:0,scale:o}}function UM(t,e,n=0,s=.05){const i=GM(t,e,n,s);if(!i)return null;const o=FM(e);return{position:{x:o.position.x,y:o.position.y+i.position.y,z:o.position.z},rotation:o.rotation,scale:i.scale}}function VM(t,e,n=.05){let s=0;return t.map(t=>{const i=t?UM(t,e,s,n):null;return i&&(s+=t.height*i.scale),i})}const WM=1e-6;function YM(t,e){const n=FM(t),s=t.allowed.width/2,i=t.allowed.depth/2,o=[[-s,-i],[s,-i],[s,i],[-s,i]].map(([t,e])=>{const s=LM(t,e,n.rotation);return{x:n.position.x+s.x,z:n.position.z+s.z}}),r=LM(1,0,n.rotation),a=LM(0,1,n.rotation),c="HANG"===t.mount?-1:1,l=[n.position.y,n.position.y+c*t.allowed.height],h=o.map(t=>t.x);return{tierIndex:e,tier:t.tier,slot:t.slotNo,corners:o,axes:[r,a],y0:Math.min(...l),y1:Math.max(...l),minX:Math.min(...h),maxX:Math.max(...h)}}function qM(t,e){for(const n of[...t.axes,...e.axes]){const s=t.corners.map(t=>t.x*n.x+t.z*n.z),i=e.corners.map(t=>t.x*n.x+t.z*n.z);if(Math.min(Math.max(...s),Math.max(...i))-Math.max(Math.min(...s),Math.min(...i))<=WM)return!1}return!0}function XM(t,e={}){const n=[],s=new Map;t.tiers.forEach((e,n)=>{const i=s.get(e.anchorId)??[];s.set(e.anchorId,i);for(const s of OM(e.layout))i.push(YM(zM(t,{tier:e.tierNo,slot:s}),n))});for(const[t,i]of s){const s=e.anchorFaces?.[t];if(s)for(const t of i)t.corners.some(t=>Math.abs(t.x)-s.width/2>WM||Math.abs(t.z)-s.depth/2>WM)&&n.push({code:"SLOT_OUTSIDE_ANCHOR",path:`tiers[${t.tierIndex}]`,params:{tier:t.tier,slot:t.slot}});else n.push({code:"ANCHOR_SPACE_UNKNOWN",path:"tiers",params:{anchorId:t}});const o=[...i].sort((t,e)=>t.minX-e.minX);for(let t=0;t<o.length;t++){const e=o[t];for(let s=t+1;s<o.length&&o[s].minX<e.maxX-WM;s++){const t=o[s];if(Math.min(e.y1,t.y1)-Math.max(e.y0,t.y0)<=WM)continue;if(!qM(e,t))continue;const[i,r]=e.tierIndex<t.tierIndex||e.tierIndex===t.tierIndex&&e.slot<t.slot?[e,t]:[t,e];n.push({code:"SLOT_OVERLAP",path:`tiers[${r.tierIndex}]`,params:{tier:r.tier,slot:r.slot,otherTier:i.tier,otherSlot:i.slot}})}}}return n}function KM(t,e,n=[],s={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const i=s.normalizeType??(t=>null==t?"":String(t)),o=[];let r=!1;if(t.accepts){const n=i(e.type);n?t.accepts.map(i).includes(n)||o.push("TYPE_NOT_ACCEPTED"):r=!0}if(n.length+1>t.stackLimit&&o.push("STACK_LIMIT_EXCEEDED"),HM(e.dims)){const s=BM(e.dims,t.rotation);if(s.width>t.allowed.width&&o.push("WIDTH_EXCEEDED"),s.depth>t.allowed.depth&&o.push("DEPTH_EXCEEDED"),n.every(t=>HM(t.dims))){const s=n.reduce((t,e)=>t+e.dims.height,e.dims.height);s>t.allowed.height&&o.push("HEIGHT_EXCEEDED")}else r=!0}else r=!0;return o.length?{verdict:"NG",reasons:r?[...o,"SPEC_UNKNOWN"]:o}:r?{verdict:"UNKNOWN",reasons:["SPEC_UNKNOWN"]}:{verdict:"OK",reasons:[]}}function JM(t){if(!t?.layout||!Array.isArray(t.anchors))return[];const e=new Map(t.anchors.map(t=>[t.id,t])),n=[];for(const s of $M(t.layout)){const i=zM(t.layout,s),o=i&&e.get(i.anchorId);if(!i||!o)continue;const r=RM(s);n.push({id:r,label:`${t.label} ${r}`,role:t.role,frame:o.frame,pose:{...o.pose},anchorId:o.id,...i.accepts?{accepts:[...i.accepts]}:{},capacity:i.stackLimit,tier:i.tier,slot:i.slotNo,...i.name?{name:i.name}:{},tierPosition:{...i.tierPosition},tierRotation:i.tierRotation,offset:{...i.offset},rotation:i.rotation,mount:i.mount,allowed:{...i.allowed}})}return n}const QM=(t,e,n)=>{throw new Xv(t,e,n)};function ZM(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||QM("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||QM("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||QM("SCHEMA",s,`unknown ${i}`)}const tS=(t,e)=>{"string"==typeof t&&t.trim()||QM("SCHEMA",e,"nonempty string required")};function eS(t,e){return function(t,e){const n=Px(t),s=structuredClone(e),i=n.outputTypes,o=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),r=new Map;ZM(s,["version","assetFrame","bindings"],["names","slotLayout","extensions"],"capabilities"),"r3-capability-3"!==s.version&&QM("VERSION","capabilities",s.version);if(tS(s.assetFrame,"assetFrame"),void 0!==s.names){Array.isArray(s.names)||QM("SCHEMA","names","array required");for(const t of s.names)Nv(t)||QM("CAPABILITY_NAME","names",`${String(t)} is not one of ${$v.join(", ")}, nor a consumer's <namespace>.<Name>`);new Set(s.names).size!==s.names.length&&QM("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(Hv))s.names.includes(t)&&!e.some(t=>s.names.includes(t))&&QM("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}if(void 0!==s.extensions){s.extensions&&"object"==typeof s.extensions&&!Array.isArray(s.extensions)||QM("SCHEMA","extensions","object required");for(const[t,e]of Object.entries(s.extensions))Fv(t)&&(s.names??[]).includes(t)||QM("CAPABILITY_NAME",`extensions.${t}`,`${t} is not a consumer capability this figure declares`),e&&"object"==typeof e&&!Array.isArray(e)||QM("SCHEMA",`extensions.${t}`,"object required")}Array.isArray(s.bindings)||QM("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(tS(t,e),Object.hasOwn(i,t)||QM("TARGET_ABSENT",e,t),i[t]),l=(t,e,n)=>{const i=c(t,e);("transform"!==i.kind||i.to!==s.assetFrame||void 0!==n&&i.from!==n)&&QM("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>_M({types:i,writers:o,model:t,assetFrame:s.assetFrame},e,n),d=new Map;for(const t of s.bindings){ZM(t,["id","label","role","frame","pose","capacity"],["accepts","region","contacts"],"binding");for(const e of["id","label","frame"])tS(t[e],e);if(a.has(t.id)&&QM("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||QM("ROLE",t.id,"explicit seat or grip required; slot is ambiguous"),"string"==typeof t.pose)l(t.pose,t.id,t.frame);else{const e=h(t.pose,t.id);e.frame!==t.frame&&QM("FRAME_TYPE",t.id,"binding frame must be the selected feature frame"),d.set(t.id,e)}if(void 0!==t.accepts&&(Array.isArray(t.accepts)&&t.accepts.length||QM("SCHEMA",t.id,"accepts names at least one type, or is left out for any"),t.accepts.forEach(e=>tS(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&QM("SCHEMA",t.id,"duplicate accepted type")),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&QM("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){ZM(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&QM("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||QM("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&QM("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||QM("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const s of t.contacts){const i=h(s,t.id),o=JSON.stringify([s.placement,s.feature]);e.has(o)&&QM("DUPLICATE_CONTACT",t.id,o),e.add(o),n.push(i)}r.set(t.id,n)}}const u=[];if(void 0!==s.slotLayout){const t=s.slotLayout;ZM(t,["label","role","anchors","layout"],[],"slotLayout"),tS(t.label,"slotLayout.label"),["seat","grip"].includes(t.role)||QM("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),Array.isArray(t.anchors)&&t.anchors.length||QM("SCHEMA","slotLayout.anchors","at least one anchor required");const e=new Map;t.anchors.forEach((t,n)=>{const s=`slotLayout.anchors[${n}]`;ZM(t,["id","frame","pose"],[],s),tS(t.id,`${s}.id`),tS(t.frame,`${s}.frame`),e.has(t.id)&&QM("SCHEMA",`${s}.id`,`duplicate anchor ${t.id}`),"string"==typeof t.pose&&QM("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a face of a part");const i=h(t.pose,s);i.frame!==t.frame&&QM("FRAME_TYPE",s,"anchor frame must be the selected feature frame");const o=i.normal[1];o||QM("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a horizontal face (its normal along Y)"),e.set(t.id,{surface:i,up:o})});const n=EM(t.layout,{anchors:e.keys()}),i=n.length?n:TM(t.layout);i.length&&QM("SLOT_LAYOUT",`slotLayout.layout.${i[0].path}`,i.map(t=>`${t.code} at ${t.path}`).join("; "));for(const n of JM(t)){void 0!==n.accepts&&(n.accepts.length||QM("SCHEMA",n.id,"accepts names at least one type, or is left out for any"),n.accepts.forEach(t=>tS(t,n.id)),new Set(n.accepts).size!==n.accepts.length&&QM("SCHEMA",n.id,"duplicate accepted type")),(!Number.isSafeInteger(n.capacity)||n.capacity<1)&&QM("CAPACITY",n.id,"positive integer capacity required"),a.has(n.id)&&QM("DUPLICATE_BINDING",n.id,"duplicate id"),a.add(n.id);const t=e.get(n.anchorId);d.set(n.id,t.surface),u.push({...n,up:t.up})}}const p=[...s.bindings,...u];function f(t,e){const n=t.pose.r,s=FM(e),i=[s.position.x,s.position.y*e.up,s.position.z],o=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*i[n],0)),r=s.rotation*Math.PI/180,a=Math.cos(r),c=Math.sin(r),l=[[a,0,c],[0,1,0],[-c,0,a]],h=n.map(t=>l[0].map((e,n)=>t.reduce((t,e,s)=>t+e*l[s][n],0)));return{...t,pose:{r:h,t:o}}}function m(t,e,n){const s=t=>function(t,e){const n=t[e.placement],s=t[e.feature],i=n.pose.r,o=i.map(t=>t.reduce((t,n,s)=>t+n*e.normal[s],0)),r=i.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*s.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,s=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);s||bM("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=s.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:i.map(t=>[...t]),t:r},normal:o,provenance:"verified-planar-surface"}}(e,t);let i=null;if(t.allowed)i={kind:"centered-box",dimensions:[t.allowed.width,t.allowed.height,t.allowed.depth]};else if(t.region){const n=t.region.dimensions.map(t=>e[t]);n.some(t=>!Number.isFinite(t)||t<=0)&&QM("REGION_DOMAIN",t.id,"positive region dimensions required"),i={kind:t.region.kind,dimensions:n}}let o={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];ZM(e,["type","occupied"],[],t.id+".request"),tS(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&QM("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const s=[];t.accepts&&!t.accepts.includes(e.type)&&s.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&s.push("CAPACITY_FULL"),o={status:s.length?"failed":"satisfied",reasons:s}}const a=(r.get(t.id)??[]).map(s),c=d.has(t.id)?s(d.get(t.id)):null,l=c&&t.allowed?f(c,t):c;return{id:t.id,label:t.label,role:t.role,frame:t.frame,pose:l?l.pose:e[t.pose],...l?{targetGeometryId:l.geometryId}:{},region:i,contacts:a,checks:{declaration:{status:"satisfied"},eligibility:o,spatial:{status:"unverified",reason:"NO_CONTACT_OR_FIT_SOLVER"},collision:{status:"unverified",reason:"NOT_CHECKED"},safety:{status:"unverified",reason:"NOT_CHECKED"}}}}function g(t,e,n={}){return ZM(n,[],[...a],"requests"),y(t.evaluate(e),n)}function y(t,e){const n=p.map(n=>m(n,t.values,e));return{geometry:t.geometry,bindings:n,values:t.values}}const b=t=>[t.placement,t.feature,...t.selection?[t.selection.collection,t.selection.index]:[]],v=new Map(p.map(t=>[t.id,[..."string"==typeof t.pose?[t.pose]:b(d.get(t.id)),...(r.get(t.id)??[]).flatMap(b),...t.region?.dimensions??[]]])),_={forbidden:Object.fromEntries(p.flatMap(t=>(t.region?.dimensions??[]).map(e=>[e,`region of ${t.id}`]))),external:[...new Set([...v.values()].flat())]};return{outputTypes:structuredClone(i),dependence:structuredClone(n.dependence),evaluate:(t,e={})=>g(n,t,e),evaluator(t={}){const e=n.evaluator({reads:_,changes:!!t.changes});return{evaluate:(t,n={})=>g(e,t,n),advance:(t,n={})=>{ZM(n,[],[...a],"requests");const s=Object.keys(n).length>0,i=e.advance(t,s?"REQUESTS":void 0);if("evaluation"===i.kind)return{...i,result:y(i.result,n)};if("changes"===i.kind){const t=p.filter(t=>s||i.structure||v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{...i,places:t}}const o=p.filter(t=>v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{kind:"poses",generation:i.generation,bodies:i.bodies,poses:i.poses,places:o}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const s=p.find(e=>e.id===t);return s||QM("TARGET_ABSENT",t,"no such place"),ZM(n,[],[...a],"requests"),m(s,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const nS=1048576;function sS(t,e,n){throw new Xv(t,"document",e,n)}function iS(t){return(new TextEncoder).encode(t).byteLength}function oS(t){const e=new Set;!function t(n,s){if(s>64&&sS("DOCUMENT_LIMIT","nesting exceeds 64",{reason:"nesting-too-deep",max:64,at:s}),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||sS("JSON_VALUE","nonfinite number"));"object"!=typeof n&&sS("JSON_VALUE","only JSON values are allowed"),e.has(n)&&sS("JSON_VALUE","cycle");const i=Array.isArray(n);i||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||sS("JSON_VALUE","plain objects required"),e.add(n);const o=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(o)){if(i&&"length"===e)continue;"string"!=typeof e&&sS("JSON_VALUE","symbols unsupported");const r=o[e];r.enumerable&&Object.hasOwn(r,"value")||sS("JSON_VALUE","hidden properties and accessors unsupported"),!i||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||sS("JSON_VALUE","extra array property"),t(r.value,s+1)}i&&Object.keys(n).length!==n.length&&sS("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function rS(t){if(oS(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new Xv("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new Xv("VERSION","document","unsupported document version");const e=iS(JSON.stringify(t));if(e>nS)throw new Xv("DOCUMENT_LIMIT","document","over 1 MiB",{reason:"document-too-large",max:nS,at:e});const n=t;if(!Array.isArray(n.model?.nodes)||n.model.nodes.length>Wv)throw new Xv("DOCUMENT_LIMIT","document","maximum 8192 nodes",{reason:"node-limit",max:Wv});return eS(n.model,n.capabilities)}function aS(t,e,n){const s=function(t,e){const n=t.find(t=>t.id===e);if(!n)return{code:"TARGET_ABSENT",message:`${String(e)} is not an input of the figure`};if("state"===n.role)return{code:"PUBLIC_INPUT",message:`${e} is a state input; a board sets it as a parameter`};if(/^(sizing\.)?size\.[xyz]$/.test(e))return{code:"PUBLIC_INPUT",message:`${e} is the figure's size; a board sets it from the instance's bounds`};const s=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return s(n.min)&&s(n.max)?null:{code:"PUBLIC_INPUT",message:`${e} has no range to hold a board's value to; give it one first`}}(t,e);if(s)throw new Xv(s.code,n,s.message)}const cS=/^[a-z][a-z0-9-]{0,31}\/[a-z][a-z0-9-]{0,63}$/,lS=(t,e,n)=>{throw new Xv(t,e,n)};function hS(t,e="extensions"){"string"==typeof t&&cS.test(t)||lS("EXTENSION_KEY",e,`${String(t)} is not {owner}/{name}: each starts with a-z and holds a-z, 0-9 and -, the owner up to 32 and the name up to 64`)}function dS(t,e){null==t&&lS("ASSET_SCHEMA",e,"a JSON value other than null"),oS(t);const n=iS(JSON.stringify(t));n>4096&&lS("EXTENSION_LIMIT",e,`${n} bytes; at most 4096`)}const uS=["floor","ceiling","center","wall"],pS=t=>"string"==typeof t&&/^#[0-9a-f]{6}$/i.test(t),fS=/^[a-zA-Z][a-zA-Z0-9_-]*$/,mS=/^[A-Za-z_][\w-]*$/,gS=(t,e,n,s)=>{throw new Xv(t,e,n,s)},yS=(t,e,n)=>gS("DATA_INTERFACE",t,e,n);function bS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||gS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||gS("ASSET_SCHEMA",s,`unknown ${i}`)}const vS=t=>"number"==typeof t&&Number.isFinite(t);function _S(t){if("string"!=typeof t||!t)return null;const e=[];for(const n of t.split(".")){const t=/^([A-Za-z_][\w-]*)(?:\[(\d+)\])?$/.exec(n);if(!t)return null;e.push({field:t[1]}),void 0!==t[2]&&e.push({index:Number(t[2])})}return e}function xS(t,e){let n,s={kind:"object",fields:t};for(const t of e)if("field"in t){if("object"!==s.kind)return{why:"absent"};const e=s.fields.find(e=>e.name===t.field);if(!e)return{why:"absent"};s=e,n=e}else{if("list"!==s.kind)return{why:"not-a-list"};s=s.item,n=void 0}return{node:s,...n?{field:n}:{}}}const wS=t=>"number"===t.kind||"boolean"===t.kind||"text"===t.kind;function MS(t,e,n){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",e,"object required");const s=n?["name","label","json"]:[],i=t.kind,o=(t,n)=>yS(`${e}.${t}`,n,{reason:"data-field-invalid",field:e,what:t});if("object"===i?bS(t,["kind","fields"],s,e):"list"===i?bS(t,["kind","item"],s,e):"number"===i?bS(t,["kind"],[...s,"unit","min","max","default"],e):"boolean"===i?bS(t,["kind"],[...s,"default"],e):"text"===i?bS(t,["kind"],[...s,"values","default"],e):gS("ASSET_SCHEMA",`${e}.kind`,`${String(i)} is not a data kind; object, list, number, boolean or text`),n&&("string"==typeof t.name&&mS.test(t.name)||o("name",`${String(t.name)} is not a field name: a letter or _, then letters, digits, _ and -`),void 0===t.label||"string"==typeof t.label&&t.label.trim()||o("label","a name shown to a person, or none"),void 0!==t.json&&(!0!==t.json||"object"!==i&&"list"!==i)&&o("json","only an object or a list may come as JSON text")),"object"===i)Array.isArray(t.fields)||gS("ASSET_SCHEMA",`${e}.fields`,"a list of fields"),SS(t.fields,`${e}.fields`);else if("list"===i)MS(t.item,`${e}.item`,!1);else if("number"===i){void 0===t.unit||function(t){return"string"==typeof t&&Object.hasOwn(W_,t)}(t.unit)||o("unit",`${String(t.unit)} is not a unit`);for(const e of["min","max","default"])void 0===t[e]||vS(t[e])||o(e,"a finite number");void 0===t.min||void 0===t.max||t.min<=t.max||o("min","a range from a number to one no smaller"),void 0!==t.default&&(void 0!==t.min&&t.default<t.min||void 0!==t.max&&t.default>t.max)&&o("default","the default lies in the range")}else"boolean"===i?void 0!==t.default&&"boolean"!=typeof t.default&&o("default","true or false"):(void 0!==t.values&&(Array.isArray(t.values)&&t.values.length&&!t.values.some(t=>"string"!=typeof t||!t)||o("values","one or more nonempty strings"),new Set(t.values).size!==t.values.length&&o("values","each value once")),void 0!==t.default&&("string"!=typeof t.default&&o("default","a string"),t.values&&!t.values.includes(t.default)&&o("default","the default is one of the values")))}function SS(t,e){const n=new Set;t.forEach((t,s)=>{MS(t,`${e}[${s}]`,!0),n.has(t.name)&&yS(`${e}[${s}].name`,`${t.name} is a field twice`,{reason:"data-field-duplicate",field:`${e}[${s}]`,name:t.name}),n.add(t.name)})}const AS=t=>"state"===t.kind?t.input:"palette"===t.kind?t.token:"pose"===t.kind?t.axis:"items"===t.kind?t.slot??"":t.group,kS=[["clip","motion-clip"],["speed","motion-speed"],["paused","motion-paused"]];function ES(t){const e=t.split("~");if(2!==e.length)return null;const[n,s]=e,i=""===n?-1/0:Number(n),o=""===s?1/0:Number(s);return(""===n||vS(i))&&(""===s||vS(o))&&i<o?[i,o]:null}const TS=(t,e)=>(n,s,i={})=>yS(e,s,{reason:"data-rule-domain",binding:t,why:n,...i});const CS=/^[a-z0-9][a-z0-9-]*$/;function OS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",s,"object required");const i="table"===t.rule;i?bS(t,["id","accessor","rule","lookup","targets","table"],["label","legend"],s):bS(t,["id","accessor","behavior","rule"],["label","param"],s),"string"==typeof t.id&&fS.test(t.id)||yS(`${s}.id`,`${String(t.id)} is not an id: a letter, then letters, digits, - and _`,{reason:"data-id-invalid",list:"bindings",id:String(t.id)}),void 0===t.label||"string"==typeof t.label&&t.label.trim()||gS("ASSET_SCHEMA",`${s}.label`,"a name shown to a person, or none");const o=(e,n)=>yS(`${s}.accessor`,`${e}: ${n}`,{reason:"data-accessor-invalid",binding:t.id,accessor:e,why:n}),r=()=>{const n=_S(t.accessor);n||o(String(t.accessor),"syntax");const s=xS(e,n);return"why"in s?o(t.accessor,s.why):s};if(i){const{node:e}=r();return"list"===e.kind?o(t.accessor,"list-needs-index"):wS(e)||o(t.accessor,"not-a-value"),function(t,e,n,s){const i=TS(t.id,s),o=t.targets;o&&"object"==typeof o&&!Array.isArray(o)||gS("ASSET_SCHEMA",`${s}.targets`,"object required"),bS(o,[],["parts","inputs","group"],`${s}.targets`);for(const t of["parts","inputs"])void 0===o[t]||Array.isArray(o[t])&&!o[t].some(t=>"string"!=typeof t||!t)||gS("ASSET_SCHEMA",`${s}.targets.${t}`,"a list of ids");void 0===o.group||"string"==typeof o.group&&o.group||gS("ASSET_SCHEMA",`${s}.targets.group`,"a nonempty string");const r=(e,n,i)=>yS(`${s}.targets`,n,{reason:"data-table-target",binding:t.id,what:e,...void 0!==i?{id:i}:{}}),a=o.parts??[],c=o.inputs??[];if(a.length||c.length||void 0!==o.group||r("none","a table shows on a part, a state input, a motion group, or more"),a.forEach((t,e)=>{n.parts.has(t)||r("part",`${t} is not a part of this figure`,t),a.indexOf(t)!==e&&r("part",`${t} is named twice`,t)}),c.forEach((t,e)=>{n.states.has(t)||r("input",`${t} is not a state input of this figure`,t),c.indexOf(t)!==e&&r("input",`${t} is named twice`,t)}),void 0===o.group||n.groups.has(o.group)||r("group",`${o.group} is not a motion group of this figure`,o.group),"code"!==t.lookup&&"ranges"!==t.lookup&&gS("ASSET_SCHEMA",`${s}.lookup`,"code or ranges"),!wS(e))return i("kind",`${t.accessor} is ${"list"===e.kind?"a list":"an object"}; a table reads one value`);if("code"===t.lookup&&"number"===e.kind)return i("kind",`${t.accessor} is a number; a table reads it by ranges`);if("ranges"===t.lookup&&"number"!==e.kind)return i("kind",`a range table reads a number; ${t.accessor} is ${"text"===e.kind?"a text":"true or false"}`);const l=t.table;l&&"object"==typeof l&&!Array.isArray(l)||gS("ASSET_SCHEMA",`${s}.table`,"an object of looks");const h=Object.keys(l).filter(t=>"default"!==t);if("code"===t.lookup){const n=function(t){return"boolean"===t.kind?[!1,!0]:"text"===t.kind&&t.values?t.values:null}(e);if(n){for(const e of h)n.some(t=>String(t)===e)||i("cases",`${e} is not a value of ${t.accessor}`,{value:e});n.every(t=>Object.hasOwn(l,String(t)))||Object.hasOwn(l,"default")||i("default",`not every value of ${t.accessor} has a look; give a default`)}}else{const n=[];for(const t of h){const e=ES(t);if(!e)return i("cases",`${t} is not an interval: from~to, either end may be left out`,{value:t});const s=n.find(([t,n])=>e[0]<n&&t<e[1]);s&&i("overlap",`${s[2]} and ${t} overlap; a value has one look`,{value:t}),n.push([e[0],e[1],t])}const s=e;Object.hasOwn(l,"default")||function(t,e,n){let s=e;for(const[e,i]of[...t].sort((t,e)=>t[0]-e[0])){if(e>s)return!1;if(i>s&&(s=i),s===1/0||s>n)return!0}return!1}(n.map(([t,e])=>[t,e]),s.min??-1/0,s.max??1/0)||i("default",`the intervals leave values of ${t.accessor} without a look; give a default`)}for(const[e,i]of Object.entries(l)){const r=`${s}.table.${e}`;i&&"object"==typeof i&&!Array.isArray(i)||gS("ASSET_SCHEMA",r,"object required"),bS(i,[],["color","effect","values","clip","speed","paused"],r);const l=(n,s,i={})=>yS(`${r}.${"column"===n?i.id:n}`,s,{reason:"data-table-entry",binding:t.id,key:e,what:n,...i}),h=(e,n)=>{void 0===i[e]||n||l("column",`${e} goes to no target of ${t.id}`,{id:e})};h("color",a.length>0),h("effect",a.length>0),h("values",c.length>0);for(const[t]of kS)h(t,void 0!==o.group);if(void 0===i.color||pS(i.color)||l("color","a colour is #RRGGBB",{value:i.color}),void 0!==i.effect){const t=i.effect;t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",`${r}.effect`,"object required"),bS(t,["kind"],["hz"],`${r}.effect`),"blink"!==t.kind&&"glow"!==t.kind&&l("effect","an effect is blink or glow",{value:t.kind}),void 0===t.hz||vS(t.hz)&&t.hz>0||l("effect","hz is a positive number",{value:t.hz})}if(void 0!==i.values){i.values&&"object"==typeof i.values&&!Array.isArray(i.values)||gS("ASSET_SCHEMA",`${r}.values`,"an object of values");for(const[e,s]of Object.entries(i.values)){c.includes(e)||l("values",`${e} is not a target of ${t.id}`,{id:e});const i=n.states.get(e);(!vS(s)||s<i.min||s>i.max)&&l("values",`${String(s)} is outside ${e}, ${i.min} to ${i.max}`,{id:e,value:s})}}void 0===i.clip||"string"==typeof i.clip&&n.groups.get(o.group).includes(i.clip)||l("clip",`${String(i.clip)} is not a clip of ${o.group}`,{value:i.clip}),void 0===i.speed||vS(i.speed)&&i.speed>=0&&i.speed<=3||l("speed","a motion speed is 0 to 3",{value:i.speed}),void 0!==i.paused&&"boolean"!=typeof i.paused&&l("paused","a pause is true or false",{value:i.paused})}void 0!==t.legend&&(t.legend&&"object"==typeof t.legend&&!Array.isArray(t.legend)||gS("ASSET_SCHEMA",`${s}.legend`,"object required"),bS(t.legend,["role"],[],`${s}.legend`),"string"==typeof t.legend.role&&CS.test(t.legend.role)||yS(`${s}.legend.role`,`${String(t.legend.role)} is not a role: lower case letters, digits and -`,{reason:"data-legend-invalid",binding:t.id,role:String(t.legend.role)}))}(t,e,n,s),t}const a=function(t,e){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",e,"object required");const n=t.kind;"state"===n?bS(t,["kind","input","sourceMode"],[],e):"palette"===n?bS(t,["kind","token"],[],e):"motion-clip"===n||"motion-speed"===n||"motion-paused"===n?bS(t,["kind","group"],[],e):"pose"===n?bS(t,["kind","axis"],["seconds"],e):"items"===n?bS(t,["kind"],["slot","id","type","place","stack","status"],e):gS("ASSET_SCHEMA",`${e}.kind`,`${String(n)} is not a behavior; state, palette, motion-clip, motion-speed, motion-paused, pose or items`),"state"===n&&"observed"!==t.sourceMode&&"commanded"!==t.sourceMode&&gS("ASSET_SCHEMA",`${e}.sourceMode`,"observed or commanded"),"pose"!==n||["x","y","z","heading"].includes(t.axis)||gS("ASSET_SCHEMA",`${e}.axis`,"x, y, z or heading"),"pose"!==n||void 0===t.seconds||vS(t.seconds)&&t.seconds>=0||gS("ASSET_SCHEMA",`${e}.seconds`,"seconds from 0");for(const n of["input","token","group","slot","id","type","place","stack","status"])!Object.hasOwn(t,n)||"string"==typeof t[n]&&t[n]||gS("ASSET_SCHEMA",`${e}.${n}`,"a nonempty string");return t}(t.behavior,`${s}.behavior`);void 0===t.param||t.param&&"object"==typeof t.param&&!Array.isArray(t.param)||gS("ASSET_SCHEMA",`${s}.param`,"an object of results");const c=e=>yS(`${s}.behavior`,`${e} is not a ${a.kind} of this figure`,{reason:"data-behavior-absent",binding:t.id,behavior:a.kind,id:e});"state"!==a.kind||n.states.has(a.input)||c(a.input),"palette"!==a.kind||Object.hasOwn(n.palette,a.token)||c(a.token),"motion-clip"!==a.kind&&"motion-speed"!==a.kind&&"motion-paused"!==a.kind||n.groups.has(a.group)||c(a.group);const{node:l}=r();if("items"===a.kind)if("list"===l.kind){const e=l.item;a.id||yS(`${s}.behavior.id`,"items from a list say which field of an element is its id",{reason:"data-accessor-invalid",binding:t.id,accessor:t.accessor,why:"item-id-required"});for(const n of["id","type","place","stack","status"]){const s=a[n];if(void 0===s)continue;const i=_S(s);i||o(s,"syntax");const r=xS("object"===e.kind?e.fields:[],i);"why"in r?o(`${t.accessor}[].${s}`,r.why):wS(r.node)||o(`${t.accessor}[].${s}`,"not-a-value")}}else wS(l)?(a.id||a.type||a.place||a.stack||a.status)&&yS(`${s}.behavior`,"one value is the id itself; element fields are for a list",{reason:"data-accessor-invalid",binding:t.id,accessor:t.accessor,why:"not-a-list"}):o(t.accessor,"not-a-value");else"list"===l.kind?o(t.accessor,"list-needs-index"):wS(l)||o(t.accessor,"not-a-value");return function(t,e,n,s){const i=TS(t.id,s),o=t.behavior,r=t.param;if("items"===o.kind)return void("value"===t.rule&&void 0===r||i("kind","items are read as they are: rule value, no param"));if(!wS(e))return i("kind",`${t.accessor} is ${"list"===e.kind?"a list":"an object"}; this behavior reads one value`);if("value"!==t.rule&&"scale"!==t.rule)return i("kind",`${String(t.rule)} is not a rule; value, scale or table`);let a=1,c=0;if("scale"===t.rule){if(!r||!vS(r.scale)||!vS(r.offset)||Object.keys(r).some(t=>"scale"!==t&&"offset"!==t))return i("cases","a scale is { scale, offset }, two finite numbers");if("number"!==e.kind)return i("kind",`a scale reads a number; ${t.accessor} is ${e.kind}`);a=r.scale,c=r.offset}else if(void 0!==r)return i("cases","value takes no param");if("motion-clip"===o.kind||"palette"===o.kind){if("scale"===t.rule||"text"!==e.kind||!e.values)return i("kind",("palette"===o.kind?"a colour":"a clip")+" is read as it is only from a text of fixed values; otherwise by a table");for(const t of e.values)"palette"!==o.kind||pS(t)||i("output","a colour is #RRGGBB",{value:t}),"motion-clip"!==o.kind||n.groups.get(o.group).includes(t)||i("output",`${t} is not a clip of ${o.group}`,{value:t});return}if("motion-paused"===o.kind)return void("scale"!==t.rule&&"boolean"===e.kind||i("kind","a pause is read as it is only from true or false; otherwise by a table"));if("number"!==e.kind)return i("kind",`${t.accessor} is ${"text"===e.kind?"a text":"true or false"}; this behavior reads a number, or a value by a table`);if("pose"===o.kind){const n="heading"===o.axis?"deg":"mm";return void("value"===t.rule&&e.unit!==n&&i("unit",`${t.accessor} is in ${e.unit??"no unit"}; a ${"heading"===o.axis?"heading":"position"} is in ${n}; say the unit, or scale it`,{from:e.unit??"",to:n}))}if("motion-speed"===o.kind)"value"===t.rule&&void 0!==e.unit&&"ratio"!==e.unit&&i("unit",`a motion speed is a ratio; ${t.accessor} is in ${e.unit}`,{from:e.unit,to:"ratio"});else{const s=n.states.get(o.input);"value"===t.rule&&e.unit!==s.unit&&i("unit",`${t.accessor} is in ${e.unit??"no unit"} and ${o.input} in ${s.unit}; say how one becomes the other`,{from:e.unit??"",to:s.unit})}const[l,h]="motion-speed"===o.kind?[0,3]:[n.states.get(o.input).min,n.states.get(o.input).max];if(void 0===e.min||void 0===e.max)return i("range",`${t.accessor} has no range; give it one inside ${l} to ${h}`,{within:[l,h]});const d=[a*e.min+c,a*e.max+c].sort((t,e)=>t-e);(d[0]<l||d[1]>h)&&i("range",`${t.accessor} gives ${d[0]} to ${d[1]}; ${AS(o)} takes ${l} to ${h}`,{min:d[0],max:d[1],within:[l,h]})}(t,l,n,s),t}function PS(t){const e=t.dataInterface;if(void 0===e)return;bS(e,["version","schema","bindings"],[],"dataInterface"),"figure-data-interface-2"!==e.version&&gS("VERSION","dataInterface.version",String(e.version)),Array.isArray(e.schema)||gS("ASSET_SCHEMA","dataInterface.schema","a list of fields"),Array.isArray(e.bindings)||gS("ASSET_SCHEMA","dataInterface.bindings","a list of bindings"),SS(e.schema,"dataInterface.schema");const n=(t=>({states:new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),palette:t.palette,groups:new Map((t.motionGroups??[]).map(t=>[t.id,t.clips])),parts:new Set(t.appearance.map(t=>t.target))}))(t),s=new Set,i=new Map,o=(t,e,n,s,o)=>{const r=i.get(t);void 0!==r&&yS(o,`${r} and ${s} both write ${t}; one writer each`,{reason:"data-behavior-duplicate",bindings:[r,s],behavior:e,id:n}),i.set(t,s)};e.bindings.forEach((t,i)=>{const r=`dataInterface.bindings[${i}]`,a=OS(t,e.schema,n,r);if(s.has(a.id)&&yS(`${r}.id`,`${a.id} is declared twice`,{reason:"data-id-duplicate",list:"bindings",id:a.id}),s.add(a.id),"table"===a.rule){for(const t of function(t){const e=(t.targets.inputs??[]).map(t=>({key:`state ${t}`,behavior:"state",id:t})),n=t.targets.group;if(void 0!==n){const s=Object.values(t.table);for(const[t,i]of kS)s.some(e=>void 0!==e[t])&&e.push({key:`${i} ${n}`,behavior:i,id:n})}return e}(a))o(t.key,t.behavior,t.id,a.id,`${r}.targets`);return}const c=(t=>"state"===t.kind?`state ${t.input}`:"palette"===t.kind?`palette ${t.token}`:"pose"===t.kind?`pose ${t.axis}`:"items"===t.kind?null:`${t.kind} ${t.group}`)(a.behavior);null!==c&&o(c,a.behavior.kind,AS(a.behavior),a.id,`${r}.behavior`)})}const IS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function DS(t){const e=t.motionGroups;if(void 0===e)return;Array.isArray(e)||IS("ASSET_SCHEMA","motionGroups","a list of motion groups");const n=new Map;for(const e of t.drivers??[])n.set(e.clip,[...n.get(e.clip)??[],e]);const s=new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),i=new Set,o=new Map;e.forEach((t,e)=>{const r=`motionGroups[${e}]`;!function(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||IS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||IS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||IS("ASSET_SCHEMA",s,`unknown ${i}`)}(t,["id","label","clips","defaultClip","transitionSeconds"],[],r),"string"==typeof t.id&&fS.test(t.id)||IS("MOTION_GROUP",`${r}.id`,`${String(t.id)} is not an id: a letter, then letters, digits, - and _`,{reason:"data-id-invalid",list:"motion-groups",id:String(t.id)}),i.has(t.id)&&IS("MOTION_GROUP",`${r}.id`,`${t.id} is declared twice`,{reason:"data-id-duplicate",list:"motion-groups",id:t.id}),i.add(t.id),"string"==typeof t.label&&t.label.trim()||IS("MOTION_GROUP",`${r}.label`,"a name shown to a person"),Array.isArray(t.clips)&&t.clips.length||IS("MOTION_GROUP",`${r}.clips`,"one or more clips"),new Set(t.clips).size!==t.clips.length&&IS("MOTION_GROUP",`${r}.clips`,"each clip once");for(const e of t.clips){"string"==typeof e&&n.has(e)||IS("MOTION_GROUP",`${r}.clips`,`${String(e)} is not a clip of this figure`,{reason:"motion-clip-absent",group:t.id,clip:String(e)});const i=o.get(e);void 0!==i&&IS("MOTION_GROUP",`${r}.clips`,`${e} is already in ${i}; a clip is in one group`,{reason:"motion-clip-shared",clip:e,groups:[i,t.id]}),o.set(e,t.id);for(const t of n.get(e)){const n=s.get(t.state);if(t.accumulates)continue;const i=t.keys.find(t=>t.value<n.min||t.value>n.max);i&&IS("MOTION_GROUP",`drivers.${t.id}`,`${e} keys ${t.state} at ${i.value}, outside ${n.min} to ${n.max}`,{reason:"value-outside-range",input:t.state,value:i.value,min:n.min,max:n.max})}}t.clips.includes(t.defaultClip)||IS("MOTION_GROUP",`${r}.defaultClip`,`${String(t.defaultClip)} is not a clip of ${t.id}`,{reason:"motion-clip-absent",group:t.id,clip:String(t.defaultClip)}),"number"==typeof t.transitionSeconds&&Number.isFinite(t.transitionSeconds)&&t.transitionSeconds>=0||IS("MOTION_GROUP",`${r}.transitionSeconds`,"seconds, zero or more")})}function zS(t){const e=new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),n=new Map;for(const e of structuredClone(t.drivers??[])){const t=n.get(e.clip)??{duration:e.time.duration,drivers:[]};t.drivers.push(e),n.set(e.clip,t)}const s=new Map;for(const n of t.drivers??[]){const i=e.get(n.state).unit,o=s.get(n.state);s.set(n.state,{unit:i,phase:(o?.phase??!1)||n.accumulates,default:t.stateDefaults[n.state]})}const i=new Map,o=new Set;for(const e of structuredClone(t.motionGroups??[])){const t=new Set(e.clips.flatMap(t=>n.get(t).drivers.map(t=>t.state)));e.clips.forEach(t=>o.add(t)),i.set(e.id,Object.freeze({group:Object.freeze(e),states:Object.freeze([...t].sort())}))}return Object.freeze({groups:i,independentClips:Object.freeze([...n.keys()].filter(t=>!o.has(t))),clips:n,states:s})}function RS(t,e,n){const s=(e,n)=>{if(null!=e){("object"!=typeof e||Array.isArray(e))&&IS("MOTION_SETTING",n,"a setting per group");for(const s of Object.keys(e)){const i=t.groups.get(s),o=e[s];i||IS("MOTION_SETTING",`${n}.${s}`,`${s} is not a motion group of this figure`,{reason:"motion-setting",why:"group-unknown",group:s}),o&&"object"==typeof o||IS("MOTION_SETTING",`${n}.${s}`,"a setting",{reason:"motion-setting",why:"group-unknown",group:s}),void 0===o.clip||i.group.clips.includes(o.clip)||IS("MOTION_SETTING",`${n}.${s}.clip`,`${String(o.clip)} is not a clip of ${s}`,{reason:"motion-setting",why:"clip-not-in-group",group:s,clip:String(o.clip)}),void 0===o.speed||"number"==typeof o.speed&&o.speed>=0&&o.speed<=3||IS("MOTION_SETTING",`${n}.${s}.speed`,"a speed is 0 to 3",{reason:"motion-setting",why:"speed-out-of-range",group:s,speed:Number(o.speed)}),void 0!==o.paused&&"boolean"!=typeof o.paused&&IS("MOTION_SETTING",`${n}.${s}.paused`,"true or false")}}};s(e,"manual"),s(n,"data");const i=Object.create(null);for(const[s,{group:o}]of t.groups){const t=e&&Object.hasOwn(e,s)?e[s]:{},r=n&&Object.hasOwn(n,s)?n[s]:{},a=void 0!==r.clip?[r.clip,"data"]:void 0!==t.clip?[t.clip,"manual"]:[o.defaultClip,"default"],c=void 0!==r.speed?[r.speed,"data"]:void 0!==t.speed?[t.speed,"manual"]:[0,"default"];i[s]={clip:a[0],speed:c[0],paused:r.paused??t.paused??!1,sources:{clip:a[1],speed:c[1]}}}return i}const jS=t=>"deg"===t||"rad"===t?t:"other";function $S(t,e,n={}){for(const n of t.groups.keys())e&&Object.hasOwn(e,n)||IS("MOTION_SELECTION_REQUIRED",`selection.${n}`,`which clip of ${n} plays is not said`,{reason:"motion-setting",why:"group-selection-required",group:n});for(const n of Object.keys(e)){const s=t.groups.get(n);s||IS("MOTION_SETTING",`selection.${n}`,`${n} is not a motion group of this figure`,{reason:"motion-setting",why:"group-unknown",group:n}),s.group.clips.includes(e[n])||IS("MOTION_SETTING",`selection.${n}`,`${String(e[n])} is not a clip of ${n}`,{reason:"motion-setting",why:"clip-not-in-group",group:n,clip:String(e[n])})}const s=Object.create(null),i=e=>{const i=Object.hasOwn(n,e)?n[e]:0;for(const n of t.clips.get(e).drivers)s[n.state]=US(n,i,jS(t.states.get(n.state).unit))};for(const e of t.independentClips)i(e);for(const[n,o]of t.groups){for(const e of o.states)s[e]=t.states.get(e).default;i(e[n])}return s}function LS(t,e,n,s){Number.isFinite(s)&&s>=0&&s<=1||IS("MOTION_SETTING","alpha","a fraction from 0 to 1");const i=Object.create(null);for(const o of Object.keys(n)){const r=n[o],a=Object.hasOwn(e,o)?e[o]:void 0;if(void 0===a){i[o]=r;continue}const c=t.states.get(o),l=c?jS(c.unit):"other";if(c?.phase&&"other"!==l){const t="deg"===l?180:Math.PI;let e=GS(r-a,l);e===-t&&(e=t),i[o]=GS(a+s*e,l)}else i[o]=a+s*(r-a)}return i}const FS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function NS(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function HS(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||FS("DRIVER","drivers","array required");const n=NS(t),s=new Set,i=new Map,o=function(t){const e=new Map,n=t.motionGroups;if(!Array.isArray(n))return e;for(const t of n)if(t&&"string"==typeof t.id&&Array.isArray(t.clips))for(const n of t.clips)"string"!=typeof n||e.has(n)||e.set(n,t.id);return e}(t),r=new Map;for(const t of e){const e=`drivers.${String(t?.id??"?")}`,a=t=>t&&"object"==typeof t?Object.keys(t).sort():null;JSON.stringify(a(t))!==JSON.stringify(["accumulates","clip","id","interpolation","keys","loop","state","time"])&&FS("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||FS("DRIVER",e,"id required"),s.has(t.id)&&FS("DRIVER",e,"duplicate driver id"),s.add(t.id),"string"==typeof t.clip&&t.clip.trim()||FS("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||FS("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`);const c=i.get(t.state)??[];c.includes(t.clip)&&FS("DRIVER_STATE",e,`clip ${t.clip} writes ${t.state} twice; one track per state in a clip`,{reason:"driver-writers",state:t.state,clips:[t.clip]});const l=o.get(t.clip);c.length&&(void 0===l||c.some(t=>o.get(t)!==l))&&FS("DRIVER_STATE",e,`${[...c,t.clip].join(", ")} all write ${t.state}; one writer per state, unless the clips are one motion group`,{reason:"driver-writers",state:t.state,clips:[...c,t.clip]}),i.set(t.state,[...c,t.clip]),JSON.stringify(a(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||FS("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||FS("DRIVER_TIME",e,"positive duration in seconds required");const h=r.get(t.clip);void 0===h?r.set(t.clip,t.time.duration):h!==t.time.duration&&FS("DRIVER_TIME",e,`clip "${t.clip}" already runs for ${h} s; one clip is one clock, so every driver in it shares a duration`),(!Array.isArray(t.keys)||t.keys.length<2)&&FS("DRIVER_KEYS",e,"at least two keys required");let d=-1/0;for(const n of t.keys)JSON.stringify(a(n))!==JSON.stringify(["at","value"])&&FS("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||FS("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>d||FS("DRIVER_KEYS",e,"key at values must strictly increase"),d=n.at,Number.isFinite(n.value)||FS("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&FS("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||FS("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||FS("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&FS("DRIVER",e,"accumulates must be a boolean");const u=n.get(t.state);t.accumulates&&"deg"!==u&&"rad"!==u&&FS("DRIVER_STATE",e,`an accumulating driver writes an angle; ${t.state} is in ${u}`)}}function BS(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const s=n[n.length-1];if(e>=s.at)return s.value;let i=0;for(;i<n.length-2&&n[i+1].at<=e;)i++;const o=n[i],r=n[i+1];if("step"===t.interpolation)return o.value;const a=r.at-o.at;return o.value+(e-o.at)/a*(r.value-o.value)}function GS(t,e){const n="deg"===e?360:2*Math.PI,s=n/2,i=((t+s)%n+n)%n-s;return i===s?-s:i}function US(t,e,n="other"){Number.isFinite(e)||FS("DRIVER_TIME",t.id,"finite time required");const s=Math.max(0,e),i=t.time.duration,o=t.keys[0].value,r=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=BS(t,Math.min(s/i,1));else{const e=Math.floor(s/i);a=BS(t,(s-e*i)/i),t.accumulates&&(a+=e*(r.value-o))}return t.accumulates?"deg"===n||"rad"===n?GS(a,n):FS("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}function VS(t,e,n,s){Number.isFinite(t)&&Number.isFinite(e)||FS("STATE_INPUT","advanceStateValue","finite values required"),(!Number.isFinite(s)||s<0)&&FS("STATE_INPUT","advanceStateValue","a non-negative step in seconds required");const i=n.sweep,o=n.max-n.min;if(!(i&&o>0))return e;const r=o/i*s;if(!(r>0))return t;const a=e-t;return Math.abs(a)<=r?e:t+Math.sign(a)*r}const WS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function YS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||WS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||WS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||WS("ASSET_SCHEMA",s,`unknown ${i}`)}function qS(t){return function(t,e,n=!1){const s=t&&"object"==typeof t?t:void 0,i=s?KS.get(s):void 0;if(i&&i.kernel===Ix&&(i.joints||!e))return i.compiled;oS(t);const o=t,r=iS(JSON.stringify(o));r>nS&&WS("DOCUMENT_LIMIT","asset","over 1 MiB",{reason:"document-too-large",max:nS,at:r});YS(o,["version","name","document","designInputs","stateDefaults","palette","appearance"],["mountingFace","item","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs","extensions","dataInterface","motionGroups"],"asset"),void 0!==o.extensions&&function(t){t&&"object"==typeof t&&!Array.isArray(t)||lS("ASSET_SCHEMA","extensions","an object of {owner}/{name} keys");const e=Object.keys(t);e.length||lS("ASSET_SCHEMA","extensions","no keys; leave the field out"),e.length>16&&lS("EXTENSION_LIMIT","extensions",`${e.length} keys; at most 16`);for(const n of e){const e=`extensions.${n}`;hS(n,e),dS(t[n],e)}}(o.extensions);void 0===o.placement||uS.includes(o.placement)||WS("ASSET_SCHEMA","placement",`one of ${uS.join(", ")} required`);void 0!==o.item&&!0!==o.item&&WS("ASSET_SCHEMA","item","true when the figure is an item; left out when it is not");"figure-asset-1"!==o.version&&WS("VERSION","asset",o.version);"string"==typeof o.name&&o.name.trim()||WS("ASSET_SCHEMA","name","nonempty name required");const a=structuredClone(o),c=rS(a.document),l=a.document.model,h=l.inputs.filter(t=>"state"!==t.role).map(t=>t.id),d=l.inputs.filter(t=>"state"===t.role).map(t=>t.id);YS(a.designInputs,h,[],"designInputs"),void 0===a.detailLevel||(t=>Gv.includes(t))(a.detailLevel)||WS("ASSET_SCHEMA","detailLevel",`${String(a.detailLevel)} is not a detail level; ${Gv.join(", ")}`);if(void 0!==a.sizing){"uniform"!==a.sizing&&WS("ASSET_SCHEMA","sizing",`${String(a.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])l.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||WS("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(YS(a.stateDefaults,d,[],"stateDefaults"),void 0!==a.publicInputs){Array.isArray(a.publicInputs)||WS("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,n]of a.publicInputs.entries()){const s=`publicInputs[${e}]`;YS(n,["input","label"],["hint"],s),aS(l.inputs,n.input,`${s}.input`),"string"==typeof n.label&&n.label.trim()||WS("ASSET_SCHEMA",`${s}.label`,"a name shown on the board"),void 0!==n.hint&&"string"!=typeof n.hint&&WS("ASSET_SCHEMA",`${s}.hint`,"one line"),t.has(n.input)&&WS("PUBLIC_INPUT",`${s}.input`,`${n.input} is listed twice`),t.add(n.input)}}a.palette&&"object"==typeof a.palette&&!Array.isArray(a.palette)||WS("ASSET_SCHEMA","palette","token to hex color map required");for(const[t,e]of Object.entries(a.palette))t.trim()&&pS(e)||WS("PALETTE","palette","six digit hex color required");const u=t=>{"string"==typeof t&&Object.hasOwn(a.palette,t)||WS("PALETTE",String(t),"unresolved color token")},p=new Map(l.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),f=new Map(l.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),m=new Map;Array.isArray(a.appearance)||WS("ASSET_SCHEMA","appearance","array required");for(const t of a.appearance){if(YS(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=c.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||WS("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(f.has(t.target)&&!m.has(t.target)||WS("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),YS(t.material,["token"],["preset","transparent","emissive"],"material"),u(t.material.token),void 0===t.material.preset||["default","metal","glass","plastic","wood","ceramic","rubber"].includes(t.material.preset)||WS("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&WS("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;YS(e,["token","intensity","on"],[],"emissive"),u(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&WS("MATERIAL","emissive","invalid intensity or switch")}const e=p.get(f.get(t.target).args[0]);"revolve@1"===e?.op||"extrude@1"===e?.op&&"ellipse"===e.params?.section?[8,12,16,24,32,48].includes(t.segments)||WS("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&WS("QUALITY","segments","segments unsupported on this provider"),m.set(t.target,t)}m.size!==f.size&&WS("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==a.mountingFace){const t=a.mountingFace;YS(t,["plane","surface"],[],"mountingFace"),"mounting-plane"!==t.plane&&WS("MOUNTING_FACE","mountingFace",`${String(t.plane)} is not a plane the figure can be mounted on`),_M({types:c.outputTypes,writers:p,model:l,assetFrame:a.document.capabilities.assetFrame},t.surface,"mountingFace.surface")}HS(a),DS(a),PS(a),function(t){const e=t.stateInputs;if(void 0===e)return;e&&"object"==typeof e&&!Array.isArray(e)||FS("STATE_INPUT","stateInputs","object required");const n=NS(t);for(const[t,s]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||FS("STATE_INPUT",e,`${t} is not a state input of this asset`),s&&"object"==typeof s&&!Array.isArray(s)||FS("STATE_INPUT",e,"object required");for(const t of Object.keys(s))"label"!==t&&"sweep"!==t&&FS("STATE_INPUT",e,`unknown ${t}`);void 0===s.label||"string"==typeof s.label&&s.label.trim()||FS("STATE_INPUT",e,"label must be a nonempty string"),void 0===s.sweep||Number.isFinite(s.sweep)&&s.sweep>=0||FS("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(a),void 0===a.joints||Array.isArray(a.joints)||WS("ASSET_SCHEMA","joints","joints is a list");function g(t={}){YS(t,[],d,"state overrides");const e={...a.designInputs,...a.stateDefaults,...t},n=c.evaluate(e),s=t=>t.key?p.get(t.key)?.id:t.id,i=new Map(a.appearance.map((t,e)=>[t.target,e])),o=n.geometry.map((t,e)=>({g:t,i:e,at:i.get(s(t))??Number.MAX_SAFE_INTEGER})).sort((t,e)=>t.at-e.at||t.i-e.i).map(t=>t.g),r=o.map(t=>{const e=s(t),i=m.get(e);return i||WS("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(i.material),visible:void 0===i.visibility||n.values[i.visibility],...void 0!==i.segments?{segments:i.segments}:{}}});return{...n,geometry:r,inputs:e,palette:structuredClone(a.palette)}}(function(t){const e=t.joints;if(!e?.length)return;const n=structuredClone(t);for(const t of e)dM({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);yM(n);const s=t=>JSON.stringify({nodes:[...t.nodes].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0),inputs:[...t.inputs].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0)});s(n.document.model)!==s(t.document.model)&&Nx("JOINT_DRIFT","joints","the joints' nodes are not what their records make; the asset was edited apart from its joints")})(a),g();const y={evaluate:g};s&&n&&(KS.set(s,{kernel:Ix,joints:e,compiled:y}),JS&&QS(s));return y}(t,!0)}function XS(t){return t.placement??"floor"}const KS=new WeakMap,JS=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function QS(t){if(t&&"object"==typeof t&&!Object.isFrozen(t)){Object.freeze(t);for(const e of Object.values(t))QS(e)}}function ZS(t,e,n,s,i={}){const[o,r]=Kv[e],a=(t,s)=>{const a={x:0,y:0,z:0};return a[e]=n,a[o]=t+(i[o]??0),a[r]=s+(i[r]??0),[a.x,a.y,a.z]};if("polygon"===t.kind)return t.points.map(t=>a(t[o],t[r]));if("ellipse"===t.kind)return Array.from({length:s},(e,n)=>{const i=2*Math.PI*n/s;return a(t.radius[o]*Math.cos(i),t.radius[r]*Math.sin(i))});const c=t.size[o]/2,l=t.size[r]/2,h=t.corner?.[o]??0,d=t.corner?.[r]??0;if(!(h>0&&d>0))return[a(-c,-l),a(c,-l),a(c,l),a(-c,l)];const u=[];for(const[t,e,n]of[[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI],[1,-1,3*Math.PI/2]])for(let s=0;s<=8;s++){const i=n+s/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(i),e*(l-d)+d*Math.sin(i)))}return u}function tA(t,e){return function(t,e){const n=t.extrusion;if(n){const s=[...ZS(n.section,n.axis,n.start,e),...ZS(n.section,n.axis,n.end,e)],i=t.cavity;if(i){const t=c_(n.section,n.axis,i.wall);if("section"in t){const o=n.start+("open"===i.start?0:i.start.closed),r=n.end-("open"===i.end?0:i.end.closed);s.push(...ZS(t.section,n.axis,o,e,t.centre),...ZS(t.section,n.axis,r,e,t.centre))}}return s}const s=t.loft;if(s){const t={x:0,y:0,z:0,...s.apex,[s.axis]:s.end};return[...ZS(s.section,s.axis,s.start,e),[t.x,t.y,t.z]]}const i=t.revolution,[o,r]=Kv[i.axis],a=(t,n)=>ZS({kind:"ellipse",radius:{[o]:n,[r]:n}},i.axis,t,e);if("taper"===i.profile.kind)return[...a(i.profile.start,Math.max(i.profile.startRadius,1e-9)),...a(i.profile.end,Math.max(i.profile.endRadius,1e-9))];const{radial:c,axial:l}=i.profile,h=[];for(let t=1;t<6;t++){const e=t/6*Math.PI;h.push(...a(l*Math.cos(e),c*Math.sin(e)))}return h.push(...a(l,1e-9).slice(0,1),...a(-l,1e-9).slice(0,1)),h}(t,e??12)}function eA(t,e,n){return t.map(([t,s,i])=>[e[0][0]*t+e[0][1]*s+e[0][2]*i+n[0],e[1][0]*t+e[1][1]*s+e[1][2]*i+n[1],e[2][0]*t+e[2][1]*s+e[2][2]*i+n[2]])}function nA(t,e,n={}){return function(t,e,n={}){const s=[];for(const i of t){if(!("pose"in i))continue;if(!1===i.visible)continue;const t=i.key?e.get(i.key):i.id,o=i.shape,r=i.pose.r,a=jv.map((t,e)=>Gw(o,[r[e][0],r[e][1],r[e][2]])),c=B_(o),l={part:t,centre:{x:i.pose.t[0]+(a[0].max+a[0].min)/2,y:i.pose.t[1]+(a[1].max+a[1].min)/2,z:i.pose.t[2]+(a[2].max+a[2].min)/2},extent:{x:a[0].max-a[0].min,y:a[1].max-a[1].min,z:a[2].max-a[2].min},dims:jv.map(t=>c[t].max-c[t].min),rotation:r};n.points&&(l.points=eA(tA(i.shape,i.segments),r,i.pose.t)),s.push(l)}return s}(t.map(t=>"pose"in t?{...t,visible:!0}:t),e,n)}function sA(t){const e=new Map;for(const n of t.document.model.nodes)for(const t of Object.values(n.outputs))e.set(t,n.id);return e}const iA=t=>Math.round(1e6*t)/1e6;const oA=(t,e,n=1)=>({terms:[...t.terms,...e.terms.map(t=>({ref:t.ref,k:t.k*n}))],c:t.c+e.c*n}),rA=t=>{const e=new Map;for(const n of t.terms)e.set(n.ref,(e.get(n.ref)??0)+n.k);return{terms:[...e].filter(([,t])=>0!==t).map(([t,e])=>({ref:t,k:e})),c:t.c}},aA=(t,e)=>{const n=new Map;for(const s of[...rA(t).terms,...rA(e).terms])n.set(s.ref,Math.max(n.get(s.ref)??0,s.k));return{terms:[...n].map(([t,e])=>({ref:t,k:e})),c:Math.max(t.c,e.c)}},cA=(t,e)=>{const n=t.constants.find(t=>t.id===e);return n?{terms:[],c:n.value}:{terms:[{ref:e,k:1}],c:0}};function lA(t,e,n=new Set,s=0){t.inputs.some(t=>t.id===e&&"state"===t.role)&&n.add(e);const i=s<256?Bx(t,e):void 0;for(const e of i?.args??[])"string"==typeof e&&lA(t,e,n,s+1);return n}function hA(t,e){const n=new Set;for(let s=e;s;s=ow(t,s))for(const{motion:e}of sM(t,s))"axis-slide@1"===e.op&&lA(t,e.args[3],n);const s=[...n].sort();return s.length>10?{many:s}:s.length<=1?["min","max"]:Array.from({length:2**s.length},(t,e)=>Object.fromEntries(s.map((t,n)=>[t,e>>n&1?"max":"min"])))}const dA=(t,e)=>`${t} is slid by ${e.length} controls; this reading goes over at most 10 of them corner by corner`;function uA(t,e,n,s,i){const o=Object.fromEntries(i.map(t=>[t,"min"])),r=MA(t,e,n,s,o);if("string"==typeof r)return r;let a={terms:[],c:0};for(const c of i){const i=MA(t,e,n,s,{...o,[c]:"max"});if("string"==typeof i)return i;const l=kA(t,oA(i,r,-1));if(!l)return`${n}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;a=oA(a,l)}return[oA(r,a,-1),oA(r,a)]}function pA(t,e,n,s){const i=t=>"object"==typeof s?"min"===s[t.id]?t.min:t.max:"start"===s?e.stateDefaults[t.id]??t.min:"min"===s?t.min:t.max,o=e=>t.inputs.find(t=>t.id===e&&"state"===t.role),r=(e,n=0)=>{if(o(e))return!1;const s=n<256?Bx(t,e):void 0;return!s||s.args.every(t=>"string"!=typeof t||r(t,n+1))},a=(e,n=0)=>{const s=(e=>t.constants.find(t=>t.id===e)?.value)(e);if(void 0!==s)return{terms:[],c:s};const c=o(e);if(c)return{terms:[],c:i(c)};const l=n<256?Bx(t,e):void 0;if("add@1"===l?.op){let t={terms:[],c:0};for(const e of l.args){const s=a(e,n+1);if(!s)return null;t=oA(t,s)}return t}if("mul@1"===l?.op&&2===l.args.length){const s=e=>t.constants.find(t=>t.id===e);if(!l.args.every(s)&&l.args.some(t=>s(t)&&"ratio"!==s(t).unit))return r(e)?{terms:[{ref:e,k:1}],c:0}:null;const[i,o]=l.args.map(t=>a(t,n+1));return i&&o?i.terms.length?o.terms.length?null:oA({terms:[],c:0},i,o.c):oA({terms:[],c:0},o,i.c):null}return r(e)?{terms:[{ref:e,k:1}],c:0}:null};return a(n.args[3])}const fA=()=>({x:{terms:[],c:0},y:{terms:[],c:0},z:{terms:[],c:0}}),mA=(t,e)=>Object.fromEntries(jv.map((n,s)=>[n,jv.reduce((n,i,o)=>t[s][o]?oA(n,e[i],t[s][o]):n,{terms:[],c:0})])),gA=t=>null!==t&&Number.isFinite(t)&&Math.abs(t/90-Math.round(t/90))<1e-9;function yA(t,e,n){const s=Hx(t,`${n}.pose`),i=(s?.args.slice(3,6)??[]).map(n=>pw(t,e,n));return i.every(t=>0===t)?null:i.every(gA)?mw(i):"other"}const bA=(t,e)=>sM(t,e).some(t=>"axis-turn@1"===t.motion.op),vA=(t,e,n)=>(Hx(t,`${n}.seat.rigid`)?.args.slice(3,6)??[]).some(n=>0!==pw(t,e,n));function _A(t,e,n){for(let s=n;s;s=ow(t,s)){if(bA(t,s))return!0;if("other"===yA(t,e,s)||vA(t,e,s))return!0}return!1}function xA(t,e,n){let s=Sw;for(let i=n;i;i=ow(t,i)){const n=yA(t,e,i);if("other"===n)return null;n&&(s=gw(n,s))}return s}function wA(t,e,n,s,i){let o=i??fA();for(let r=n;r;r=ow(t,r)){const a=Hx(t,`${r}.pose`);if(!a)return`${r} has no pose this command can read`;if(r!==n||i){const n=yA(t,e,r);if("other"===n)return`${r} is turned by other than quarter turns, so what it carries is not a box this command can add up`;n&&(o=mA(n,o))}for(const[e,n]of jv.entries())o[n]=oA(o[n],cA(t,a.args[e]));for(const{motion:n}of sM(t,r)){if("axis-slide@1"!==n.op)return`${r} turns, so its reach is not a box this command can add up`;const i=n.args.slice(0,3).map(e=>t.constants.find(t=>t.id===e)?.value??null);if(i.some(t=>null===t))return`${r}'s slide axis is not a constant`;if(i.some(t=>0!==t)){const a=pA(t,e,n,s);if(!a)return`${r}'s travel is not a distance this command can read`;for(const[t,e]of jv.entries())i[t]&&(o[e]=oA(o[e],a,i[t]))}}const c=Hx(t,`${r}.seat.rigid`);if(c){if(c.args.slice(3,6).some(n=>0!==pw(t,e,n)))return`${r} is seated turned, which this command does not add up`;for(const[e,n]of jv.entries())o[n]=oA(o[n],cA(t,c.args[e]))}}return o}function MA(t,e,n,s,i){const o=wA(t,e,n,i);return"string"==typeof o?o:o[s]}function SA(t,e,n=0){if(n>64)return null;const s=t.constants.find(t=>t.id===e);if(s)return{terms:[],c:s.value};if(t.inputs.some(t=>t.id===e))return{terms:[{ref:e,k:1}],c:0};const i=Bx(t,e);if("add@1"===i?.op){let e={terms:[],c:0};for(const s of i.args){const i=SA(t,s,n+1);if(!i)return null;e=oA(e,i)}return e}if("mul@1"===i?.op&&2===i.args.length){const s=e=>t.constants.find(t=>t.id===e);if(!i.args.every(s)&&i.args.some(t=>s(t)&&"ratio"!==s(t).unit))return AA(t,e)?{terms:[{ref:e,k:1}],c:0}:null;const[o,r]=i.args.map(e=>SA(t,e,n+1));if(!o||!r)return null;if(!o.terms.length)return oA({terms:[],c:0},r,o.c);if(!r.terms.length)return oA({terms:[],c:0},o,r.c)}return AA(t,e)?{terms:[{ref:e,k:1}],c:0}:null}function AA(t,e,n=0){if(n>64)return!1;const s=t.inputs.find(t=>t.id===e);if(s)return"state"!==s.role&&(/^size\.[xyz]$/.test(s.id)||s.min>=0);const i=Bx(t,e),o=e=>(t.constants.find(t=>t.id===e)?.value??-1)>0;return"geomean@1"===i?.op?i.args.every(e=>AA(t,e,n+1)):"div@1"===i?.op?AA(t,i.args[0],n+1)&&o(i.args[1]):"mul@1"===i?.op&&(2===i.args.length&&(AA(t,i.args[0],n+1)&&o(i.args[1])||o(i.args[0])&&AA(t,i.args[1],n+1)))}function kA(t,e){let n={terms:[],c:0};const s=Gx(t,e);for(const e of s.terms){const s=SA(t,e.ref);if(!s){const s=CA(t,e.ref);if(!s)return null;n=oA(n,s,Math.abs(e.k));continue}for(const i of s.terms){if(!AA(t,i.ref))return null;n=oA(n,{terms:[{ref:i.ref,k:Math.abs(i.k*e.k)}],c:0})}n.c+=Math.abs(s.c*e.k)}return n.c+=Math.abs(s.c),n}function EA(t,e){const n=Bx(t,e);if("geomean@1"===n?.op&&!AA(t,e))return{root:[n.args[0],n.args[1]]};if("div@1"!==n?.op)return;const s=Bx(t,n.args[0]),i="mul@1"===s?.op?t.constants.find(t=>t.id===s.args[1]&&"ratio"===t.unit)?.value:void 0,o=i?Bx(t,s.args[0]):void 0;return"mul@1"===o?.op&&o.args[0]===o.args[1]?{point:{radius:o.args[0],sign:i>0?1:-1}}:void 0}function TA(t,e,n,s=0){const i=Gx(t,e);let o=[{terms:[],c:i.c}];for(const e of i.terms){let i=[{terms:[e],c:0}];const r=s<64?EA(t,e.ref):void 0;if(r){const o=e.k>0?n:!n;let a;if("root"in r){const e=r.root.map(e=>TA(t,{terms:[{ref:e,k:1}],c:0},o,s+1));a=o?e[0].flatMap(t=>e[1].map(e=>oA({terms:[],c:0},oA(t,e),.5))):e.flat()}else{a=r.point.sign>0===o?TA(t,{terms:[{ref:r.point.radius,k:r.point.sign}],c:0},o,s+1):[{terms:[],c:0}]}i=a.map(t=>oA({terms:[],c:0},t,e.k))}o=o.flatMap(t=>i.map(e=>oA(t,e)))}return o.map(rA)}function CA(t,e,n=!1){const s=Bx(t,e),i=EA(t,e);if(i&&"point"in i)return kA(t,{terms:[{ref:i.point.radius,k:1}],c:0});if(!i&&(!n||"max@1"!==s?.op&&"min@1"!==s?.op))return null;const o=s.args.map(e=>{const n=Gx(t,{terms:[{ref:e,k:1}],c:0});let s={terms:[],c:Math.abs(n.c)};for(const e of n.terms){const n=SA(t,e.ref)?kA(t,{terms:[e],c:0}):CA(t,e.ref,!0);if(!n)return null;s=oA(s,n,Math.abs(e.k))}return s});return o.some(t=>!t)?null:"geomean@1"===s.op?oA({terms:[],c:0},oA(o[0],o[1]),.5):o.reduce((t,e)=>aA(t,e))}const OA=(t,e)=>[0,1,2].map(n=>t[0][n]*e[0]+t[1][n]*e[1]+t[2][n]*e[2]),PA=t=>t.mid.map((e,n)=>Math.min(1,Math.abs(e)+t.spread[n]));function IA(t,e){const n=t.map((t,n)=>Math.max(-1,t-e[n])),s=t.map((t,n)=>Math.min(1,t+e[n]));return{mid:n.map((t,e)=>(t+s[e])/2),spread:n.map((t,e)=>(s[e]-t)/2)}}function DA(t,e){return IA(OA(e,t.mid),[0,1,2].map(n=>t.spread.reduce((t,s,i)=>t+Math.abs(e[i][n])*s,0)))}function zA(t,e,n,s){if(!s)return[t-Math.hypot(e,n),t+Math.hypot(e,n)];const[i,o]=s,r=s=>t+e*Math.cos(s)+n*Math.sin(s);let a=Math.min(r(i),r(o)),c=Math.max(r(i),r(o));const l=2*Math.PI;for(const t of[Math.atan2(n,e),Math.atan2(n,e)+Math.PI])for(let e=t+Math.ceil((i-t)/l)*l;e<=o;e+=l)a=Math.min(a,r(e)),c=Math.max(c,r(e));return[a,c]}function RA(t,e,n){const s=[[0,-e[2],e[1]],[e[2],0,-e[0]],[-e[1],e[0],0]],i=(t,n)=>e[t]*e[n],o=(t,n)=>(t===n?1:0)-e[t]*e[n],r=(t,e)=>s[t][e];if(n&&Math.abs(n[1]-n[0])<1e-12){const e=n[0];return DA(t,[0,1,2].map(t=>[0,1,2].map(n=>i(t,n)+o(t,n)*Math.cos(e)+r(t,n)*Math.sin(e))))}const a=(e,n)=>[0,1,2].reduce((s,i)=>s+e(i,n)*t.mid[i],0),c=[0,1,2].map(t=>zA(a(i,t),a(o,t),a(r,t),n)),l=[0,1,2].map(e=>t.spread.reduce((t,s,a)=>{const[c,l]=zA(i(a,e),o(a,e),r(a,e),n);return t+Math.max(Math.abs(c),Math.abs(l))*s},0));return IA(c.map(([t,e])=>(t+e)/2),c.map(([t,e],n)=>(e-t)/2+l[n]))}function jA(t,e,n=0){if(n>64)return null;const s=t.constants.find(t=>t.id===e);if(s)return"deg"===s.unit?[s.value,s.value]:null;const i=t.inputs.find(t=>t.id===e);if(i){if("state"!==i.role||"deg"!==i.unit)return null;const{min:t,max:e}=i;return Number.isFinite(t)&&Number.isFinite(e)&&e-t<360?[t,e]:null}const o=Bx(t,e);if("add@1"===o?.op){let e=0,s=0;for(const i of o.args){const o=jA(t,i,n+1);if(!o)return null;e+=o[0],s+=o[1]}return s-e<360?[e,s]:null}if("mul@1"===o?.op&&2===o.args.length){const e=e=>t.constants.find(t=>t.id===e&&"ratio"===t.unit)?.value,[s,i]=o.args,r=e(s)??e(i),a=void 0!==e(s)?jA(t,i,n+1):void 0!==e(i)?jA(t,s,n+1):null;if(void 0===r||!a)return null;const c=[a[0]*r,a[1]*r].sort((t,e)=>t-e);return c[1]-c[0]<360?c:null}return null}function $A(t,e,n){const s=[];for(let e=n;e;e=ow(t,e))s.push(e);const i=s.reduce((n,s,i)=>bA(t,s)||"other"===yA(t,e,s)||vA(t,e,s)?i:n,-1);if(i<0)return`${n} is carried by no turn`;const o=s[i],r=ow(t,o),a=r?xA(t,e,r):Sw;if(!a)return`${o} is carried by a part turned by other than quarter turns`;const c=dw(t,n,n),{shape:l}=Vx(t,n,n),h=I_(l)?.faces,d=Object.fromEntries(jv.map(t=>[t,uw(l,h,t)])),u=e=>e.map(e=>t.constants.find(t=>t.id===e)?.value),p=o=>{let r={mid:OA(a,o),spread:[0,0,0]},l={terms:[],c:0};const h=t=>Math.abs(t)<1e-12,p=(e,n)=>{const s=u(e);if(s.every(t=>void 0!==t)){const t=s.reduce((t,e,n)=>t+r.mid[n]*e+r.spread[n]*Math.abs(e),0),e=PA(r),n=Math.hypot(...s.map((t,n)=>e[n]>0?t:0));return l=oA(l,{terms:[],c:Math.min(t,n)}),null}for(const[s,i]of e.entries()){if(h(r.mid[s])||(l=oA(l,cA(t,i),r.mid[s])),h(r.spread[s]))continue;const e=kA(t,cA(t,i));if(!e)return`${n} is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,e,r.spread[s])}return null},f=n=>{const s=(n=>n.map(n=>pw(t,e,n)))(n);if(!s.every(t=>0===t))if(s.every(t=>null!==t&&Number.isFinite(t)))r=DA(r,(([t,e,n])=>gw(gw(Cw("x",t),Cw("y",e)),Cw("z",n)))(s));else{const t=Math.min(1,PA(r).reduce((t,e)=>t+e,0));r={mid:[0,0,0],spread:[t,t,t]}}};for(let n=i;n>=0;n--){const o=s[n],a=Hx(t,`${o}.seat.rigid`);if(a){if(n<i){const t=p(a.args.slice(0,3),`where ${o} is fastened`);if(t)return t}f(a.args.slice(3,6))}for(const{motion:n,through:s,back:i}of sM(t,o)){if(s){const t=p(s.args.slice(0,3),`the point ${o} turns about`);if(t)return t}const a=u(n.args.slice(0,3));if(a.some(t=>void 0===t))return`${o}'s ${"axis-turn@1"===n.op?"turn":"slide"} axis is not a constant`;const c=Math.hypot(...a),h=a.map(t=>t/c);if("axis-turn@1"===n.op){const e=jA(t,n.args[3]);r=RA(r,h,e&&[e[0]*Math.PI/180,e[1]*Math.PI/180])}else{if("axis-slide@1"!==n.op)return`${o} moves by ${n.op}, which this command does not add up`;{const s=r.mid.reduce((t,e,n)=>t+e*h[n],0),i=r.spread.reduce((t,e,n)=>t+e*Math.abs(h[n]),0),a=[...lA(t,n.args[3])].sort();if(a.length>10)return`${o}'s slide reads ${a.length} controls; how far it reaches is read over at most 10`;const c=a.length<=1?["min","max"]:Array.from({length:2**a.length},(t,e)=>Object.fromEntries(a.map((t,n)=>[t,e>>n&1?"max":"min"]))),d=c.map(s=>pA(t,e,n,s));if(d.some(t=>!t))return`${o}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;const[u,p]=2===d.length?d:[null,null],f=t=>!rA(t).terms.length&&Math.abs(t.c)<1e-12,m=e=>e.c>=0&&rA(e).terms.every(e=>e.k>0&&AA(t,e.ref)),g=u&&p?f(u)?p:f(p)?u:null:null,y=g&&(m(g)?1:m(oA({terms:[],c:0},g,-1))?-1:0);if(g&&y)l=oA(l,g,y*(Math.max(y*s,0)+i));else{const e=d.reduce((e,n)=>{const s=e&&kA(t,n);return s&&e&&aA(e,s)},{terms:[],c:0});if(!e)return`${o}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,e,Math.abs(s)+i)}}}if(i){const t=p(i.args.slice(0,3),`the point ${o} turns about`);if(t)return t}}const c=Hx(t,`${o}.pose`);if(!c)return`${o} has no pose this command can read`;const h=p(c.args.slice(0,3),`${o}'s place`);if(h)return h;f(c.args.slice(3,6))}for(const[e,s]of jv.entries()){const i=r.mid[e],o=r.spread[e];if(h(i)&&h(o))continue;const a=d[s];if(a){const e=i>0?a[1]:a[0];if(h(i)||(l=oA(l,{terms:[{ref:e.ref,k:e.k*i}],c:0})),h(o))continue;const s=a.reduce((e,n)=>{const s=e&&kA(t,{terms:[{ref:n.ref,k:n.k}],c:0});return s&&e&&aA(e,s)},{terms:[],c:0});if(!s)return`${n}'s size is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,s,o);continue}const u=kA(t,{terms:[{ref:c[s].ref,k:.5*c[s].k}],c:0});if(!u)return`${n}'s size is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,u,Math.min(1,Math.abs(i)+o))}return rA(l)},f={},m={};for(const[t,e]of jv.entries()){const n=[0,0,0];n[t]=1;const s=p(n);if("string"==typeof s)return s;n[t]=-1;const i=p(n);if("string"==typeof i)return i;f[e]=s,m[e]=i}const g=Hx(t,`${o}.seat.rigid`),y=Object.fromEntries(jv.map((e,n)=>[e,g?cA(t,g.args[n]):{terms:[],c:0}])),b=[],v=r?hA(t,r):["min"];if(!Array.isArray(v))return dA(r,v.many);for(const n of v){const s=r?wA(t,e,r,n,structuredClone(y)):y;if("string"==typeof s)return s;b.push(s)}return{centres:b,up:f,down:m}}function LA(t){const e=t.document.model,n=[],s=[],i={x:[],y:[],z:[]},o={x:[],y:[],z:[]},r={low:{x:[],y:[],z:[]},high:{x:[],y:[],z:[]}},a=(t,n)=>{const s=rA(oA(t,n,-1));return s.c>=-1e-9&&s.terms.every(t=>t.k>0&&AA(e,t.ref))},c=(t,e,n)=>{const s=r[t][e],i=(e,n)=>"high"===t?a(e,n):a(n,e);s.some(t=>i(t,n))||(r[t][e]=[...s.filter(t=>!i(n,t)),n])},l=t=>Hx(e,`${t}.repeat`),h=(n,s)=>{const i=function(t,e,n,s=!1){const{shape:i}=Vx(t,e,n),o=I_(i);if(o&&!s){const t={};for(const e of jv){const n=o.measure[e];if("profile"===n)t[e]={offsets:hw(i,e)};else{const s=uw(i,o.faces,e);t[e]=s?{offsets:s}:n.map(t=>({ref:i.args[t.arg],k:t.k}))}}return t}const r=dw(t,e,n);return{x:[r.x],y:[r.y],z:[r.z]}}(e,n,n,s),o=s?Sw:xA(e,t,n);if(!o)throw new Xv("EDIT_TARGET",n,`${n} is turned by other than quarter turns`);return Object.fromEntries(jv.map((t,e)=>{const n=o[e].findIndex(t=>0!==t),s=i[jv[n]];return[t,lw(s)&&o[e][n]<0?{offsets:s.offsets.map(t=>({...t,k:-t.k}))}:s]}))},d=n=>{const s=l(n),i=String(s.params?.axis??"").toLowerCase(),o=ow(e,n),r=o&&xA(e,t,o);if(!o||!jv.includes(i)||!r||jv.some((t,e)=>1!==r[e][e]))return`${n} is a row whose run this command cannot read`;const a=function(t,e,n,s,i=!0){const o=dw(t,n,s),r=fw(t,e,n,s,i),a={};return jv.forEach((t,e)=>a[t]=o[jv[r[e].findIndex(t=>0!==t)]]),a}(e,t,o,o,!1)[i],c={terms:[{ref:a.ref,k:.5*a.k}],c:0},d=hA(e,o);if(!Array.isArray(d))return dA(o,d.many);const u=d.map(n=>MA(e,t,o,i,n)),p=u.find(t=>"string"==typeof t);if(p)return String(p);const f=h(n,!1)[i];if(lw(f))return`${n} is a row of a drawn section along its section; how far each copy reaches is not added up`;const m=f[0],g={terms:[{ref:m.ref,k:m.k}],c:0},y=(t.joints??[]).find(t=>t.body1.part===n&&t.repeat)?.repeat;let b;if(y?.rise){const t=y.rise.mm;let e;if(void 0!==y.count)e={terms:[],c:(y.count-1)*t};else{if("number"!=typeof y.pitch)return`${n} is a rising row whose pitch follows a length; how far it rises is not added up`;e={terms:[{ref:a.ref,k:a.k*t/y.pitch},{ref:m.ref,k:-m.k*t/y.pitch}],c:0}}b={axis:y.rise.axis.toLowerCase(),up:t>0,reach:e}}return{axis:i,lows:u.map(t=>oA(t,c,-1)),highs:u.map(t=>oA(t,c,1)),extent:g,climb:b}};for(const r of e.nodes.filter(t=>"place@1"===t.op||"member@1"===t.op&&(l(t.id)||Ux(e,t.id)))){const a=_A(e,t,r.id);let u={};try{u=h(r.id,a)}catch(t){s.push({part:r.id,reason:t instanceof Xv?t.message:"not a part whose size this command can read"});continue}const p=[];let f;for(let t="member@1"===r.op?r.id:null;t;t=ow(e,t)){if(!l(t))continue;const e=d(t);if("string"==typeof e){f=e;break}p.push({part:t,run:e})}if(f){s.push({part:r.id,reason:f});continue}const m=new Set(p.map(t=>t.run.axis)),g=(t,e,n,s)=>{const i=p.map(t=>t.run.climb).filter(t=>t&&t.axis===s&&(t.up?1:-1)===e);i.length&&n[s].push(i.reduce((t,e)=>oA(t,e.reach),t))};if(a){const a=$A(e,t,r.id);if("string"==typeof a){s.push({part:r.id,reason:a});continue}if(n.push(r.id),p.length){for(const{run:t}of p){for(const e of t.lows)i[t.axis].push(oA(e,a.down[t.axis],-1));for(const e of t.highs)o[t.axis].push(oA(e,a.up[t.axis],1))}for(const t of a.centres)for(const e of jv.filter(t=>!m.has(t))){const n=oA(t[e],a.down[e],-1),s=oA(t[e],a.up[e],1);i[e].push(n),o[e].push(s),g(n,-1,i,e),g(s,1,o,e)}continue}for(const t of a.centres)for(const e of jv)c("low",e,rA(oA(t[e],a.down[e],-1))),c("high",e,rA(oA(t[e],a.up[e],1)));continue}const y=hA(e,r.id);if(!Array.isArray(y)&&p.some(t=>t.part!==r.id)){s.push({part:r.id,reason:dA(r.id,y.many)});continue}const b=jv.map(n=>({axis:n,at:Array.isArray(y)?y.map(s=>MA(e,t,r.id,n,s)):uA(e,t,r.id,n,y.many)})).map(t=>({axis:t.axis,at:"string"==typeof t.at?[t.at]:t.at})),v=b.flatMap(t=>t.at).find(t=>"string"==typeof t);if(v){s.push({part:r.id,reason:String(v)});continue}let _;for(const{part:n,run:s}of p){if(n===r.id){i[s.axis].push(...s.lows),o[s.axis].push(...s.highs);continue}const a=y.map(i=>MA(e,t,n,s.axis,i)),c=a.find(t=>"string"==typeof t);if(c){_=String(c);break}const l=b.find(t=>t.axis===s.axis).at,h=oA({terms:[],c:0},s.extent,.5),d=u[s.axis];if(lw(d)){_=`${r.id} is a drawn section carried along a row; how far each copy reaches is not added up`;break}for(const[t,e]of l.entries()){const n=oA(e,a[t],-1);for(const t of d){const e={terms:[{ref:t.ref,k:.5*t.k}],c:0};for(const t of s.lows)i[s.axis].push(oA(oA(oA(t,h),n),e,-1));for(const t of s.highs)o[s.axis].push(oA(oA(oA(t,h,-1),n),e))}}}if(_)s.push({part:r.id,reason:_});else{n.push(r.id);for(const t of b){if(m.has(t.axis))continue;const e=u[t.axis],n=new Set;for(const s of t.at){const r=JSON.stringify([s.terms.map(t=>[t.ref,t.k]).sort(),s.c]);if(n.has(r))continue;if(n.add(r),lw(e)){for(const n of e.offsets){const e=oA(s,{terms:[{ref:n.ref,k:n.k}],c:0});i[t.axis].push(e),o[t.axis].push(e),g(e,-1,i,t.axis),g(e,1,o,t.axis)}continue}const a=e.map(t=>({terms:[{ref:t.ref,k:.5*t.k}],c:0}));for(const e of a){const n=oA(s,e,-1),r=oA(s,e,1);i[t.axis].push(n),o[t.axis].push(r),g(n,-1,i,t.axis),g(r,1,o,t.axis)}}}}}return{parts:n,skipped:s,low:i,high:o,reaches:r}}const FA=(t,e)=>e.terms.reduce((e,n)=>e+n.k*(t[n.ref]??NaN),e.c);function NA(t,e={}){const n=structuredClone(t),{parts:s,skipped:i,low:o,high:r,reaches:a}=LA(n);for(const t of jv)o[t].push(...a.low[t]),r[t].push(...a.high[t]);if(function(t,e,n){for(const s of jv)e[s]=e[s].flatMap(e=>TA(t,e,!1)),n[s]=n[s].flatMap(e=>TA(t,e,!0))}(n.document.model,o,r),!s.length)return;const c=Px(n.document.model).evaluate({...n.designInputs,...n.stateDefaults,...e}).values,l=Object.fromEntries(jv.map(t=>[t,{min:rw(Math.min(...o[t].map(t=>FA(c,t)))),max:rw(Math.max(...r[t].map(t=>FA(c,t))))}]));return{bounds:l,parts:s,skipped:i}}function HA(t){const e=t.document.capabilities.slotLayout;if(!e)return;const n=t.document.model.nodes;return{label:e.label,role:e.role,anchors:e.anchors.map(t=>({id:t.id,part:n.find(e=>"place@1"===e.op&&e.outputs?.placed===t.pose.placement)?.id,face:n.find(e=>"feature@1"===e.op&&e.outputs?.pose===t.pose.feature)?.params?.name})),layout:structuredClone(e.layout)}}function BA(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,s=t.document.capabilities.bindings.map(t=>{const s="string"==typeof t.pose?null:t.pose,i=s?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===s.placement):null,o=s?Bx(e,s.feature):null,r=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:i?.id??null,face:o?.params?.name??null,...t.accepts?{accepts:[...t.accepts]}:{},capacity:t.capacity,region:3===r.length&&r.every(t=>"number"==typeof t)?{x:r[0],y:r[1],z:r[2]}:null}}),i=JM(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),s=Bx(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:s?.params?.name??null,...t.accepts?{accepts:[...t.accepts]}:{},capacity:t.capacity,region:{x:t.allowed.width,y:t.allowed.height,z:t.allowed.depth},slot:{tier:t.tier,slot:t.slot,anchorId:t.anchorId,tierPosition:{...t.tierPosition},tierRotation:t.tierRotation,offset:{...t.offset},rotation:t.rotation}}});return[...s,...i]}function GA(t){const e=(t,e,n)=>{throw new Xv("ITEM_SNAPSHOT",t,e,n)},n=t;n&&"object"==typeof n&&"string"==typeof n.revision&&Array.isArray(n.items)||e("snapshot","a revision and a list of items",{reason:"item-snapshot-shape"});const s=new Set,i=new Map;n.items.forEach((t,n)=>{const o=`items[${n}]`;t&&"string"==typeof t.itemId&&t.itemId&&"string"==typeof t.slotId&&t.slotId||e(o,"an item id and a slot id",{reason:"item-snapshot-shape"}),(!Number.isSafeInteger(t.stackIndex)||t.stackIndex<0)&&e(`${o}.stackIndex`,"a whole number from 0",{reason:"item-snapshot-shape"}),void 0!==t.type&&"string"!=typeof t.type&&e(`${o}.type`,"a type name",{reason:"item-snapshot-shape"}),void 0===t.dims||t.dims&&["width","depth","height"].every(e=>(t=>"number"==typeof t&&Number.isFinite(t))(t.dims[e])&&t.dims[e]>0)||e(`${o}.dims`,"three positive numbers in mm",{reason:"item-invalid-dimensions",item:t.itemId}),s.has(t.itemId)&&e(o,`${t.itemId} is in the snapshot twice`,{reason:"item-duplicate",item:t.itemId}),s.add(t.itemId),i.set(t.slotId,[...i.get(t.slotId)??[],t.stackIndex])});for(const[t,n]of i){const s=[...n].sort((t,e)=>t-e);s.forEach((n,i)=>{n!==i&&e("items",`the stack in ${t} has ${s.join(", ")}; each height once, from 0`,{reason:"item-stack-index",slot:t,heights:s})})}}function UA(t){const e=t.material,n=e.emissive?.on?`on:${e.emissive.token}:${e.emissive.intensity}`:"off";return`${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${n}`}const VA=t=>JSON.stringify([t.shape.provider,t.shape.dimensions,t.shape.extrusion?[t.shape.extrusion.axis,t.shape.extrusion.section.kind,t.shape.cavity??null]:t.shape.revolution?[t.shape.revolution.axis,t.shape.revolution.profile.kind]:t.shape.loft?[t.shape.loft.axis,"loft"]:t.shape.mesh?[t.shape.mesh.asset,t.shape.mesh.node??null]:null,t.segments??null,UA(t),!1!==t.visible]);function WA(t,e){const n=function(t,e){const n=e??rS(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=sA(t),o=t=>{const e=void 0===t?void 0:s.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!o("string"==typeof n?.[0]?n[0]:t.id)||!!e&&o(i.get(e))}}(t,e),s=sA(t),i=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target));return t=>{const e=new Set;for(const o of t){if(!("pose"in o)||n(o))continue;const t=o.key?s.get(o.key):o.id;void 0!==t&&i.has(t)||e.add(o.id)}return e}}function YA(t){const e=function(t){return new Set((t.dataInterface?.bindings??[]).flatMap(t=>"table"===t.rule?t.targets.parts??[]:[]))}(t),n=new Set(e);if(e.size)for(const s of t.document.model.nodes)if(e.has(s.id))for(const t of Object.values(s.outputs))n.add(t);return n}const qA=t=>!!t.shape?.mesh,XA=t=>`${UA(t)}|${!1!==t.visible?"shown":"hidden"}`;function KA(t,e={}){const n=[],s=new Set,i=new Map;for(const o of t){if(!("pose"in o))continue;if(e.own?.has(o.id)||"string"==typeof o.key&&e.own?.has(o.key)){n.push(o.id),s.add(o.id);continue}const t="key"in o&&"string"==typeof o.key?o.key:void 0;if(!t){n.push(o.id);continue}const r=i.get(t)??[];r.push(o),i.set(t,r)}const o=[],r=[];for(const[t,e]of i){const s=new Map;for(const t of e){const e=VA(t),n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}for(const[i,a]of s)qA(e.find(t=>t.id===a[0]))?(n.push(...a),r.push({member:t,ids:a,reason:"mesh"})):a.length>1?o.push({key:`${t}|${i}`,member:t,ids:a}):(n.push(...a),r.push({member:t,ids:a,reason:1===e.length?"one-copy":"copies-differ"}))}const a=[];if(e.still?.size){const i=new Map(t.map(t=>[t.id,t])),o=new Map;for(const t of n){const n=i.get(t);if(!n||s.has(t)||!e.still.has(t)||n.material.transparent||qA(n))continue;const r=XA(n),a=o.get(r);a?a.push(t):o.set(r,[t])}const r=new Set;for(const[t,e]of o)e.length<2||(a.push({key:t,ids:e}),e.forEach(t=>r.add(t)));r.size&&n.splice(0,n.length,...n.filter(t=>!r.has(t)))}const c=[];if(e.carried?.size){const i=new Map(t.map(t=>[t.id,t])),o=new Map;for(const t of n){const n=i.get(t),r=e.carried.get(t);if(!n||s.has(t)||void 0===r||e.still?.has(t)||n.material.transparent||qA(n))continue;const a=`${r}|${XA(n)}`,c=o.get(a);c?c.ids.push(t):o.set(a,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of o)n.length<2||(c.push({key:t,carrier:e,ids:n}),n.forEach(t=>r.add(t)));r.size&&n.splice(0,n.length,...n.filter(t=>!r.has(t)))}const l=new Map(t.map(t=>[t.id,t])),h=n.reduce((t,e)=>t+Math.max((t=>l.get(t)?.shape?.mesh?.primitives??1)(e),1)-1,0);return{batches:o,merged:a,carried:c,alone:n,unbatched:r,meshDraws:h}}const JA=Uv[0];function QA(t,e,n,s={}){const[i,o]=Kv[e],r=s[i]??0,a=s[o]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[i],t[o]]);else if("ellipse"===t.kind){const e=t.radius[i],s=t.radius[o];c=Array.from({length:n},(t,i)=>{const o=2*Math.PI*i/n;return[e*Math.cos(o),s*Math.sin(o)]})}else{const e=t.size[i]/2,n=t.size[o]/2,s=t.corner?.[i]??0,r=t.corner?.[o]??0;if(s>0&&r>0){c=[];for(const[t,i,o]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=JA;a++){const l=o+a/JA*(Math.PI/2);c.push([t*(e-s)+s*Math.cos(l),i*(n-r)+r*Math.sin(l)])}}else c=[[-e,-n],[e,-n],[e,n],[-e,n]]}return c=c.map(([t,e])=>[t+r,e+a]),ZA(c)<0?c.reverse():c}const ZA=t=>t.reduce((e,n,s)=>e+n[0]*t[(s+1)%t.length][1]-t[(s+1)%t.length][0]*n[1],0)/2;function tk(t){const e=[...t].sort((t,e)=>t[0]-e[0]||t[1]-e[1]).map(([t,e])=>[t,e]);if(e.length<3)return e;const n=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]),s=[];for(const t of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],t)<=1e-9;)s.pop();s.push(t)}const i=[];for(let t=e.length-1;t>=0;t--){const s=e[t];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],s)<=1e-9;)i.pop();i.push(s)}return s.slice(0,-1).concat(i.slice(0,-1))}const ek=t=>"shape"in t&&"pose"in t&&!!t.shape;function nk(t,e,n,s={}){const[i,o]=Kv.y;return QA(t,"y",n,s).map(([t,n])=>{const s={x:0,y:e,z:0};return s[i]=t,s[o]=n,[s.x,s.y,s.z]})}const sk=(t,e,n,s={})=>({allowed:{width:t,depth:e,height:n},...s}),ik=(t,e,n)=>({tierNo:t,anchorId:n.anchorId,mount:n.mount??"ON",position:{x:0,y:n.y??0,z:0},rotation:0,layout:e}),ok=t=>`fork_${t}`;function rk(t,e,n,s,i){return{tiers:[ik(1,{pattern:"GRID",rows:2,cols:2,pitch:{x:t.width/2,z:t.depth/2},order:e,origin:n,slot:sk(t.width/2,t.depth/2,t.slotHeight,s)},{anchorId:i})]}}const ak={agvTandem:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:2,pitch:t.width/2,axis:"X",origin:"MAX",slot:sk(t.width/2,t.depth,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),agvParallel:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:2,pitch:t.depth/2,axis:"Z",origin:"MIN",slot:sk(t.width,t.depth/2,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),agv2x2:(t,e,n={})=>rk(t,"COL_MAJOR",{x:"MAX",z:"MIN"},e,n.anchor??wM),bufferPort2x2:(t,e,n={})=>rk(t,"ROW_MAJOR",{x:"MIN",z:"MIN"},e,n.anchor??wM),multiBufferPort:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:4,pitch:t.width/4,axis:"X",origin:"MIN",slot:sk(t.width/4,t.depth,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),dualTierConveyor(t,e,n,s={}){const i=sk(t.width,t.depth,t.slotHeight,n),o=s.anchor??wM;return{tiers:[ik(1,{pattern:"SINGLE",slot:i},{anchorId:o}),ik(2,{pattern:"SINGLE",slot:{...i}},{anchorId:o,y:e})]}},craneTwinFork(t,e,n={}){const s=sk(t.width,t.depth,t.slotHeight,e),i=n.forks??[ok(1),ok(2)];return{tiers:[1,2].map(t=>ik(t,{pattern:"SINGLE",slot:{...s}},{anchorId:i[t-1]}))}},floorBlock:(t,e,n,s,i,o={})=>({tiers:[ik(1,{pattern:"GRID",rows:e,cols:n,pitch:{x:t.width/n,z:t.depth/e},slot:sk(t.width/n,t.depth/e,t.slotHeight,{...i,stackLimit:s})},{anchorId:o.anchor??wM})]}),single:(t,e,n,s={})=>({tiers:[ik(1,{pattern:"SINGLE",slot:sk(e.width,e.depth,e.slotHeight,n)},{anchorId:s.anchor??wM,mount:t})]})},ck={single:[],agvTandem:[],agvParallel:[],agv2x2:[],bufferPort2x2:[],multiBufferPort:[],dualTierConveyor:[{key:"upperElevation",integer:!1}],craneTwinFork:[],floorBlock:[{key:"rows",integer:!0},{key:"cols",integer:!0},{key:"stackLimit",integer:!0}]},lk=Object.keys(ck);function hk(t,e){const n=EM(t,{anchors:[...e]});if(n.length)return n;const s=TM(t);if(s.length)return s;const i=[],o=t=>Array.isArray(t)&&0===t.length;return t.tiers.forEach((t,e)=>{const n=t.layout;"CUSTOM"===n.pattern?n.slots.forEach((t,n)=>o(t.accepts)&&i.push(xM("ACCEPTS_EMPTY",`tiers[${e}].layout.slots[${n}].accepts`))):o(n.slot.accepts)&&i.push(xM("ACCEPTS_EMPTY",`tiers[${e}].layout.slot.accepts`))}),i}function dk(t,e,n){const s=null!=e?{source:"override",raw:e}:t?{source:"figure",raw:t}:void 0;if(!s)return{source:"none",status:"none",issues:[]};const i=hk(s.raw,n);return i.length?{source:s.source,status:"invalid",issues:i,refusal:{code:"SLOT_LAYOUT",details:{reason:"slot-layout-issues",issues:i}}}:{source:s.source,status:"valid",layout:s.raw,issues:[]}}function uk(t,e){const n=t.document.capabilities.slotLayout,s=dk(n?.layout,e,(n?.anchors??[]).map(t=>t.id));if("override"!==s.source)return{asset:t,effective:s};const i=structuredClone(t);return"valid"===s.status&&i.document.capabilities.slotLayout?i.document.capabilities.slotLayout.layout=structuredClone(s.layout):delete i.document.capabilities.slotLayout,{asset:i,effective:s}}function pk(t,e){const[n,s,i]=[Number(t?.state?.width),Number(t?.state?.height),Number(t?.state?.depth)];return[n,s,i].every(t=>Number.isFinite(t)&&t>0)?{width:n*e,depth:s*e,height:i*e}:null}function fk(t,e){const n=new Map;for(const s of t._items??[]){if(e&&s===e.item)continue;const t=s?.[_v];"string"==typeof t&&t&&(n.get(t)??n.set(t,[]).get(t)).push(s)}return e&&(n.get(e.slotId)??n.set(e.slotId,[]).get(e.slotId)).push(e.item),n}function mk(t,e=""){return gk(t,fk(t),e).snapshot}function gk(t,e,n){const s=new Map,i=new Set,o=[];let r=0;for(const[n,a]of e)a.forEach((e,a)=>{let c=hh(e);c&&!i.has(c)||(c=`#${r}`),r++,i.add(c),s.set(e,c);const l=t.itemTypeOf?.(e)??null,h=t.itemDimsOf?.(e)??null;o.push({itemId:c,slotId:n,stackIndex:a,...l?{type:l}:{},...h?{dims:h}:{}})});return{snapshot:{revision:n,items:o},ids:s}}function yk(t){return{tier:0,slotNo:0,anchorId:t.anchorId,mount:t.mount??"ON",tierPosition:{...t.frame.position},tierRotation:t.frame.rotation,offset:{x:0,z:0},allowed:{width:1/0,depth:1/0,height:1/0},stackLimit:1/0,rotation:0}}function bk(t,e){const n=FM(t),s=e?.position.y??0;return{position:{x:n.position.x,y:n.position.y+s,z:n.position.z},rotation:n.rotation,scale:e?.scale??1}}function vk(t,e,n,s,i,o){if(!t.itemShownDimsOf)return;let r=0;for(const a of s){const s=i.get(a),c=t.itemDimsOf?.(a)??("seated"===s.status?null:t.itemShownDimsOf(a,n,e)),l="seated"===s.status?s.inSlot:c?GM(c,n,r,o):null;if(!l||!c)return;r+=c.height*l.scale,"seated"!==s.status&&i.set(a,{...s,inSlot:l,inAnchor:bk(n,l),shrunk:l.scale<1,dims:c})}}function _k(t,e){const n=t.effectiveLayout?.layout,s=new Map((t.outsideSlots?.()??[]).map(t=>[t.id,t])),i=fk(t,e),o=new Map,r=new Map;for(const[e,n]of i){const i=s.get(e);if(!i){r.set(e,n);continue}const a=yk(i);let c=0,l=!0;n.forEach((n,s)=>{const r=t.itemDimsOf?.(n)??null,h={slotId:e,stackIndex:s,outside:!0,anchorId:i.anchorId,shrunk:!1,dims:r},d=l&&r?GM(r,a,c,0):null;if(!d){const t=l?"size-unknown":"below-unknown";return l=!1,o.set(n,{...h,status:"unconfirmed",why:t,inSlot:null,inAnchor:bk(a,null)})}c+=r.height,o.set(n,{...h,status:"seated",inSlot:d,inAnchor:bk(a,d)})}),vk(t,e,a,n,o,0)}const{snapshot:a,ids:c}=gk(t,r,""),l=new Map(function(t,e,n={}){GA(e);const s=n.margin??NM,i=new Map;for(const t of e.items)i.set(t.slotId,[...i.get(t.slotId)??[],t]);const o=new Map;for(const[e,r]of i){const i=[...r].sort((t,e)=>t.stackIndex-e.stackIndex),a=t?jM(e):null,c=a?zM(t,a):null;let l=0,h=!0;i.forEach((t,r)=>{const a=KM(c,{type:t.type,dims:t.dims??null},i.slice(0,r).map(t=>({type:t.type,dims:t.dims??null})),n.normalizeType?{normalizeType:n.normalizeType}:{}),d={itemId:t.itemId,slotId:e,stackIndex:t.stackIndex,fit:a};if(!c)return o.set(t.itemId,{...d,status:"unplaced",why:"slot-absent",seat:null,shrunk:!1});if(!h)return o.set(t.itemId,{...d,status:"unconfirmed",why:"below-unknown",seat:null,shrunk:!1});const u=t.dims?GM(t.dims,c,l,s):null;if(!u)return h=!1,o.set(t.itemId,{...d,status:"unconfirmed",why:"size-unknown",seat:null,shrunk:!1});l+=t.dims.height*u.scale,o.set(t.itemId,{...d,status:"seated",seat:u,shrunk:u.scale<1})})}return e.items.map(t=>o.get(t.itemId))}(n,a).map(t=>[t.itemId,t]));for(const[e,s]of c){const i=l.get(s),r=n?jM(i.slotId):null,a=r?zM(n,r):null;o.set(e,{slotId:i.slotId,stackIndex:i.stackIndex,status:i.status,...i.why?{why:i.why}:{},fit:i.fit,outside:!1,anchorId:a?.anchorId??null,inSlot:i.seat,inAnchor:a&&"unplaced"!==i.status?bk(a,i.seat):null,shrunk:i.shrunk,dims:t.itemDimsOf?.(e)??null})}for(const[e,s]of r){const i=n?jM(e):null,r=i?zM(n,i):null;r&&vk(t,e,r,s,o,NM)}return o}class xk{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const wk=new xk,Mk=[{id:"__default__",maxCount:1/0}];function Sk(t){const e={id:RM({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function Ak(t,e,n){const s=t.itemTypeOf?t.itemTypeOf(n):n?.state?.type??n?.type;return e.accepts?!!s&&e.accepts.includes(s):!e.allowedTypes?.length||!!s&&e.allowedTypes.includes(s)}function kk(t){var e;return e=class extends t{get slotLayout(){}get effectiveLayout(){const t=this.slotLayout,e=this.state?.slotLayout,n=this.slotAnchors(),s=n.join("\n"),i=this.__effectiveLayout;if(i&&i.declared===t&&i.override===e&&i.anchors===s)return i.value;const o=dk(t,e,n);return this.__effectiveLayout={declared:t,override:e,anchors:s,value:o},o}slotAnchors(){return[wM]}anchorObject3D(t){const e=this._realObject?.object3d;return t===wM&&e?function(t){let e=t.userData.itemAnchor;if(!e||e.parent!==t){const n=new w.Group;n.name="item-anchor";const s=n.updateMatrix.bind(n);n.updateMatrix=()=>{const t=n.parent?.scale;t&&n.scale.set(1/(t.x||1),1/(t.y||1),1/(t.z||1)),s()},t.add(n),t.userData.itemAnchor=n,e=n}return e.updateMatrix(),e}(e):null}outsideSlots(){return[]}itemTypeOf(t){const e=Wl(this);if(e)return Yl(e,t)?.code??null;const n=t?.state?.type??t?.type;return"string"==typeof n&&n?n:null}get mmPerSceneUnit(){return rh(this).mmPerUnit}itemDimsOf(t){const e=pk(t,this.mmPerSceneUnit);return e||(Wl(this)?null:Pv(t))}itemShownDimsOf(t,e,n){if(!Wl(this))return null;const{width:s,depth:i,height:o}=e.allowed;if(![s,i,o].every(t=>Number.isFinite(t)&&t>0))return Pv(t);return{width:s,depth:i,height:o/(Number.isFinite(e.stackLimit)&&e.stackLimit>0?e.stackLimit:1)}}itemSeatOf(t,e){const n=e??t?.[_v];if("string"!=typeof n||!n)return null;return _k(this,t?.[_v]===n&&this._items?.includes(t)?void 0:{item:t,slotId:n}).get(t)??null}get slots(){const t=this.effectiveLayout.layout;if(!t)return[];const e=[];for(const n of $M(t)){const s=zM(t,n);s&&e.push(Sk(s))}return e}slotById(t){const e=this.outsideSlots().find(e=>e.id===t);if(e)return{id:e.id,maxCount:1/0};const n=this.effectiveLayout.layout;if(n){const e=jM(t),s=e?zM(n,e):null;return s?Sk(s):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,s){const i=this.effectiveLayout.layout,o=i?jM(t):null,r=o?zM(i,o):null,a=r?UM(e,r,n,s):null;return a?{...a,anchorId:r.anchorId}:null}get arrangementStrategy(){return wk}canReceive(t,e){const n=null!==(void 0!==e?.slotId?this._slotIfAvailable(this.slotById(e.slotId),t):this.findSlot(t));return ep.log({role:"target",contract:"canReceive",component:this,args:{carrier:yv(t)},result:n}),n}findSlot(t){const e=this.slots.length?this.slots:Mk;for(const n of e){if(!Ak(this,n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),s=this._countOccupied(n.id);if(!(s>=e))return ep.log({role:"target",contract:"findSlot",component:this,args:{carrier:yv(t)},result:{slotId:n.id,occupied:s,max:e}}),n}return ep.log({role:"target",contract:"findSlot",component:this,args:{carrier:yv(t)},result:null}),null}acceptanceRotation(t,e){}deliveryWorldRotation(t){const e=this.acceptanceRotation?.(t);if(!e)return;const n=this._realObject?.object3d;if(!n)return;n.updateWorldMatrix(!0,!1);const s=new w.Quaternion;n.getWorldQuaternion(s);const i=new w.Quaternion(e.x,e.y,e.z,e.w);return s.clone().multiply(i)}deliveryWorldPosition(t){const e=this._realObject,n=e?.object3d;if(!n)return;n.updateWorldMatrix(!0,!1);const s=new w.Vector3;n.getWorldPosition(s);const i=this._receivingSurfaceLocalY();if(null!==i){const t=new w.Vector3(0,i,0);return n.localToWorld(t),{x:s.x,y:t.y,z:s.z}}return{x:s.x,y:s.y,z:s.z}}attachPointFor(t,e){const n=e?.slotId??t?.[_v];if(!n)return null;if("none"!==this.effectiveLayout.status||this.outsideSlots().length){const e=this.itemSeatOf(t,n),s=e?.anchorId&&e.inAnchor?this.anchorObject3D(e.anchorId):null;if(!e||!s)return null;const i=this.mmPerSceneUnit,o=e.inAnchor;return{attach:s,localPosition:{x:o.position.x/i,y:o.position.y/i,z:o.position.z/i},localRotation:{x:0,y:o.rotation*Math.PI/180,z:0},carryPolicy:"slot",displayScale:o.scale,slotId:n,seat:e}}const s=this.slots.find(t=>t.id===n);return s?{position:s.localPosition??{x:0,y:0,z:0},rotation:s.localRotation??{x:0,y:0,z:0},slotId:s.id}:null}placementFor(t,e={}){const n=t&&"object"==typeof t&&"state"in t?t:void 0,s=n?n.state??{}:t??{},i={width:Number(s.width)||0,height:Number(s.height)||0,depth:Number(s.depth)||0},o=e.slot??this.slots.find(t=>{const e=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<e});if(!o)return null;const r=e.index??this._countOccupied(o.id),a=e.occupantCount??r,c=this.arrangementStrategy.positionAt(r,o,a,n??{state:{...i}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+i.width/2-l/2,u=c.y+i.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-i.depth/2:i.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:o.localPosition&&Number.isFinite(o.localPosition.z)?o.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??i,o)??void 0;return b?{position:{x:d,y:y,z:u},rotation:b}:{position:{x:d,y:y,z:u}}}_zPosFromSeatY(t,e,n){const s=this._realObject,i=s?.receivingSurfaceY??0,o=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===i&&!o)return null;const r=Number(e)||0,a=s?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-r/2:r/2)+(s?.geometricOffsetY??0)-i}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!Ak(this,t,e))return null;const n=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<n?t:null}_countOccupied(t){const e=this._items;if(e)return e.filter(e=>e?.[_v]===t).length;const n=this.components;return n?n.filter(e=>e.parent===this&&e[_v]===t).length:0}},e.__hasCapacity=!0,e}function Ek(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,o=t.height??0;if(i<=0||o<=0)return[];const r="number"==typeof t.rotation?t.rotation:0,a=Math.cos(r),c=Math.sin(r),l=n+i/2,h=s+o/2,d="inbound"===e?-1:1;return[{lx:-i/2,lz:0,odx:-1,odz:0},{lx:i/2,lz:0,odx:1,odz:0},{lx:0,lz:-o/2,odx:0,odz:-1},{lx:0,lz:o/2,odx:0,odz:1}].map(t=>{var e,n;return{worldPos:(e=t.lx,n=t.lz,{x:l+e*a-n*c,z:h+e*c+n*a}),direction:{x:d*(t.odx*a-t.odz*c),z:d*(t.odx*c+t.odz*a)},halfSpan:0!==t.odx?o/2:i/2}})}function Tk(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,o=t.height??0;if(i<=0||o<=0)return{inbounds:[],outbounds:[]};const r="number"==typeof t.rotation?t.rotation:0,a=e??"reverse"===t.status,c="vertical"===t.orientation||"horizontal"!==t.orientation&&i<o,l=n+i/2,h=s+o/2,d=c?o/2:i/2,u=c?0:1,p=c?1:0,f=Math.cos(r),m=Math.sin(r),g=(t,e)=>({x:l+t*f-e*m,z:h+t*m+e*f}),y=c?{lx:0,lz:-d}:{lx:-d,lz:0},b=c?{lx:0,lz:d}:{lx:d,lz:0},v=g(y.lx,y.lz),_=g(b.lx,b.lz),x={x:u*f-p*m,z:u*m+p*f},w=Math.hypot(x.x,x.z)||1,M={x:x.x/w,z:x.z/w},S={x:-M.x,z:-M.z},A=(c?i:o)/2;return a?{inbounds:[{worldPos:_,direction:S,halfSpan:A}],outbounds:[{worldPos:v,direction:S,halfSpan:A}]}:{inbounds:[{worldPos:v,direction:M,halfSpan:A}],outbounds:[{worldPos:_,direction:M,halfSpan:A}]}}function Ck(t){const e=t.left??0,n=t.top??0,s=t.width??0,i=t.height??0;if(s<=0||i<=0)return null;const o="number"==typeof t.rotation?t.rotation:0,r="vertical"===t.orientation||"horizontal"!==t.orientation&&s<i,a=e+s/2,c=n+i/2,l=r?i/2:s/2,h=Math.cos(o),d=Math.sin(o),u=(t,e)=>({x:a+t*h-e*d,z:c+t*d+e*h});return{start:r?u(0,-l):u(-l,0),end:r?u(0,l):u(l,0)}}function Ok(t){const e=t.cx??0,n=t.cy??0,s=Math.abs(t.rx??100),i=Math.abs(t.ry??100),o=t.ratio??50,r=(s+s*o/100)/2,a=(i+i*o/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(s<=0||i<=0)return{inbounds:[],outbounds:[]};const d={x:e+r*Math.sin(c),z:n-a*Math.cos(c)},u={x:e+r*Math.sin(l),z:n-a*Math.cos(l)},p={x:Math.cos(c),z:Math.sin(c)},f={x:Math.cos(l),z:Math.sin(l)};return h?{inbounds:[{worldPos:u,direction:{x:-f.x,z:-f.z}}],outbounds:[{worldPos:d,direction:{x:-p.x,z:-p.z}}]}:{inbounds:[{worldPos:d,direction:p}],outbounds:[{worldPos:u,direction:f}]}}function Pk(t){const e=Tk(t),n=e.outbounds[0];if(!n)return{inbounds:Ek(t,"inbound"),outbounds:[]};const s=Ek(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,s=t.worldPos.z-n.worldPos.z;return Math.hypot(e,s)>1}),i=n.direction,o=[];for(const t of s){const e=t.direction.x*i.x+t.direction.z*i.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+i.x,s=t.direction.z+i.z,r=Math.hypot(n,s)||1;o.push({worldPos:t.worldPos,direction:{x:n/r,z:s/r},halfSpan:t.halfSpan})}return{inbounds:[...s,...o],outbounds:e.outbounds}}function Ik(t,e,n={}){const s=n.distance??5,i=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<i)return!1;const o=t.worldPos.x-e.worldPos.x,r=t.worldPos.z-e.worldPos.z;if("number"==typeof t.halfSpan&&"number"==typeof e.halfSpan){const n=t.direction.x,i=t.direction.z;if(Math.abs(o*n+r*i)>s)return!1;const a=Math.abs(o*-i+r*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(o,r)<=s}function Dk(t,e,n,s=0){const i=n.width??0,o=n.height??0;if(i<=0||o<=0)return!1;const r=(n.left??0)+i/2,a=(n.top??0)+o/2,c="number"==typeof n.rotation?n.rotation:0,l=Math.cos(-c),h=Math.sin(-c),d=t-r,u=e-a,p=d*l-u*h,f=d*h+u*l;return Math.abs(p)<=i/2+s&&Math.abs(f)<=o/2+s}function zk(t,e,n){const s=n.width??0,i=n.height??0;if(s<=0||i<=0)return 1/0;const o=(n.left??0)+s/2,r=(n.top??0)+i/2;let a=t.x-o,c=t.z-r,l=e.x,h=e.z;const d="number"==typeof n.rotation?n.rotation:0;if(0!==d){const t=Math.cos(-d),e=Math.sin(-d),n=a*e+c*t,s=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=s}const u=s/2,p=i/2;let f=-1/0,m=1/0;if(Math.abs(l)<1e-9){if(a<-u||a>u)return 1/0}else{const t=(-u-a)/l,e=(u-a)/l;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}if(Math.abs(h)<1e-9){if(c<-p||c>p)return 1/0}else{const t=(-p-c)/h,e=(p-c)/h;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}return m<f?1/0:f>=0?f:m>=0?Math.min(-f,m):-m}function Rk(t,e,n,s=6){return!!Dk(t.worldPos.x,t.worldPos.z,e,s)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function jk(t,e,n){return t.outbounds.map(t=>{const s=[];for(const i of e){let e=null;for(const s of i.topology.inbounds){if(!Ik(t,s,n))continue;const i=t.worldPos.x-s.worldPos.x,o=t.worldPos.z-s.worldPos.z,r=Math.hypot(i,o);(null===e||r<e)&&(e=r)}if(null===e&&i.bounds){const s=i.topology.outbounds[0]?.direction,o=!(i.topology.outbounds&&i.topology.outbounds.length)?n?.sinkMargin??30:6;if(Rk(t,i.bounds,s,o)){const n=zk(t.worldPos,t.direction,i.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(i.bounds.left??0)+(i.bounds.width??0)/2,s=(i.bounds.top??0)+(i.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-s)+1e3}}}null!==e&&s.push({id:i.id,dist:e})}return 0===s.length?null:(s.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),s[0].id)})}function $k(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const s=new Map,i=new Set;for(const n of t){const o=t.filter(t=>t.id!==n.id),r=jk(n.topology,o,e);s.set(n.id,r);for(const t of r)null!=t&&i.add(t)}const o=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const o=s.get(t)??[];o.includes(e)||(o.push(e),s.set(t,o),i.add(e))};for(const e of t)if(e.links){for(const t of e.links.downstream??[])o(e.id,t);for(const t of e.links.upstream??[])o(t,e.id)}const r=new Set,a=new Set;for(const e of t){(s.get(e.id)??[]).some(t=>null!=t)||r.add(e.id),i.has(e.id)||a.add(e.id)}return{nodes:n,out:s,sinks:r,sources:a}}function Lk(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const s=new Set([e]);for(const i of function(t,e,n){const s=n.get(e);if(s)return s;const i=new Set,o=[e],r=new Set([e]);for(;o.length;){const e=o.shift();for(const n of t.out.get(e)??[])null!=n&&(i.add(n),r.has(n)||(r.add(n),o.push(n)))}return n.set(e,i),i}(t,e,n))s.add(i);return s})}function Fk(t,e,n,s){return e===n?0:function(t,e,n){const s=n.get(e);if(s)return s;const i=new Map([[e,0]]),o=[e];for(;o.length;){const e=o.shift(),n=i.get(e);for(const s of t.out.get(e)??[])null==s||i.has(s)||(i.set(s,n+1),o.push(s))}return n.set(e,i),i}(t,e,s).get(n)??1/0}function Nk(t,e,n){const s=t.out.get(e)??[],i=new Map,o=[];for(let e=0;e<s.length;e++){const r=s[e];if(null==r)continue;const a=r===n?0:Fk(t,r,n,i);a!==1/0&&o.push({i:e,hops:1+a})}return o.sort((t,e)=>t.hops-e.hops||t.i-e.i),o.map(t=>t.i)}function Hk(t,e,n){const s=Nk(t,e,n);return s.length?s[0]:-1}function Bk(t,e,n){return e===n||Nk(t,e,n).length>0}function Gk(t,e){const n=new Set;for(const s of Lk(t,e))for(const e of s)t.sinks.has(e)&&n.add(e);return n}function Uk(t,e,n){return Vk(t,e,n).map(t=>t.index)}function Vk(t,e,n){const s=n instanceof Set?n:new Set(n);if(0===s.size)return[];const i=t.out.get(e)??[],o=new Map,r=[...s].sort(),a=[];for(let e=0;e<i.length;e++){const n=i[e];if(null==n)continue;let s=1/0,c="";for(const e of r){const i=1+(n===e?0:Fk(t,n,e,o));i<s&&(s=i,c=e)}s!==1/0&&a.push({index:e,hops:s,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function Wk(t,e={}){const n=[],s=e.loopCapableIds??new Set,i=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const s=t.nodes.get(e);if(!s||!s.topology.outbounds?.length)continue;const i=(t.out.get(e)??[]).some(t=>null!=t);i||n.push({severity:"error",code:"orphan-source",nodeId:e,message:`source 노드 "${e}" 가 outgoing edge 0 — 아무 데도 carrier 를 보낼 수 없음`})}for(const e of[...t.nodes.keys()].sort()){const s=(t.out.get(e)??[]).some(t=>null!=t);s||(i.has(e)||t.sources.has(e)||n.push({severity:"error",code:"dead-end",nodeId:e,message:`노드 "${e}" 가 outgoing 0 인데 RoutingTarget 자격 없음 — routing 미정의 종착`}))}const o=function(t){const e=[],n=[...t.nodes.keys()].sort(),s=new Set,i=[],o=new Set,r=n=>{s.add(n),i.push(n),o.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(o.has(a)){const t=i.indexOf(a),n=i.slice(t),s=n.indexOf([...n].sort()[0]),o=[...n.slice(s),...n.slice(0,s)],r=o.join("→");e.some(t=>t.join("→")===r)||e.push(o)}else s.has(a)||r(a);i.pop(),o.delete(n)};for(const t of n)s.has(t)||r(t);return e.sort((t,e)=>t[0].localeCompare(e[0])||t.length-e.length),e}(t);for(const t of o){const e=t.some(t=>s.has(t));e||n.push({severity:"error",code:"cycle",cycle:t,message:`의도 cycle 자격 (isLoop) 없는 cycle: ${t.join(" → ")} → ${t[0]}`})}const r=e.routingWeights;if(r)for(const[t,e]of[...r].sort((t,e)=>t[0].localeCompare(e[0])))(!Number.isFinite(e)||e<=0)&&n.push({severity:"warning",code:"invalid-weight",nodeId:t,message:`RoutingTarget "${t}" 의 routingWeight=${e} — weight ≤ 0 비정상, weight 정책에서 제외됨`});const a=new Set;for(const e of t.out.values())for(const t of e)null!=t&&a.add(t);for(const e of[...i].sort())t.nodes.has(e)&&(a.has(e)||n.push({severity:"warning",code:"unreachable-target",nodeId:e,message:`RoutingTarget "${e}" 에 incoming edge 0 — 누구도 이쪽으로 carrier 를 보내지 않음`}));return n.sort((t,e)=>t.code!==e.code?t.code.localeCompare(e.code):(t.nodeId??"").localeCompare(e.nodeId??"")),n}function Yk(t,e){if(!t)return[];const n=[],s=new Set,i=t=>{if(!t||s.has(t))return;if(s.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,s=t.refid??t.state?.refid,i="string"==typeof e&&e.length>0?e:null!=s?String(s):void 0;if(i)try{const e=t.getSegmentTopology(),s=t.state??{},o={left:s.left,top:s.top,width:s.width,height:s.height,rotation:s.rotation};e&&n.push({id:i,topology:e,bounds:o})}catch{}}const o=t?.components;if(Array.isArray(o))for(const t of o)i(t)};return i(t),n}function qk(t,e){const n=t.state?.targetRef??t.state?.downstreamRef;if("string"==typeof n&&n.length>0)return n;if("function"!=typeof t.getSegmentTopology)return null;const s=t.getSegmentTopology();if(!s||0===s.outbounds.length)return null;const i=Yk(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),o=jk(s,i,e);for(const t of o)if(t)return t;return null}function Xk(t){return!!t&&"function"==typeof t.routingConstraints}function Kk(t){return!!t&&"function"==typeof t.acceptedCarrierData}function Jk(t,e=16){const n=[],s=t.parent??t.rootModel??t.root;if(!s)return n;const i=qk(t);if(!i)return n;const o=tE(s,i);if(!o)return n;const r=[{segment:o,accumulated:{},pathIds:[i],visited:new Set([i])}];for(;r.length>0;){const t=r.shift();if(t.pathIds.length>e)continue;const i=Xk(t.segment)?t.segment.routingConstraints():null;if(i&&i.length>0)for(const e of i)for(const i of e.candidates){const o=Qk(t.accumulated,i);if(!o)continue;const a=Zk(t.segment,e.portId,s);a&&!t.visited.has(a.state?.id??"")?r.push({segment:a,accumulated:o,pathIds:[...t.pathIds,a.state?.id??"?"],visited:new Set([...t.visited,a.state?.id??""])}):n.push({data:o,weight:1,pathIds:[...t.pathIds,`${e.portId}`],destination:e.portId})}else{if(Kk(t.segment)){const e=t.segment.acceptedCarrierData(),s=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:s});else for(const i of e){const e=Qk(t.accumulated,i);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:s})}continue}const e=qk(t.segment);if(!e||t.visited.has(e)){n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:t.pathIds[t.pathIds.length-1]});continue}const i=tE(s,e);if(!i)continue;r.push({segment:i,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function Qk(t,e){const n={...t};for(const[t,s]of Object.entries(e)){if(t in n&&n[t]!==s)return null;n[t]=s}return n}function Zk(t,e,n){if("straight"===e&&t.state?.downstreamRef)return tE(n,t.state.downstreamRef);const s=tE(n,e);if(s)return s;const i=qk(t);return i?tE(n,i):null}function tE(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,s=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const i=t.components;if(Array.isArray(i))for(const t of i){const e=s(t);if(e)return e}return null};return s(t)}function eE(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function nE(t,e,n=5,s=[],i=n){const o=t.length,r=new Array(o).fill(void 0),a=new Set,c=(e,n)=>"start"===n?t[e].start:t[e].end,l=[],h=new Map,d=[],u=new Map;for(const t of s){const e=Array.isArray(t),n=e?t:t.positions,s=e?void 0:t.kind;if(!n.length)continue;const i=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:i});s&&u.set(i,s)}const p=(t,e)=>{const s=c(t,e),i=h.get(`${t}:${"end"===e?"start":"end"}`),o=[];for(const t of d)eE(t.pos,s)<=n&&!o.includes(t.pt)&&o.push(t.pt);for(let t=0;t<l.length;t++)eE(l[t].pos,s)<=n&&!o.includes(t)&&o.push(t);let r=o.find(t=>t!==i)??-1;r<0&&(r=l.length,l.push({pos:s,members:[]})),l[r].members.push({seg:t,end:e}),h.set(`${t}:${e}`,r)};for(let t=0;t<o;t++)p(t,"start"),p(t,"end");const f=new Set,m=new Set,g=new Set;{const t=t=>{let e=-1,n=1/0;for(let s=0;s<l.length;s++){const i=eE(l[s].pos,t);i<n&&(n=i,e=s)}for(const s of d){const i=eE(s.pos,t);i<n&&(n=i,e=s.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:s}=t(n.pos);e>=0&&s<=i&&(f.add(e),("source"===n.kind?m:g).add(e))}}for(const[t,e]of u)f.add(t),("source"===e?m:g).add(t);const y=(t,e)=>"end"===e!==r[t],b=[],v=(e,n)=>{if(void 0===r[e])return r[e]=n,void b.push(e);r[e]!==n&&a.add(t[e].id)},_=t=>{for(const e of["start","end"]){const n=h.get(`${t}:${e}`);if(void 0===n)continue;const s=l[n];if(2!==s.members.length||f.has(n))continue;const i=s.members[0],o=i.seg===t&&i.end===e?s.members[1]:i;if(o.seg===t)continue;const a="end"===e!==r[t],c="end"===o.end!==!a;v(o.seg,c)}},x=()=>{for(;b.length;)_(b.shift())},w=t=>{let e=-1,n="start",s=1/0;for(let i=0;i<o;i++)for(const o of["start","end"]){const r=eE(c(i,o),t.pos);r<s&&(s=r,e=i,n=o)}if(e<0||s>i)return;const r="source"===t.kind?"end"===n:"start"===n;v(e,r)};for(const t of e)"source"===t.kind&&w(t);x();for(const t of e)"sink"===t.kind&&w(t);x();let M=!0;for(;M;){M=!1;for(const t of l){if(t.members.length<3)continue;const e=t.members.filter(t=>void 0===r[t.seg]);if(1!==e.length)continue;let n=0,s=0;for(const e of t.members)void 0!==r[e.seg]&&(y(e.seg,e.end)?n++:s++);const i=e[0];let o;0===s&&n>0?o="end"===i.end:0===n&&s>0&&(o="start"===i.end),void 0!==o&&(r[i.seg]=o,b.push(i.seg),x(),M=!0)}}if(r.some(t=>void 0===t)&&m.size>0&&g.size>0){const t=t=>{const e=new Array(l.length).fill(1/0),n=[];for(const s of t)e[s]=0,n.push(s);for(;n.length;){const t=n.shift();for(const s of l[t].members){const i=h.get(`${s.seg}:${"start"===s.end?"end":"start"}`);void 0!==i&&e[i]>e[t]+1&&(e[i]=e[t]+1,n.push(i))}}return e},e=t(m),n=t(g);for(let t=0;t<o;t++){if(void 0!==r[t])continue;const s=h.get(`${t}:start`),i=h.get(`${t}:end`);if(void 0===s||void 0===i)continue;if(l[s].members.length<2||l[i].members.length<2)continue;if(e[s]===1/0||e[i]===1/0||n[s]===1/0||n[i]===1/0)continue;let o;e[s]!==e[i]?o=e[s]<e[i]:n[s]!==n[i]&&(o=n[i]<n[s]),void 0!==o&&(r[t]=!o,b.push(t))}x()}const S=new Map;for(let e=0;e<o;e++)S.set(t[e].id,void 0===r[e]?"unknown":r[e]?"reverse":"forward");return{directions:S,conflicts:[...a]}}function sE(...t){}function iE(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function oE(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}function*rE(t){if(!t)return;("function"==typeof t.getSegmentTopology||t.flowOrientable)&&(yield t);const e=t.components;if(Array.isArray(e))for(const t of e)yield*rE(t)}function aE(t,e,n){const s=e.width??0,i=e.height??0;if(s<=0||i<=0)return!1;const o=(e.left??0)+s/2,r=(e.top??0)+i/2,a="number"==typeof e.rotation?e.rotation:0,c=t.x-o,l=t.z-r,h=Math.cos(-a),d=Math.sin(-a),u=c*h-l*d,p=c*d+l*h;return Math.abs(u)<=s/2+n&&Math.abs(p)<=i/2+n}function cE(t){const e=[],n=[],s=[],i=[];for(const o of rE(t)){const t=oE(o);if(!t)continue;if(o.flowOrientable){const n=Ck(o.state??{});n&&e.push({id:t,start:n.start,end:n.end});continue}if("function"==typeof o.openings){const t=o.state??{};(t.width??0)>0&&(t.height??0)>0&&i.push(t);continue}let r;try{r=o.getSegmentTopology()}catch{continue}if(!r)continue;const a=r.inbounds??[],c=r.outbounds??[],l="function"==typeof o.routingDestination;if(0===a.length&&c.length>0)for(const t of c)n.push({pos:{x:t.worldPos.x,z:t.worldPos.z},kind:"source"});else if(a.length>0&&(0===c.length||l))for(const t of a)n.push({pos:{x:t.worldPos.x,z:t.worldPos.z},kind:"sink"});else if(a.length>0||c.length>0){const t=[];for(const e of a)t.push({x:e.worldPos.x,z:e.worldPos.z});for(const e of c)t.push({x:e.worldPos.x,z:e.worldPos.z});t.length&&s.push({positions:t})}}for(const t of i){const i=[];for(const n of e)for(const e of[n.start,n.end])aE(e,t,16)&&i.push(e);let o=!1,r=!1;for(const e of n)aE(e.pos,t,16)&&("sink"===e.kind?o=!0:r=!0);const a=o&&!r?"sink":r&&!o?"source":void 0;(i.length>=2||a&&i.length>=1)&&s.push({positions:i,kind:a})}if(0===e.length||0===n.length)return new Map;return nE(e,n,8,s,60).directions}function lE(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:cE(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const s=oE(t),i=s?n.map.get(s):void 0;return"reverse"===i||"forward"!==i&&void 0}function hE(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function dE(t,e,n,s){if(!t||!e)return null;const i=[],o=t=>{if(!t||t===s)return;if(og(t,e)&&hE(t)){const e=function(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}(t);e&&i.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const r=t.components;if(Array.isArray(r))for(const t of r)o(t)};return o(t),0===i.length?null:(i.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),i[0])}function uE(t){return!!t&&"function"==typeof t.routingDestination}function pE(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}function*fE(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*fE(t)}function mE(t){const e=[],n=new Map,s=new Map,i=new Set,o=[];for(const r of fE(t)){"function"==typeof r?.registerWithHost&&o.push(r);const t="function"==typeof r?.getSegmentTopology,a="function"==typeof r?.routingLinks?r.routingLinks():void 0,c=!(!a||!((a.downstream?.length??0)>0||(a.upstream?.length??0)>0));if(!(t||uE(r)||c||hE(r)))continue;const l=pE(r);if(!l)continue;let h={inbounds:[],outbounds:[]};if(t){try{h=r.getSegmentTopology()}catch{continue}if(!h)continue}const d=r.state??{},u={left:d.left,top:d.top,width:d.width,height:d.height,rotation:d.rotation};if(e.push({id:l,topology:h,bounds:u,links:a}),s.set(l,r),uE(r)){i.add(l);const t=r.routingDestination();if("string"==typeof t&&t.length>0){const e=n.get(t)??[];e.push(l),n.set(t,e)}}}return{nodes:e,destToSinks:n,components:s,routingTargetIds:i,stationClients:o}}function gE(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:s,components:i,routingTargetIds:o,stationClients:r}=mE(t),a=$k(n);!function(t,e){if(!t)return;const n=t=>{if(!t)return;"function"==typeof t.clearStations&&t.clearStations();const e=t.components;if(Array.isArray(e))for(const t of e)n(t)};n(t);const s=[...e].sort((t,e)=>{const n=pE(t)??"",s=pE(e)??"";return n.localeCompare(s)});for(const e of s){const n=e.declaredHostRef?.();let s=null;if(n&&(s=t.findById?.(n)??null),!s){const n=e.hostCapability?.(),i=e.hostFacingPoint?.();n&&i&&(s=dE(t,n,i,e)?.component??null)}s&&"function"==typeof e.registerWithHost&&e.registerWithHost(s)}const i=e=>{if(!e)return;if(hE(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const s=t.findById?.(n);s&&e.registerDivertStation(n,s)}const n=e.components;if(Array.isArray(n))for(const t of n)i(t)};i(t)}(t,r);const c=new Set;for(const[t,e]of i){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of o){const e=i.get(t);if("function"==typeof e?.routingWeight){const n=e.routingWeight();"number"==typeof n&&(!Number.isFinite(n)||n<=0)&&l.set(t,n)}}const h=Wk(a,{routingTargetIds:o,loopCapableIds:c,routingWeights:l});if(h.length>0&&"undefined"!=typeof console){const t=h.filter(t=>"error"===t.severity),e=h.filter(t=>"warning"===t.severity);t.length>0?console.warn(`[FlowGraph] ${t.length} error(s) / ${e.length} warning(s):`,h):console.info(`[FlowGraph] ${e.length} warning(s):`,h)}e={graph:a,destToSinks:s,components:i,issues:h},t.__flowGraph=e}return e}function yE(t){return gE(t)?.issues??[]}function bE(t){const e=gE(t);return e&&e.graph.nodes.size>0?e.graph:null}function vE(t,e){return gE(t)?.destToSinks.get(e)??[]}function _E(t,e){return gE(t)?.components.get(e)}function xE(t){const e=gE(t);return e?[...e.destToSinks.keys()]:[]}function wE(t){return pE(t)}function ME(t){const e="number"==typeof t?.inventoryCount?t.inventoryCount:"function"==typeof t?.size?t.size():0,n=t?.state?.capacity;return"number"==typeof n&&n>0?e/n:e}function SE(t,e,n,s,i){if(1===s.length)return s[0];switch(t){case"index":default:return s[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),s[t%s.length]}case"weight":{const t=s.map(t=>function(t){if("function"==typeof t?.routingWeight){const e=t.routingWeight();if("number"==typeof e&&Number.isFinite(e)&&e>0)return e}return 1}(i.get(t.target))),o=t.reduce((t,e)=>t+e,0);if(o<=0)return s[0];const r=n.counters.get(e)??0;n.counters.set(e,r+1);let a=r%o;for(let e=0;e<s.length;e++){if(a<t[e])return s[e];a-=t[e]}return s[s.length-1]}case"utilization":{let t=1/0,e=s[0];for(const n of s){const s=ME(i.get(n.target));s<t&&(t=s,e=n)}return e}}}function AE(t,e,n){const s=t?.root;if(!s)return null;const i=e?.state?.meta?.destination;if("string"!=typeof i||0===i.length)return null;const o=gE(s);if(!o||0===o.graph.nodes.size)return null;const r=pE(t);if(!r)return null;let a=o.destToSinks.get(i)??[];0===a.length&&(a=[i]);const c=Vk(o.graph,r,a);if(0===c.length)return null;const l=o.graph.out.get(r)??[],h=c.filter(t=>{const n=l[t.index],s=n?o.components.get(n):null;return!s||"function"!=typeof s.canReceive||s.canReceive(e)});if(0===h.length)return l[c[0].index]??null;const d=n?.policy??function(t,e){const n=t?.state?.balancingPolicy;if(n)return n;const s=e?.state?.routingBalancingPolicy;return s||"round-robin"}(t,s),u=SE(d,r,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(s),h,o.components);return l[u.index]??null}cg({name:"Capacity",description:"Item 을 *보유(keep)* 하는 측면 — slot 위상 / 수용 판정(canReceive/findSlot) / 3D 안착(placementFor/attachPointFor/acceptanceRotation) / delivery 좌표 질의 / 점유 수. 이동(receive/dispatch 등)은 Transferable 소관.",methods:["get slotLayout","get slots","slotById","slotSeatTransform","get arrangementStrategy","canReceive","findSlot","placementFor","attachPointFor","acceptanceRotation","deliveryWorldRotation","deliveryWorldPosition","_countOccupied"],sourceFile:"src/items/capacity-mixin.ts"}),cg({name:"PlacementSurface",description:"carrier 가 holder 위 *정확히 어디에 앉는가* 의 단일 진입점 — placementFor(carrier, ctx) → SeatingPose (holder object3d local frame, 순수 함수). I1 접촉 (밑면 = 받침 상면) / I2 frame-explicit (parent-child 비가정 — Sovereign handover 와 reparent 양쪽이 같은 값 소비) / I3 순수성 / I4 per-carrier 치수. default 구현은 Capacity(FlowNode) 가 기존 receivingSurfaceY + ArrangementStrategy + acceptanceRotation 합성과 수치 동일하게 제공.",methods:["placementFor"],models:["CarrierDims","PlacementContext","SeatingPose"],sourceFile:"src/items/capacity-mixin.ts"});try{globalThis.__operatoBuildFlowGraph=(t,e)=>{try{return e?.force&&t&&delete t.__flowGraph,bE(t)}catch{return null}}}catch{}function kE(t,e,n){const s=AE(t,e,n);if(null==s)return null;const i=t?.root,o=_E(i,s)??i?.findById?.(s)??null;return o?{targetId:s,component:o,origin:"explicit"}:null}function EE(t){const e=t?.root,n=bE(e),s=wE(t);if(!n||!s)return null;const i=(n.out.get(s)??[]).find(Boolean);if(!i)return null;const o=_E(e,i)??e?.findById?.(i)??null;return o?{id:i,component:o}:null}function TE(t){const e=wE(t);return e?CE(t?.root,e):[]}function CE(t,e){if(!t||!e)return[];const n=bE(t);if(!n)return[];const s=new Set;for(const i of Gk(n,e)){const e=_E(t,i);if(uE(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&s.add(t)}}return[...s]}function OE(t,e){if(!t||!e)return[];const n=bE(t);if(!n)return[];const s=new Map;for(const t of n.out.values())for(const e of t)null!=e&&s.set(e,(s.get(e)??0)+1);const i=new Map;for(const o of Gk(n,e)){const e=_E(t,o);if(!uE(e))continue;const n=e.routingDestination();if("string"!=typeof n||0===n.length)continue;let r=null;if("function"==typeof e.routingWeight){const t=e.routingWeight();"number"==typeof t&&Number.isFinite(t)&&t>0&&(r=t)}null===r&&(r=s.get(o)??0,0===r&&(r=1)),i.set(n,(i.get(n)??0)+r)}return[...i].map(([t,e])=>({value:t,weight:e}))}function PE(t){return bE(t)}function IE(t){const e=bE(t);if(!e)return[];const n=new Set,s=new Set,i=t=>{if(!t)return;const o=wE(t);if(o&&e.nodes.has(o)){uE(t)&&n.add(o);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&s.add(o)}const r=t.components;if(Array.isArray(r))for(const t of r)i(t)};return i(t),Wk(e,{routingTargetIds:n,loopCapableIds:s})}function DE(t){if(0===t.length)return;const e=t.reduce((t,e)=>t+e.weight,0);if(e<=0)return t[Math.floor(Math.random()*t.length)].value;const n=Math.random()*e;let s=0;for(const e of t)if(s+=e.weight,n<s)return e.value;return t[t.length-1].value}const zE={next:kE,downstream:EE,reachableDestinations:TE,reachableDestinationsFrom:CE,reachableDestinationsWeightedFrom:OE,pickWeightedDestination:DE,graphFor:PE,validate:IE};function RE(t){try{t()}catch(t){Ns("[holdable] a listener of a handover failed; the handover stands",t)}}function jE(t){if(!t?.traverse||!t.matrixWorld)return null;t.updateWorldMatrix(!0,!0);const e=t.matrixWorld.clone().invert(),n=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];return t.traverse(t=>{const i=t.isMesh?t.geometry:null;if(!i)return;i.boundingBox||i.computeBoundingBox?.();const o=i.boundingBox;if(!o)return;const r=t.matrixWorld.clone().premultiply(e),a=o.min.constructor;for(const t of[o.min.x,o.max.x])for(const e of[o.min.y,o.max.y])for(const i of[o.min.z,o.max.z]){const o=new a(t,e,i).applyMatrix4(r);[o.x,o.y,o.z].forEach((t,e)=>{n[e]=Math.min(n[e],t),s[e]=Math.max(s[e],t)})}}),Number.isFinite(n[0])?{x:s[0]-n[0],y:s[1]-n[1],z:s[2]-n[2]}:null}function $E(t){let e=0;for(let n=t;n&&!n.isRootModel?.();n=n.parent)e+=n.state?.rotation||0;return e}function LE(t){const e=t?.shownSize;return e&&[e.width,e.height,e.depth].every(Number.isFinite)?{...e}:null}function FE(t,e){if("function"!=typeof t?.toScene)return null;try{const n=t.bounds,s=t.center,i=t.toScene(s.x,s.y),o={x:i.x,y:i.y,rotation:$E(e),width:n.width,height:n.height};return Object.values(o).every(Number.isFinite)?o:null}catch{return null}}function NE(t){var e;return e=class extends t{constructor(){super(...arguments),this._items=[]}get items(){return this._items}containsItem(t){return-1!==this._items.indexOf(t)}attachPointFor(e,n){const s=t.prototype?.attachPointFor;return"function"==typeof s?s.call(this,e,n):null}addItem(t,e){if(!t||this.containsItem(t))return;const n=t.parent;if(n&&"function"==typeof n.removeItem&&n!==this&&n.removeItem(t,!0),this._items.push(t),t.parent=this,t.delegate_on?.(this),uh(this,t),!e?.silent&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}t.held?.(this)}removeItem(t,e){if(!t)return;const n=this._items.indexOf(t);if(-1!==n)if(this._items.splice(n,1),t.parent=null,t.delegate_off?.(this),this._reseatSlot(t[_v]),e)t._realObject?.setTransientDisplayScale?.(1);else{if(ph(t),function(t){const e=t?._realObject?.object3d;if(!e?.parent)return;let n=e.parent;for(;n.parent;)n=n.parent;n!==e.parent&&(n.updateWorldMatrix?.(!0,!1),e.updateWorldMatrix?.(!0,!1),n.attach(e))}(t),t._realObject?.setTransientDisplayScale?.(1,{x:1,y:1,z:1}),"function"==typeof this.trigger)try{this.trigger("release",this,t,n)}catch{}t.released?.(this)}}forEachItem(t,e){this._items.forEach(t,e)}handoverIn(t,e){if(!t)return;const n=e?.slotId,s=e?.toParent3D,i=s?null:this.attachPointFor?.(t,{slotId:n}),o=e?.animated?function(t){const e=t?._realObject?.object3d;let n=null;if(e?.parent){e.updateWorldMatrix(!0,!1);const t=e.position.clone(),s=e.quaternion.clone(),i=e.scale.clone();e.matrixWorld.decompose(t,s,i),n={position:t,quaternion:s,scale:i}}return{world3D:n,world2D:t?.parent?FE(t,t.parent):null,shown:LE(t),content:n?jE(e):null}}(t):null,r=t.parent,a=r===this?t[_v]:void 0;r&&("function"==typeof r.removeComponent&&-1!==r._components?.indexOf?.(t)&&r.removeComponent(t,!0),r!==this&&"function"==typeof r.removeItem&&-1!==r._items?.indexOf?.(t)&&r.removeItem(t,!0));const c=-1===this._items.indexOf(t);c&&(this._items.push(t),t.delegate_on?.(this)),t.parent=this,void 0!==n&&(t[_v]=n),uh(this,t);const l=!!t._realObject?.object3d;l&&this.seatHeldItem(t,{toParent3D:s,slotId:n,point:i}),void 0!==a&&a!==t[_v]&&this._reseatSlot(a),c&&RE(()=>this.trigger?.("hold",this,t,this._items.length-1)),l||this.seatHeldItem(t,{toParent3D:s,slotId:n,point:i}),RE(()=>t.held?.(this)),o&&function(t,e,n,s){const i=t.root?.transitionEffect;if(!i)return;const o=s.duration??2e3,r=s.ease??"inout",a=e._realObject?.object3d;if(n.world3D&&a?.parent){const t={pos:a.position.clone(),quat:a.quaternion.clone()},s={x:a.scale.x,y:a.scale.y,z:a.scale.z},c=a.parent;c.updateWorldMatrix(!0,!1);const l=c.matrixWorld.clone().invert(),h=a.matrixWorld.clone().compose(n.world3D.position,n.world3D.quaternion,n.world3D.scale).premultiply(l),d=a.position.clone(),u=a.quaternion.clone(),p=a.scale.clone();h.decompose(d,u,p);const f=(t,e)=>t&&e&&t>0&&e>0?t/e:1,m=n.content?jE(a):null,g=LE(e),y=n.content&&m?{x:p.x*f(n.content.x,m.x),y:p.y*f(n.content.y,m.y),z:p.z*f(n.content.z,m.z)}:{x:p.x*f(n.shown?.width,g?.width),y:p.y*f(n.shown?.depth,g?.depth),z:p.z*f(n.shown?.height,g?.height)};return void i.begin(e,{from3D:{pos:d,quat:u,fromScale:y,toScale:s},to3D:t,duration:o,ease:r,keepSuppressed:!0,placementAfter:e._realObject.placement})}const c=n.world2D?FE(e,t):null;n.world2D&&c&&i.begin(e,{fromWorld:n.world2D,toWorld:c,duration:o,ease:r})}(this,t,o,e),RE(()=>this._bumpReceived?.(t))}seatHeldItem(t,e={}){const n=t._realObject,s=n?.object3d;if(s){let i,o,r=e.toParent3D,a="world-preserve",c=1,l=null;if(!r){const n=void 0!==e.point?e.point:this.attachPointFor?.(t,{slotId:e.slotId});n?.attach&&(r=n.attach,i=n.localPosition,o=n.localRotation,a=n.carryPolicy??"world-preserve",c=n.displayScale??1,l=n.seat?.dims??null)}r&&s.parent!==r&&(r.updateWorldMatrix?.(!0,!1),s.updateWorldMatrix?.(!0,!1),r.attach(s),n.suppressTransform=!0),r&&(i&&s.position.set(i.x,i.y,i.z),"world-preserve"!==a?o?s.rotation.set(o.x,o.y,o.z):s.quaternion.identity():o&&s.rotation.set(o.x,o.y,o.z),n?.setTransientPlacement?.({policy:"carried",meta:{carryPolicy:a}}),n?.setTransientDisplayScale?.(c,function(t){if(!t?.matrixWorld)return;let e=t;for(;e.parent;)e=e.parent;t.updateWorldMatrix?.(!0,!1);const n=t.matrixWorld.elements,s=t=>Math.hypot(n[t],n[t+1],n[t+2]),i=e.scale??{x:1,y:1,z:1};return{x:s(0)/(i.x||1),y:s(4)/(i.y||1),z:s(8)/(i.z||1)}}(r)),t.takeSeatDims?.(l))}}_reseatSlot(t){if(null!=t)for(const e of this._items.slice())e?.[_v]===t&&e._realObject?.object3d&&this.seatHeldItem(e,{slotId:t})}handoverOut(t){this.removeItem(t),this._bumpDispatched?.(t)}dispose(){const t=this._items.slice();this._items.length=0;for(const e of t){ph(e);try{e.dispose?.()}catch{}}super.dispose?.()}_drawItems(t){const e=this.root?.transitionEffect;for(const t of this._items)e?.isReparenting?.(t)||t.draw?.(this.getContext?.(t))}_captureItems(t,e,n,s,i){for(let o=this._items.length-1;o>=0;o--){const r=this._items[o],a="static"===r.position?r.capture?.(t,e,i):r.capture?.(n,s,i);if(a)return a}return null}postrender(t){super.postrender?.(t);const e=this;if("popup"===e.position)return;const n=this._items;if(!n||0===n.length)return;t.save();const s=e.bounds;!e.showOverflow&&s&&(t.beginPath(),t.rect(s.left,s.top,s.width,s.height),t.clip(),t.closePath());const{left:i=0,top:o=0}=e.state??{};t.translate(i,o),this._drawItems(t),t.translate(-i,-o),t.restore()}capture(t,e,n){const s=this,i=this._items;if(i&&i.length>0&&!s.app?.isEditMode&&(!s.app||s.app.isEditMode||!s.hidden)){const i=s.fromParent?.(t,e);if(i&&s.contains?.(i.x,i.y)){const o=s.bounds,r=this._captureItems(i.x-o.left,i.y-o.top,t,e,n);if(r)return r}}return super.capture?.(t,e,n)}},e.capabilities=Object.freeze([...t.capabilities??[],"Holdable"]),e}function HE(t,e,n){return void 0!==n?t._slotIfAvailable(t.slotById(n),e):t.findSlot(e)}function BE(t){var e;return e=class extends t{reserve(t,e){const n=HE(this,t,e?.slotId);return n?{slot:n,token:Symbol("slot-reservation")}:null}release(t){}async receive(t,e={}){ep.log({role:"target",contract:"receive:enter",component:this,args:{carrier:yv(t),options:e}});const n=this.reserve(t,e);if(!n){ep.log({role:"target",contract:"receive:reject",component:this,args:{carrier:yv(t)},result:{reason:"no-slot"}}),this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:"no-slot"});const e=new Error("receive rejected: no-slot");throw e.reason="no-slot",e}this.commit(n,t,e)}commit(t,e,n={}){const s=t.slot,i=this._countOccupied(s.id),o=this.arrangementStrategy.positionAt(i,s,i,e);ep.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:i,slotId:s.id,occupantCount:i,carrier:yv(e)},result:o});const r=function(t,e,n,s,i){const o={},r=t.placementFor?.(e,{slot:n,index:s,occupantCount:s})??null;if(ep.log({role:"target",contract:"placementFor",component:t,args:{carrier:yv(e),slotId:n.id,index:s},result:r}),r){const s=e.state??{},i=t.state??{};o.left=r.position.x-(Number(s.width)||0)/2+(Number(i.width)||0)/2,o.top=r.position.z-(Number(s.height)||0)/2+(Number(i.height)||0)/2;const a=t._zPosFromSeatY(r.position.y,s.depth,n);null!==a&&(o.zPos=a),r.rotation&&vv(o,r.rotation)}else{if(i&&(o.left=i.x,o.top=i.y),0!==(t._realObject?.receivingSurfaceY??0))o.zPos=0;else if(n.localPosition&&Number.isFinite(n.localPosition.z)){const e=t._realObject?.geometricOffsetY??0;o.zPos=n.localPosition.z+e}const s=t.acceptanceRotation?.(e,n);ep.log({role:"target",contract:"acceptanceRotation",component:t,args:{carrier:yv(e),slotId:n.id},result:s}),s&&vv(o,s)}const a=t.normalizePose?.(e,n);return"function"==typeof t.normalizePose&&ep.log({role:"target",contract:"normalizePose",component:t,args:{carrier:yv(e),slotId:n.id},result:a}),a&&Object.assign(o,a),o}(this,e,s,i,o),a=e._realObject;let c,l;a?.object3d&&(a.object3d.updateWorldMatrix(!0,!1),c=new w.Vector3,l=new w.Quaternion,a.object3d.getWorldPosition(c),a.object3d.getWorldQuaternion(l));const{animated:h=!1,duration:d,ease:u}=n;if("function"==typeof this.handoverIn?this.handoverIn(e,{slotId:s.id}):(e[_v]=s.id,this.reparent?.(e,{animated:h,duration:d,ease:u})),!h&&e._realObject&&(e._realObject.suppressTransform=!1),Object.keys(r).length){try{e.setState?.(r)}catch(t){Ns("[transferable] the received item's state could not be set; the handover stands",t)}ep.log({role:"target",contract:"receive:setState",component:this,args:{carrier:yv(e),keys:Object.keys(r)}})}this.trigger("transfer-received",{type:"transfer-received",component:e,container:this,slotId:s.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),ep.log({role:"target",contract:"receive:done",component:this,args:{carrier:yv(e),slotId:s.id}})}async dispatch(t,e,n={}){const s=new op({source:this,target:e,carrier:t,options:n}),i=await s.execute();"rolled-back"!==i.phase?this.trigger("transfer-dispatched",{type:"transfer-dispatched",component:t,container:this,target:e}):this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:i.rejectReason??"rejected"})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e="rejected"){this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:e})}canAccept(t,e){const n=(()=>{const n=this.slots;if(!n.length)return{ok:!1,reason:"no-slots-defined"};if(void 0!==e?.slotId){if(!this.slotById(e.slotId))return{ok:!1,reason:"slot-absent"};const n=HE(this,t,e.slotId);return n?{ok:!0,slot:n}:{ok:!1,reason:"slot-unavailable"}}const s=this.findSlot(t);if(!s){const e=t?.state?.type??t?.type;for(const t of n)if(!t.allowedTypes?.length||!e||t.allowedTypes.includes(e))return{ok:!1,reason:"all-slots-full"};return{ok:!1,reason:"type-not-accepted"}}return{ok:!0,slot:s}})();return ep.log({role:"target",contract:"canAccept",component:this,args:{carrier:yv(t)},result:n.ok?{ok:!0,slotId:n.slot.id}:{ok:!1,reason:n.reason}}),n}accept(t,e){return this.receive(t,e)}},e.__hasTransferable=!0,e}function GE(t){var e;const n=!!t.__hasCapacity,s=!!t.__hasTransferable,i=n?t:kk(t),o=s?i:BE(i),r=[...t.capabilities??[]];n||r.push("Capacity","PlacementSurface"),s||r.push("Transferable"),r.push("Holdable","FlowNode");const a=(e=class extends(NE(o)){get isFlowNode(){return!0}containable(t){return!!t&&!0===t.isItem}get showMoveHandle(){return!1}inboundPorts(){return[]}outboundPorts(){return[]}_bumpReceived(t){const e=this.state?.received??0;this.setState?.({received:e+1})}_bumpDispatched(t){const e=this.state?.dispatched??0;this.setState?.({dispatched:e+1})}_bumpRejected(t,e){const n=this.state?.rejected??0;this.setState?.({rejected:n+1})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e){}resolveDownstream(){const t=this.state?.downstreamRef;if(!t)return[];return(this.root?.findAll?.(t)??[]).map(t=>t?.state?.id).filter(Boolean)}routingLinks(){return{downstream:this.resolveDownstream()}}},function(t,e,n){"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}(e,"FlowNodeMixed"),e.capabilities=Object.freeze(r),e.isFlowNode=!0,e);return wv(a)}function UE(t){return!!t&&!0===t.isFlowNode}cg({name:"Holdable",description:"어떤 Component 든 item(데이타바인딩 동적 물건) 을 보유하는 capability. _items + add/remove/forEach + handover + hold/release event + dispose cascade. Container(정적 _components) 와 직교 — 컨테이너 비의존.",methods:["addItem","removeItem","forEachItem","containsItem","handoverIn","handoverOut","_drawItems","_captureItems","dispose"],sourceFile:"src/components/mixins/holdable.ts"}),cg({name:"Transferable",description:"Item 을 노드 간에 옮기는 *이동(move)* 측면. 수용 트랜잭션 라이프사이클(reserve → commit → release)과 receive/accept/dispatch/route 를 제공. 보유(keep — slots/findSlot/canReceive 등)는 Capacity 소관.",methods:["reserve","commit","release","receive","accept","canAccept","dispatch","route","resolveRoute","rejectRoute"],sourceFile:"src/transfer/transferable-mixin.ts"}),cg({name:"FlowNode",description:"Flow graph 의 노드 — 구조 (inbound/outbound port + slot) + flow (route + 5-phase transfer stat). 보유(_items/handover)는 Holdable base 위임. 모든 flow 컴포넌트의 base — Storable/Mobile/Processable 의도가 위에 직교로 적용.",methods:["inboundPorts","outboundPorts","slotIds","slotAt","route","resolveRoute","rejectRoute"],models:["Port","SlotInfo","Vec3"],sourceFile:"src/flow/flow-node.ts"});const VE={x:0,y:0,z:0,w:1};function WE(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function YE(t,e){const n=t.rotation,s=e.rotation,i=e.position,o=n.w*i.x+n.y*i.z-n.z*i.y,r=n.w*i.y+n.z*i.x-n.x*i.z,a=n.w*i.z+n.x*i.y-n.y*i.x,c=-n.x*i.x-n.y*i.y-n.z*i.z,l=o*n.w+c*-n.x+r*-n.z-a*-n.y,h=r*n.w+c*-n.y+a*-n.x-o*-n.z,d=a*n.w+c*-n.z+o*-n.y-r*-n.x,u={x:n.w*s.x+n.x*s.w+n.y*s.z-n.z*s.y,y:n.w*s.y-n.x*s.z+n.y*s.w+n.z*s.x,z:n.w*s.z+n.x*s.y-n.y*s.x+n.z*s.w,w:n.w*s.w-n.x*s.x-n.y*s.y-n.z*s.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const qE={east:{axis:{x:1,y:0,z:0},yaw:0,idSuffix:"east"},west:{axis:{x:-1,y:0,z:0},yaw:Math.PI,idSuffix:"west"},south:{axis:{x:0,y:0,z:1},yaw:-Math.PI/2,idSuffix:"south"},north:{axis:{x:0,y:0,z:-1},yaw:Math.PI/2,idSuffix:"north"}};function XE(t){const{carrierWorld:e,width:n,depth:s,entryHeight:i,mountLocalY:o,approachDistance:r,sides:a,toolType:c,tolerance:l,priority:h}=t,d="number"==typeof o?{position:{x:0,y:o,z:0},rotation:{...VE}}:void 0,u=n/2,p=s/2;return a.map(t=>{const n=qE[t],s="string"==typeof c?c:c[t]??"unknown",o={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:i,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:WE(n.yaw)},a={position:{x:o.position.x+n.axis.x*r,y:i,z:o.position.z+n.axis.z*r},rotation:WE(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:s,approach:YE(e,a),engage:YE(e,o),...d?{mount:d}:{},tolerance:l,priority:h}})}function KE(t){const{carrierWorld:e,topY:n,approachDistance:s,toolType:i,mountLocalY:o,tolerance:r,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...VE}};return{id:c??"top",toolType:i,approach:YE(e,{position:{x:0,y:n+s,z:0},rotation:{...VE}}),engage:YE(e,l),..."number"==typeof o?{mount:{position:{x:0,y:o,z:0},rotation:{...VE}}}:{},tolerance:r,priority:a}}function JE(t,e){return t.filter(t=>t.toolType===e.toolType)}function QE(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,s=t.approach.position.y-e.y,i=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+s*s+i*i)}});return n.sort((t,e)=>{const n=t.f.priority??0,s=e.f.priority??0;return n!==s?n-s:t.dist-e.dist}),n[0].f}class ZE{constructor(t){this.owner=t}positionAt(t,e,n,s){if(0!==t)return null;const i=this.owner?.state?.width??0,o=this.owner?.state?.height??0,r=s?.state?.width??0,a=s?.state?.height??0;return{x:Math.max(0,(i-r)/2),y:Math.max(0,(o-a)/2),z:0}}capacity(t){return t.maxCount??1}}let tT=1;function eT(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const nT={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class sT{constructor(t=nT){this._byResource=new Map,this._byReserver=new Map,this._listeners=new Set,this._conflictLog=[],this._maxConflictLog=1e3,this._yieldPolicy=t}add(t){const e={...t,id:"res-"+tT++},n=(this._byResource.get(e.resource)??[]).filter(t=>eT(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const s=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}}),i=s.every(t=>"b-yields"===t.decision);if(i){const s=n.slice();for(const t of s)this._remove(t),this._emit({kind:"evicted",reservation:t,by:e});return this._insert(e),this._emit({kind:"added",reservation:e}),this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:s,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:s}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:s}}conflictLog(){return[...this._conflictLog]}setMaxConflictLog(t){this._maxConflictLog=Math.max(1,t)}_appendConflictLog(t){this._conflictLog.push(t),this._conflictLog.length>this._maxConflictLog&&this._conflictLog.shift()}conflicts(t,e){return(this._byResource.get(t)??[]).filter(t=>eT(t.timeWindow,e))}release(t){this._remove(t)&&this._emit({kind:"released",reservation:t})}releaseAllOf(t){const e=(this._byReserver.get(t)??[]).slice();for(const t of e)this._remove(t),this._emit({kind:"released",reservation:t});return e}forResource(t){return[...this._byResource.get(t)??[]]}forReserver(t){return[...this._byReserver.get(t)??[]]}all(){const t=[];for(const e of this._byResource.values())t.push(...e);return t}clear(){this._byResource.clear(),this._byReserver.clear(),this._conflictLog.length=0}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}_insert(t){let e=this._byResource.get(t.resource);e||(e=[],this._byResource.set(t.resource,e));const n=e.findIndex(e=>e.timeWindow.startSimMs>t.timeWindow.startSimMs);n<0?e.push(t):e.splice(n,0,t);let s=this._byReserver.get(t.reserverId);s||(s=[],this._byReserver.set(t.reserverId,s)),s.push(t)}_remove(t){const e=this._byResource.get(t.resource);if(!e)return!1;const n=e.findIndex(e=>e.id===t.id);if(n<0)return!1;e.splice(n,1),0===e.length&&this._byResource.delete(t.resource);const s=this._byReserver.get(t.reserverId);if(s){const e=s.findIndex(e=>e.id===t.id);e>=0&&s.splice(e,1),0===s.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const iT=new sT;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=iT);class oT{constructor(){this.nodes=new Map,this.edges=new Map,this.laneEndpoints=new Map}addNode(t){this.nodes.has(t.id)||(this.nodes.set(t.id,t),this.edges.set(t.id,[]))}addEdge(t){const e=this.edges.get(t.fromNode);if(!e)throw new Error(`NavGraph.addEdge: source node not found: ${t.fromNode}`);if(!this.nodes.has(t.toNode))throw new Error(`NavGraph.addEdge: target node not found: ${t.toNode}`);e.push(t)}edgesFrom(t){return this.edges.get(t)??[]}findNearestNode(t){let e=null,n=1/0;for(const s of this.nodes.values()){const i=rT(s.position,t);i<n&&(n=i,e=s)}return e}}function rT(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}function aT(t,e){return Math.sqrt(rT(t,e))}function cT(t,e,n={}){const s=new oT,i=n.defaultSpeed??100;for(const e of t){const t=e.geometry.centerPoints;if(t.length<2)continue;const n=`${e.id}:start`,o=`${e.id}:end`;s.addNode({id:n,position:t[0],type:"lane-start"}),s.addNode({id:o,position:t[t.length-1],type:"lane-end"}),s.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:o});let r=0;for(let e=1;e<t.length;e++)r+=aT(t[e-1],t[e]);const a=r/(e.speedLimit??i)*1e3;s.addEdge({fromNode:n,toNode:o,resource:e.id,distance:r,durationMs:a,forward:!0}),"twoway"===e.direction&&s.addEdge({fromNode:o,toNode:n,resource:e.id,distance:r,durationMs:a,forward:!1})}for(const t of e){if(t.lanes.length<2)continue;const e=[];for(const n of t.lanes){const i=s.laneEndpoints.get(n);if(!i)continue;const o=s.nodes.get(i.startNodeId).position,r=s.nodes.get(i.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=s.laneEndpoints.get(e);if(!t)continue;const i=s.nodes.get(t.startNodeId).position,h=s.nodes.get(t.endNodeId).position;a+=Math.min(rT(o,i),rT(o,h)),c+=Math.min(rT(r,i),rT(r,h)),l++}if(0===l)continue;const h=a<c?i.startNodeId:i.endNodeId;e.push({laneId:n,nodeId:h,pos:s.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let i=0;i<e.length;i++){if(n===i)continue;const o=e[n],r=e[i],a=aT(o.pos,r.pos);s.addEdge({fromNode:o.nodeId,toNode:r.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return s}function lT(t,e,n,s={}){const i=t.nodes.get(e),o=t.nodes.get(n);if(!i||!o)return null;const r=s.speed?.max??100,a=e=>{const n=function(t,e){return Math.sqrt(function(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}(t,e))}(t.nodes.get(e).position,o.position);return n/r*1e3},c=new Map,l=new Set,h=new Set,d={nodeId:e,gScore:0,fScore:a(e)};c.set(e,d),l.add(e);const u=s.startSimMs??0,p=s.deadlineSimMs;for(;l.size>0;){let e=null,s=null;for(const t of l){const n=c.get(t);(!s||n.fScore<s.fScore||n.fScore===s.fScore&&t<e)&&(s=n,e=t)}if(!s||!e)return null;if(e===n){const t=[];let e=s,n=0;for(;e&&e.cameFromEdge;){const s=e.cameFromEdge,i=u+(e.gScore-s.durationMs);t.unshift({resource:s.resource,timeWindow:{startSimMs:i,endSimMs:i+s.durationMs},fromPos:s.fromPos,toPos:s.toPos}),n+=s.distance,e=c.get(s.fromNodeId)}const i=s.gScore;return void 0!==p&&u+i>p?null:{segments:t,totalDurationMs:i,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=s.gScore+n.durationMs,i=c.get(n.toNode);if(!i||e<i.gScore){const s=t.nodes.get(n.fromNode),i=t.nodes.get(n.toNode),o={nodeId:n.toNode,gScore:e,fScore:e+a(n.toNode),cameFromEdge:{fromNodeId:n.fromNode,resource:n.resource,distance:n.distance,durationMs:n.durationMs,fromPos:s.position,toPos:i.position}};c.set(n.toNode,o),l.add(n.toNode)}}}return null}function hT(t,e,n=0,s){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:s}))}const dT={closed:!0,round:0,divisions:24};class uT{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const s=t[e].x-t[e-1].x,i=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(s*s+i*i))}this.cumulative=n,this.length=n[n.length-1]??0}sample(t){const e=this.length;if(0===this.points.length)return{x:0,y:0,theta:0};if(0===e)return{x:this.points[0].x,y:this.points[0].y,theta:0};let n=t;this.closed?n=(t%e+e)%e:n<0?n=0:n>e&&(n=e);const s=this.cumulative;let i=0,o=s.length-2;for(;i<o;){const t=i+o>>1;s[t+1]<=n?i=t+1:o=t}const r=s[i+1]-s[i],a=r>0?(n-s[i])/r:0,c=this.points[i],l=this.points[i+1],h=l.x-c.x,d=l.y-c.y;return{x:c.x+h*a,y:c.y+d*a,theta:0===h&&0===d?0:Math.atan2(d,h)}}}function pT(t,e={}){const n={...dT,...e},s=t.length;if(0===s)return new uT([],n.closed);if(1===s)return new uT([{x:t[0].x,y:t[0].y}],n.closed);const i=[],o=(t,e)=>{if(i.length>0){const n=i[i.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}i.push({x:t,y:e})},r=(n.closed,s);for(let e=0;e<r;e++){const i=0===e?n.closed?s-1:-1:e-1,r=e===s-1?n.closed?0:-1:e+1,a=i>=0?t[i]:null,c=t[e],l=r>=0?t[r]:null;if(a&&a.x===c.x&&a.y===c.y)continue;const h=a&&l?Lo(c,n.round):0;let d,u,p,f;if(a){const t=Math.sqrt((a.x-c.x)**2+(a.y-c.y)**2),e=0!==t?Math.atan2(a.x-c.x,a.y-c.y):0,n=Math.min(h,t/2);d=Math.sin(e)*n+c.x,u=Math.cos(e)*n+c.y}else d=c.x,u=c.y;if(l){const t=Math.sqrt((l.x-c.x)**2+(l.y-c.y)**2),e=0!==t?Math.atan2(l.x-c.x,l.y-c.y):0,n=Math.min(h,t/2);p=Math.sin(e)*n+c.x,f=Math.cos(e)*n+c.y}else p=c.x,f=c.y;if(o(d,u),h>0&&a&&l)for(let t=1;t<=n.divisions;t++){const e=t/n.divisions,s=1-e;o(s*s*d+2*s*e*c.x+e*e*p,s*s*u+2*s*e*c.y+e*e*f)}else d===p&&u===f||o(p,f);if(l&&zo(c)){const t=Lo(l,n.round),e=Math.sqrt((c.x-l.x)**2+(c.y-l.y)**2),s=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,i=Math.min(t,e/2),r=Ro({x:p,y:f},{x:Math.sin(s)*i+l.x,y:Math.cos(s)*i+l.y},c.bulge);if(r){let t=r.endAngle-r.startAngle;if(r.clockwise)for(;t>0;)t-=2*Math.PI;else for(;t<0;)t+=2*Math.PI;for(let e=1;e<=n.divisions;e++){const s=e/n.divisions,i=r.startAngle+t*s;o(r.cx+r.radius*Math.cos(i),r.cy+r.radius*Math.sin(i))}}}}if(n.closed&&i.length>0){const t=i[0],e=i[i.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&i.push({x:t.x,y:t.y})}return new uT(i,n.closed)}function fT(t,e){return pT(t,e).length}function mT(t){return t?/forklift|agv|amr|oht|tugger|worker/i.test(t)?"mobile":/conveyor|sorter|induct|chute|belt/i.test(t)?"flow":/rack|shelf|stocker|cell/i.test(t)?"cell":/pallet|box|parcel|crate|drum|tray/i.test(t)?"atomic":/robot[-_]?arm|crane|lift/i.test(t)?"articulated":/spawn[-_]?point|sink[-_]?point/i.test(t)?"boundary":"":""}function gT(t){const e=[];let n=t.parent;for(;n&&!n.isRootModel?.();){const t=n.state?.id??n.constructor?.name;t&&e.unshift(t),n=n.parent}return e.join(" › ")}function yT(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",s={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:mT(n),parentId:t.parent?.state?.id,parentPath:gT(t)},i=t._realObject?.object3d;if(i){i.updateWorldMatrix?.(!0,!1);const t=i.matrixWorld?.elements;t&&(s.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(s.isItem=!0),!0===t.isMover&&(s.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(s.isHolder=!0),"function"==typeof t.pickupFrames)try{s.isPickable=t.pickupFrames().length>0}catch{s.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?s.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(s.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,s]of Object.entries(t.state))"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s&&null!==s||(e[n]=s);s.state=e}if(e){const e=t.components??[];s.childIds=e.map(t=>t.state?.id).filter(Boolean)}return s}function bT(t){function e(t,n){if(!t)return;n.push(yT(t));const s=t.components??[];for(const t of s)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const s=e.components??[];for(const e of s){const s=n(t,e);if(s)return s}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const s=n(e,t?.rootModel??t);if(!s)return null;const i={...yT(s)};if("function"==typeof s.pickupFrames)try{i.pickupFrames=s.pickupFrames()}catch{}if("object"==typeof s.slots)try{i.slots=Array.isArray(s.slots)?s.slots:"function"==typeof s.slots?s.slots():[]}catch{}if("function"==typeof s.acceptanceRotation)try{i.acceptanceWorldQuat=s.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof s.deliveryWorldPosition)try{i.deliveryWorldPosition=s.deliveryWorldPosition(null)}catch{}return i},simStatus(){let e=0;const n=[t?.rootModel??t];for(;n.length>0;){const t=n.pop();if(!t)continue;!0===t.isItem&&e++;const s=t.components??[];for(const t of s)n.push(t)}return{simTime:bo.now,realTime:"undefined"!=typeof performance?performance.now():Date.now(),speed:bo.speed,paused:bo.isPaused,carrierCount:e}},transferLog(){const t={};rp.flows().forEach((e,n)=>{t[n]=e});const e={};rp.targetCounts().forEach((t,n)=>{e[n]=t});const n={};return rp.rejectReasonCounts().forEach((t,e)=>{n[e]=t}),{entries:rp.toJSON(),stats:rp.stats(),flows:t,targetCounts:e,rejectReasonCounts:n}},reservations(){const t=[...iT.all()],e={},n={};for(const s of t)(e[s.resource]??=[]).push(s),(n[s.reserverId]??=[]).push(s);for(const t of Object.values(e))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);for(const t of Object.values(n))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);return{simTime:bo.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=iT.conflictLog(),e={},n={};let s=0,i=0;for(const o of t)e[o.resource]=(e[o.resource]??0)+1,n[o.proposed.reserverId]=(n[o.proposed.reserverId]??0)+1,"rejected"===o.outcome?s++:i++;return{simTime:bo.now,log:[...t],total:t.length,rejected:s,preempted:i,byResource:e,byReserver:n}}}}function vT(t){const e=bT(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let _T=0;const xT=new FinalizationRegistry(()=>{_T--});class wT{static get residents(){return _T}static get residentsCount(){return _T}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,_T++,xT.register(this,_T)}dispose(){if(this.disposer)for(const t in this.references)this.disposer(t,this.references[t]);this.references={},this.counters={}}get ids(){return Object.keys(this.references)}create(t){return new Promise((e,n)=>{this.creator?this.creator(t,n=>{n.release=()=>{this.disposer?.(t,n),delete n.release,Hs("RELEASED",t)},e(n)},n):n(Error("Reference id("+t+") could not be created. Reference creator should be defined."))})}add(t,e){const n=new Promise((n,s)=>{const i=this.references[t];if(i)i===e?s(Error("Reference ID and target duplicate")):e?s(Error("Reference ID duplicate")):n(i);else{const i=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)i(e);else{if(!this.creator)return void s(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,i,s)}}});return this.references[t]||(this.references[t]=n),n}async get(t,e=!1){let n=this.references[t];if(n){if(!(n instanceof Promise)){if(!(t in this.counters))throw new Error("No Reference Count");return this.counters[t]++,n}if(e)return n=await n,this.counters[t]++,n}if(e)return await this.add(t);throw new Error("No References for "+t)}_id(t){for(const e in this.references){if(this.references[e]===t)return e}}release(t){const e=this._id(t);if(!e)return void Fs("No Referenced ID");const n=this.references[e];n&&(this.counters[e]--,0==this.counters[e]&&(this.disposer?.(e,n),delete this.references[e],delete this.counters[e],delete t.release,Hs("RELEASED",e)))}}const MT={},ST={};let AT=[];function kT(t){const e=t.target,n="SCRIPT"===e.tagName?MT:ST,s=e.src||e.href;n[s]=!0,AT.forEach((t,e)=>{if(!t)return;const{resolve:i,scripts:o,styles:r}=t;if(n===MT){const t=o.indexOf(s);t>-1&&t<o.length-1&&TT(o[t+1])}o.some(t=>!MT[t])||r?.some(t=>!ST[t])||(i(),AT[e]=null)}),AT=AT.filter(Boolean)}function ET(t){if("string"==typeof t)return;const e=t.target,n=e.src,s="SCRIPT"===e.tagName?MT:ST;AT.forEach((e,i)=>{if(!e)return;const{reject:o,scripts:r,styles:a}=e;(s===MT&&r.includes(n)||s===ST&&!!a?.includes(n))&&(o(t),AT[i]=null)}),AT=AT.filter(Boolean),delete s[n],document.head.removeChild(e)}function TT(t){MT[t]=!1;const e=document.createElement("script");e.onload=kT,e.onerror=ET,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class CT{static load(t,e){const n="string"==typeof t?[t]:t,s="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||s&&!Array.isArray(s))return void e(new Error("invalid sources for load"));let i,o=!0;if(s?.forEach(t=>{t in ST||function(t){ST[t]=!1;const e=document.createElement("link");e.onload=kT,e.onerror=ET,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),ST[t]||(o=!1)}),n&&n.length>0)for(const t of n)t in MT?MT[t]||(o=!1):i??=t;if(i)TT(i);else if(o)return void t();AT.push({resolve:t,reject:e,scripts:n,styles:s})})}}const OT="0.0.0";function PT(t){if(!(t>0))return 1;let e=0;if(!(t&t-1))return t;for(;0!=t;)t>>=1,e+=1;return 1<<e}function IT(t){const{lineWidth:e=0}=t.state;let{width:n,height:s}=t.bounds;n+=e,s+=e;const i=PT(2*n),o=PT(2*s),r=Zp(i,o),a=new w.CanvasTexture(r);return DT(r,t,2),a.needsUpdate=!0,a.wrapS=w.RepeatWrapping,a.wrapT=w.RepeatWrapping,a.offset.set(0,1-2*s/o),a.repeat.set(2*n/i,2*s/o),a.magFilter=w.NearestFilter,a.minFilter=w.LinearFilter,a.colorSpace=w.SRGBColorSpace,a}function DT(t,e,n){const{lineWidth:s=0}=e.state;let{left:i,top:o}=e.bounds;i-=s/2,o-=s/2;const r=t.getContext("2d");r.scale(n,n),r.translate(-i,-o),e.render(r),e.postrender(r)}function zT(t,e,n=2){const s=t.getContext("2d");s&&(s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,t.width,t.height),DT(t,e,n))}const RT=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class jT extends Du{get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}constructor(t){super(t),this._origInvalidate=t.invalidate.bind(t),t.invalidate=()=>{this._origInvalidate(),this._refreshTextureNow()}}getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds;if(!t||!e)return;const n=Nd(this.component.state.material3d),s=new w.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const i=IT(this.component),o=new w.MeshStandardMaterial({map:i});Gd(o,n),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=n.castShadow,this.object3d.receiveShadow=n.receiveShadow}updateDimension(){const{width:t,height:e}=this.component.bounds;this.setDimensionScale(t,1,e)}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}_debouncedRebuild(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=void 0,this._rebuildTexture()},100)}_rebuildTexture(){this.clear(),this.build(),this.updateTransform(),this.updateDimension(),this.updateHidden()}_refreshTextureNow(){const t=this.object3d.material,e=t?.map;if(!e)return;const n=e.source?.data;n&&(zT(n,this.component,2),e.needsUpdate=!0)}updateFillStyle(){this._debouncedRebuild()}updateStrokeStyle(){this._debouncedRebuild()}updateText(){this._debouncedRebuild()}onchange(t,e){super.onchange(t,e);for(const e of Object.keys(t))if(!RT.has(e)){this._debouncedRebuild();break}}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),t.transparent=!0,this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}clear(){return this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),bu(this.object3d),super.clear()}dispose(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),this._origInvalidate&&(this.component.invalidate=this._origInvalidate,this._origInvalidate=void 0),super.dispose()}}const $T=new Map;function LT(t){return Math.round(1e3*t)/1e3}function FT(t){return new w.Color(t).getHexString()}const NT={material(t,e,n){const s=t+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+FT(t.color)),null!=t.metalness&&e.push("m"+LT(t.metalness)),null!=t.roughness&&e.push("r"+LT(t.roughness)),null!=t.opacity&&e.push("o"+LT(t.opacity)),null!=t.emissive&&e.push("E"+FT(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+LT(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+LT(t.envMapIntensity)),null!=t.side&&e.push("s"+t.side),t.transparent&&e.push("t"),t.flatShading&&e.push("f"),!1===t.depthWrite&&e.push("dw0"),t.map&&e.push("M"+(t.map.uuid??"")),e.join("|")}(e);let i=$T.get(s);return i||$T.set(s,i=function(t){const e=new w.MeshStandardMaterial;return e.userData.__bankOwned=!0,null!=t.color&&e.color.set(t.color),null!=t.emissive&&e.emissive.set(t.emissive),null!=t.metalness&&(e.metalness=t.metalness),null!=t.roughness&&(e.roughness=t.roughness),null!=t.emissiveIntensity&&(e.emissiveIntensity=t.emissiveIntensity),null!=t.envMapIntensity&&(e.envMapIntensity=t.envMapIntensity),null!=t.side&&(e.side=t.side),null!=t.map&&(e.map=t.map),null!=t.flatShading&&(e.flatShading=t.flatShading),null!=t.depthWrite&&(e.depthWrite=t.depthWrite),null!=t.opacity&&(e.opacity=t.opacity),null!=t.transparent?e.transparent=t.transparent:null!=t.opacity&&t.opacity<1&&(e.transparent=!0),e}(e)),null==n?i:ou(i,{color:n})},get size(){return $T.size},has(t){const e=t+"::";for(const t of $T.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of $T.values())au(t),t.dispose();$T.clear()}};class HT extends Du{getObject3dInstance(){return new w.Mesh}build(){super.build(),this.buildGeometry(),this.buildMaterial(),this.updateDimension()}updateAlpha(){if(this.canShareMaterial)return void super.updateAlpha();const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}updateFillStyle(){if(this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const{fillStyle:t,alpha:e=1}=this.component.state,n=this.object3d.material;if(!n)return;const s=Du.buildFillStyleTexture(this.component);s?(n.map&&n.map.dispose(),s.needsUpdate=!0,n.map=s,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(du(t))),hu(n,0,t)}updateStrokeStyle(){const t=this.object3d.getObjectByName("__edgeLines__");t&&(this.object3d.remove(t),bu(t));const{strokeStyle:e}=this.component.state;if(!e||"transparent"===e||"none"===e)return;const n=this.object3d.geometry;if(!n?.getAttribute("position"))return;const s=new w.EdgesGeometry(n),i=new w.LineBasicMaterial({color:e}),o=new w.LineSegments(s,i);o.name="__edgeLines__",this.object3d.add(o)}updateDimension(){const{width:t,height:e}=this.component.bounds,{depth:n=1}=this.component.state;if(!this.object3d)return;this.object3d.geometry.computeBoundingBox();const s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,o=s.max.y-s.min.y,r=s.max.z-s.min.z;this.setDimensionScale(t/i,n/o,e/r)}}get canShareMaterial(){return void 0===this.materialSharingIssue}get materialSharingIssue(){const{fillStyle:t}=this.component.state;if(!t||"object"!=typeof t)return;const e=t.type;return"pattern"===e?"무늬(pattern) fillStyle 은 인스턴스마다 캔버스 텍스처가 필요하다":"gradient"===e?"그라디언트 fillStyle 은 인스턴스마다 캔버스 텍스처가 필요하다":`fillStyle 이 색 문자열이 아니다 (type: ${String(e)})`}get requiresSharedMaterial(){return!0===this.component.constructor.requiresSharedMaterial}get materialSharing(){const t=this.materialSharingIssue,e=void 0===t,n=this.requiresSharedMaterial,s={shared:e,required:n,violated:n&&!e};return void 0!==t&&(s.reason=t),e&&(s.bankKey=this.materialBankKey),s}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=Nd(this.component.state.material3d),e=lu(this.component.state.fillStyle);return{metalness:t.metalness,roughness:t.roughness,emissive:t.emissive,emissiveIntensity:t.emissiveIntensity,envMapIntensity:t.envMapIntensity,side:Bd(t.side),flatShading:t.flatShading,opacity:e,transparent:e<1}}buildMaterial(){if(!this.canShareMaterial){const t=Nd(this.component.state.material3d),e=new w.MeshStandardMaterial({transparent:!0});return Gd(e,t),void(this.object3d.material=e)}this.applyBankMaterial()}applyBankMaterial(){const{fillStyle:t}=this.component.state,e=lu(t)>0&&"string"==typeof t?du(t):void 0;ru(this.object3d),this.object3d.material=NT.material(this.materialBankKey,this.materialSpec(),e)}updateMaterial3d(){if(super.updateMaterial3d(),this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const t=this.object3d.material;t&&Gd(t,Nd(this.component.state.material3d))}clear(){return ru(this.object3d),bu(this.object3d),super.clear()}}function BT(t,e,n,s){return[["bold",t],["italic",e],[n+"px",!0],[s,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function GT(t){let e=0;if(!((t=Math.abs(t)||1)&t-1))return t;for(;0!=t;)t>>=1,e+=1;return 1<<e}function UT(t,e,n){const{bold:s=!1,italic:i=!1,fontFamily:o="Serif",fontSize:r=10,fontColor:a="black",textAlign:c="center",textBaseline:l="middle",width:h=t.width,height:d=t.height,offsetX:u=0,offsetY:p=0}=n||{},f=t.getContext("2d");let m,g;f.imageSmoothingEnabled=!1,f.fillStyle=a,f.strokeStyle=a,f.font=BT(s,i,r,o),"left"===c||"start"===c?(f.textAlign="left",m=u):"right"===c||"end"===c?(f.textAlign="right",m=u+h):(f.textAlign="center",m=u+h/2);const y=1.2*r,b=String(e).split("\n"),v=y*b.length;g="top"===l||"hanging"===l?p+.1*r:"bottom"===l||"alphabetic"===l?p+d-v+.1*r:p+(d-v)/2+.1*r,f.textBaseline="top";for(const t of b)f.fillText(t,m,g),g+=y}function VT(t,e,n,s){const i=GT(2*e),o=GT(2*n),r=Zp(i,o),a=r.getContext("2d"),{fillStyle:c}=s||{};if(c&&"object"==typeof c&&c.colorStops?.length){const t=vu(c,2*e,2*n);t&&a.drawImage(t,0,0)}a.scale(2,2),"string"==typeof c&&""!==c&&"transparent"!==c&&(a.fillStyle=c,a.fillRect(0,0,e,n)),UT(r,t,s);const l=new w.CanvasTexture(r);return l.needsUpdate=!0,l.wrapS=w.RepeatWrapping,l.wrapT=w.RepeatWrapping,l.offset.set(0,1-2*n/o),l.repeat.set(2*e/i,2*n/o),l.minFilter=w.LinearFilter,l.colorSpace=w.SRGBColorSpace,l}function WT(t,e,n,s,i,o,r){const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const t=2*n,c=2*s,l=GT(t),h=GT(c),d=Zp(l,h),u=d.getContext("2d");if(o.color&&(u.fillStyle=o.color,u.fillRect(0,0,t,c)),o.fitPattern)u.drawImage(a,0,0,t,c);else{const e=2*(o.width||a.naturalWidth),n=2*(o.height||a.naturalHeight),s=2*(o.offsetX||0),i=2*(o.offsetY||0);let r=0,l=0;switch(o.align){case"center":r=(t-e)/2,l=(c-n)/2;break;case"left-top":break;case"left-bottom":l=c-n;break;case"right-top":r=t-e;break;case"right-bottom":r=t-e,l=c-n;break;case"left":l=(c-n)/2;break;case"right":r=t-e,l=(c-n)/2;break;case"top":r=(t-e)/2;break;case"bottom":r=(t-e)/2,l=c-n}const h=s+r,d=i+l;if(o.noRepeat)u.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,h,d,e,n);else{u.save(),u.rect(0,0,t,c),u.clip();const s=h>0?h-Math.ceil(h/e)*e:h;for(let i=d>0?d-Math.ceil(d/n)*n:d;i<c;i+=n)for(let o=s;o<t;o+=e)u.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,o,i,e,n);u.restore()}}e&&(u.scale(2,2),UT(d,e,i));const p=new w.CanvasTexture(d);p.needsUpdate=!0,p.wrapS=w.RepeatWrapping,p.wrapT=w.RepeatWrapping,p.offset.set(0,1-c/h),p.repeat.set(t/l,c/h),p.minFilter=w.LinearFilter,p.colorSpace=w.SRGBColorSpace,r(p)},a.onerror=()=>{const t=VT(e,n,s,i);r(t)},a.src=t}function YT(t,e){let{bold:n=!1,italic:s=!1,fontFamily:i="Serif",fontSize:o=10,lineHeight:r="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=BT(n,s,o,i),a.style.lineHeight=String(r),a.style.whiteSpace="pre",a.style.position="absolute",a.textContent=t,document.body.appendChild(a);const c=a.getBoundingClientRect();return document.body.removeChild(a),{width:c.width,height:c.height}}class qT extends HT{get zPriority(){return Su.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){this.updateDimension()}get materialSharingIssue(){return"텍스트는 인스턴스마다 글자 텍스처를 재질에 얹는다"}updateStrokeStyle(){}updateFillStyle(){this.updateText()}updateDimension(){const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const i=new w.PlaneGeometry(n,s);i.rotateX(-Math.PI/2),this.object3d.geometry=i}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:s=!1,italic:i=!1,fontFamily:o="Serif",fontSize:r=10,fontColor:a="black",textAlign:c="center",textBaseline:l="middle",fillStyle:h}=this.component.state,d=Math.abs(e)||1,u=Math.abs(n)||1,p=this.component.text,f=h&&"none"!==h?h:"transparent",m={bold:s,italic:i,fontFamily:o,fontSize:r,fontColor:a,textAlign:c,textBaseline:l,width:d,height:u,fillStyle:f};if("object"==typeof f&&"pattern"===f?.type&&f.image){return void WT(this.component.app.url(h.image),p,d,u,m,h,e=>{t.map&&t.map.dispose(),t.map=e,t.color.set(16777215),t.needsUpdate=!0})}const g=VT(p,d,u,m);g?(t.map&&t.map.dispose(),t.map=g,t.color.set(16777215),g.needsUpdate=!0):"string"==typeof h&&(""!==h&&"transparent"!==h?t.color.set(du(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}hf("text",t=>new qT(t));const XT={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function KT(t){const e=t.model?.type??"";return"texture"===(XT[e]??"css3d")?new jT(t):new af(t)}hf("html-overlay-element",KT),hf("html-overlay-container",KT);class JT{setShape({extrudedShape:t,extrudedOptions:e}){this.extrudedShape=t,this.bb=new w.Box2,this.bb.setFromPoints(this.extrudedShape?.extractPoints(0).shape),this.extrudedOptions=e}generateTopUV(t,e,n,s,i){const o=e[3*n],r=e[3*n+1],a=e[3*s],c=e[3*s+1],l=e[3*i],h=e[3*i+1],d=this.bb,u=d.max.x-d.min.x,p=d.max.y-d.min.y;return[new w.Vector2((o-d.min.x)/u,1-(r-d.min.y)/p),new w.Vector2((a-d.min.x)/u,1-(c-d.min.y)/p),new w.Vector2((l-d.min.x)/u,1-(h-d.min.y)/p)]}generateSideWallUV(t,e,n,s,i,o){const r=e[3*n],a=e[3*n+1],c=e[3*n+2],l=e[3*s],h=e[3*s+1],d=e[3*s+2],u=e[3*i],p=e[3*i+1],f=e[3*i+2],m=e[3*o],g=e[3*o+1],y=e[3*o+2],b=this.extrudedOptions?.depth||100,v=this.bb,_=v.max.x-v.min.x,x=v.max.y-v.min.y;return Math.abs(a-h)<.01?[new w.Vector2(r/_,1-c/b),new w.Vector2(l/_,1-d/b),new w.Vector2(u/_,1-f/b),new w.Vector2(m/_,1-y/b)]:[new w.Vector2(a/x,1-c/b),new w.Vector2(h/x,1-d/b),new w.Vector2(p/x,1-f/b),new w.Vector2(g/x,1-y/b)]}}function QT(t,e){const n=t/2,s=e/2;return{points:[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}]}}function ZT(t,e,n){const s=Math.max(3,Math.floor(n)),i=[];for(let n=0;n<s;n++){const o=n/s*Math.PI*2;i.push({x:t*Math.cos(o),y:e*Math.sin(o)})}return{points:i,segments:s}}function tC(t){if(0===t.length)return[];let e=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of t)o.x<e&&(e=o.x),o.x>s&&(s=o.x),o.y<n&&(n=o.y),o.y>i&&(i=o.y);const o=(e+s)/2,r=(n+i)/2,a=t.map(t=>({x:t.x-o,y:t.y-r})),c=a[0],l=a[a.length-1];return a.length>1&&Math.abs(c.x-l.x)<1e-9&&Math.abs(c.y-l.y)<1e-9&&a.pop(),a}class eC extends Du{clear(){return this._mesh=void 0,super.clear()}get shape(){return null}topOutline(){const t=this.shape;if(!t||"function"!=typeof t.getPoints)return null;const e=this.outlineDivisions,n=t.getPoints(e);if(!n||n.length<3)return null;const s=tC(n);return s.length<3?null:{points:s}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new JT),this._boundUVGenerator}build(){super.build();const t=this.effectiveDepth,e=this.shape;if(!e)return;const n=this.boundUVGenerator;n&&n.setShape({extrudedShape:e,extrudedOptions:{depth:t}});const s=this.createGeometry(e),i=this.createMaterials();this._mesh=new w.Mesh(s,i),this._mesh.rotation.x=-Math.PI/2,this._mesh.rotation.y=-Math.PI,this._mesh.rotation.z=-Math.PI,this._mesh.castShadow=!0,this.object3d.add(this._mesh),this.updateFillStyle(),this.updateStrokeStyle()}createGeometry(t){const e=this.effectiveDepth,{lineWidth:n=0}=this.component.state,s={steps:1,depth:e,bevelEnabled:n>0,bevelThickness:0,bevelSize:n,bevelSegments:1,UVGenerator:this.boundUVGenerator},i=new w.ExtrudeGeometry(t,s);return i.center(),i}createMaterials(){const t=Nd(this.component.state.material3d),e=new w.MeshStandardMaterial;Gd(e,t);const n=new w.MeshStandardMaterial;return Gd(n,t),[e,n]}createTexture(){const{width:t,height:e}=this.component.bounds,n=GT(t),s=GT(e),i=Zp(n,s);this.component.render(i.getContext("2d"));const o=new w.CanvasTexture(i);return o.needsUpdate=!0,o.wrapS=w.RepeatWrapping,o.wrapT=w.RepeatWrapping,o.offset.set(0,1-e/s),o.repeat.set(t/n,e/s),o.minFilter=w.LinearFilter,o}getMaterials(){if(!this._mesh)return;const t=this._mesh.material;return Array.isArray(t)?t:void 0}updateMaterial3d(){super.updateMaterial3d();const t=this.getMaterials();if(!t)return;const e=Nd(this.component.state.material3d);for(const n of t)Gd(n,e)}updateAlpha(){const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,s=this.getMaterials();s&&(hu(s[0],0,e),hu(s[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(du(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,s=this.component.hasTextProperty?this.component.text:"";if(!s){const t=Du.buildFillStyleTexture(this.component);return t?(e.map&&e.map.dispose(),e.map=t,e.color.set(16777215)):(e.map&&(e.map.dispose(),e.map=null),e.color.set(du(n))),void(e.needsUpdate=!0)}const{bold:i=!1,italic:o=!1,fontFamily:r="Serif",fontSize:a=10,fontColor:c="black",textAlign:l="center",textBaseline:h="middle",paddingTop:d=0,paddingLeft:u=0,paddingRight:p=0,paddingBottom:f=0}=this.component.state,{width:m,height:g}=this.component.bounds,y=Math.abs(m)||1,b=Math.abs(g)||1,v={bold:i,italic:o,fontFamily:r,fontSize:a,fontColor:c,textAlign:l,textBaseline:h,width:Math.max(y-u-p,0),height:Math.max(b-d-f,0),fillStyle:n,offsetX:u,offsetY:d};if("object"==typeof n&&"pattern"===n?.type&&n.image){return void WT(this.component.app.url(n.image),s,y,b,v,n,t=>{e.map&&e.map.dispose(),e.map=t,e.color.set(16777215),e.needsUpdate=!0})}e.map&&e.map.dispose();const _=VT(s,y,b,v);e.map=_,e.color.set(16777215),e.needsUpdate=!0}updateDimension(){super.updateDimension()}onchange(t,e){if("path"in t&&this._mesh){const t=this._mesh.geometry,e=this.shape;if(e){const n=this.createGeometry(e);this._mesh.geometry=n,t.dispose()}}super.onchange(t,e)}}class nC extends eC{get shape(){const{cx:t=0,cy:e=0,rx:n=1,ry:s=1,startAngle:i=0,endAngle:o=2*Math.PI,anticlockwise:r=!1}=this.component.state,a=new w.EllipseCurve(t,e,Math.abs(n),Math.abs(s),i,o,r,0);return new w.Shape(a.getPoints(50))}}hf("ellipse",t=>new nC(t));class sC extends eC{get shape(){const{width:t,height:e,round:n=0}=this.component.state,s=fc(n,t,e);if(s>0){const n=s,i=new w.Path;return i.moveTo(n,0),i.lineTo(t-n,0),i.quadraticCurveTo(t,0,t,n),i.lineTo(t,e-n),i.quadraticCurveTo(t,e,t-n,e),i.lineTo(n,e),i.quadraticCurveTo(0,e,0,e-n),i.lineTo(0,n),i.quadraticCurveTo(0,0,n,0),new w.Shape(i.getPoints(12))}const i=new w.Shape;return i.moveTo(0,0),i.lineTo(t,0),i.lineTo(t,e),i.lineTo(0,e),i.lineTo(0,0),i}}function iC(t,e={}){const n=e.round??0,s=e.divisions??24;if(!t||0===t.length)return new w.Shape;const i=t.some(t=>zo(t)),o=n>0||t.some(t=>Lo(t,0)>0);if(i||o){const e=new w.Path;for(let s=0;s<t.length;s++){const i=t[(s-1+t.length)%t.length],o=t[s],r=t[(s+1)%t.length];if(i.x===o.x&&i.y===o.y)continue;const a=Lo(o,n);let c=Math.sqrt((i.x-o.x)**2+(i.y-o.y)**2),l=0!==c?Math.atan2(i.x-o.x,i.y-o.y):0;const h=Math.sin(l)*Math.min(a,c/2)+o.x,d=Math.cos(l)*Math.min(a,c/2)+o.y;c=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),l=0!==c?Math.atan2(r.x-o.x,r.y-o.y):0;const u=Math.sin(l)*Math.min(a,c/2)+o.x,p=Math.cos(l)*Math.min(a,c/2)+o.y;if(0===s?e.moveTo(h,d):e.lineTo(h,d),a>0&&e.quadraticCurveTo(o.x,o.y,u,p),zo(o)){const t=Lo(r,n),s=Math.sqrt((o.x-r.x)**2+(o.y-r.y)**2),i=0!==s?Math.atan2(o.x-r.x,o.y-r.y):0,a=Ro({x:u,y:p},{x:Math.sin(i)*Math.min(t,s/2)+r.x,y:Math.cos(i)*Math.min(t,s/2)+r.y},o.bulge);a&&e.absarc(a.cx,a.cy,a.radius,a.startAngle,a.endAngle,a.clockwise)}}return new w.Shape(e.getPoints(s))}const r=new w.Shape;for(let e=0;e<t.length;e++)0===e?r.moveTo(t[e].x,t[e].y):r.lineTo(t[e].x,t[e].y);return r}hf("rect",t=>new sC(t));class oC extends eC{get shape(){const{path:t=[],round:e=0}=this.component.state;return iC(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(eC.prototype).build.call(this);const t=this.effectiveDepth,e=this.shape;if(!e)return;const n=this.boundUVGenerator,s=this.minMax;if(n&&void 0!==s.minX&&void 0!==s.maxX&&void 0!==s.minY&&void 0!==s.maxY){const e=new w.Shape;e.moveTo(s.minX,s.minY),e.lineTo(s.maxX,s.minY),e.lineTo(s.maxX,s.maxY),e.lineTo(s.minX,s.maxY),e.closePath(),n.setShape({extrudedShape:e,extrudedOptions:{depth:t}})}else n&&n.setShape({extrudedShape:e,extrudedOptions:{depth:t}});const i=this.createGeometry(e),o=this.createMaterials();this._mesh=new w.Mesh(i,o),this._mesh.rotation.x=-Math.PI/2,this._mesh.rotation.y=-Math.PI,this._mesh.rotation.z=-Math.PI,this._mesh.castShadow=!0,this.object3d.add(this._mesh),this.updateFillStyle(),this.updateStrokeStyle()}createGeometry(t){const e=this.effectiveDepth,{lineWidth:n=0}=this.component.state,s={steps:1,depth:e,bevelEnabled:n>0,bevelThickness:0,bevelSize:n,bevelSegments:1,UVGenerator:this.boundUVGenerator},i=new w.ExtrudeGeometry(t,s),o=this.minMax;if(void 0!==o.minX&&void 0!==o.maxX&&void 0!==o.minY&&void 0!==o.maxY){const t=(o.minX+o.maxX)/2,e=(o.minY+o.maxY)/2;i.translate(-t,-e,0),i.computeBoundingBox();const n=i.boundingBox;n&&i.translate(0,0,-(n.min.z+n.max.z)/2)}else i.center();return i}get minMax(){if(!this._minMax){const{path:t}=this.component.state;let e,n,s,i;t.forEach((t,o)=>{if(0==o)return e=s=t.x,void(n=i=t.y);e=Math.min(e,t.x),s=Math.max(s,t.x),n=Math.min(n,t.y),i=Math.max(i,t.y)}),this._minMax={minX:e,minY:n,maxX:s,maxY:i}}return this._minMax}}hf("polygon",t=>new oC(t));class rC extends eC{get shape(){const{cx:t=0,cy:e=0,rx:n=1,ry:s=1,ratio:i=50,startAngle:o=0,endAngle:r=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=Math.abs(n),l=Math.abs(s),h=new w.EllipseCurve(t,e,c,l,o,r,a,0),d=new w.Shape(h.getPoints(50)),u=c/100*i,p=l/100*i;if(u>0&&p>0){const n=new w.EllipseCurve(t,e,u,p,o,r,a,0),s=new w.Path(n.getPoints(50));d.holes.push(s)}return d}}hf("donut",t=>new rC(t));class aC extends eC{get shape(){const{x1:t=0,y1:e=0,x2:n=0,y2:s=0,x3:i=0,y3:o=0,round:r=0}=this.component.state,a=[{x:t,y:e},{x:n,y:s},{x:i,y:o}];if(r>0){const t=new w.Path;for(let e=0;e<a.length;e++){const n=a[(e-1+a.length)%a.length],s=a[e],i=a[(e+1)%a.length];let o=Math.sqrt((n.x-s.x)**2+(n.y-s.y)**2),c=0!==o?Math.atan2(n.x-s.x,n.y-s.y):0;const l=Math.sin(c)*Math.min(r,o/2)+s.x,h=Math.cos(c)*Math.min(r,o/2)+s.y;o=Math.sqrt((i.x-s.x)**2+(i.y-s.y)**2),c=0!==o?Math.atan2(i.x-s.x,i.y-s.y):0;const d=Math.sin(c)*Math.min(r,o/2)+s.x,u=Math.cos(c)*Math.min(r,o/2)+s.y;0===e?t.moveTo(l,h):t.lineTo(l,h),t.quadraticCurveTo(s.x,s.y,d,u)}return new w.Shape(t.getPoints(12))}const c=new w.Shape;return c.moveTo(t,e),c.lineTo(n,s),c.lineTo(i,o),c.closePath(),c}}hf("triangle",t=>new aC(t));class cC extends eC{get shape(){const{ratio:t=30,wing:e=5,cx:n=0,cy:s=0,rx:i=1,ry:o=1}=this.component.state;if(e<3)return null;const r=Math.PI/2,a=2*Math.PI/e,c=i-t/100*i,l=o-t/100*o,h=new w.Shape;h.moveTo(n+i*Math.cos(-r),s+o*Math.sin(-r)),h.lineTo(n+(i-c)*(Math.cos(a-r)+Math.cos(0-r))/2,s+(o-l)*(Math.sin(a-r)+Math.sin(0-r))/2);for(let t=1;t<e;t++)h.lineTo(n+i*Math.cos(a*t-r),s+o*Math.sin(a*t-r)),h.lineTo(n+(i-c)*(Math.cos(a*(t+1)-r)+Math.cos(a*t-r))/2,s+(o-l)*(Math.sin(a*(t+1)-r)+Math.sin(a*t-r))/2);return h.closePath(),h}}hf("star",t=>new cC(t));const lC=[8,12,16],hC={cylinder:25,sphere:32},dC=128;function uC(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(dC,Math.max(3,Math.floor(t))):e}function pC(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(dC,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function fC(t){return lC.includes(t)}const mC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"},{type:"number",label:"height-segments",name:"heightSegments",property:"heightSegments"}],help:"scene/component/sphere"};class gC extends HT{buildGeometry(){const t=this.component.state,e=uC(t.segments,hC.sphere),n=pC(t.heightSegments,e);this.object3d.geometry=Av.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,s=n??t;this.setDimensionScale(2*t,2*s,2*e)}get effectiveDepth(){const{rx:t=0,rz:e}=this.component.state,n=e??t;return Math.max(2*n,1)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return ZT(t,e,uC(this.component.state.segments,hC.sphere))}}t.Sphere=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new gC(this)}get nature(){return mC}},t.Sphere=ug([ov("sphere")],t.Sphere);class yC extends Du{getObject3dInstance(){return new w.Sprite}build(){super.build(),this.buildMaterial()}get cz(){const{zPos:t=0}=this.component.state,{height:e}=this.component.bounds,{tz:n=0}=this.component.delta(),s=this.component.parent?._realObject;return t+n+e/2-(s?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}updateFillStyle(){const{fillStyle:t}=this.component.state,e=this.object3d.material;if(!e)return;const n=Du.buildFillStyleTexture(this.component);n?(e.map&&e.map.dispose(),n.needsUpdate=!0,e.map=n):"string"==typeof t&&("transparent"!==t?e.color.set(du(t)):e.opacity=0)}}class bC extends yC{buildMaterial(){const t=this.object3d.material;t&&t.dispose(),this.object3d.material=new w.SpriteMaterial({map:IT(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:s=1,height:i=1}=n?.bounds??{},{scale:o=1}=this.component.state;return{x:o*t/s,y:o*e/i,z:o}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const vC={mutable:!1,resizable:!0,rotatable:!0,properties:[]};t.Sprite=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new bC(this)}get nature(){return vC}},t.Sprite=ug([ov("sprite")],t.Sprite);const _C={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class xC extends HT{buildGeometry(){this.object3d.geometry=Av.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?QT(t,e):null}}t.Cube=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new xC(this)}get nature(){return _C}},t.Cube=ug([ov("cube")],t.Cube);const wC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class MC extends HT{buildGeometry(){const t=uC(this.component.state.segments,hC.cylinder);this.object3d.geometry=Av.primitive({kind:"cylinder",segments:t})}updateDimension(){const{rx:t=0,ry:e=0,depth:n=1}=this.component.state;this.setDimensionScale(2*t,n,2*e)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return ZT(t,e,uC(this.component.state.segments,hC.cylinder))}}t.Cylinder=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new MC(this)}get nature(){return wC}},t.Cylinder=ug([ov("cylinder")],t.Cylinder);const SC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class AC extends Du{get zPriority(){return Su.DECAL}build(){super.build();const{width:t=1,height:e=1,depth:n=1}=this.component.state;this.object3d.add(this.createCube(t,e,n));const s=this.createTextureBoard(t,n);s.position.set(0,0,.5*e+1),this.object3d.add(s)}createCube(t,e,n){const{boxColor:s="#ccaa76"}=this.component.state,i=Nd(this.component.state.material3d),o=new w.BoxGeometry(t,n,e),r=new w.MeshStandardMaterial({color:s,side:w.FrontSide});Gd(r,i);const a=new w.Mesh(o,r);return a.castShadow=i.castShadow,a.receiveShadow=i.receiveShadow,a}createTextureBoard(t,e){const n=Nd(this.component.state.material3d),{fillStyle:s="#ccaa76"}=this.component.state,i=Du.buildFillStyleTexture(this.component),o=new w.MeshStandardMaterial(i?{map:i}:{color:s||"#ccaa76",side:w.FrontSide});Gd(o,n);const r=new w.PlaneGeometry(t,e,1,1),a=new w.Mesh(r,o);return a.castShadow=n.castShadow,a.receiveShadow=n.receiveShadow,a}updateMaterial3d(){super.updateMaterial3d();const t=Nd(this.component.state.material3d);this.object3d.traverse(e=>{if(e.isMesh){const n=e.material;n&&Gd(n,t),e.castShadow=t.castShadow,e.receiveShadow=t.receiveShadow}})}updateFillStyle(){this.update()}onchange(t,e){super.onchange(t,e),"boxColor"in t&&this.update()}}var kC;t.Banner=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return SC}buildRealObject(){return new AC(this)}},t.Banner=ug([ov("banner")],t.Banner);const EC={far:1e5,fov:80,near:1,zoom:1},TC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"near",name:"near"},{type:"number",label:"far",name:"far"},{type:"number",label:"fov",name:"fov"},{type:"number",label:"zoom",name:"zoom"},{type:"checkbox",label:"show-helper",name:"showHelper"}],help:"scene/component/camera"};class CC extends Du{getObject3dInstance(){return new w.Mesh}updateCamera(){const{near:t=EC.near,far:e=EC.far,fov:n=EC.fov,zoom:s=EC.zoom,showHelper:i}=this.component.state;this.camera.far=e,this.camera.fov=n,this.camera.near=t,this.camera.zoom=s,i?this.helper||(this.helper=new w.CameraHelper(this.camera),this.object3d.add(this.helper)):this.helper&&(this.object3d.remove(this.helper),delete this.helper)}build(){super.build();const{width:t=0,height:e=0,depth:n=0,fillStyle:s="lightgray"}=this.component.state;this.object3d.geometry=new w.BoxGeometry(t,n,e);const i=Nd(this.component.state.material3d),o=new w.MeshStandardMaterial({color:s});Gd(o,i),this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.receiveShadow,this.camera=new w.PerspectiveCamera,this.camera.position.set(0,0,0),this.object3d.add(this.camera),this.object3d.lookAt(0,0,0),this.updateCamera()}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}}t.Camera=kC=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return kC._image||(kC._image=new Image,kC._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1IAAANSAQMAAABV6G1EAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAABlBMVEX6+voBAQGV71ZvAAAFO0lEQVR42u3dMZLkNBiGYakUKFRIqKOISxDvETiCTBEQcgQOQE7clyAi8REm7KDXIhgYoMa/7fbIX+2K9w022MCP/25Z28GW5RwRERERERERERERERERERERERERERERERERERERERERERERERHRl9mv7fdPn7879sf8Mcq3J3r5EJXaUy3Wddrcd6qNybx9F2/lZ63H+nVCa9Oe9elZa5ksa/dDbE+3fsm4v27C89bd+i6W3l+XdcnSWtuxyvPW+hqorbWb0Jr7Pl3m4tjfVMIZ625d6L5pxTPWw7rQY9P6pqu1dF8aq5d83cE3rXrGWluIxV6h53eotv4c1FigureLn7Nm66ZvvZf8SSues16sD2jubz2sC839fmvYiz7t//LJna27wsr7VjlnNWtPeHTfNlae2bZvnaTePUd+74fqV2LNxv6zdN8O3z9HSWhlc4F+dOvdsKbe2+F7q+zPddq6W2ts6r31vrN825/rtPWwvvcL5losy11uxQNz5U6fYT4w12mrWf80TUNZdetXal/LtwNW6WOFI1Y9bU3GVnfFXM9bneZKwrmKcK4qnKsK52q6uULTzRWFVjpkta/OykKrCq02puWFVhRaSWjlQa0itJrO8oNaQWgloZWFVhnUqjrLN50VBrWi0MpCqwitOqjVdFYQWlFopUGtLLSq0GpjWl5oRaGVBrWy0KpCq+ksP6gVhFYSWllolUGtqrNW/jvBZVYY1IpCKwutIrTqoFbTWUFoxUGtJLSK0KpCq41peaEVhVYa1MpCqwqtprP8oFYUWklo5UGtIrSazvJCKwxqRaGVhVYZ1Ko664ems34UWj8Nav0stBoWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhbW/9L6RWgp37WofIek8j2cyveLTkqrCq0itLLQSkJL+Q5k5budle/HVr73e/24gAHenZ6FlvK9+srzAoLQUp65oDy3QnoeRxFaWWgpz2pRnncThJbyzCDpuUtVaBWhlYWW8qwx5RlqynPovNBSnuUnPaOwCK0stJLQUp4BqjzbVHk+rFNaVWgVoZWFlvJc6Si0lGdzK88cV57bLj2PvgitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqxyyahcrH7JKFysJ54rCuYJwLi+cywnn+vdlLp+rCOfKwrnStXP95zLxiJX7WEFoeaHljO/xEqsaf9/FWqz1bM+VzloP655df2uxrnP9XPHKue7OeMDsuWInyx+Y67T1Yv0gs+cKvay6P5fvZZULrdnYFBbbcr2sdKF1MxbZFdZkLLItq3aay6/vJ102eusD2rJKl633nw/o3n+uxbrpLSv1svL6M95hQ3xYNz33t16sC21Zoc+28Xahm+u+Ic7WhbYs1+dRfrvQ5LpvHOaFNq3SZ8n/faEt6twDtli7wrJpxT6P1183/di0Ti36u3XT903Ld1qGrzf9smmdWhyTddNzf8t8UqdtK/dZGq8P2DZ1ZnHcrQ/osWO5PkvDuby7NE58Yctk7Qq3PSv3+bpc3F0aJ56wF+uLX9xu6eOb4es9z/vWc0vR3oZuByjnf2t/fP/54B/2WvvWEREREREREREREREREREREREREREREREREREREREREREREREREX2J/QlrTpqHD8xO1gAAAABJRU5ErkJggg=="),kC._image}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,kC.image,e,n,s,i)}buildRealObject(){return new CC(this)}get nature(){return TC}},t.Camera=kC=ug([ov("camera")],t.Camera);const OC={mutable:!1,resizable:!0,rotatable:!0,properties:[...sv],"value-property":"source",help:"scene/component/gltf-object"};t.GLTFObject=class extends(iv(mc(pc))){get nature(){return OC}},t.GLTFObject=ug([ov("gltf-object")],t.GLTFObject);const PC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"light-type",name:"lightType",property:{options:["","point","directional"]}},{type:"number",label:"intensity",name:"intensity"},{type:"number",label:"distance",name:"distance"},{type:"number",label:"decay",name:"decay"},{type:"checkbox",label:"cast-shadow",name:"castShadow"},{type:"number",label:"near",name:"near",placeholder:"0.5"},{type:"number",label:"far",name:"far",placeholder:"1000"},{type:"number",label:"fov",name:"fov",placeholder:"90"},{type:"number",label:"zoom",name:"zoom",placeholder:"1"},{type:"checkbox",label:"show-helper",name:"showHelper"}],help:"scene/component/light"};class IC extends Du{updatePointLight(){const{lightType:t="point",distance:e=0,intensity:n=10,decay:s=1,fillStyle:i="white",castShadow:o,near:r=.5,far:a=1e3,fov:c=90,zoom:l=1,showHelper:h}=this.component.state;if(this.object3d.color=new w.Color(i),"point"==t&&(this.object3d.distance=e,this.object3d.decay=s),this.object3d.intensity=n,this.object3d.castShadow=o,o){const t=this.object3d.shadow?.camera;t.far=a,t.near=r,t.fov=c,t.zoom=l}if(h){const t=this.object3d.shadow?.camera;this.helper||(this.helper=new w.CameraHelper(t),this.object3d.add(this.helper))}else this.helper&&(this.object3d.remove(this.helper),delete this.helper)}getObject3dInstance(){const{lightType:t="point"}=this.component.state;return"point"==t?new w.PointLight:new w.DirectionalLight}update(){this.clear(),this.build(),this.updateDimension(),this.updateHidden(),this.updatePointLight()}}t.PointLight=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new IC(this)}get anchors(){return[]}get nature(){return PC}},t.PointLight=ug([ov("light")],t.PointLight);const DC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class zC extends HT{buildGeometry(){this.object3d.geometry=Av.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?QT(t,e):null}}t.Wall=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new zC(this)}get nature(){return DC}},t.Wall=ug([ov("wall")],t.Wall);const RC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"},{type:"checkbox",label:"hide-in-2d-view",name:"hideIn2DView"},{type:"checkbox",label:"hide-in-3d-view",name:"hideIn3DView"}],help:"scene/component/floor-plate"};class jC extends Du{get zPriority(){return Su.FLOOR}get receivingSurfaceY(){return this.placementSurfaceY()}resolveShadow(){const t=this.component.state,e=t.material3d,{alpha:n=1,fillStyle:s}=t,i=n>=.9&&"none"!==s;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??i}}updateHidden(){const t=this.component.state,e=!!this.component.app?.isViewMode;this.object3d.visible=!(t.hidden||e&&t.hideIn3DView)}clear(){return this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0),this._mesh=void 0,super.clear()}build(){super.build();const{width:t,height:e,depth:n=1}=this.component.state;if(!t||!e)return;const s=Math.abs(t),i=Math.abs(e),o=Math.max(n,.5),r=new w.BoxGeometry(s,o,i),a=this._buildTopMaterial(),c=this._buildSideMaterial(),l=[c,c,a,c,c,c];this._mesh=new w.Mesh(r,l),this._mesh.position.y=0;const{cast:h,receive:d}=this.resolveShadow();this._mesh.castShadow=h,this._mesh.receiveShadow=d,this.object3d.add(this._mesh)}_buildTopMaterial(){const{alpha:t=1,fillStyle:e}=this.component.state,n=Nd(this.component.state.material3d),s=Du.buildFillStyleTexture(this.component);if(s){this._topTexture=s;const t=new w.MeshStandardMaterial({map:s,side:w.DoubleSide});return hu(t,0,e),t.depthWrite=t.opacity>=.9,Gd(t,n),t}const i="string"==typeof e&&"none"!==e?du(e):"#e0e0e0",o=new w.MeshStandardMaterial({color:i,side:w.DoubleSide});return hu(o,0,e),o.depthWrite=o.opacity>=.9,Gd(o,n),o}_buildSideMaterial(){const{strokeStyle:t,alpha:e=1}=this.component.state,n="string"==typeof t&&t?du(t):"#999999",s=Nd(this.component.state.material3d),i=new w.MeshStandardMaterial({color:n});return Gd(i,s),i.side=w.DoubleSide,hu(i,0,t),i.depthWrite=i.opacity>=.9,i}updateAlpha(){if(!this._mesh)return;const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,s=this._mesh.material;for(let t=0;t<s.length;t++){const i=s[t];hu(i,0,2===t?e:n),i.depthWrite=i.opacity>=.9}}updateFillStyle(){if(!this._mesh)return;this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0);const t=this._mesh.material;t[2].dispose(),t[2]=this._buildTopMaterial()}updateStrokeStyle(){if(!this._mesh)return;const t=this._mesh.material,e=this._buildSideMaterial();for(let n=0;n<t.length;n++)2!==n&&(t[n].dispose(),t[n]=e)}}t.FloorPlate=class extends Kl{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new jC(this)}get nature(){return RC}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}},t.FloorPlate.requires3d=!0,t.FloorPlate=ug([ov("floor-plate")],t.FloorPlate);function $C(t,e={}){const n=e.size??5,s=e.color??4500172,i=e.emissive??2245734,o=new w.SphereGeometry(n,16,12),r=new w.MeshStandardMaterial({color:s,emissive:i,emissiveIntensity:.15,metalness:.3,roughness:.4,transparent:!0,opacity:.35}),a=new w.Mesh(o,r);e.position&&a.position.set(e.position[0],e.position[1],e.position[2]),a.userData.alwaysRaycast=!0,a.scale.setScalar(1),a.visible=e.visible??!(!0===t.app?.isViewMode);const c=()=>{r.emissiveIntensity=.9,r.opacity=.95,a.scale.setScalar(1.35),t.invalidate?.()},l=()=>{r.emissiveIntensity=.15,r.opacity=.35,a.scale.setScalar(1),t.invalidate?.()};return t.on("mouseenter",c),t.on("mouseleave",l),a.userData.dispose=()=>{t.off("mouseenter",c),t.off("mouseleave",l)},a}class LC extends HT{get zPriority(){return Su.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1,i=new w.PlaneGeometry(n,s);i.rotateX(-Math.PI/2),this.object3d.geometry=i}updateDimension(){this.update()}build(){super.build();const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1,i=Math.max(2,.04*Math.min(n,s));this.object3d.add($C(this.component,{size:i,position:[n/2-i,i,-s/2+i]}))}}const FC={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let NC=class extends(ev(mc(pc))){buildRealObject(){return new LC(this)}get nature(){return FC}};NC=ug([ov("decal")],NC);class HC extends Du{getObject3dInstance(){return new w.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const BC="#dde2e8",GC="#9c9c9c",UC="#e8e8ec",VC=.35;function WC(t,e,n,s,i){if(!e.visible)return new w.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=e.alpha*n,r="wall"===s?BC:"floor"===s?GC:UC,a=new w.MeshStandardMaterial({metalness:0,roughness:"wall"===s?.6:.85,transparent:o<1,opacity:o,side:i?w.BackSide:w.DoubleSide});return function(t,e,n,s,i,o){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const s=!o,r=Du.buildFillStyleTexture(e,n,{mirror:s,rotation:i});if(r)return t.map&&t.map.dispose(),t.map=r,void t.color.set("#ffffff")}t.color.set(s)}}(a,t,e.fillStyle,r,e.rotation,e.mirror),a}class YC extends HC{get zPriority(){return Su.BACKDROP}get position(){if(this.component.state.fitToBoard){return{x:0,y:super.position.y,z:0}}return super.position}build(){super.build();const t=this.component.state;let e=t.width,n=t.height;if(t.fitToBoard){const t=this.component.rootModel,s=t?.state;s&&Number.isFinite(s.width)&&Number.isFinite(s.height)&&(e=s.width,n=s.height)}const s=this.effectiveDepth||Math.min(e,n)||200,i=t.alpha??1,o=!1!==t.seeThrough,r={east:this._resolveFace("east",BC,!0,VC),west:this._resolveFace("west",BC,!0,VC),north:this._resolveFace("north",BC,!0,VC),south:this._resolveFace("south",BC,!0,VC),floor:this._resolveFace("floor",GC,!0,1),ceiling:this._resolveFace("ceiling",UC,!0,1)},a=[WC(this.component,r.east,i,"wall",o),WC(this.component,r.west,i,"wall",o),WC(this.component,r.ceiling,i,"ceiling",o),WC(this.component,r.floor,i,"floor",o),WC(this.component,r.south,i,"wall",o),WC(this.component,r.north,i,"wall",o)],c=new w.BoxGeometry(e,s,n),l=new w.Mesh(c,a);if(l.receiveShadow=!0,this.object3d.add(l),this.component.app?.isEditMode){const t=new w.LineBasicMaterial({color:4473941,transparent:!0,opacity:.7}),e=new w.LineSegments(new w.EdgesGeometry(c),t);this.object3d.add(e)}const h=Math.max(2,.04*Math.min(e,n,s));this.object3d.add($C(this.component,{size:h,position:[e/2,s/2+h,-n/2]}))}_resolveFace(t,e,n,s){const i=this.component.state,o=i.faces?.[t]??{},r=o.visible,a=o.alpha,c=o.rotation,l=90===c||180===c||270===c?c:0;return{fillStyle:o.fillStyle??e,visible:"boolean"==typeof r?r:n,alpha:"number"==typeof a&&Number.isFinite(a)?a:s,rotation:l,mirror:!0===o.mirror}}updateDimension(){}onchange(t,e){["alpha","width","height","depth","fitToBoard","faces","seeThrough"].some(e=>e in t)?this.update():super.onchange(t,e)}updateAlpha(){}}const qC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"checkbox",label:"fit-to-board",name:"fitToBoard"},{type:"checkbox",label:"see-through",name:"seeThrough"},{type:"backdrop-faces",label:"",name:"faces"}],help:"scene/component/backdrop"};let XC=class extends(ev(mc(pc))){buildRealObject(){return new YC(this)}get workEnvironmentCeiling(){const t=this.state,e=this.rootModel?.state,n=t.fitToBoard&&e&&Number.isFinite(e.width)&&Number.isFinite(e.height),s=n?e.width:Math.abs(Number(t.width)||0),i=n?e.height:Math.abs(Number(t.height)||0),o=Number(t.depth)||Math.min(s,i)||200,r=Number(t.zPos)||0,a=e?.placement;return"inverted"===a?r:"space"===a?r+o/2:r+o}get nature(){return qC}added(t){super.added?.(t),this.state.fitToBoard&&(this._syncFromRoot(!0),this._attachRootListener())}async ready(){await super.ready(),this.state.fitToBoard&&this._syncFromRoot(!1)}removed(t){this._detachRootListener(),super.removed?.(t)}dispose(){this._detachRootListener(),super.dispose?.()}onchange(t,e){"fitToBoard"in t&&(t.fitToBoard?(this._syncFromRoot(!0),this._attachRootListener()):this._detachRootListener()),super.onchange?.(t,e)}_syncFromRoot(t=!1){const e=this.rootModel;if(!e||e===this)return;const n=e.state;if(!n)return;const s={},i=Number.isFinite(n.width)?n.width:this.state.width,o=Number.isFinite(n.height)?n.height:this.state.height;i!==this.state.width&&(s.width=i),o!==this.state.height&&(s.height=o);const r=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(r!==this.state.left&&(s.left=r),a!==this.state.top&&(s.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(i,o);e!==t&&(s.depth=e)}}Object.keys(s).length>0&&this.set(s)}_attachRootListener(){if(this._onRootChange)return;const t=this.rootModel;t&&t!==this&&(this._onRootChange=t=>{("width"in t||"height"in t||"left"in t||"top"in t)&&this._syncFromRoot()},t.on?.("change",this._onRootChange))}_detachRootListener(){if(!this._onRootChange)return;const t=this.rootModel;t?.off?.("change",this._onRootChange),this._onRootChange=void 0}};function KC(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function JC(t,e,n,s){const i=[];for(let o=1;o<=s;o++){const r=o/s,a=1-r;i.push(new w.Vector3(a*a*t.x+2*a*r*e.x+r*r*n.x,a*a*t.y+2*a*r*e.y+r*r*n.y,a*a*t.z+2*a*r*e.z+r*r*n.z))}return i}XC=ug([ov("backdrop")],XC);class QC extends Du{getObject3dInstance(){return new w.Group}get gizmoTransformable(){return!0}get syncZPosOffset(){return 0}get geometricOffsetY(){return 0}syncFromObject3D(){}applyDimensionFromGizmo(t){}build(){super.build(),this._buildLine()}get smoothedPath(){const t=this.worldPath;if(t.length<2)return t;const{round:e=0}=this.component.state;if(e<=0||t.length<3)return t;const n=[];n.push(t[0]);for(let s=1;s<t.length;s++){const i=t[s-1],o=t[s],r=t[s+1];if(!r){n.push(o);break}const a=i.x-o.x,c=i.y-o.y,l=i.z-o.z,h=Math.sqrt(a*a+c*c+l*l),d=Math.min(e,h/2),u=r.x-o.x,p=r.y-o.y,f=r.z-o.z,m=Math.sqrt(u*u+p*p+f*f),g=Math.min(e,m/2),y=h>0?new w.Vector3(o.x+a/h*d,o.y+c/h*d,o.z+l/h*d):o.clone(),b=m>0?new w.Vector3(o.x+u/m*g,o.y+p/m*g,o.z+f/m*g):o.clone();n.push(y),n.push(...JC(y,o,b,8))}return n}_buildLine(){const t=this.smoothedPath;if(t.length<2)return;const{strokeStyle:e,lineWidth:n=2,alpha:s=1,lineDash:i,begin:o="none",beginSize:r="size5",end:a="none",endSize:c="size5"}=this.component.state,l=Math.max(n,1),p="string"==typeof e&&"transparent"!==e?du(e):"#000000",f=new w.Color(p),m=this._getResolution(),g=o,y=a,b=KC(g,l),v=KC(y,l),_=t[0],x=t[t.length-1],M=(new w.Vector3).subVectors(t[1],_).normalize(),S=(new w.Vector3).subVectors(t[t.length-2],x).normalize(),A=[...t];b>0&&(A[0]=_.clone().add(M.clone().multiplyScalar(b))),v>0&&(A[A.length-1]=x.clone().add(S.clone().multiplyScalar(v)));const k=new u.LineGeometry;k.setPositions(A.flatMap(t=>[t.x,t.y,t.z]));const E=function(t,e){switch(t){case"round-dot":return{dashSize:e,gapSize:e};case"square-dot":return{dashSize:2*e,gapSize:e};case"dash":return{dashSize:4*e,gapSize:1.5*e};case"dash-dot":return{dashSize:4*e,gapSize:2*e};case"long-dash":return{dashSize:6*e,gapSize:3*e};case"long-dash-dot":return{dashSize:6*e,gapSize:2*e};case"long-dash-dot-dot":return{dashSize:6*e,gapSize:e};default:return null}}(i,l),T=new d.LineMaterial({color:f.getHex(),linewidth:l,worldUnits:!0,transparent:s<1,opacity:s,resolution:m,dashed:!!E,dashSize:E?.dashSize??1,gapSize:E?.gapSize??1,dashScale:1});if(this._line2=new h.Line2(k,T),this._line2.computeLineDistances(),this.object3d.add(this._line2),"none"!==g){const t=nf(g,ef(r,l));if(t){const e=(new w.Quaternion).setFromUnitVectors(new w.Vector3(1,0,0),M.clone().negate());this._placeTip(t,_,e,f,s,m)}}if("none"!==y){const t=nf(y,ef(c,l));if(t){const e=(new w.Quaternion).setFromUnitVectors(new w.Vector3(1,0,0),S.clone().negate());this._placeTip(t,x,e,f,s,m)}}}_placeTip(t,e,n,s,i,o){const r=t.mesh||t.line2||t.group;if(r){if(r.position.copy(e),r.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(s),e.transparent=i<1,e.opacity=i}else if(t.line2){const e=t.line2.material;e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution.copy(o)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution&&e.resolution.copy(o)}});this.object3d.add(r)}}_getResolution(){const t=this.threeContainer?.renderer3d;if(t){return t.getSize(new w.Vector2)}return new w.Vector2(window.innerWidth,window.innerHeight)}onGizmoDragEnd(t){const e=this._component,n=e.path;if(!n||n.length<2)return;const s=this.object3d,{width:i=0,height:o=0}=e.parent?.bounds??{},{x:r,y:a}=e.center,c=s.position,l=s.rotation,h=s.scale,d=this.position;if(Math.abs(c.x-d.x)<.001&&Math.abs(c.y-d.y)<.001&&Math.abs(c.z-d.z)<.001&&Math.abs(l.x)<.001&&Math.abs(l.y)<.001&&Math.abs(l.z)<.001&&Math.abs(h.x-1)<.001&&Math.abs(h.y-1)<.001&&Math.abs(h.z-1)<.001)return;const u=QC.computeBakedPath(n,{x:r,y:a},{width:i,height:o},s);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(t,e,n,s){const i=n.width,o=n.height,r=e.x,a=e.y;return s.updateMatrixWorld(!0),t.map(t=>{const e=new w.Vector3(t.x-r,t.z||0,t.y-a).applyMatrix4(s.matrixWorld),n={x:e.x+i/2,y:e.z+o/2};return Math.abs(e.y)>.001&&(n.z=e.y),n})}updateStrokeStyle(){this.updateDimension()}updateAlpha(){this.updateDimension()}updateDimension(){this.clear(),this.build()}onchange(t,e){("path"in t||"from"in t||"to"in t)&&(this.updateDimension(),this.updatePosition()),("round"in t||"lineDash"in t||"lineWidth"in t||"begin"in t||"end"in t||"beginSize"in t||"endSize"in t)&&this.updateDimension(),super.onchange(t,e)}clear(){for(;this.object3d.children.length>0;){const t=this.object3d.children[0];this.object3d.remove(t),bu(t)}return this._line2=void 0,super.clear()}}class ZC extends QC{get worldPath(){const t=this.component.path;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center,s=this.component,i=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return t.map((s,r)=>{const a=t.length>1?r/(t.length-1):0;return new w.Vector3(s.x-e,s.z||i+(o-i)*a,s.y-n)})}}hf("line",t=>new ZC(t));class tO extends QC{get worldPath(){const t=this.component.path;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center;return t.map(t=>new w.Vector3(t.x-e,t.z||0,t.y-n))}}hf("polyline",t=>new tO(t));class eO extends QC{get worldPath(){const t=this.component.drawPath;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center,s=this.component,i=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return t.map((s,r)=>{const a=t.length>1?r/(t.length-1):0;return new w.Vector3(s.x-e,s.z||i+(o-i)*a,s.y-n)})}}function nO(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}hf("ortholine",t=>new eO(t)),hf("group",t=>new HC(t));class sO{constructor(t){this._count=0,this._placements=[],this._geometry=t.geometry,this._material=t.material,this._capacity=Math.max(1,t.capacity??16),this._name=t.name??"instanced",this._castShadow=t.castShadow??!0,this._receiveShadow=t.receiveShadow??!1,this.object3d=new w.Group,this.object3d.name=this._name,this._mesh=this._makeMesh(this._capacity),this.object3d.add(this._mesh)}_makeMesh(t){const e=new w.InstancedMesh(this._geometry,this._material,t);return e.name=this._name+"__instances",e.castShadow=this._castShadow,e.receiveShadow=this._receiveShadow,e.instanceMatrix.setUsage(w.DynamicDrawUsage),e.count=0,e}get mesh(){return this._mesh}get material(){return this._material}set material(t){this._material=t,this._mesh.material=t}get count(){return this._count}get capacity(){return this._capacity}place(t){const e=t.length;if(e>this._capacity){const t=nO(e,this._capacity);this.object3d.remove(this._mesh),this._mesh.dispose(),this._capacity=t,this._mesh=this._makeMesh(t),this.object3d.add(this._mesh)}this._placements.length=e;for(let n=0;n<e;n++){const e=t[n];this._placements[n]=e,this._writeMatrix(n,e),void 0!==e.color&&this._writeColor(n,e.color)}this._count=e,this._mesh.count=e,this.commit()}setCount(t){if(t>this._capacity){const e=nO(t,this._capacity),n=this._mesh.frustumCulled;this.object3d.remove(this._mesh),this._mesh.dispose(),this._capacity=e,this._mesh=this._makeMesh(e),this._mesh.frustumCulled=n,this.object3d.add(this._mesh)}this._placements.length=0,this._count=t,this._mesh.count=t}setMatrix(t,e){t<0||t>=this._count||this._mesh.setMatrixAt(t,e)}update(t,e){t<0||t>=this._count||(this._placements[t]=e,this._writeMatrix(t,e),void 0!==e.color&&this._writeColor(t,e.color),this.commit())}setRotation(t,e){if(t<0||t>=this._count)return;const n=this._placements[t];n&&(n.rotation=e,this._writeMatrix(t,n))}commitMatrices(){this._mesh.instanceMatrix.needsUpdate=!0}setColor(t,e){t<0||t>=this._count||(this._writeColor(t,e),this._mesh.instanceColor&&(this._mesh.instanceColor.needsUpdate=!0))}indexOf(t){return t>=0&&t<this._count?t:-1}commit(){this._mesh.instanceMatrix.needsUpdate=!0,this._mesh.instanceColor&&(this._mesh.instanceColor.needsUpdate=!0),this._mesh.computeBoundingSphere()}dispose(){this.object3d.remove(this._mesh),this._mesh.dispose(),this._placements.length=0,this._count=0}_writeMatrix(t,e){const n=sO;n._p.set(e.position.x,e.position.y,e.position.z);const s=e.rotation;n._e.set(s?.x??0,s?.y??0,s?.z??0),n._q.setFromEuler(n._e);const i=e.scale;"number"==typeof i?n._s.set(i,i,i):n._s.set(i?.x??1,i?.y??1,i?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){sO._c.set(e),this._mesh.setColorAt(t,sO._c)}}function iO(t,e,n){const s=Math.max(1,Math.floor(t.x??1)),i=Math.max(1,Math.floor(t.y??1)),o=Math.max(1,Math.floor(t.z??1)),r=e.x??0,a=e.y??0,c=e.z??0,l=n?.x??0,h=n?.y??0,d=n?.z??0,u=[];for(let t=0;t<i;t++)for(let e=0;e<o;e++)for(let n=0;n<s;n++)u.push({position:{x:l+n*r,y:h+t*a,z:d+e*c}});return u}sO._m=new w.Matrix4,sO._p=new w.Vector3,sO._q=new w.Quaternion,sO._e=new w.Euler,sO._s=new w.Vector3,sO._c=new w.Color;class oO extends Du{build(){super.build()}update(){}}const rO={far:1e5,fov:80,near:1,zoom:1};class aO extends Du{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new w.PerspectiveCamera}updateCamera(){const{near:t=rO.near,far:e=rO.far,fov:n=rO.fov,zoom:s=rO.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=s}}class cO extends HT{buildGeometry(){const{width:t,height:e}=this.component.state.dimension;this.object3d.geometry=new w.PlaneGeometry(t,e)}buildMaterial(){this.object3d.material=new w.MeshStandardMaterial({opacity:0,side:w.DoubleSide,blending:w.NoBlending})}}class lO extends Du{getObject3dInstance(){return new w.Scene}dispose(){for(const t of this.object3d.children)bu(t);this._animationMixer&&(this._animationMixer.stopAllAction(),this._animationMixer.uncacheRoot(this.object3d),this._animationMixer=void 0),super.dispose()}clear(){return this._floor&&(this.object3d.remove(this._floor),this._floor.material instanceof Array?this._floor.material.forEach(t=>t.dispose()):this._floor.material.dispose(),this._floor.geometry.dispose(),delete this._floor),super.clear()}get floor(){return this._floor}set floor(t){this._floor&&(this.object3d.remove(this._floor),this._floor.clear(),delete this._floor),t&&(this._floor=t,this.object3d.add(t)),this.component.invalidate()}build(){super.build(),this.floor=Tf(this.component)}updateTransform(){}updateDimension(){}updatePosition(){}updateRotate(){}updateScale(){}updateAlpha(){}updateHidden(){}get animationMixer(){return this._animationMixer||(this._animationMixer=new w.AnimationMixer(this.object3d)),this._animationMixer}}const hO=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class dO extends Du{get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}constructor(t){super(t),this._origInvalidate=t.invalidate.bind(t),t.invalidate=()=>{this._origInvalidate(),this._refreshTextureNow()}}getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds;if(!t||!e)return;const n=Nd(this.component.state.material3d),s=new w.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const i=IT(this.component),o=new w.MeshStandardMaterial({map:i});Gd(o,n),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=n.castShadow,this.object3d.receiveShadow=n.receiveShadow}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}get dimension(){const{width:t,height:e}=this.component.bounds;return{width:t||1,height:e||1,depth:1}}get scale(){const t=super.scale,{width:e,height:n}=this.dimension;return{x:t.x*e,y:t.y,z:t.z*n}}updateDimension(){this.updateTransform()}_debouncedRebuild(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=void 0,this.update()},100)}_refreshTextureNow(){const t=this.object3d.material,e=t?.map;if(!e)return;const n=e.source?.data;n&&(zT(n,this.component,2),e.needsUpdate=!0)}update(){this.clear(),this.build(),this.updateDimension(),this.updateTransform(),this.updateHidden()}onchange(t,e){super.onchange(t,e);for(const e of Object.keys(t))if(!hO.has(e)){this._debouncedRebuild();break}}updateFillStyle(){this._debouncedRebuild()}updateStrokeStyle(){this._debouncedRebuild()}updateText(){this._debouncedRebuild()}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),t.transparent=!0,this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}clear(){return this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),bu(this.object3d),super.clear()}dispose(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),this._origInvalidate&&(this.component.invalidate=this._origInvalidate,this._origInvalidate=void 0),super.dispose()}}const uO={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"precision",name:"precision",property:{options:[{display:"High",value:"highp"},{display:"Medium",value:"mediump"},{display:"Low",value:"lowp"}]}},{type:"checkbox",label:"anti-alias",name:"antialias",property:"antialias"},{type:"checkbox",label:"3dmode",name:"threed",property:"threed"},{type:"checkbox",label:"figure-lod",name:"lodEnabled",property:"lodEnabled"},{type:"checkbox",label:"auto-rotate",name:"autoRotate",property:"autoRotate"},{type:"checkbox",label:"debug",name:"debug",property:"debug"}],help:"scene/component/three-container"};function pO(t){if(Array.isArray(t))return`[${t.map(pO).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${pO(e[t])}`).join(",")}}`}return JSON.stringify(t)}t.ThreeContainer=class extends Cy{constructor(){super(...arguments),this._capability=new rm}get sceneManager(){return this._capability.sceneManager}get cameraManager(){return this._capability.cameraManager}get rendererManager(){return this._capability.rendererManager}get lightManager(){return this._capability.lightManager}get controlsManager(){return this._capability.controlsManager}get eventManager(){return this._capability.eventManager}get hasEnvironment(){return this._capability.hasEnvironment}containable(t){return!0}is3dContainer(){return!0}getLightingConfig(){return{hemisphere:{skyColor:16777215,groundColor:14540253,intensity:1},directional:{color:16777215,intensity:1.2,attachToCamera:!0,castShadow:!1}}}getCss3DSceneAttribute(){return"three-container:css3d-renderer"}init_scene3d(){this._capability.isInitialized&&this._capability.destroy(),this._capability.init(this,{lightingConfig:this.getLightingConfig(),css3DSceneAttribute:this.getCss3DSceneAttribute(),skipEnvironment:!0,skipPostprocessing:!0,skipShadowMap:!0}),this._capability.buildOverlays(),this._capability.resize(),this.onchangeData&&this.onchangeData(this.data,this.data)}destroy_scene3d(){this.stop(),this._capability.destroy()}stop(){}resize(){this._capability.resize()}get scene3d(){return this._capability.isInitialized||this.init_scene3d(),this._capability.scene3d}get renderer3d(){return this._capability.renderer3d}get mixer(){return this._capability.mixer}get css3DScene(){return this._capability.css3DScene}get css3DRenderer(){return this._capability.css3DRenderer}render_threed(){this._capability.renderThreeD()}get _parentIs3dMode(){return!!this.rootModel?.is3dMode}render(t){this._parentIs3dMode||(this.app.isViewMode&&this.setState("threed",!0),!this.state.threed||this._capability.noSupportWebgl?super.render(t):this._capability.camera&&this._capability.renderCSS3D())}postrender(t){if(this._parentIs3dMode)return;const{left:e,top:n,debug:s,threed:i}=this.state;let{width:o,height:r}=this.bounds;if(o=Math.floor(o),r=Math.floor(r),i){if(this._capability.isInitialized||this.init_scene3d(),this._capability.noSupportWebgl)return void this._capability.showWebglNoSupportText(t,this.state.width,this.state.height);if(!this._capability.renderer3d)return;this._capability.renderThreeD();const i=this._capability.domElement;if(!i||!i.width||!i.height)return;t.drawImage(i,0,0,i.width,i.height,e,n,o,r),s&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return xc.get("three")}get nature(){return uO}getObjectByRaycast(){return this._capability.getObjectByRaycast()}getObjectsByRaycast(){return this._capability.getObjectsByRaycast()}onchange(t,e){(t.hasOwnProperty("width")||t.hasOwnProperty("height"))&&this._capability.destroy(),this._capability.onchange(t)}onmousedown(t){this._capability.onMouseDown(t)}onmouseup(t){this._capability.onMouseUp(t)}onmousemove(t){this._capability.onMouseMove(t)}onmouseleave(t){this._capability.onMouseLeave(t)}onwheel(t){this._capability.onWheel(t)&&this.invalidate()}ondblclick(t){this._capability.onDblClick(t)&&this.invalidate()}ondragstart(t){this._capability.onDragStart(t)}ondragmove(t){this._capability.onDragMove(t)&&this.invalidate()}ondragend(t){this._capability.onDragEnd(t)&&this.invalidate()}ontouchstart(t){this._capability.onTouchStart(t)}onpan(t){this._capability.onPan(t)&&this.invalidate()}ontouchend(t){this._capability.onTouchEnd(t)}onkeydown(t){this._capability.onKeyDown(t)}onpinch(t){this._capability.onPinch(t)&&this.invalidate()}ondoubletap(){this._capability.onDoubleTap(),this.invalidate()}},t.ThreeContainer=ug([ov("3d-container")],t.ThreeContainer),df(t=>new jT(t));const fO=new Map;function mO(t){const e=function(t){const e=pO(t),n=t=>{let n=t>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")};return n(2166136261)+n(2538058380)}(t),n=`${e}|${Ix}`,s=fO.get(n);if(s)return fO.delete(n),fO.set(n,s),s;const i=structuredClone(t),o=new Map;for(const t of i.document.model.nodes)for(const e of Object.values(t.outputs))o.set(e,t.id);const r={key:n,fingerprint:e,kernel:Ix,compiled:qS(i),document:rS(i.document),looks:new Map(i.appearance.map(t=>[t.target,t])),writers:o,asset:i};return fO.set(n,r),fO.size>256&&fO.delete(fO.keys().next().value),r}let gO=null;function yO(t){gO=t}function bO(t,e=[],n,s){gO?.registerType?.(t,e,n,s)}const vO=$v,_O=new Map,xO=new Map,wO=new Set;function MO(t,e){if(!vO.includes(t.name)&&!Fv(t.name))throw new Error(`능력 이름 ${t.name} 은 공용 넷도, <이름공간>.<이름> 도 아니다`);const n={descriptor:t,...e?{mixin:e}:{}};xO.set(t.name,n),_O.clear();for(const t of[...wO])t();return()=>{if(xO.get(t.name)===n){xO.delete(t.name),_O.clear();for(const t of[...wO])t()}}}function SO(){return[...xO.values()].map(t=>t.descriptor).sort((t,e)=>Number(Fv(t.name))-Number(Fv(e.name)))}const AO=t=>xO.get(t)?.descriptor;function kO(t){return wO.add(t),()=>wO.delete(t)}MO({name:"Capacity",label:"Capacity",note:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",version:"1",needs:[]},t=>kk(t)),MO({name:"Holdable",label:"Holdable",note:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",version:"1",needs:[]},t=>NE(t)),MO({name:"Transferable",label:"Transferable",note:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",version:"1",needs:Object.entries(Hv).flatMap(([t,e])=>"Transferable"===t?[e]:[])},t=>BE(t)),MO({name:"FlowNode",label:"FlowNode",note:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다",version:"1",needs:[]},t=>GE(t));const EO=t=>xO.get(t).mixin;function TO(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:t.accepts?[...t.accepts]:[]}))}function CO(t,e){const n=[...new Set(t)],s=n.filter(t=>!vO.includes(t)&&!Fv(t));if(s.length>0)throw new Error(`모르는 능력이다: ${s.join(" · ")} — 쓸 수 있는 것은 ${vO.join(" · ")}, 또는 <이름공간>.<이름>`);const i=[];let o=n.filter(t=>!!vO.includes(t)||(!!xO.has(t)||(i.push({code:"CAPABILITY_UNREGISTERED",severity:"warning",name:t}),!1)));const r=t=>"item"===t?!!e?.item:o.includes(t);for(let t=!0;t;){t=!1;for(const e of o){const n=xO.get(e).descriptor.needs.filter(t=>Array.isArray(t)?!t.some(r):!r(t)).map(t=>Array.isArray(t)?t.join(" 이나 "):t);if(n.length){if(!Fv(e))throw new Error(`${e} 은 혼자 설 수 없다 — ${n.join(", ")} 가 함께 있어야 한다`);i.push({code:"CAPABILITY_NEEDS",severity:"warning",name:e,reasons:n}),o=o.filter(t=>t!==e),t=!0;break}}}return e&&(o=o.filter(t=>{const n=xO.get(t).descriptor,s=n.check?.(e.document.capabilities.extensions?.[t],e)??[];return!s.length||(i.push({code:"CAPABILITY_SETTINGS",severity:"warning",name:t,reasons:s}),!1)})),{names:o,issues:i}}function OO(t,e=[],n,s){const i=CO(e,s);for(const t of i.issues)console.warn(`[figure] ${t.code} ${t.name}${t.reasons?` — ${t.reasons.join(" · ")}`:""}`);const o=new Set(i.names),r=`${[...o].sort().join("+")}|${n??""}`,a=_O.get(r);if(a)return a;const c=[...o].filter(t=>Fv(t)),l=new Set([...o].filter(t=>!Fv(t))),h=0===l.size?t:(d=PO(function(t,e){if(e.has("FlowNode"))return EO("FlowNode")(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=EO(t)(n));return e.has("Holdable")&&(n=wv(n)),n}(t,l),l),class extends d{get _places(){const t=TP(this.state);return t?BA(t):null}get slots(){const t=this._places;return t?.length?TO(t):super.slots??[]}get effectiveLayout(){return CP(this.state)??super.effectiveLayout}get _itemsBound(){const t=BO(this.state?.type)?.compiled.asset;return!!t?.dataInterface?.bindings.some(t=>"table"!==t.rule&&"items"===t.behavior.kind)}_itemsFromData(){return!this._itemsBound&&(super._itemsFromData?.()??!0)}_keyedById(){return this._itemsBound||(super._keyedById?.()??!1)}_createItemFromRecord(t){if(!this._itemsBound)return super._createItemFromRecord(t);const e=this.slots.find(e=>e.id===t.slotId)?.allowedTypes??[],n=t.itemType??(1===e.length?e[0]:void 0);return new zv({...n?{type:n}:{},...t.itemState??{},id:t.itemId})}_syncItemsFromData(){if(!this._itemsBound||"function"!=typeof this._reconcileItems)return;const t=(this.figureInputs?.data?.items??[]).flatMap(t=>[...t.records].map((t,e)=>({r:t,i:e})).sort((t,e)=>(t.r.stack??t.i)-(e.r.stack??e.i)).map(({r:e})=>({slotId:e.place??t.slot??"",itemId:e.id,...e.type?{itemType:e.type}:{},itemState:{id:e.id,...void 0!==e.status?{status:e.status}:{}}})));this._reconcileItems(t)}onchange(t,e){super.onchange?.(t,e),"data"in t&&this._syncItemsFromData()}async ready(){await(super.ready?.()),this._syncItemsFromData()}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,s=e?.slotId??t?.[_v],i=this._places;return i&&s&&i.some(t=>t.id===s)?this._realObject?.placeAttachment?.(s,t)??n():n()}});var d;const u=c.length?PO(c.reduce((t,e)=>xO.get(e).mixin?.(t)??t,class extends h{}),o):h,p=void 0===n?u:function(t,e){const n=class extends t{};return Object.defineProperty(n,"placement",{value:e,enumerable:!0}),Object.defineProperty(n,"name",{value:`${t.name??"Figure"}·${e}`}),n}(u,n);return _O.set(r,p),p}function PO(t,e){const n=t.capabilities??[],s=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(s),configurable:!0}),t}function IO(t){return zO(t,t=>!!xO.get(t)?.mixin)}function DO(t){return zO(t,()=>!0)}function zO(t,e){const{names:n}=CO(t.document.capabilities.names??[],t),s=[];for(const i of n){const n=xO.get(i).descriptor.takes?.(t.document.capabilities.extensions?.[i],t);if(!n)continue;const o={...n,items:!!n.items&&e(i)},r=new Set(o.parts??[]),a=new Set(o.inputs??[]);for(const e of t.dataInterface?.bindings??[])if(!s.some(t=>t.id===e.id&&t.whole))if("table"===e.rule){const t=(e.targets.parts??[]).filter(t=>r.has(t)),n=(e.targets.inputs??[]).filter(t=>a.has(t));if(!t.length&&!n.length)continue;const o=!e.targets.group&&t.length===(e.targets.parts??[]).length&&n.length===(e.targets.inputs??[]).length;s.push({id:e.id,capability:i,whole:o,parts:t,inputs:n})}else("items"===e.behavior.kind&&o.items||"state"===e.behavior.kind&&a.has(e.behavior.input))&&s.push({id:e.id,capability:i,whole:!0,parts:[],inputs:"state"===e.behavior.kind?[e.behavior.input]:[]})}return s}function RO(t){const{names:e}=CO(t.document.capabilities.names??[],t),n=[];let s=function(t,e){if(!e.length||!t.dataInterface)return t;const n=t.dataInterface.bindings.flatMap(t=>{const n=e.filter(e=>e.id===t.id);if(!n.length)return[t];if("table"!==t.rule||n.some(t=>t.whole))return[];const s=(t.targets.parts??[]).filter(t=>!n.some(e=>e.parts.includes(t))),i=(t.targets.inputs??[]).filter(t=>!n.some(e=>e.inputs.includes(t)));if(!s.length&&!i.length&&!t.targets.group)return[];const o=Object.fromEntries(Object.entries(t.table).map(([t,e])=>{const{color:n,effect:o,values:r,...a}=e,c=r&&Object.fromEntries(Object.entries(r).filter(([t])=>i.includes(t)));return[t,{...a,...s.length?{...void 0!==n?{color:n}:{},...void 0!==o?{effect:o}:{}}:{},...c&&Object.keys(c).length?{values:c}:{}}]})),r={...s.length?{parts:s}:{},...i.length?{inputs:i}:{},...t.targets.group?{group:t.targets.group}:{}};return[{...t,targets:r,table:o}]});return{...t,dataInterface:{...t.dataInterface,bindings:n}}}(t,IO(t));for(const i of e){const e=xO.get(i).descriptor,o=e.dataInterface?.(t.document.capabilities.extensions?.[i],t);if(!o||!o.bindings.length&&!o.schema?.length)continue;const r=s.dataInterface??{version:"figure-data-interface-2",schema:[],bindings:[]},a=[...r.schema,...(o.schema??[]).filter(t=>!r.schema.some(e=>e.name===t.name))],c={...s,dataInterface:{...r,schema:a,bindings:[...r.bindings,...o.bindings]}};try{qS(c),s=c}catch(t){n.push({code:"CAPABILITY_SETTINGS",severity:"warning",name:i,reasons:[t instanceof Error?t.message:String(t)]})}}return{asset:s,issues:n}}function jO(){_O.clear()}const $O=new Map,LO=new Set;function FO(t){return LO.add(t),()=>LO.delete(t)}function NO(){for(const t of[...LO])t()}function HO(t,e){qS(e);const{asset:n,issues:s}=RO(e);for(const t of s)console.warn(`[figure] ${t.code} ${t.name} — ${t.reasons?.join(" · ")}`);const i={type:t,compiled:mO(n)};return $O.set(t,i),bO(t,n.document.capabilities.names??[],n.placement,n),NO(),i}function BO(t){return $O.get(t)??null}function GO(t){return $O.has(t)}function UO(t){const e=$O.delete(t);return e&&NO(),e}function VO(){$O.clear(),NO()}const WO=Math.cos(40*Math.PI/180);function YO(t){const[e,n]=Kv[t];return([s,i],o)=>{const r={x:0,y:0,z:0};return r[e]=s,r[n]=i,r[t]=o,new w.Vector3(r.x,r.y,r.z)}}class qO{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,s,i,o){for(const[r,a]of[[t,s],[e,i],[n,o]])this.positions.push(r.x,r.y,r.z),this.normals.push(a.x,a.y,a.z)}facing(t,e,n,s){(new w.Vector3).subVectors(e,t).cross((new w.Vector3).subVectors(n,t)).dot(s)<0?this.tri(t,n,e,s,s,s):this.tri(t,e,n,s,s,s)}geometry(){const t=new w.BufferGeometry;return t.setAttribute("position",new w.Float32BufferAttribute(this.positions,3)),t.setAttribute("normal",new w.Float32BufferAttribute(this.normals,3)),t}}function XO(t,e,n,s,i,o){const r=YO(n),a=e.length,c=e.map((t,n)=>{const s=e[(n+1)%a],i=s[0]-t[0],r=s[1]-t[1],c=Math.hypot(i,r)||1;return[o*r/c,-o*i/c]}),l=t=>r(t,0),h=(t,e)=>{const n=c[t],s=c[e];return n[0]*s[0]+n[1]*s[1]<WO?l(n):l([n[0]+s[0],n[1]+s[1]]).normalize()};for(let n=0;n<a;n++){const o=e[n],d=e[(n+1)%a],u=h(n,(n-1+a)%a),p=h(n,(n+1)%a),f=r(o,s),m=r(d,s),g=r(d,i),y=r(o,i),b=l(c[n]);(new w.Vector3).subVectors(m,f).cross((new w.Vector3).subVectors(g,f)).dot(b)>=0?(t.tri(f,m,g,u,p,p),t.tri(f,g,y,u,p,u)):(t.tri(f,g,m,u,p,p),t.tri(f,y,g,u,u,p))}}function KO(t,e,n,s,i,o){const r=YO(n),a=r([0,0],i),c=e.map(([t,e])=>new w.Vector2(t,e)),l=o?[o.map(([t,e])=>new w.Vector2(t,e))]:[],h=w.ShapeUtils.triangulateShape(c,l),d=[...e,...o??[]];for(const[e,n,i]of h)t.facing(r(d[e],s),r(d[n],s),r(d[i],s),a)}const JO=new Map;let QO=0,ZO=67108864;function tP(){return{entries:JO.size,bytes:QO,limit:ZO}}function eP(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),s=t.extrusion,i=t.cavity,o=t.revolution,r=t.loft,a=t.mesh,c=a?`${a.asset}:${a.node??"-"}:${["x","y","z"].map(t=>`${Math.round(1e6*a.bounds[t].min)/1e6}~${Math.round(1e6*a.bounds[t].max)/1e6}`).join(",")}`:s?`${s.axis}:${s.section.kind}:${i?`${"open"===i.start?"o":"c"}${"open"===i.end?"o":"c"}`:"-"}`:o?`${o.axis}:${o.profile.kind}`:r?`${r.axis}:point`:"";return`${t.provider}|${c}|${n}|s${e}|p1`}function nP(t,e=12,n=1/0){const s=eP(t,e),i=JO.get(s);if(i)return i.users++,i.geometry;const o=iP(t,e),r=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(o);if(QO+r>ZO||r>n)throw o.dispose(),new Error("figure: geometry bank budget exceeded");return o.userData.figureKey=s,JO.set(s,{geometry:o,users:1,bytes:r}),QO+=r,o}function sP(t){const e=t.userData.figureKey;if(!e)return;const n=JO.get(e);n&&--n.users<=0&&(JO.delete(e),QO-=n.bytes,n.geometry.dispose())}function iP(t,e=12){if("extrude"===t.provider&&t.extrusion)return function(t,e){const n=t.extrusion,s=QA(n.section,n.axis,e),i=new qO;XO(i,s,n.axis,n.start,n.end,1);const o=t.cavity,r=o&&c_(n.section,n.axis,o.wall);if(!o||!r||!("section"in r))return KO(i,s,n.axis,n.start,-1),KO(i,s,n.axis,n.end,1),i.geometry();const a=QA(r.section,n.axis,e,r.centre),c=n.start+("open"===o.start?0:o.start.closed),l=n.end-("open"===o.end?0:o.end.closed);return XO(i,a,n.axis,c,l,-1),"open"===o.start?KO(i,s,n.axis,n.start,-1,a):(KO(i,s,n.axis,n.start,-1),KO(i,a,n.axis,c,1)),"open"===o.end?KO(i,s,n.axis,n.end,1,a):(KO(i,s,n.axis,n.end,1),KO(i,a,n.axis,l,-1)),i.geometry()}(t,e);if("revolve"===t.provider&&t.revolution)return function(t,e){const n=t.profile;let s;return"half-ellipse"===n.kind?s=new w.SphereGeometry(1,e,Math.max(2,Math.round(e/2))).scale(n.radial,n.axial,n.radial):(s=new w.CylinderGeometry(n.endRadius,n.startRadius,n.end-n.start,e),s.translate(0,(n.start+n.end)/2,0)),"x"===t.axis&&s.rotateZ(-Math.PI/2),"z"===t.axis&&s.rotateX(Math.PI/2),s}(t.revolution,e);const n=t.loft;if("loft"===t.provider&&n)return function(t){const[e,n]=Kv[t.axis],s=YO(t.axis),i=QA(t.section,t.axis,0),o=s([t.apex[e],t.apex[n]],t.end),r=new qO;KO(r,i,t.axis,t.start,t.end>t.start?-1:1);const a=i.length;for(let e=0;e<a;e++){const n=s(i[e],t.start),c=s(i[(e+1)%a],t.start),l=(new w.Vector3).subVectors(c,n).cross((new w.Vector3).subVectors(o,n)).normalize();r.tri(n,c,o,l,l,l)}return r.geometry()}(n);const s=t.mesh;if("mesh"===t.provider&&s){const t=s.bounds,e=new w.BoxGeometry(t.x.max-t.x.min,t.y.max-t.y.min,t.z.max-t.z.min);return e.translate((t.x.min+t.x.max)/2,(t.y.min+t.y.max)/2,(t.z.min+t.z.max)/2),e}return new w.BufferGeometry}const oP=new Map;let rP=0,aP=0,cP=67108864;function lP(t,e=1/0){const n=(t=>t.map(t=>eP(t.shape,t.segments)).join(";"))(t),s=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const s=t.pose.r,i=t.pose.t;e.set([s[0][0],s[0][1],s[0][2],s[1][0],s[1][1],s[1][2],s[2][0],s[2][1],s[2][2],i[0],i[1],i[2]],12*n)}),e}(t),i=oP.get(n),o=i?.find(t=>function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(t.poses,s));if(o)return o.users++,o;const r=t.map(t=>nP(t.shape,t.segments));try{const o=r.map(t=>t.index?.count??t.getAttribute("position")?.count??0),a=o.reduce((t,e)=>t+e,0),c=6*a*4;if(c>e)throw new Error("figure: LOD transition budget exceeded");if(aP+c>cP)return null;const l=new Float32Array(3*a),h=new Float32Array(3*a),d=new Int32Array(t.length+1),u=new w.Matrix4,p=new w.Matrix3;let f=0;t.forEach((t,e)=>{d[e]=f/3;const{r:n,t:s}=t.pose;u.set(n[0][0],n[0][1],n[0][2],s[0],n[1][0],n[1][1],n[1][2],s[1],n[2][0],n[2][1],n[2][2],s[2],0,0,0,1),p.getNormalMatrix(u);const i=u.elements,a=p.elements,c=r[e].getAttribute("position"),m=r[e].getAttribute("normal"),g=r[e].index;for(let t=0;t<o[e];t++,f++){const e=g?g.getX(t):t,n=c.getX(e),s=c.getY(e),o=c.getZ(e);if(l[3*f]=i[0]*n+i[4]*s+i[8]*o+i[12],l[3*f+1]=i[1]*n+i[5]*s+i[9]*o+i[13],l[3*f+2]=i[2]*n+i[6]*s+i[10]*o+i[14],!m)continue;const r=m.getX(e),d=m.getY(e),u=m.getZ(e),p=a[0]*r+a[3]*d+a[6]*u,y=a[1]*r+a[4]*d+a[7]*u,b=a[2]*r+a[5]*d+a[8]*u,v=Math.hypot(p,y,b)||1;h[3*f]=p/v,h[3*f+1]=y/v,h[3*f+2]=b/v}}),d[t.length]=f/3;const m=new w.BufferGeometry;m.setAttribute("position",new w.BufferAttribute(l,3)),m.setAttribute("normal",new w.BufferAttribute(h,3)),m.computeBoundingSphere(),m.computeBoundingBox();const g={geometry:m,starts:d,users:1,bytes:c,poses:s};return m.userData.figureMergedKey=n,m.userData.figureMergedEntry=g,i?i.push(g):oP.set(n,[g]),rP++,aP+=c,g}finally{for(const t of r)sP(t)}}function hP(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,s=void 0===e?void 0:oP.get(e);!n||!s?.includes(n)||--n.users>0||(s.splice(s.indexOf(n),1),s.length||oP.delete(e),rP--,aP-=n.bytes,n.geometry.dispose())}function dP(){let t=0;for(const e of oP.values())for(const n of e)t+=n.users;return{entries:rP,users:t,bytes:aP,limit:cP}}let uP;function pP(t){uP=t}function fP(t){return uP?.(t)}async function mP(t,e=Nu.loadGLTF){const n=fP(t.asset);if(!n)return;let s,i;try{s=await e(n)}catch{return}if(void 0===t.node)i=s.scene.clone(!0);else{const e=function(t,e){let n;return t.scene.traverse(s=>{n||t.parser?.associations?.get(s)?.nodes!==e||(n=s)}),n}(s,t.node);if(!e)return;s.scene.updateMatrixWorld(!0);const n=new w.Vector3;e.matrixWorld.decompose(new w.Vector3,new w.Quaternion,n),i=e.clone(!0),i.position.set(0,0,0),i.quaternion.identity(),i.scale.copy(n)}const o=new w.Group;return o.name="figure-mesh-file",o.add(i),o.scale.setScalar(t.scale),o.traverse(t=>{t.raycast=()=>{}}),o}const gP=t=>1e-9*Math.round(t/1e-9)+0;class yP{static carrierJudgeOf(t){let e=yP.carrierJudges.get(t);return e||yP.carrierJudges.set(t,e=function(t,e){const n=e??rS(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))i.set(t,e);const o=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target)),r=t=>"string"==typeof t&&(n[t]?.length??0)>0,a=new Map,c=t=>{const e=a.get(t);if(void 0!==e)return e;const n=i.get(t),s="compose@1"!==n?.op||"string"!=typeof n.args[0]||r(n.args[1])?t:c(n.args[0]);return a.set(t,s),s};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||o.has(n.id))continue;const t=s.get(n.id),i="place@1"===t?.op?t.args[1]:void 0;"string"==typeof i&&r(i)&&!r(t.args[0])&&e.set(n.id,c(i))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=yP.stillJudges.get(t);return e||yP.stillJudges.set(t,e=WA(t.asset,t.document.dependence)),e}constructor(t,e={}){this._lodRevision=0,this._lodGeometryRevision=0,this.boundsAt=-1,this.semanticBounds=new w.Box3,this.group=new w.Group,this.meshes=new Map,this.batches=new Map,this.merged=new Map,this.carried=new Map,this.places=new Map,this.size=null,this.design={},this.designRefused=[],this.external={},this.clipTimes=new Map,this.groupRuns=new Map,this.dataStates={},this.commanded=new Map,this.paletteOverrides={},this.partColours={},this.flags=new Map,this.materials=new Map,this.dressed=new Map,this.drawnWith=new Map,this.lastDrawn=null,this.slots=[],this.generation=-1,this.files=new Map,this.clamped=[],this.partEffects=new Map,this.opacity=1,this.effectClock=0,this.blinkDark=!1,this.compiled=mO(t),this.own=YA(t),this.theme=e.theme??{},this.merge=!1!==e.merge,this._renderLevel=e.renderLevel??"full",this.onFileArrived=e.onFileArrived,this.group.name=`figure:${t.name}`}dressWithFile(t,e,n){const s=n.shape?.mesh,i=this.files.get(t);if(!s)return void(i&&this.undressFile(t,e,n));const o=`${s.asset}:${s.node??"-"}`;if(i?.key===o)return i.scale=s.scale,void i.object?.scale.setScalar(s.scale);i&&this.undressFile(t,e,n);const r={key:o,scale:s.scale};this.files.set(t,r),mP({asset:s.asset,...void 0!==s.node?{node:s.node}:{},scale:s.scale}).then(n=>{n&&this.files.get(t)===r&&this.meshes.get(t)===e&&(n.scale.setScalar(r.scale),r.object=n,e.add(n),e.material=yP.HIDDEN_BOX,this.onFileArrived?.())})}undressFile(t,e,n){const s=this.files.get(t);this.files.delete(t),s?.object&&s.object.parent?.remove(s.object),e&&n&&e.material===yP.HIDDEN_BOX&&(e.material=this.materialFor(n))}get asset(){return this.compiled.asset}get renderLevel(){return this._renderLevel}get lodRevision(){return this._lodRevision}get lodGeometryRevision(){return this._lodGeometryRevision}bodyMatrix(t,e,n){const s=this.slots[t];if(s&&"mesh"in s)return n.copy(s.mesh.matrix);if(s&&"entry"in s)return s.entry.set.mesh.getMatrixAt(s.index,n),n;if(s&&"rides"in s){const t=s.rides,i=12*t.ids.indexOf(e.id),o=t.relative;return n.set(o[i],o[i+1],o[i+2],o[i+9],o[i+3],o[i+4],o[i+5],o[i+10],o[i+6],o[i+7],o[i+8],o[i+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(yP.matrixOf(e.pose)):n.identity()}lodBounds(t){if(this.boundsAt!==this._lodRevision){this.semanticBounds.makeEmpty();const t=new w.Matrix4,e=new w.Box3;this.lastDrawn?.geometry.forEach((n,s)=>{if(!("shape"in n)||!("pose"in n)||!1===n.visible)return;let i=yP.shapeBounds.get(n.shape);if(!i){const t=B_(n.shape);i=new w.Box3(new w.Vector3(t.x.min,t.y.min,t.z.min),new w.Vector3(t.x.max,t.y.max,t.z.max)),yP.shapeBounds.set(n.shape,i)}this.semanticBounds.union(e.copy(i).applyMatrix4(this.bodyMatrix(s,n,t)))}),this.boundsAt=this._lodRevision}return t.copy(this.semanticBounds)}setRenderLevel(t){if(!["full","medium","coarse"].includes(t))throw new Error(`figure: unknown render level ${t}`);if(t===this._renderLevel)return!0;const e=this._renderLevel,n=this.lastDrawn;if(this.lastLodError=void 0,!n||n.geometry.every(n=>Yv(n,e)===Yv(n,t)))return this._renderLevel=t,!0;const s=new w.Matrix4,i=n.geometry.map((t,e)=>{if(!("pose"in t))return t;const n=this.bodyMatrix(e,t,s).elements;return{...t,pose:{r:[[n[0],n[4],n[8]],[n[1],n[5],n[9]],[n[2],n[6],n[10]]],t:[n[12],n[13],n[14]]}}}),o={...n,geometry:i},r=qv(o,t),a=[],c=[],l=tP().bytes+dP().bytes,h=()=>yP.LOD_TRANSITION_LIMIT_BYTES-(tP().bytes+dP().bytes-l);try{const t=new Set;for(const e of r.geometry){if(!("shape"in e))continue;const n=eP(e.shape,e.segments);t.has(n)||(t.add(n),a.push(nP(e.shape,e.segments,h())))}const e=KA(r.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf,own:this.own}:{own:this.own}),n=new Map(r.geometry.map(t=>[t.id,t]));for(const t of[...e.merged,...e.carried]){let e=t.ids.map(t=>n.get(t));if("carrier"in t){const t=(new w.Matrix4).copy(yP.matrixOf(e[0].pose)).invert(),n=new w.Matrix4;e=e.map(e=>{const s=n.multiplyMatrices(t,yP.matrixOf(e.pose)).elements,i=t=>gP(s[t]);return{...e,pose:{r:[[i(0),i(4),i(8)],[i(1),i(5),i(9)],[i(2),i(6),i(10)]],t:[i(12),i(13),i(14)]}}})}const s=lP(e,h());s&&c.push(s.geometry)}if(tP().bytes+dP().bytes-l>yP.LOD_TRANSITION_LIMIT_BYTES)throw new Error("figure: LOD transition budget exceeded")}catch(t){this.lastLodError=t instanceof Error?t.message:String(t);for(const t of c)hP(t);for(const t of a)sP(t);return!1}try{return this._renderLevel=t,this.draw(o,this.generation),!0}finally{for(const t of c)hP(t);for(const t of a)sP(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(Vv.x)&&e(Vv.y)&&e(Vv.z)?{x:t[Vv.x],y:t[Vv.y],z:t[Vv.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const s of["x","y","z"]){const i=e.find(t=>t.id===Vv[s]);if(!i)continue;const o=t[s],r=Math.min(Math.max(o,i.min??-1/0),i.max??1/0);r!==o&&this.clamped.push({axis:s,asked:o,used:r,bound:r>o?"min":"max"}),n[s]=r}this.size=n}get drawnSize(){return this.size?{...this.size}:null}setDesignInputs(t){const e=[],n=new Set((this.asset.publicInputs??[]).map(t=>t.input)),s=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),i={};for(const[o,r]of Object.entries(t??{})){const t=s.get(o);let a;n.has(o)&&t?"number"==typeof r&&Number.isFinite(r)?(r<t.min||r>t.max)&&(a=`outside ${t.min}…${t.max}`):a="not a number":a="not an input the figure lets a board set",a?(e.push({input:o,value:r,reason:a}),o in this.design&&(i[o]=this.design[o])):i[o]=r}try{this.compiled.document.evaluate({...this.evaluationInputs(),...i}),this.design=i}catch(t){for(const[n,s]of Object.entries(i))e.push({input:n,value:s,reason:t instanceof Error?t.message:String(t)})}this.designRefused=e}get designValues(){return{...this.design}}setState(t){this.external={...t}}static clipOf(t){return t.clip}get clips(){return[...new Set((this.asset.drivers??[]).map(t=>yP.clipOf(t)))]}get motionPlan(){return this.motionPlanOf??=zS(this.asset)}get independentClips(){return this.motionPlan.independentClips}setMotionSettings(t){const e=this.motionPlan;let n;for(const[s,{group:i}]of e.groups){const o=t[s]??{clip:i.defaultClip,speed:0,paused:!1},r=this.groupRuns.get(s);r?(r.clip!==o.clip&&(n??=this.drivenValues(),r.from=Object.fromEntries(e.groups.get(s).states.map(t=>[t,n[t]])),r.clip=o.clip,r.time=0,r.elapsed=0),r.speed=o.speed,r.paused=o.paused):this.groupRuns.set(s,{clip:o.clip,time:0,speed:o.speed,paused:o.paused,elapsed:0})}}restartMotion(t){const e=this.groupRuns.get(t);if(!e)return!1;const n=this.drivenValues();return e.from=Object.fromEntries(this.motionPlan.groups.get(t).states.map(t=>[t,n[t]])),e.time=0,e.elapsed=0,!0}get motionRuns(){return Object.fromEntries([...this.groupRuns].map(([t,e])=>[t,{clip:e.clip,time:e.time,speed:e.speed,paused:e.paused,blending:!!e.from}]))}setDataStates(t){let e;for(const[n,{sourceMode:s}]of Object.entries(t))"commanded"!==s||this.commanded.has(n)||(e??={...this.asset.stateDefaults,...this.stateOverrides()},this.commanded.set(n,e[n]));for(const e of[...this.commanded.keys()])"commanded"!==t[e]?.sourceMode&&this.commanded.delete(e);this.dataStates={...t}}advance(t){if(!(t>0))return!1;let e=!1;for(const[n,s]of this.groupRuns)!s.paused&&s.speed>0&&(s.time+=t*s.speed,s.from&&(s.elapsed+=t,s.elapsed>=this.motionPlan.groups.get(n).group.transitionSeconds&&(s.from=void 0)),e=!0);if(this.advanceEffects(t)&&(e=!0),this.commanded.size){const n=new Map(this.asset.document.model.inputs.map(t=>[t.id,t]));for(const[s,i]of this.commanded){const o=this.dataStates[s]?.value;if(void 0===o||i===o)continue;const r=n.get(s);this.commanded.set(s,VS(i,o,{min:r.min,max:r.max,sweep:this.asset.stateInputs?.[s]?.sweep},t)),e=!0}}return e}get moving(){for(const t of this.groupRuns.values())if(!t.paused&&t.speed>0)return!0;for(const t of this.partEffects.values())if("blink"===t.kind)return!0;for(const[t,e]of this.commanded)if(this.dataStates[t]&&this.dataStates[t].value!==e)return!0;return!1}drivenValues(){const t=this.motionPlan;if(!t.clips.size)return{};const e={},n={};for(const e of t.independentClips)n[e]=this.clipTime(e);for(const[s,{group:i}]of t.groups){const t=this.groupRuns.get(s);e[s]=t?.clip??i.defaultClip,n[e[s]]=t?.time??0}const s={...$S(t,e,n)};for(const[e,{group:n,states:i}]of t.groups){const o=this.groupRuns.get(e);if(!o?.from)continue;const r=n.transitionSeconds>0?Math.min(1,o.elapsed/n.transitionSeconds):1,a=Object.fromEntries(i.map(t=>[t,s[t]]));Object.assign(s,LS(t,o.from,a,r))}return s}setPaletteOverrides(t){const e={...t},n=Object.keys(e).length===Object.keys(this.paletteOverrides).length&&Object.entries(e).every(([t,e])=>this.paletteOverrides[t]===e);n||(this.paletteOverrides=e,this.repaint())}setPartColours(t){const e={...t},n=Object.keys(e).length===Object.keys(this.partColours).length&&Object.entries(e).every(([t,e])=>this.partColours[t]===e);n||(this.partColours=e,this.repaint())}setPartEffects(t){const e=new Map;for(const[n,s]of Object.entries(t))!s||"blink"!==s.kind&&"glow"!==s.kind||e.set(n,{kind:s.kind,hz:s.hz&&s.hz>0?s.hz:1});const n=e.size===this.partEffects.size&&[...e].every(([t,e])=>this.partEffects.get(t)?.kind===e.kind&&this.partEffects.get(t)?.hz===e.hz);n||(this.partEffects=e,this.repaint())}setOpacity(t){const e=Number.isFinite(t)&&t>0&&t<1?t:1;e!==this.opacity&&(this.opacity=e,this.repaint())}partOf(t){return t.key?this.compiled.writers.get(t.key):t.id}advanceEffects(t){const e=[...this.partEffects.values()].find(t=>"blink"===t.kind);if(!e)return!1;this.effectClock+=t;const n=this.effectClock*e.hz%1>=.5;return n!==this.blinkDark&&(this.blinkDark=n,this.repaint(),!0)}get palette(){return{...this.asset.palette,...this.paletteOverrides}}repaint(){const t=new Map((this.lastDrawn?.geometry??[]).map(t=>[t.id,t]));for(const[e,n]of this.meshes){const s=t.get(e);s&&n.material!==yP.HIDDEN_BOX&&(n.material=this.materialFor(s))}for(const e of this.batches.values()){const n=t.get(e.ids[0]);n&&(e.set.material=this.materialFor(n))}for(const e of[...this.merged.values(),...this.carried.values()]){const n=t.get(e.ids[0]);n&&(e.mesh.material=this.materialFor(n))}this.lastDrawn&&(this.lastDrawn={...this.lastDrawn,palette:this.palette})}setClipTime(t,e){this.clipTimes.set(t,e)}clipTime(t){return this.clipTimes.get(t)??0}setTime(t){for(const e of this.clips)this.clipTimes.set(e,t)}stateOverrides(){const{states:t}=this.inputsRead(),e=this.drivenValues();for(const[n,{value:s,sourceMode:i}]of Object.entries(this.dataStates))t.has(n)&&(e[n]="commanded"===i?this.commanded.get(n)??s:s);for(const[n,s]of Object.entries(this.external))t.has(n)&&(e[n]=s);return e}inputsRead(){const t=this.asset.document.model.inputs;return this.inputFacts??={units:new Map(t.map(t=>[t.id,t.unit])),states:new Set(t.filter(t=>"state"===t.role).map(t=>t.id))}}get externalState(){return{...this.external}}update(){const t=this.evaluationInputs();this.evaluator??=this.compiled.document.evaluator({changes:!0});const e=this.evaluator.advance(t),n=this.carried.size>0&&this.carriedAt!==this.designKey();if("poses"===e.kind&&e.generation===this.generation&&!n&&!this.movesMerged(e.bodies))return this.movePoses(e);const s="changes"===e.kind?this.fromChanges(e,t):null;this.draw(s??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const s=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||s.has(n)||!t.structure&&!t.changed(n))continue;const i=!0===t.read(n);this.flags.get(n)!==i&&s.add(n),this.flags.set(n,i)}const i=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),o=new Int32Array(i.length).fill(-1);for(let e=0;e<t.bodies.length;e++){if(!t.shapes[e])return null;o[t.bodies[e]]=e}for(let e=0;e<i.length;e++){const n=o[e],r=i[e];if(n<0&&!(r&&s.size&&void 0!==this.flagOf(r)&&s.has(this.flagOf(r))))continue;const a=t.structure?t.structure.ids[e]:r.id,c=t.structure?t.structure.keys[e]:r.key,l={id:a},h=t.structure?t.structure.paths[e]:r.path;void 0!==h&&(l.path=h),void 0!==c&&(l.key=c);const d=t.structure?t.structure.indexes[e]:r.index;if(void 0!==d&&(l.index=d),n>=0){const e=t.poses,s=12*n;l.shape=t.shapes[n],l.pose={r:[[e[s],e[s+1],e[s+2]],[e[s+3],e[s+4],e[s+5]],[e[s+6],e[s+7],e[s+8]]],t:[e[s+9],e[s+10],e[s+11]]}}else l.shape=r.shape,l.pose=r.pose;i[e]=this.dressBody(l)}const r=new Map((t.structure?[]:n.bindings).map(t=>[t.id,t]));for(const e of t.places)r.set(e.id,e);return{geometry:i,bindings:[...r.values()],inputs:e,palette:this.palette}}flagOf(t){return this.compiled.looks.get(t.key?this.compiled.writers.get(t.key):t.id)?.visibility}dressBody(t){return this.dressOne(t,t=>!0===this.flags.get(t)).dressed}dressOne(t,e){const n=t.key?this.compiled.writers.get(t.key):t.id,s=this.compiled.looks.get(n);if(!s)throw new Error(`figure: no appearance for ${n}`);const i=void 0===s.visibility||e(s.visibility);let o=this.materials.get(n);o||this.materials.set(n,o=structuredClone(s.material));const r={...t,material:o,visible:i};return void 0!==s.segments&&(r.segments=s.segments),{dressed:r,visible:i,ref:s.visibility}}evaluation(){return this.evaluate()}movesMerged(t){if(!this.merged.size)return!1;for(let e=0;e<t.length;e++){const n=this.slots[t[e]];if(n&&"merged"in n)return!0}return!1}movePoses(t){t.bodies.length&&this._lodRevision++;const e=yP.matrix,n=new Set;for(let s=0;s<t.bodies.length;s++){const i=this.slots[t.bodies[s]];if(!i)continue;const o=t.poses,r=12*s;if(e.set(o[r],o[r+1],o[r+2],o[r+9],o[r+3],o[r+4],o[r+5],o[r+10],o[r+6],o[r+7],o[r+8],o[r+11],0,0,0,1),!("merged"in i)&&!("rides"in i))if("mesh"in i){i.mesh.matrix.copy(e),i.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(i.id);t&&(t.pose=void 0)}else i.entry.set.setMatrix(i.index,e),n.add(i.entry)}for(const t of this.batches.values())n.has(t)?(t.settled=!1,t.set.commitMatrices(),t.set.mesh.boundingSphere=null,t.set.mesh.frustumCulled=!1):t.settled||(t.set.commit(),t.set.mesh.frustumCulled=!0,t.settled=!0);for(const e of t.places){const t=this.places.get(e.id);t&&yP.pose(t,e.pose)}}draw(t,e){this.lastDrawn=t,this._lodRevision++,this._lodGeometryRevision++,t=qv(t,this._renderLevel);const n=this.planOf(t.geometry),s=new Map(t.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),i=this.drawCarried(n,s,this.drawMerged(n,s)),o=new Set;for(const t of i){const e=s.get(t);if(!("pose"in e))continue;o.add(t);let n=this.meshes.get(t);const i=!1!==e.visible,r=this.drawnWith.get(t);if(!n||!r||r.shape!==e.shape||r.segments!==e.segments){const s=nP(e.shape,e.segments);n?n.geometry!==s?(sP(n.geometry),n.geometry=s):sP(s):(n=new w.Mesh(s,this.materialFor(e)),n.name=t,n.matrixAutoUpdate=!1,this.meshes.set(t,n),i&&this.group.add(n))}r&&r.pose===e.pose||yP.pose(n,e.pose),this.dressWithFile(t,n,e),this.drawnWith.set(t,{shape:e.shape,segments:e.segments,pose:e.pose}),n.castShadow=i,i&&n.parent!==this.group?this.group.add(n):i||n.parent!==this.group||this.group.remove(n)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),this.undressFile(t,void 0),sP(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const r=new Set;for(const t of n.batches){r.add(t.key);const e=s.get(t.ids[0]);if(!("pose"in e))continue;let n=this.batches.get(t.key);if(!n){const s=nP(e.shape,e.segments);n={set:new sO({geometry:s,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:s},this.batches.set(t.key,n)}const{set:i}=n,o=i.count!==t.ids.length;i.setCount(t.ids.length);const a=i.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=s.get(t);if(!("pose"in n))return;yP.matrixOf(n.pose);const o=yP.matrix.elements;for(let t=0;t<16&&!c;t++)a[16*e+t]!==Math.fround(o[t])&&(c=!0);i.setMatrix(e,yP.matrix)}),n.ids=t.ids,o||!c&&!n.settled?(i.commit(),i.mesh.frustumCulled=!0,n.settled=!0):c&&(n.settled=!1,i.commitMatrices(),i.mesh.boundingSphere=null,i.mesh.frustumCulled=!1);const l=!1!==e.visible;l&&i.object3d.parent!==this.group?this.group.add(i.object3d):l||i.object3d.parent!==this.group||this.group.remove(i.object3d)}for(const[t,e]of this.batches)r.has(t)||(e.set.object3d.parent===this.group&&this.group.remove(e.set.object3d),e.set.dispose(),sP(e.geometry),this.batches.delete(t));for(const e of t.bindings){const t=this.places.get(e.id);t&&yP.pose(t,e.pose)}const a=new Map;for(const t of this.batches.values())t.ids.forEach((e,n)=>a.set(e,{entry:t,index:n}));for(const t of this.merged.values())for(const e of t.ids)a.set(e,{merged:t});const c=new Map;for(const t of this.carried.values())t.ids.forEach((e,n)=>0===n?c.set(e,t.mesh):a.set(e,{rides:t}));this.slots=t.geometry.map(t=>{const e=this.meshes.get(t.id)??c.get(t.id);return e?{mesh:e,id:t.id}:a.get(t.id)??null}),this.generation=e}drawMerged(t,e){const n=[...t.alone],s=new Set;for(const i of t.merged){const t=i.ids.map(t=>e.get(t));let o=this.merged.get(i.key);const r=o&&o.ids.length===t.length&&t.every((t,e)=>t.id===o.ids[e]&&t.shape===o.made[e].shape&&t.segments===o.made[e].segments&&t.pose===o.made[e].pose);if(!r){const e=lP(t.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!e){n.push(...i.ids);continue}if(o)hP(o.mesh.geometry),o.mesh.geometry=e.geometry,o.ids=i.ids,o.starts=e.starts;else{const n=new w.Mesh(e.geometry,this.materialFor(t[0]));n.name=`figure-merged:${this.merged.size}`,n.matrixAutoUpdate=!1,n.castShadow=!0,o={mesh:n,ids:i.ids,starts:e.starts,made:[]},this.merged.set(i.key,o)}o.made=t.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose}))}s.add(i.key);const a=!1!==t[0].visible;a&&o.mesh.parent!==this.group?this.group.add(o.mesh):a||o.mesh.parent!==this.group||this.group.remove(o.mesh)}for(const[t,e]of this.merged)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),hP(e.mesh.geometry),this.merged.delete(t));return n}drawCarried(t,e,n){const s=new Set,i=new w.Matrix4,o=new w.Matrix4;for(const r of t.carried){const t=r.ids.map(t=>e.get(t));i.copy(yP.matrixOf(t[0].pose)).invert();const a=t.map(t=>{const e=o.multiplyMatrices(i,yP.matrixOf(t.pose)).elements,n=t=>gP(e[t]);return{r:[[n(0),n(4),n(8)],[n(1),n(5),n(9)],[n(2),n(6),n(10)]],t:[n(12),n(13),n(14)]}}),c=new Float64Array(a.flatMap(t=>[...t.r.flat(),...t.t]));let l=this.carried.get(r.key);const h=l&&l.ids.length===t.length&&t.every((t,e)=>t.id===l.ids[e]&&t.shape===l.made[e].shape&&t.segments===l.made[e].segments)&&c.every((t,e)=>t===l.relative[e]);if(!h){const e=lP(t.map((t,e)=>({shape:t.shape,segments:t.segments,pose:a[e]})));if(!e){n.push(...r.ids);continue}if(l)hP(l.mesh.geometry),l.mesh.geometry=e.geometry,l.ids=r.ids,l.starts=e.starts;else{const n=new w.Mesh(e.geometry,this.materialFor(t[0]));n.name=`figure-carried:${this.carried.size}`,n.matrixAutoUpdate=!1,n.castShadow=!0,l={mesh:n,ids:r.ids,starts:e.starts,made:[],relative:c},this.carried.set(r.key,l)}l.made=t.map(t=>({shape:t.shape,segments:t.segments})),l.relative=c}yP.pose(l.mesh,t[0].pose),s.add(r.key);const d=!1!==t[0].visible;d&&l.mesh.parent!==this.group?this.group.add(l.mesh):d||l.mesh.parent!==this.group||this.group.remove(l.mesh)}for(const[t,e]of this.carried)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),hP(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),n}designKey(){const t=this.size;let e=t?`${t.x},${t.y},${t.z}`:"-";for(const t in this.design)e+=`|${t}=${this.design[t]}`;return e}placeNode(t){let e=this.places.get(t);if(e)return e;if(!BA(this.asset).some(e=>e.id===t))return null;e=new w.Object3D,e.name=`place:${t}`,e.matrixAutoUpdate=!1,this.places.set(t,e),this.group.add(e);const n=this.evaluator&&this.lastDrawn?this.placeNow(t):this.evaluation().bindings.find(e=>e.id===t);return n&&yP.pose(e,n.pose),e}placeNow(t){try{return this.evaluator.place(t)}catch(e){if("NOT_BOUND"!==e.code)throw e;return this.evaluation().bindings.find(e=>e.id===t)}}static pose(t,e){t.matrix.copy(yP.matrixOf(e)),t.matrixWorldNeedsUpdate=!0}planOf(t){const e=this.planned,n=t.filter(t=>"pose"in t);if(e&&e.ids.length===n.length&&n.every((t,n)=>t.id===e.ids[n]&&t.shape===e.shapes[n]&&t.segments===e.segments[n]&&!1!==t.visible===e.shown[n]))return e.plan;const s=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===s.length&&s.every((t,n)=>t===e.ids[n])||(this.stillOf=yP.stillJudgeOf(this.compiled)(t),this.carriedOf=yP.carrierJudgeOf(this.compiled)(t));const i=this.merge?this.stillOf:void 0,o=KA(t,i?{still:i,carried:this.carriedOf,own:this.own}:{own:this.own});return this.planned={ids:s,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:o,still:i},o}static matrixOf(t){const e=t.r,n=t.t;return yP.matrix.set(e[0][0],e[0][1],e[0][2],n[0],e[1][0],e[1][1],e[1][2],n[1],e[2][0],e[2][1],e[2][2],n[2],0,0,0,1)}bodyAt(t,e,n){if(t.isMesh&&this.meshes.get(t.name)===t)return t.name;for(const n of this.batches.values())if(n.set.mesh===t&&void 0!==e){const t=n.set.indexOf(e);return t>=0?n.ids[t]:void 0}for(const e of[...this.merged.values(),...this.carried.values()]){if(e.mesh!==t||void 0===n)continue;const{starts:s}=e;if(n<0||n>=s[s.length-1])return;let i=0,o=e.ids.length-1;for(;i<o;){const t=i+o+1>>1;s[t]<=n?i=t:o=t-1}return e.ids[i]}}drawOf(t){const e=this.meshes.get(t);if(e)return e.parent===this.group?{kind:"alone",object:e}:void 0;for(const e of this.batches.values()){const n=e.ids.indexOf(t);if(n>=0)return e.set.object3d.parent===this.group?{kind:"copy",object:e.set.mesh,index:n}:void 0}for(const e of this.merged.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"merged",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}for(const e of this.carried.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"carried",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}}get draws(){let t=0;for(const e of this.batches.values())e.set.object3d.parent===this.group&&(t+=e.set.count);return{batches:[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).length,merged:[...this.merged.values()].filter(t=>t.mesh.parent===this.group).length,carried:[...this.carried.values()].filter(t=>t.mesh.parent===this.group).length,alone:[...this.meshes.values()].filter(t=>t.parent===this.group).length,instances:t}}evaluationInputs(){const t={...this.asset.designInputs,...this.design,...this.asset.stateDefaults,...this.stateOverrides()};return this.size&&(t[Vv.x]=this.size.x,t[Vv.y]=this.size.y,t[Vv.z]=this.size.z),t}evaluate(){const t=this.evaluationInputs();return this.evaluator??=this.compiled.document.evaluator({changes:!0}),this.dress(this.evaluator.evaluate(t),t)}evaluateOnce(){const t=this.evaluationInputs(),e=this.compiled.document.evaluate(t),n=e.values,s=e.geometry.map(t=>this.dressOne(t,t=>!0===n[t]).dressed);return{geometry:s,bindings:e.bindings,inputs:t,palette:this.palette}}dress(t,e){const n=this.dressed,s=new Map,i=t.geometry.map(e=>{const i=n.get(e.id),o=this.dressOne(e,e=>!0===t.values[e]);return void 0!==o.ref&&this.flags.set(o.ref,o.visible),i&&i.body===e&&i.visible===o.visible?(s.set(e.id,i),i.dressed):(s.set(e.id,{body:e,visible:o.visible,dressed:o.dressed}),o.dressed)});return this.dressed=s,{geometry:i,bindings:t.bindings,inputs:e,palette:this.palette}}colourOf(t){return this.paletteOverrides[t]??this.theme[t]??this.asset.palette[t]??"#9a9a9a"}materialFor(t){const e=t.material,n=Fd[e.preset??"default"]??Fd.default,s=this.partOf(t),i=this.partEffects.get(s),o=!!e.emissive?.on||"glow"===i?.kind,r=o&&e.emissive?this.colourOf(e.emissive.token):this.partColours[s]??this.colourOf(e.token),a="blink"===i?.kind&&this.blinkDark?function(t){const e=/^#([0-9a-f]{6})$/i.exec(t);if(!e)return"#202020";const n=parseInt(e[1],16),s=t=>Math.round(.25*(n>>t&255)).toString(16).padStart(2,"0");return`#${s(16)}${s(8)}${s(0)}`}(r):r,c="glow"===i?.kind?.8:o&&e.emissive?e.emissive.intensity:0,l=(e.transparent?n.opacity??.3:1)*this.opacity,h=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${l}|${o?"on":"off"}|${a}|${c}`;return NT.material(h,{color:a,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:(e.transparent??!1)||l<1,opacity:l,emissive:a,emissiveIntensity:c})}meshOf(t){return this.meshes.get(t)}drawnIds(){const t=[...this.meshes.values()].filter(t=>t.parent===this.group).map(t=>t.name),e=[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).flatMap(t=>t.ids),n=[...this.merged.values(),...this.carried.values()].filter(t=>t.mesh.parent===this.group).flatMap(t=>t.ids);return[...t,...e,...n]}dispose(){for(const t of this.meshes.values())t.parent===this.group&&this.group.remove(t),sP(t.geometry);this.meshes.clear();for(const t of[...this.files.keys()])this.undressFile(t,void 0);this.drawnWith.clear(),this.dressed.clear();for(const t of this.batches.values())t.set.object3d.parent===this.group&&this.group.remove(t.set.object3d),t.set.dispose(),sP(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),hP(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),hP(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}yP.shapeBounds=new WeakMap,yP.LOD_TRANSITION_LIMIT_BYTES=16777216,yP.matrix=new w.Matrix4,yP.carrierJudges=new WeakMap,yP.stillJudges=new WeakMap,yP.HIDDEN_BOX=new w.MeshBasicMaterial({visible:!1});const bP=["x","y","z"],vP=new WeakMap;function _P(t){let e=vP.get(t);return e||vP.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,s=bP.every(t=>"number"==typeof n[Vv[t]]&&e.some(e=>e.id===Vv[t])),i={};if(s)for(const t of bP){const n=e.find(e=>e.id===Vv[t]);i[t]={min:n.min??0,max:n.max??1/0}}const o=e=>{const n=function(t,e={}){const n=Object.keys(e).length?{...t,designInputs:{...t.designInputs,...e}}:t,s=nA(qS(n).evaluate().geometry,sA(n));return Object.fromEntries(jv.map(t=>[t,s.length?{min:iA(Math.min(...s.map(e=>e.centre[t]-e.extent[t]/2))),max:iA(Math.max(...s.map(e=>e.centre[t]+e.extent[t]/2)))}:{min:0,max:0}]))}(t,e?kP(e):{});return{box:{x:Math.max(n.x.max-n.x.min,1e-6),y:Math.max(n.y.max-n.y.min,1e-6),z:Math.max(n.z.max-n.z.min,1e-6)},centre:{x:(n.x.min+n.x.max)/2,y:(n.y.min+n.y.max)/2,z:(n.z.min+n.z.max)/2}}},r=s?{x:n[Vv.x],y:n[Vv.y],z:n[Vv.z]}:null,a=!s||"uniform"===t.sizing,c=o(r),l={};if(r&&a){const t=Math.min(2,...bP.map(t=>i[t].max/r[t])),e=Math.max(.5,...bP.map(t=>i[t].min/r[t])),n=t>1?t:e<1?e:1;if(1!==n){const t=o({x:r.x*n,y:r.y*n,z:r.z*n}).box;for(const e of bP)l[e]=(t[e]-c.box[e])/(r[e]*(n-1))}}else if(r)for(const t of bP){const{min:e,max:n}=i[t],s=r[t],a=n>s?Math.min(n,2*s):e<s?Math.max(e,s/2):s;if(a===s)continue;const h=o({...r,[t]:a}).box;l[t]=(h[t]-c.box[t])/(a-s)}const h=(t,e)=>{if(!r)return e;const n=l[t]??0;return Math.abs(n)>1e-9?r[t]+(e-c.box[t])/n:r[t]};return{evaluated:s,proportional:a,limits:i,authoredInputs:r,authored:c,bodyAt:o,inputFor:h}}(t)),e}function xP(t){return _P(t).proportional}function wP(t){return{..._P(t).authored.box}}function MP(t,e){const n=t.bounds?.width??Number(t.state.width??0),s=t.bounds?.height??Number(t.state.height??0),i=SP(t),o=rh(t).mmPerUnit;return AP(e,{x:n*o,z:s*o,y:void 0===i?void 0:i*o})}function SP(t){const e=t=>"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0;return e(t.state.depth)??e(t.effectiveDepth)}function AP(t,e,n=[]){const s=_P(t),i=n.find(t=>void 0!==e[t])??"x",o=(t,e)=>{const n=s.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!s.evaluated){const t=Math.max(e[i]/s.authored.box[i],1e-6),n=e=>({x:e.x*t,y:e.y*t,z:e.z*t});return{inputs:null,scale:t,box:n(s.authored.box),centre:n(s.authored.centre)}}const r=s.authoredInputs;let a;if(s.proportional){let t=Math.max(s.inputFor(i,e[i])/r[i],1e-6);for(const e of bP){const n=s.limits[e];n&&(t=Math.min(Math.max(t,n.min/r[e]),n.max/r[e]))}a={x:r.x*t,y:r.y*t,z:r.z*t}}else a={x:o("x",s.inputFor("x",e.x)),y:o("y",void 0!==e.y?s.inputFor("y",e.y):r.y),z:o("z",s.inputFor("z",e.z))};return{inputs:a,scale:1,...s.bodyAt(a)}}const kP=t=>Object.fromEntries(bP.map(e=>[Vv[e],t[e]])),EP=new WeakMap;function TP(t){const e=BO(String(t?.type??""));if(!e)return null;const n=t?.slotLayout;return null==n?e.compiled.asset:mO(uk(e.compiled.asset,n).asset).asset}function CP(t){const e=BO(String(t?.type??""));return e?uk(e.compiled.asset,t?.slotLayout).effective:null}const OP={single:"Single slot",agvTandem:"AGV tandem (front/rear)",agvParallel:"AGV parallel (left/right)",agv2x2:"AGV 2×2",bufferPort2x2:"Buffer port 2×2",multiBufferPort:"Multi-buffer port (4)",dualTierConveyor:"Dual-tier conveyor",craneTwinFork:"Crane twin fork",floorBlock:"Floor block"},PP={upperElevation:"Upper tier elevation (mm)",rows:"Rows",cols:"Columns",stackLimit:"Stack limit"},IP=t=>Math.round(1e3*t)/1e3;function DP(t,e){const n={};for(const s of t){const t=e.find(t=>t.id===s.part);if(!t?.shape)continue;const i=B_(t.shape);n[s.id]={width:IP(i.x.max-i.x.min),depth:IP(i.z.max-i.z.min)}}return n}function zP(t,e){const n=new Map(e.filter(t=>t.shape).map(t=>[t.id,RP(t)]));if(!n.size)return{};const s=Math.max(...[...n.values()].map(t=>t.max)),i=Math.min(...[...n.values()].map(t=>t.min)),o={};for(const e of t){const t=e.part?n.get(e.part):void 0;t&&(o[e.id]=IP(Math.max(0,"bottom"===e.face?t.min-i:s-t.max)))}return o}function RP(t){const e=B_(t.shape),n=[(e.x.min+e.x.max)/2,(e.y.min+e.y.max)/2,(e.z.min+e.z.max)/2],s=[(e.x.max-e.x.min)/2,(e.y.max-e.y.min)/2,(e.z.max-e.z.min)/2],i=t.pose?.r?.[1]??[0,1,0],o=(t.pose?.t?.[1]??0)+i[0]*n[0]+i[1]*n[1]+i[2]*n[2],r=Math.abs(i[0])*s[0]+Math.abs(i[1])*s[1]+Math.abs(i[2])*s[2];return{min:o-r,max:o+r}}function jP(t){const e=t?.state,n=BO(String(e?.type??"")),s=n?.compiled.asset.document.capabilities.slotLayout;if(!s)return;const i=s.anchors.map(t=>t.id),o=uk(n.compiled.asset,e?.slotLayout).effective,r={anchor:i[0],...i.length>=2?{forks:[i[0],i[1]]}:{}},a=function(t,e){const n=HA(e)?.anchors??[];try{const s=new yP(e);s.setSize(MP(t,e).inputs);const i=t.state.designInputs;return i&&"object"==typeof i&&s.setDesignInputs(i),DP(n,s.evaluateOnce().geometry)}catch{return{}}}(t,n.compiled.asset),c=Wl(t),l=t._items??[];return{effective:s.layout,canUseDefault:null!=e?.slotLayout,live:!0,unit:"mm",anchors:(HA(n.compiled.asset)?.anchors??s.anchors).map(t=>({id:t.id,..."part"in t&&t.part?{part:t.part,face:t.face}:{}})),anchorFaces:a,presetSize:a[i[0]??""]??{},validate:t=>hk(t,i),...c?{itemTypes:[...c.types.values()].map(t=>({code:t.code,name:t.name}))}:{},items:l.map(e=>({id:String(e.state?.id??""),slot:e[_v],code:e.state?.type,type:t.itemTypeOf?t.itemTypeOf(e):e.state?.type??null,dims:t.itemDimsOf?.(e)??null})),presets:lk.map(t=>({key:t,label:OP[t],params:ck[t].map(t=>({key:t.key,label:PP[t.key]??t.key,integer:t.integer})),build:(e,n)=>function(t,e,n={},s={}){const i=ak,o={single:()=>i.single(s.mount??"ON",e,void 0,s),agvTandem:()=>i.agvTandem(e,void 0,s),agvParallel:()=>i.agvParallel(e,void 0,s),agv2x2:()=>i.agv2x2(e,void 0,s),bufferPort2x2:()=>i.bufferPort2x2(e,void 0,s),multiBufferPort:()=>i.multiBufferPort(e,void 0,s),dualTierConveyor:()=>i.dualTierConveyor(e,n.upperElevation,void 0,s),craneTwinFork:()=>i.craneTwinFork(e,void 0,s),floorBlock:()=>i.floorBlock(e,n.rows,n.cols,n.stackLimit,void 0,s)}[t](),r=Object.fromEntries(ck[t].map(t=>[t.key,n[t.key]]));return{...o,preset:{key:t,size:{width:e.width,depth:e.depth,slotHeight:e.slotHeight},params:r}}}(t,e,n,r)})),notes:"invalid"===o.status?[{level:"error",code:"OVERRIDE_INVALID",issue:o.issues[0]}]:[]}}const $P="@figure",LP=[],FP=new Set;function NP(t){return FP.add(t),()=>FP.delete(t)}function HP(t){for(const e of[...FP])e(t)}function BP(t){return LP.push(t),HP(),()=>{const e=LP.indexOf(t);e<0||(LP.splice(e,1),HP())}}function GP(t){const e=new Map;for(const{binding:n}of t?.bindings??[])"table"===n.rule&&n.legend&&!e.has(n.legend.role)&&e.set(n.legend.role,n);return e}const UP=t=>!!t&&"object"==typeof t&&!Array.isArray(t),VP=t=>t?.rootModel?.state??t?.root?.state??{};function WP(t,e){const n={},s=[],i=(t=>{const e=t?.root;return e?.style??e?._style})(t);let o=!1;const r=(t,e,n,r)=>{if(!o&&"string"==typeof n&&n){if(n!==$P)return i&&Object.prototype.hasOwnProperty.call(i,n)?{legend:i[n],source:r,name:n}:void s.push({role:t,binding:e.id,reason:"legend-absent",name:n,source:r});o=!0}};for(const[a,c]of GP(e)){let e;o=!1;for(const n of LP)try{const s=n({component:t,binding:c,role:a});if(null!=s){e={legend:s,source:"resolver"};break}}catch(t){s.push({role:a,binding:c.id,reason:"resolver-failed",source:"resolver",value:t instanceof Error?t.message:String(t)})}const l=t?.state?.legends;e??=r(a,c,UP(l)?l[a]:void 0,"component");const h=VP(t).legends;e??=r(a,c,UP(h)?h[a]:void 0,"board"),!e&&!o&&i&&Object.prototype.hasOwnProperty.call(i,a)&&(e={legend:i[a],source:"domain",name:a}),e&&(n[a]=e)}return{legends:n,notes:s}}function YP(t){let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}return UP(e)?e:null}class qP extends Du{constructor(){super(...arguments),this.rig=null,this.lodEpoch=0}get renderLevel(){return this.rig?.renderLevel??"full"}get lodRevision(){return this.lodEpoch+(this.rig?.lodRevision??0)}get lodGeometryRevision(){return this.lodEpoch+(this.rig?.lodGeometryRevision??0)}get lodError(){return this.rig?.lastLodError}lodBounds(t){return this.rig?(this.rig.group.updateWorldMatrix(!0,!1),this.rig.lodBounds(t).applyMatrix4(this.rig.group.matrixWorld)):t.makeEmpty()}setRenderLevel(t){return this.rig?.setRenderLevel(t)??!0}get figure(){return BO(this.component.state.type)}getObject3dInstance(){return new w.Group}build(){super.build();const t=this.figure;t&&(this.rig=new yP(TP(this.component.state)??t.compiled.asset,{onFileArrived:()=>this.component.invalidate?.()}),this.lodEpoch+=1e6,this.object3d.add(this.rig.group),this.size(),this.seat(),this.rig.setDesignInputs(this.designInputs),this.rig.setState(this.parameters),this.rig.setOpacity(this.opacity),this.applyInputs(),this.followLegendSources(),this.rig.update(),this.reseatHeld(),this.startTicking())}followLegendSources(){const t=this.component.figureInputs;if(this.unfollowLegends||!GP(t?.dataPlan).size)return;const e=()=>this.inputsChanged(),n=this.component.rootModel,s=t=>{t&&"legends"in t&&e()},i=NP(t=>{for(let n=this.component;n;n=n.parent)if(void 0===t||n===t)return e()});n?.on?.("change",s),this.unfollowLegends=()=>{i(),n?.off?.("change",s)}}inputsChanged(){this.applyInputs(),this.startTicking(),this.refresh()}applyInputs(){const t=this.component.figureInputs;if(!this.rig||!t)return;GP(t.dataPlan).size&&t.setThemes(WP(this.component,t.dataPlan));const e=t.data,n={},s={};for(const[t,i]of Object.entries(e.parts))i.color&&(n[t]=i.color),i.effect&&(s[t]=i.effect);this.rig.setDataStates(e.states),this.rig.setPaletteOverrides(e.palette),this.rig.setPartColours(n),this.rig.setPartEffects(s),this.rig.setMotionSettings(t.motion)}get inputIssues(){return this.component.figureInputs?.diagnostics()??[]}get motionRuns(){return this.rig?.motionRuns??{}}restartMotion(t){const e=this.rig?.restartMotion(t)??!1;return e&&this.refresh(),e}get designInputs(){const t=this.component.state.designInputs;return t&&"object"==typeof t?t:{}}get parameters(){const t=this.component.state.parameters;return t&&"object"==typeof t?t:{}}get clipSpeeds(){const t=this.component.state.clips;return t&&"object"==typeof t?t:{}}clipTime(t){return this.rig?.clipTime(t)??0}onchange(t,e){super.onchange(t,e),"designInputs"in t&&this.updateDesignInputs(),"parameters"in t&&this.updateParameters(),"clips"in t&&this.updateClips(),("data"in t||"figureValues"in t||"motion"in t||"legends"in t)&&this.inputsChanged(),"slotLayout"in t&&this.update()}applied(){const t=this.figure?.compiled.asset;return t?MP(this.component,t):null}get mmPerUnit(){return rh(this.component).mmPerUnit}instanceSize(){return this.applied()?.inputs??null}get effectiveDepth(){const t=this.applied()?.box.y;return void 0===t?super.effectiveDepth:t/this.mmPerUnit}get effectiveZPos(){const t=this.component.state.zPos;if("number"==typeof t&&Number.isFinite(t))return t;const e=this.component.effectiveZPos;return"number"==typeof e&&Number.isFinite(e)?e:"ceiling"!==this.figure?.compiled.asset.placement?super.effectiveZPos:XP(this.placementMode,this.sceneHeights.ceiling,this.effectiveDepth)}updateDimension(){this.rig&&(this.size(),this.seat(),this.refresh())}size(){if(!this.rig)return;const t=this.applied();this.rig.setSize(t?.inputs??null),this.rig.group.scale.setScalar((t?.inputs?1:t?.scale??1)/this.mmPerUnit)}seat(){if(!this.rig)return;const t=this.figure?.compiled.asset.placement,e=this.applied()?.centre??{x:0,z:0},n=this.mmPerUnit;if(this.rig.group.position.x=-e.x/n,"wall"===t)return this.rig.group.position.y=0,void(this.rig.group.position.z=-this.component.bounds.height/2);if(this.rig.group.position.z=-e.z/n,"ceiling"===t)return void(this.rig.group.position.y=this.effectiveDepth/2);const s=this.effectiveDepth,i=this.effectiveDepth-s,o="center"===t?i/2:0;this.rig.group.position.y=-this.effectiveDepth/2+o}get sizeClamps(){return this.rig?.clamped??[]}get opacity(){const t=Number(this.component.effectiveOpacity);return Number.isFinite(t)&&t>0&&t<1?t:1}updateDesignInputs(){this.rig&&(this.rig.setDesignInputs(this.designInputs),this.refresh())}updateParameters(){this.rig&&(this.rig.setState(this.parameters),this.refresh())}updateClips(){this.rig&&(this.startTicking(),this.refresh())}refresh(){this.rig&&(this.rig.update(),this.component.invalidate?.())}startTicking(){const t=this.rig?.asset;!this.unsubscribe&&t&&(t.drivers?.length||t.dataInterface)&&(this.unsubscribe=_o.subscribe(t=>this.advance(t),{description:`Figure[${this.component.state.type}].drivers`,component:this.component,getTargets:()=>this.rig?[this.rig.group]:[]}))}tick(t){const e=this.rig;if(!e)return;const n=this.clipSpeeds;let s=!1;for(const i of e.independentClips){const o=n[i]??0;Number.isFinite(o)&&0!==o&&(e.setClipTime(i,e.clipTime(i)+t/1e3*o),s=!0)}e.advance(t/1e3)&&(s=!0),s&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,s=n?.placeNode(t);if(!n||!s)return;const i=n.asset.document.capabilities.slotLayout;if(i&&JM(i).some(e=>e.id===t))return this.slotAttachment(t,s,e);const o=BA(n.asset).find(e=>e.id===t)?.face,r=o&&vM[o]||[0,0,0],a=e?this.itemDimsOf(e):null,c=t=>(t??0)/2;return{attach:s,localPosition:{x:r[0]*c(a?.width),y:r[1]*c(a?.height),z:r[2]*c(a?.depth)}}}itemDimsOf(t){const e=this.component,n=e.itemDimsOf?e.itemDimsOf(t):pk(t,this.mmPerUnit);if(n)return n;const s=t.shownSize,i=this.mmPerUnit;return s?{width:s.width*i,depth:s.height*i,height:s.depth*i}:null}slotAttachment(t,e,n){const s=this.component,i=n?s.itemSeatOf?.(n,t)??null:null,o=i?.inSlot;return{attach:e,localPosition:o?{x:o.position.x,y:o.position.y,z:o.position.z}:{x:0,y:0,z:0},localRotation:{x:0,y:0,z:0},carryPolicy:"slot",displayScale:o?.scale??1,...i?{seat:i}:{}}}clear(){return this.unsubscribe?.(),this.unsubscribe=void 0,this.unfollowLegends?.(),this.unfollowLegends=void 0,this.keepHeld(),this.rig?.dispose(),this.rig=null,super.clear()}keepHeld(){const t=this.rig?.group;if(!t)return;const e=[],n=t=>{for(const s of t.children){const t=s.userData?.context;t instanceof Du&&t!==this?e.push(s):n(s)}};n(t);for(const t of e)t.parent!==this.object3d&&this.object3d.attach(t)}reseatHeld(){const t=this.component;if(this.rig&&t.seatHeldItem)for(const e of t._items??[]){const n=e[_v];"string"==typeof n&&this.rig.placeNode(n)&&t.seatHeldItem(e,{slotId:n})}}}function XP(t,e,n){switch(t){case"inverted":return e;case"space":return e-n/2;default:return e-n}}function KP(t,e,n=1,s={},i={}){const o=new yP(t.compiled.asset);o.setSize(e),o.setPaletteOverrides(s);const r=o.evaluateOnce(),a=new Map(r.geometry.map(t=>[t.id,t])),c=function(t,e){const n=[];for(const s of t){if(!1===s.visible||!ek(s))continue;let t;try{t=eA(tA(s.shape,s.segments),s.pose.r,s.pose.t)}catch{continue}if(t.length<3)continue;const i=t=>t.map(t=>[t[0],t[2]]),o=Math.abs(s.pose.r[1][1]-1)<1e-6,r=s.shape.extrusion;let a;const c=[];if(o&&"y"===r?.axis){const t=(t,e)=>i(eA(nk(t,r.end,s.segments??12,e),s.pose.r,s.pose.t));a=t(r.section);const e=s.shape.cavity;if(e&&"open"===e.end){const n=c_(r.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=tk(i(t));const l=s.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:s.id,color:e[h]??"#9a9a9a",outline:a,holes:c,top:Math.max(...t.map(t=>t[1])),transparent:!!l.transparent})}return n.sort((t,e)=>t.top-e.top)}(r.geometry,r.palette).map(e=>{const n=i[(e=>{const n=a.get(e);return n?.key?t.compiled.writers.get(n.key):e})(e.id)??""];return n&&!a.get(e.id)?.material.emissive?.on?{...e,color:n}:e}),l=1===n?c:c.map(t=>({...t,outline:t.outline.map(([t,e])=>[t*n,e*n]),holes:t.holes.map(t=>t.map(([t,e])=>[t*n,e*n]))}));return{shapes:l,size:o.drawnSize}}const JP=Object.freeze({states:{},palette:{},motion:{},parts:{},pose:{},items:[]}),QP=t=>"number"==typeof t&&Number.isFinite(t),ZP=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tI(t,e){return null==e?null:"number"===t.kind?QP(e)?void 0!==t.min&&e<t.min||void 0!==t.max&&e>t.max?"out-of-range":null:"type-mismatch":"boolean"===t.kind?"boolean"==typeof e?null:"type-mismatch":"text"===t.kind?"string"!=typeof e?"type-mismatch":t.values&&!t.values.includes(e)?"value-unknown":null:"list"===t.kind?Array.isArray(e)?null:"not-a-list":ZP(e)?null:"not-a-record"}function eI(t,e,n,s,i){if(!ZP(t))return t;const o=e[n];if(!Object.prototype.hasOwnProperty.call(t,o.name))return t;const r=s?`${s}.${o.name}`:o.name;let a=t[o.name];const c=n===e.length-1;if(c&&"string"==typeof a)try{a=JSON.parse(a)}catch{return i.push({reason:"json-unreadable",path:r}),{...t,[o.name]:void 0}}else if(!c){const t=(s,o,r)=>o>0?Array.isArray(s)?s.map((e,n)=>t(e,o-1,`${r}[${n}]`)):s:eI(s,e,n+1,r,i);a=t(a,o.lists,r)}return{...t,[o.name]:a}}class nI{constructor(t){this.plan=t,this.bindings=t.bindings.map(t=>{const e=t.binding,n={};if("table"!==e.rule&&"items"===e.behavior.kind)for(const t of["id","type","place","stack","status"]){const s=e.behavior[t];s&&(n[t]=Js(s))}const s="table"===e.rule?t=>t:mi({param:e.param},null,e.rule,e.param,void 0);return{ready:t,read:Js(e.accessor),turn:s,element:n}})}read(t){const e=[],n=[],s=void 0===t.live||null===t.live?void 0:function(t,e,n){if(!e.length||!ZP(t))return t;let s=t;for(const t of e)s=eI(s,t.split(".").map(t=>{const e=(t.match(/\[\]/g)??[]).length;return{name:t.replace(/\[\]/g,""),lists:e}}),0,"",n);return s}(t.live,this.plan.jsonFields,e);void 0===s||ZP(s)||e.push({reason:"not-a-record",path:""});const i=t.manual??null,o={states:{},palette:{},motion:{},parts:{},pose:{},items:[]},r={};for(const{ready:t,read:a,turn:c,element:l}of this.bindings){const h=t.binding;if("table"!==h.rule&&"items"===h.behavior.kind){const n=void 0===s?void 0:a(s);o.items.push({binding:h.id,...h.behavior.slot?{slot:h.behavior.slot}:{},records:this.records(t,n,l,e)});continue}let d,u="absent";const p=void 0===s?void 0:a(s);if(null!=p){const n=tI(t.node,p);n&&e.push({reason:n,path:h.accessor,value:p}),[d,u]=[p,"live"]}else if(i&&void 0!==i[h.accessor]&&null!==i[h.accessor]){const e=tI(t.node,i[h.accessor]);e&&n.push({reason:e,path:h.accessor,value:i[h.accessor]}),[d,u]=[i[h.accessor],"manual"]}else{const e="default"in t.node?t.node.default:void 0;void 0!==e&&([d,u]=[e,"default"])}r[h.id]={value:d,source:u},"absent"!==u&&"table"!==h.rule&&sI(o,h,c(d))}return{result:o,values:r,liveIssues:e,manualIssues:n}}records(t,e,n,s){const i=t.binding;if(null==e||""===e)return[];if("list"!==t.node.kind){const n=tI(t.node,e);return n?(s.push({reason:n,path:i.accessor,value:e}),[]):[{id:String(e)}]}if(!Array.isArray(e))return s.push({reason:"not-a-list",path:i.accessor,value:e}),[];const o=[];return e.forEach((e,r)=>{const a=o=>{const a=n[o]?.(e),c=t.itemNodes?.[o],l=c?tI(c,a):null;return l&&s.push({reason:l,path:`${i.accessor}[${r}].${i.behavior[o]}`,value:a}),null===a?void 0:a},c=a("id");if(void 0===c||""===c)return void s.push({reason:"item-id-missing",path:`${i.accessor}[${r}]`});const[l,h,d,u]=[a("type"),a("place"),a("stack"),a("status")];o.push({id:String(c),...void 0!==l?{type:String(l)}:{},...void 0!==h?{place:String(h)}:{},...QP(d)?{stack:d}:{},...void 0!==u?{status:String(u)}:{}})}),o}}function sI(t,e,n){if(null==n)return;const s=e.behavior;"state"===s.kind?t.states[s.input]={value:n,sourceMode:s.sourceMode}:"palette"===s.kind?t.palette[s.token]=n:"motion-clip"===s.kind?t.motion[s.group]={...t.motion[s.group],clip:n}:"motion-speed"===s.kind?t.motion[s.group]={...t.motion[s.group],speed:n}:"motion-paused"===s.kind?t.motion[s.group]={...t.motion[s.group],paused:n}:"pose"===s.kind&&(t.pose[s.axis]={value:n,seconds:s.seconds??0})}const iI=t=>!!t&&"object"==typeof t&&!Array.isArray(t);class oI{constructor(t){this.asset=t,this.live=null,this.liveEpoch=-1/0,this.manualValues={},this.manualMotion={},this.result=JP,this.values={},this.motionSettings={},this.refused=[],this.legends={},this.legendNotes=[],this.notes=[],this.uses={},this.dataPlan=function(t){if(void 0===t.dataInterface)return null;PS(t);const e=structuredClone(t.dataInterface),n=e.bindings.map(t=>{const n=xS(e.schema,_S(t.accessor)).node;let s;if("table"!==t.rule&&"items"===t.behavior.kind&&"list"===n.kind){const e=n.item;s={};for(const n of["id","type","place","stack","status"]){const i=t.behavior[n];i&&(s[n]=xS("object"===e.kind?e.fields:[],_S(i)).node)}}return Object.freeze({binding:Object.freeze(t),node:n,...s?{itemNodes:Object.freeze(s)}:{}})}),s=[],i=(t,e)=>{for(const n of t){const t=e?`${e}.${n.name}`:n.name;n.json&&s.push(t);let o=n,r=t;for(;"list"===o.kind;)r=`${r}[]`,o=o.item;"object"===o.kind&&i(o.fields,r)}};return i(e.schema,""),Object.freeze({schema:Object.freeze(e.schema),bindings:Object.freeze(n),jsonFields:Object.freeze(s)})}(t),this.reader=this.dataPlan?new nI(this.dataPlan):null,this.motionPlan=zS(t),this.recompute()}setData(t,e){if(void 0!==e){if(e<this.liveEpoch)return{accepted:!1,skipped:!0,issues:[]};this.liveEpoch=e}if(null==t||!this.reader)return this.live=null,this.clear("live"),this.recompute(),{accepted:!0,issues:[]};const{liveIssues:n}=this.reader.read({live:t,manual:null});return n.length?this.refuse({source:"live",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:n}):(this.live=t,this.clear("live"),this.recompute(),{accepted:!0,issues:[]})}setManual(t){const e=[],n=t.figureValues??{};if(iI(n))if(this.reader){const{manualIssues:t}=this.reader.read({manual:n});t.length?e.push({source:"manual",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:t}):this.manualValues={...n}}else Object.keys(n).length&&e.push({source:"manual",severity:"refused",code:"DATA_INTERFACE",reason:"no-data-interface"});else e.push({source:"manual",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:[{reason:"not-a-record",path:"figureValues"}]});const s=t.motion??{};try{if(!iI(s))throw new Xv("MOTION_SETTING","motion","a setting per group",{reason:"motion-setting",why:"group-unknown",group:""});RS(this.motionPlan,s,null),this.manualMotion={...s}}catch(t){if(!(t instanceof Xv))throw t;const n=t.details;e.push({source:"motion",severity:"refused",code:"MOTION_SETTING",reason:n?.why??n?.reason??"motion-setting",group:n?.group})}return this.clear("manual"),this.clear("motion"),this.refused.push(...e),this.recompute(),{accepted:!e.length,issues:e}}setThemes(t){const e=t.legends??{},n=t.notes??[],s=Object.keys(e),i=s.length===Object.keys(this.legends).length&&s.every(t=>this.legends[t]&&this.legends[t].legend===e[t].legend&&this.legends[t].source===e[t].source&&this.legends[t].name===e[t].name)&&JSON.stringify(n)===JSON.stringify(this.legendNotes);return!i&&(this.legends={...e},this.legendNotes=[...n],this.recompute(),!0)}get data(){return this.result}get tableUses(){return this.uses}get dataValues(){return this.values}get motion(){return this.motionSettings}diagnostics(){return[...this.refused,...this.notes]}refuse(t){return this.clear(t.source),this.refused.push(t),{accepted:!1,issues:[t]}}clear(t){this.refused=this.refused.filter(e=>e.source!==t)}recompute(){const t=this.legendNotes.map(t=>({source:"legend",severity:"note",code:"LEGEND_ABSENT",reason:t.reason,binding:t.binding,role:t.role,...void 0!==t.name?{legend:t.name}:{},...void 0!==t.value?{value:t.value}:{}}));if(this.uses={},this.reader){const e=this.reader.read({live:this.live,manual:this.manualValues});this.result=e.result,this.values=e.values;for(const{binding:e}of this.dataPlan.bindings)"table"===e.rule&&this.showTable(e,t)}this.notes=t,this.motionSettings=RS(this.motionPlan,this.manualMotion,this.result.motion)}showTable(t,e){const n=t.legend?.role,s=n?this.legends[n]:void 0,i=(i,o,r={})=>e.push({source:"legend",severity:"note",code:i,reason:o,binding:t.id,...n?{role:n}:{},...s?.name?{legend:s.name}:{},...r});let o=t.table,r="figure";if(s){const t=YP(s.legend);t?[o,r]=[t,s.source]:i("LEGEND_SHAPE","not-a-table",{value:"string"==typeof s.legend?s.legend.slice(0,80):s.legend})}const a=this.values[t.id],c=e=>this.uses[t.id]={value:a?.value,key:e,source:r,..."figure"!==r&&s?.name?{legend:s.name}:{}};if(!a||"absent"===a.source)return void c(null);const l=function(t,e,n,s){const i=Object.keys(n);if("code"===t)return Qs(e,Object.fromEntries(i.map(t=>[t,t])))??null;const o=[];for(const t of i){if("default"===t)continue;const e=ES(t);e?o.push({min:Number.isFinite(e[0])?e[0]:null,max:Number.isFinite(e[1])?e[1]:null,result:t}):s(t)}return ti(e,o,Object.prototype.hasOwnProperty.call(n,"default")?"default":void 0)??null}(t.lookup,a.value,o,t=>i("LEGEND_VALUE","not-an-interval",{key:t}));if(c(l),null===l)return void i("CODE_UNMATCHED","code-unmatched",{value:a.value});const h=o[l],d="string"==typeof h&&pS(h)?{color:h}:iI(h)?h:null;if(!d)return void i("LEGEND_VALUE","not-a-look",{key:l,value:h});const u=(t,e,n)=>i("LEGEND_VALUE","not-taken",{key:l,column:t,value:e,...void 0!==n?{id:n}:{}}),{parts:p=[],inputs:f=[],group:m}=t.targets,g=this.result;if(p.length&&void 0!==d.color)if(pS(d.color))for(const t of p)g.parts[t]={...g.parts[t],color:d.color};else u("color",d.color);if(p.length&&void 0!==d.effect){const t=d.effect,e=void 0===t?.hz||"number"==typeof t.hz&&Number.isFinite(t.hz)&&t.hz>0;if(iI(t)&&("blink"===t.kind||"glow"===t.kind)&&e)for(const e of p)g.parts[e]={...g.parts[e],effect:{kind:t.kind,...void 0!==t.hz?{hz:t.hz}:{}}};else u("effect",d.effect)}if(f.length&&void 0!==d.values)if(iI(d.values))for(const[t,e]of Object.entries(d.values)){if(!f.includes(t))continue;const n=this.ranges.get(t);"number"!=typeof e||!Number.isFinite(e)||n&&(e<n.min||e>n.max)?u("values",e,t):g.states[t]={value:e,sourceMode:"observed"}}else u("values",d.values);if(void 0!==m){const t=this.motionPlan.groups.get(m)?.group.clips??[],e={...g.motion[m]};void 0!==d.clip&&("string"==typeof d.clip&&t.includes(d.clip)?e.clip=d.clip:u("clip",d.clip,m)),void 0!==d.speed&&("number"==typeof d.speed&&d.speed>=0&&d.speed<=3?e.speed=d.speed:u("speed",d.speed,m)),void 0!==d.paused&&("boolean"==typeof d.paused?e.paused=d.paused:u("paused",d.paused,m)),Object.keys(e).length&&(g.motion[m]=e)}}get ranges(){return this._ranges??=new Map(this.asset.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,{min:t.min,max:t.max}]))}}const rI=["x","z","y","heading"];class aI{constructor(t){this.component=t,this.runs=new Map}aim(t){const e=this.now(),n={};for(const s of rI){const i=t[s];if(!i||!Number.isFinite(i.value))continue;const o=this.runs.get(s);(o?o.to:e[s])!==i.value&&(i.seconds>0?this.runs.set(s,{from:e[s],to:i.value,seconds:i.seconds,elapsed:0}):(this.runs.delete(s),n[s]=i.value))}Object.keys(n).length&&this.write(n),this.runs.size&&this.startTicking()}advance(t){if(!this.runs.size)return!1;const e={};for(const[n,s]of this.runs){s.elapsed=Math.min(s.seconds,s.elapsed+t);const i=s.elapsed/s.seconds;e[n]=s.from+(s.to-s.from)*i,i>=1&&this.runs.delete(n)}return this.write(e),this.runs.size||this.stopTicking(),!0}dispose(){this.runs.clear(),this.stopTicking()}startTicking(){this.unsubscribe||(this.unsubscribe=_o.subscribe(t=>this.advance(t/1e3),{description:`Figure[${this.component.state.type}].pose`,component:this.component}))}stopTicking(){this.unsubscribe?.(),this.unsubscribe=void 0}get mmPerUnit(){return rh(this.component).mmPerUnit}now(){const t=this.component.state,e=t=>"number"==typeof t&&Number.isFinite(t)?t:0,n=this.mmPerUnit;return{x:(e(t.left)+e(t.width)/2)*n,z:(e(t.top)+e(t.height)/2)*n,heading:180*e(t.rotation)/Math.PI,y:e(t.zPos)*n}}write(t){const e=this.component.state,n=this.mmPerUnit,s={};void 0!==t.x&&(s.left=t.x/n-(e.width??0)/2),void 0!==t.z&&(s.top=t.z/n-(e.height??0)/2),void 0!==t.heading&&(s.rotation=t.heading*Math.PI/180),void 0!==t.y&&(s.zPos=t.y/n),this.component.setState?this.component.setState(s):this.component.set?.(s)}}const cI=t=>{const e=Wl(t),n=e?Yl(e,t)?.figure:t?.itemTypeCode??t?.state?.type;return"string"==typeof n?BO(n):null};Ov({keyFor(t){const e=cI(t);return e?`${e.type}|${e.compiled.fingerprint}|${rh(t).mmPerUnit}`:null},lookFor(t){const e=cI(t);if(!e)return null;const n=rh(t).mmPerUnit,s=wP(e.compiled.asset),i=new hI({type:e.type,left:0,top:0,width:s.x/n,height:s.z/n,depth:s.y/n,...void 0!==t.state.data?{data:t.state.data}:{}});return i.parent=t,{key:`${e.type}|${e.compiled.fingerprint}|${n}`,component:i,depth:s.y/n,fitTo({width:t,depth:s,height:o}){const r={x:t,z:s,y:o},a=["x","z","y"].map(t=>AP(e.compiled.asset,r,[t]).box),c=1e-6,l=t=>t.x*t.y*t.z,h=a.filter(e=>e.x<=t+c&&e.z<=s+c&&e.y<=o+c),d=h.length?h.reduce((t,e)=>l(e)>l(t)?e:t):a.reduce((t,e)=>l(e)<l(t)?e:t);i.set({width:d.x/n,height:d.z/n,depth:d.y/n})},dispose(){i._realObject?.dispose(),i.dispose()}}},dimsOf(t){const e=cI(t);if(!e)return null;const n=wP(e.compiled.asset);return{width:n.x,depth:n.z,height:n.y}},subscribe:FO});const lI={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"lod",name:"lod",placeholder:"Auto",property:{options:[{display:"Auto",value:"auto"},{display:"Full",value:"full"}]}}],help:"scene/component/figure"};class hI extends(mc(pc)){constructor(){super(...arguments),this.onPicked=(t=[],e=[])=>{t.includes(this)!==e.includes(this)&&this.invalidate()}}static registerType(t,e=[],n,s){const i=uc.register(t);if(i&&!(i===hI||i.prototype instanceof hI))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const o=OO(hI,e,n,s);uc.register(t,o)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=BO(this.state.type);if(!t)return lI;const e=t.compiled.asset,n=e.document.model.inputs,s=(e.publicInputs??[]).flatMap(t=>{const s=n.find(e=>e.id===t.input);return s?[{key:t.input,label:t.label,unit:s.unit,min:s.min,max:s.max,default:e.designInputs[t.input]}]:[]}),i=n.filter(t=>"state"===t.role).map(t=>({key:t.id,label:e.stateInputs?.[t.id]?.label??t.id,unit:t.unit,min:t.min,max:t.max,default:e.stateDefaults[t.id]})),o=new Set((e.motionGroups??[]).flatMap(t=>t.clips)),r=[...new Set((e.drivers??[]).map(t=>t.clip))].filter(t=>!o.has(t)).map(t=>({key:t,label:t,min:0,max:3})),a=new Map((e.dataInterface?function(t){const e=[],n=new Map,s=(t,e)=>n.set(t,[...n.get(t)??[],e]),i=t=>t.replace(/\[\d+\]/g,"[]");for(const e of t.bindings)if(s(i(e.accessor),e.id),"table"!==e.rule&&"items"===e.behavior.kind)for(const t of[e.behavior.id,e.behavior.type,e.behavior.place,e.behavior.stack,e.behavior.status])t&&s(`${i(e.accessor)}[].${i(t)}`,e.id);const o=(t,s,i)=>{for(const r of t){const t=s?`${s}.${r.name}`:r.name;e.push({path:t,depth:i,name:r.name,...r.label?{label:r.label}:{},node:r,json:!!r.json,bindings:n.get(t)??[]});let a=r,c=t;for(;"list"===a.kind;)c=`${c}[]`,a=a.item;"object"===a.kind&&o(a.fields,c,i+1)}};return o(t.schema,"",0),e}(e.dataInterface):[]).map(t=>[t.path,t.label??t.name])),c=new Set,l=(this.figureInputs?.dataPlan?.bindings??[]).flatMap(({binding:t,node:e})=>{if("table"!==t.rule&&"items"===t.behavior.kind||c.has(t.accessor))return[];c.add(t.accessor);const n=a.get(t.accessor.replace(/\[\d+\]/g,"[]"))??t.accessor;return"number"===e.kind?[{key:t.accessor,label:n,unit:e.unit,min:e.min,max:e.max,default:e.default}]:"boolean"===e.kind?[{key:t.accessor,label:n,kind:"boolean",default:e.default}]:"text"===e.kind&&e.values?[{key:t.accessor,label:n,kind:"enum",values:[...e.values],default:e.default}]:[]}),h=(e.motionGroups??[]).flatMap(t=>[{key:`${t.id}.clip`,label:t.label,kind:"enum",values:[...t.clips],default:t.defaultClip},{key:`${t.id}.speed`,label:t.label,unit:"×",min:0,max:3,default:0},{key:`${t.id}.paused`,label:t.label,kind:"boolean",unit:"‖",default:!1}]),d=[...lI.properties];s.length&&d.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:s}}),i.length&&d.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:i}}),r.length&&d.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),e.dataInterface&&d.push({type:"figure-data",label:"figure-data",name:"data"}),l.length&&d.push({type:"number-map",label:"data-values",name:"figureValues",property:{entries:l}}),GP(this.figureInputs?.dataPlan).size&&d.push({type:"figure-legends",label:"figure-legends",name:"legends"}),h.length&&d.push({type:"number-map",label:"motion-groups",name:"motion",property:{entries:h,nested:!0}});for(const t of(this.constructor.capabilities??[]).filter(t=>Fv(t)))for(const e of AO(t)?.properties??[])d.some(t=>t.name===e.name)||d.push(e);return e.document.capabilities.slotLayout&&d.push({type:"slot-layout",label:"slot-layout",name:"slotLayout",property:{options:t=>jP(t[0])}}),d.length===lI.properties.length?lI:{...lI,properties:d}}get figureInputs(){const t=BO(this.state.type);if(t){if(this._inputs?.fingerprint!==t.compiled.fingerprint){const e=new oI(t.compiled.asset);e.setManual({figureValues:this.state.figureValues,motion:this.state.motion}),e.setData(this.state.data),this._inputs={fingerprint:t.compiled.fingerprint,inputs:e}}return this._inputs.inputs}}buildRealObject(){return GO(this.state.type)?new qP(this):void 0}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state,o=BO(this.state.type);if(!o)return void this.renderPlace(t,e,n,s,i);const r=this.topView(o,s,i),a=this.mmPerUnit,{centre:c}=this.appliedAt(o.compiled.asset,s,i,this.askedDepth),l=e+s/2-c.x,h="wall"===o.compiled.asset.placement?n:n+i/2-c.z,d=Number(this.effectiveOpacity),u=Number.isFinite(d)&&d>0&&d<1?d:1;for(const e of r.shapes)if(!(e.outline.length<3)){t.save(),t.fillStyle=e.color,e.transparent&&(t.globalAlpha=.35),t.globalAlpha*=u,t.beginPath();for(const n of[e.outline,...e.holes])if(!(n.length<3)){t.moveTo(l+n[0][0]/a,h+n[0][1]/a);for(let e=1;e<n.length;e++)t.lineTo(l+n[e][0]/a,h+n[e][1]/a);t.closePath()}t.fill("evenodd"),t.restore()}this.picked&&this.renderMotionRange(t,o,s,i,l,h)}get picked(){return!!this.app?.isEditMode&&(this.root?.selected??[]).includes(this)}renderMotionRange(t,e,n,s,i,o){const r=e.compiled.asset,a=this.mmPerUnit,c=function(t,e){let n=EP.get(t);n||EP.set(t,n=new Map);const s=e.inputs?`${e.inputs.x}|${e.inputs.y}|${e.inputs.z}`:"authored";n.has(s)||n.set(s,NA(t,e.inputs?kP(e.inputs):{})?.bounds??null);const i=n.get(s);if(!i||e.inputs)return i;const o=e.scale;return Object.fromEntries(bP.map(t=>[t,{min:i[t].min*o,max:i[t].max*o}]))}(r,AP(r,{x:n*a,z:s*a,y:void 0===this.askedDepth?void 0:this.askedDepth*a}));if(!c)return;const l="wall"===r.placement?c.y:c.z;t.save(),t.strokeStyle="rgba(80, 120, 200, 0.7)",t.lineWidth=1,t.setLineDash([6,4]),t.beginPath(),t.rect(i+c.x.min/a,o+l.min/a,(c.x.max-c.x.min)/a,(l.max-l.min)/a),t.stroke(),t.restore()}topView(t,e,n){const s=this.appliedAt(t.compiled.asset,e,n,this.askedDepth),i=s.inputs,o=this.figureInputs;o&&GP(o.dataPlan).size&&o.setThemes(WP(this,o.dataPlan));const r=this.figureInputs?.data.palette??{},a=Object.fromEntries(Object.entries(this.figureInputs?.data.parts??{}).flatMap(([t,e])=>e.color?[[t,e.color]]:[])),c=`${t.compiled.fingerprint}|${i?`${i.x}|${i.y}|${i.z}`:`x${s.scale}`}|${JSON.stringify(r)}|${JSON.stringify(a)}`;return this._top?.key!==c&&(this._top={key:c,view:KP(t,i,s.scale,r,a)}),this._top.view}get mmPerUnit(){return rh(this).mmPerUnit}appliedAt(t,e,n,s,i){const o=this.mmPerUnit,r=AP(t,{x:e*o,z:n*o,y:void 0===s?void 0:s*o},i),a=r.box,c=r.centre;return{...r,box:{x:a.x/o,y:a.y/o,z:a.z/o},centre:{x:c.x/o,y:c.y/o,z:c.z/o}}}get askedDepth(){return SP(this)}adjustResize(t,e,n){const s=BO(this.state.type);if(!s)return super.adjustResize(t,e,n);const i=s.compiled.asset,o=xP(i),r=super.adjustResize(t,e,n),a=this.bounds,c=[];Math.abs(r.width-a.width)>1e-6&&c.push("x"),Math.abs(r.height-a.height)>1e-6&&c.push("z");const{box:l}=this.appliedAt(i,r.width,r.height,o?void 0:this.askedDepth,c);return{left:Math.abs(r.left-a.left)>1e-6?r.left+r.width-l.x:r.left,top:Math.abs(r.top-a.top)>1e-6?r.top+r.height-l.z:r.top,width:l.x,height:l.z}}added(t){super.added(t),this.root?.on?.("selected",this.onPicked),this.fitBoxToFigure([])}get figurePose(){return this._pose??=new aI(this)}async ready(){await super.ready();const t=this.figureInputs?.data.pose;t&&this.figurePose.aim(t)}onchange(t,e){if(super.onchange(t,e),this._inputs&&(("figureValues"in t||"motion"in t)&&this._inputs.inputs.setManual({figureValues:this.state.figureValues,motion:this.state.motion}),"data"in t&&this._inputs.inputs.setData(t.data)),"data"in t){const t=this.figureInputs?.data.pose;t&&this.figurePose.aim(t)}const n=[];"width"in t&&n.push("x"),"height"in t&&n.push("z"),"depth"in t&&n.push("y"),n.length&&this.fitBoxToFigure(n)}removed(t){this.root?.off?.("selected",this.onPicked),this._pose?.dispose(),super.removed(t)}fitBoxToFigure(t){if(!this.rootModel)return;const e=BO(this.state.type);if(!e)return;const n=e.compiled.asset,s=xP(n),{width:i=0,height:o=0}=this.state;if(!(i>0&&o>0)){const t=wP(n),e=t.x/this.mmPerUnit,s=t.z/this.mmPerUnit,{left:r=0,top:a=0}=this.state;return void this.set({left:r+i/2-e/2,top:a+o/2-s/2,width:e,height:s})}const{box:r}=this.appliedAt(n,i,o,this.askedDepth,t),a={};Math.abs(r.x-i)>1e-6&&(a.width=r.x),Math.abs(r.z-o)>1e-6&&(a.height=r.z);const c=this.state.depth,l="number"==typeof c&&Number.isFinite(c)&&c>0?c:void 0;(void 0!==l&&Math.abs(r.y-l)>1e-6||s&&void 0===this.askedDepth&&t.includes("y"))&&(a.depth=r.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,s,i){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,s,i),t.stroke(),t.restore()}postrender(t){uc.prototype.postrender.call(this,t)}}yO(hI);const dI={"palette.primary":"#154473","palette.accent":"#f79c40","palette.neutral":"#96989b","palette.dark":"#27292c","palette.light":"#d6d7d9","palette.surface":"#56585b","palette.status-danger":"#f61b30","palette.status-warning":"#e68d1a","palette.status-info":"#158bde","palette.status-success":"#1cb648"},uI=new Map([["default",dI]]);let pI="default",fI=0;function mI(){return fI}function gI(t,e){uI.set(t,e),t===pI&&fI++}function yI(t){if(!uI.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...uI.keys()].join(", ")}`);t!==pI&&(pI=t,fI++)}function bI(){return pI}function vI(){return uI.get(pI)}function _I(t){const e=vI()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${pI}'). 쓸 수 있는 것 — ${Object.keys(vI()).join(", ")}`);return e}const xI=dI["palette.neutral"];function wI(){uI.clear(),uI.set("default",dI),pI="default",fI++}const MI={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},SI=["shape","segments"],AI=["color","preset","transparent","glow"];function kI(t,e){let n;try{n=iP(t,e)}catch{return null}if(!n?.getAttribute("position"))return null;const s=n.clone();n.dispose(),s.computeBoundingBox();const i=s.boundingBox,o=i.getCenter(new w.Vector3),r=i.getSize(new w.Vector3);return s.translate(-o.x,-o.y,-o.z),s.scale(1/(r.x||1),1/(r.y||1),1/(r.z||1)),s.computeBoundingBox(),s.getAttribute("normal")||s.computeVertexNormals(),{geometry:s,extent:r,centre:o}}class EI extends Du{build(){super.build();const t=this.component.state,e=t.shape?kI(t.shape,t.segments):null;if(!e)return;const n=new w.Mesh(e.geometry,this.material());n.castShadow=!0,n.receiveShadow=!0,this.object3d.add(n),this.mesh=n,this.updateDimension(),t.shape?.mesh&&this.dressWithFile(n,t.shape.mesh,e)}dressWithFile(t,e,n){mP({asset:e.asset,...void 0!==e.node?{node:e.node}:{},scale:e.scale}).then(e=>{if(!e||this.mesh!==t)return;const s=new w.Group;s.scale.set(1/(n.extent.x||1),1/(n.extent.y||1),1/(n.extent.z||1)),e.position.set(-n.centre.x,-n.centre.y,-n.centre.z),s.add(e),t.add(s),t.material=EI.HIDDEN_BOX,this.component.invalidate?.()})}clear(){return this.mesh?.geometry.dispose(),this.mesh=void 0,super.clear()}onchange(t,e){const n=e=>e.some(e=>e in t);n(SI)?this.update():(super.onchange(t,e),n(AI)&&this.mesh&&this.mesh.material!==EI.HIDDEN_BOX&&(this.mesh.material=this.material()))}updateDimension(){const{width:t=1,height:e=1}=this.component.bounds;this.setDimensionScale(t||1,this.effectiveDepth||1,e||1)}material(){const t=this.component.state,e=Fd[t.preset??"default"]??Fd.default,n=t.color??"#9a9a9a",s=t.transparent??!1,i=t.glow,o=i?i.color:n,r=i?i.intensity:0;return NT.material(`figure-part|${n}|${t.preset??"default"}|${s}|${i?`${i.color}:${r}`:"-"}`,{color:o,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:s,opacity:s?e.opacity??.3:1,emissive:o,emissiveIntensity:r})}}EI.HIDDEN_BOX=new w.MeshBasicMaterial({visible:!1});class TI extends(mc(pc)){static registerType(){uc.register("figure-part",TI)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return MI}buildRealObject(){return new EI(this)}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state;t.beginPath(),t.rect(e,n,s,i),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var CI;TI.registerType(),t.Model=void 0,(CI=t.Model||(t.Model={})).compile=kl,CI.duplicate=El,CI.select=Fa,CI.match=ja,Ss.registerResidents(()=>({componentResidentsCount:uc.residentsCount,sceneResidentsCount:lp.residentsCount,referenceMapResidentsCount:wT.residentsCount,sceneResidents:uc.residents}));var OI=Object.freeze({__proto__:null,AbsoluteLayout:Mc,Animation:la,AudioPlayer:Ab,BULGE_EPSILON:Do,get Banner(){return t.Banner},Banner3D:AC,BoxSelectionManager:Xf,COMMON_PLACEHOLDER_PROPERTIES:Yy,CORE_PLACEHOLDER_TYPES:Jy,get Camera(){return t.Camera},Camera3D:CC,CameraBookmarkManager:qf,CameraManager:If,Capacity:kk,CapacityEventTracker:cv,CardLayout:Ac,CenteringQueueStrategy:hv,CenteringSlotStrategy:ZE,Component:uc,Connectable:xm,Container:Cy,ContainerAbstract:Kl,ControlsManager:jf,get Cube(){return t.Cube},Cube3D:xC,get Cylinder(){return t.Cylinder},Cylinder3D:MC,DEFAULT:zi,DEFAULT_CEILING:Cu,DEFAULT_PALETTE:dI,DEFAULT_PLACEMENT:wu,DEFAULT_SEAT_MARGIN:NM,DPPX:Pi,DRAWING_DISPLAY_UNITS:Jl,DataLagTracker:bh,DataSource:tv,DefaultLoadingOverlayRenderer:Zd,Donut:Ub,DonutExtrude:rC,EMPTY_FIGURE_DATA:JP,Ellipse:Vy,EllipseExtrude:nC,EventManager3D:$f,EventMap:Qc,FIGURE_CAPABILITIES:vO,FIGURE_OWN_TABLE:$P,FPS:Jp,FigureDataReader:nI,FigureInputs:oI,FigureInstance:hI,FigurePart:TI,FigurePartRealObject:EI,FixedSlotStrategy:xk,get FloorPlate(){return t.FloorPlate},FlowEngine:zE,FlowNode:GE,GESTURES:Ii,get GLTFObject(){return t.GLTFObject},GLTF_BASE_URL_ALIAS:nv,GenericObject:Ky,GeometryBank:Av,GifView:Mb,GizmoManager:Nf,GizmoOperationManager:Gf,GlobalRef:Db,GltfComponent:iv,GridStacking:pv,Group:Tb,HOLDER_ANCHOR:wM,HTMLAbsoluteLayout:wc,HTMLOverlayContainer:Pb,HTMLOverlayElement:db,Holdable:NE,ITEM_TYPES_THEME:Hl,ITEM_TYPE_CODE_MAX:64,ImageView:hb,InfoWindow:vc,InstancedSet:sO,InteractionManager:Uf,Item:zv,ItemRealObject:Rv,ItemsDataBinding:wv,KEYEVENTS:Di,Layer:Cp,Layout:xc,LightManager:zf,LightObject:IC,Line:Gy,Line3D:ZC,LinearHorizontalLayout:Ec,LinearVerticalLayout:Cc,LoadTracker:xh,LoadingOverlay:Vd,LocalRef:Ob,MATERIAL_PRESETS:Fd,MAX_SEGMENTS:dC,MAX_UNDO_SIZE:30,MIN_SEGMENTS:3,MODE_ADD:3,MODE_EDIT:1,MODE_PASTE_DATABIND:5,MODE_PASTE_STYLE:4,MODE_SHIFT:2,MODE_VIEW:0,MaterialBank:NT,get Model(){return t.Model},MoveHandle:ql,NOTHING:Ci,NavGraph:oT,Node:Xb,OrthoLine:cb,OrthoLine3D:eO,PIXEL_RATIO:Qp,PLACEHOLDER_THEMES:Wy,Path:Fb,PatternStacking:uv,PlacementManager:Vf,get PointLight(){return t.PointLight},Polygon:eb,PolygonContainer:sb,PolygonExtrude:oC,PolygonPathPolyline:uT,Polyline:rb,Polyline3D:tO,Popup:jb,PopupContainer:Lb,Pose6DOF:il,RealObject:Du,RealObjectCamera:aO,RealObjectDomElement:af,RealObjectDomTexture:jT,RealObjectDummy:oO,RealObjectExternalModel:ju,RealObjectExtrude:eC,RealObjectGLTF:Nu,RealObjectGroup:HC,RealObjectLine:QC,RealObjectMesh:HT,RealObjectPlane:cO,RealObjectPlane2D:dO,RealObjectScene:lO,RealObjectService:Kb,RealObjectSprite:yC,RealObjectSprite2D:bC,RealObjectText:qT,Rect:Sm,RectExtrude:sC,RectPath:mc,ReferenceMap:wT,RendererManager:Df,ReservationTable:sT,RootContainer:yh,Ruler:km,SCALE_MIN:cu,SCENE_MODE:Oi,SEGMENT_DEFAULTS:hC,SEGMENT_PRESETS:lC,SHORTCUT_SECTIONS:pm,Scene:lp,SceneManager:Pf,ScenePopup:Tp,SceneSearchEngine:Vu,ScriptLoader:CT,SearchOverlay:Yu,ServiceComponent:Qb,Shape:pc,get Sphere(){return t.Sphere},Sphere3D:gC,get Sprite(){return t.Sprite},Star:Yb,StarExtrude:cC,TRANSFER_SLOT_KEY:_v,TableLayout:Oc,Text:kb,ThreeCapability:rm,get ThreeContainer(){return t.ThreeContainer},ThreeDOnly:ev,Tracker:Xu,Transfer:op,TransitionEffect:Nl,Triangle:Hb,TriangleExtrude:aC,UNIT_DIMENSION:uu,UNIT_ROTATE:mu,UNIT_SCALE:pu,UNIT_TRANSLATE:fu,UNTOKENED_COLOR:xI,ValueHolder:Zb,VertexGizmoManager:tm,VolumeStacking:fv,get Wall(){return t.Wall},Wall3D:zC,Z_PRIORITY:Su,acquireFigureGeometry:nP,activePalette:vI,activePaletteName:bI,addressOfSlotId:jM,allDestinations:xE,anchorsConnect:Ik,animate:ca,applyAlpha:hu,applyMaterial3dProps:Gd,applyPolicy:SE,applySeatingRotation:vv,applyStackLayout:mv,applyZPriorityToMaterials:ku,arcSegmentTopology:Ok,autoWireBackPressure:lv,buildArrow3D:of,buildContractInspector:bT,buildCoordinateGround:yf,buildFigureGeometry:iP,buildFlowGraph:$k,buildNavGraph:cT,buildShapeFromPolygonPath:iC,buildTether:vp,bulgeFromDrag:$o,bulgeHandlePosition:jo,calibratedMmPerUnit:oh,canReach:Bk,capability:rg,ceilingZPos:XP,centerOnBBox:tC,chooseNearestPickupFrame:QE,clearTether:xp,collectAdjacentSegments:Yk,compile:da,componentForNode:_E,computeArcParams:Ro,computeFlowMap:cE,computeStackPositions:dv,cornerHandlePosition:Fo,cornerRadiusFromDrag:No,create:dp,createCanvas:Zp,createCanvasTexture:IT,createFloor:Tf,createRealObjectFor:uf,createSelectionHandle3D:$C,dataLagTracker:vh,debug:Hs,deliversInto:Rk,delta:ra,displayToMm:ih,disposeCoordinateGround:xf,disposeObject3D:bu,disposeTether:wp,downstream:EE,drawTextTexture:UT,drawingScaleFor:rh,drawingScaleOf:th,drawingToMm:nh,effectiveCornerRadius:Lo,ellipseOutline:ZT,enumerateDataScenarios:Jk,error:Fs,figureAnchorFacesOf:DP,figureAnchorRoomOf:zP,figureAssetFor:TP,figureAssetWithCapabilities:RO,figureBindingsResting:IO,figureBindingsTakenOver:DO,figureCapabilitiesAssembled:CO,figureCapabilityDescriptorOf:AO,figureCapabilityDescriptors:SO,figureClassFor:OO,figureLegendRolesOf:GP,figureLegendSourcesChanged:HP,figureLegendTableOf:YP,figureMeshObjectOf:mP,figureMeshUrlOf:fP,figurePlacementSlotLayoutOptions:jP,figureSectionOutline:QA,figureSlotLayoutOfPlacement:CP,fillStyleOpacity:lu,filterByToolType:JE,filterShortcuts:fm,findNearestWithCapability:dE,flattenPolygonPath:pT,flowGraphFor:bE,flowGraphIssues:yE,flowReverseFor:lE,fontStyle:BT,footprint2D:gv,frameClock:_o,ftId:iE,ftrace:sE,getAllCapabilityMeta:hg,getCapabilityMeta:lg,getFigure:BO,getPose:ll,getWorldPose:hl,globalSimClock:bo,gltfNatureProperties:sv,graphFor:PE,gridCellOf:IM,gridPlacements:iO,gridSlotNo:PM,hasArc:zo,hasCapability:og,hasCapacity:rv,hasFigure:GO,inferCapacity:av,inferDownstreamId:qk,inferFlowDirections:nE,initFontFamilyWatcher:ji,inspector:Ud,installContractInspector:vT,isFlowNode:UE,isGenericPlaceholder:Qy,isGeometricHost:hE,isItemTypeTable:Vl,isParted:zu,isRoutingTarget:uE,isSegmentPreset:fC,isStateDriven:Mu,isThreedEnabled:Bu,itemById:dh,itemIdOf:hh,itemLookDimsOf:Pv,itemSeatsOf:_k,itemTypeEntryOf:Yl,itemTypeTableOf:Wl,itemTypesFromThemes:Ul,judgeItemFit:KM,layoutIssue:xM,matchOutbounds:jk,metrics:Ss,mmToDisplay:sh,mmToDrawing:eh,next:kE,nextHop:Hk,nextHops:Nk,nextHopsToAny:Uk,nextHopsToAnyDetailed:Vk,niceGridStep:mf,nodeIdOf:wE,occupancySnapshotOf:mk,onFigureCapabilitiesChanged:kO,onFigureLegendSourcesChanged:NP,onFiguresChanged:FO,opaqueColor:du,paletteVersion:mI,partAtByIndex:Ru,persistenceIssues:TM,pickFigureLegends:WP,pickWeightedDestination:DE,planPathAStar:lT,planToReservations:hT,pointInRotatedRect:Dk,polygonOffsetForPriority:Au,polygonPathLength:fT,projectToScreen:mp,quatFromYaw:WE,rayAbsDistanceToRect:zk,reachableByOutbound:Lk,reachableDestinations:TE,reachableDestinationsFrom:CE,reachableDestinationsWeightedFrom:OE,reachableSinks:Gk,readItemTypes:Gl,receiptToJSON:sp,recommendsLogarithmicDepthForSky:Of,rectFaceAnchors:Ek,rectOutline:QT,rectangularFootprintFrames:XE,registerCapabilityMeta:cg,registerDefaultRealObjectFactory:df,registerFigure:HO,registerFigureCapability:MO,registerFigureLegendResolver:BP,registerFigureType:bO,registerPalette:gI,registerRealObjectFactory:hf,registerTypeResolver:vl,releaseFigureGeometry:sP,renderCanvasTexture:DT,renderPlaceholder:qy,reservationTable:iT,resetFigureClasses:jO,resetFigures:VO,resetPalettes:wI,resolveAnchorWorldPosition:bp,resolveHeightSegments:pC,resolveLegend:Qs,resolveLegendEntries:ti,resolveMaterial3d:Nd,resolveNextHop:AE,resolveSegments:uC,resolveSlot:zM,resolveToken:_I,resolveUnknownTypes:xl,resolveVariant:ou,rotatedFootprint:BM,rulerPixelsPerTick:ah,sceneComponent:ov,sceneHeightsOf:Ou,seatInSlot:GM,seatTransform:UM,setActivePalette:yI,setFigureMeshResolver:pP,setItemLookProvider:Ov,setPose:dl,setThreedEnabled:Gu,setWorldPose:ul,sinksForDestination:vE,slotAddresses:$M,slotCount:CM,slotFrame:FM,slotIdOf:RM,slotNumbers:OM,slotSpaceWarnings:XM,slotsFromBindings:TO,stackSeatTransforms:VM,standardYieldPolicy:nT,stopFPSMeasure:Kp,straightSegmentEndpoints:Ck,straightSegmentMultiInbound:Pk,straightSegmentTopology:Tk,textBounds:YT,textTexture:VT,toThreeSide:Bd,topApproachFrame:KE,transferLog:rp,transferTracer:ep,uniformZ:Ho,unitFigurePartGeometry:kI,unknownTypesOf:_l,unregisterFigure:UO,unresolvedReasonOf:yl,updateDefaultFontFamily:Ri,updateTether:_p,useFigureComponent:yO,validate:IE,validateFlowGraph:Wk,validateSlotLayout:EM,version:OT,warn:Ns});const PI=globalThis;"undefined"==typeof globalThis||PI.scene||(PI.scene=OI),t.AbsoluteLayout=Mc,t.Animation=la,t.AudioPlayer=Ab,t.BULGE_EPSILON=Do,t.Banner3D=AC,t.BoxSelectionManager=Xf,t.COMMON_PLACEHOLDER_PROPERTIES=Yy,t.CORE_PLACEHOLDER_TYPES=Jy,t.Camera3D=CC,t.CameraBookmarkManager=qf,t.CameraManager=If,t.Capacity=kk,t.CapacityEventTracker=cv,t.CardLayout=Ac,t.CenteringQueueStrategy=hv,t.CenteringSlotStrategy=ZE,t.Component=uc,t.Connectable=xm,t.Container=Cy,t.ContainerAbstract=Kl,t.ControlsManager=jf,t.Cube3D=xC,t.Cylinder3D=MC,t.DEFAULT=zi,t.DEFAULT_CEILING=Cu,t.DEFAULT_PALETTE=dI,t.DEFAULT_PLACEMENT=wu,t.DEFAULT_SEAT_MARGIN=NM,t.DPPX=Pi,t.DRAWING_DISPLAY_UNITS=Jl,t.DataLagTracker=bh,t.DataSource=tv,t.DefaultLoadingOverlayRenderer=Zd,t.Donut=Ub,t.DonutExtrude=rC,t.EMPTY_FIGURE_DATA=JP,t.Ellipse=Vy,t.EllipseExtrude=nC,t.EventManager3D=$f,t.EventMap=Qc,t.FIGURE_CAPABILITIES=vO,t.FIGURE_OWN_TABLE=$P,t.FPS=Jp,t.FigureDataReader=nI,t.FigureInputs=oI,t.FigureInstance=hI,t.FigurePart=TI,t.FigurePartRealObject=EI,t.FixedSlotStrategy=xk,t.FlowEngine=zE,t.FlowNode=GE,t.GESTURES=Ii,t.GLTF_BASE_URL_ALIAS=nv,t.GenericObject=Ky,t.GeometryBank=Av,t.GifView=Mb,t.GizmoManager=Nf,t.GizmoOperationManager=Gf,t.GlobalRef=Db,t.GltfComponent=iv,t.GridStacking=pv,t.Group=Tb,t.HOLDER_ANCHOR=wM,t.HTMLAbsoluteLayout=wc,t.HTMLOverlayContainer=Pb,t.HTMLOverlayElement=db,t.Holdable=NE,t.ITEM_TYPES_THEME=Hl,t.ITEM_TYPE_CODE_MAX=64,t.ImageView=hb,t.InfoWindow=vc,t.InstancedSet=sO,t.InteractionManager=Uf,t.Item=zv,t.ItemRealObject=Rv,t.ItemsDataBinding=wv,t.KEYEVENTS=Di,t.Layer=Cp,t.Layout=xc,t.LightManager=zf,t.LightObject=IC,t.Line=Gy,t.Line3D=ZC,t.LinearHorizontalLayout=Ec,t.LinearVerticalLayout=Cc,t.LoadTracker=xh,t.LoadingOverlay=Vd,t.LocalRef=Ob,t.MATERIAL_PRESETS=Fd,t.MAX_SEGMENTS=dC,t.MAX_UNDO_SIZE=30,t.MIN_SEGMENTS=3,t.MODE_ADD=3,t.MODE_EDIT=1,t.MODE_PASTE_DATABIND=5,t.MODE_PASTE_STYLE=4,t.MODE_SHIFT=2,t.MODE_VIEW=0,t.MaterialBank=NT,t.MoveHandle=ql,t.NOTHING=Ci,t.NavGraph=oT,t.Node=Xb,t.OrthoLine=cb,t.OrthoLine3D=eO,t.PIXEL_RATIO=Qp,t.PLACEHOLDER_THEMES=Wy,t.Path=Fb,t.PatternStacking=uv,t.PlacementManager=Vf,t.Polygon=eb,t.PolygonContainer=sb,t.PolygonExtrude=oC,t.PolygonPathPolyline=uT,t.Polyline=rb,t.Polyline3D=tO,t.Popup=jb,t.PopupContainer=Lb,t.Pose6DOF=il,t.RealObject=Du,t.RealObjectCamera=aO,t.RealObjectDomElement=af,t.RealObjectDomTexture=jT,t.RealObjectDummy=oO,t.RealObjectExternalModel=ju,t.RealObjectExtrude=eC,t.RealObjectGLTF=Nu,t.RealObjectGroup=HC,t.RealObjectLine=QC,t.RealObjectMesh=HT,t.RealObjectPlane=cO,t.RealObjectPlane2D=dO,t.RealObjectScene=lO,t.RealObjectService=Kb,t.RealObjectSprite=yC,t.RealObjectSprite2D=bC,t.RealObjectText=qT,t.Rect=Sm,t.RectExtrude=sC,t.RectPath=mc,t.ReferenceMap=wT,t.RendererManager=Df,t.ReservationTable=sT,t.RootContainer=yh,t.Ruler=km,t.SCALE_MIN=cu,t.SCENE_MODE=Oi,t.SEGMENT_DEFAULTS=hC,t.SEGMENT_PRESETS=lC,t.SHORTCUT_SECTIONS=pm,t.Scene=lp,t.SceneManager=Pf,t.ScenePopup=Tp,t.SceneSearchEngine=Vu,t.ScriptLoader=CT,t.SearchOverlay=Yu,t.ServiceComponent=Qb,t.Shape=pc,t.Sphere3D=gC,t.Star=Yb,t.StarExtrude=cC,t.TRANSFER_SLOT_KEY=_v,t.TableLayout=Oc,t.Text=kb,t.ThreeCapability=rm,t.ThreeDOnly=ev,t.Tracker=Xu,t.Transfer=op,t.TransitionEffect=Nl,t.Triangle=Hb,t.TriangleExtrude=aC,t.UNIT_DIMENSION=uu,t.UNIT_ROTATE=mu,t.UNIT_SCALE=pu,t.UNIT_TRANSLATE=fu,t.UNTOKENED_COLOR=xI,t.ValueHolder=Zb,t.VertexGizmoManager=tm,t.VolumeStacking=fv,t.Wall3D=zC,t.Z_PRIORITY=Su,t.acquireFigureGeometry=nP,t.activePalette=vI,t.activePaletteName=bI,t.addressOfSlotId=jM,t.allDestinations=xE,t.anchorsConnect=Ik,t.animate=ca,t.applyAlpha=hu,t.applyMaterial3dProps=Gd,t.applyPolicy=SE,t.applySeatingRotation=vv,t.applyStackLayout=mv,t.applyZPriorityToMaterials=ku,t.arcSegmentTopology=Ok,t.autoWireBackPressure=lv,t.buildArrow3D=of,t.buildContractInspector=bT,t.buildCoordinateGround=yf,t.buildFigureGeometry=iP,t.buildFlowGraph=$k,t.buildNavGraph=cT,t.buildShapeFromPolygonPath=iC,t.buildTether=vp,t.bulgeFromDrag=$o,t.bulgeHandlePosition=jo,t.calibratedMmPerUnit=oh,t.canReach=Bk,t.capability=rg,t.ceilingZPos=XP,t.centerOnBBox=tC,t.chooseNearestPickupFrame=QE,t.clearTether=xp,t.collectAdjacentSegments=Yk,t.compile=da,t.componentForNode=_E,t.computeArcParams=Ro,t.computeFlowMap=cE,t.computeStackPositions=dv,t.cornerHandlePosition=Fo,t.cornerRadiusFromDrag=No,t.create=dp,t.createCanvas=Zp,t.createCanvasTexture=IT,t.createFloor=Tf,t.createRealObjectFor=uf,t.createSelectionHandle3D=$C,t.dataLagTracker=vh,t.debug=Hs,t.deliversInto=Rk,t.delta=ra,t.displayToMm=ih,t.disposeCoordinateGround=xf,t.disposeObject3D=bu,t.disposeTether=wp,t.downstream=EE,t.drawTextTexture=UT,t.drawingScaleFor=rh,t.drawingScaleOf=th,t.drawingToMm=nh,t.effectiveCornerRadius=Lo,t.ellipseOutline=ZT,t.enumerateDataScenarios=Jk,t.error=Fs,t.figureAnchorFacesOf=DP,t.figureAnchorRoomOf=zP,t.figureAssetFor=TP,t.figureAssetWithCapabilities=RO,t.figureBindingsResting=IO,t.figureBindingsTakenOver=DO,t.figureCapabilitiesAssembled=CO,t.figureCapabilityDescriptorOf=AO,t.figureCapabilityDescriptors=SO,t.figureClassFor=OO,t.figureLegendRolesOf=GP,t.figureLegendSourcesChanged=HP,t.figureLegendTableOf=YP,t.figureMeshObjectOf=mP,t.figureMeshUrlOf=fP,t.figurePlacementSlotLayoutOptions=jP,t.figureSectionOutline=QA,t.figureSlotLayoutOfPlacement=CP,t.fillStyleOpacity=lu,t.filterByToolType=JE,t.filterShortcuts=fm,t.findNearestWithCapability=dE,t.flattenPolygonPath=pT,t.flowGraphFor=bE,t.flowGraphIssues=yE,t.flowReverseFor=lE,t.fontStyle=BT,t.footprint2D=gv,t.frameClock=_o,t.ftId=iE,t.ftrace=sE,t.getAllCapabilityMeta=hg,t.getCapabilityMeta=lg,t.getFigure=BO,t.getPose=ll,t.getWorldPose=hl,t.globalSimClock=bo,t.gltfNatureProperties=sv,t.graphFor=PE,t.gridCellOf=IM,t.gridPlacements=iO,t.gridSlotNo=PM,t.hasArc=zo,t.hasCapability=og,t.hasCapacity=rv,t.hasFigure=GO,t.inferCapacity=av,t.inferDownstreamId=qk,t.inferFlowDirections=nE,t.initFontFamilyWatcher=ji,t.inspector=Ud,t.installContractInspector=vT,t.isFlowNode=UE,t.isGenericPlaceholder=Qy,t.isGeometricHost=hE,t.isItemTypeTable=Vl,t.isParted=zu,t.isRoutingTarget=uE,t.isSegmentPreset=fC,t.isStateDriven=Mu,t.isThreedEnabled=Bu,t.itemById=dh,t.itemIdOf=hh,t.itemLookDimsOf=Pv,t.itemSeatsOf=_k,t.itemTypeEntryOf=Yl,t.itemTypeTableOf=Wl,t.itemTypesFromThemes=Ul,t.judgeItemFit=KM,t.layoutIssue=xM,t.matchOutbounds=jk,t.metrics=Ss,t.mmToDisplay=sh,t.mmToDrawing=eh,t.next=kE,t.nextHop=Hk,t.nextHops=Nk,t.nextHopsToAny=Uk,t.nextHopsToAnyDetailed=Vk,t.niceGridStep=mf,t.nodeIdOf=wE,t.occupancySnapshotOf=mk,t.onFigureCapabilitiesChanged=kO,t.onFigureLegendSourcesChanged=NP,t.onFiguresChanged=FO,t.opaqueColor=du,t.paletteVersion=mI,t.partAtByIndex=Ru,t.persistenceIssues=TM,t.pickFigureLegends=WP,t.pickWeightedDestination=DE,t.planPathAStar=lT,t.planToReservations=hT,t.pointInRotatedRect=Dk,t.polygonOffsetForPriority=Au,t.polygonPathLength=fT,t.projectToScreen=mp,t.quatFromYaw=WE,t.rayAbsDistanceToRect=zk,t.reachableByOutbound=Lk,t.reachableDestinations=TE,t.reachableDestinationsFrom=CE,t.reachableDestinationsWeightedFrom=OE,t.reachableSinks=Gk,t.readItemTypes=Gl,t.receiptToJSON=sp,t.recommendsLogarithmicDepthForSky=Of,t.rectFaceAnchors=Ek,t.rectOutline=QT,t.rectangularFootprintFrames=XE,t.registerCapabilityMeta=cg,t.registerDefaultRealObjectFactory=df,t.registerFigure=HO,t.registerFigureCapability=MO,t.registerFigureLegendResolver=BP,t.registerFigureType=bO,t.registerPalette=gI,t.registerRealObjectFactory=hf,t.registerTypeResolver=vl,t.releaseFigureGeometry=sP,t.renderCanvasTexture=DT,t.renderPlaceholder=qy,t.reservationTable=iT,t.resetFigureClasses=jO,t.resetFigures=VO,t.resetPalettes=wI,t.resolveAnchorWorldPosition=bp,t.resolveHeightSegments=pC,t.resolveLegend=Qs,t.resolveLegendEntries=ti,t.resolveMaterial3d=Nd,t.resolveNextHop=AE,t.resolveSegments=uC,t.resolveSlot=zM,t.resolveToken=_I,t.resolveUnknownTypes=xl,t.resolveVariant=ou,t.rotatedFootprint=BM,t.rulerPixelsPerTick=ah,t.sceneComponent=ov,t.sceneHeightsOf=Ou,t.seatInSlot=GM,t.seatTransform=UM,t.setActivePalette=yI,t.setFigureMeshResolver=pP,t.setItemLookProvider=Ov,t.setPose=dl,t.setThreedEnabled=Gu,t.setWorldPose=ul,t.sinksForDestination=vE,t.slotAddresses=$M,t.slotCount=CM,t.slotFrame=FM,t.slotIdOf=RM,t.slotNumbers=OM,t.slotSpaceWarnings=XM,t.slotsFromBindings=TO,t.stackSeatTransforms=VM,t.standardYieldPolicy=nT,t.stopFPSMeasure=Kp,t.straightSegmentEndpoints=Ck,t.straightSegmentMultiInbound=Pk,t.straightSegmentTopology=Tk,t.textBounds=YT,t.textTexture=VT,t.toThreeSide=Bd,t.topApproachFrame=KE,t.transferLog=rp,t.transferTracer=ep,t.uniformZ=Ho,t.unitFigurePartGeometry=kI,t.unknownTypesOf=_l,t.unregisterFigure=UO,t.unresolvedReasonOf=yl,t.updateDefaultFontFamily=Ri,t.updateTether=_p,t.useFigureComponent=yO,t.validate=IE,t.validateFlowGraph=Wk,t.validateSlotLayout=EM,t.version=OT,t.warn=Ns});
|
|
72
|
+
`,this.element)}catch(t){}}onchangeMinimized(){const{minimized:t}=this.state;t?this.setState("height",24):this.setState("height",this.get("height"))}}Ay=new WeakMap,uc.memoize(Cy.prototype,"bounds",!0),uc.register("container",Cy);const Oy=Math.sqrt(3),Py=2;function Iy(t,e,n,s,i){const o=5+i,r=n.x,a=n.y,c=s.x,l=s.y;if(Math.abs(r-c)>o&&Math.abs(a-l)>o){const n=(l-a)/(c-r),s=a-n*r;if(Math.abs(e-(n*t+s))>o)return!1}let h,d,u,p;return r>c?(d=r,h=c):(d=c,h=r),a>l?(p=a,u=l):(p=l,u=a),!(d+5<t)&&(!(h-5>t)&&(!(p+5<e)&&!(u-5>e)))}function Dy(t,e,n,s=2){for(let i=0;i<n.length-1;i++)if(Iy(t,e,n[i],n[i+1],s))return!0;return!1}function zy(t,e,n,s){if("arrow"!=t.slice(-5))return n;const i=Math.atan2(s.y-n.y,s.x-n.x),o=1.5*e;return{x:n.x+Math.cos(i)*o,y:n.y+Math.sin(i)*o}}function Ry(t,e,n){let{lineWidth:s=Py,strokeStyle:i="#000000",lineCap:o=!1,alpha:r=1,begin:a="none",end:c="none",beginSize:l="size5",endSize:h="size5"}=n;if(("none"!=a||"none"!=c)&&(s=Number(s)||Py,t.lineCap=o,t.lineWidth=s,t.strokeStyle=i,t.fillStyle=i,t.globalAlpha*=r,"none"!=a&&jy(t,e[0],e[1],s,a,$y(l,s)),"none"!=c)){const n=e.length;jy(t,e[n-1],e[n-2],s,c,$y(h,s))}}function jy(t,e,n,s,i,o){const{x:r,y:a}=e,c=Math.atan2(n.y-a,n.x-r);switch(t.beginPath(),t.translate(r,a),t.rotate(c),i){case"oval":t.ellipse(0,0,o.X,o.Y,0,0,2*Math.PI),t.fill();break;case"diamond":t.moveTo(-o.X,0),t.lineTo(0,-o.Y),t.lineTo(o.X,0),t.lineTo(0,o.Y),t.fill();break;case"arrow":t.moveTo(0,0),t.lineTo(Oy*o.X,-o.Y),t.lineTo(Oy*o.X,o.Y),t.fill();break;case"sharp-arrow":t.moveTo(0,0),t.lineTo(Oy*o.X,-o.Y),t.lineTo(-o.X/1.5+Oy*o.X,0),t.lineTo(Oy*o.X,o.Y),t.fill();break;case"open-arrow":t.moveTo(Oy*o.X+s,-o.Y),t.lineTo(s,0),t.lineTo(Oy*o.X+s,o.Y),t.stroke();break;case"cross":t.moveTo(-o.X,-o.Y),t.lineTo(o.X,o.Y),t.moveTo(o.X,-o.Y),t.lineTo(-o.X,o.Y),t.stroke()}t.rotate(-c),t.translate(-r,-a),t.closePath()}function $y(t,e){const n={X:0,Y:0};switch(e*=1.2,t){case"size1":n.X=e,n.Y=e;break;case"size2":n.X=1.5*e,n.Y=e;break;case"size3":n.X=2*e,n.Y=e;break;case"size4":n.X=e,n.Y=1.5*e;break;case"size5":default:n.X=1.5*e,n.Y=1.5*e;break;case"size6":n.X=2*e,n.Y=1.5*e;break;case"size7":n.X=e,n.Y=2*e;break;case"size8":n.X=1.5*e,n.Y=2*e;break;case"size9":n.X=2*e,n.Y=2*e}return n}const Ly="N",Fy="S",Ny="E",Hy="W";class By{constructor({component:t,anchor:e,position:n,self:s}){this.component=t,this._anchorName=e,this._position=n,this.self=s}get position(){const t=this.anchor;if(t){const{position:e}=t,n=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(n.x,n.y)}return this._position}set position({x:t,y:e}){this._position={x:t,y:e}}get anchor(){return this.component?.findAnchor(this._anchorName)}get direction(){const t=this.component.bounds,e=this.anchor;if(!e)return Ny;const n=e.position;return n.y<=t.top?Ly:n.y>=t.top+t.height?Fy:n.x<=t.left?Hy:Ny}get boundaryPosition(){const t=this.anchor;if(t){let{position:e}=t,n=0,s=0;switch(this.direction){case Fy:s=20;break;case Ly:s=-20;break;case Hy:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+s};const i=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(i.x,i.y)}}}class Gy extends uc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const s=t.get(n.component)||n.component;this.set(e,{...n,component:s})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._fromEnd=new By({component:s,fromto:"from",anchor:e,position:n,self:this})}return this._fromEnd}get from(){return this.getState("from")}set from(t){delete this._fromEnd,this.set("from",t)}get toEnd(){if(this.parent&&!this._toEnd){const{component:t,anchor:e,position:n}=this.getState("to")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._toEnd=new By({component:s,fromto:"to",anchor:e,position:n,self:this})}return this._toEnd}get to(){return this.getState("to")}set to(t){delete this._toEnd,this.set("to",t)}move({x:t,y:e},n){n&&(this.from={position:this._fromEnd?.position||this.getState("from")?.position||{x:0,y:0}},this.to={position:this._toEnd?.position||this.getState("to")?.position||{x:0,y:0}}),super.move({x:t,y:e})}render(t){const{begin:e="none",end:n="none",lineWidth:s,round:i=0}=this.state;let o=this.drawPath;Ry(t,o,this.state),t.beginPath();const r=zy(e,s,o[0],o[1]),a=zy(n,s,o[o.length-1],o[o.length-2]),c=o[0];o=[r,...o.slice(1,-1),a];let l={x:r.x,y:r.y};if(t.moveTo(r.x,r.y),o.length>=2&&zo(c)){const e=o[1],n=Lo(e,i),s=Math.sqrt((r.x-e.x)**2+(r.y-e.y)**2),a=0!==s?Math.atan2(r.x-e.x,r.y-e.y):0,l=Math.sin(a)*Math.min(n,s/2)+e.x,h=Math.cos(a)*Math.min(n,s/2)+e.y,d=Ro({x:r.x,y:r.y},{x:l,y:h},c.bulge);d&&t.arc(d.cx,d.cy,d.radius,d.startAngle,d.endAngle,d.clockwise)}for(let e=1;e<o.length;e++){const n=l;l=o[e];const s=o[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!s){t.lineTo(l.x,l.y);break}const r=Lo(l,i);let a=Math.sqrt((n.x-l.x)*(n.x-l.x)+(n.y-l.y)*(n.y-l.y)),c=0!==a?Math.atan2(n.x-l.x,n.y-l.y):0,h=Math.sin(c)*Math.min(r,a/2)+l.x,d=Math.cos(c)*Math.min(r,a/2)+l.y;const u=r>0||0!==a?{x:h,y:d}:l;a=Math.sqrt((s.x-l.x)*(s.x-l.x)+(s.y-l.y)*(s.y-l.y)),c=0!==a?Math.atan2(s.x-l.x,s.y-l.y):0,h=Math.sin(c)*Math.min(r,a/2)+l.x,d=Math.cos(c)*Math.min(r,a/2)+l.y;const p=r>0||0!==a?{x:h,y:d}:l;if(t.lineTo(u.x,u.y),r>0&&t.quadraticCurveTo(l.x,l.y,p.x,p.y),zo(l)){const e=Lo(s,i),n=Math.sqrt((l.x-s.x)**2+(l.y-s.y)**2),o=0!==n?Math.atan2(l.x-s.x,l.y-s.y):0,r=Math.sin(o)*Math.min(e,n/2)+s.x,a=Math.cos(o)*Math.min(e,n/2)+s.y,c=Ro({x:p.x,y:p.y},{x:r,y:a},l.bulge);c&&t.arc(c.cx,c.cy,c.radius,c.startAngle,c.endAngle,c.clockwise)}}this.drawStroke(t,void 0)}contains(t,e){const{lineWidth:n}=this.state;return Dy(t,e,this.drawPath,n)}get resizable(){return!1}get mutable(){return!0}get rotatable(){return!1}get path(){const{from:t,to:e}=this.state,{x1:n,y1:s,x2:i,y2:o}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:s},this.toEnd?.position||e?.position||{x:i,y:o}]}set path(t){const[e,n]=t,{from:s,to:i}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...s,position:e},to:{...i,position:n}})}get textBounds(){const t=this.drawPath;let e,n,s=0;for(let i=1;i<t.length;i++){const o=t[i-1],r=t[i],a=(o.x-r.x)*(o.x-r.x)+(o.y-r.y)*(o.y-r.y);a>s&&(s=Math.ceil(a),e=o,n=r)}let{paddingTop:i,paddingLeft:o,paddingRight:r,paddingBottom:a}=this.state;return a||=0,i||=0,o||=0,r||=0,{left:Math.min(e.x,n.x)+o,top:Math.min(e.y,n.y)+i,width:Math.max(Math.abs(e.x-n.x)-o-r,0),height:Math.max(Math.abs(e.y-n.y)-i-a,0)}}get decorators(){return this.app.isEditMode?["decotag"]:[]}}Gy.getTipNeckPos=zy,Gy.containedInPath=Dy,Gy.drawEndTips=Ry,uc.register("line",Gy);const Uy={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"angle",label:"start-angle",name:"startAngle",property:"startAngle"},{type:"angle",label:"end-angle",name:"endAngle",property:"endAngle"}],"value-property":"text"};class Vy extends(xm(pc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:s,ry:i,startAngle:o,endAngle:r,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(s),Math.abs(i),0,o||0,r||2*Math.PI,a),void 0!==o&&void 0!==r&&(t.lineTo(e,n),t.closePath())}get path(){const{cx:t,cy:e,rx:n,ry:s}=this.state;return[{x:t-n,y:e-s},{x:t+n,y:e-s},{x:t+n,y:e+s},{x:t-n,y:e+s}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2,rx:(n.x-e.x)/2,ry:(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s,rx:i,ry:o}=this.state,r=(t-n)/(2*i-.5),a=(e-s)/(2*o-.5);return r*r+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:s,rx:i,ry:o}=t.model,r=2*Math.PI*e,a=n+i*Math.cos(r),c=s+o*Math.sin(r);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:s,height:i}=t.bounds,o=e+s/2,r=n+i/2;return[{name:"TOP",position:{x:o,y:n}},{name:"RIGHT",position:{x:e+s,y:r}},{name:"BOTTOM",position:{x:o,y:n+i}},{name:"LEFT",position:{x:e,y:r}}]}(this)}get nature(){return Uy}}uc.memoize(Vy.prototype,"path",!1),uc.register("ellipse",Vy);const Wy={object:{fill:"rgba(180,180,180,0.18)",stroke:"#888888",icon:"?",label:"object"},transport:{fill:"rgba(100,180,255,0.18)",stroke:"#3a78c8",icon:"⇄",label:"transport"},facility:{fill:"rgba(160,140,220,0.18)",stroke:"#6b4ec8",icon:"◫",label:"facility"},vehicle:{fill:"rgba(120,200,140,0.18)",stroke:"#3a8c5e",icon:"⊙",label:"vehicle"},region:{fill:"rgba(220,200,100,0.18)",stroke:"#a0892a",icon:"▢",label:"region"},path:{fill:"rgba(200,140,160,0.18)",stroke:"#a0506a",icon:"⌐",label:"path"},"3d-asset":{fill:"rgba(255,180,80,0.18)",stroke:"#c87a2a",icon:"◈",label:"3D asset"}},Yy=[{type:"string",label:"placeholder-label",name:"placeholderLabel",description:'사용자에게 표시할 추가 라벨 (예: "Stocker A1")'},{type:"string",label:"hint",name:"placeholderHint",description:"구체화 시 참고 — 도면의 원본 식별자 / VLM 라벨 등"}];function qy(t,e,n,s,i){const{left:o,top:r,width:a,height:c}=e,l=Math.max(a,1),h=Math.max(c,1);t.save(),t.fillStyle=n.fill,t.fillRect(o,r,l,h),t.strokeStyle=n.stroke,t.lineWidth=1.5,t.setLineDash([4,3]),t.strokeRect(o,r,l,h),t.setLineDash([]),t.restore(),Math.min(l,h)>=24&&(t.save(),t.fillStyle=n.stroke,t.font=`bold ${Math.min(20,.4*Math.min(l,h))}px Arial`,t.textAlign="center",t.textBaseline="middle",t.fillText(n.icon,o+l/2,r+h/2),t.restore());const d=s?`${n.label}: ${s}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,o+l/2,r+h-4),t.restore()),i&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${i}`,o+l-4,r+4),t.restore())}const Xy={mutable:!1,resizable:!0,rotatable:!0,properties:[...Yy,{type:"placeholder-convert",label:"",name:"_convert"}],help:"scene/component/placeholder"};class Ky extends(mc(pc)){get nature(){return Xy}render(t){const{placeholderLabel:e,placeholderHint:n}=this.state;qy(t,this.bounds,Wy.object,e,n)}}uc.register("placeholder",Ky);const Jy=["placeholder"];function Qy(t,e=[]){return!!t&&(!!Jy.includes(t)||e.includes(t))}const Zy={ondragstart:function(t,e,n){n.mutatePath(null,function(n){n.splice(e+1,0,t)})},ondragmove:function(t,e,n){n.mutatePath(null,function(n){const s=n[e+1];n[e+1]={...s||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},tb={mutable:!0,resizable:!1,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/polygon"};class eb extends pc{is3dish(){return!0}get mutable(){return!0}get pathExtendable(){return!0}get cornerEditable(){return!0}get path(){return this.state.path??[]}set path(t){this.set("path",t)}contains(t,e){const n=this.path;let s=!1;return n.forEach((i,o)=>{const r=(o+n.length+1)%n.length,a=i.x,c=i.y,l=n[r].x,h=n[r].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}get controls(){const t=this.path;return t.map((e,n)=>{const s=t[n+1>=t.length?0:n+1];return{x:(e.x+s.x)/2,y:(e.y+s.y)/2,handler:Zy}})}get nature(){return tb}}uc.memoize(eb.prototype,"controls",!1),uc.register("polygon",eb);const nb=[];class sb extends(ql(eb)){constructor(t,e){super(t,e),this._components=[]}replaceRefids(t){this.components.forEach(e=>e.replaceRefids(t))}get showMoveHandle(){return!0}get showOverflow(){return!1}dispose(){this.components.slice().forEach(t=>t.dispose()),super.dispose()}isContainer(){return!0}containable(t){return t.isDescendible(this)}get hasTextProperty(){return!1}get components(){return this._components}get focusible(){return!0}get layout(){return xc.get(this.get("layout"))||Mc}reflow(){this.layout.reflow(this),this.components&&this.components.forEach(t=>{t.isContainer()&&t.reflow()})}get hierarchy(){const t=super.hierarchy;return this.components?.length&&(t.components=this.components.map(t=>t.hierarchy)),t}reparent(t,e={}){t&&t.parent!==this&&this.addComponent(t,{silent:!0})}addComponent(t,e=!1){const{ghost:n=!1,silent:s=!1}="boolean"==typeof e?{ghost:e}:e,i=t.parent;if(i){if(this===i)return;i.removeComponent(t,n||s)}const o=this._components.push(t)-1;s&&(t._silentAdd=!0),t.parent=this,t.added(this),n||s||this.trigger("add",this,t,o),t.delegate_on(this),s?(i&&this.root?._removeTraverse?.(t),this.trigger("add",this,t,o),t.trigger("added",this,t,o),delete t._silentAdd):n||t.trigger("added",this,t,o),this.root&&this.root.isReady&&t.invokeReady()}removeComponent(t,e=!1){const n=this._components.indexOf(t);-1!=n&&(this._components.splice(n,1),t.parent=null,t.removed(this),e||(this.trigger("remove",this,t),t.trigger("removed",this,t)),t.delegate_off(this))}insertComponentAt(t,e,n=!1){const s=t.parent;s&&s.removeComponent(t,n);const i=this._components.splice(0,e);this._components=i.concat(t,this._components),e=this._components.indexOf(t),t.parent=this,t.added(this),n||this.trigger("add",this,t,e),t.delegate_on(this),n||t.trigger("added",this,t,e)}add(t,e=!1){return t instanceof Array?(t.forEach(t=>{-1==this._components.indexOf(t)&&this.addComponent(t,e)}),this):this.add.call(this,[t],e)}remove(t,e=!1){return t instanceof Array?this._components?(t.forEach(t=>this.removeComponent(t,e)),this):this:this.remove.call(this,[t],e)}getAt(t){if(this._components)return this._components[t]}forEach(t,e){this._components&&this._components.forEach(t,e)}traverse(t,e){t.call(e,this),this._components&&this._components.forEach(n=>{n.isContainer()?n.traverse(t,e):t.call(e,n)})}indexOf(t){return(this._components||nb).indexOf(t)}size(){return(this._components||nb).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let s=this._components.splice(0,n);const i=this._components.splice(1);this._components=s.concat(i),t=Math.max(0,t),t=Math.min(t,this._components.length),s=this._components.splice(0,t),this._components=s.concat(e,this._components)}moveChildForward(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this._components[e]=this._components[e+1],this._components[e+1]=t)}moveChildBackward(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this._components[e]=this._components[e-1],this._components[e-1]=t)}moveChildToFront(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=n.concat(s,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=this._components.concat(n,s)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return Fa(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let s=this.components.length-1;s>=0;s--){const i=this.components[s].findAll(t,...e);i&&(n=n.concat(i))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return Fa(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const s=this.components[n].findFirst(t,...e);if(null!=s)return s}return t(this,...e)?this:void 0}}findById(t){return this.root.findAllById?.(t)?.[0]}findByRefid(t){return this.root.findByRefid?.(t)}capture(t,e,n){if(!this.app.isEditMode&&this.hidden)return!1;const s=this.fromParent(t,e);if(!this.contains(s.x,s.y))return!1;const i=this.bounds;s.x-=i.left,s.y-=i.top;const o=this.layout.capturables(this);for(let i=o.length-1;i>=0;i--){const r=o[i];let a;if(a="static"==r.position?r.capture(s.x,s.y,n):r.capture(t,e,n),a)return a}return this.capturable&&!n?.(this)&&this}capturePath(t,e){if(e){if(e.indexOf(this)>-1)return!1;for(let t=0;t<e.length;t++)if(!this.containable(e[t]))return!1}const n=[],{left:s,top:i,width:o,height:r}=this.bounds;for(let e=0;e<t.length;e++){const a=this.fromParent(t[e].x,t[e].y);if(a.x<s||a.x>s+o||a.y<i||a.y>i+r)return!1;a.x-=s,a.y-=i,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const s=a[t];if(!s.isContainer())continue;const i=s.capturePath(n,e);if(i)return i}return this.focusible&&this}render(t){"popup"!==this.position&&super.render(t)}postrender(t){if("popup"===this.position)return void super.postrender(t);const e=this.layout.drawables(this);if(e.length>0){let{left:n=0,top:s=0,width:i,height:o}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,s,i,o),t.clip(),t.closePath()),t.translate(n,s),e.forEach(e=>{const n=this.root?.transitionEffect;n?.isReparenting(e)||e.draw(this.position&&"static"!==this.position?t:this.getContext(e))}),t.translate(-n,-s),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>uc.memoize(sb.prototype,t,!1));const ib={ondragstart:function(t,e,n){n.mutatePath(null,function(n){n.splice(e,0,t)})},ondragmove:function(t,e,n){n.mutatePath(null,function(n){const s=n[e];n[e]={...s||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},ob={mutable:!1,resizable:!1,rotatable:!1,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/polyline"};class rb extends Gy{get pathExtendable(){return!0}get cornerEditable(){return!0}get path(){const{from:t,to:e}=this.state,{path:n}=this.state;return[this.fromEnd?.position||t?.position||n[0],...n.slice(1,-1),this.toEnd?.position||e?.position||n[n.length-1]]}set path(t){const{from:e,to:n}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...e,position:t[0]},to:{...n,position:t[t.length-1]},path:t})}get controls(){const t=this.path,e=[];for(let n=0;n<t.length-1;n++){const s=t[n],i=t[n+1];0==n&&e.push({x:s.x,y:s.y,handler:ib}),e.push({x:(s.x+i.x)/2,y:(s.y+i.y)/2,handler:ib}),n==t.length-2&&e.push({x:i.x,y:i.y,handler:ib})}return e}get nature(){return ob}}uc.register("polyline",rb);const ab={mutable:!1,resizable:!1,rotatable:!1,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/ortholine"};class cb extends Gy{get pathExtendable(){return!1}get drawPath(){const t=this.path[0],e=this.path[1],{component:n,direction:s,boundaryPosition:i=t}=this.fromEnd||{},{component:o,direction:r,boundaryPosition:a=e}=this.toEnd||{},c=[i,a],l=[];i&&l.push(i);let h,d=n?.bounds;d&&(h=n.toScene(d.left,d.top),h=this.transcoordT2P(h.x,h.y),d={...d,left:h.x,top:h.y});const u=d?{left:d.left-20,top:d.top-20,width:d.width+40,height:d.height+40}:{left:i.x,top:i.y,width:0,height:0};d=d||u;let p=o?.bounds;p&&(h=o.toScene(p.left,p.top),h=this.transcoordT2P(h.x,h.y),p={...p,left:h.x,top:h.y});const f=p?{left:p.left-20,top:p.top-20,width:p.width+40,height:p.height+40}:{left:a.x,top:a.y,width:0,height:0};p=p||f;const m=[u,f],g=u.left>f.left?f.left:u.left,y=u.top>f.top?f.top:u.top,b={left:g,top:y,width:u.left+u.width>f.left+f.width?u.left+u.width-g:f.left+f.width-g,height:u.top+u.height>f.top+f.height?u.top+u.height-y:f.top+f.height-y};let v,_,x,w,M,S,A,k,E,T,C=0,O=0;d.left+d.width<p.left?(w=0,M=1,E=s,T=r,v=(d.left+d.width+p.left)/2,C=p.left-v):p.left+p.width<d.left&&(w=1,M=0,E=r,T=s,v=(d.left+p.width+p.left)/2,C=d.left-v),d.top+d.height<p.top?(x=0,S=1,A=s,k=r,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,A=r,k=s,_=(d.top+p.height+p.top)/2,O=d.top-_);const P=[];if(v&&C>O){let t,e,n;switch(T){case Hy:switch(E){case Ny:P.push({x:v,y:c[w].y}),P.push({x:v,y:c[M].y});break;case Hy:t=m[w].top+m[w].height/2,e=t>c[M].y?Math.min(m[w].top,c[M].y):Math.max(m[w].top+m[w].height,c[M].y),P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:c[M].y});break;case Ly:case Fy:e=E===Fy?Math.max(c[w].y,c[M].y):Math.min(c[w].y,c[M].y),P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:c[M].y});break;default:return this.path}break;case Ny:switch(E){case Ny:e=c[w].y<c[M].y?Math.min(m[M].top,c[w].y):Math.max(m[M].top+m[M].height,c[w].y),n=e;break;case Hy:e=void 0!==_?_:c[w].y<c[M].y?b.top-.5*C:b.top+b.height+.5*C,n=e;break;case Fy:e=void 0!==_?Math.max(_,c[w].y):b.top+b.height,n=e;break;case Ly:e=_?Math.min(_,m[w].top):b.top,n=e;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;case Fy:switch(E){case Ny:e=c[w].y,n=c[w].y>c[M].y?c[w].y:m[M].top+m[M].height;break;case Hy:e=_?Math.max(_,m[M].top+m[M].height):b.top+b.height,n=e;break;case Fy:e=b.top+b.height,n=e;break;case Ly:e=_?Math.min(_,m[w].top):m[w].top,n=_?Math.max(_,m[M].top+m[M].height):m[M].top+m[M].height;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;case Ly:switch(E){case Ny:e=c[w].y,n=c[w].y<c[M].y?c[w].y:m[M].top;break;case Hy:e=_?Math.min(_,m[M].top):b.top,n=e;break;case Fy:e=void 0!==_?Math.max(_,c[w].y):c[w].y,n=void 0!==_?Math.min(_,c[M].y):c[M].y;break;case Ly:e=b.top,n=e;break;default:return this.path}P.push({x:c[w].x,y:e}),P.push({x:v,y:e}),P.push({x:v,y:n}),P.push({x:c[M].x,y:n});break;default:return this.path}l.push(...0===w?P:P.reverse())}else if(_){let t,e,n;switch(k){case Ly:switch(A){case Fy:P.push({x:c[x].x,y:_}),P.push({x:c[S].x,y:_});break;case Ly:t=m[x].left+m[x].width/2,e=t>c[S].x?Math.min(m[x].left,c[S].x):Math.max(m[x].left+m[x].width,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;case Hy:e=Math.min(c[x].x,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;case Ny:e=Math.max(c[x].x,c[S].x),P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:c[S].x,y:_});break;default:return this.path}break;case Fy:switch(A){case Hy:e=b.left,n=e;break;case Ny:e=void 0!==v?Math.max(v,c[x].x):b.left+b.width,n=e;break;case Ly:e=void 0!==v?v:c[x].x<c[S].x?b.left-.5*O:b.left+b.width+.5*O,n=e;break;case Fy:e=c[x].x,n=c[x].x<c[S].x?Math.min(m[S].left,c[x].x):Math.max(m[S].left+m[S].width,c[x].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;case Ny:switch(A){case Hy:e=void 0!==v?Math.min(v,c[x].x):c[x].x,n=void 0!==v?Math.max(v,c[S].x):c[S].x;break;case Ny:e=b.left+b.width,n=e;break;case Ly:e=void 0!==v?Math.max(v,c[S].x):b.left+b.width,n=e;break;case Fy:e=c[x].x,n=Math.max(m[S].left+m[S].width,c[x].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;case Hy:switch(A){case Hy:e=b.left,n=e;break;case Ny:e=void 0!==v?Math.max(v,c[x].x):c[x].x,n=void 0!==v?Math.min(v,c[S].x):c[S].x;break;case Ly:e=b.left,n=e;break;case Fy:e=c[x].x<c[S].x?Math.min(m[S].left,c[x].x):c[x].x,n=Math.min(e,c[S].x);break;default:return this.path}P.push({x:e,y:c[x].y}),P.push({x:e,y:_}),P.push({x:n,y:_}),P.push({x:n,y:c[S].y});break;default:return this.path}l.push(...0===x?P:P.reverse())}else{let t,e;switch(s){case Ly:switch(r){case Ly:e=b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Fy:t=b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:b.top+b.height}),l.push({x:c[1].x,y:b.top+b.height});break;case Ny:t=c[1].y<c[0].y&&c[1].x<c[0].x?c[0].x:b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;case Hy:t=b.left,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;default:return this.path}break;case Fy:switch(r){case Ly:t=b.left+b.width,l.push({x:t,y:c[0].y}),l.push({x:t,y:b.top}),l.push({x:c[1].x,y:b.top});break;case Fy:case Ny:case Hy:e=b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;default:return this.path}break;case Hy:switch(r){case Ly:t=c[0].x>c[1].x&&c[0].y<c[1].y?c[1].x:b.left,e=c[0].x>c[1].x&&c[0].y<c[1].y?c[1].y:Math.min(b.top,c[0].y),l.push({x:t,y:c[0].y}),l.push({x:t,y:e}),l.push({x:c[1].x,y:e});break;case Fy:t=b.left,e=Math.max(b.top+b.height,c[0].y),l.push({x:t,y:c[0].y}),l.push({x:t,y:e}),l.push({x:c[1].x,y:e});break;case Ny:t=b.left+b.width,l.push({x:c[0].x,y:b.top}),l.push({x:t,y:b.top}),l.push({x:t,y:c[1].y});break;case Hy:t=b.left,l.push({x:t,y:c[0].y}),l.push({x:t,y:c[1].y});break;default:return this.path}break;case Ny:switch(r){case Ly:e=c[0].y<c[1].y&&c[0].x<c[1].x?c[0].y:b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Fy:e=c[0].y>c[1].y&&c[0].x<c[1].x?c[0].y:b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case Ny:case Hy:e=b.top+b.height,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;default:return this.path}break;default:return this.path}}return a&&l.push(a),[t,...l,e].filter((t,e,n)=>{if(0===e)return!0;const s=n[e-1];return t.x!==s.x||t.y!==s.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const s=n[e-1],i=n[e+1];return!(t.x===s.x&&t.x===i.x||t.y===s.y&&t.y===i.y)})}get nature(){return ab}}uc.register("ortholine",cb);const lb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"image-selector",label:"image-src",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:"$base_url",defaultStorage:"scene-image",storageFilters:{type:Array,value:[{name:"category",value:"image"}]},useUpload:!0}},{type:"select",label:"cross-origin",name:"crossOrigin",property:{options:["","anonymous","use-credentials"]}}],"value-property":"src",help:"scene/component/image-view"};class hb extends(mc(pc)){static get noimage(){return hb.NOIMAGE||(hb.NOIMAGE=new Image,hb.NOIMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABIBAMAAAD7Se1QAAAAIVBMVEUAAABHcEwBAQEREREBAQEEBAQGBgYLCwsDAwMDAwMICAi6HF9tAAAAC3RSTlNNAEAERiMYCS41Eac10lYAAAEgSURBVHhe7dY9asQwEAXgh7DNertNiJy48pIitY3SB7bYdk0ukL1BDDmA9gZecoH4pmFQ3MQayUMguPBrNPD4wD9TCMvJmt3M/AtYwXOlXiWgqADVCUBD46MAnGhMBaCiUQmAm8VA/Eh/eWl9Fn5WcxD+OLuRrUYJDKLluwH2InACUgkoACSdADxQc50Bytadb9RkM0CT13TcvlCT1HFg8UTHvasuUVACCa3El6u2UdD8LFTlKhUFFgA+d3dj10aABkUN72N3jAADCrJq7PIIsPidcxBoTHIIAjMFmyCwmGYIAA1P9gFgfCANAOsDSccCDW+uLDB+kLGg94OkZoAGkwsDDAe2DOg5oPxAg03rBR88OHpBz4N8UVeHFSwma74BTW6Ge4rIRa4AAAAASUVORK5CYII="),hb.NOIMAGE}dispose(){super.dispose(),this._offcanvas=null,this._image=null}render(t){const{left:e,top:n,width:s,height:i,isGray:o=!1,alpha:r=1,src:a}=this.state;if(this.prepareIf(!this._image&&a),t.beginPath(),t.globalAlpha*=r,this._image&&this._image.complete)if(o&&this._offcanvas)t.drawImage(this._offcanvas,e,n,s,i);else try{t.drawImage(this._image,e,n,s,i)}catch(o){t.drawImage(hb.noimage,e,n,s,i)}else!this.app.isViewMode&&t.drawImage(hb.noimage,e,n,s,i)}get nature(){return lb}get hasTextProperty(){return!1}async ready(){await super.ready();const{src:t}=this.state;if(!this._image&&t){const e=this.root?.app?.loadTracker;if(e){const n=new Promise((t,e)=>{this.prepare(()=>t(),t=>e(t))});e.track(`image:${t}`,"image",t,n)}else this.prepareIf(!0)}}prepare(t,e){const{src:n,crossOrigin:s}=this.state;if(n){this._image=new Image;try{s&&(this._image.crossOrigin=s),this._image.src=this.app.url(n)||""}catch(t){return void e(t)}this._image.onload=()=>{if(this.get("isGray")){const t=this._image.width,e=this._image.height;this._offcanvas=uc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const s=function(t,e,n){let s;try{s=t.getImageData(0,0,e,n)}catch(t){return Fs("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const i=s.data;for(let t=0;t<e*n*4;t+=4){const e=i[t],n=i[t+1],o=i[t+2],r=Math.floor((e+n+o)/3);s.data[t]=r,s.data[t+1]=r,s.data[t+2]=r}return s}(n,t,e);n.putImageData(s,0,0)}t(this)},this._image.onerror=t=>{this._image&&!this._image.currentSrc&&(this._image=null),e(t)}}else t(this)}get src(){return this.get("src")}set src(t){this.set("src",t)}onchange(t,e){(t.hasOwnProperty("src")||t.hasOwnProperty("isGray"))&&(this._offcanvas=null,this._image=null,this.prepareIf(t.src))}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("image/"))return void(this.src=e[n])}}uc.register("image-view",hb);class db extends(Sy(mc(uc))){is3dish(){return!0}prerender(){}}var ub,pb,fb={},mb={},gb={};function yb(){if(pb)return mb;pb=1,Object.defineProperty(mb,"__esModule",{value:!0});var t=function(){if(ub)return gb;ub=1,Object.defineProperty(gb,"__esModule",{value:!0});var t=function(){function t(){}return t.bitsToNum=function(t){return t.reduce(function(t,e){return 2*t+e},0)},t.byteToBitArr=function(t){for(var e=[],n=7;n>=0;n--)e.push(!!(t&1<<n));return e},t.lzwDecode=function(t,e){for(var n,s,i=0,o=function(t){for(var n=0,s=0;s<t;s++)e.charCodeAt(i>>3)&1<<(7&i)&&(n|=1<<s),i++;return n},r=[],a=1<<t,c=a+1,l=t+1,h=[],d=function(){h=[],l=t+1;for(var e=0;e<a;e++)h[e]=[e];h[a]=[],h[c]=null};;)if(s=n,(n=o(l))!==a){if(n===c)break;if(n<h.length)s!==a&&h.push(h[s].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[s].concat(h[s][0]))}r.push.apply(r,h[n]),h.length===1<<l&&l<12&&l++}else d();return r},t}();return gb.SuperGifUtils=t,gb}(),e=function(){function e(t,e){this.stream=t,this.handler=e}return e.prototype.parseCT=function(t){for(var e=[],n=0;n<t;n++)e.push(this.stream.readBytes(3));return e},e.prototype.readSubBlocks=function(){var t,e;e="";do{t=this.stream.readByte(),e+=this.stream.read(t)}while(0!==t);return e},e.prototype.parseHeader=function(){var e={};if(e.sig=this.stream.read(3),e.ver=this.stream.read(3),"GIF"!==e.sig)throw new Error("Not a GIF file.");e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.gctFlag=n.shift(),e.colorRes=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.sorted=n.shift(),e.gctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.bgColor=this.stream.readByte(),e.pixelAspectRatio=this.stream.readByte(),e.gctFlag&&(e.gct=this.parseCT(1<<e.gctSize+1)),this.handler.hdr&&this.handler.hdr(e)},e.prototype.parseExt=function(e){var n=this;switch(e.label=this.stream.readByte(),e.label){case 249:e.extType="gce",function(e){n.stream.readByte();var s=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=s.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(s.splice(0,3)),e.userInput=s.shift(),e.transparencyGiven=s.shift(),e.delayTime=n.stream.readUnsigned(),e.transparencyIndex=n.stream.readByte(),e.terminator=n.stream.readByte(),n.handler.gce&&n.handler.gce(e)}(e);break;case 254:e.extType="com",function(t){t.comment=n.readSubBlocks(),n.handler.com&&n.handler.com(t)}(e);break;case 1:e.extType="pte",function(t){n.stream.readByte(),t.ptHeader=n.stream.readBytes(12),t.ptData=n.readSubBlocks(),n.handler.pte&&n.handler.pte(t)}(e);break;case 255:e.extType="app",function(t){n.stream.readByte(),t.identifier=n.stream.read(8),t.authCode=n.stream.read(3),"NETSCAPE"===t.identifier?function(t){n.stream.readByte(),t.unknown=n.stream.readByte(),t.iterations=n.stream.readUnsigned(),t.terminator=n.stream.readByte(),n.handler.app&&n.handler.app.NETSCAPE&&n.handler.app.NETSCAPE(t)}(t):function(t){t.appData=n.readSubBlocks(),n.handler.app&&n.handler.app[t.identifier]&&n.handler.app[t.identifier](t)}(t)}(e);break;default:e.extType="unknown",function(t){t.data=n.readSubBlocks(),n.handler.unknown&&n.handler.unknown(t)}(e)}},e.prototype.parseImg=function(e){e.leftPos=this.stream.readUnsigned(),e.topPos=this.stream.readUnsigned(),e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.lctFlag&&(e.lct=this.parseCT(1<<e.lctSize+1)),e.lzwMinCodeSize=this.stream.readByte();var s=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,s),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),s=t.length/e,i=function(s,i){var o=t.slice(i*e,(i+1)*e);n.splice.apply(n,[s*e,e].concat(o))},o=[0,4,2,1],r=[8,8,4,2],a=0,c=0;c<4;c++)for(var l=o[c];l<s;l+=r[c])i(l,a),a++;return n}(e.pixels,e.width)),this.handler.img&&this.handler.img(e)},e.prototype.parseBlock=function(){var t={};switch(t.sentinel=this.stream.readByte(),String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this.handler.eof&&this.handler.eof(t);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&setTimeout(this.parseBlock.bind(this),0)},e.prototype.parse=function(){this.parseHeader(),setTimeout(this.parseBlock.bind(this),0)},e}();return mb.SuperGifParser=e,mb}var bb,vb,_b={};var xb=function(){if(vb)return fb;vb=1,Object.defineProperty(fb,"__esModule",{value:!0});var t=yb(),e=function(){if(bb)return _b;bb=1,Object.defineProperty(_b,"__esModule",{value:!0});var t=function(){function t(t){this.data=t,this.position=0}return t.prototype.readByte=function(){if(this.position>=this.data.length)throw new Error("Attempted to read past end of stream.");return this.data instanceof Uint8Array?this.data[this.position++]:255&this.data.charCodeAt(this.position++)},t.prototype.readBytes=function(t){for(var e=[],n=0;n<t;n++)e.push(this.readByte());return e},t.prototype.read=function(t){for(var e="",n=0;n<t;n++)e+=String.fromCharCode(this.readByte());return e},t.prototype.readUnsigned=function(){var t=this.readBytes(2);return(t[1]<<8)+t[0]},t}();return _b.SuperGifStream=t,_b}(),n=function(){function n(t,e){var n=this;for(var s in this.gifImgElement=t,this.options={autoPlay:!0},this.loading=!1,this.ready=!1,this.transparency=null,this.delay=null,this.disposalMethod=null,this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,this.playing=!0,this.forward=!0,this.ctxScaled=!1,this.frames=[],this.frameOffsets=[],this.initialized=!1,this.currentFrameIndex=-1,this.iterationCount=0,this.stepping=!1,this.handler={hdr:this.withProgress(this.doHdr.bind(this)),gce:this.withProgress(this.doGCE.bind(this)),com:this.withProgress(this.doNothing.bind(this)),app:{NETSCAPE:this.withProgress(this.doNothing.bind(this))},img:this.withProgress(this.doImg.bind(this)),eof:function(){n.pushFrame(),n.canvas.width=n.hdr.width*n.getCanvasScale(),n.canvas.height=n.hdr.height*n.getCanvasScale(),n.playerInit(),n.loading=!1,n.ready=!0,n.loadCallback&&n.loadCallback(n.gifImgElement)}},e)this.options[s]=e[s];this.onEndListener=e.onEnd,this.loopDelay=e.loopDelay||0,this.overrideLoopMode=null!=e.loopMode?e.loopMode:"auto",this.drawWhileLoading=null==e.drawWhileLoading||e.drawWhileLoading}return n.prototype.init=function(){var t=this.gifImgElement.parentNode,e=document.createElement("div");this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"),this.tmpCanvas=document.createElement("canvas"),e.className=this.options.enclosingClass||"super-gif",e.appendChild(this.canvas),t&&(t.insertBefore(e,this.gifImgElement),t.removeChild(this.gifImgElement)),this.initialized=!0},n.prototype.loadSetup=function(t){return!this.loading&&(t&&(this.loadCallback=t),this.loading=!0,this.frames=[],this.clear(),this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,!0)},n.prototype.completeLoop=function(){this.onEndListener&&this.onEndListener(this.gifImgElement),this.iterationCount++,!1!==this.overrideLoopMode||this.iterationCount<0?this.doStep():(this.stepping=!1,this.playing=!1)},n.prototype.doStep=function(){if(this.stepping=this.playing,this.stepping){this.stepFrame(1);var t=10*this.frames[this.currentFrameIndex].delay;t||(t=100),0===this.getNextFrameNo()?(t+=this.loopDelay,setTimeout(this.completeLoop.bind(this),t)):setTimeout(this.doStep.bind(this),t)}},n.prototype.step=function(){this.stepping||setTimeout(this.doStep.bind(this),0)},n.prototype.putFrame=function(){var t;this.currentFrameIndex=parseInt(this.currentFrameIndex.toString(),10),this.currentFrameIndex>this.frames.length-1&&(this.currentFrameIndex=0),this.currentFrameIndex<0&&(this.currentFrameIndex=0),t=this.frameOffsets[this.currentFrameIndex],this.tmpCanvas.getContext("2d").putImageData(this.frames[this.currentFrameIndex].data,t.x,t.y),this.canvasContext.globalCompositeOperation="copy",this.canvasContext.drawImage(this.tmpCanvas,0,0)},n.prototype.playerInit=function(){this.loadErrorCause||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.options.autoPlay?this.step():(this.currentFrameIndex=0,this.putFrame()))},n.prototype.clear=function(){this.transparency=null,this.delay=null,this.lastDisposalMethod=this.disposalMethod,this.disposalMethod=null,this.frame=null},n.prototype.parseStream=function(e){try{new t.SuperGifParser(e,this.handler).parse()}catch(t){this.handleError("parse")}},n.prototype.setSizes=function(t,e){this.canvas.width=t*this.getCanvasScale(),this.canvas.height=e*this.getCanvasScale(),this.tmpCanvas.width=t,this.tmpCanvas.height=e,this.tmpCanvas.style.width=t+"px",this.tmpCanvas.style.height=e+"px",this.tmpCanvas.getContext("2d").setTransform(1,0,0,1,0,0)},n.prototype.drawError=function(){this.canvasContext.fillStyle="black",this.canvasContext.fillRect(0,0,this.hdr.width,this.hdr.height),this.canvasContext.strokeStyle="red",this.canvasContext.lineWidth=3,this.canvasContext.moveTo(0,0),this.canvasContext.lineTo(this.hdr.width,this.hdr.height),this.canvasContext.moveTo(0,this.hdr.height),this.canvasContext.lineTo(this.hdr.width,0),this.canvasContext.stroke()},n.prototype.handleError=function(t){this.loadErrorCause=t,this.hdr={width:this.gifImgElement.width,height:this.gifImgElement.height},this.frames=[],this.drawError()},n.prototype.doHdr=function(t){this.hdr=t,this.setSizes(this.hdr.width,this.hdr.height)},n.prototype.doGCE=function(t){this.pushFrame(),this.clear(),this.transparency=t.transparencyGiven?t.transparencyIndex:null,this.delay=t.delayTime,this.disposalMethod=t.disposalMethod},n.prototype.pushFrame=function(){this.frame&&(this.frames.push({data:this.frame.getImageData(0,0,this.hdr.width,this.hdr.height),delay:this.delay}),this.frameOffsets.push({x:0,y:0}))},n.prototype.doImg=function(t){var e=this;this.frame||(this.frame=this.tmpCanvas.getContext("2d"));var n=this.frames.length,s=t.lctFlag?t.lct:this.hdr.gct;n>0&&(3===this.lastDisposalMethod?null!==this.disposalRestoreFromIdx?this.frame.putImageData(frames[this.disposalRestoreFromIdx].data,0,0):this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height):this.disposalRestoreFromIdx=n-1,2===this.lastDisposalMethod&&this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height));var i=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(i.data[4*n+0]=s[t][0],i.data[4*n+1]=s[t][1],i.data[4*n+2]=s[t][2],i.data[4*n+3]=255)}),this.frame.putImageData(i,t.leftPos,t.topPos),this.ctxScaled||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.ctxScaled=!0),this.drawWhileLoading&&(this.canvasContext.drawImage(this.tmpCanvas,0,0),this.drawWhileLoading=this.options.autoPlay),this.lastImg=t},n.prototype.doNothing=function(){},n.prototype.withProgress=function(t){return function(e){t(e)}},n.prototype.getNextFrameNo=function(){var t=this.forward?1:-1;return(this.currentFrameIndex+t+this.frames.length)%this.frames.length},n.prototype.stepFrame=function(t){this.currentFrameIndex=this.currentFrameIndex+t,this.putFrame()},n.prototype.getCanvasScale=function(){return this.options.maxWidth&&this.hdr&&this.hdr.width>this.options.maxWidth?this.options.maxWidth/this.hdr.width:window.devicePixelRatio||1},n.prototype.play=function(){this.playing=!0,this.step()},n.prototype.pause=function(){this.playing=!1},n.prototype.isPlaying=function(){return this.playing},n.prototype.getCanvas=function(){return this.canvas},n.prototype.isLoading=function(){return this.loading},n.prototype.isReady=function(){return this.ready},n.prototype.isAutoPlay=function(){return this.options.autoPlay},n.prototype.getLength=function(){return this.frames.length},n.prototype.getCurrentFrame=function(){return this.currentFrameIndex},n.prototype.moveTo=function(t){this.currentFrameIndex=t,this.putFrame()},n.prototype.loadURL=function(t,n){var s=this;if(this.loadSetup(n)){var i=new XMLHttpRequest;i.open("GET",t,!0),"overrideMimeType"in i?i.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in i?i.responseType="arraybuffer":i.setRequestHeader("Accept-Charset","x-user-defined"),i.onloadstart=function(){s.initialized||s.init()},i.onload=function(){if(200===i.status){var t=i.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){s.parseStream(n)},0)}else s.handleError("xhr - response")},i.onerror=function(){s.handleError("xhr")},i.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return fb.SuperGif=n,fb}();const wb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"image-selector",label:"src",name:"src"},{type:"checkbox",label:"play",name:"play"}],"value-property":"src",help:"scene/component/gif-view"};class Mb extends db{async oncreate_element(t){const{src:e,play:n}=this.state;this.onchangesrc(e),this.onchangeplay(n)}buildImg(){const t=this.element;if(!t)return document.createElement("img");t.replaceChildren();const e=document.createElement("img");return e.style.width="100%",e.style.height="100%",t.appendChild(e),e}onchange(t,e){super.onchange(t,e),"src"in t&&this.onchangesrc(t.src),"play"in t&&this.onchangeplay(t.play)}setElementProperties(t){}onchangeplay(t){const e=this._superGif;e&&e.isReady()&&(t?e.play():e.pause())}onchangesrc(t){const e=this.buildImg();t||(t="data:image/gif;base64,R0lGODlhYABIAPcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4ODg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEhISIiIiMjIyQkJCUlJSYmJicnJygoKCkpKSoqKisrKywsLC0tLS4uLi8vLzAwMDExMTIyMjMzMzQ0NDU1NTY2Njc3Nzg4ODk5OTo6Ojs7Ozw8PD09PT4+Pj8/P0BAQEFBQUJCQkNDQ0REREVFRUZGRkdHR0hISElJSUpKSktLS0xMTE1NTU5OTk9PT1BQUFFRUVJSUlNTU1RUVFVVVVZWVldXV1hYWFlZWVpaWltbW1xcXF1dXV5eXl9fX2BgYGFhYWJiYmNjY2RkZGVlZWZmZmdnZ2hoaGlpaWpqamtra2xsbG1tbW5ubm9vb3BwcHFxcXJycnNzc3R0dHV1dXZ2dnd3d3h4eHl5eXp6ent7e3x8fH19fX5+fn9/f4CAgIGBgYKCgoODg4SEhIWFhYaGhoeHh4iIiImJiYqKio+Pj5iYmKCgoKampqurq66urrCwsLGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrOzs7S0tLa2tre3t7m5ubu7u7+/v8DAwMHBwcPDw8XFxcfHx8vLy8/Pz9LS0tXV1dfX193d3eTk5Onp6fj4+Pz8/P7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v///////////////////////////////////////////////////////////////////////////////yH5BAkAAPUAIf47R2VuZXJhdGVkIGJ5IGpzZ2lmIChodHRwczovL2dpdGh1Yi5jb20vYW50aW1hdHRlcjE1L2pzZ2lmLykALAAAAABgAEgAAAj+AGcJHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmypMmR9VKqXMmypcuXMGPKnJkSIs2bOHPqZGlzp8+fQOv1DEq0KMyhRpMmRaq0KVCmTqPmhCq1qkyqLrFRSyYwGTVsVo1iZXmNa8Fk18ISHasSm1mDycCq/ck2JTWF1ObSfTjz7cFken3WFbow8M7BDA3rHOwXruKpfGXeTZg3qDVrUge7RRg3KLZjx+Q2HVyvLNy0QaMJjBaVdD2tZr2K/mmNIObRkR+n9AsYt0Pddg1WXppb8bWDx1CLLW74GcJnSl3TtDY8Zu2Et4tKl7n52eyWnxXvhl7+26jqrspbnlfIWjtz2gWPZV95neH8veU9NxZYfbfD3kFt99J6Bnmn0mQO9XfYezrVxxlmx0GUXIAM4hSeffsxBN1TFd5E4Ef3QZbfTg6CNJ5gHXJ3TEntLThiTh+KFCJNAqZU4kgAitjQTheepOBMNcZI0oQ6JpbTjSZtiNN2PZ400IxHpdiSc07G911M0iFZZYtAStnWilUeBGVLrlEZpmM0elmPlmfO8iOZXl4DZpsGEYmll2bSWWCXLwJXVY1+urhjoGEBSuiSah6K36CKtpZoo4s9CimielZq6aWYZqrpppx26umnoIZ6UkAAOw=="),e.src=t,e.setAttribute("rel:animated_src",t),e.setAttribute("rel:auto_play",String(0)),this._superGif=new xb.SuperGif(e,{autoPlay:!1}),this._superGif.init(),this.element&&Array.from(this.element.children).forEach(t=>{t.style.width="100%",t.style.height="100%"});const n=this._superGif.getCanvas();n.style.width="100%",n.style.height="100%",this._superGif.load(()=>{setTimeout(()=>{this._superGif.moveTo(0),this.play&&this._superGif.play()},100)})}ondropfile(t,e){for(let n=0;n<t.length;n++)if(/\.gif$/.test(t[n].name))return void(this.src=e[n])}get src(){return this.getState("src")}set src(t){this.set("src",t)}get play(){return this.getState("play")}set play(t){this.setState("play",t)}get nature(){return wb}get tagName(){return"div"}}uc.register("gif-view",Mb);const Sb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"attachment-selector",label:"src",name:"src",property:{category:"audio"}},{type:"checkbox",label:"started",name:"started"},{type:"checkbox",label:"loop",name:"loop"}],"value-property":"src",help:"scene/component/audio"};class Ab extends(mc(pc)){static get image(){return Ab.IMAGE||(Ab.IMAGE=new Image,Ab.IMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAMAAAC3Ycb+AAAAP1BMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACzJYIvAAAAFHRSTlMA8BAwgNBgQKB/wCBwUJDg37CvXyUlBK8AABFYSURBVHja7NsBkqIwFIThTiAQgyBq3/+sm6p1tnamZkaTMhJJf1f4S/JeEIiIiIiIiIiIiIiIiEhD7Hg4BH84TpAKjJ4f3NFCtjVd+InXz2RTs+FXlxGylYHfcVfIJmb+YFWSLUyGVJKKBJJKUo+Rd6w63l/qzLuCkryO5fe0l2xk5mMWbe+v0fNBRqf7S3je6CipQ2ACr+dWcYEpzBFS1plpguatsnomMgdIQSOTuQ5SjmE6/UgK8szgdJIUM/FG41YlFmYJ2kkKsY5ZzAwBurHDk3WGeRY0bvYrGa1+rqNI22f7dS32ZnUK1GMr0eSK3mEc9dhKMxp+ZTo8kT2emOXS5LQ1kCxbJBocSd2k5PaIjMVzjWcdJPk9ooBnmzx1t5XbIxqBKpJ4NGTgzwKiGpK4do72gb+ZUMIYtCPm9WCPMsYTE5k2hq2ZvzujlCE1iRmwf3dvmRyKsT0T7b9I7HEPCpqCiqT2IIqaT1pI0noQZdlFC8l/PbYPAnRORT56VBEE6FXkb49agmByKhJ71BME6FsvEntUFQTdqekisUdlQWCXhovEHtUFAWbTapHYo8YgmFybO3vsUWcQYGmxSOxRbRAMprkisUfFQVKmrX18sxt7VB0ENjT1xir2qDxIwkFi3v89e+xRfxAMzfzzIfZ4hyAYDR9zwVuLPd4jCDrTwoLYGb5LEFi3/+E3rweR6urX20c/Fvls2Pvwm9mDSGIPhv8YPyGf3/eo9Ye7O8B2FIShAAooakEttex/rbODad5/yTHIAjqn505IQPv+Xz06dz+4VXORHEZcgAcB8updM8F6e25jBzwIkE07l+x8amMnPDp6nsNJ+BoZ7Q6F8egqAda9VEuRNlZjBzwYkMskdXR73okd8GBAJiKYjBcZKKqG9OiKDbgdfxJ5VhsBPDiQZhaouD3p4hfw4EAmwxisz3MSHwAPEmQ1TB1N+SmXWoAHC7JbZsWl/IxLLcCDBplNo3lrfMLsmwAPGmShAxX5/1vOEzjEz3iyfQ/hI36W4TctsUesOAifPdrQg8M++KYl95iCBkjI1r8634betBAPHZDTPFAmD3zLiHgogVTziMsahz0eIh5aIGHGRSJ2mFtHPR4iHhQIP2UvWGMf8wk74qEIEib7rLjPiBfxiAcCwp8V+Nae3uMdRhAPDIR/J5f/Q2DTcC+hIB7qIGEq3Ti9bx+sryMeAAgS70OK8G2kBD8L8QBAoLWU3g3vUVIc6D0txAMAsY+4jBWowXHO64gHBGKfYJ2T5qY1BxcL98BB+PQ+XiS9xxh9EQ8ChA6C5UXWIUoE9MBB8LVHQoS7ib8/dRn3sAcJ6bQRSdH96RDxIEH4QEX+AHF4LxHEAwUh12xyr1V8lwjiQYDYF8kuf1jluUQQDwrEvkhW8Wc6LhHUgwfhi4QPlHm7LRHawx4kpE191Dq8lgjhAYDQa1cftYrPEiE8OJDb40uqyzdQCA8WhAzL4G/PT4c3WrgHD2IfllGl53V37zsgHg5ApPNvVvq4Fn4spx4oiH1W3CwtEV+PDhEPJyBSkVX4aa7emkM83ICEKWpGM7wdvYCCeDgCEYpcwhLxczhEPFyBCEUWnRL5T6X59SBASBF+9l28TL5F7uEORCZyCUvEx+S7yT0cgoRVb9JaXLR1qUdfgksQ0fTbgmhFB20d8HAKEha14+F8f1sHPNyCiL6EqK+n20/rgIdjkFC0Ho1s6Gndvcc9ICkr/ey8/rHO6vp9KawL8DAFOV6l9Fyub7IbflsCag1qRfVsXWvxHjxIejU+BHZV6uvHD1XiEb++Bw8i+dNd+Wv0eCQmhcPhRPwUUt2DB5G1sfa1aeyzAuyJj9x2HjyIdKzIKw5SI14ieFtvo3kIQERj3lVhkUOnRD7AnjV5369QkAOJZeCH+Jh41xOLs73dQwAifY6dpxCCbjTDzLf1Bm1Y93tAIDOWXcLPvrHyr2hVoEAceEAgDQzB4jetk0/c2OXRHB48EJCpa4dgpYh2ETxtrshz7zx4ICCzfuTSDn8p/EOS9OTjwgMB+cABP3yWYuOPIofs33LigYCULlpZNXJppVU30Vf14kGAUCLijf1D71lN9FW9eFiA9KgZ8FPpPUsSnufGA+8hvAg2Kpz0nrX//qp+PIgpC3i6xJRITOye9fn1VT15ICCrVlQG5rywo0H8x965bVkNwmCYQ2kR6Gmb939WXV65dFnI/tPdjPBfO7XMN4EkTUJtqZp4sCJ1+8jwkhMu0KpMxFXFA8hlVfQSMxGH5mDK1VKV8QCyvTVtUiYyo7V358VStfGoAEFMhGYhEwloxZy9WKo2Hjwg5iSOvFDXeUYd33+PuVfHgwnEBWLocDJp+IIa2fyvperjwQRiXCKGosyXqoA+YfsIELuYu4HAt+msMknfDK4jfQJIzOZ2IPAQWJtFOhQKivR2IDZ6Awis7V0iLxqBI7uEZo19dakTogLSwKvf8yk8Jq6CGK0GKvWlatG7b7kkUU/Lo1gdXWn7/4E0j0qeJDpqN/ABqQcgJgdqURb4chjQktIugDS6wFFiz3JgaJj7AGJmholAe9YKhoZLJ0Ca6smjwJ4VwVN96gVIE5GM71kHaGKxGyAtRDaB2NBhLVmpHyANRKzDO28W7FS3HQFpaIWa8TrfCXQwegJSL5k+8M9UJ+pm9QTEnCIZrR0MDQeQ9ua0iCcYQaBTV0CqNXQW/yiyYG7W1heQanPaCkciBXuH1BkQJzHcDQxmpgGkPatl4WkbCXO/bW9AqlNg4H0PPMi6A1IxkQmOZ8D0ousNSMVEEuyreTAQ6Q7IRJeCX2YZQHhv6SrBOmpkM+YUzN0BqSRQCupmTeCP9wdkhiOREwtEzgGEsWcF9BhK9R8fQDiN7A8DiR0CKXQlj/q9IM8OgXjIzcKBlAHkD6FulgNzJwPIHwpo8mQAkX3LiPq9dKUMAQk9AqmcqmjuBAJCPQIpA4guIAsKJA0gnwNy3A4kDyBIHCEPxAwgf8gPILqA5AFEF5CxZX0lIHYc6rqADLf380BmFMgxgIzUyf8MJKLTRelKHgKy9wgkjfS7LiA0gKgC8vQn3HUA4RQ5LKPIAQciWbqIEg0YkLNDIHYUyqkCsmKN5vg3+W0AYTRATaPY+uu1IwS6UMGAlO6AFPjSCQMStaNh53cdcPG7Hx1Uupo+rx+Bltn1BuTAj5BptEV/bHAAwbnJMICwRmtUDOSEA8s4Rmtw3nITGD6TwUNoG0Ca7xi2YKSPj2eKXQFxQWKA2QbGMWEMMGseOb7C7T47uJS1JyAzVbTjqZdU3zbHzMXWS+qp4Fgn8Ahy/QCRGqQcwU1vGnN7fylboWn8Bzg//hyjxltvdcl45bwFfYKzFyBy11UU9BnjuoqfWizVlQXulpzBTNbaB5Aid+VRrkBFB630AMS9BC8FK2ggE7u/FGy1kvfcB9TKQufX5uUXNWl3EjvWCi4k/u9A3Ddq1CpTIQGe6VN1qd8ArcvDQNw3S41Kn6qQmOq5e7pRr+8fAYLiIJtFrrvYRMYL0q06vj8EZLXUriJzRY8H1xEagOCK7gkghRg6RQYO0I6aWPwIEAru80AiMWSdzAeuDXUKyr+WqpAID8hMHC1Ct8F4mUsQ6W8pJMICki0JHCBczAFdBl38G3VE6ErQhhWlih4LWrCSLpaqjggHiGe9mVjRY0YPoelyqcqIcIDEe97rqJFFH7FcLlUZEQ6Qg5plvZiBFNhtri1VFREGEC/Eg4nZoU5vqi1VFREGkIXDQ8xAIhzoT/WlKiLCAFIYPOQMxOPdjfWlKiLCADJRm3YGj+pDE2xktmmpaogwgMz8d8GrumZ4xzpbvinqISJ+hiTWm7wEqoJdI9JEV9JChAEkS3xCZzKecLcgN6YwlRBhAGmweTsblg6qKMM7Vmh321UQ4QAp1VfwhqVJIh+Wm03W0qV0EOEAybXtivkCmWrKeH2EZ/xBaSBCV2L9Re+LYSqJJIxDu1ew07U0EGEBcTtmHty4JuPtQhvLh1BAhK7Uvvq0GK484QZST0GvvFDqeSJ1IA0r2mfDljvqBoJ//rVsq7yZCA6kXgVkJ2f4ijIGMjOfMVsCBBORB2Jy+sM6ijNvaBUqmw/cStZ8EiKciHwp6Rp++88qmxXQeTUxDiJWJ9wSISvBicgXW+dypn1PqWTznlwgwdZdfiLHr5OELEAEASKvJFRE5JCPKbh8OxHdQKJU0crEzRXrJ/IEkFms6tGyrUw9kQeALFRXvK2iSzsRAAi6BLxM+60xdsqJAEBuXMAMxDLVp+gmAgC57/UT4qvVj3TVRCAgSAYL91aXtyNLzUQAIFhAiP8m0/NHOp+ILiBtPFKrs6bgSOcT0QTEB8nO3QR1yKslggKRf+m11UB0HOl8IlqAeCvauXuo8HnfIqIDyCw6G8XMcGiplMingMzCnbuHFp/3LSLPA4nUpqm5YkWNzwsQeQxIDsKjH5wVSU5qJPIJIIt4jjpqNBAekQeBfJOeHWS81FQoo4/I7UDcS3wUh0liTzLqiEgDqddx4ZHDrNZAACIAEMw88HPYWb0GAhABgEDmgf9Vb5oNBCByOxD3uqWYbCHVBgIQuRlIsbfwMEG5gQBE7gSyHMDsOayrxJvHBRC5B0hOxJH1nK4SlUE6QOR+IG6ju3iYQEqDdIDIzUDyZu/jMRHpS/OiRG4FkiPRfTw8kbrvIAJEACAIDpyHC1/GQHhEbgKSXwTyqIeEur6kixEBgABHOTr7YSX1MSFAhA0E307wUU76Y0KACAsI/tvCRzkF+iIuL0AEAYLbR2QOfvhKJ/obRESBxNt5rPSFXN4f7dyNdqMgEIbhAXWwJErT/e7/Wreb5HTT07QVgWSAeW5g7b4n8qOSUCRPEId4HP93SXp5dDNGRJFcQTxihSH+NW1Bb1cXKpIryJAwnG/zhl8ZcSP6jiKZghwRaaWLnP/AkcSKKJIniEcUs8QfjFLdEmRvkSxB4lfn0QN6DY+lshQpHiT96Dlr6r5hxRUpHST9ZEY71X7DOmOZQVZLsd5Q8wzrPxYYJDiKNqOBG1ZCkZKzrNXu6lHvkjChSFqQsdTPg45ApXtYaUXKr9TNuPcvqO2pVMkitFXAL2a79/qr3HQvVSTXUtofCl79RDXh5CDpw3pwu6+9kRlvtiI5VtPhmHLltT4EKVQkfb8pcOHrXqk6nBAksUjgpKtuYsskaxGKYT0+84uYgziE4YQgMdx0m8PRfis2MbL33PMXoVjD6PEunI4HSjDjStiJP08vQk9hZzQ7oH/geoLYCUBDW4rf4FqCDFt7THUO6B+4jiDn2XNTW7zf4hqCMND4BOsGyw+yAmh0x+QeFh7EeqD5Ce8nLDrI8NpbDyIWHIQNruo4GyAPlhrEzuixBxHLDDJMnfYgYolBricHNfjIdgMWF+Qyu+pkgX4HCwuymL57ELGkIHZG7z2IWE6Q5VV7vGMhQewbtMcZiwhyHj26ne9+xs8PcvDQHnFFqCD7Au0RW4TK+fOKqw4eoOcqYqgU53HR3/5uShFPCfKey9hFDyJO/vAi7RDZnp7X5igyUH72xSDW1E2Pn4tMRCQgR8vLwbgii4gcmLvqQcSPGtIPX3M08wn6I4qYQ94cM/Yw9Xxhmw+X/59wHrtMlX1AmIkzdyaaAnLg1Nnw8WGYSk40X/BOh4+El6LMSBnN2Cd0tPq4w/LJXGrMbCX06PZ2dcM65yzlNertShSHf3SzRAyPM332IcSAHUKPi8EHmXU0l8Uglmni0yipDoi16s+jJKejhywLooz68yiMEcHr2qM4h81CJ++VPJfTu5UwBpv4Pp9DJSi6MJx0bvUwiw4ewgT8zNR0LHUL+OccOpY/3ElzyGKD5pBlMJpDlsOkMythRoNbXh95PJsdA67MrMtAEYbjeDqNo+7oKqWUUkoppZRSSimllFJKFfMXp4vmSjB8n6sAAAAASUVORK5CYII="),Ab.IMAGE}dispose(){super.dispose(),this.started=!1,delete this._audio}async ready(){super.ready(),this._audio=new Audio;const{src:t="",loop:e=!1,started:n=!1}=this.state;if(t){const e=this.root?.app?.loadTracker;if(e){const n=new Promise((e,n)=>{this._audio.addEventListener("canplay",()=>e(),{once:!0}),this._audio.addEventListener("error",()=>n(new Error(`Audio load failed: ${t}`)),{once:!0})});e.track(`audio:${t}`,"audio",t,n)}}this._audio.addEventListener("canplay",()=>{this.started&&this._audio.play()}),this.onchangeSrc(t),this.onchangeLoop(e),this.onchangeStarted(n)}render(t){const{left:e,top:n,width:s,height:i}=this.state;t.beginPath(),this.drawImage(t,Ab.image,e,n,s,i)}get nature(){return Sb}get hasTextProperty(){return!1}get src(){return this.get("src")}set src(t){this.set("src",t)}get started(){return!!this.get("started")}set started(t){this.set("started",t)}start(){this._audio&&(this._audio.classList.add("active"),this._audio.play())}pause(){this._audio&&(this._audio.classList.remove("active"),this._audio.pause())}onchangeSrc(t){try{"data"!==String(t).substring(0,4)?this._audio.crossOrigin="use-credentials":this._audio.crossOrigin=null,this._audio.src="string"==typeof t?this.app.url(t):t}catch(t){return void Fs(t)}}onchangeStarted(t){const e=this._audio;t?4==e.readyState&&e.play():e.pause()}onchangeLoop(t){this._audio.loop=t}onchange(t,e){"src"in t&&this.onchangeSrc(t.src),"started"in t&&this.onchangeStarted(t.started),"loop"in t&&this.onchangeLoop(t.loop)}ondblclick(t){this.started=!this.started}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("audio/"))return void(this.src=e[n])}}uc.register("audio",Ab);class kb extends(mc(uc)){is3dish(){return!0}}uc.register("text",kb);const Eb=["refid","left","top","width","height","rotation","animation","zPos"];class Tb extends Cy{isGroup(){return!0}is3dish(){return!0}get showMoveHandle(){return!1}get(t){return this._model[t]}set(t,e){if("string"==typeof t)return this.set({[t]:e});const n=Eb.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{});return super.set(n,void 0)}capture(t,e,n){const s=super.capture(t,e,n);if(s!==this)return s}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,s=t.height/e.height;this.path=this.path.map(i=>({x:t.left+(i.x-e.left)*n,y:t.top+(i.y-e.top)*s})),this.components&&this.components.forEach(t=>{if(t.mutable)t.mutatePath(null,function(t){return t.map(function(t){return{x:t.x*n,y:t.y*s}})});else{const e=t.bounds,i=t.center,o={x:i.x*(1-n),y:i.y*(1-s)},r=e.width*(1-n),a=e.height*(1-s),c=-(o.x-r/2),l=-(o.y-a/2);t.bounds={left:e.left+c,top:e.top+l,width:e.width*n,height:e.height*s}}})}get focusible(){return!1}get bounds(){return super.bounds}get hasTextProperty(){return!1}isIdentifiable(){return!1}calculateBounds(){this.clearCache(),this.__MUTATING__=!0,this.mutateBounds(function(t){const e=uc.union(this.components.map(t=>t.bounds));return this.components.forEach(t=>{const n=t.bounds;t.bounds={left:n.left-e.left,top:n.top-e.top,width:n.width,height:n.height}}),{left:t.left+e.left,top:t.top+e.top,width:e.width,height:e.height}},this),this.__MUTATING__=!1,this.parent.isGroup()&&this.parent.calculateBounds?.()}render(t){}postrender(t){const{top:e,left:n}=this.state;t.translate(n,e),this.layout.drawables(this).forEach(e=>{e.draw(t)}),t.translate(-n,-e)}}uc.memoize(Tb.prototype,"bounds",!0),uc.register("group",Tb);const Cb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"id-input",label:"ref",name:"ref"},{type:"select",label:"fit",name:"fit",property:{options:["","both","ratio"]}}],"value-property":"ref",help:"scene/component/local-ref"};class Ob extends(mc(pc)){get ref(){const t=this.getState("ref");return t&&"string"==typeof t?this.root.findById?.(t):null}set ref(t){this.setState("ref",t)}get refScale(){const t=this.ref;if(!t)return{x:1,y:1};const e=t.bounds,n=this.bounds,s=n.width/e.width,i=n.height/e.height;return"both"===this.model.fit?{x:s,y:i}:{x:Math.min(s,i),y:Math.min(s,i)}}draw(t){this._drawing||(this._drawing=!0,super.draw(t),this._drawing=!1)}prerender(t){if(super.prerender(t),this.ref){const e=this.ref.center,n=this.center,s=this.refScale;t.translate(n.x,n.y),t.scale(s.x,s.y),t.translate(-e.x,-e.y)}}postrender(t){if(this.ref)return this.ref.postrender(t);super.postrender(t)}render(t){if(this.ref)return this.ref.render(t);const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),t.rect(e,n,s,i)}get nature(){return Cb}get hasTextProperty(){return!1}}uc.memoize(Ob.prototype,"ref",!1),uc.memoize(Ob.prototype,"refScale",!1),uc.register("local-ref",Ob);class Pb extends(Sy(Kl)){render(t){}is3dish(){return!0}get layout(){return xc.get(this.get("layout"))||wc}}const Ib={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"board-selector",label:"scene-number",name:"ref",placeholder:"SCENE-1"},{type:"number",label:"round",name:"round",property:{min:0}},{type:"select",label:"fit",name:"fit",property:{options:["","both","ratio","width","height","none"]}},{type:"select",label:"mode",name:"mode",property:{options:["view","interaction"]}}],"value-property":"ref",help:"scene/component/global-ref"};class Db extends Pb{dispose(){this._releaseRef(),super.dispose()}get nature(){return Ib}get hasTextProperty(){return!1}get tagName(){return"div"}setElementProperties(t){const{mode:e="view",round:n=0}=this.state;t.style.pointerEvents="view"==e?"none":"inherit",t.style.borderRadius=n+"px"}async ready(){super.ready(),this.fetchRef()}reposition(){if(!this.element)return;super.reposition();const t=this._element_bounds,{offsetWidth:e,offsetHeight:n}=this.element;if(this._element_bounds={offsetWidth:e,offsetHeight:n},(!t||t.offsetWidth!=e||t.offsetHeight!=n)&&this.ref&&this.root.target_element){const{fit:t="ratio"}=this.state;this.ref.fit(t)}}async fetchRef(){this._releaseRef();const{ref:t,fit:e="ratio"}=this.state;if(!t)return;const n=this.app.refProvider;if(n&&t){const s=(async()=>{this.__ref=await n.get(t,!0),this.__ref.target=this.element,this.__ref.fit(e),this.__ref.data=this.data})();this.root?.app?.loadTracker?.track(`ref:${t}`,"ref-board",t,s);try{await s}catch(t){Fs(t)}}}get ref(){return this.__ref}set ref(t){this.setState("ref",t)}_releaseRef(){this.__ref&&this.__ref.release&&this.__ref.release(),delete this.__ref}onchange(t,e,n){super.onchange(t,e),"ref"in t&&this.fetchRef(),"fit"in t&&this.ref&&requestAnimationFrame(()=>{const{fit:t}=this.state;this.ref.fit(t)}),"data"in t&&this.ref&&requestAnimationFrame(()=>{this.ref.data=t.data})}}uc.register("global-ref",Db);const zb="center-middle",Rb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"board-selector",label:"board",name:"board"},{type:"checkbox",label:"modal",name:"modal"},{type:"checkbox",label:"closable",name:"closable"},{type:"checkbox",label:"draggable",name:"draggable"},{type:"checkbox",label:"minimizable",name:"minimizable"},{type:"checkbox",label:"show",name:"show"},{type:"select",label:"popup-position",name:"popupPosition",property:{options:["static","absolute"]}},{type:"select",label:"popup-origin",name:"origin",property:{options:["left-top","center-top","right-top","left-middle",zb,"right-middle","left-bottom","center-bottom","right-bottom","auto"]}},{type:"string",label:"title",name:"text"},{type:"data",label:"value",name:"value"},{type:"string",label:"container-ref",name:"containerRef",placeholder:"PopupContainer id (same board)"},{type:"textarea",label:"html-template",name:"htmlTemplate",property:{language:"html"}},{type:"string",label:"anchor-ref",name:"anchorRef",placeholder:"component id (3D-tracked anchor)"},{type:"select",label:"anchor-pin",name:"anchorPin",property:{options:[{display:"Top",value:"top"},{display:"Center",value:"center"},{display:"Bottom",value:"bottom"}]}},{type:"number",label:"anchor-offset-x",name:"anchorOffsetX"},{type:"number",label:"anchor-offset-y",name:"anchorOffsetY"},{type:"number",label:"anchor-offset-z",name:"anchorOffsetZ"},{type:"checkbox",label:"constant-size",name:"constantSize"},{type:"checkbox",label:"tether",name:"tether"},{type:"select",label:"off-screen",name:"offScreen",property:{options:[{display:"Hide",value:"hide"},{display:"Edge-pin",value:"edge-pin"},{display:"Keep last",value:"keep-last"}]}}],help:"scene/component/popup"};class jb extends(mc(pc)){static get image(){return jb._image||(jb._image=new Image,jb._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAABGCAMAAABG8BK2AAADJmlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNy4xLWMwMDAgNzkuZGFiYWNiYiwgMjAyMS8wNC8xNC0wMDozOTo0NCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIDIzLjAgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RkM4QzQxNUMzMzBEMTFFQ0JEMzZDMDUwQUI4MEI3QTAiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RkM4QzQxNUQzMzBEMTFFQ0JEMzZDMDUwQUI4MEI3QTAiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpENjlENTQ3RjMzMDkxMUVDQkQzNkMwNTBBQjgwQjdBMCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpENjlENTQ4MDMzMDkxMUVDQkQzNkMwNTBBQjgwQjdBMCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PsiUYSQAAAAZdEVYdFNvZnR3YXJlAEFkb2JlIEltYWdlUmVhZHlxyWU8AAAA51BMVEVHcEwzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzOguTm2AAAATHRSTlMARhB73r9B7YLrsqdE+0cq9Avzeg31eQx4aQ+Ks6aUd5DsYKixEX1w8vyT2VjoZ3YezY/cCEDvl+QTvRwJ0ifwK/5T/aw6+IuFuCImAcS6MQAAAeJJREFUWMPt2FlX2zAQhuHJYmOSFhIggbC0QNn3rS1dKXSH9///Hi58CJLxKIpEWi6YO8c5z4lG/nxGEXmu/1OVLGnhrFaSVQYg1SZetTTvUibqeFZ9QlfmvRWoV1VmCaCRzroXPpsuAjTV7gLUfPahBqD1OQMW/fazAWTKvQRI/ZgUSJR7U8CM/dHZ+/2VcatWdvdEZAaYUhiAwkerJXt0rnzXwdRKmHfDM0fHD5kxjTFyVLzVfvvirn7+cDJWjhy7c7XlYuwc6Urvu2tRhRypyhwAf1sKY+TIxfQA+H39q5wxc+RgVrcBduTmZTlj5khnDgH4IzKpMGaOVCbvyyvRGTNHGtPrKypjXirM5jb910I4k69oQeKY+77EMAcALEsck/+W6f71tyCma/ZFROTrJVwMy7wmf3bv6/MX+Dgkkysblvxps/dhOKZb6IvrTakzXXuPApnpYneDGOeKvJlaSXcDmA7AicQyW84VeTOnY+NdiWcG1uiZksFEHdyAlsJEjEkmkwGNsKHNZCJGSKtVTYC1tO022mnjwUBrMdXg8dreuOBhv7D/62/8lGZ1wLxXyZKOm+iUHIQintyny0TkaATHjYgcjeAoFpEje9R/nGPqIx2aw3NU9odCQI6e6x/VLY32cKQXVBnkAAAAAElFTkSuQmCC"),jb._image}async ready(){await super.ready(),this.show&&this.onchangeShow(!0)}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,jb.image,e,n,s,i)}onchange(t,e){"value"in t?this.show?this.onchangeShow(!0):this.show=!0:"show"in t&&this.onchangeShow(this.show)}onchangeShow(t){if(this.app.isEditMode)return;(this.getState("board")||this.getState("containerRef")||this.getState("htmlTemplate"))&&(t?this.openPopup(this.value):this.hidePopup())}openPopup(t,e){if(this.app.isEditMode)return;const n=this.getState("anchorRef"),s=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;Tp.show(this,this.getState("board"),{origin:this.getState("origin")||zb,modal:this.getState("modal"),closable:this.getState("closable")||!1,draggable:this.getState("draggable")||!1,minimizable:this.getState("minimizable")||!1,popupPosition:this.getState("popupPosition"),title:this.text,data:t||this.value,containerRef:this.getState("containerRef"),htmlTemplate:this.getState("htmlTemplate"),anchor:s,anchorPin:this.getState("anchorPin")||"top",anchorOffsetX:this.getState("anchorOffsetX")??0,anchorOffsetY:this.getState("anchorOffsetY")??0,anchorOffsetZ:this.getState("anchorOffsetZ")??0,constantSize:this.getState("constantSize")??!0,tether:this.getState("tether")??!1,offScreen:this.getState("offScreen")||"hide",...e})}hidePopup(){Tp.hide(this)}get board(){return this.getState("board")}set board(t){this.set("board",t)}get show(){return this.getState("show")}set show(t){this.setState("show",t)}get started(){return this.getState("show")}set started(t){this.setState("show",t)}get value(){return this.getState("value")}set value(t){this.setState("value",t)}get hasTextProperty(){return!1}get nature(){return Rb}}uc.register("popup",jb);const $b={mutable:!1,resizable:!0,rotatable:!1,properties:[{type:"layout",label:"layout",name:"layoutOption"},{type:"checkbox",label:"constant-size",name:"constantSize"},{type:"checkbox",label:"billboard",name:"billboard"},{type:"checkbox",label:"tether",name:"tether"},{type:"select",label:"off-screen",name:"offScreen",property:{options:[{display:"Hide",value:"hide"},{display:"Edge-pin",value:"edge-pin"},{display:"Keep last",value:"keep-last"}]}}],help:"scene/component/popup-container"};class Lb extends Cy{get nature(){return $b}isPopupContainer(){return!0}}uc.register("popup-container",Lb);class Fb extends uc{render(t){const{path:e=[]}=this.state;if(!(e.length<=1)){t.beginPath(),t.moveTo(e[0].x,e[0].y);for(let n=1;n<e.length;n++)t.lineTo(e[n].x,e[n].y);t.closePath(),this.drawStroke(t,void 0)}}get path(){return this.model.path}set path(t){this.set("path",t)}contains(t,e){const n=this.state.path;let s=!1;return n.forEach((i,o)=>{const r=(o+n.length+1)%n.length,a=i.x,c=i.y,l=n[r].x,h=n[r].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}}uc.register("path",Fb);const Nb={mutable:!0,resizable:!1,rotatable:!0,properties:[{type:"number",label:"round",name:"round",property:{min:0,max:100,step:1}}],help:"scene/component/triangle"};class Hb extends pc{is3dish(){return!0}contains(t,e){const{x1:n,y1:s,x2:i,y2:o,x3:r,y3:a}=this.state,c=[n,s,i,o,r,a];let l=!1;for(let n=0;n<c.length;n+=2){const s=(n+2)%c.length,i=c[n],o=c[n+1],r=c[s+1];o>e!=r>e&&t<(c[s]-i)*(e-o)/(r-o)+i&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:s,x3:i,y3:o}=this.state;return[{x:t,y:e},{x:n,y:s},{x:i,y:o}]}set path(t){this.set({x1:t[0].x,y1:t[0].y,x2:t[1].x,y2:t[1].y,x3:t[2].x,y3:t[2].y})}get nature(){return Nb}}uc.memoize(Hb.prototype,"path",!1),uc.register("triangle",Hb);const Bb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"}],help:"scene/component/donut"},Gb={ondragmove:function(t,e,n){let{cx:s,rx:i}=n.model;i=Math.abs(i);let o=(n.fromParent(t.x,t.y).x-s)/i*100;o=o>=100||o<=-100?100:Math.abs(o),n.set({ratio:o})}};class Ub extends Vy{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:s,rx:i,ry:o,startAngle:r,endAngle:a,anticlockwise:c}=this.state;i=Math.abs(i),o=Math.abs(o),t.beginPath(),t.ellipse(n,s,i,o,0,r||0,a||2*Math.PI,c),t.moveTo(n+i/100*e,s),t.ellipse(n,s,i/100*e,o/100*e,0,r||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:s,rx:i,ry:o,ratio:r}=this.state;i=Math.abs(i),o=Math.abs(o);const a=(t-n)/(2*i-.5),c=(e-s)/(2*o-.5),l=(t-n)/(i/100*r*2-.5),h=(e-s)/(o/100*r*2-.5);let d=!1;return a*a+c*c<.25&&l*l+h*h>.25&&(d=!d),d}get controls(){let{cx:t,cy:e,rx:n,ratio:s}=this.state;return n=Math.abs(n),[{x:t+n/100*s,y:e,handler:Gb}]}get nature(){return Bb}}uc.memoize(Ub.prototype,"controls",!1),uc.register("donut",Ub);const Vb={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"},{type:"number",label:"wing",name:"wing",property:"wing"}],help:"scene/component/star"},Wb={ondragmove:function(t,e,n){const{cy:s,ry:i}=n.model;let o=(n.fromParent(t.x,t.y).y-s)/i*100+100;o>=100?o=100:o<=0&&(o=0),n.set({ratio:o})}};class Yb extends Vy{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:s,cy:i,rx:o,ry:r}=this.state;if(n<3)return;const a=1.5707963267948966,c=2*Math.PI/n,l=o-e/100*o,h=r-e/100*r;t.save(),t.beginPath(),t.translate(s,i),t.moveTo(o*Math.cos(-a),r*Math.sin(-a)),t.lineTo((o-l)*(Math.cos(c-a)+Math.cos(0-a))/2,(r-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let e=1;e<n;e++)t.lineTo(o*Math.cos(c*e-a),r*Math.sin(c*e-a)),t.lineTo((o-l)*(Math.cos(c*(e+1)-a)+Math.cos(c*e-a))/2,(r-h)*(Math.sin(c*(e+1)-a)+Math.sin(c*e-a))/2);t.closePath(),t.restore()}get controls(){const{cx:t,cy:e,ry:n,ratio:s}=this.state;return[{x:t,y:e-n+n*(s/100),handler:Wb}]}get nature(){return Vb}}uc.memoize(Yb.prototype,"controls",!1),uc.register("star",Yb);const qb={mutable:!1,resizable:!1,rotatable:!1,properties:[]};class Xb extends(xm(pc)){is3dish(){return!1}isDescendible(){return!1}render(t){const{cx:e,cy:n,anticlockwise:s}=this.state,i=this.app?.scale||1;t.beginPath(),t.scale(1/i,1/i),t.ellipse(e,n,Math.abs(Xb.RADIUS),Math.abs(Xb.RADIUS),0,0,2*Math.PI,s),t.scale(i,i),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-Xb.RADIUS,y:e-Xb.RADIUS},{x:t+Xb.RADIUS,y:e-Xb.RADIUS},{x:t+Xb.RADIUS,y:e+Xb.RADIUS},{x:t-Xb.RADIUS,y:e+Xb.RADIUS}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s}=this.state,i=(t-n)/(2*Xb.RADIUS-.5),o=(e-s)/(2*Xb.RADIUS-.5);return i*i+o*o<.25}outline(t){const{cx:e,cy:n}=this.state;return this.toScene(e,n)}get nature(){return qb}}Xb.RADIUS=5,uc.memoize(Xb.prototype,"path",!1),uc.register("node",Xb);class Kb extends Du{getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds,n=this.component.state.depth||.5*Math.min(t,e),s=.15*Math.min(t,e,n),i=new _.RoundedBoxGeometry(1,1,1,4,s/Math.min(t,e,n));i.scale(t,n,e),this.object3d.geometry=i,this.object3d.material=new w.MeshStandardMaterial({color:"#5090d0",transparent:!0,opacity:.35,roughness:.6,metalness:.1,side:w.FrontSide,depthWrite:!1}),this.object3d.visible=!!this.component.app?.isEditMode}updateAlpha(){const t=this.object3d.material;t&&(t.opacity=this.component.app?.isEditMode?.35:0)}updateHidden(){this.object3d.visible=!!this.component.app?.isEditMode&&!this.component.state.hidden}updateDimension(){const{width:t,height:e}=this.component.bounds,n=this.component.state.depth||.5*Math.min(t,e);this.object3d.geometry.computeBoundingBox();const s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,o=s.max.y-s.min.y,r=s.max.z-s.min.z;this.setDimensionScale(t/i,n/o,e/r)}}updateFillStyle(){}updateStrokeStyle(){}updateText(){}clear(){return bu(this.object3d),super.clear()}}const Jb="data:image/svg+xml;base64,"+btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="#5090d0">\n <path d="M32 20a12 12 0 1 0 0 24 12 12 0 0 0 0-24zm0 18a6 6 0 1 1 0-12 6 6 0 0 1 0 12z"/>\n <path d="M55.4 27.2l-3.6-.6c-.4-1.2-.8-2.4-1.4-3.4l2.2-3c.6-.8.4-2-.2-2.6l-3-3c-.8-.6-1.8-.8-2.6-.2l-3 2.2c-1.2-.6-2.2-1-3.4-1.4l-.6-3.6c-.2-1-1-1.6-2-1.6h-4.2c-1 0-1.8.6-2 1.6l-.6 3.6c-1.2.4-2.4.8-3.4 1.4l-3-2.2c-.8-.6-2-.4-2.6.2l-3 3c-.6.8-.8 1.8-.2 2.6l2.2 3c-.6 1.2-1 2.2-1.4 3.4l-3.6.6c-1 .2-1.6 1-1.6 2v4.2c0 1 .6 1.8 1.6 2l3.6.6c.4 1.2.8 2.4 1.4 3.4l-2.2 3c-.6.8-.4 2 .2 2.6l3 3c.8.6 1.8.8 2.6.2l3-2.2c1.2.6 2.2 1 3.4 1.4l.6 3.6c.2 1 1 1.6 2 1.6h4.2c1 0 1.8-.6 2-1.6l.6-3.6c1.2-.4 2.4-.8 3.4-1.4l3 2.2c.8.6 2 .4 2.6-.2l3-3c.6-.8.8-1.8.2-2.6l-2.2-3c.6-1.2 1-2.2 1.4-3.4l3.6-.6c1-.2 1.6-1 1.6-2v-4.2c0-1-.6-1.8-1.6-2z"/>\n</svg>');class Qb extends(mc(uc)){static get icon(){return Qb._defaultIcon||(Qb._defaultIcon=new Image,Qb._defaultIcon.src=Jb),Qb._defaultIcon}get serviceName(){}get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Kb(this)}render(t){if(this.app?.isViewMode)return;const{left:e,top:n,width:s,height:i}=this.bounds,o=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,o,e,n,s,i),t.globalAlpha=1}added(t){super.added(t);const e=this.serviceName;e&&(this._registeredRoot=this.root,this._registeredRoot?.registerService?.(e,this))}removed(t){const e=this.serviceName;e&&this._registeredRoot&&(this._registeredRoot.unregisterService?.(e),this._registeredRoot=void 0),super.removed(t)}get controls(){return[]}}function Zb(t){return class extends t{animOnValueChange(t,e=!1,n){if(t==this._lastValue)return;if(this.root?.app?.suppressAnimations)return this._lastValue=t,this._anim_alpha=0,void this.invalidate();let s;s=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-s,this.animate({step:t=>{this._anim_alpha=s*(t-1),this.invalidate()},duration:1e3,delta:"circ",options:{x:1},ease:"out"}).start()}dispose(){super.dispose(),delete this._value_substitutor}onchange(t,e){t.hasOwnProperty("value")&&delete this._value_substitutor}get animAlpha(){return this._anim_alpha||0}get animValue(){return(this._lastValue||0)+(this._anim_alpha||0)}defaultValueSubstitutor(){return this.getState("value")}get valueSubstitutor(){return this._value_substitutor||(this._value_substitutor=Oo(this.getState("value"),this,void 0)||this.defaultValueSubstitutor),this._value_substitutor}get value(){return Number(this.valueSubstitutor())||0}set value(t){delete this._value_substitutor,this.setState("value",Number(ls(t)))}}}function tv(t){return class extends t{_convertDataFormat(t,e){let n;if("json"===e)n=JSON.parse(t);else n=t;return n}isDataSource(){return!0}}}function ev(t){var e;return(e=class extends t{is3dish(){return!0}get hasTextProperty(){return!1}get capturable(){return!1}render(t){}}).raycastTargetDefault=!1,e.requires3d=!0,e}const nv="$base_url",sv=[{type:"gltf-preset",label:"preset",name:"preset"},{type:"gltf-selector",label:"url",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:nv,defaultStorage:"3d-model",storageFilters:{type:Array,value:[{name:"category",value:"image"}]},useUpload:!0,category:"application"},observe:function(t){const e=this.parentNode?.querySelector("[name=gltfInfo]");e&&(e.src=t);const n=this.parentNode?.querySelector("[name=fillStyleTargets]");n&&(n.src=t);const s=this.parentNode?.querySelector("[name=playTargets]");s&&(s.src=t)}},{type:"gltf-info",label:"",name:"gltfInfo",readonly:!0,property:{action:(t,e)=>{t._ratioLocking=!0;try{t.set(e)}finally{t._ratioLocking=!1}}},editor:{fullwidth:!0}},{type:"gltf-fill-targets",label:"fill-targets",name:"fillStyleTargets",editor:{fullwidth:!0}},{type:"gltf-play-targets",label:"play-targets",name:"playTargets",editor:{fullwidth:!0}}];function iv(t){return class extends t{constructor(){super(...arguments),this._snapshotLoading=!1,this._ratioLocking=!1}is3dish(){return!0}get hasTextProperty(){return!1}get controls(){return[]}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath();const o=this._topViewSnapshot;if(o)return void t.drawImage(o,e,n,s,i);this._ensureTopViewSnapshot(),t.rect(e,n,s,i),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const r=this.getState("src"),a=r&&r.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(s,i));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+s/2,n+i/2,.9*s)}onchange(t,e){super.onchange?.(t,e),"src"in t&&(this._topViewSnapshot=void 0)}_ensureTopViewSnapshot(){if(this._snapshotLoading)return;const t=this.getState("src");if(!t)return;const e=Nu.getTopViewCache(t);if(e)return this._topViewSnapshot=e,void this.invalidate();this._snapshotLoading=!0;const n=this.app.url(t);Nu.loadGLTF(n).then(e=>{if(this._snapshotLoading=!1,this.getState("src")!==t)return;const n=Nu.getTopViewCache(t);if(n)return this._topViewSnapshot=n,void this.invalidate();const s=Nu.renderTopView(e.scene);Nu.setTopViewCache(t,s),this._topViewSnapshot=s,this.invalidate()}).catch(()=>{this._snapshotLoading=!1})}buildRealObject(){return new Nu(this)}get source(){return this.getState("src")}set source(t){this.setState("src",t)}get play(){return!1!==this.getState("play")}set play(t){this.setState("play",t)}get nodes(){return this.getState("nodes")}set nodes(t){this.setState("nodes",t)}get animations(){return this.getState("animations")}set animations(t){this.setState("animations",t)}get playTargets(){return this.getState("playTargets")}set playTargets(t){this.setState("playTargets",t)}get fillStyleTargets(){return this.getState("fillStyleTargets")}set fillStyleTargets(t){this.setState("fillStyleTargets",t)}get nodeNames(){const t=this.realObject;return t?.nodeNames??[]}get animationNames(){const t=this.realObject;return t?.animationNames??[]}set dimension(t){const{width:e=1,height:n=1,depth:s=1}=t;this.setState({width:e,height:n,depth:s}),this.realObject?.updateDimension()}_applyRatioLock(t){if(!("width"in t||"height"in t||"depth"in t))return t;const e=this.state.width||1,n=this.state.height||1,s=this.state.depth||1,i=Bf([(t.width??e)/e,(t.height??n)/n,(t.depth??s)/s]);return i?{...t,width:Math.round(e*i),height:Math.round(n*i),depth:Math.round(s*i)}:t}set(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.set(t)}finally{this._ratioLocking=!1}}setState(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.setState(t)}finally{this._ratioLocking=!1}}}}function ov(t){return function(e){return Array.isArray(t)?t.forEach(t=>{uc.register(t,e)}):uc.register(t,e),e}}function rv(t){return!!t&&"function"==typeof t.capacity&&"function"==typeof t.available}function av(t){if(rv(t)){const e=t.capacity(),n=t.available();return{capacity:e,available:n,isFull:0===n}}if("function"==typeof t?.slotIds){const e=t.slotIds().length,n="function"==typeof t.emptySlotIds?t.emptySlotIds().length:e;return{capacity:e,available:n,isFull:0===n}}const e=t?.state?.capacity,n=Array.isArray(t?.state?.data)?t.state.data.length:0;if("number"==typeof e){const t=Math.max(0,e-n);return{capacity:e,available:t,isFull:0===t}}return{capacity:1/0,available:1/0,isFull:!1}}class cv{constructor(){this.wasFull=!1,this.availableListeners=[],this.fullListeners=[]}notify(t){const e=0===t;if(e&&!this.wasFull){this.wasFull=!0;for(const t of this.fullListeners)try{t()}catch(t){}}else if(!e&&this.wasFull){this.wasFull=!1;for(const t of this.availableListeners)try{t()}catch(t){}}}onAvailable(t){return this.availableListeners.push(t),()=>{const e=this.availableListeners.indexOf(t);e>=0&&this.availableListeners.splice(e,1)}}onFull(t){return this.fullListeners.push(t),()=>{const e=this.fullListeners.indexOf(t);e>=0&&this.fullListeners.splice(e,1)}}dispose(){this.availableListeners=[],this.fullListeners=[]}}function lv(t,e){if(!t||!e)return()=>{};if("function"!=typeof t.pauseEmit||"function"!=typeof t.resumeEmit)return()=>{};if("function"!=typeof e.onFull||"function"!=typeof e.onAvailable)return()=>{};const n=e.onFull(()=>t.pauseEmit()),s=e.onAvailable(()=>t.resumeEmit());return av(e).isFull&&t.pauseEmit(),()=>{n?.(),s?.()}}class hv{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,s){const i=e.maxCount??1/0;if(t<0||t>=i)return null;const o=this.owner?.state?.width??0,r=this.owner?.state?.height??0,a=s?.state?.width??0,c=s?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(r-c)/2),z:0}:{x:Math.max(0,(o-a)/2),y:t*this.itemSpacing,z:0}}capacity(t){return t.maxCount??1/0}}function dv(t,e,n,s,i,o,r){const a=n.w,c=n.h,l=s.w,h=s.h,d=s.d,u=[],p=l+i,f=h+i,m=Math.max(1,Math.floor((a+i)/p)),g=Math.max(1,Math.floor((c+i)/f)),y=m*g,b=o&&o>0?Math.floor(o):4;if("row"===t||"column"===t){const n=r?.advanceAlongX??!1,s=r?.reverse??!1,i=n?m:g,o=n?g:m,l=(t,e,s)=>((t,e,n)=>u.push({x:-a/2+(t+.5)*p,y:n*d+d/2,z:-c/2+(e+.5)*f}))(n?t:e,n?e:t,s);let h=0;for(let n=0;n<i&&h<e;n++){const r=s?i-1-n:n;if("column"===t)for(let t=0;t<o&&h<e;t++)for(let n=0;n<b&&h<e;n++)l(r,t,n),h++;else for(let t=0;t<b&&h<e;t++)for(let n=0;n<o&&h<e;n++)l(r,n,t),h++}return u}if("pyramid"===t){let t=e,n=0;for(;t>0;){const e=Math.max(1,m-n),s=Math.max(1,g-n),i=e*s,r=Math.min(t,i);for(let t=0;t<r;t++){const i=t%e,o=Math.floor(t/e),r=-a/2+(i+(m-e)/2+.5)*p,l=-c/2+(o+(g-s)/2+.5)*f;u.push({x:r,y:n*d+d/2,z:l})}if(t-=r,n++,1===e&&1===s){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(o&&n>=o)break}return u}if("pile"===t){const t=t=>(43758.5453*Math.sin(12.9898*t)%1+1)%1;for(let n=0;n<e;n++){const e=Math.floor(n/y),s=n%y,i=s%m,r=Math.floor(s/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(i+.5)*p+g,_=-c/2+(r+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),o&&e>=o-1&&s===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(o&&e>=o)break;const s=n%y,i=s%m,r=Math.floor(s/m);let l=-a/2+(i+.5)*p;const h=-c/2+(r+.5)*f;"staggered"===t&&e%2==1&&(l+=p/2),u.push({x:l,y:e*d+d/2,z:h})}return u}class uv{constructor(t,e={}){this.pattern=t,this.defaults=e}layout(t,e,n,s={}){const i=s.gap??this.defaults.gap??0,o=s.heightLimit??this.defaults.heightLimit,r=s.fill??this.defaults.fill;return dv(this.pattern,t,e,n,i,o,r).map(t=>({position:t}))}}class pv{constructor(t,e,n={}){this.cols=t,this.rows=e,this.defaults=n}layout(t,e,n,s={}){const i=Math.max(1,this.cols),o=Math.max(1,this.rows),r=i*o,a=s.gap??this.defaults.gap??0,c=n.w+a,l=n.h+a,h=[];for(let e=0;e<t;e++){const t=Math.floor(e/r),s=e%r,a=s%i,d=Math.floor(s/i);h.push({position:{x:(a-(i-1)/2)*c,z:(d-(o-1)/2)*l,y:t*n.d+n.d/2}})}return h}}class fv{constructor(t=.1,e=!1,n=!1){this.gapRatio=t,this.fillFromFar=e,this.sliceFirst=n}grid(t,e){const n=e.w*this.gapRatio,s=e.h*this.gapRatio;return{cols:Math.max(1,Math.floor((t.w-n)/(e.w+n))),rows:Math.max(1,Math.floor((t.h-s)/(e.h+s))),pitchX:e.w+n,pitchZ:e.h+s}}capacity(t,e,n){const{cols:s,rows:i}=this.grid(t,e);return s*i*Math.max(1,Math.floor(n))}layout(t,e,n,s={}){const{cols:i,rows:o,pitchX:r,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=s.heightLimit?Math.max(1,Math.floor(s.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=i*o,p=i*(h?l:1),f=i*o*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,s,l;if(d){const n=Math.floor(t/p),o=t%p;e=o%i,l=Math.floor(o/i),s=n}else{l=Math.floor(t/u);const n=t%u;e=n%i,s=Math.floor(n/i)}this.fillFromFar&&(s=o-1-s),g.push({position:{x:(e-(i-1)/2)*r,z:(s-(o-1)/2)*a,y:l*c+n.d/2}})}return g}}function mv(t,e,n,s=0){for(let i=0;i<e.length;i++){const o=e[i],r=n[i];o&&r&&(o.parent!==t&&t.attach(o),o.position.set(r.position.x,s+r.position.y,r.position.z),r.rotation?o.quaternion.set(r.rotation.x,r.rotation.y,r.rotation.z,r.rotation.w):o.quaternion.identity())}}function gv(t,e,n,s=.12){const i=e.left+e.width/2,o=e.top+e.height/2,r=Math.min(n.w,n.h)*s,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let s=a.get(t);s||(s={x:i+e.position.x-n.w/2+r,y:o+e.position.z-n.h/2+r,w:n.w-2*r,h:n.h-2*r,count:0},a.set(t,s)),s.count++}return[...a.values()]}function yv(t){return{id:t?.state?.id??t?.id??t?.refid,type:t?.state?.type??t?.type}}const bv=new w.Euler;function vv(t,e){bv.setFromQuaternion(new w.Quaternion(e.x,e.y,e.z,e.w),"YXZ"),t.rotationX=bv.x,t.rotation=-bv.y,t.rotationY=bv.z}const _v="_transferSlotId",xv=new Set(["left","top","width","height","depth","zPos","rotation","rotationX","rotationY","rotationZ","scale","translate","material3d","fillStyle","strokeStyle","lineWidth","lineDash","alpha","opacity","hidden","text","fontColor","fontSize","fontFamily","bold","italic","textAlign","textBaseline","shadow","border","cssText","object3d","_realObject","refid","id"]);function wv(t){return class extends t{constructor(){super(...arguments),this._itemIssues=[],this._itemsStale=!1,this._lastItemIds=new Set}_itemsFromData(){return!0}_currentKeyOf(t){const e=this._keyedById()?t?.state?.id:t?.[_v];return null!=e?String(e):null}get itemIssues(){return this._itemIssues}get itemsStale(){return this._itemsStale}_sayItemIssues(t,e){const n=this._itemIssues.length>0||this._itemsStale;this._itemIssues=t,this._itemsStale=e,(n||t.length>0||e)&&this.trigger?.("item-issues",this,t,e)}_keyedById(){return!1}async ready(){if(await super.ready(),!this._itemsFromData())return;const t=this.state?.data;Array.isArray(t)&&0===this._items.length&&!this.isRecordStorage&&this._reconcileItems(t)}set data(t){if(Array.isArray(t)&&this._itemsFromData()){if(this.isRecordStorage){const e=this.setState;return void("function"==typeof e&&e.call(this,{data:t}))}this._reconcileItems(t)}else this.setState?.({data:t})}get data(){if(!this._itemsFromData())return this.state?.data;if(this.isRecordStorage)return this.state?.data??[];const t=this._exportSlotRecords();return 0===t.length?this.state?.data:t}_reconcileItems(t){if(this._keyedById())return this._reconcileItemsById(t);const e=new Map;for(const n of t){const t=this._recordKey(n);t&&e.set(t,n)}const n=new Map;for(const t of this._items){const e=this._currentKeyOf(t);null!=e&&n.set(e,t)}for(const[t,s]of n)if(!e.has(t)){try{this.removeItem(s,!0)}catch{}ph(s);try{s?.dispose?.()}catch{}}for(const[t,s]of e){if(n.has(t))continue;if(null==s.itemId)continue;const e=this._createItemFromRecord(s);if(e){e[_v]=t;try{this.handoverIn(e)}catch{}}}for(const[t,s]of e){const e=n.get(t);if(e&&s.itemState&&"function"==typeof e.setState)try{e.setState(s.itemState)}catch{}}}_reconcileItemsById(t){const e=new Map;t.forEach((t,n)=>{const s=this._recordKey(t);s&&(e.get(s)??e.set(s,[]).get(s)).push(n)});const n=[...e].filter(([,t])=>t.length>1);if(n.length>0)return void this._sayItemIssues(n.map(([t,e])=>({code:"item-duplicate",id:t,at:e})),!0);const s=new Map;for(const e of t)s.set(this._recordKey(e),e);const i=new Map;for(const t of this._items){const e=this._currentKeyOf(t);null!=e&&i.set(e,t)}const o=this._lastItemIds,r=this.root,a=[];for(const[t,e]of i)s.has(t)||setTimeout(()=>{if(e.parent===this){try{this.removeItem(e,!0)}catch{}ph(e);try{e?.dispose?.()}catch{}}},0);for(const[t,e]of s){if(i.has(t))continue;const n=dh(r,t);let s,c=!1;if(n&&n.parent!==this){if(o.has(t)){const e=n.parent?.state?.id;a.push({code:"item-repeat-report",id:t,holder:null!=e?String(e):null});continue}s=n,c=!!n.parent}else s=this._createItemFromRecord(e);if(!s)continue;s[_v]=e.slotId;const l=c?this.itemMoveAnimation():null,h={...e.slotId?{slotId:e.slotId}:{},...l?{animated:!0,...l}:{}};try{this.handoverIn(s,Object.keys(h).length?h:void 0)}catch{}}for(const[t,e]of s){const n=i.get(t);if(n){if(e.itemState&&"function"==typeof n.setState)try{n.setState(e.itemState)}catch{}if(e.itemType&&n.state?.type!==e.itemType&&"function"==typeof n.setState)try{n.setState({type:e.itemType})}catch{}if(n[_v]!==e.slotId){n[_v]=e.slotId;try{this.handoverIn(n,e.slotId?{slotId:e.slotId}:void 0)}catch{}}}}this._orderItemsAs([...s.keys()]),this._lastItemIds=new Set(s.keys()),this._sayItemIssues(a,!1)}itemMoveAnimation(){return null}_orderItemsAs(t){const e=new Map(t.map((t,e)=>[t,e])),n=this._items.filter(t=>e.has(this._currentKeyOf(t)??"")),s=[...n].sort((t,n)=>e.get(this._currentKeyOf(t))-e.get(this._currentKeyOf(n)));if(s.every((t,e)=>t===n[e]))return;let i=0;for(let t=0;t<this._items.length;t++)e.has(this._currentKeyOf(this._items[t])??"")&&(this._items[t]=s[i++]);const o=this.seatHeldItem;if("function"==typeof o)for(const t of s)o.call(this,t,{slotId:t[_v]})}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,s=[];for(const t of this._items){const e=t[_v];null!=e?n.set(String(e),t):s.push(t)}for(const s of t){const t=n.get(s)??null;e.push(this._slotRecordOf(s,t))}for(const t of s)e.push(this._slotRecordOf("",t));for(const[s,i]of n)t.includes(s)||e.push(this._slotRecordOf(s,i));return e}_recordKey(t){return this._keyedById()?null!=t.itemId?String(t.itemId):"":t.slotId??t.cellId??""}_slotRecordOf(t,e){if(!e)return{slotId:t,itemId:null};const n=e?.state?.id;return{slotId:t,itemId:null!=n?String(n):null,itemType:e?.state?.type,itemState:this._extractItemState(e)}}_extractItemState(t){const e=t?.state;if(!e||"object"!=typeof e)return;const n=this._businessFields?.();if(Array.isArray(n)){if(0===n.length)return;const t={};for(const s of n)s in e&&void 0!==e[s]&&(t[s]=e[s]);return Object.keys(t).length>0?t:void 0}const s={};for(const t of Object.keys(e))xv.has(t)||t.startsWith("_")||(s[t]=e[t]);return Object.keys(s).length>0?s:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=uc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}const Mv=new Map;function Sv(t){return t.userData.__bankOwned=!0,t}const Av={primitive(t){const e="primitive::"+function(t){switch(t.kind){case"cylinder":return`cylinder|${t.segments??0}`;case"sphere":return`sphere|${t.segments??0}|${t.heightSegments??0}`;default:return t.kind}}(t);let n=Mv.get(e);return n||Mv.set(e,n=Sv(function(t){switch(t.kind){case"box":return new w.BoxGeometry(1,1,1);case"plane":return new w.PlaneGeometry(1,1);case"cylinder":return new w.CylinderGeometry(.5,.5,1,t.segments??16);case"sphere":return new w.SphereGeometry(.5,t.segments??16,t.heightSegments??Math.max(2,Math.round((t.segments??16)/2)))}}(t))),n},shaped(t,e){const n="shaped::"+t;let s=Mv.get(n);return s||Mv.set(n,s=Sv(e())),s},owns:t=>!0===t.userData?.__bankOwned,get size(){return Mv.size},has:t=>Mv.has("primitive::"+t)||Mv.has("shaped::"+t),dispose(){for(const t of Mv.values())t.dispose();Mv.clear()}};let kv=null;const Ev=new Set;let Tv=null;function Cv(){for(const t of[...Ev]){const e=t.deref();e?e.refreshLook():Ev.delete(t)}}function Ov(t){Tv?.(),kv=t,Tv=t?t.subscribe(Cv):null,Cv()}function Pv(t){return kv?.dimsOf(t)??null}const Iv=t=>Number(t.component.state.depth)||t.depth,Dv="#9e9e9e";class zv extends(mc(pc)){constructor(){super(...arguments),this._look=null,this._lookKey=null,this._seatDims=null,this.lookResized=t=>{!("width"in t||"height"in t||"depth"in t)||this.sized||this._seatDims||this.parent?._reseatSlot?.(this[_v])}}get itemTypeCode(){return this.state.type}get drawnAsItem(){return!0}get isItem(){return!0}is3dish(){return!0}get lookNow(){return this._look}get look(){this._lookRef||Ev.add(this._lookRef=new WeakRef(this));const t=kv?.keyFor(this)??null;return(t!==this._lookKey||t&&!this._look)&&(this._look?.dispose(),this._look=t?kv?.lookFor(this)??null:null,this._lookKey=this._look?t:null,this._look?.component.on?.("change",this.lookResized),this.fitLook()),this._look}get seatDims(){return this._seatDims}takeSeatDims(t){((t,e)=>t===e||!!t&&!!e&&t.width===e.width&&t.depth===e.depth&&t.height===e.height)(t,this._seatDims)||(this._seatDims=t?{...t}:null,this.sized||(this.fitLook(),this._realObject?.rebuildLook?.(),this.invalidate?.()))}fitLook(){this._look&&!this.sized&&this._seatDims&&this._look.fitTo(this._seatDims)}refreshLook(){const t=kv?.keyFor(this)??null;if(t===this._lookKey&&(!t||this._look))return;this._look?.dispose(),this._look=null,this._lookKey=null;const e=this._realObject,n=this.parent;e&&e instanceof Rv!==this.drawnAsItem?(n?.trigger?.("item-remake",n,this),n?._reseatSlot?.(this[_v])):(e?.rebuildLook?.(),!e||this.sized||this._seatDims||n?._reseatSlot?.(this[_v])),this.invalidate?.()}onchange(t,e){super.onchange?.(t,e),"type"in t&&(this.refreshLook(),this.parent?._reseatSlot?.(this[_v])),"data"in t&&this._look&&this._look.component.set("data",t.data)}get sized(){const{width:t=0,height:e=0,depth:n=0}=this.state;return t>0&&e>0&&n>0}get shownSize(){if(this.sized||!this._seatDims)return this.shownSizeOutOfSeat;const t=rh(this).mmPerUnit;return{width:this._seatDims.width/t,height:this._seatDims.depth/t,depth:this._seatDims.height/t}}get shownSizeOutOfSeat(){if(this.sized){const{width:t,height:e,depth:n}=this.state;return{width:t,height:e,depth:n}}const t=this.look;if(t)return{width:Number(t.component.state.width)||0,height:Number(t.component.state.height)||0,depth:Iv(t)};const e=200/rh(this).mmPerUnit;return{width:e,height:e,depth:e}}get bounds(){const{left:t=0,top:e=0,width:n=0,height:s=0}=this.state;if(n>0&&s>0)return super.bounds;const i=this.shownSize;return{left:t,top:e,width:i.width,height:i.height}}render(t){const{left:e,top:n,width:s,height:i}=this.bounds,o=this.look;if(o){const r=o.component,a={left:e+(s-(Number(r.state.width)||0))/2,top:n+(i-(Number(r.state.height)||0))/2};return r.state.left===a.left&&r.state.top===a.top||r.set(a),void r.render(t)}t.save(),t.fillStyle=this.state.fillStyle||Dv,t.strokeStyle=this.state.strokeStyle||"#616161",t.lineWidth=1,this.sized||t.setLineDash([4,3]),t.beginPath(),t.rect(e,n,s,i),this.sized&&t.fill(),t.stroke(),t.restore()}buildRealObject(){return this.drawnAsItem?new Rv(this):void 0}dispose(){this._lookRef&&Ev.delete(this._lookRef),this._look?.dispose(),this._look=null,super.dispose()}}class Rv extends Du{constructor(){super(...arguments),this.box=null,this.shown=null}getObject3dInstance(){return new w.Group}build(){super.build(),this.rebuildLook()}rebuildLook(){this.box&&(this.object3d.remove(this.box),this.box.material.dispose(),this.box=null),this.shown&&(this.object3d.remove(this.shown),this.shown=null);const t=this.component,e=t.look,n=t.shownSize;if(e){const t=e.component.realObject,s=t?.object3d;if(!t||!s)return;return t.suppressTransform=!0,s.position.set(0,(Iv(e)-n.depth)/2,0),s.quaternion.identity(),this.object3d.add(s),void(this.shown=s)}const s=new w.Mesh(Av.primitive({kind:"box"}),new w.MeshStandardMaterial({color:t.state.fillStyle||Dv,wireframe:!t.sized&&!t.seatDims}));s.scale.set(n.width,n.depth,n.height),this.object3d.add(s),this.box=s}dispose(){const t=this.component.lookNow,e=t?.component._realObject;e&&(e.dispose(),t.component._realObject=void 0),super.dispose(),this.component._realObject===this&&(this.component._realObject=void 0)}clear(){return this.box=null,this.shown=null,super.clear()}}const jv=["x","y","z"],$v=["Capacity","Holdable","Transferable","FlowNode"],Lv=/^[a-z0-9][a-z0-9-]*\.[A-Za-z][A-Za-z0-9]*$/,Fv=t=>"string"==typeof t&&Lv.test(t),Nv=t=>$v.includes(t)||Fv(t),Hv=Object.freeze({Transferable:["Capacity","FlowNode"]}),Bv=100,Gv=["S","M","L","XL"],Uv=[8,12,16,24,32,48],Vv=Object.freeze({x:"size.x",y:"size.y",z:"size.z"}),Wv=8192;function Yv(t,e){const n="shape"in t?t.shape:void 0,s=n?.extrusion?.section,i="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===s?.kind||"rectangle"===s?.kind&&Object.values(s.corner??{}).some(t=>t>0));if(!i||"full"===e)return t.segments;const o=t.segments??12,r=Math.ceil(o/("medium"===e?2:4));return Math.min(o,Uv.find(t=>t>=r)??o)}function qv(t,e){if("full"===e)return t;let n=!1;const s=t.geometry.map(t=>{const s=Yv(t,e);return s===t.segments?t:(n=!0,{...t,segments:s})});return n?{...t,geometry:s}:t}class Xv extends Error{code;path;details;constructor(t,e,n,s){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==s&&(this.details=s)}}const Kv=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),Jv=1e-6,Qv=256,Zv=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function t_(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const e_=t=>Kv[t],n_=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function s_(t,e){const[n,s]=e_(e);if("rectangle"===t.kind){const e=[];for(const i of[n,s]){const n=t.size[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`size.${i}`})}if(!t.corner)return e;for(const i of[n,s]){const n=t.corner[i];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:i}):Number.isFinite(t.size[i])&&n>t.size[i]/2+Jv&&e.push({code:"CORNER_TOO_LARGE",axis:i,max:t.size[i]/2}):e.push({code:"NON_FINITE",at:`corner.${i}`})}return e.length||t.corner[n]>0==t.corner[s]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:s}),e}if("ellipse"===t.kind){const e=[];for(const i of[n,s]){const n=t.radius[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`radius.${i}`})}return e}return function(t,e){const[n,s]=e_(e),i=[],o=new Set;for(const e of t){"string"==typeof e.id&&Zv.test(e.id)?o.has(e.id)?i.push({code:"DUPLICATE_POINT_ID",point:e.id}):o.add(e.id):i.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,s])"number"==typeof e[t]&&Number.isFinite(e[t])||i.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&i.push({code:"TOO_FEW_POINTS",count:t.length});t.length>Qv&&i.push({code:"TOO_MANY_POINTS",count:t.length,limit:Qv});if(i.length)return i;const r=t.length,a=function(t,e){const[n,s]=e_(e);return t.map(t=>[t[n],t[s]])}(t,e),c=e=>t_(t[e].id,t[(e+1)%r].id),l=Jv,h=a.map((t,e)=>Math.hypot(a[(e+1)%r][0]-t[0],a[(e+1)%r][1]-t[1]));if(h.forEach((t,e)=>{t<=l&&i.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),i.length)return i;for(let t=0;t<r;t++){const e=a[t],n=a[(t+1)%r],s=a[(t+2)%r],o=(n[0]-e[0])*(s[1]-n[1])-(n[1]-e[1])*(s[0]-n[0]),d=(n[0]-e[0])*(s[0]-n[0])+(n[1]-e[1])*(s[1]-n[1]);Math.abs(o)<=l*h[t]&&d<0&&i.push({code:"SIDES_FOLD",sides:[c(t),c((t+1)%r)]})}for(let t=0;t<r;t++)for(let e=t+1;e<r;e++){if(e===t+1||0===t&&e===r-1)continue;const n=r_(a[t],a[(t+1)%r],a[e],a[(e+1)%r],l);n&&i.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(i.length)return i;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[s,i]=t[n],[o,r]=t[(n+1)%t.length];e+=s*r-o*i}return e}(a))/2<=l&&i.push({code:"ZERO_AREA"});return i}(t.points,e)}const i_=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function o_(t,e,n){const s=n[0]-e[0],i=n[1]-e[1],o=s*s+i*i,r=o?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*i)/o)):0;return Math.hypot(t[0]-e[0]-r*s,t[1]-e[1]-r*i)}function r_(t,e,n,s,i){const o=i_(n,s,t),r=i_(n,s,e),a=i_(t,e,n),c=i_(t,e,s),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>i*n&&e<-i*n||t<-i*n&&e>i*n;if(h(o,r,Math.hypot(s[0]-n[0],s[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(o_(t,n,s),o_(e,n,s),o_(n,t,e),o_(s,t,e))<=i?"touch":null}function a_(t,e){const[n,s]=e_(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,i]=[n,s].sort(),o=[e,i].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!n_(t))return o;const r=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${i}${n}`,shape:"curved"})));return[...o,...r]}const i=t.points;return i.map((t,e)=>{const n=i[(e+1)%i.length];return{id:t_(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function c_(t,e,n){const[s,i]=e_(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const o=[s,i].flatMap(t=>[`${t}-`,`${t}+`]);for(const t of o){const e=n[t];if("number"!=typeof e||!Number.isFinite(e))return{refused:"NON_FINITE",side:t};if(!(e>0))return{refused:"WALL_NOT_POSITIVE",side:t}}const r=t=>n[t],a=(t,e)=>e-r(`${t}-`)-r(`${t}+`),c={[s]:(r(`${s}-`)-r(`${s}+`))/2,[i]:(r(`${i}-`)-r(`${i}+`))/2};if("rectangle"===t.kind){const e={[s]:a(s,t.size[s]),[i]:a(i,t.size[i])};if(!(e[s]>0&&e[i]>0))return{refused:"NO_ROOM_INSIDE"};if(!n_(t))return{section:{kind:"rectangle",size:e},centre:c};const n=e=>Math.max(t.corner[e]-Math.max(r(`${e}-`),r(`${e}+`)),0),o={[s]:n(s),[i]:n(i)};return{section:{kind:"rectangle",size:e,...o[s]>0&&o[i]>0?{corner:o}:{}},centre:c}}const l={[s]:a(s,2*t.radius[s])/2,[i]:a(i,2*t.radius[i])/2};return l[s]>0&&l[i]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const l_=(t,e)=>Object.fromEntries(jv.map(n=>[n,n===t?e:0]));function h_(t,e,n){const[s,i]=Kv[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return l_(t,n.id.endsWith("+")?1:-1)}const o=t.points.find(t=>t.id===n.from),r=t.points.find(t=>t.id===n.to),a=r[s]-o[s],c=r[i]-o[i],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[s]=c/l||0,h[i]=-a/l||0,h}const d_=(t,e,n,s)=>{throw new Xv(t,e,n,s)},u_=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],p_=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),f_=["rectangle","ellipse","polygon","portal"],m_=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function g_(t,e){const n=t??{},s=n.axis;jv.includes(s)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const i=n.section;f_.includes(i)||d_("PARAM",e,`section is ${f_.join(", ")}, not ${String(n.section)}`);const o=[...Kv[s]].sort(),[r,a]=o,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===i||d_("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===i?String(n.points??"").split("."):[];"polygon"===i?((l.length<3||l.some(t=>!m_.test(t)))&&d_("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&d_("PARAM",e,"a point is named twice")):void 0!==n.points&&d_("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==i&&"ellipse"!==i&&"portal"!==i||(u.across={[r]:d(),[a]:d()}),c&&(u.corner={[r]:d(),[a]:d()}),"portal"===i&&(u.jamb=d(),u.head=d()),"polygon"===i&&(u.point=Object.fromEntries(l.map(t=>[t,{[r]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==i&&"ellipse"!==i&&d_("SECTION_KIND",e,`a ${i} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const s=n[t];return"open"!==s&&"closed"!==s&&d_("PARAM",e,`${t} is open or closed`),s};p={id:n.cavity,start:t("cavity-start"),end:t("cavity-end")},u.wall=Object.fromEntries([r,a].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>[t,d()])),"closed"===p.start&&(u.startClosed=d()),"closed"===p.end&&(u.endClosed=d())}else void 0===n["cavity-start"]&&void 0===n["cavity-end"]||d_("PARAM",e,"the ends of an inside need the inside");return{axis:s,plane:o,section:i,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const y_=(t,e=1)=>[{arg:t,k:e}];function b_(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const s=t.args?.[0],i=t.args?.[1],o=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(s));return"mul@1"!==o?.op||2!==o.args.length||o.args[0]!==i||-.5!==e.constants.find(t=>t.id===o.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function v_(t,e){const n=g_(t.params,t.id),[s,i]=n.plane,o={},r={},a={},[c,l]=p_[n.axis],h=b_(t,e);if(o[n.axis]=y_(1),r[n.axis]={arg:1,k:1},a[c]={axis:n.axis,normal:-1,plane:h.lo},a[l]={axis:n.axis,normal:1,plane:h.hi},"polygon"===n.section){for(const t of[s,i])o[t]="profile",r[t]={refused:"SECTION_CORNERS"};return{measure:o,edit:r,faces:a,kind:"polygon"}}const d=n.arg.across,u="ellipse"===n.section?2:1;for(const t of[s,i])o[t]=y_(d[t],u),r[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[s]]&&t.args[d[s]]===t.args[d[i]]&&(r[i]={arg:d[i],k:u,sameAs:s}),"portal"===n.section){const[t,e]=p_[s],[c,l]=p_[i];return a[t]={axis:s,normal:-1,plane:[{arg:d[s],k:-.5}]},a[e]={axis:s,normal:1,plane:[{arg:d[s],k:.5}]},a[c]={axis:i,normal:-1,plane:[]},a[l]={axis:i,normal:1,plane:[{arg:d[i],k:1}]},a[`opening-${t}`]={axis:s,normal:1,plane:[{arg:d[s],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:s,normal:-1,plane:[{arg:d[s],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:i,normal:-1,plane:[{arg:d[i],k:1},{arg:n.arg.head,k:-1}]},{measure:o,edit:r,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[s,i]){const[e,n]=p_[t];a[e]={axis:t,normal:-1,plane:[{arg:d[t],k:-p}],...f},a[n]={axis:t,normal:1,plane:[{arg:d[t],k:p}],...f}}if(n.cavity){const t=n.arg.wall;for(const e of[s,i]){const[n,s]=p_[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${s}`]={axis:e,normal:-1,plane:[{arg:d[e],k:p},{arg:t[`${e}+`],k:-1}],...f}}void 0!==n.arg.startClosed&&(a[`inside-${c}`]={axis:n.axis,normal:1,plane:[...h.lo,{arg:n.arg.startClosed,k:1}]}),void 0!==n.arg.endClosed&&(a[`inside-${l}`]={axis:n.axis,normal:-1,plane:[...h.hi,{arg:n.arg.endClosed,k:-1}]})}return{measure:o,edit:r,faces:a,kind:n.section}}function __(t,e){const n=t??{},s=n.axis;return jv.includes(s)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&d_("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:s,profile:n.profile,count:"taper"===n.profile?4:2}}function x_(t,e){const n=__(t.params,t.id),[s,i]=[...Kv[n.axis]].sort(),o={},r={};if("half-ellipse"===n.profile)return o[n.axis]=y_(1,2),r[n.axis]={arg:1,k:2},o[s]=o[i]=y_(0,2),r[s]={arg:0,k:2},r[i]={arg:0,k:2,sameAs:s},{measure:o,edit:r,faces:{},kind:"sphere"};const[a,c]=p_[n.axis];o[n.axis]=y_(1),r[n.axis]={arg:1,k:1};o[s]=o[i]=[{arg:2,k:2},{arg:3,k:2}],r[s]={arg:3,k:2,with:[2]},r[i]={arg:3,k:2,with:[2],sameAs:s};const l=b_(t,e);return{measure:o,edit:r,faces:{[a]:{axis:n.axis,normal:-1,plane:l.lo},[c]:{axis:n.axis,normal:1,plane:l.hi}},kind:"taper"}}function w_(t,e){const n=t??{};"polygon"!==n.section&&d_("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||d_("PARAM",e,"a loft has no corners and no inside");const s=g_(n,e),[i,o]=s.plane;return{...s,apex:{[i]:s.count,[o]:s.count+1},count:s.count+2}}function M_(t,e){const n=w_(t.params,t.id),s={},i={},[o]=p_[n.axis];s[n.axis]=y_(1),i[n.axis]={arg:1,k:1};for(const t of n.plane)s[t]="profile",i[t]={refused:"SECTION_CORNERS"};return{measure:s,edit:i,faces:{[o]:{axis:n.axis,normal:-1,plane:b_(t,e).lo}},kind:"pyramid"}}const S_=["glb"],A_={m:1e3,mm:1},k_=/^sha256-([0-9a-f]{64})$/,E_=new RegExp(`^mm${"_(-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e-?\\d+)?)".repeat(6)}$`),T_=/^n(\d+)$/,C_=/^node-(\d+)$/;function O_(t,e){const n=t??{},s=k_.exec(n.asset??"")?.[1];s||d_("PARAM",e,"asset is sha256- and the file's 64 lower-case hex digits"),S_.includes(n.format)||d_("PARAM",e,`format is ${S_.join(" or ")}, not ${String(n.format)}`),Object.hasOwn(A_,n.unit??"")||d_("PARAM",e,`unit is ${Object.keys(A_).join(" or ")}, not ${String(n.unit)}`);const i=void 0===n.node?void 0:C_.exec(n.node)?.[1];void 0!==n.node&&void 0===i&&d_("PARAM",e,"node, when given, is node- and its place in the file");const o=E_.exec(n.bounds??""),r=(o??[]).slice(1).map(Number);o&&6===r.length&&r.every(Number.isFinite)||d_("PARAM",e,"bounds are mm_ and six numbers: min x, y, z, then max x, y, z");const a={x:{min:r[0],max:r[3]},y:{min:r[1],max:r[4]},z:{min:r[2],max:r[5]}};jv.some(t=>!(a[t].max>=a[t].min))&&d_("PARAM",e,"each bound's max is at least its min");const c=n.axis;jv.includes(c)||d_("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const l=t=>a[t].max-a[t].min;l(c)>0&&!jv.some(t=>l(t)>l(c))||d_("PARAM",e,"axis is the one the bounds reach furthest along, and it has a reach");const h=t=>{const s=Number(T_.exec(n[t]??"")?.[1]);return Number.isSafeInteger(s)||d_("PARAM",e,`${t} is n and a count`),s};return{asset:s,format:n.format,...void 0!==i?{node:Number(i)}:{},unit:n.unit,bounds:a,axis:c,triangles:h("triangles"),primitives:h("primitives")}}function P_(t){const e=O_(t.params,t.id),n=e.bounds[e.axis].max-e.bounds[e.axis].min,s={},i={},o={};for(const t of jv){const r=(e.bounds[t].max-e.bounds[t].min)/n;s[t]=[{arg:0,k:r}],i[t]=t===e.axis?{arg:0,k:1}:{refused:r>0?"MESH_UNIFORM":"NO_MEASURE"};const[a,c]=p_[t];o[a]={axis:t,normal:-1,plane:[{arg:0,k:e.bounds[t].min/n}],contact:"bounds"},o[c]={axis:t,normal:1,plane:[{arg:0,k:e.bounds[t].max/n}],contact:"bounds"}}return{measure:s,edit:i,faces:o,kind:"mesh"}}function I_(t,e){return"extrude@1"===t?.op?v_(t,e):"revolve@1"===t?.op?x_(t,e):"loft@1"===t?.op?M_(t,e):"mesh@1"===t?.op?P_(t):void 0}const D_=(t,e)=>Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{axis:n.axis,normal:n.normal,at:n.plane.reduce((t,n)=>t+n.k*e[n.arg],0)}]));function z_(t,e,n){const s=jv.find(t=>t!==e&&t!==n),[i,o]=Kv[s];let r=0;for(let e=0;e<t.length;e++){const n=t[e],s=t[(e+1)%t.length];r+=n[i]*s[o]-s[i]*n[o]}return r>0?t:[t[0],...t.slice(1).reverse()]}function R_(t,e){const[n,s]=Kv[e];let i=0;const o=t.points;for(let t=0;t<o.length;t++){const e=o[t],r=o[(t+1)%o.length];i+=e[n]*r[s]-r[n]*e[s]}return i}function j_(t,e,n){const s=g_(n.params,e),[i,o]=s.plane,r=t[0],a=t[1];a>0||d_("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:r,length:a};let l;if("polygon"===s.section){const e=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[o]:t[s.arg.point[e][o]]}));e.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${o}`]=t[o]}),l={kind:"polygon",points:e}}else if("portal"===s.section){const n=t[s.arg.across[i]],r=t[s.arg.across[o]],a=t[s.arg.jamb],h=t[s.arg.head];n>0&&r>0&&a>0&&h>0&&2*a<n&&h<r||d_("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${i}`]:n,[`size.${o}`]:r,jamb:a,head:h}),l=function(t,e,n,s,i,o){const r=-n/2,a=n/2,c=r+i,l=a-i,h=s-o,d=(n,s,i)=>({id:n,[t]:s,[e]:i});return{kind:"polygon",points:z_([d("p1",r,0),d("p2",r,s),d("p3",a,s),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(i,o,n,r,a,h)}else{const e={[i]:t[s.arg.across[i]],[o]:t[s.arg.across[o]]},n="ellipse"===s.section?"radius":"size";if(c[`${n}.${i}`]=e[i],c[`${n}.${o}`]=e[o],"ellipse"===s.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},s.rounded){const n={[i]:t[s.arg.corner[i]],[o]:t[s.arg.corner[o]]};c[`corner.${i}`]=n[i],c[`corner.${o}`]=n[o],(n[i]>0||n[o]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=s_(l,s.axis);h.length&&d_("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`,{reason:"section-invalid",issues:h}),"polygon"!==l.kind||"polygon"!==s.section||R_(l,s.axis)>0||d_("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:s.axis,section:l,start:r,end:r+a};let u;if(s.cavity){const n=Object.fromEntries(Object.entries(s.arg.wall).map(([e,n])=>[e,t[n]]));u={id:s.cavity.id,wall:n,start:"open"===s.cavity.start?"open":{closed:t[s.arg.startClosed]},end:"open"===s.cavity.end?"open":{closed:t[s.arg.endClosed]}};for(const[t,e]of Object.entries(n))c[`wall.${t}`]=e;"open"!==u.start&&(c["closed.start"]=u.start.closed),"open"!==u.end&&(c["closed.end"]=u.end.closed);const i=function(t,e=[]){const{axis:n,section:s,start:i,end:o}=t;if(!(o-i>0))return{refused:{code:"SPAN_NOT_POSITIVE"}};if(e.length>1)return{refused:{code:"CAVITY_COUNT",count:e.length}};const r=e[0];let a;if(r){const t=c_(s,n,r.wall);if("refused"in t)return{refused:{code:"CAVITY",cavity:r.id,refused:t.refused,...t.side?{side:t.side}:{}}};a=t.section;const e=t=>"open"===t?0:t.closed;for(const t of["start","end"]){const e=r[t];if("open"!==e&&!(e.closed>0))return{refused:{code:"CAVITY_END_NOT_POSITIVE",cavity:r.id,end:t}}}if(!(o-i-e(r.start)-e(r.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:r.id}}}const c=a_(s,n),l=[{id:"start-face",kind:"plane",normal:l_(n,-1),..."open"===r?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:l_(n,1),..."open"===r?.end?{open:!0}:{}}];for(const t of c)l.push("flat"===t.shape?{id:`side-face:${t.id}`,kind:"plane",normal:h_(s,n,t)}:{id:`side-face:${t.id}`,kind:"curved"}),l.push({id:`edge:start:${t.id}`,kind:"edge"},{id:`edge:end:${t.id}`,kind:"edge"});if("polygon"===s.kind)for(const t of s.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===s.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...Kv[n]].sort();for(const n of["-","+"])for(const s of["-","+"])l.push({id:`edge:${t}${n}${e}${s}`,kind:"edge"})}if(r&&a){for(const t of a_(a,n)){const e=`cavity-wall:${r.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const s=h_(a,n,t);l.push({id:e,kind:"plane",normal:{x:-s.x||0,y:-s.y||0,z:-s.z||0}})}}"open"!==r.start&&l.push({id:`cavity-start:${r.id}`,kind:"plane",normal:l_(n,1)}),"open"!==r.end&&l.push({id:`cavity-end:${r.id}`,kind:"plane",normal:l_(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in i&&d_("GEOMETRY_DOMAIN",e,`the inside is not valid: ${i.refused.code}${"refused"in i.refused?` ${i.refused.refused}`:""}`,{reason:"inside-invalid",refusal:i.refused})}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:D_(v_(n).faces,t)}}function $_(t,e,n){const s=__(n.params,e),i=D_(x_(n).faces,t);if("half-ellipse"===s.profile){const[n,o]=t;return n>0&&o>0||d_("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:o},revolution:{axis:s.axis,profile:{kind:"half-ellipse",radial:n,axial:o}},faces:i}}const[o,r,a,c]=t;return r>0&&a>=0&&c>=0&&a+c>0||d_("GEOMETRY_DOMAIN",e,"a positive length and radii of 0 or more, not both 0, required"),{provider:"revolve",dimensions:{start:o,length:r,startRadius:a,endRadius:c},revolution:{axis:s.axis,profile:{kind:"taper",start:o,end:o+r,startRadius:a,endRadius:c}},faces:i}}function L_(t,e,n){const s=w_(n.params,e),[i,o]=s.plane,r=t[0],a=t[1];a>0||d_("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:r,length:a},l=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[o]:t[s.arg.point[e][o]]}));l.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${o}`]=t[o]});const h={kind:"polygon",points:l},d=s_(h,s.axis);d.length&&d_("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`,{reason:"section-invalid",issues:d}),R_(h,s.axis)>0||d_("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[i]:t[s.apex[i]],[o]:t[s.apex[o]]};return Number.isFinite(u[i])&&Number.isFinite(u[o])||d_("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${i}`]=u[i],c[`apex.${o}`]=u[o],{provider:"loft",dimensions:c,loft:{axis:s.axis,section:h,start:r,end:r+a,apex:u},faces:D_(M_(n).faces,t)}}function F_(t,e,n){const s=O_(n.params,e),i=t[0];i>0||d_("GEOMETRY_DOMAIN",e,`a mesh of positive size required, not ${i}`);const o=i/(s.bounds[s.axis].max-s.bounds[s.axis].min),r=Object.fromEntries(jv.map(t=>[t,{min:s.bounds[t].min*o,max:s.bounds[t].max*o}]));return{provider:"mesh",dimensions:{size:i},mesh:{asset:s.asset,format:s.format,...void 0!==s.node?{node:s.node}:{},unit:s.unit,scale:A_[s.unit]*o,bounds:r,triangles:s.triangles,primitives:s.primitives},faces:D_(P_(n).faces,t)}}function N_(t,e,n){return{kind:"shape",provider:t,frame:e.params.frame,faces:Object.fromEntries(Object.entries(n).map(([t,e])=>[t,e.contact?[e.axis,e.normal,e.contact]:[e.axis,e.normal]]))}}const H_={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const s=g_(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a ${s.section} push takes ${s.count} lengths, not ${t.length}`),[N_("extrude",n,v_(n).faces)]},run:(t,e,n)=>[j_(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const s=__(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a ${s.profile} turn takes ${s.count} lengths, not ${t.length}`),[N_("revolve",n,x_(n).faces)]},run:(t,e,n)=>[$_(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const s=w_(n.params,e);return t.length===s.count&&t.every(u_)||d_("TYPE",e,`a loft of ${s.points.length} points takes ${s.count} lengths, not ${t.length}`),[N_("loft",n,M_(n).faces)]},run:(t,e,n)=>[L_(t,e,n)]},"mesh@1":{ports:["shape"],params:["frame","asset","format","unit","bounds","axis","triangles","primitives"],optionalParams:["node"],types:(t,e,n)=>(1===t.length&&t.every(u_)||d_("TYPE",e,`a mesh takes one length, its size, not ${t.length}`),[N_("mesh",n,P_(n).faces)]),run:(t,e,n)=>[F_(t,e,n)]}};function B_(t){if(t.mesh)return Object.fromEntries(jv.map(e=>[e,{...t.mesh.bounds[e]}]));const e={};if(t.extrusion){const n=t.extrusion,[s,i]=Kv[n.axis];e[n.axis]={min:n.start,max:n.end};const o=n.section;for(const t of[s,i])if("rectangle"===o.kind)e[t]={min:-o.size[t]/2,max:o.size[t]/2};else if("ellipse"===o.kind)e[t]={min:-o.radius[t],max:o.radius[t]};else{const n=o.points.map(e=>e[t]);e[t]={min:Math.min(...n),max:Math.max(...n)}}return e}if(t.loft){const n=t.loft;e[n.axis]={min:n.start,max:n.end};for(const t of Kv[n.axis]){const s=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...s),max:Math.max(...s)}}return e}const n=t.revolution,[s,i]=Kv[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[s,i])e[t]={min:-n.profile.radial,max:n.profile.radial}}else{const t=Math.max(n.profile.startRadius,n.profile.endRadius);e[n.axis]={min:n.profile.start,max:n.profile.end};for(const n of[s,i])e[n]={min:-t,max:t}}return e}function G_(t,e){const n=I_(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}const U_=1e4,V_=(t,e,n,s)=>{throw new Xv(t,e,n,s)},W_={mm:[[1,0,0],1],cm:[[1,0,0],10],m:[[1,0,0],1e3],rad:[[0,1,0],1],deg:[[0,1,0],Math.PI/180],s:[[0,0,1],1],ratio:[[0,0,0],1],percent:[[0,0,0],.01]},Y_=[1,0,0],q_=[0,0,0],X_=[0,1,0],K_={kind:"count"},J_={kind:"flag"};W_.count=[K_,1];const Q_=(t,e)=>Array.isArray(t)&&Array.isArray(e)?t.length===e.length&&t.every((t,n)=>t===e[n]):JSON.stringify(t)===JSON.stringify(e);function Z_(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||V_("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||V_("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||V_("SCHEMA",s,`unknown ${i}`)}function tx(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||V_("ID",e,"invalid id"),t}function ex(t,e){return"number"==typeof t&&Number.isFinite(t)||V_("NON_FINITE",e,String(t)),t}function nx(t,e){return Object.hasOwn(W_,t)||V_("UNIT",e,String(t)),W_[t]}function sx(t,e,n){(t.length!==e.length||t.some((t,n)=>!Q_(t,e[n])))&&V_("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}Object.freeze(Object.keys(W_));const ix={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&Q_(t[0],t[1])||V_("TYPE",e,"addition needs same scalar dimensions"),[t[0]]),run:([t,e])=>[t+e]},"mul@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)||V_("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e+t[1][n])]),run:([t,e])=>[t*e]},"div@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)||V_("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&V_("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>(sx(t,[X_],e),[q_]),run:([t])=>[Math.sin(t)]},"geomean@1":{ports:["value"],types:(t,e)=>((t.length<2||t.length>3||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&V_("DOMAIN",e,"geometric mean of a negative value"),[Math.pow(t.reduce((t,e)=>t*e,1),1/t.length)])},"curve@1":{ports:["value"],types(t,e){(t.length<5||t.length%2==0||!t.every(Array.isArray))&&V_("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)Q_(t[n],t[0])||V_("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),Q_(t[n+1],t[2])||V_("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],s=(t.length-1)/2,i=e=>t[1+2*e],o=e=>t[2+2*e];for(let t=1;t<s;t++)i(t)>i(t-1)||V_("DOMAIN",e,`keys out of order: at[${t}] = ${i(t)} is not after at[${t-1}] = ${i(t-1)}`);if(n<=i(0))return[o(0)];if(n>=i(s-1))return[o(s-1)];let r=0;for(;r<s-2&&i(r+1)<=n;)r++;const a=(n-i(r))/(i(r+1)-i(r));return[o(r)+(o(r+1)-o(r))*a]}},"at-least@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&Q_(t[0],t[1])||V_("TYPE",e,"at-least compares two scalars of the same dimension"),[J_]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.max(...t)]},"hypot@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.hypot(...t)]},"min@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>Q_(e,t[0])))&&V_("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.min(...t)]},"between@1":{ports:["length","center"],types:(t,e)=>(sx(t,[Y_,Y_,Y_,Y_],e),[Y_,Y_]),run:([t,e,n,s],i)=>{(n<0||s<0)&&V_("DOMAIN",i,"negative margin");const o=e-t-n-s;return o>0||V_("NO_SPACE",i,`available=${e-t}; margins=${n+s}; deficit=${Math.max(0,-o)}; positive length required`),[o,(t+e+n-s)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>(sx(t,[Y_,Y_,Y_],e),Array(6).fill(Y_)),run:([t,e,n],s)=>([t,e,n].some(t=>!(t>0))&&V_("GEOMETRY_DOMAIN",s,"positive width,height,depth required"),[-t/2,t/2,-e/2,e/2,-n/2,n/2]),geometry:([t,e,n])=>({provider:"box@1",dimensions:{width:t,height:e,depth:n}})},"cylinder@1":{ports:["start","end","radialMin","radialMax"],types:(t,e)=>(sx(t,[Y_,Y_],e),Array(4).fill(Y_)),run:([t,e],n)=>(t>0&&e>0||V_("GEOMETRY_DOMAIN",n,"positive radius,length required"),[-e/2,e/2,-t,t]),geometry:([t,e])=>({provider:"cylinder@1",axis:"Y",dimensions:{radius:t,length:e}})}},ox=(t,e)=>({kind:"transform",from:t,to:e}),rx=()=>[[1,0,0],[0,1,0],[0,0,1]],ax=t=>t[0].map((e,n)=>t.map(t=>t[n])),cx=(t,e)=>t.reduce((t,n,s)=>t+n*e[s],0),lx=(t,e,n,s)=>0+t[0]*e+t[1]*n+t[2]*s,hx=(t,e)=>3===t.length&&3===e.length?[lx(t[0],e[0],e[1],e[2]),lx(t[1],e[0],e[1],e[2]),lx(t[2],e[0],e[1],e[2])]:t.map(t=>cx(t,e)),dx=(t,e)=>{if(3!==t.length||3!==e.length||t.some(t=>3!==t.length)||e.some(t=>3!==t.length))return t.map(t=>ax(e).map(e=>cx(t,e)));const[n,s,i]=e;return t.map(t=>[lx(t,n[0],s[0],i[0]),lx(t,n[1],s[1],i[1]),lx(t,n[2],s[2],i[2])])},ux=(t,e)=>3===t.length&&3===e.length?[t[0]+e[0],t[1]+e[1],t[2]+e[2]]:t.map((t,n)=>t+e[n]),px=(t,e)=>({r:dx(t.r,e.r),t:ux(hx(t.r,e.t),t.t)}),fx=t=>{const e=ax(t.r);return{r:e,t:hx(e,t.t.map(t=>-t))}};function mx(t,e,n=[]){Z_(t.params,e,n,t.id);for(const s of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])tx(t.params[s],t.id)}function gx(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&V_("TYPE",e,"rigid transforms required")}Object.assign(ix,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>(sx(t,[Y_,Y_,Y_,Y_,Y_,q_,K_],e),[{kind:"layout"}]),run:([t,e,n,s,i,o,r],a)=>{t>=0&&e>=0&&n>=0&&s>0&&i>0&&o>=0&&o<=1&&Number.isSafeInteger(r)&&r>=0&&r<=1e4||V_("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<s?0:1+Math.floor((c-s)/i);l>r&&V_("RESOURCE_LIMIT",a,`count=${l}, limit=${r}`,{reason:"copies-over-limit",count:l,limit:r});const h=l?c-s-(l-1)*i:0;return[{centers:Array.from({length:l},(t,n)=>e+s/2+o*h+n*i),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>(sx(t,[K_,Y_,Y_,Y_,Y_,q_,K_],e),[{kind:"layout"}]),run:([t,e,n,s,i,o,r],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(r)&&r>=0&&r<=1e4&&e>=0&&n>=0&&s>=0&&i>0&&o>=0&&o<=1||V_("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>r&&V_("RESOURCE_LIMIT",a,"fixed count exceeds limit",{reason:"copies-over-limit",count:t,limit:r}),!t)return[{centers:[],count:0}];const c=e-n-s-i;return(c<0||t>1&&c/(t-1)<i)&&V_("NO_SPACE",a,"fixed count non-overlapping items do not fit",{reason:"row-does-not-fit",count:t,length:e-n-s,extent:i}),[{centers:1===t?[n+i/2+o*c]:Array.from({length:t},(e,s)=>n+i/2+s*c/(t-1)),count:t}]}},"assembly@1":{ports:["assembly"],types:(t,e)=>(t.length&&!t.some(e=>"placed"!==e.kind&&"collection"!==e.kind||e.frame!==t[0].frame)||V_("FRAME_TYPE",e,"assembly members need one common frame"),[{kind:"assembly",frame:t[0].frame}]),run:(t,e,n)=>[{members:t.flatMap((t,e)=>t.items?t.items.map(t=>({key:t.key,path:t.path,shape:t.shape,pose:t.pose})):[{key:n.args[e],...t}])}]},"repeat@1":{ports:["collection"],params:["axis"],optionalParams:["riseAxis","within"],types(t,e,n){["x","y","z"].includes(n.params.axis)||V_("AXIS",e,n.params.axis);const s=4===t.length;return!s||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&Q_(t[3],Y_)||V_("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!s||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&V_("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,s],i,o)=>{t.count*e.members.length>U_&&V_("RESOURCE_LIMIT",i,"expanded geometry count > 10000",{reason:"geometry-over-limit",count:t.count*e.members.length,limit:U_});const r=["x","y","z"].indexOf(o.params.axis),a=["x","y","z"].indexOf(o.params.riseAxis),c=[];for(let i=0;i<t.count;i++)for(const l of e.members){const e=[0,0,0];e[r]=t.centers[i],void 0!==s&&(e[a]=i*s);const h=[o.id,i,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:i,shape:l.shape,pose:px(px(n,{r:rx(),t:e}),l.pose)})}return[{items:c}]},geometry:(t,e,n)=>n.params.within?[]:e[0].items},"select-item@1":{ports:["placed"],params:["member"],types:(t,e)=>(2===t.length&&"collection"===t[0].kind&&Q_(t[1],K_)||V_("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,s)=>{const i=t.items.find(t=>t.index===e&&t.key===s.params.member);return i||V_("TARGET_ABSENT",n,`${s.params.member}[${e}]`),[{shape:i.shape,pose:i.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[Y_,Y_,Y_,X_,X_,X_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s,i,o])=>{const r=Math.cos(s),a=Math.sin(s),c=Math.cos(i),l=Math.sin(i),h=Math.cos(o),d=Math.sin(o);return[{r:dx(dx([[1,0,0],[0,r,-a],[0,a,r]],[[c,0,l],[0,1,0],[-l,0,c]]),[[h,-d,0],[d,h,0],[0,0,1]]),t:[t,e,n]}]}},"axis-turn@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[q_,q_,q_,X_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const o=Math.hypot(t,e,n);Math.abs(o-1)>1e-6&&V_("AXIS",i,"unit axis required");const r=t/o,a=e/o,c=n/o,l=Math.cos(s),h=Math.sin(s),d=1-l;return[{r:[[l+r*r*d,r*a*d-c*h,r*c*d+a*h],[a*r*d+c*h,l+a*a*d,a*c*d-r*h],[c*r*d-a*h,c*a*d+r*h,l+c*c*d]],t:[0,0,0]}]}},"axis-slide@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(sx(t,[q_,q_,q_,Y_],e),[ox(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const o=Math.hypot(t,e,n);return Math.abs(o-1)>1e-6&&V_("AXIS",i,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/o*s,e/o*s,n/o*s]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(gx(t,e,2),t[1].to!==t[0].from&&V_("FRAME_TYPE",e,"composition intermediate frame mismatch"),[ox(t[1].from,t[0].to)]),run:([t,e])=>[px(t,e)]},"attach@1":{ports:["pose"],types(t,e){gx(t,e,3);const[n,s,i]=t;return n.from===s.to&&s.from===i.from||V_("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[ox(i.to,n.to)]},run:([t,e,n])=>[px(px(t,e),fx(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>(sx(t,[Y_,Y_,Y_],e),[{kind:"point",frame:n.params.frame}]),run:t=>[t]},"map-point@1":{ports:["point"],types:(t,e)=>(2===t.length&&"transform"===t[0].kind&&"point"===t[1].kind&&t[0].from===t[1].frame||V_("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[ux(hx(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&Q_(t[0],t[1])||V_("FRAME_TYPE",e,"distance requires points in same frame"),[Y_]),run:([t,e])=>[Math.hypot(...t.map((t,n)=>t-e[n]))]},"feature@1":{ports:["pose"],params:["frame","name"],types(t,e,n){1===t.length&&"shape"===t[0].kind&&t[0].faces||V_("TYPE",e,"shape required");const s=Object.keys(t[0].faces);return[...s,"centre",..."revolve"!==t[0].provider||s.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||V_("UNKNOWN_FEATURE",e,n.params.name),[ox(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const s=function(t,e){const n=B_(t),s=jv.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return s;const i=t.faces[e],o={x:0,y:1,z:2};if(i){const n=[...s];if(n[o[i.axis]]=i.at,t.loft)for(const e of Kv[t.loft.axis]){const s=t.loft.section.points.map(t=>t[e]);n[o[e]]=(Math.min(...s)+Math.max(...s))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,r=t.cavity,a=r.wall;for(const t of Kv[e.axis])t!==i.axis&&(n[o[t]]=s[o[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(i.axis!==e.axis){const t=e.start+("open"===r.start?0:r.start.closed),s=e.end-("open"===r.end?0:r.end.closed);n[o[e.axis]]=(t+s)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(p_).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]),i=t.find(([t])=>t===e);if(!i)return;const r=[...s];return r[o[i[1]]]=i[2]<0?n[i[1]].min:n[i[1]].max,r}}(t,n.params.name);return s||V_("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:s}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||V_("FRAME_TYPE",e,"shape local frame mismatch"),[{kind:"placed",frame:t[1].to}]),run:([t,e])=>[{shape:t,pose:e}],geometry:([t,e])=>({shape:t,pose:e})}}),ix["member@1"]={...ix["place@1"],geometry:void 0},Object.assign(ix,H_);for(const[t,e]of Object.entries(ix))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const yx=[];for(const[t,e]of Object.entries(ix))e.pure=!yx.includes(t);const bx=["add@1","mul@1","div@1","sin@1","geomean@1","curve@1","at-least@1","max@1","min@1","hypot@1","between@1","assembly@1","repeat@1","select-item@1","rigid@1","axis-turn@1","axis-slide@1","compose@1","attach@1","point@1","map-point@1","distance@1","place@1","member@1"];for(const[t,e]of Object.entries(ix))e.pure&&bx.includes(t)&&(e.poseForm="run");function vx(t,e,n){return Array.isArray(e)?ex(t,n):"flag"===e.kind?("boolean"!=typeof t&&V_("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&V_("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&Sx(t)?kx(t,n):"placed"===e.kind&&Mx(t,"shape","pose")&&Tx.has(t.shape)&&Sx(t.pose)?kx(t.pose,n):(Ex(t,n),"shape"===e.kind&&t&&"object"==typeof t&&Tx.add(t)),t)}function _x(t){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;if(Object.freeze(t),Array.isArray(t))for(let e=0;e<t.length;e++)_x(t[e]);else for(const e in t)_x(t[e]);return t}function xx(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(Sx(t)){const e=new Array(t.r.length);for(let n=0;n<e.length;n++)e[n]=Object.freeze(t.r[n].slice());n={r:Object.freeze(e),t:Object.freeze(t.t.slice())}}else if(Array.isArray(t)){n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=xx(t[s],e)}else{n={};for(const s in t)n[s]=xx(t[s],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(ix).filter(t=>!ix[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(ix).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(ix).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(ix));const wx=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],Mx=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let s=0;for(const i in t)if(Object.hasOwn(t,i)){if(s>1||i!==(0===s?e:n))return!1;s++}return 2===s},Sx=t=>Mx(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function Ax(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const s=t[n];"number"==typeof s?Number.isFinite(s)||V_("NON_FINITE",e,String(s)):Ex(s,e)}}function kx(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const s=t.r[n];Array.isArray(s)?Ax(s,e):Ex(s,e)}Ax(t.t,e)}function Ex(t,e){if("number"==typeof t)Number.isFinite(t)||V_("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&Ex(t[n],e);else if(t&&"object"==typeof t){const n=Object.keys(t);if(!(n.length<=2&&Array.isArray(t[n[0]])&&(n.length<2||Array.isArray(t[n[1]])))&&Tx.has(t))return;for(let s=0;s<n.length;s++)Ex(t[n[s]],e)}}const Tx=new WeakSet,Cx=["transform","placed","assembly","collection","point"],Ox=t=>Array.isArray(t)||Cx.includes(t?.kind)?void 0:String(t?.kind??"value");function Px(t){return function(t){Z_(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||V_("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||V_("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,s=new Map,i=new Map,o=new Map,r=[],a=[],c=(t,e)=>{tx(t,e),n.has(t)&&V_("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)Z_(t,["id","unit"],["min","max","role"],"input"),c(t.id,"input"),s.set(t.id,nx(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&V_("SCHEMA",t.id,"unknown input role"),"state"===t.role&&i.set(t.id,new Set([t.id])),"state"!==t.role||void 0!==t.min&&void 0!==t.max||V_("SCHEMA",t.id,"a state input has a range"),void 0!==t.min&&ex(t.min,t.id),void 0!==t.max&&ex(t.max,t.id),void 0!==t.min&&void 0!==t.max&&t.min>t.max&&V_("RANGE",t.id,"min > max"),"count"===t.unit&&(void 0!==t.min&&vx(t.min,K_,t.id),void 0!==t.max&&vx(t.max,K_,t.id));for(const t of e.constants)Z_(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),s.set(t.id,nx(t.unit,t.id)[0]),vx(t.value,s.get(t.id),t.id);for(const t of e.nodes){Z_(t,["id","op","args","outputs"],["params"],"node"),tx(t.id,"node"),o.has(t.id)&&V_("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(ix,t.op)||V_("OPERATOR",t.id,t.op),ix[t.op].params?mx(t,ix[t.op].params,ix[t.op].optionalParams):Object.hasOwn(t,"params")&&V_("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||V_("SCHEMA",t.id,"args array required"),t.args.forEach(e=>tx(e,t.id)),Z_(t.outputs,ix[t.op].ports,[],t.id);for(const e of Object.values(t.outputs))c(e,t.id);o.set(t.id,t)}const l=new Set,h=new Set,d=[],u=t=>{h.has(t)&&V_("CYCLE",t,[...a,t].join(" -> ")),a.push(t),h.add(t),d.push({n:o.get(t),at:0,inputTypes:[]})};for(const t of o.keys())if(!l.has(t))for(u(t);d.length;){const t=d[d.length-1],e=t.n;if(t.at<e.args.length){const i=e.args[t.at];if(n.has(i)||V_("UNKNOWN_REFERENCE",e.id,i),!s.has(i)){u(n.get(i));continue}t.inputTypes.push(s.get(i)),t.at++;continue}const o=ix[e.op],c=o.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of i.get(t)??[])p.add(e);p.size&&(void 0===o.state&&V_("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===o.state&&V_("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),o.ports.forEach((t,n)=>s.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>i.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),r.push(e)}let p;const f=new Map,m=new Set(e.inputs.map(t=>t.id));function g(t){t&&"object"==typeof t&&!Array.isArray(t)||V_("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||V_("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||V_("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=ex(e,t.id);return(n<(t.min??-1/0)||n>(t.max??1/0))&&V_("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`,{reason:"value-outside-range",input:t.id,value:n,...void 0!==t.min?{min:t.min}:{},...void 0!==t.max?{max:t.max}:{}}),vx(n*nx(t.unit,t.id)[1],s.get(t.id),t.id)}function b(t,n){g(t);const i=new Map,o=[],a=new Map,c=new Set;for(const n of e.inputs)i.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)i.set(t.id,ex(t.value*nx(t.unit,t.id)[1],t.id));for(const t of r){const e=ix[t.op],n=t.args.map(t=>i.get(t)),r=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{i.set(t.outputs[e],vx(r[n],s.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const s=wx(e.geometry(n,r,t),t.id);a.set(t.id,s),o.push(...s)}}return{result:{values:Object.fromEntries(i),geometry:o},kept:{input:{...t},values:i,bodies:a}}}return{outputTypes:Object.fromEntries([...s].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...i].map(([t,e])=>[t,[...e].sort()])),order:r.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,s=0,i=[],o=0;const r=(t,e)=>{const n=e||t.length!==i.length||t.some((t,e)=>t!==i[e]);return n&&s++,i=t,n},a=(t,e)=>(r(t.geometry.map(t=>t.id),e),t),c=t=>{o++;const n=e;if(e=void 0,!n)return e=_(b(t).kept),a({values:{...e.values},geometry:e.geometry.slice()},!0);const s=A(t,n,!0);return e=n,a(s,!1)},l=(t,n)=>{const i=++o,a=e;e=void 0;const c=a?.fast;let l;a?(l=A(t,a,!1),e=a):(e=_(b(t).kept,!1),l=h().shapes);const d=e,u=[],p=[],f=[],m=[],g=new Int32Array(h().nodes.length);for(const t of h().shapes){g[t]=u.length;for(const e of d.bodies[t]??[])u.push(e.id),p.push(e.key),f.push(e.path?Object.freeze(e.path.slice()):void 0),m.push(e.index)}const y=r(u,!a),v=y?h().shapes:c?.wrote.size?[...new Set([...l,...c.wrote])].sort((t,e)=>t-e):l;let x=0;for(const t of v)x+=d.bodies[t]?.length??0;const w=new Int32Array(x),M=new Float64Array(12*x),S=new Array(x);let k=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[k]=g[t]+n,S[k]=e.shape??null;const s=12*k;if(e.pose){const t=e.pose.r,n=e.pose.t;M[s]=t[0][0],M[s+1]=t[0][1],M[s+2]=t[0][2],M[s+3]=t[1][0],M[s+4]=t[1][1],M[s+5]=t[1][2],M[s+6]=t[2][0],M[s+7]=t[2][1],M[s+8]=t[2][2],M[s+9]=n[0],M[s+10]=n[1],M[s+11]=n[2]}else M.fill(NaN,s,s+12);k++});const E=d.epoch,T=()=>{o!==i&&V_("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:s,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{T();const e=h().slot.get(t);return void 0===e&&V_("TARGET_ABSENT",t,"no such value"),xx(d.slots[e],new Map)},changed:t=>{T();const e=h().slot.get(t);return void 0!==e&&(y||d.mark[e]===E||!!c?.moved.has(e))}}},h=()=>v();return{evaluate:c,advance(i,r){if(e&&!r){const r=++o,a=e;e=void 0;const h=S(i,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{o!==r&&V_("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:s,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(i,h.why);return{kind:"evaluation",result:c(i),generation:s,why:h.why}}const a={code:!!e?r:"NOT_BOUND"};if(t.changes)return l(i,a);return{kind:"evaluation",result:c(i),generation:s,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||V_("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&V_("TARGET_ABSENT",t,"no such value");const s=e.fast;if(!s)return xx(e.slots[n],new Map);const i=h().nodes.find(t=>t.outs.includes(n));if(i&&s.wrote.has(i.index)&&!s.moved.has(n)){const t=i.op.run(i.args.map(t=>s.slots[t]),i.n.id,i.n);return xx(t[i.outs.indexOf(n)],new Map)}return xx(s.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],i=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>i(t.id)),e.constants.forEach(t=>i(t.id));const o=r.map((e,n)=>{const o=ix[e.op];return o.ports.forEach(t=>i(e.outputs[t])),{n:e,op:o,index:n,args:e.args.map(e=>t.get(e)),outs:o.ports.map(n=>t.get(e.outputs[n])),types:o.ports.map(t=>s.get(e.outputs[t]))}}),a=n.map(()=>[]);for(const t of o)for(const e of t.args)a[e].push(t.index);const c=t=>{const e=new Uint8Array(o.length),n=[...t];for(;n.length;){const t=n.pop();for(const s of a[t])e[s]||(e[s]=1,n.push(...o[s].outs))}const s=[];return e.forEach((t,e)=>t&&s.push(e)),s},l=o.filter(t=>!t.op.pure),h=[...new Set([...l.map(t=>t.index),...c(l.flatMap(t=>t.outs))])].sort((t,e)=>t-e);return p={keys:n,slot:t,nodes:o,readers:a,reach:e.inputs.map((t,e)=>c([e])),always:h,shapes:o.filter(t=>t.op.geometry).map(t=>t.index),shapeSlot:n.map(t=>"shape"===s.get(t)?.kind)},p}function _(t,n=!0){const s=v(),i=s.keys.map(e=>t.values.get(e));i.forEach((t,e)=>s.shapeSlot[e]&&_x(t));const o=s.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of s.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:o,shown:o.map(()=>{}),values:n,geometry:[],mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set(s.shapes.filter(t=>o[t])),slots:new Set(s.keys.keys())}}}const r=new Map,a=o.map(t=>t?.map(t=>xx(t,r))),c={};s.keys.forEach((t,e)=>c[t]=xx(i[e],r));const l=[];for(const t of s.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:o,shown:a,values:c,geometry:l,mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),i=f.get(n);if(i)return i;const o=v(),r=t.forbidden??{},a=new Set(t.external??[]),c=e.inputs.map((t,e)=>{const n=Ox(s.get(t.id));if(n)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:n};if(Object.hasOwn(r,t.id))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:r[t.id]};for(const n of o.reach[e]){const e=o.nodes[n];if(!e.op.poseForm)return{fast:!1,code:"UNSUPPORTED_OPERATOR",input:t.id,node:e.n.id,op:e.n.op};for(const[n,s]of e.outs.entries()){const i=Ox(e.types[n]);if(i)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:i};const a=o.keys[s];if(Object.hasOwn(r,a))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:r[a]}}}return{fast:!0}}),l=o.nodes.map(t=>"repeat@1"===t.n.op&&!t.n.params?.within&&t.outs.every(t=>!o.readers[t].length&&!a.has(o.keys[t]))),h={inputs:c,terminal:l,visits:new Map};return f.set(n,h),h}function w(t,e){const n=v();if(1===t.length)return n.reach[t[0]];const s=t.join();let i=e.visits.get(s);if(!i){const o=new Set;for(const e of t)for(const t of n.reach[e])o.add(t);i=[...o].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(s,i)}return i}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let s=0;for(const i of e.shapes)n[i]=s,s+=t.bodies[i]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:s,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,s){const i=v();g(t);const o=n.fast?.raw??n.raw,r=[],a=[];for(let n=0;n<e.inputs.length;n++){const s=e.inputs[n],i=t[s.id];i!==o[n]&&(a.push(y(s,i)),r.push(n))}for(const t of r)if(!s.inputs[t].fast)return{why:s.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;r.forEach((n,s)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[s],c.mark[n]=l});const h=w(r,s),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,s=e.t,i=12*p;d[p++]=t,u[i]=n[0][0],u[i+1]=n[0][1],u[i+2]=n[0][2],u[i+3]=n[1][0],u[i+4]=n[1][1],u[i+5]=n[1][2],u[i+6]=n[2][0],u[i+7]=n[2][1],u[i+8]=n[2][2],u[i+9]=s[0],u[i+10]=s[1],u[i+11]=s[2]};for(const t of h){const e=i.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const o=new Array(e.args.length);for(let t=0;t<e.args.length;t++)o[t]=c.slots[e.args[t]];if(s.terminal[t]){const[n,s,i,r]=o,a=["x","y","z"].indexOf(e.n.params.axis),h=["x","y","z"].indexOf(e.n.params.riseAxis);let d=c.mark[e.args[2]]!==l&&(void 0===e.args[3]||c.mark[e.args[3]]!==l)?c.prefix.get(t):void 0;if(!d){d=[];for(let t=0;t<n.count;t++){const e=[0,0,0];e[a]=n.centers[t],void 0!==r&&(e[h]=t*r),d.push(px(i,{r:rx(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of s.members){const s=px(d[t],n.pose);Ex(s,e.n.id),f(u++,s)}c.wrote.add(t);continue}const r=e.op.run(o,e.n.id,e.n);if(e.outs.forEach((t,n)=>{c.slots[t]=vx(r[n],e.types[n],e.n.id),c.mark[t]=l,c.moved.add(t)}),e.op.geometry){const n=e.op.geometry(o,r,e.n),s=Array.isArray(n)?n:[n];let i=c.start[t];for(const t of s)f(i++,t.pose);c.wrote.add(t)}}const m={kind:"poses",generation:0,bodies:d.slice(0,p),poses:u.slice(0,12*p),read:t=>{const e=i.slot.get(t);return void 0===e&&V_("TARGET_ABSENT",t,"no such value"),xx(c.slots[e],new Map)},changed:t=>{const e=i.slot.get(t);return void 0!==e&&c.mark[e]===l}};return{result:m}}function A(t,n,s){const i=v();g(t),n.fast=void 0;const o=++n.epoch,r=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,s)=>{const i=t[e.id];i!==n.raw[s]&&(n.slots[s]=y(e,i),n.raw[s]=i,n.mark[s]=o,r.push(s),c>=0&&(l=!0),c=s)}),l||i.always.length){const t=[];for(const e of[...r.map(t=>i.reach[t]),i.always])for(const s of e)n.ran[s]!==o&&(n.ran[s]=o,t.push(s));a=t.sort((t,e)=>t-e)}else a=c>=0?i.reach[c]:[];const h=[];for(const t of a){const e=i.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===o))continue;const s=e.args.map(t=>n.slots[t]),a=e.op.run(s,e.n.id,e.n);e.outs.forEach((t,s)=>{n.slots[t]=vx(a[s],e.types[s],e.n.id),i.shapeSlot[t]&&_x(n.slots[t]),n.mark[t]=o,r.push(t)}),e.op.geometry&&(n.bodies[t]=wx(e.op.geometry(s,a,e.n),e.n.id),n.pending.nodes.add(t),h.push(t))}for(const t of r)n.pending.slots.add(t);if(!s){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of r)n.values[i.keys[t]]=void 0;return h}return k(n),{values:{...n.values},geometry:n.geometry.slice()}}function k(t){const e=v(),{nodes:n,slots:s}=t.pending;if(!n.size&&!s.size)return;const i=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>xx(t,i));for(const n of s)t.values[e.keys[n]]=xx(t.slots[n],i);if(n.size){const n=[];for(const s of e.shapes){const e=t.shown[s];e&&n.push(...e)}t.geometry=n}n.clear(),s.clear()}}(t)}const Ix="0.12.1",Dx=Object.freeze({x:"size.x",y:"size.y",z:"size.z"}),zx=["meet","flush","centre"],Rx=["revolute","prismatic"],jx=["seat","child-face","child-centre"];function $x(t){const e=t.mimic;return e&&"object"==typeof e?Object.hasOwn(e,"sum")?Array.isArray(e.sum)?e.sum:[]:[{motion:e.motion,multiplier:e.multiplier}]:[]}const Lx=t=>{const e=Fx(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)};function Fx(t){if(!t||"object"!=typeof t)return;if(Object.hasOwn(t,"sum")){const e=t;return{terms:e.sum,plus:e.plus??0,sum:!0}}const e=t;return{terms:[{from:e.from,...void 0!==e.times?{times:e.times}:{}}],plus:e.plus??0,sum:!1}}const Nx=(t,e,n,s)=>{throw new Xv(t,e,n,s)},Hx=(t,e)=>t.nodes.find(t=>t.id===e),Bx=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function Gx(t,e){const n=(t,e)=>({terms:[...t.terms,...e.terms],c:t.c+e.c}),s=e=>t.constants.find(t=>t.id===e&&"ratio"===t.unit)?.value,i=(e,o,r)=>{const a=(e=>t.constants.find(t=>t.id===e)?.value)(e);if(void 0!==a)return{terms:[],c:a*o};const c=r<256?Bx(t,e):void 0;if("add@1"===c?.op)return c.args.reduce((t,e)=>n(t,i(e,o,r+1)),{terms:[],c:0});if("mul@1"===c?.op){const[t,e]=c.args;if(void 0!==s(e))return i(t,o*s(e),r+1);if(void 0!==s(t))return i(e,o*s(t),r+1)}return{terms:[{ref:e,k:o}],c:0}},o=e.terms.reduce((t,e)=>n(t,i(e.ref,e.k,0)),{terms:[],c:e.c}),r=new Map;for(const t of o.terms)r.set(t.ref,(r.get(t.ref)??0)+t.k);return{terms:[...r].filter(([,t])=>0!==t).map(([t,e])=>({ref:t,k:e})),c:o.c}}function Ux(t,e){const n=Hx(t,e);if("member@1"!==n?.op||Hx(t,`${e}.repeat`))return;const s=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return s?String(s.id).replace(/\.assembly$/,""):void 0}function Vx(t,e,n){const s=Hx(t,e),i="member@1"===s?.op&&(!!Hx(t,`${e}.repeat`)||void 0!==Ux(t,e));s&&("place@1"===s.op||i)||Nx("TARGET_ABSENT",n,`${e} is not a placed part`);const o=Bx(t,s.args[0]);o||Nx("TARGET_ABSENT",n,`${e} has no shape`);const r=Hx(t,`${e}.pose`);return r&&"rigid@1"===r.op||Nx("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:s,shape:o,pose:r}}function Wx(t,e){const n=new Set([...t.nodes.map(t=>t.id),...t.nodes.flatMap(t=>Object.values(t.outputs)),...t.constants.map(t=>t.id),...t.inputs.map(t=>t.id)]);return t=>{let s=`${e}.${t}`;for(let i=2;n.has(s)||n.has(`${s}.value`);i++)s=`${e}.${t}.${i}`;return n.add(s),n.add(`${s}.value`),s}}function Yx(t,e,n,s){const i=t.constants.find(t=>t.unit===e&&t.value===n);if(i)return i.id;const o=`${s}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:o,unit:e,value:n}),o}function qx(t,e,n,s,i,o){let r=n;if(1!==s){const n=e(`${o}.times`);t.nodes.push({id:n,op:"mul@1",args:[r,Yx(t,"ratio",s,"k")],outputs:{value:`${n}.value`}}),r=`${n}.value`}if(0!==i){const n=e(`${o}.plus`);t.nodes.push({id:n,op:"add@1",args:[r,Yx(t,"mm",i,"d")],outputs:{value:`${n}.value`}}),r=`${n}.value`}return r}function Xx(t,e,n,s,i,o){if(void 0===s)return Yx(t,"mm",0,"d");if("number"==typeof s)return Number.isFinite(s)||Nx("SCHEMA",o,"a finite length is required"),Yx(t,"mm",s,"d");s&&"object"==typeof s&&(Object.hasOwn(s,"sum")||s.from)||Nx("SCHEMA",o,"a length is a number of millimetres, or something to follow");const{terms:r,plus:a,sum:c}=Fx(s),l=Kx(t,e,r,a,o);return c?qx(t,n,Jx(t,n,l,`${i}.sum`),1,a,i):qx(t,n,l[0].ref,l[0].k,a,i)}function Kx(t,e,n,s,i){return Array.isArray(n)&&n.length||Nx("SCHEMA",i,"a sum has one term or more"),Number.isFinite(s)||Nx("SCHEMA",i,"finite times and plus required"),n.map((s,o)=>{const r=n.length>1?`${i}.sum.${o}`:i;return s&&"object"==typeof s&&s.from||Nx("SCHEMA",r,"a length is a number of millimetres, or something to follow"),Number.isFinite(s.times??1)||Nx("SCHEMA",r,"finite times and plus required"),{ref:Qx(t,e,s.from,r),k:s.times??1}})}function Jx(t,e,n,s){const i=n.filter(t=>0!==t.k);if(!i.length)return Yx(t,"mm",0,"d");let o="";for(const[n,r]of i.entries()){const i=qx(t,e,r.ref,r.k,0,`${s}.${n}`);if(o){const r=e(`${s}.${n}.sum`);t.nodes.push({id:r,op:"add@1",args:[o,i],outputs:{value:`${r}.value`}}),o=`${r}.value`}else o=i}return o}function Qx(t,e,n,s){if(n&&"object"==typeof n||Nx("SCHEMA",s,"a dimension source is required"),"instance"===n.of){const i=`size.${n.axis}`;return t.inputs.some(t=>t.id===i)||Nx("TARGET_ABSENT",s,`the instance has no ${i}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const s=Hx(t,`sizing.size.${e}`);return s||Nx("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),s.outputs.value}(t,n.axis,s):i}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||Nx("TARGET_ABSENT",s,`${n.input} is not an input of this asset`),"state"===e.role&&Nx("EDIT_TARGET",s,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?Zx(t,n.part,n.axis,s):Nx("SCHEMA",s,`${String(n.of)} is not a dimension source`)}function Zx(t,e,n,s){const i=Vx(t,e,s).shape,o=I_(i);if(o){const r=o.edit[n];if("refused"in r)return Nx("EDIT_TARGET",s,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(r.sameAs)return Zx(t,e,r.sameAs,s);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(Hx(t,a))return c;const l=i.args[r.arg],h=Yx(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),i.args=i.args.map(t=>t===l?c:t);const d=Hx(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return Nx("EDIT_TARGET",s,`${e} is a ${i.op}; it is not a shape with measures`)}const tw=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role),ew=t=>new Set([...cw(t.mountingFace),...cw(t.document.capabilities),...cw(t.joints)]);let nw;const sw=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function iw(t,e,n){const s=t.document.model,i=nw&&nw.asset===t?nw.declared:void 0,o=i??ew(t);if(i&&sw){const n=ew(t);if(n.size!==i.size||[...n].some(t=>!i.has(t)))throw new Error(`the names held for the joint rewrite went stale at ${e}`)}const r=t=>s.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||o.has(t);if(r(e))return;const a=s.inputs.findIndex(t=>t.id===e);if(a>=0){if(e!==n)return;return s.inputs.splice(a,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const c=Bx(s,e);if(c&&"place@1"!==c.op&&!Object.values(c.outputs).some(t=>t!==e&&r(t))){s.nodes=s.nodes.filter(t=>t!==c);for(const e of c.args)iw(t,e)}}function ow(t,e){if(!Hx(t,`${e}.chain`)&&!Hx(t,`${e}.repeat`))return null;const n=Hx(t,`${e}.seat.rigid`)??Hx(t,`${e}.motion`),s=/^(.*)\.local$/.exec(String(n?.params?.to));return s&&s[1]!==e?s[1]:null}const rw=t=>Math.round(1e6*t)/1e6,aw=(t,e)=>t.inputs.find(t=>t.id===Dx[e]),cw=t=>{const e=[],n=t=>{if("string"==typeof t)e.push(t);else if(Array.isArray(t))for(const e of t)n(e);else if(t&&"object"==typeof t)for(const e of Object.values(t))n(e)};return n(t),e},lw=t=>!Array.isArray(t);function hw(t,e){const n="loft@1"===t.op?w_(t.params,t.id):g_(t.params,t.id),s=Object.values(n.arg.point??{}).map(t=>t[e]).filter(t=>void 0!==t),i=n.apex?.[e];return[...s,...void 0!==i?[i]:[]].map(e=>({ref:t.args[e],k:1}))}function dw(t,e,n){const{shape:s}=Vx(t,e,n),i=I_(s);if(i){const t={};for(const o of jv){const r=i.edit[o];if("refused"in r)return Nx("EDIT_TARGET",n,`${e} is a drawn section; its reach across is its points, not a measure this command can read`);t[o]={ref:s.args[r.arg],k:r.k}}return t}return Nx("EDIT_TARGET",n,`${e} is a ${s.op}; it is not a shape this command can measure`)}function uw(t,e,n){const[s,i]=vw[n].map(t=>e?.[t]);if(!s||!i||s.plane.length>1||i.plane.length>1)return;const[o,r]=[ww(t,s),ww(t,i)];if(JSON.stringify(o)===JSON.stringify(yw(r)))return;const a=(t,e)=>t[0]??{ref:e[0].ref,k:0};return o.length||r.length?[a(o,r),a(r,o)]:void 0}function pw(t,e,n){const s=t.constants.find(t=>t.id===n);if(s)return s.value;const i=t.inputs.find(t=>t.id===n);return i&&"state"!==i.role?e.designInputs[n]??null:null}function fw(t,e,n,s,i){const o=function(t,e,n,s){return Vx(t,n,s).pose.args.slice(3,6).map(n=>pw(t,e,n))}(t,e,n,s);if(o.every(t=>0===t))return[[1,0,0],[0,1,0],[0,0,1]];o.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&Nx("EDIT_TARGET",s,`${n} is turned (${(t=>jv.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", "))(o)}); only quarter turns keep its faces level with the axes`);const r=mw(o);if(i){const i=Vx(t,n,s).pose,r=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...o.map(e=>Yx(t,"deg",e,"a"))];for(const s of r)iw(e,s,tw(t,n,s)?s:void 0)}return r}function mw(t){const[e,n,s]=t.map(t=>t*Math.PI/180),i=t=>Math.round(Math.cos(t)),o=t=>Math.round(Math.sin(t)),r=[[1,0,0],[0,i(e),-o(e)],[0,o(e),i(e)]],a=[[i(n),0,o(n)],[0,1,0],[-o(n),0,i(n)]],c=[[i(s),-o(s),0],[o(s),i(s),0],[0,0,1]];return gw(gw(r,a),c)}const gw=(t,e)=>t.map(t=>e[0].map((n,s)=>t.reduce((t,n,i)=>t+n*e[i][s],0)));const yw=t=>t.map(t=>({ref:t.ref,k:-t.k})),bw=t=>t.map(t=>({ref:t.ref,k:t.k/2})),vw={x:["left","right"],y:["bottom","top"],z:["back","front"]};function _w(t,e,n){const{shape:s}=Vx(t,e,n),i=G_(s,t);return i||Nx("EDIT_TARGET",n,`${e} is a ${s.op}; it has no flat face to fasten by`),{shape:s,faces:i}}function xw(t,e){const n=jv.indexOf(t),s=0===n?1:0,i=3-n-s,o=(n+1)%3===s?1:-1,r=e*Math.PI/180,a=[0,0,0];return a[s]=Math.cos(r),a[i]=o*Math.sin(r),a}const ww=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function Mw(t,e,n){const{shape:s,faces:i}=_w(t,e,n),o={},r=I_(s,t).measure;for(const t of jv){const[e,n]=vw[t].map(t=>i[t]),a=r[t],c=a&&"profile"!==a?ww(s,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?ww(s,e):[...ww(s,n),...yw(c)],h=n?ww(s,n):[...ww(s,e),...c];o[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(yw(h))}}return o}const Sw=[[1,0,0],[0,1,0],[0,0,1]],Aw=t=>t[0].map((e,n)=>t.map(t=>t[n])),kw=(t,e)=>t.map(t=>t.reduce((t,n,s)=>t+n*e[s],0)),Ew={x:["y","z"],y:["z","x"],z:["x","y"]};function Tw(t){return gw(gw(Cw("z",t.z??0),Cw("y",t.y??0)),Cw("x",t.x??0))}function Cw(t,e){const n=Math.cos(e*Math.PI/180),s=Math.sin(e*Math.PI/180),[i,o]=Ew[t].map(t=>jv.indexOf(t)),r=[[1,0,0],[0,1,0],[0,0,1]];return r[i][i]=n,r[i][o]=-s,r[o][i]=s,r[o][o]=n,r}function Ow(t,e=!1){const n=t=>{const n=e?Math.round(180*t/Math.PI*1e12)/1e12:rw(180*t/Math.PI);return 0===n?0:n},s=Math.max(-1,Math.min(1,t[0][2]));return Math.abs(s)<1-1e-12?[n(Math.atan2(-t[1][2],t[2][2])),n(Math.asin(s)),n(Math.atan2(-t[0][1],t[0][0]))]:[n(Math.atan2(t[2][1],t[1][1])),n(Math.asin(s)),0]}(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const s of[0,90,180,270]){const i=mw([e,n,s]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===i[e][n])))||t.push(i)}})();const Pw=1e-12,Iw=t=>Math.abs(t)<Pw?0:Math.round(1e12*t)/1e12;function Dw(t){const e=new Map;for(const n of t)e.set(n.ref,(e.get(n.ref)??0)+n.k);return[...e].map(([t,e])=>({ref:t,k:Iw(e)})).filter(t=>0!==t.k)}const zw=(t,e=0)=>({terms:Dw(t),constant:Iw(e)}),Rw=t=>"terms"in t;function jw(t,e){return 1===e?t:Rw(t)?zw(t.terms.map(t=>({ref:t.ref,k:t.k*e})),t.constant*e):"add"in t?$w(...t.add.map(t=>jw(t,e))):"scaled"in t?jw(t.scaled,t.k*e):{scaled:t,k:Iw(e)}}function $w(...t){const e=t.flatMap(t=>"add"in t?t.add:[t]),n=e.filter(Rw),s=zw(n.flatMap(t=>t.terms),n.reduce((t,e)=>t+e.constant,0)),i=[],o=new Map;for(const t of e.filter(t=>!Rw(t))){const[e,n]="scaled"in t?[t.scaled,t.k]:[t,1];if(!("geomean"in e)){i.push(t);continue}const s=JSON.stringify(e);o.set(s,{part:e,k:(o.get(s)?.k??0)+n})}for(const t of o.values())0!==Iw(t.k)&&i.push(1===Iw(t.k)?t.part:{scaled:t.part,k:Iw(t.k)});return i.length?{add:[...s.terms.length||s.constant?[s]:[],...i]}:s}function Lw(t){const e=new Map(t.map(t=>[JSON.stringify(t),t])),n=[...e.values()];return 1===n.length?n[0]:{max:n}}function Fw(t,e){const n=t=>e[jv.indexOf(t)];if("box"===t.kind)return $w(...jv.filter(t=>Math.abs(n(t))>=Pw).map(e=>jw(n(e)>0?t.hi[e]:t.lo[e],n(e))));if("sphere"===t.kind){const e=Math.hypot(...jv.filter(e=>e!==t.axis).map(n));return Vw(t.radial,t.axial,e,n(t.axis))}const s=n(t.axis),i=e=>jw(t.ends[e],s);if("taper"===t.kind){const e=Math.hypot(...jv.filter(e=>e!==t.axis).map(n));return Lw([$w(i("lo"),jw(t.radii[0],e)),$w(i("hi"),jw(t.radii[1],e))])}const[o,r]=t.plane,a=n(o),c=n(r),l=([t,e])=>$w(jw(t,a),jw(e,c));if("loft"===t.kind){const e=t.points.map(t=>$w(l(t),i("lo"))),n=$w(i("hi"),l(t.apex));return Math.abs(a)<Pw&&Math.abs(c)<Pw?s>0?n:e[0]:Lw([...e,n])}const h=i(s>0?"hi":"lo");if("rounded"===t.kind){const e=$w(jw(t.across[0],Math.abs(a)/2),jw(t.corner[0],-Math.abs(a)),jw(t.across[1],Math.abs(c)/2),jw(t.corner[1],-Math.abs(c)));return $w(h,e,Vw(t.corner[0],t.corner[1],a,c))}return"ellipse"===t.kind?$w(h,Vw(t.radius[0],t.radius[1],a,c)):$w(h,Lw(t.points.map(l)))}function Nw(t,e,n,s){const i=Uw(t,e,s);if("taper"===i.kind)return{not:"taper"};if("rounded"===i.kind)return{not:"rounded"};if("sphere"!==i.kind&&"ellipse"!==i.kind)return{not:"flat"};const o="sphere"===i.kind?Object.fromEntries(jv.map(t=>[t,t===i.axis?i.axial:i.radial])):{[i.plane[0]]:i.radius[0],[i.plane[1]]:i.radius[1]},r=jv.filter(t=>o[t]&&Math.abs(n[jv.indexOf(t)])>1e-12),a=new Set(r.map(e=>(e=>{const n=Gx(t,Rw(e)?{terms:e.terms,c:e.constant}:{terms:[],c:NaN});return JSON.stringify([[...n.terms].sort((t,e)=>t.ref<e.ref?-1:t.ref>e.ref?1:0),n.c])})(o[e]))).size<=1,c={hypot:r.map(t=>jw(o[t],n[jv.indexOf(t)]))},l=Object.fromEntries(jv.map((t,e)=>r.includes(t)?[t,a?jw(o[t],n[e]):{quotient:[jw({product:[o[t],o[t]]},n[e]),c]}]:[t,zw([])]));return{point:l,..."ellipse"===i.kind?{push:{axis:i.axis,...i.ends}}:{}}}function Hw(t){if(Rw(t))return t.terms.map(t=>t.ref);if("scaled"in t)return Hw(t.scaled);return("add"in t?t.add:"max"in t?t.max:"hypot"in t?t.hypot:"product"in t?t.product:"quotient"in t?t.quotient:t.geomean).flatMap(Hw)}function Bw(t,e,n,s){return Fw(Uw(t,e,s),n)}function Gw(t,e){const n=function(t){const e=t=>zw([],t),n=()=>{const n=B_(t);return{kind:"box",lo:Object.fromEntries(jv.map(t=>[t,e(n[t].min)])),hi:Object.fromEntries(jv.map(t=>[t,e(n[t].max)]))}};if(t.extrusion){const s=t.extrusion,i=[...Kv[s.axis]],o={lo:e(s.start),hi:e(s.end)},r=s.section;if("rectangle"===r.kind){const[t,a]=i.map(t=>r.corner?.[t]??0);return t||a?{kind:"rounded",axis:s.axis,plane:i,ends:o,across:[e(r.size[i[0]]),e(r.size[i[1]])],corner:[e(t),e(a)]}:n()}return"ellipse"===r.kind?{kind:"ellipse",axis:s.axis,plane:i,ends:o,radius:[e(r.radius[i[0]]),e(r.radius[i[1]])]}:{kind:"polygon",axis:s.axis,plane:i,ends:o,points:r.points.map(t=>[e(t[i[0]]),e(t[i[1]])])}}if(t.loft){const n=t.loft,s=[...Kv[n.axis]];return{kind:"loft",axis:n.axis,plane:s,ends:{lo:e(n.start),hi:e(n.end)},points:n.section.points.map(t=>[e(t[s[0]]),e(t[s[1]])]),apex:[e(n.apex[s[0]]??0),e(n.apex[s[1]]??0)]}}if(t.revolution){const n=t.revolution;return"half-ellipse"===n.profile.kind?{kind:"sphere",axis:n.axis,radial:e(n.profile.radial),axial:e(n.profile.axial)}:{kind:"taper",axis:n.axis,ends:{lo:e(n.profile.start),hi:e(n.profile.end)},radii:[e(n.profile.startRadius),e(n.profile.endRadius)]}}return n()}(t),s=e.map(t=>-t);return{max:Ww(Fw(n,e),{}),min:-Ww(Fw(n,s),{})}}function Uw(t,e,n){const{shape:s}=Vx(t,e,n),i=I_(s,t),o=t=>zw([{ref:s.args[t],k:1}]),r=G_(s,t)??{},a=t=>{const[e,n]={x:["left","right"],y:["bottom","top"],z:["back","front"]}[t],i=[{ref:s.args[0],k:1}];return{lo:zw(r[e]?ww(s,r[e]):i),hi:zw(r[n]?ww(s,r[n]):[...i,{ref:s.args[1],k:1}])}},c=()=>{const s=Mw(t,e,n);return{kind:"box",lo:Object.fromEntries(jv.map(t=>[t,zw(s[t].lo)])),hi:Object.fromEntries(jv.map(t=>[t,zw(s[t].hi)]))}},l=t=>{const[e,n]=t.plane;return t.points.map(s=>[o(t.arg.point[s][e]),o(t.arg.point[s][n])])};if("extrude@1"===s.op){const t=g_(s.params,s.id),e=t.plane,n=a(t.axis);if("portal"===t.section||"rectangle"===t.section&&!t.rounded)return c();const i=()=>[o(t.arg.across[e[0]]),o(t.arg.across[e[1]])];return"rectangle"===t.section?{kind:"rounded",axis:t.axis,plane:e,ends:n,across:i(),corner:[o(t.arg.corner[e[0]]),o(t.arg.corner[e[1]])]}:"ellipse"===t.section?{kind:"ellipse",axis:t.axis,plane:e,ends:n,radius:i()}:{kind:"polygon",axis:t.axis,plane:e,ends:n,points:l(t)}}if("loft@1"===s.op){const t=w_(s.params,s.id),e=t.plane;return{kind:"loft",axis:t.axis,plane:e,ends:a(t.axis),points:l(t),apex:[o(t.apex[e[0]]),o(t.apex[e[1]])]}}if("revolve@1"===s.op){const t=s.params.axis;return"sphere"===i?.kind?{kind:"sphere",axis:t,radial:o(0),axial:o(1)}:{kind:"taper",axis:t,ends:a(t),radii:[o(2),o(3)]}}return c()}function Vw(t,e,n,s){return JSON.stringify(t)===JSON.stringify(e)?jw(t,Math.hypot(n,s)):function(t){const e=t.filter(t=>!(Rw(t)&&!t.terms.length&&!t.constant));if(1===e.length&&Rw(e[0])){const t=e[0];return zw(t.terms.map(t=>({ref:t.ref,k:Math.abs(t.k)})),Math.abs(t.constant))}return e.length?{hypot:e}:zw([])}([jw(t,n),jw(e,s)])}function Ww(t,e){if(Rw(t))return t.constant+t.terms.reduce((t,n)=>t+n.k*e[n.ref],0);if("scaled"in t)return t.k*Ww(t.scaled,e);if("product"in t)return Ww(t.product[0],e)*Ww(t.product[1],e);if("quotient"in t)return Ww(t.quotient[0],e)/Ww(t.quotient[1],e);if("geomean"in t)return Math.sqrt(Ww(t.geomean[0],e)*Ww(t.geomean[1],e));const n=("add"in t?t.add:"max"in t?t.max:t.hypot).map(t=>Ww(t,e));return"add"in t?n.reduce((t,e)=>t+e,0):"max"in t?Math.max(...n):Math.hypot(...n)}function Yw(t,e,n,s){const i=(n,s,i)=>{const o=e(i);return t.nodes.push({id:o,op:n,args:s,outputs:{value:`${o}.value`}}),`${o}.value`},o=(e,n)=>{if(Rw(e)){const s=e.terms.map((e,s)=>1===e.k?e.ref:i("mul@1",[e.ref,Yx(t,"ratio",e.k,"k")],`${n}.t${s}`));return!e.constant&&s.length||s.push(Yx(t,"mm",e.constant,"d")),1===s.length?s[0]:s.slice(1).reduce((t,e,s)=>i("add@1",[t,e],`${n}.s${s}`),s[0])}if("scaled"in e)return i("mul@1",[o(e.scaled,`${n}.x`),Yx(t,"ratio",e.k,"k")],n);if("product"in e)return i("mul@1",[o(e.product[0],`${n}.p0`),o(e.product[1],`${n}.p1`)],n);if("quotient"in e)return i("div@1",[o(e.quotient[0],`${n}.q0`),o(e.quotient[1],`${n}.q1`)],n);if("geomean"in e)return i("geomean@1",[o(e.geomean[0],`${n}.g0`),o(e.geomean[1],`${n}.g1`)],n);const s="add"in e?"add@1":"max"in e?"max@1":"hypot@1",r=("add"in e?e.add:"max"in e?e.max:e.hypot).map((t,e)=>o(t,`${n}.${e}`));return"add@1"===s?r.slice(1).reduce((t,e,s)=>i("add@1",[t,e],`${n}.a${s}`),r[0]):i(s,r,n)};return o(n,s)}const qw=(t,e)=>t.motion?.[e]?.id??(0===e?t.id:`${t.id}.${e+1}`);function Xw(t){return(Array.isArray(t.motion)?t.motion:[]).map((e,n)=>({...e,id:qw(t,n)}))}const Kw=t=>t.state?.id??t.id,Jw=(t,e)=>0===e?`${t}.motion`:`${t}.motion.${e+1}`;function Qw(t){return(t??[]).flatMap(t=>Xw(t).map((e,n)=>({joint:t,motion:e,k:n})))}const Zw=(t,e)=>jv.map(n=>n===t?e:0);function tM(t,e,n){const s=t.document.model,i=e.body1.part,o=n.path,r=e.body0,a=e.origin??{},c=a.facing??"meet";zx.includes(c)||Nx("JOINT_SCHEMA",`${o}.origin.facing`,`${String(c)} is not a facing; ${zx.join(", ")}`);const l="plane"in r,h=Wx(s,`${i}.on.${l?"plane":r.part}`);let d,u,p;const f={};let m,g;if("surface"in r){r.part===i&&Nx("ATTACH_CYCLE",o,"a part cannot be fastened to itself"),g=function(t,e,n,s){const i=`${s}.body0.surface`,{shape:o}=Vx(t,e,s),r=function(t,e,n){const{shape:s}=Vx(t,e,n);return"extrude@1"===s.op&&"ellipse"===s.params?.section?"around":"revolve@1"===s.op&&"half-ellipse"===s.params?.profile?"toward":void 0}(t,e,s),a="around"===r,c="toward"===r,l="revolve@1"===o.op?"a frustum, whose side turns with its slope (not taken yet, ADR-0140 3.9) -- fasten to its top or bottom":"flat faces only -- fasten to a face";a||c||Nx("ATTACH_FACE",i,`${e} has no curved surface to fasten to: ${l}`);const h=t=>{const e=Math.hypot(...t);return t.map(t=>t/e)},d=(t,e)=>[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]];let u,p;if("toward"in n){c||Nx("ATTACH_FACE",i,`${e} is a cylinder: a point on its side is { around, along }`),u=h(jv.map(t=>n.toward[t]??0));const t=jv.reduce((t,e,n)=>Math.abs(u[n])<Math.abs(u[t])-1e-12?n:t,0);p=h(jv.map((e,n)=>(n===t?1:0)-u[t]*u[n]))}else{a||Nx("ATTACH_FACE",i,`${e} is round: a point on it is { toward }`);const t=o.params.axis;u=h(xw(t,n.around)),p=Zw(t,1)}const f=d(p,u),m=jv.map((t,e)=>[p[e],u[e],f[e]].map(t=>Math.abs(t)<1e-12?0:t)),g=Nw(t,e,u,s);"not"in g&&Nx("ATTACH_FACE",i,`${e} has no curved surface to fasten to: ${l}`);const{point:y,push:b}=g;return{frame:m,point:y,along:{x:"along"in n?n.along:"centre",z:"centre"},...b?{push:b}:{}}}(s,r.part,r.surface,o),d="y",u=1,p=[];const t=g.push;t&&(f.x={lo:t.lo.terms,hi:t.hi.terms})}else if(l){const e=XS(t);d="wall"===e?"z":"y",u=1,p=[],"wall"===e&&"meet"!==c&&Nx("ATTACH_FACE",o,`the figure hangs on a wall; ${i} stands out of it (meet), not ${c}`),"centre"===c&&Nx("JOINT_SCHEMA",`${o}.origin.facing`,"a part stands on the mounting plane or hangs from it; its middle is not on it");for(const e of jv.filter(t=>t!==d))if(aw(s,e)){const n=Qx(s,t,{of:"instance",axis:e},o);f[e]={lo:[{ref:n,k:-.5}],hi:[{ref:n,k:.5}]}}}else{r.part===i&&Nx("ATTACH_CYCLE",o,"a part cannot be fastened to itself");const t=_w(s,r.part,o),e=Object.hasOwn(t.faces,String(r.face))?t.faces[r.face]:void 0;e||Nx("SCHEMA",o,`${r.part} has no face ${String(r.face)}; it has ${Object.keys(t.faces).join(", ")}`),"line"===e.contact&&Nx("ATTACH_FACE",o,`${r.part}'s ${String(r.face)} is the curved side of a cylinder; fasten to a point on it -- surface: { around, along } (ADR-0140 3.9)`),d=e.axis,u=e.normal,p=ww(t.shape,e);const n=Mw(s,r.part,o);for(const t of jv.filter(t=>t!==d))n[t]&&(f[t]={lo:n[t].lo,hi:n[t].hi});m=function(t,e,n,s){const{shape:i}=Vx(t,e,s),o=G_(i,t)?.[n],r=Uw(t,e,s);if(!o||"ellipse"!==r.kind&&"taper"!==r.kind||o.axis!==r.axis)return;if("ellipse"===r.kind)return{[r.plane[0]]:r.radius[0],[r.plane[1]]:r.radius[1]};const a=r.radii[o.normal<0?0:1];return Object.fromEntries(jv.filter(t=>t!==r.axis).map(t=>[t,a]))}(s,r.part,String(r.face),o)}const y=a.childRotate??{},b=g?gw(Aw(g.frame),Tw(y)):Tw(y),v=t=>Bw(s,i,kw(Aw(b),t),o),_=void 0===a.gap?zw([]):zw([{ref:Xx(s,t,h,a.gap,`gap.${d}`,o),k:1}]),[x,w]=[v(Zw(d,-u)),v(Zw(d,u))],M={},S={},A=zw(p);M[d]=$w(A,"meet"===c?jw($w(_,x),u):"flush"===c?jw($w(_,w),-u):jw($w(_,jw($w(x,jw(w,-1)),.5)),u)),S[d]="centre"===c?$w(M[d],jw($w(v(Zw(d,1)),jw(v(Zw(d,-1)),-1)),.5)):A;const k=jv.filter(t=>t!==d),E=t=>g?g.along[t]??"centre":a.align?.[t]??"centre",T=t=>"object"==typeof t&&!!t&&Object.hasOwn(t,"mm"),C={},O=e=>{const n=E(e);return C[e]??=T(n)?zw([{ref:Xx(s,t,h,n.mm,`align.${e}`,o),k:1}]):zw([])},P=m&&function(t,e,n,s,i,o,r){const{child:a,part:c,face:l,C:h,reach:d,path:u}=r,p=s.filter(t=>"min"===i(t)||"max"===i(t));if(!p.length)return;const f=`${c}'s ${l} is a disc`;2===p.length&&Nx("ATTACH_FACE",u,`${f}: ${a} touches its rim lined up on one axis, min or max; the other is the centre or a measured offset (ADR-0140 3.9)`);const m=p[0],g=s.find(t=>t!==m);"mesh@1"===Vx(e,a,u).shape.op&&Nx("ATTACH_FACE",u,`${f}: a mesh's footprint is not known, so ${a} cannot be lined up with its rim -- give the centre or a measured offset (ADR-0140 3.9)`);const y=jv.find(t=>!s.includes(t)),b=t=>kw(Aw(h),Zw(t,1)),v=zw([]),_=JSON.stringify(o(g))===JSON.stringify(v)?v:{max:[o(g),jw(o(g),-1)]},[x,w]=[n[m],n[g]],M=JSON.stringify(x)===JSON.stringify(w),S=(t,e)=>({geomean:[{max:[$w(t,jw(e,-1)),v]},$w(t,e)]});let A,k;if(function(t,e,n,s){const i=Uw(t,e,s);return("sphere"===i.kind||"taper"===i.kind||"ellipse"===i.kind&&JSON.stringify(i.radius[0])===JSON.stringify(i.radius[1]))&&Math.abs(Math.abs(n[jv.indexOf(i.axis)])-1)<1e-9}(e,a,b(y),u)){M||Nx("ATTACH_FACE",u,`${f} of two radii: a round part touches its rim at no closed-form place -- give the centre or a measured offset (ADR-0140 3.9)`);const t=$w(x,jw(d(Zw(m,1)),-1));A=[t,_],k=S(t,_)}else{const t=[0,1,2].some(t=>[m,g].some(e=>Math.abs(Math.abs(h[jv.indexOf(e)][t])-1)<1e-9));t||Nx("ATTACH_FACE",u,`${f}: ${a} is turned about its axis by other than a right angle, so its corners are not where its reaches say -- give the centre or a measured offset (ADR-0140 3.9)`);const e=t=>jw($w(d(Zw(t,1)),d(Zw(t,-1))),.5),n=$w(_,e(g));A=[w,n];const s=S(w,n);k=$w(M?s:{product:[{quotient:[x,w]},s]},jw(e(m),-1))}const E=function(t,e,n){const s=new Map,i=t=>{const n=Bx(e,t);if(n&&!s.has(n.id)){s.set(n.id,n);for(const t of n.args??[])i(t)}};for(const t of n.flatMap(Hw))i(t);return Px({...e,nodes:[...s.values()]}).evaluate({...t.designInputs,...t.stateDefaults}).values}(t,e,[...A,...M?[]:[x]]),[T,C]=A.map(t=>Ww(t,E));T-C>=-1e-9||Nx("ATTACH_FACE",u,`${f}: ${a} is wider than the disc where it would touch its rim (${Math.round(C)} mm across from its middle, ${Math.round(T)} mm there) -- give the centre or a measured offset (ADR-0140 3.9)`);return{middle:k}}(t,s,m,k,E,O,{child:i,part:String(r.part),face:String(r.face),C:b,reach:v,path:o});for(const t of k){const[e,n]=[v(Zw(t,1)),v(Zw(t,-1))],s=jw($w(e,jw(n,-1)),.5),a=E(t),c=f[t];if("min"!==a&&"max"!==a){if("centre"===a||T(a)){const e=zw(c?[...bw(c.lo),...bw(c.hi)]:[]);M[t]=$w(e,O(t),jw(s,-1))}else Nx("SCHEMA",o,`${String(a)} is not an alignment`);S[t]=$w(M[t],s)}else{if(c||Nx(l?"SCHEMA":"ATTACH_FACE",o,l?`the plane has no edges to line ${i} up with on ${t}; declare the figure's size, or give the centre or a measured offset`:`${r.part} has no edges along ${t} to line ${i} up with; give the centre or a measured offset`),P){const i=zw([...bw(c.lo),...bw(c.hi)]),o="min"===a?-1:1;M[t]=$w(i,jw(P.middle,o),jw(s,-1)),S[t]=$w(M[t],"min"===a?jw(n,-1):e);continue}M[t]="min"===a?$w(zw(c.lo),n):$w(zw(c.hi),jw(e,-1)),S[t]=zw("min"===a?c.lo:c.hi)}}const I=n.pivot??"seat";if("child-centre"===I)for(const t of jv)S[t]=$w(M[t],jw($w(v(Zw(t,1)),jw(v(Zw(t,-1)),-1)),.5));if("child-face"===I){const t=kw(Aw(b),Zw(d,-u)),e=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9),n="meet"===c&&e>=0?Mw(s,i,o):{},a=e>=0?n[jv[e]]:void 0;a||Nx("JOINT_SCHEMA",`${o}.origin.pivot`,`${i} meets ${l?"the plane":g?`${r.part}'s surface`:`${r.part}'s ${r.face}`} at a point or a line${"meet"===c?"":` (${c})`}, not by a face of its own; child-face has no face to turn about -- child-centre or seat`);const h=jv.map((s,i)=>i===e?t[e]>0?a.hi:a.lo:n[s]?[...bw(n[s].lo),...bw(n[s].hi)]:[]);jv.forEach((t,e)=>{S[t]=$w(M[t],...jv.map((t,n)=>zw(h[n].map(t=>({ref:t.ref,k:t.k*b[e][n]})))))})}const D=jv.map(t=>$w(M[t],jw(S[t],-1))),z=n.offset??{},R=t=>jv.map((e,n)=>$w(...jv.map((e,s)=>jw(t[s],g.frame[n][s])))),j=g?R(jv.map(t=>S[t])).map((t,e)=>$w(g.point[jv[e]],t)):jv.map(t=>S[t]),$=g?R(D):D,L=jv.map((e,n)=>void 0===z[e]||0===z[e]?j[n]:$w(j[n],zw([{ref:Xx(s,t,h,z[e],`offset.${e}`,`${o}.origin.offset.${e}`),k:1}]))),F=(t,e)=>Yw(s,h,t,e);nM(t,i,l?t.document.capabilities.assetFrame:`${r.part}.local`,{seat:L.map((t,e)=>F(t,`seat.${jv[e]}`)),pose:$.map((t,e)=>F(t,`pose.${jv[e]}`))});const{pose:N}=Vx(s,i,o),H=N.args.slice(3,6);N.args=[...N.args.slice(0,3),...Ow(g?Tw(y):b,!0).map(t=>Yx(s,"deg",t,"a"))];for(const e of H)iw(t,e,tw(s,i,e)?e:void 0);jv.some(t=>0!==(n.parentRotate?.[t]??0))&&eM(t,i,Tw(n.parentRotate),n.parentRotate,Sw)}function eM(t,e,n,s,i){const o=t.document.model,r=Hx(o,`${e}.seat.rigid`),a=t=>String(rw(t)).replace("-","m").replace(".","_"),c=(t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)))(i)?"":`.in.${Ow(Aw(i)).map(a).join("_")}`,l=`rotate.${jv.map(t=>a(s[t]??0)).join("_")}${c}`,h=Ow(n,!0),d=r.args.slice(3,6);r.args=[...r.args.slice(0,3),...jv.map((t,e)=>{const n=`${l}.${t}`;return o.constants.some(t=>t.id===n)||o.constants.push({id:n,unit:"deg",value:h[e]}),n})];for(const e of d)iw(t,e)}function nM(t,e,n,s){const i=t.document.model,{place:o,pose:r}=Vx(i,e,e),a=s?r.args.slice(0,3):[];s&&(r.args=[...s.pose,...r.args.slice(3)]),r.params={...r.params,to:`${e}.seat`};const c=sM(i,e),l=c.length>0,h=Yx(i,"mm",0,"d"),d=Yx(i,"deg",0,"a");let u=Hx(i,`${e}.seat.rigid`);u||(u={id:`${e}.seat.rigid`,op:"rigid@1",args:[h,h,h,d,d,d],outputs:{pose:`${e}.seat.value`},params:{}},i.nodes.push(u));const p=s?u.args.slice(0,3):[];s&&(u.args=[...s.seat,...u.args.slice(3)]),u.params={from:l?`${e}.joint`:`${e}.seat`,to:n};const f=function(t,e,n,s){const i=n.length,o=new Set,r=e=>{o.add(e.id);const n=Hx(t,e.id);return n?Object.assign(n,e):t.nodes.push(e),e.outputs.pose};let a=s;for(let t=i-1;t>=0;t--){const{motion:s,through:o,back:c}=n[t],l=t===i-1?`${e}.seat`:`${e}.joint.${t+1}`,h=0===t?`${e}.joint`:`${e}.joint.${t}`;let d=s.outputs.pose;if(o&&c){c.params={from:l,to:`${s.id}.axis`},s.params={...s.params,from:`${s.id}.axis`,to:`${s.id}.moved`},o.params={from:`${s.id}.moved`,to:h};const t=r({id:`${s.id}.about.turned`,op:"compose@1",args:[s.outputs.pose,c.outputs.pose],outputs:{pose:`${s.id}.about.turned.value`}});d=r({id:`${s.id}.about`,op:"compose@1",args:[o.outputs.pose,t],outputs:{pose:`${s.id}.about.value`}})}else s.params={...s.params,from:l,to:h};a=r({id:0===t?`${e}.turned`:`${e}.turned.${t+1}`,op:"compose@1",args:[d,a],outputs:{pose:(0===t?`${e}.turned`:`${e}.turned.${t+1}`)+".value"}})}const c=t=>t===`${e}.turned`||t.startsWith(`${e}.turned.`)||/\.about(\.turned)?$/.test(t)&&t.startsWith(`${e}.motion`);return t.nodes=t.nodes.filter(t=>!c(t.id)||o.has(t.id)),i?a:void 0}(i,e,c,r.outputs.pose);let m=Hx(i,`${e}.chain`);m||(m={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},i.nodes.push(m)),m.args=[u.outputs.pose,f??r.outputs.pose];const g=/^(.*)\.local$/.exec(n);let y=Hx(i,`${e}.world`);if(g&&g[1]!==e){const t=Hx(i,`${g[1]}.world`)?.outputs?.pose??Hx(i,`${g[1]}.chain`)?.outputs?.pose??Hx(i,`${g[1]}.turned`)?.outputs?.pose??Hx(i,`${g[1]}.pose`).outputs.pose;y?y.args=[t,m.outputs.pose]:(y={id:`${e}.world`,op:"compose@1",args:[t,m.outputs.pose],outputs:{pose:`${e}.world.value`}},i.nodes.push(y)),o.args=[o.args[0],y.outputs.pose]}else y&&(i.nodes=i.nodes.filter(t=>t!==y)),o.args=[o.args[0],m.outputs.pose];for(const n of[...a,...p])iw(t,n,tw(i,e,n)?n:void 0)}function sM(t,e){const n=[];for(let s=0,i=Hx(t,Jw(e,s));i;i=Hx(t,Jw(e,++s)))n.push({motion:i,through:Hx(t,`${i.id}.through`),back:Hx(t,`${i.id}.back`)});return n}function iM(t,e,n,s=1,i={k:0}){const o=t.document.model,r=e.part;Vx(o,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&Nx("SCHEMA",r,"a slide or a turn is required"),jv.includes(e.motion.axis)||Nx("SCHEMA",r,`${String(e.motion.axis)} is not an axis`),0===i.k&&Hx(o,`${e.part}.motion`),0===i.k&&Hx(o,`${e.part}.motion`)&&oM(t,{part:e.part});const a=Jw(e.part,i.k),c=e.motion.frame??"attachment",l=((t,e)=>{const n=ow(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame})(t,e.part);"asset"===c&&l!==t.document.capabilities.assetFrame?Nx("MOTION_FRAME",r,`${e.part} is fastened into ${l}; an axis in the asset frame would have to be re-expressed there, which this command does not do`):"attachment"!==c&&"asset"!==c&&Nx("SCHEMA",r,`${String(c)} is not a frame for the axis`);const h=e.state,d=Wx(o,a);let u=h?.id;if(n){if(n.sum)for(const[t,e]of n.terms.entries()){const n=d(`mimic.${t}`);if(o.nodes.push({id:n,op:"mul@1",args:[e.of,Yx(o,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=d(`mimic.${t}.sum`);o.nodes.push({id:e,op:"add@1",args:[u,`${n}.value`],outputs:{value:`${e}.value`}}),u=`${e}.value`}else u=`${n}.value`}else{const t=d("mimic");o.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,Yx(o,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),u=`${t}.value`}if(n.c){const t=d("mimic.offset"),s="slide"===e.motion.kind?"mm":"deg";o.nodes.push({id:t,op:"add@1",args:[u,Yx(o,s,n.c,"d")],outputs:{value:`${t}.value`}}),u=`${t}.value`}}else{h&&"string"==typeof h.id&&h.id.trim()||Nx("SCHEMA",r,"a state input id is required");const n=o.inputs.find(t=>t.id===h.id&&"state"===t.role&&t.unit===h.unit&&t.min===h.min&&t.max===h.max);if(n);else if(o.inputs.some(t=>t.id===h.id)){const e=o.nodes.some(t=>t.args.includes(h.id))||(t.drivers??[]).some(t=>t.state===h.id)||t.appearance.some(t=>t.visibility===h.id);if(e&&Nx("DUPLICATE_WRITER",r,`${h.id} already exists`),o.inputs=o.inputs.filter(t=>t.id!==h.id),delete t.stateDefaults[h.id],t.stateInputs?.[h.id]){const{[h.id]:e,...n}=t.stateInputs;t.stateInputs=n}}const s="turn"===e.motion.kind?["deg"]:["mm","ratio"];s.includes(h.unit)||Nx("SCHEMA",r,`a ${e.motion.kind} takes a ${s.join(" or ")} control, not ${String(h.unit)}`),Number.isFinite(h.min)&&Number.isFinite(h.max)&&h.max>h.min||Nx("SCHEMA",r,"a range with max above min is required");const i=h.start??h.min;i>=h.min&&i<=h.max||Nx("SCHEMA",r,"the starting value is outside the range"),n||(o.inputs.push({id:h.id,unit:h.unit,min:h.min,max:h.max,role:"state"}),t.stateDefaults[h.id]=i),void 0===h.label&&void 0===h.sweep||(t.stateInputs={...t.stateInputs??{}},t.stateInputs[h.id]={...void 0!==h.label?{label:h.label}:{},...void 0!==h.sweep?{sweep:h.sweep}:{}})}if("slide"===e.motion.kind&&"ratio"===h.unit){e.travel||Nx("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let s;if(Object.hasOwn(n,"sum")){const e=n.plus??0;s=qx(o,d,Jx(o,d,Kx(o,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?Qx(o,t,n.source,r):Yx(o,"mm",n.plus??0,"d");s=n.source?qx(o,d,e,n.times??1,n.plus??0,"travel"):e}const i=d("distance");o.nodes.push({id:i,op:"mul@1",args:[u,s],outputs:{value:`${i}.value`}}),u=`${i}.value`}else"slide"===e.motion.kind&&e.travel&&Nx("SCHEMA",r,"a mm control is the distance; travel would say it twice");const p=Array.isArray(s)?s.map(t=>Yx(o,"ratio",t,"axis")):jv.map(t=>Yx(o,"ratio",t===e.motion.axis?s:0,"axis"));o.nodes.push({id:a,op:"slide"===e.motion.kind?"axis-slide@1":"axis-turn@1",args:[...p,u],outputs:{pose:`${a}.value`},params:{from:`${e.part}.seat`,to:l}});const f=jv.map(t=>i.through?.[t]);if(f.some(t=>void 0!==t&&0!==t)){const e=f.map((e,n)=>Xx(o,t,d,e,`through.${jv[n]}`,`${i.path??r}.through.${jv[n]}`)),n=Yx(o,"deg",0,"a"),s=(t,e)=>o.nodes.push({id:`${a}.${t}`,op:"rigid@1",args:[...e,n,n,n],outputs:{pose:`${a}.${t}.value`},params:{}});s("through",e),s("back",e.map((t,e)=>Jx(o,d,[{ref:t,k:-1}],`back.${jv[e]}`)))}if(nM(t,e.part,l),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||Nx("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||Nx("SCHEMA",r,"a clip runs for a positive number of seconds"),t.drivers=[...t.drivers??[],{id:`${e.part}/${n.name}`,clip:n.name,state:h.id,time:{unit:"s",duration:n.duration},keys:structuredClone(n.keys),interpolation:"linear",loop:n.loop??"wrap",accumulates:n.accumulates??!1}]}return t}function oM(t,e){const n=t.document.model,s=sM(n,e.part);s.length||Nx("EDIT_TARGET",e.part,`${e.part} does not move`);const i=Hx(n,`${e.part}.seat.rigid`)?.params?.to??s[0].motion.params.to,o=s.map(({motion:t})=>{const e=t.args[3],s=n.inputs.find(t=>t.id===e&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(Bx(n,e)?.args??[]).includes(t.id));return{quantity:e,state:s}}),r=s.flatMap(({through:t,back:e})=>[t,e].filter(Boolean)),a=new Set([...s.map(t=>t.motion),...r]);n.nodes=n.nodes.filter(t=>!a.has(t)),nM(t,e.part,i);for(const e of r)for(const n of e.args)iw(t,n);for(const{quantity:e,state:s}of o)iw(t,e,e),s&&!n.nodes.some(t=>t.args.includes(s.id))&&(n.inputs=n.inputs.filter(t=>t!==s),delete t.stateDefaults[s.id],t.stateInputs&&delete t.stateInputs[s.id],t.drivers&&(t.drivers=t.drivers.filter(t=>t.state!==s.id)),t.drivers&&!t.drivers.length&&delete t.drivers,t.stateInputs&&!Object.keys(t.stateInputs).length&&delete t.stateInputs);return t}const rM={joint:((...t)=>t)("id","body0","body1","origin","motion","repeat"),motion:((...t)=>t)("id","type","axis","through","lowerLimit","upperLimit","travel","state","mimic"),body0:((...t)=>t)("part","face","surface","plane","at"),surface:((...t)=>t)("toward","around","along"),body1:((...t)=>t)("part","at"),origin:((...t)=>t)("facing","gap","align","childRotate","pivot","offset","parentRotate"),axes:((...t)=>t)("x","y","z"),alignment:((...t)=>t)("mm"),measure:((...t)=>t)("from","times","plus","sum"),term:((...t)=>t)("from","times"),source:((...t)=>t)("of","axis","input","part"),travel:((...t)=>t)("source","times","plus","sum"),state:((...t)=>t)("id","label","start","sweep"),mimic:((...t)=>t)("motion","multiplier","offset","sum"),leader:((...t)=>t)("motion","multiplier"),repeat:((...t)=>t)("axis","pitch","count","rise"),rise:((...t)=>t)("axis","mm")};const aM=t=>!!t.body0&&"at"in t.body0;function cM(t,e){if(!t||"object"!=typeof t)return;const n=jv.map(e=>t[e]);n.every(t=>"number"==typeof t&&Number.isFinite(t))||Nx("JOINT_SCHEMA",`${e}.axis`,"an axis vector is three finite numbers { x, y, z }");const s=Math.hypot(...n);return s>1e-9||Nx("JOINT_SCHEMA",`${e}.axis`,"an axis vector is not zero"),n.map(t=>t/s)}const lM=t=>jv.some(e=>0!==(t.origin?.parentRotate?.[e]??0));function hM(t,e){const n=t.origin??{},s=t.body0,i=t.body1;if("at"in s&&"origin"!==s.at&&Nx("JOINT_SCHEMA",`${e}.body0`,`${String(s.at)} is not a place on a part; at: 'origin' is`),"at"in i&&"origin"!==i.at&&Nx("JOINT_SCHEMA",`${e}.body1`,`${String(i.at)} is not a place on a part; at: 'origin' is`),"at"in s&&("face"in s||"plane"in s||"surface"in s)&&Nx("JOINT_SCHEMA",`${e}.body0`,"a joint hangs at a part's origin or on a face, not both"),"surface"in s&&function(t,e){const n=t.body0.surface,s=`${e}.body0.surface`;n&&"object"==typeof n||Nx("JOINT_SCHEMA",s,"a place on a surface is { toward } or { around, along }");const i="toward"in n&&void 0!==n.toward;if(i===("around"in n&&void 0!==n.around||"along"in n&&void 0!==n.along)&&Nx("JOINT_SCHEMA",s,"a place on a surface is { toward } on a round surface or { around, along } on a side, one of them"),i){const t=jv.map(t=>n.toward?.[t]??0);t.every(t=>"number"==typeof t&&Number.isFinite(t))||Nx("JOINT_SCHEMA",`${s}.toward`,"toward is three finite numbers { x, y, z }");const e=Math.hypot(...t);e>1e-9||Nx("JOINT_SCHEMA",`${s}.toward`,"toward is the outward normal there; a zero vector points nowhere"),Math.abs(e-1)>1e-5&&Nx("JOINT_SCHEMA",`${s}.toward`,`toward is a unit vector; this one is ${rw(e)} long`)}else"number"==typeof n.around&&Number.isFinite(n.around)||Nx("JOINT_SCHEMA",`${s}.around`,"around is the normal's angle about the push axis, in degrees"),void 0===n.along&&Nx("JOINT_SCHEMA",`${s}.along`,"along says where on the push: 'centre', 'min', 'max' or { mm }");void 0!==t.origin?.align&&Object.values(t.origin.align).some(t=>void 0!==t)&&Nx("JOINT_SCHEMA",`${e}.origin.align`,"on a surface the place is the surface's own words (toward, around, along), not align"),lM(t)&&Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,"on a surface the joint frame is the surface's there; it is not turned again")}(t,e),aM(t))for(const t of["align","gap","facing","childRotate","pivot"])void 0!==n[t]&&Nx("JOINT_SCHEMA",`${e}.origin.${t}`,`${t} places a part on a face; ${s.part}'s origin is a point and a frame, placed by offset and parentRotate`);else"at"in i&&Nx("JOINT_SCHEMA",`${e}.body1`,`a child is placed by its origin only at its parent's origin; ${"plane"in s?"the mounting plane":"surface"in s?`${s.part}'s surface`:`${s.part}'s ${String(s.face)}`} is a face`);if(void 0===n.pivot||jx.includes(n.pivot)||Nx("JOINT_SCHEMA",`${e}.origin.pivot`,`${String(n.pivot)} is not a pivot; ${jx.join(", ")}`),"child-face"===n.pivot&&"centre"===n.facing&&Nx("JOINT_SCHEMA",`${e}.origin.pivot`,`${i.part} is fastened by its middle, not by a face; child-face has no face to turn about -- it turns about its middle already (child-centre)`),void 0!==n.parentRotate){n.parentRotate&&"object"==typeof n.parentRotate&&!Object.values(n.parentRotate).some(t=>"number"!=typeof t||!Number.isFinite(t))||Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,"a rotation is degrees about x, y and z");const t=jv.filter(t=>"min"===n.align?.[t]||"max"===n.align?.[t]);t.length&&!(t=>t.every(t=>t.every(t=>Math.abs(t)<1e-9||Math.abs(Math.abs(t)-1)<1e-9)))(Tw(n.parentRotate))&&Nx("JOINT_SCHEMA",`${e}.origin.parentRotate`,`the joint frame is turned by other than quarter turns; ${i.part}'s sides are not level with the edges it is lined up with (${t.join(", ")}) -- place it by the centre or a distance`)}void 0===n.offset||n.offset&&"object"==typeof n.offset||Nx("JOINT_SCHEMA",`${e}.origin.offset`,"an offset is a length along x, y and z")}function dM(t,e){const n=t.document.model,s=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||Nx("JOINT_SCHEMA","joints","a joint has an id"),function(t,e){const n=(t,e,n)=>{if(t&&"object"==typeof t&&!Array.isArray(t))for(const[s,i]of Object.entries(t))void 0===i||e.includes(s)||Nx("JOINT_SCHEMA",n,`${s} is a field this kernel does not know`)},s=(t,e)=>n(t,rM.source,e),i=(t,e)=>{if(t&&"object"==typeof t&&(n(t,rM.measure,e),s(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[i,o]of t.sum.entries())n(o,rM.term,`${e}.sum.${i}`),s(o?.from,`${e}.sum.${i}.from`)};n(t,rM.joint,e),n(t.body0,rM.body0,`${e}.body0`);const o=t.body0?.surface;n(o,rM.surface,`${e}.body0.surface`),o&&"object"==typeof o&&(n(o.toward,rM.axes,`${e}.body0.surface.toward`),n(o.along,rM.alignment,`${e}.body0.surface.along`),i(o.along?.mm,`${e}.body0.surface.along.mm`)),n(t.body1,rM.body1,`${e}.body1`);const r=t.origin;if(n(r,rM.origin,`${e}.origin`),r&&"object"==typeof r){i(r.gap,`${e}.origin.gap`),n(r.childRotate,rM.axes,`${e}.origin.childRotate`),n(r.parentRotate,rM.axes,`${e}.origin.parentRotate`),n(r.offset,rM.axes,`${e}.origin.offset`);for(const[t,n]of Object.entries(r.offset&&"object"==typeof r.offset?r.offset:{}))i(n,`${e}.origin.offset.${t}`);n(r.align,rM.axes,`${e}.origin.align`);for(const[t,s]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(s,rM.alignment,`${e}.origin.align.${t}`),i(s?.mm,`${e}.origin.align.${t}.mm`)}void 0===t.motion||Array.isArray(t.motion)||Nx("JOINT_SCHEMA",`${e}.motion`,"a motion is a list of axes");for(const[o,r]of(Array.isArray(t.motion)?t.motion:[]).entries()){const t=`${e}.motion.${o}`;if(n(r,rM.motion,t),r&&"object"==typeof r){n(r.axis,rM.axes,`${t}.axis`),n(r.through,rM.axes,`${t}.through`);for(const[e,n]of Object.entries(r.through&&"object"==typeof r.through?r.through:{}))i(n,`${t}.through.${e}`);if(r.travel&&"object"==typeof r.travel&&(n(r.travel,rM.travel,`${t}.travel`),s(r.travel.source,`${t}.travel.source`),Array.isArray(r.travel.sum)&&i({sum:r.travel.sum},`${t}.travel`)),n(r.state,rM.state,`${t}.state`),n(r.mimic,rM.mimic,`${t}.mimic`),Array.isArray(r.mimic?.sum))for(const[e,s]of r.mimic.sum.entries())n(s,rM.leader,`${t}.mimic.sum.${e}`)}}n(t.repeat,rM.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(i(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,rM.rise,`${e}.repeat.rise`))}(e,s),e.body1&&"string"==typeof e.body1.part||Nx("JOINT_SCHEMA",s,"a joint carries a part (body1)"),Vx(n,e.body1.part,s),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||Nx("JOINT_SCHEMA",s,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&Vx(n,e.body0.part,s),hM(e,s);const i=(t.joints??[]).filter(t=>t.id!==e.id),o=i.find(t=>t.body1.part===e.body1.part);if(o&&Nx("JOINT_TREE",s,`${e.body1.part} already hangs from ${"part"in o.body0?o.body0.part:"the mounting plane"} by ${o.id}; a part has one joint above it`),"part"in e.body0){const t=t=>i.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&Nx("ATTACH_CYCLE",s,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const i=t(n);n=i&&"part"in i?i.part:void 0}}!function(t,e,n){const s=Xw(e),i=Qw(t).map(t=>t.motion),o=new Set([...i.map(t=>t.id),...t.map(t=>t.id)]);for(const[t,i]of s.entries()){const s=`${n}.motion.${t}`,r=e.motion[t];r&&"object"==typeof r||Nx("JOINT_SCHEMA",s,"an axis is { type, axis }"),Rx.includes(i.type)||Nx("JOINT_SCHEMA",s,`${String(i.type)} is not a motion; ${Rx.join(", ")}`),void 0===r.id||"string"==typeof r.id&&r.id.trim()||Nx("JOINT_SCHEMA",`${s}.id`,"an axis id is a name"),o.has(i.id)&&Nx("JOINT_SCHEMA",`${s}.id`,`${i.id} names another axis already; an axis id is unique among every joint's axes`),o.add(i.id),["X","Y","Z"].includes(i.axis)||cM(i.axis,s)||Nx("JOINT_SCHEMA",s,`a ${i.type} axis is X, Y or Z, or a vector { x, y, z }`);for(const[t,e]of Object.entries(i.through??{}))void 0===e||("number"==typeof e?Number.isFinite(e):Lx(e))||Nx("JOINT_SCHEMA",`${s}.through.${t}`,"the point an axis passes is millimetres, or a length that follows something");void 0!==i.travel&&"prismatic"!==i.type&&Nx("JOINT_SCHEMA",s,"only a prismatic axis travels a length");const a=void 0!==i.lowerLimit||void 0!==i.upperLimit;if("prismatic"===i.type&&i.travel&&!a&&(r.lowerLimit=0,r.upperLimit=1),!i.mimic&&(a||"prismatic"===i.type)){const[t,e]=[r.lowerLimit,r.upperLimit];Number.isFinite(t)&&Number.isFinite(e)&&t<e||Nx("JOINT_SCHEMA",s,`a ${i.type} axis has both limits, lower below upper`)}}for(const[t,e]of s.entries()){if(!e.mimic)continue;const o=`${n}.motion.${t}`;!Object.hasOwn(e.mimic,"sum")||Array.isArray(e.mimic.sum)&&e.mimic.sum.length||Nx("JOINT_SCHEMA",o,"a mimic sum follows one axis or more");const r=new Set;for(const t of $x(e)){const n=[...i,...s].find(n=>n.id===t?.motion&&n.id!==e.id);n||Nx("JOINT_SCHEMA",o,`${String(t?.motion)} is not a moving axis to follow`),r.has(n.id)&&Nx("JOINT_SCHEMA",o,`${n.id} is followed twice; a sum names each axis once`),r.add(n.id),n.mimic&&Nx("JOINT_SCHEMA",o,`${n.id} follows another axis; follow the one it follows`),"prismatic"===n.type!=("prismatic"===e.type)&&Nx("JOINT_SCHEMA",o,`${n.id} ${"prismatic"===n.type?"slides":"turns"}; an axis follows ones that move the same way: a slide a slide, a turn a turn`),Number.isFinite(t.multiplier)||Nx("JOINT_SCHEMA",o,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||Nx("JOINT_SCHEMA",o,"a mimic's offset is a number in the axis's unit")}}(i,e,s),void 0===e.origin?.childRotate||e.origin.childRotate&&"object"==typeof e.origin.childRotate&&!Object.values(e.origin.childRotate).some(t=>!Number.isFinite(t))||Nx("JOINT_SCHEMA",`${s}.origin.childRotate`,"a pose is degrees about x, y and z");const r=[...i,e],a=t=>r.find(e=>e.body1.part===t&&"part"in e.body0),c=t=>{for(let e=a(t);e;e=a(e.body0.part))if(e.repeat)return e};if(e.repeat){const t=e=>r.filter(t=>"part"in t.body0&&t.body0.part===e).flatMap(e=>[e.body1.part,...t(e.body1.part)]),n=[];for(let t=("part"in e.body0?c(e.body0.part):void 0);t;t="part"in t.body0?c(t.body0.part):void 0)n.push(t);const i=t(e.body1.part).map(t=>r.find(e=>e.body1.part===t)).filter(t=>t.repeat),o=[...n,...i].find(t=>t.repeat.axis===e.repeat.axis);o&&Nx("JOINT_SCHEMA",`${s}.repeat`,`${o.body1.part}'s row runs along ${o.repeat.axis} too; a row inside a row runs along another axis`,{reason:"row-same-axis",part:e.body1.part,outer:o.body1.part,axis:o.repeat.axis.toLowerCase()})}if(e.repeat){const n=e.repeat,i=`${s}.repeat`;"part"in e.body0||Nx("JOINT_SCHEMA",i,"a row fills the part it is fastened to; the mounting plane has no length to fill"),"surface"in e.body0&&Nx("JOINT_SCHEMA",i,"a row runs across a flat face, from edge to edge; one on a curved surface is not covered yet (ADR-0140 3.9)"),aM(e)&&Nx("JOINT_SCHEMA",i,"a row runs across the face it is fastened to; a joint placed at an origin has none");for(const t of["offset","parentRotate"])void 0!==e.origin?.[t]&&Nx("JOINT_SCHEMA",i,`a row with its joint frame moved or turned (origin.${t}) is not covered yet`);"seat"!==(e.origin?.pivot??"seat")&&Nx("JOINT_SCHEMA",i,`a row turning about ${e.origin.pivot} is not covered yet; its copies turn where they are fastened`),["X","Y","Z"].includes(n.axis)||Nx("JOINT_SCHEMA",i,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===function(t,e,n){if("plane"in n.body0)return"wall"===XS(e)?"z":"y";const s=t.nodes.find(t=>t.id===`${n.body0.part}.shape`);if("surface"in n.body0){const t=n.body0.surface;let e;return e="toward"in t?jv.map(e=>t.toward[e]??0):xw(s?.params?.axis??"y",t.around),jv.reduce((t,n,s)=>Math.abs(e[s])>Math.abs(e[jv.indexOf(t)])+1e-9?n:t,jv[0])}return"face"in n.body0?G_(s,t)?.[n.body0.face]?.axis??void 0:void 0}(t.document.model,t,e)&&Nx("JOINT_SCHEMA",i,`a row runs across the face it is fastened to; ${n.axis} is out of that face`),("number"==typeof n.pitch?Number.isFinite(n.pitch)&&n.pitch>0:Lx(n.pitch))||Nx("GEOMETRY_DOMAIN",i,"a row has a positive pitch, or one that follows a length"),void 0===n.count||Number.isSafeInteger(n.count)&&n.count>=1&&n.count<=Bv||Nx("GEOMETRY_DOMAIN",i,"a row has 1 to 100 copies",{reason:"row-copies-out-of-range",count:n.count,min:1,max:Bv}),void 0!==n.rise&&(n.rise&&["X","Y","Z"].includes(n.rise.axis)&&n.rise.axis!==n.axis||Nx("JOINT_SCHEMA",`${i}.rise`,`a row rises along X, Y or Z other than the one it runs along (${n.axis})`),Number.isFinite(n.rise.mm)&&0!==n.rise.mm||Nx("GEOMETRY_DOMAIN",`${i}.rise`,"a rise is a length in mm, not zero"))}}function uM(t,e){if(aM(e))return function(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,o=`joints.${e.id}`,{pose:r}=Vx(n,s,s),a=Yx(n,"deg",0,"a"),c=r.args.slice(3,6);r.args=[...r.args.slice(0,3),a,a,a];for(const e of c)iw(t,e,tw(n,s,e)?e:void 0);const l=Wx(n,`${s}.on.${i}`),h=Yx(n,"mm",0,"d"),d=t=>{if("at"in e.body1)return h;const i=e=>Bw(n,s,jv.map(n=>n===t?e:0),o);return Yw(n,l,jw($w(i(1),jw(i(-1),-1)),-.5),`own-centre.${t}`)},u=e.origin?.offset??{},p=jv.map(e=>void 0===u[e]?h:Xx(n,t,l,u[e],`offset.${e}`,`${o}.origin.offset.${e}`));nM(t,s,`${i}.local`,{seat:p,pose:jv.map(d)}),lM(e)&&eM(t,s,Tw(e.origin.parentRotate),e.origin.parentRotate,Sw)}(t,e),pM(t,e,Sw);tM(t,e,{pivot:e.origin?.pivot,offset:e.origin?.offset,parentRotate:e.origin?.parentRotate,path:`joints.${e.id}`}),pM(t,e,Sw)}function pM(t,e,n){const s=t.document.model,i=e.body1.part,o="part"in e.body0?e.body0.part:void 0,r=`joints.${e.id}`,a=Xw(e).map((t,e)=>({a:t,k:e})).sort((t,e)=>Number(!!t.a.mimic)-Number(!!e.a.mimic)||t.k-e.k);for(const{a:e,k:c}of a){const a=`${r}.motion.${c}`,l="prismatic"===e.type?"slide":"turn",h="prismatic"===e.type?e.travel?"ratio":"mm":"deg",d=void 0!==e.lowerLimit&&void 0!==e.upperLimit?{min:e.lowerLimit,max:e.upperLimit}:"revolute"===e.type?{min:-180,max:180}:{min:0,max:1},u=$x(e).map(e=>({leader:fM(t,e.motion),k:e.multiplier})),p=cM(e.axis,a),f=kw(n,p??jv.map(t=>t===e.axis.toLowerCase()?1:0)),m=p?0:f.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);m<0&&Nx("JOINT_SCHEMA",a,`${o} stands twisted; the axis ${e.axis} is not level with an axis in it`);const g=p?f.map(t=>Math.abs(t)<1e-12?0:Math.round(1e12*t)/1e12):f[m]>0?1:-1;iM(t,{part:i,motion:{kind:l,axis:jv[m]},state:{id:Kw(e),unit:h,min:d.min,max:d.max,start:e.state?.start??Math.min(d.max,Math.max(d.min,0)),...void 0!==e.state?.label?{label:e.state.label}:{},...void 0!==e.state?.sweep?{sweep:e.state.sweep}:{}},...e.travel?{travel:e.travel}:{}},e.mimic?{terms:u.map(({leader:t,k:e})=>({of:Hx(s,Jw(t.joint.body1.part,t.k))?.args[3]??Kw(t.motion),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,g,{k:c,through:e.through,path:a})}e.repeat&&function(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,o=`joints.${e.id}.repeat`,r=e.repeat.axis.toLowerCase(),a=jv.indexOf(r),c=Mw(n,i,o)[r];c||Nx("EDIT_TARGET",o,`${i} has no two faces along ${r}; there is no length to fill`);const l=Tw(e.origin?.childRotate??{}),h=t=>Bw(n,s,kw(Aw(l),jv.map(e=>e===r?t:0)),o),[d,u]=[h(1),h(-1)],{place:p,pose:f}=Vx(n,s,o),m=Hx(n,`${s}.seat.rigid`),g=Wx(n,`${s}.row`),y=Yx(n,"mm",0,"d");m.args=m.args.map((t,e)=>e===a?Jx(n,g,c.lo,"start"):t);const b=Yw(n,g,jw($w(d,jw(u,-1)),-.5),"own-centre");f.args=f.args.map((t,e)=>e===a?b:t);const v=Jx(n,g,[...c.hi,...yw(c.lo)],"length"),_=Yw(n,g,$w(d,u),"extent"),x=Yx(n,"ratio",.5,"k"),w=Yx(n,"count",Bv,"limit"),M=e.repeat.count;n.nodes.push(void 0===M?{id:`${s}.layout`,op:"fit-pitch@1",args:[v,y,y,_,Xx(n,t,g,e.repeat.pitch,"pitch",o),x,w],outputs:{layout:`${s}.layout.value`}}:{id:`${s}.layout`,op:"fixed-count@1",args:[Yx(n,"count",M,"count"),v,y,y,_,x,w],outputs:{layout:`${s}.layout.value`}}),p.op="member@1",p.args=[p.args[0],Hx(n,`${s}.turned`)?.outputs?.pose??f.outputs.pose],n.nodes.push({id:`${s}.assembly`,op:"assembly@1",args:[p.outputs.placed],outputs:{assembly:`${s}.assembly.value`}});const S=Hx(n,`${i}.world`)?.outputs?.pose??Hx(n,`${i}.chain`)?.outputs?.pose??Hx(n,`${i}.turned`)?.outputs?.pose??Hx(n,`${i}.pose`)?.outputs?.pose;let A=m.outputs.pose;S&&(n.nodes.push({id:`${s}.row`,op:"compose@1",args:[S,m.outputs.pose],outputs:{pose:`${s}.row.value`}}),A=`${s}.row.value`);n.nodes=n.nodes.filter(t=>t.id!==`${s}.chain`&&t.id!==`${s}.world`);const k=e.repeat.rise;n.nodes.push({id:`${s}.repeat`,op:"repeat@1",args:[`${s}.layout.value`,`${s}.assembly.value`,A,...k?[Yx(n,"mm",k.mm,"rise")]:[]],outputs:{collection:`${s}.repeat.value`},params:{axis:r,...k?{riseAxis:k.axis.toLowerCase()}:{}}})}(t,e)}const fM=(t,e)=>Qw(t.joints).find(t=>t.motion.id===e);function mM(t,e){const n=t.document.model,s=e.body1.part;!function(t,e){const n=t.document.model,s=Hx(n,e);if("member@1"!==s?.op||!Hx(n,`${e}.repeat`))return;const i=Hx(n,`${e}.layout`),o=Hx(n,`${e}.repeat`)?.args[3],r=new Set([`${e}.layout`,`${e}.assembly`,`${e}.repeat`,`${e}.row`]),a=n.nodes.filter(t=>r.has(t.id)||t.id.startsWith(`${e}.row.`));n.nodes=n.nodes.filter(t=>!a.includes(t)),s.op="place@1";for(const e of[...i?.args??[],...o?[o]:[]])iw(t,e)}(t,s),Hx(n,`${s}.motion`)&&oM(t,{part:s});const{pose:i,place:o}=Vx(n,s,s),r=new Set([`${s}.seat.rigid`,`${s}.chain`,`${s}.world`,`${s}.turned`]);n.nodes=n.nodes.filter(t=>!r.has(t.id)&&!t.id.startsWith(`${s}.on.`));const a=Yx(n,"mm",0,"d"),c=i.args.slice(0,3);i.args=[a,a,a,...i.args.slice(3)],i.params={...i.params,to:t.document.capabilities.assetFrame};for(const e of c)iw(t,e,tw(n,s,e)?e:void 0);o.args=[o.args[0],i.outputs.pose]}function gM(t){const e=[];void 0!==t.origin?.gap&&e.push({at:"gap",get:()=>t.origin.gap,set:e=>t.origin.gap=e}),t.repeat&&e.push({at:"pitch",get:()=>t.repeat.pitch,set:e=>t.repeat.pitch=e});for(const[n,s]of(t.motion??[]).entries()){if(s.travel){const t=s.travel;e.push({at:`motion.${n}.travel`,get:()=>Object.hasOwn(t,"sum")?{sum:t.sum,...void 0!==t.plus?{plus:t.plus}:{}}:t.source?{from:t.source,...void 0!==t.times?{times:t.times}:{},...void 0!==t.plus?{plus:t.plus}:{}}:t.plus??0,set:t=>{const e=Fx(t);s.travel=e?e.sum?{sum:e.terms,...e.plus?{plus:e.plus}:{}}:{source:e.terms[0].from,...void 0!==e.terms[0].times?{times:e.terms[0].times}:{},...void 0!==t.plus?{plus:t.plus}:{}}:{plus:t}}})}for(const t of Object.keys(s.through??{}))void 0!==s.through[t]&&e.push({at:`motion.${n}.through.${t}`,get:()=>s.through[t],set:e=>s.through[t]=e})}for(const n of Object.keys(t.origin?.align??{})){const s=t.origin.align[n];s&&"object"==typeof s&&Object.hasOwn(s,"mm")&&e.push({at:`align.${n}`,get:()=>s.mm,set:t=>s.mm=t})}for(const n of Object.keys(t.origin?.offset??{}))void 0!==t.origin.offset[n]&&e.push({at:`offset.${n}`,get:()=>t.origin.offset[n],set:e=>t.origin.offset[n]=e});return e}function yM(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:s}of gM(n))for(const i of Fx(s())?.terms??[])"part"===i?.from?.of&&Zx(t.document.model,i.from.part,i.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],s=new Map(t.map(t=>[t.body1.part,t])),i=new Map(Qw(t).map(t=>[t.motion.id,t.joint.id]));for(;n.length<t.length;){const o=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?s.get(t.body0.part):void 0,o=Xw(t).flatMap(t=>$x(t).map(t=>i.get(t.motion)));return(!n||e.has(n.id))&&o.every(n=>n===t.id||e.has(n))});o.length||Nx("JOINT_TREE","joints","the joints do not make a tree");for(const t of o)e.add(t.id),n.push(t)}return n}(e),s={...t.stateDefaults};!function(t,e){const n=nw;nw={asset:t,declared:ew(t)};try{e()}finally{nw=n}}(t,()=>{for(const e of t.document.model.nodes)"member@1"!==e.op||Hx(t.document.model,`${e.id}.repeat`)||(e.op="place@1");const i=t.document.model,o=new Set(i.nodes.filter(t=>e.some(e=>t.id.startsWith(`${e.body1.part}.on.`))).flatMap(t=>t.args));for(const e of[...n].reverse())mM(t,e);for(const e of n)uM(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const s=Hx(n,`${t.body1.part}.assembly`),i=o=>{for(const r of e.filter(t=>"part"in t.body0&&t.body0.part===o)){if(r.repeat){const e=Hx(n,`${r.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},s.args.push(e.outputs.collection);continue}const e=Hx(n,r.body1.part);e.op="member@1",s.args.push(e.outputs.placed),i(r.body1.part)}};i(t.body1.part)}}(t,e);for(const e of o){const n=i.nodes.find(t=>"place@1"===t.op&&e.startsWith(`${t.id}.`))?.id;n&&tw(i,n,e)&&iw(t,e,e)}for(const{motion:e}of Qw(n))e.mimic||void 0===s[Kw(e)]||(t.stateDefaults[Kw(e)]=s[Kw(e)])})}const bM=(t,e,n,s)=>{throw new Xv(t,e,n,s)},vM={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]};function _M(t,e,n){const{types:s,writers:i,model:o,assetFrame:r}=t;e&&"object"==typeof e&&!Array.isArray(e)||bM("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||bM("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||bM("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||bM("SCHEMA",n,"nonempty string required"),Object.hasOwn(s,t)||bM("TARGET_ABSENT",n,t),s[t]),c=a(e.placement),l=a(e.feature),h=i.get(e.placement),d=i.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=i.get(h.args[0]),e="repeat@1"===t?.op?i.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||bM("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=i.get(h.params.member),"member@1"!==p?.op&&bM("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),o.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&bM("TARGET_STATE",n,"binding target index must not change as animation state"),u={collection:h.args[0],index:h.args[1],member:h.params.member}}else"place@1"!==h?.op&&bM("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required","member@1"===h?.op?{reason:"surface-on-row",part:h.id,at:n}:void 0);"feature@1"!==d?.op&&bM("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===r&&"transform"===l.kind||bM("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&bM("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=s[d.args[0]].provider,m=d.params.name,g=s[d.args[0]].faces,y=g?.[m];y||bM("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&bM("SURFACE_UNSUPPORTED",n,"feature touches a curved side along a line; it is not a surface to hold things on");const b=["x","y","z"].map(t=>t===y[0]?y[1]:0);return{...e,geometryId:u?null:h.id,selection:u,provider:f,face:m,frame:l.from,normal:b}}function xM(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const wM="holder",MM=t=>"number"==typeof t&&Number.isFinite(t),SM=t=>MM(t)&&t>0,AM=t=>Number.isSafeInteger(t)&&t>0;function kM(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])SM(s[t])||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(xM("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||AM(t.stackLimit)||t.stackLimit===1/0||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||MM(t.rotation)||n.push(xM("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(xM("ARRAY_REQUIRED",`${e}.accepts`))}function EM(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[xM("TIERS_REQUIRED","tiers")];const s=e.anchors?new Set(e.anchors):null,i=new Set;return t.tiers.forEach((t,e)=>{const o=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(xM("OBJECT_REQUIRED",o));if(AM(t.tierNo)?i.has(t.tierNo)?n.push(xM("TIER_NUMBER_DUPLICATE",`${o}.tierNo`,{tierNo:t.tierNo})):i.add(t.tierNo):n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?s&&!s.has(t.anchorId)&&n.push(xM("ANCHOR_UNKNOWN",`${o}.anchorId`,{anchorId:t.anchorId})):n.push(xM("ANCHOR_REQUIRED",`${o}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(xM("MOUNT_INVALID",`${o}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])MM(t.position[e])||n.push(xM("FINITE_NUMBER_REQUIRED",`${o}.position.${e}`));else n.push(xM("OBJECT_REQUIRED",`${o}.position`));MM(t.rotation)||n.push(xM("FINITE_NUMBER_REQUIRED",`${o}.rotation`));const r=t.layout;switch(r?.pattern){case"SINGLE":kM(r.slot,`${o}.layout.slot`,n);break;case"ROW":AM(r.count)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.count`)),SM(r.pitch)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch`)),"X"!==r.axis&&"Z"!==r.axis&&n.push(xM("AXIS_INVALID",`${o}.layout.axis`)),kM(r.slot,`${o}.layout.slot`,n);break;case"GRID":AM(r.rows)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.rows`)),AM(r.cols)||n.push(xM("POSITIVE_INTEGER_REQUIRED",`${o}.layout.cols`)),SM(r.pitch?.x)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch.x`)),SM(r.pitch?.z)||n.push(xM("POSITIVE_NUMBER_REQUIRED",`${o}.layout.pitch.z`)),kM(r.slot,`${o}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(r.slots)){n.push(xM("ARRAY_REQUIRED",`${o}.layout.slots`));break}r.slots.length||n.push(xM("SLOTS_REQUIRED",`${o}.layout.slots`));const t=new Set;r.slots.forEach((e,s)=>{const i=`${o}.layout.slots[${s}]`;AM(e?.slotNo)?t.has(e.slotNo)?n.push(xM("SLOT_NUMBER_DUPLICATE",`${i}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(xM("POSITIVE_INTEGER_REQUIRED",`${i}.slotNo`)),MM(e?.offset?.x)&&MM(e?.offset?.z)||n.push(xM("FINITE_NUMBER_REQUIRED",`${i}.offset`)),kM(e,i,n)});break}default:n.push(xM("PATTERN_INVALID",`${o}.layout.pattern`))}}),n}function TM(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(xM("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}function CM(t){switch(t.pattern){case"SINGLE":return 1;case"ROW":return t.count;case"GRID":return t.rows*t.cols;case"CUSTOM":return t.slots.length}}function OM(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:CM(t)},(t,e)=>e+1)}function PM(t,e,n,s,i="ROW_MAJOR"){switch(i){case"ROW_MAJOR":return(n-1)*e+s;case"COL_MAJOR":return(s-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?s:e-s+1);case"SERPENTINE_COL":return(s-1)*t+(s%2==1?n:t-n+1)}}function IM(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const DM=(t,e)=>e&&0!==t?-t:t;function zM(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!AM(e.slot))return null;const i=s.layout;let o,r,a;switch(i.pattern){case"SINGLE":if(1!==e.slot)return null;o=i.slot,r={x:0,z:0};break;case"ROW":{if(e.slot>i.count)return null;const t=DM((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);o=i.slot,r="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>i.rows*i.cols)return null;const{r:t,c:n}=IM(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};o=i.slot,r={x:DM((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:DM((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;o=t,r={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,anchorId:s.anchorId,mount:s.mount,tierPosition:{...s.position},tierRotation:s.rotation,offset:r,allowed:{...o.allowed},accepts:o.accepts?[...o.accepts]:void 0,stackLimit:o.stackLimit??n.defaultStackLimit??1,rotation:o.rotation??0}}function RM(t){return`t${t.tier}_s${t.slot}`}function jM(t){const e="string"==typeof t?/^t(\d+)_s(\d+)$/.exec(t):null;return e?{tier:Number(e[1]),slot:Number(e[2])}:null}function*$M(t){for(const e of t?.tiers??[])for(const t of OM(e.layout))yield{tier:e.tierNo,slot:t}}function LM(t,e,n){if(!n)return{x:t,z:e};const s=n*Math.PI/180,i=Math.cos(s),o=Math.sin(s),r=t=>Math.round(1e9*t)/1e9;return{x:r(t*i+e*o),z:r(-t*o+e*i)}}function FM(t){const e=LM(t.offset.x,t.offset.z,t.tierRotation);return{position:{x:t.tierPosition.x+e.x,y:t.tierPosition.y,z:t.tierPosition.z+e.z},rotation:t.tierRotation+t.rotation}}const NM=.05,HM=t=>!!t&&SM(t.width)&&SM(t.depth)&&SM(t.height);function BM(t,e){const n=e*Math.PI/180,s=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),o=t=>Math.round(1e9*t)/1e9;return{width:o(t.width*s+t.depth*i),depth:o(t.width*i+t.depth*s)}}function GM(t,e,n=0,s=.05){if(!HM(t))return null;if(!MM(n)||!MM(s)||s<0||s>=1)return null;const i=BM(t,e.rotation),o=Math.min(1,Math.min(e.allowed.width/i.width,e.allowed.depth/i.depth)*(1-s)),r=t.height*o;return{position:{x:0,y:("HANG"===e.mount?-1:1)*(n+r/2),z:0},rotation:0,scale:o}}function UM(t,e,n=0,s=.05){const i=GM(t,e,n,s);if(!i)return null;const o=FM(e);return{position:{x:o.position.x,y:o.position.y+i.position.y,z:o.position.z},rotation:o.rotation,scale:i.scale}}function VM(t,e,n=.05){let s=0;return t.map(t=>{const i=t?UM(t,e,s,n):null;return i&&(s+=t.height*i.scale),i})}const WM=1e-6;function YM(t,e){const n=FM(t),s=t.allowed.width/2,i=t.allowed.depth/2,o=[[-s,-i],[s,-i],[s,i],[-s,i]].map(([t,e])=>{const s=LM(t,e,n.rotation);return{x:n.position.x+s.x,z:n.position.z+s.z}}),r=LM(1,0,n.rotation),a=LM(0,1,n.rotation),c="HANG"===t.mount?-1:1,l=[n.position.y,n.position.y+c*t.allowed.height],h=o.map(t=>t.x);return{tierIndex:e,tier:t.tier,slot:t.slotNo,corners:o,axes:[r,a],y0:Math.min(...l),y1:Math.max(...l),minX:Math.min(...h),maxX:Math.max(...h)}}function qM(t,e){for(const n of[...t.axes,...e.axes]){const s=t.corners.map(t=>t.x*n.x+t.z*n.z),i=e.corners.map(t=>t.x*n.x+t.z*n.z);if(Math.min(Math.max(...s),Math.max(...i))-Math.max(Math.min(...s),Math.min(...i))<=WM)return!1}return!0}function XM(t,e={}){const n=[],s=new Map;t.tiers.forEach((e,n)=>{const i=s.get(e.anchorId)??[];s.set(e.anchorId,i);for(const s of OM(e.layout))i.push(YM(zM(t,{tier:e.tierNo,slot:s}),n))});for(const[t,i]of s){const s=e.anchorFaces?.[t];if(s)for(const t of i)t.corners.some(t=>Math.abs(t.x)-s.width/2>WM||Math.abs(t.z)-s.depth/2>WM)&&n.push({code:"SLOT_OUTSIDE_ANCHOR",path:`tiers[${t.tierIndex}]`,params:{tier:t.tier,slot:t.slot}});else n.push({code:"ANCHOR_SPACE_UNKNOWN",path:"tiers",params:{anchorId:t}});const o=[...i].sort((t,e)=>t.minX-e.minX);for(let t=0;t<o.length;t++){const e=o[t];for(let s=t+1;s<o.length&&o[s].minX<e.maxX-WM;s++){const t=o[s];if(Math.min(e.y1,t.y1)-Math.max(e.y0,t.y0)<=WM)continue;if(!qM(e,t))continue;const[i,r]=e.tierIndex<t.tierIndex||e.tierIndex===t.tierIndex&&e.slot<t.slot?[e,t]:[t,e];n.push({code:"SLOT_OVERLAP",path:`tiers[${r.tierIndex}]`,params:{tier:r.tier,slot:r.slot,otherTier:i.tier,otherSlot:i.slot}})}}}return n}function KM(t,e,n=[],s={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const i=s.normalizeType??(t=>null==t?"":String(t)),o=[];let r=!1;if(t.accepts){const n=i(e.type);n?t.accepts.map(i).includes(n)||o.push("TYPE_NOT_ACCEPTED"):r=!0}if(n.length+1>t.stackLimit&&o.push("STACK_LIMIT_EXCEEDED"),HM(e.dims)){const s=BM(e.dims,t.rotation);if(s.width>t.allowed.width&&o.push("WIDTH_EXCEEDED"),s.depth>t.allowed.depth&&o.push("DEPTH_EXCEEDED"),n.every(t=>HM(t.dims))){const s=n.reduce((t,e)=>t+e.dims.height,e.dims.height);s>t.allowed.height&&o.push("HEIGHT_EXCEEDED")}else r=!0}else r=!0;return o.length?{verdict:"NG",reasons:r?[...o,"SPEC_UNKNOWN"]:o}:r?{verdict:"UNKNOWN",reasons:["SPEC_UNKNOWN"]}:{verdict:"OK",reasons:[]}}function JM(t){if(!t?.layout||!Array.isArray(t.anchors))return[];const e=new Map(t.anchors.map(t=>[t.id,t])),n=[];for(const s of $M(t.layout)){const i=zM(t.layout,s),o=i&&e.get(i.anchorId);if(!i||!o)continue;const r=RM(s);n.push({id:r,label:`${t.label} ${r}`,role:t.role,frame:o.frame,pose:{...o.pose},anchorId:o.id,...i.accepts?{accepts:[...i.accepts]}:{},capacity:i.stackLimit,tier:i.tier,slot:i.slotNo,...i.name?{name:i.name}:{},tierPosition:{...i.tierPosition},tierRotation:i.tierRotation,offset:{...i.offset},rotation:i.rotation,mount:i.mount,allowed:{...i.allowed}})}return n}const QM=(t,e,n)=>{throw new Xv(t,e,n)};function ZM(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||QM("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||QM("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||QM("SCHEMA",s,`unknown ${i}`)}const tS=(t,e)=>{"string"==typeof t&&t.trim()||QM("SCHEMA",e,"nonempty string required")};function eS(t,e){return function(t,e){const n=Px(t),s=structuredClone(e),i=n.outputTypes,o=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),r=new Map;ZM(s,["version","assetFrame","bindings"],["names","slotLayout","extensions"],"capabilities"),"r3-capability-3"!==s.version&&QM("VERSION","capabilities",s.version);if(tS(s.assetFrame,"assetFrame"),void 0!==s.names){Array.isArray(s.names)||QM("SCHEMA","names","array required");for(const t of s.names)Nv(t)||QM("CAPABILITY_NAME","names",`${String(t)} is not one of ${$v.join(", ")}, nor a consumer's <namespace>.<Name>`);new Set(s.names).size!==s.names.length&&QM("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(Hv))s.names.includes(t)&&!e.some(t=>s.names.includes(t))&&QM("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}if(void 0!==s.extensions){s.extensions&&"object"==typeof s.extensions&&!Array.isArray(s.extensions)||QM("SCHEMA","extensions","object required");for(const[t,e]of Object.entries(s.extensions))Fv(t)&&(s.names??[]).includes(t)||QM("CAPABILITY_NAME",`extensions.${t}`,`${t} is not a consumer capability this figure declares`),e&&"object"==typeof e&&!Array.isArray(e)||QM("SCHEMA",`extensions.${t}`,"object required")}Array.isArray(s.bindings)||QM("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(tS(t,e),Object.hasOwn(i,t)||QM("TARGET_ABSENT",e,t),i[t]),l=(t,e,n)=>{const i=c(t,e);("transform"!==i.kind||i.to!==s.assetFrame||void 0!==n&&i.from!==n)&&QM("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>_M({types:i,writers:o,model:t,assetFrame:s.assetFrame},e,n),d=new Map;for(const t of s.bindings){ZM(t,["id","label","role","frame","pose","capacity"],["accepts","region","contacts"],"binding");for(const e of["id","label","frame"])tS(t[e],e);if(a.has(t.id)&&QM("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||QM("ROLE",t.id,"explicit seat or grip required; slot is ambiguous"),"string"==typeof t.pose)l(t.pose,t.id,t.frame);else{const e=h(t.pose,t.id);e.frame!==t.frame&&QM("FRAME_TYPE",t.id,"binding frame must be the selected feature frame"),d.set(t.id,e)}if(void 0!==t.accepts&&(Array.isArray(t.accepts)&&t.accepts.length||QM("SCHEMA",t.id,"accepts names at least one type, or is left out for any"),t.accepts.forEach(e=>tS(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&QM("SCHEMA",t.id,"duplicate accepted type")),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&QM("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){ZM(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&QM("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||QM("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&QM("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||QM("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const s of t.contacts){const i=h(s,t.id),o=JSON.stringify([s.placement,s.feature]);e.has(o)&&QM("DUPLICATE_CONTACT",t.id,o),e.add(o),n.push(i)}r.set(t.id,n)}}const u=[];if(void 0!==s.slotLayout){const t=s.slotLayout;ZM(t,["label","role","anchors","layout"],[],"slotLayout"),tS(t.label,"slotLayout.label"),["seat","grip"].includes(t.role)||QM("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),Array.isArray(t.anchors)&&t.anchors.length||QM("SCHEMA","slotLayout.anchors","at least one anchor required");const e=new Map;t.anchors.forEach((t,n)=>{const s=`slotLayout.anchors[${n}]`;ZM(t,["id","frame","pose"],[],s),tS(t.id,`${s}.id`),tS(t.frame,`${s}.frame`),e.has(t.id)&&QM("SCHEMA",`${s}.id`,`duplicate anchor ${t.id}`),"string"==typeof t.pose&&QM("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a face of a part");const i=h(t.pose,s);i.frame!==t.frame&&QM("FRAME_TYPE",s,"anchor frame must be the selected feature frame");const o=i.normal[1];o||QM("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a horizontal face (its normal along Y)"),e.set(t.id,{surface:i,up:o})});const n=EM(t.layout,{anchors:e.keys()}),i=n.length?n:TM(t.layout);i.length&&QM("SLOT_LAYOUT",`slotLayout.layout.${i[0].path}`,i.map(t=>`${t.code} at ${t.path}`).join("; "));for(const n of JM(t)){void 0!==n.accepts&&(n.accepts.length||QM("SCHEMA",n.id,"accepts names at least one type, or is left out for any"),n.accepts.forEach(t=>tS(t,n.id)),new Set(n.accepts).size!==n.accepts.length&&QM("SCHEMA",n.id,"duplicate accepted type")),(!Number.isSafeInteger(n.capacity)||n.capacity<1)&&QM("CAPACITY",n.id,"positive integer capacity required"),a.has(n.id)&&QM("DUPLICATE_BINDING",n.id,"duplicate id"),a.add(n.id);const t=e.get(n.anchorId);d.set(n.id,t.surface),u.push({...n,up:t.up})}}const p=[...s.bindings,...u];function f(t,e){const n=t.pose.r,s=FM(e),i=[s.position.x,s.position.y*e.up,s.position.z],o=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*i[n],0)),r=s.rotation*Math.PI/180,a=Math.cos(r),c=Math.sin(r),l=[[a,0,c],[0,1,0],[-c,0,a]],h=n.map(t=>l[0].map((e,n)=>t.reduce((t,e,s)=>t+e*l[s][n],0)));return{...t,pose:{r:h,t:o}}}function m(t,e,n){const s=t=>function(t,e){const n=t[e.placement],s=t[e.feature],i=n.pose.r,o=i.map(t=>t.reduce((t,n,s)=>t+n*e.normal[s],0)),r=i.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*s.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,s=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);s||bM("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=s.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:i.map(t=>[...t]),t:r},normal:o,provenance:"verified-planar-surface"}}(e,t);let i=null;if(t.allowed)i={kind:"centered-box",dimensions:[t.allowed.width,t.allowed.height,t.allowed.depth]};else if(t.region){const n=t.region.dimensions.map(t=>e[t]);n.some(t=>!Number.isFinite(t)||t<=0)&&QM("REGION_DOMAIN",t.id,"positive region dimensions required"),i={kind:t.region.kind,dimensions:n}}let o={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];ZM(e,["type","occupied"],[],t.id+".request"),tS(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&QM("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const s=[];t.accepts&&!t.accepts.includes(e.type)&&s.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&s.push("CAPACITY_FULL"),o={status:s.length?"failed":"satisfied",reasons:s}}const a=(r.get(t.id)??[]).map(s),c=d.has(t.id)?s(d.get(t.id)):null,l=c&&t.allowed?f(c,t):c;return{id:t.id,label:t.label,role:t.role,frame:t.frame,pose:l?l.pose:e[t.pose],...l?{targetGeometryId:l.geometryId}:{},region:i,contacts:a,checks:{declaration:{status:"satisfied"},eligibility:o,spatial:{status:"unverified",reason:"NO_CONTACT_OR_FIT_SOLVER"},collision:{status:"unverified",reason:"NOT_CHECKED"},safety:{status:"unverified",reason:"NOT_CHECKED"}}}}function g(t,e,n={}){return ZM(n,[],[...a],"requests"),y(t.evaluate(e),n)}function y(t,e){const n=p.map(n=>m(n,t.values,e));return{geometry:t.geometry,bindings:n,values:t.values}}const b=t=>[t.placement,t.feature,...t.selection?[t.selection.collection,t.selection.index]:[]],v=new Map(p.map(t=>[t.id,[..."string"==typeof t.pose?[t.pose]:b(d.get(t.id)),...(r.get(t.id)??[]).flatMap(b),...t.region?.dimensions??[]]])),_={forbidden:Object.fromEntries(p.flatMap(t=>(t.region?.dimensions??[]).map(e=>[e,`region of ${t.id}`]))),external:[...new Set([...v.values()].flat())]};return{outputTypes:structuredClone(i),dependence:structuredClone(n.dependence),evaluate:(t,e={})=>g(n,t,e),evaluator(t={}){const e=n.evaluator({reads:_,changes:!!t.changes});return{evaluate:(t,n={})=>g(e,t,n),advance:(t,n={})=>{ZM(n,[],[...a],"requests");const s=Object.keys(n).length>0,i=e.advance(t,s?"REQUESTS":void 0);if("evaluation"===i.kind)return{...i,result:y(i.result,n)};if("changes"===i.kind){const t=p.filter(t=>s||i.structure||v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{...i,places:t}}const o=p.filter(t=>v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{kind:"poses",generation:i.generation,bodies:i.bodies,poses:i.poses,places:o}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const s=p.find(e=>e.id===t);return s||QM("TARGET_ABSENT",t,"no such place"),ZM(n,[],[...a],"requests"),m(s,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const nS=1048576;function sS(t,e,n){throw new Xv(t,"document",e,n)}function iS(t){return(new TextEncoder).encode(t).byteLength}function oS(t){const e=new Set;!function t(n,s){if(s>64&&sS("DOCUMENT_LIMIT","nesting exceeds 64",{reason:"nesting-too-deep",max:64,at:s}),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||sS("JSON_VALUE","nonfinite number"));"object"!=typeof n&&sS("JSON_VALUE","only JSON values are allowed"),e.has(n)&&sS("JSON_VALUE","cycle");const i=Array.isArray(n);i||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||sS("JSON_VALUE","plain objects required"),e.add(n);const o=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(o)){if(i&&"length"===e)continue;"string"!=typeof e&&sS("JSON_VALUE","symbols unsupported");const r=o[e];r.enumerable&&Object.hasOwn(r,"value")||sS("JSON_VALUE","hidden properties and accessors unsupported"),!i||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||sS("JSON_VALUE","extra array property"),t(r.value,s+1)}i&&Object.keys(n).length!==n.length&&sS("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function rS(t){if(oS(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new Xv("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new Xv("VERSION","document","unsupported document version");const e=iS(JSON.stringify(t));if(e>nS)throw new Xv("DOCUMENT_LIMIT","document","over 1 MiB",{reason:"document-too-large",max:nS,at:e});const n=t;if(!Array.isArray(n.model?.nodes)||n.model.nodes.length>Wv)throw new Xv("DOCUMENT_LIMIT","document","maximum 8192 nodes",{reason:"node-limit",max:Wv});return eS(n.model,n.capabilities)}function aS(t,e,n){const s=function(t,e){const n=t.find(t=>t.id===e);if(!n)return{code:"TARGET_ABSENT",message:`${String(e)} is not an input of the figure`};if("state"===n.role)return{code:"PUBLIC_INPUT",message:`${e} is a state input; a board sets it as a parameter`};if(/^(sizing\.)?size\.[xyz]$/.test(e))return{code:"PUBLIC_INPUT",message:`${e} is the figure's size; a board sets it from the instance's bounds`};const s=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return s(n.min)&&s(n.max)?null:{code:"PUBLIC_INPUT",message:`${e} has no range to hold a board's value to; give it one first`}}(t,e);if(s)throw new Xv(s.code,n,s.message)}const cS=/^[a-z][a-z0-9-]{0,31}\/[a-z][a-z0-9-]{0,63}$/,lS=(t,e,n)=>{throw new Xv(t,e,n)};function hS(t,e="extensions"){"string"==typeof t&&cS.test(t)||lS("EXTENSION_KEY",e,`${String(t)} is not {owner}/{name}: each starts with a-z and holds a-z, 0-9 and -, the owner up to 32 and the name up to 64`)}function dS(t,e){null==t&&lS("ASSET_SCHEMA",e,"a JSON value other than null"),oS(t);const n=iS(JSON.stringify(t));n>4096&&lS("EXTENSION_LIMIT",e,`${n} bytes; at most 4096`)}const uS=["floor","ceiling","center","wall"],pS=t=>"string"==typeof t&&/^#[0-9a-f]{6}$/i.test(t),fS=/^[a-zA-Z][a-zA-Z0-9_-]*$/,mS=/^[A-Za-z_][\w-]*$/,gS=(t,e,n,s)=>{throw new Xv(t,e,n,s)},yS=(t,e,n)=>gS("DATA_INTERFACE",t,e,n);function bS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||gS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||gS("ASSET_SCHEMA",s,`unknown ${i}`)}const vS=t=>"number"==typeof t&&Number.isFinite(t);function _S(t){if("string"!=typeof t||!t)return null;const e=[];for(const n of t.split(".")){const t=/^([A-Za-z_][\w-]*)(?:\[(\d+)\])?$/.exec(n);if(!t)return null;e.push({field:t[1]}),void 0!==t[2]&&e.push({index:Number(t[2])})}return e}function xS(t,e){let n,s={kind:"object",fields:t};for(const t of e)if("field"in t){if("object"!==s.kind)return{why:"absent"};const e=s.fields.find(e=>e.name===t.field);if(!e)return{why:"absent"};s=e,n=e}else{if("list"!==s.kind)return{why:"not-a-list"};s=s.item,n=void 0}return{node:s,...n?{field:n}:{}}}const wS=t=>"number"===t.kind||"boolean"===t.kind||"text"===t.kind;function MS(t,e,n){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",e,"object required");const s=n?["name","label","json"]:[],i=t.kind,o=(t,n)=>yS(`${e}.${t}`,n,{reason:"data-field-invalid",field:e,what:t});if("object"===i?bS(t,["kind","fields"],s,e):"list"===i?bS(t,["kind","item"],s,e):"number"===i?bS(t,["kind"],[...s,"unit","min","max","default"],e):"boolean"===i?bS(t,["kind"],[...s,"default"],e):"text"===i?bS(t,["kind"],[...s,"values","default"],e):gS("ASSET_SCHEMA",`${e}.kind`,`${String(i)} is not a data kind; object, list, number, boolean or text`),n&&("string"==typeof t.name&&mS.test(t.name)||o("name",`${String(t.name)} is not a field name: a letter or _, then letters, digits, _ and -`),void 0===t.label||"string"==typeof t.label&&t.label.trim()||o("label","a name shown to a person, or none"),void 0!==t.json&&(!0!==t.json||"object"!==i&&"list"!==i)&&o("json","only an object or a list may come as JSON text")),"object"===i)Array.isArray(t.fields)||gS("ASSET_SCHEMA",`${e}.fields`,"a list of fields"),SS(t.fields,`${e}.fields`);else if("list"===i)MS(t.item,`${e}.item`,!1);else if("number"===i){void 0===t.unit||function(t){return"string"==typeof t&&Object.hasOwn(W_,t)}(t.unit)||o("unit",`${String(t.unit)} is not a unit`);for(const e of["min","max","default"])void 0===t[e]||vS(t[e])||o(e,"a finite number");void 0===t.min||void 0===t.max||t.min<=t.max||o("min","a range from a number to one no smaller"),void 0!==t.default&&(void 0!==t.min&&t.default<t.min||void 0!==t.max&&t.default>t.max)&&o("default","the default lies in the range")}else"boolean"===i?void 0!==t.default&&"boolean"!=typeof t.default&&o("default","true or false"):(void 0!==t.values&&(Array.isArray(t.values)&&t.values.length&&!t.values.some(t=>"string"!=typeof t||!t)||o("values","one or more nonempty strings"),new Set(t.values).size!==t.values.length&&o("values","each value once")),void 0!==t.default&&("string"!=typeof t.default&&o("default","a string"),t.values&&!t.values.includes(t.default)&&o("default","the default is one of the values")))}function SS(t,e){const n=new Set;t.forEach((t,s)=>{MS(t,`${e}[${s}]`,!0),n.has(t.name)&&yS(`${e}[${s}].name`,`${t.name} is a field twice`,{reason:"data-field-duplicate",field:`${e}[${s}]`,name:t.name}),n.add(t.name)})}const AS=t=>"state"===t.kind?t.input:"palette"===t.kind?t.token:"pose"===t.kind?t.axis:"items"===t.kind?t.slot??"":t.group,kS=[["clip","motion-clip"],["speed","motion-speed"],["paused","motion-paused"]];function ES(t){const e=t.split("~");if(2!==e.length)return null;const[n,s]=e,i=""===n?-1/0:Number(n),o=""===s?1/0:Number(s);return(""===n||vS(i))&&(""===s||vS(o))&&i<o?[i,o]:null}const TS=(t,e)=>(n,s,i={})=>yS(e,s,{reason:"data-rule-domain",binding:t,why:n,...i});const CS=/^[a-z0-9][a-z0-9-]*$/;function OS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",s,"object required");const i="table"===t.rule;i?bS(t,["id","accessor","rule","lookup","targets","table"],["label","legend"],s):bS(t,["id","accessor","behavior","rule"],["label","param"],s),"string"==typeof t.id&&fS.test(t.id)||yS(`${s}.id`,`${String(t.id)} is not an id: a letter, then letters, digits, - and _`,{reason:"data-id-invalid",list:"bindings",id:String(t.id)}),void 0===t.label||"string"==typeof t.label&&t.label.trim()||gS("ASSET_SCHEMA",`${s}.label`,"a name shown to a person, or none");const o=(e,n)=>yS(`${s}.accessor`,`${e}: ${n}`,{reason:"data-accessor-invalid",binding:t.id,accessor:e,why:n}),r=()=>{const n=_S(t.accessor);n||o(String(t.accessor),"syntax");const s=xS(e,n);return"why"in s?o(t.accessor,s.why):s};if(i){const{node:e}=r();return"list"===e.kind?o(t.accessor,"list-needs-index"):wS(e)||o(t.accessor,"not-a-value"),function(t,e,n,s){const i=TS(t.id,s),o=t.targets;o&&"object"==typeof o&&!Array.isArray(o)||gS("ASSET_SCHEMA",`${s}.targets`,"object required"),bS(o,[],["parts","inputs","group"],`${s}.targets`);for(const t of["parts","inputs"])void 0===o[t]||Array.isArray(o[t])&&!o[t].some(t=>"string"!=typeof t||!t)||gS("ASSET_SCHEMA",`${s}.targets.${t}`,"a list of ids");void 0===o.group||"string"==typeof o.group&&o.group||gS("ASSET_SCHEMA",`${s}.targets.group`,"a nonempty string");const r=(e,n,i)=>yS(`${s}.targets`,n,{reason:"data-table-target",binding:t.id,what:e,...void 0!==i?{id:i}:{}}),a=o.parts??[],c=o.inputs??[];if(a.length||c.length||void 0!==o.group||r("none","a table shows on a part, a state input, a motion group, or more"),a.forEach((t,e)=>{n.parts.has(t)||r("part",`${t} is not a part of this figure`,t),a.indexOf(t)!==e&&r("part",`${t} is named twice`,t)}),c.forEach((t,e)=>{n.states.has(t)||r("input",`${t} is not a state input of this figure`,t),c.indexOf(t)!==e&&r("input",`${t} is named twice`,t)}),void 0===o.group||n.groups.has(o.group)||r("group",`${o.group} is not a motion group of this figure`,o.group),"code"!==t.lookup&&"ranges"!==t.lookup&&gS("ASSET_SCHEMA",`${s}.lookup`,"code or ranges"),!wS(e))return i("kind",`${t.accessor} is ${"list"===e.kind?"a list":"an object"}; a table reads one value`);if("code"===t.lookup&&"number"===e.kind)return i("kind",`${t.accessor} is a number; a table reads it by ranges`);if("ranges"===t.lookup&&"number"!==e.kind)return i("kind",`a range table reads a number; ${t.accessor} is ${"text"===e.kind?"a text":"true or false"}`);const l=t.table;l&&"object"==typeof l&&!Array.isArray(l)||gS("ASSET_SCHEMA",`${s}.table`,"an object of looks");const h=Object.keys(l).filter(t=>"default"!==t);if("code"===t.lookup){const n=function(t){return"boolean"===t.kind?[!1,!0]:"text"===t.kind&&t.values?t.values:null}(e);if(n){for(const e of h)n.some(t=>String(t)===e)||i("cases",`${e} is not a value of ${t.accessor}`,{value:e});n.every(t=>Object.hasOwn(l,String(t)))||Object.hasOwn(l,"default")||i("default",`not every value of ${t.accessor} has a look; give a default`)}}else{const n=[];for(const t of h){const e=ES(t);if(!e)return i("cases",`${t} is not an interval: from~to, either end may be left out`,{value:t});const s=n.find(([t,n])=>e[0]<n&&t<e[1]);s&&i("overlap",`${s[2]} and ${t} overlap; a value has one look`,{value:t}),n.push([e[0],e[1],t])}const s=e;Object.hasOwn(l,"default")||function(t,e,n){let s=e;for(const[e,i]of[...t].sort((t,e)=>t[0]-e[0])){if(e>s)return!1;if(i>s&&(s=i),s===1/0||s>n)return!0}return!1}(n.map(([t,e])=>[t,e]),s.min??-1/0,s.max??1/0)||i("default",`the intervals leave values of ${t.accessor} without a look; give a default`)}for(const[e,i]of Object.entries(l)){const r=`${s}.table.${e}`;i&&"object"==typeof i&&!Array.isArray(i)||gS("ASSET_SCHEMA",r,"object required"),bS(i,[],["color","effect","values","clip","speed","paused"],r);const l=(n,s,i={})=>yS(`${r}.${"column"===n?i.id:n}`,s,{reason:"data-table-entry",binding:t.id,key:e,what:n,...i}),h=(e,n)=>{void 0===i[e]||n||l("column",`${e} goes to no target of ${t.id}`,{id:e})};h("color",a.length>0),h("effect",a.length>0),h("values",c.length>0);for(const[t]of kS)h(t,void 0!==o.group);if(void 0===i.color||pS(i.color)||l("color","a colour is #RRGGBB",{value:i.color}),void 0!==i.effect){const t=i.effect;t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",`${r}.effect`,"object required"),bS(t,["kind"],["hz"],`${r}.effect`),"blink"!==t.kind&&"glow"!==t.kind&&l("effect","an effect is blink or glow",{value:t.kind}),void 0===t.hz||vS(t.hz)&&t.hz>0||l("effect","hz is a positive number",{value:t.hz})}if(void 0!==i.values){i.values&&"object"==typeof i.values&&!Array.isArray(i.values)||gS("ASSET_SCHEMA",`${r}.values`,"an object of values");for(const[e,s]of Object.entries(i.values)){c.includes(e)||l("values",`${e} is not a target of ${t.id}`,{id:e});const i=n.states.get(e);(!vS(s)||s<i.min||s>i.max)&&l("values",`${String(s)} is outside ${e}, ${i.min} to ${i.max}`,{id:e,value:s})}}void 0===i.clip||"string"==typeof i.clip&&n.groups.get(o.group).includes(i.clip)||l("clip",`${String(i.clip)} is not a clip of ${o.group}`,{value:i.clip}),void 0===i.speed||vS(i.speed)&&i.speed>=0&&i.speed<=3||l("speed","a motion speed is 0 to 3",{value:i.speed}),void 0!==i.paused&&"boolean"!=typeof i.paused&&l("paused","a pause is true or false",{value:i.paused})}void 0!==t.legend&&(t.legend&&"object"==typeof t.legend&&!Array.isArray(t.legend)||gS("ASSET_SCHEMA",`${s}.legend`,"object required"),bS(t.legend,["role"],[],`${s}.legend`),"string"==typeof t.legend.role&&CS.test(t.legend.role)||yS(`${s}.legend.role`,`${String(t.legend.role)} is not a role: lower case letters, digits and -`,{reason:"data-legend-invalid",binding:t.id,role:String(t.legend.role)}))}(t,e,n,s),t}const a=function(t,e){t&&"object"==typeof t&&!Array.isArray(t)||gS("ASSET_SCHEMA",e,"object required");const n=t.kind;"state"===n?bS(t,["kind","input","sourceMode"],[],e):"palette"===n?bS(t,["kind","token"],[],e):"motion-clip"===n||"motion-speed"===n||"motion-paused"===n?bS(t,["kind","group"],[],e):"pose"===n?bS(t,["kind","axis"],["seconds"],e):"items"===n?bS(t,["kind"],["slot","id","type","place","stack","status"],e):gS("ASSET_SCHEMA",`${e}.kind`,`${String(n)} is not a behavior; state, palette, motion-clip, motion-speed, motion-paused, pose or items`),"state"===n&&"observed"!==t.sourceMode&&"commanded"!==t.sourceMode&&gS("ASSET_SCHEMA",`${e}.sourceMode`,"observed or commanded"),"pose"!==n||["x","y","z","heading"].includes(t.axis)||gS("ASSET_SCHEMA",`${e}.axis`,"x, y, z or heading"),"pose"!==n||void 0===t.seconds||vS(t.seconds)&&t.seconds>=0||gS("ASSET_SCHEMA",`${e}.seconds`,"seconds from 0");for(const n of["input","token","group","slot","id","type","place","stack","status"])!Object.hasOwn(t,n)||"string"==typeof t[n]&&t[n]||gS("ASSET_SCHEMA",`${e}.${n}`,"a nonempty string");return t}(t.behavior,`${s}.behavior`);void 0===t.param||t.param&&"object"==typeof t.param&&!Array.isArray(t.param)||gS("ASSET_SCHEMA",`${s}.param`,"an object of results");const c=e=>yS(`${s}.behavior`,`${e} is not a ${a.kind} of this figure`,{reason:"data-behavior-absent",binding:t.id,behavior:a.kind,id:e});"state"!==a.kind||n.states.has(a.input)||c(a.input),"palette"!==a.kind||Object.hasOwn(n.palette,a.token)||c(a.token),"motion-clip"!==a.kind&&"motion-speed"!==a.kind&&"motion-paused"!==a.kind||n.groups.has(a.group)||c(a.group);const{node:l}=r();if("items"===a.kind)if("list"===l.kind){const e=l.item;a.id||yS(`${s}.behavior.id`,"items from a list say which field of an element is its id",{reason:"data-accessor-invalid",binding:t.id,accessor:t.accessor,why:"item-id-required"});for(const n of["id","type","place","stack","status"]){const s=a[n];if(void 0===s)continue;const i=_S(s);i||o(s,"syntax");const r=xS("object"===e.kind?e.fields:[],i);"why"in r?o(`${t.accessor}[].${s}`,r.why):wS(r.node)||o(`${t.accessor}[].${s}`,"not-a-value")}}else wS(l)?(a.id||a.type||a.place||a.stack||a.status)&&yS(`${s}.behavior`,"one value is the id itself; element fields are for a list",{reason:"data-accessor-invalid",binding:t.id,accessor:t.accessor,why:"not-a-list"}):o(t.accessor,"not-a-value");else"list"===l.kind?o(t.accessor,"list-needs-index"):wS(l)||o(t.accessor,"not-a-value");return function(t,e,n,s){const i=TS(t.id,s),o=t.behavior,r=t.param;if("items"===o.kind)return void("value"===t.rule&&void 0===r||i("kind","items are read as they are: rule value, no param"));if(!wS(e))return i("kind",`${t.accessor} is ${"list"===e.kind?"a list":"an object"}; this behavior reads one value`);if("value"!==t.rule&&"scale"!==t.rule)return i("kind",`${String(t.rule)} is not a rule; value, scale or table`);let a=1,c=0;if("scale"===t.rule){if(!r||!vS(r.scale)||!vS(r.offset)||Object.keys(r).some(t=>"scale"!==t&&"offset"!==t))return i("cases","a scale is { scale, offset }, two finite numbers");if("number"!==e.kind)return i("kind",`a scale reads a number; ${t.accessor} is ${e.kind}`);a=r.scale,c=r.offset}else if(void 0!==r)return i("cases","value takes no param");if("motion-clip"===o.kind||"palette"===o.kind){if("scale"===t.rule||"text"!==e.kind||!e.values)return i("kind",("palette"===o.kind?"a colour":"a clip")+" is read as it is only from a text of fixed values; otherwise by a table");for(const t of e.values)"palette"!==o.kind||pS(t)||i("output","a colour is #RRGGBB",{value:t}),"motion-clip"!==o.kind||n.groups.get(o.group).includes(t)||i("output",`${t} is not a clip of ${o.group}`,{value:t});return}if("motion-paused"===o.kind)return void("scale"!==t.rule&&"boolean"===e.kind||i("kind","a pause is read as it is only from true or false; otherwise by a table"));if("number"!==e.kind)return i("kind",`${t.accessor} is ${"text"===e.kind?"a text":"true or false"}; this behavior reads a number, or a value by a table`);if("pose"===o.kind){const n="heading"===o.axis?"deg":"mm";return void("value"===t.rule&&e.unit!==n&&i("unit",`${t.accessor} is in ${e.unit??"no unit"}; a ${"heading"===o.axis?"heading":"position"} is in ${n}; say the unit, or scale it`,{from:e.unit??"",to:n}))}if("motion-speed"===o.kind)"value"===t.rule&&void 0!==e.unit&&"ratio"!==e.unit&&i("unit",`a motion speed is a ratio; ${t.accessor} is in ${e.unit}`,{from:e.unit,to:"ratio"});else{const s=n.states.get(o.input);"value"===t.rule&&e.unit!==s.unit&&i("unit",`${t.accessor} is in ${e.unit??"no unit"} and ${o.input} in ${s.unit}; say how one becomes the other`,{from:e.unit??"",to:s.unit})}const[l,h]="motion-speed"===o.kind?[0,3]:[n.states.get(o.input).min,n.states.get(o.input).max];if(void 0===e.min||void 0===e.max)return i("range",`${t.accessor} has no range; give it one inside ${l} to ${h}`,{within:[l,h]});const d=[a*e.min+c,a*e.max+c].sort((t,e)=>t-e);(d[0]<l||d[1]>h)&&i("range",`${t.accessor} gives ${d[0]} to ${d[1]}; ${AS(o)} takes ${l} to ${h}`,{min:d[0],max:d[1],within:[l,h]})}(t,l,n,s),t}function PS(t){const e=t.dataInterface;if(void 0===e)return;bS(e,["version","schema","bindings"],[],"dataInterface"),"figure-data-interface-2"!==e.version&&gS("VERSION","dataInterface.version",String(e.version)),Array.isArray(e.schema)||gS("ASSET_SCHEMA","dataInterface.schema","a list of fields"),Array.isArray(e.bindings)||gS("ASSET_SCHEMA","dataInterface.bindings","a list of bindings"),SS(e.schema,"dataInterface.schema");const n=(t=>({states:new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),palette:t.palette,groups:new Map((t.motionGroups??[]).map(t=>[t.id,t.clips])),parts:new Set(t.appearance.map(t=>t.target))}))(t),s=new Set,i=new Map,o=(t,e,n,s,o)=>{const r=i.get(t);void 0!==r&&yS(o,`${r} and ${s} both write ${t}; one writer each`,{reason:"data-behavior-duplicate",bindings:[r,s],behavior:e,id:n}),i.set(t,s)};e.bindings.forEach((t,i)=>{const r=`dataInterface.bindings[${i}]`,a=OS(t,e.schema,n,r);if(s.has(a.id)&&yS(`${r}.id`,`${a.id} is declared twice`,{reason:"data-id-duplicate",list:"bindings",id:a.id}),s.add(a.id),"table"===a.rule){for(const t of function(t){const e=(t.targets.inputs??[]).map(t=>({key:`state ${t}`,behavior:"state",id:t})),n=t.targets.group;if(void 0!==n){const s=Object.values(t.table);for(const[t,i]of kS)s.some(e=>void 0!==e[t])&&e.push({key:`${i} ${n}`,behavior:i,id:n})}return e}(a))o(t.key,t.behavior,t.id,a.id,`${r}.targets`);return}const c=(t=>"state"===t.kind?`state ${t.input}`:"palette"===t.kind?`palette ${t.token}`:"pose"===t.kind?`pose ${t.axis}`:"items"===t.kind?null:`${t.kind} ${t.group}`)(a.behavior);null!==c&&o(c,a.behavior.kind,AS(a.behavior),a.id,`${r}.behavior`)})}const IS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function DS(t){const e=t.motionGroups;if(void 0===e)return;Array.isArray(e)||IS("ASSET_SCHEMA","motionGroups","a list of motion groups");const n=new Map;for(const e of t.drivers??[])n.set(e.clip,[...n.get(e.clip)??[],e]);const s=new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),i=new Set,o=new Map;e.forEach((t,e)=>{const r=`motionGroups[${e}]`;!function(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||IS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||IS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||IS("ASSET_SCHEMA",s,`unknown ${i}`)}(t,["id","label","clips","defaultClip","transitionSeconds"],[],r),"string"==typeof t.id&&fS.test(t.id)||IS("MOTION_GROUP",`${r}.id`,`${String(t.id)} is not an id: a letter, then letters, digits, - and _`,{reason:"data-id-invalid",list:"motion-groups",id:String(t.id)}),i.has(t.id)&&IS("MOTION_GROUP",`${r}.id`,`${t.id} is declared twice`,{reason:"data-id-duplicate",list:"motion-groups",id:t.id}),i.add(t.id),"string"==typeof t.label&&t.label.trim()||IS("MOTION_GROUP",`${r}.label`,"a name shown to a person"),Array.isArray(t.clips)&&t.clips.length||IS("MOTION_GROUP",`${r}.clips`,"one or more clips"),new Set(t.clips).size!==t.clips.length&&IS("MOTION_GROUP",`${r}.clips`,"each clip once");for(const e of t.clips){"string"==typeof e&&n.has(e)||IS("MOTION_GROUP",`${r}.clips`,`${String(e)} is not a clip of this figure`,{reason:"motion-clip-absent",group:t.id,clip:String(e)});const i=o.get(e);void 0!==i&&IS("MOTION_GROUP",`${r}.clips`,`${e} is already in ${i}; a clip is in one group`,{reason:"motion-clip-shared",clip:e,groups:[i,t.id]}),o.set(e,t.id);for(const t of n.get(e)){const n=s.get(t.state);if(t.accumulates)continue;const i=t.keys.find(t=>t.value<n.min||t.value>n.max);i&&IS("MOTION_GROUP",`drivers.${t.id}`,`${e} keys ${t.state} at ${i.value}, outside ${n.min} to ${n.max}`,{reason:"value-outside-range",input:t.state,value:i.value,min:n.min,max:n.max})}}t.clips.includes(t.defaultClip)||IS("MOTION_GROUP",`${r}.defaultClip`,`${String(t.defaultClip)} is not a clip of ${t.id}`,{reason:"motion-clip-absent",group:t.id,clip:String(t.defaultClip)}),"number"==typeof t.transitionSeconds&&Number.isFinite(t.transitionSeconds)&&t.transitionSeconds>=0||IS("MOTION_GROUP",`${r}.transitionSeconds`,"seconds, zero or more")})}function zS(t){const e=new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t])),n=new Map;for(const e of structuredClone(t.drivers??[])){const t=n.get(e.clip)??{duration:e.time.duration,drivers:[]};t.drivers.push(e),n.set(e.clip,t)}const s=new Map;for(const n of t.drivers??[]){const i=e.get(n.state).unit,o=s.get(n.state);s.set(n.state,{unit:i,phase:(o?.phase??!1)||n.accumulates,default:t.stateDefaults[n.state]})}const i=new Map,o=new Set;for(const e of structuredClone(t.motionGroups??[])){const t=new Set(e.clips.flatMap(t=>n.get(t).drivers.map(t=>t.state)));e.clips.forEach(t=>o.add(t)),i.set(e.id,Object.freeze({group:Object.freeze(e),states:Object.freeze([...t].sort())}))}return Object.freeze({groups:i,independentClips:Object.freeze([...n.keys()].filter(t=>!o.has(t))),clips:n,states:s})}function RS(t,e,n){const s=(e,n)=>{if(null!=e){("object"!=typeof e||Array.isArray(e))&&IS("MOTION_SETTING",n,"a setting per group");for(const s of Object.keys(e)){const i=t.groups.get(s),o=e[s];i||IS("MOTION_SETTING",`${n}.${s}`,`${s} is not a motion group of this figure`,{reason:"motion-setting",why:"group-unknown",group:s}),o&&"object"==typeof o||IS("MOTION_SETTING",`${n}.${s}`,"a setting",{reason:"motion-setting",why:"group-unknown",group:s}),void 0===o.clip||i.group.clips.includes(o.clip)||IS("MOTION_SETTING",`${n}.${s}.clip`,`${String(o.clip)} is not a clip of ${s}`,{reason:"motion-setting",why:"clip-not-in-group",group:s,clip:String(o.clip)}),void 0===o.speed||"number"==typeof o.speed&&o.speed>=0&&o.speed<=3||IS("MOTION_SETTING",`${n}.${s}.speed`,"a speed is 0 to 3",{reason:"motion-setting",why:"speed-out-of-range",group:s,speed:Number(o.speed)}),void 0!==o.paused&&"boolean"!=typeof o.paused&&IS("MOTION_SETTING",`${n}.${s}.paused`,"true or false")}}};s(e,"manual"),s(n,"data");const i=Object.create(null);for(const[s,{group:o}]of t.groups){const t=e&&Object.hasOwn(e,s)?e[s]:{},r=n&&Object.hasOwn(n,s)?n[s]:{},a=void 0!==r.clip?[r.clip,"data"]:void 0!==t.clip?[t.clip,"manual"]:[o.defaultClip,"default"],c=void 0!==r.speed?[r.speed,"data"]:void 0!==t.speed?[t.speed,"manual"]:[0,"default"];i[s]={clip:a[0],speed:c[0],paused:r.paused??t.paused??!1,sources:{clip:a[1],speed:c[1]}}}return i}const jS=t=>"deg"===t||"rad"===t?t:"other";function $S(t,e,n={}){for(const n of t.groups.keys())e&&Object.hasOwn(e,n)||IS("MOTION_SELECTION_REQUIRED",`selection.${n}`,`which clip of ${n} plays is not said`,{reason:"motion-setting",why:"group-selection-required",group:n});for(const n of Object.keys(e)){const s=t.groups.get(n);s||IS("MOTION_SETTING",`selection.${n}`,`${n} is not a motion group of this figure`,{reason:"motion-setting",why:"group-unknown",group:n}),s.group.clips.includes(e[n])||IS("MOTION_SETTING",`selection.${n}`,`${String(e[n])} is not a clip of ${n}`,{reason:"motion-setting",why:"clip-not-in-group",group:n,clip:String(e[n])})}const s=Object.create(null),i=e=>{const i=Object.hasOwn(n,e)?n[e]:0;for(const n of t.clips.get(e).drivers)s[n.state]=US(n,i,jS(t.states.get(n.state).unit))};for(const e of t.independentClips)i(e);for(const[n,o]of t.groups){for(const e of o.states)s[e]=t.states.get(e).default;i(e[n])}return s}function LS(t,e,n,s){Number.isFinite(s)&&s>=0&&s<=1||IS("MOTION_SETTING","alpha","a fraction from 0 to 1");const i=Object.create(null);for(const o of Object.keys(n)){const r=n[o],a=Object.hasOwn(e,o)?e[o]:void 0;if(void 0===a){i[o]=r;continue}const c=t.states.get(o),l=c?jS(c.unit):"other";if(c?.phase&&"other"!==l){const t="deg"===l?180:Math.PI;let e=GS(r-a,l);e===-t&&(e=t),i[o]=GS(a+s*e,l)}else i[o]=a+s*(r-a)}return i}const FS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function NS(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function HS(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||FS("DRIVER","drivers","array required");const n=NS(t),s=new Set,i=new Map,o=function(t){const e=new Map,n=t.motionGroups;if(!Array.isArray(n))return e;for(const t of n)if(t&&"string"==typeof t.id&&Array.isArray(t.clips))for(const n of t.clips)"string"!=typeof n||e.has(n)||e.set(n,t.id);return e}(t),r=new Map;for(const t of e){const e=`drivers.${String(t?.id??"?")}`,a=t=>t&&"object"==typeof t?Object.keys(t).sort():null;JSON.stringify(a(t))!==JSON.stringify(["accumulates","clip","id","interpolation","keys","loop","state","time"])&&FS("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||FS("DRIVER",e,"id required"),s.has(t.id)&&FS("DRIVER",e,"duplicate driver id"),s.add(t.id),"string"==typeof t.clip&&t.clip.trim()||FS("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||FS("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`);const c=i.get(t.state)??[];c.includes(t.clip)&&FS("DRIVER_STATE",e,`clip ${t.clip} writes ${t.state} twice; one track per state in a clip`,{reason:"driver-writers",state:t.state,clips:[t.clip]});const l=o.get(t.clip);c.length&&(void 0===l||c.some(t=>o.get(t)!==l))&&FS("DRIVER_STATE",e,`${[...c,t.clip].join(", ")} all write ${t.state}; one writer per state, unless the clips are one motion group`,{reason:"driver-writers",state:t.state,clips:[...c,t.clip]}),i.set(t.state,[...c,t.clip]),JSON.stringify(a(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||FS("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||FS("DRIVER_TIME",e,"positive duration in seconds required");const h=r.get(t.clip);void 0===h?r.set(t.clip,t.time.duration):h!==t.time.duration&&FS("DRIVER_TIME",e,`clip "${t.clip}" already runs for ${h} s; one clip is one clock, so every driver in it shares a duration`),(!Array.isArray(t.keys)||t.keys.length<2)&&FS("DRIVER_KEYS",e,"at least two keys required");let d=-1/0;for(const n of t.keys)JSON.stringify(a(n))!==JSON.stringify(["at","value"])&&FS("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||FS("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>d||FS("DRIVER_KEYS",e,"key at values must strictly increase"),d=n.at,Number.isFinite(n.value)||FS("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&FS("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||FS("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||FS("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&FS("DRIVER",e,"accumulates must be a boolean");const u=n.get(t.state);t.accumulates&&"deg"!==u&&"rad"!==u&&FS("DRIVER_STATE",e,`an accumulating driver writes an angle; ${t.state} is in ${u}`)}}function BS(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const s=n[n.length-1];if(e>=s.at)return s.value;let i=0;for(;i<n.length-2&&n[i+1].at<=e;)i++;const o=n[i],r=n[i+1];if("step"===t.interpolation)return o.value;const a=r.at-o.at;return o.value+(e-o.at)/a*(r.value-o.value)}function GS(t,e){const n="deg"===e?360:2*Math.PI,s=n/2,i=((t+s)%n+n)%n-s;return i===s?-s:i}function US(t,e,n="other"){Number.isFinite(e)||FS("DRIVER_TIME",t.id,"finite time required");const s=Math.max(0,e),i=t.time.duration,o=t.keys[0].value,r=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=BS(t,Math.min(s/i,1));else{const e=Math.floor(s/i);a=BS(t,(s-e*i)/i),t.accumulates&&(a+=e*(r.value-o))}return t.accumulates?"deg"===n||"rad"===n?GS(a,n):FS("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}function VS(t,e,n,s){Number.isFinite(t)&&Number.isFinite(e)||FS("STATE_INPUT","advanceStateValue","finite values required"),(!Number.isFinite(s)||s<0)&&FS("STATE_INPUT","advanceStateValue","a non-negative step in seconds required");const i=n.sweep,o=n.max-n.min;if(!(i&&o>0))return e;const r=o/i*s;if(!(r>0))return t;const a=e-t;return Math.abs(a)<=r?e:t+Math.sign(a)*r}const WS=(t,e,n,s)=>{throw new Xv(t,e,n,s)};function YS(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||WS("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||WS("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||WS("ASSET_SCHEMA",s,`unknown ${i}`)}function qS(t){return function(t,e,n=!1){const s=t&&"object"==typeof t?t:void 0,i=s?KS.get(s):void 0;if(i&&i.kernel===Ix&&(i.joints||!e))return i.compiled;oS(t);const o=t,r=iS(JSON.stringify(o));r>nS&&WS("DOCUMENT_LIMIT","asset","over 1 MiB",{reason:"document-too-large",max:nS,at:r});YS(o,["version","name","document","designInputs","stateDefaults","palette","appearance"],["mountingFace","item","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs","extensions","dataInterface","motionGroups"],"asset"),void 0!==o.extensions&&function(t){t&&"object"==typeof t&&!Array.isArray(t)||lS("ASSET_SCHEMA","extensions","an object of {owner}/{name} keys");const e=Object.keys(t);e.length||lS("ASSET_SCHEMA","extensions","no keys; leave the field out"),e.length>16&&lS("EXTENSION_LIMIT","extensions",`${e.length} keys; at most 16`);for(const n of e){const e=`extensions.${n}`;hS(n,e),dS(t[n],e)}}(o.extensions);void 0===o.placement||uS.includes(o.placement)||WS("ASSET_SCHEMA","placement",`one of ${uS.join(", ")} required`);void 0!==o.item&&!0!==o.item&&WS("ASSET_SCHEMA","item","true when the figure is an item; left out when it is not");"figure-asset-1"!==o.version&&WS("VERSION","asset",o.version);"string"==typeof o.name&&o.name.trim()||WS("ASSET_SCHEMA","name","nonempty name required");const a=structuredClone(o),c=rS(a.document),l=a.document.model,h=l.inputs.filter(t=>"state"!==t.role).map(t=>t.id),d=l.inputs.filter(t=>"state"===t.role).map(t=>t.id);YS(a.designInputs,h,[],"designInputs"),void 0===a.detailLevel||(t=>Gv.includes(t))(a.detailLevel)||WS("ASSET_SCHEMA","detailLevel",`${String(a.detailLevel)} is not a detail level; ${Gv.join(", ")}`);if(void 0!==a.sizing){"uniform"!==a.sizing&&WS("ASSET_SCHEMA","sizing",`${String(a.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])l.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||WS("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(YS(a.stateDefaults,d,[],"stateDefaults"),void 0!==a.publicInputs){Array.isArray(a.publicInputs)||WS("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,n]of a.publicInputs.entries()){const s=`publicInputs[${e}]`;YS(n,["input","label"],["hint"],s),aS(l.inputs,n.input,`${s}.input`),"string"==typeof n.label&&n.label.trim()||WS("ASSET_SCHEMA",`${s}.label`,"a name shown on the board"),void 0!==n.hint&&"string"!=typeof n.hint&&WS("ASSET_SCHEMA",`${s}.hint`,"one line"),t.has(n.input)&&WS("PUBLIC_INPUT",`${s}.input`,`${n.input} is listed twice`),t.add(n.input)}}a.palette&&"object"==typeof a.palette&&!Array.isArray(a.palette)||WS("ASSET_SCHEMA","palette","token to hex color map required");for(const[t,e]of Object.entries(a.palette))t.trim()&&pS(e)||WS("PALETTE","palette","six digit hex color required");const u=t=>{"string"==typeof t&&Object.hasOwn(a.palette,t)||WS("PALETTE",String(t),"unresolved color token")},p=new Map(l.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),f=new Map(l.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),m=new Map;Array.isArray(a.appearance)||WS("ASSET_SCHEMA","appearance","array required");for(const t of a.appearance){if(YS(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=c.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||WS("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(f.has(t.target)&&!m.has(t.target)||WS("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),YS(t.material,["token"],["preset","transparent","emissive"],"material"),u(t.material.token),void 0===t.material.preset||["default","metal","glass","plastic","wood","ceramic","rubber"].includes(t.material.preset)||WS("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&WS("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;YS(e,["token","intensity","on"],[],"emissive"),u(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&WS("MATERIAL","emissive","invalid intensity or switch")}const e=p.get(f.get(t.target).args[0]);"revolve@1"===e?.op||"extrude@1"===e?.op&&"ellipse"===e.params?.section?[8,12,16,24,32,48].includes(t.segments)||WS("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&WS("QUALITY","segments","segments unsupported on this provider"),m.set(t.target,t)}m.size!==f.size&&WS("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==a.mountingFace){const t=a.mountingFace;YS(t,["plane","surface"],[],"mountingFace"),"mounting-plane"!==t.plane&&WS("MOUNTING_FACE","mountingFace",`${String(t.plane)} is not a plane the figure can be mounted on`),_M({types:c.outputTypes,writers:p,model:l,assetFrame:a.document.capabilities.assetFrame},t.surface,"mountingFace.surface")}HS(a),DS(a),PS(a),function(t){const e=t.stateInputs;if(void 0===e)return;e&&"object"==typeof e&&!Array.isArray(e)||FS("STATE_INPUT","stateInputs","object required");const n=NS(t);for(const[t,s]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||FS("STATE_INPUT",e,`${t} is not a state input of this asset`),s&&"object"==typeof s&&!Array.isArray(s)||FS("STATE_INPUT",e,"object required");for(const t of Object.keys(s))"label"!==t&&"sweep"!==t&&FS("STATE_INPUT",e,`unknown ${t}`);void 0===s.label||"string"==typeof s.label&&s.label.trim()||FS("STATE_INPUT",e,"label must be a nonempty string"),void 0===s.sweep||Number.isFinite(s.sweep)&&s.sweep>=0||FS("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(a),void 0===a.joints||Array.isArray(a.joints)||WS("ASSET_SCHEMA","joints","joints is a list");function g(t={}){YS(t,[],d,"state overrides");const e={...a.designInputs,...a.stateDefaults,...t},n=c.evaluate(e),s=t=>t.key?p.get(t.key)?.id:t.id,i=new Map(a.appearance.map((t,e)=>[t.target,e])),o=n.geometry.map((t,e)=>({g:t,i:e,at:i.get(s(t))??Number.MAX_SAFE_INTEGER})).sort((t,e)=>t.at-e.at||t.i-e.i).map(t=>t.g),r=o.map(t=>{const e=s(t),i=m.get(e);return i||WS("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(i.material),visible:void 0===i.visibility||n.values[i.visibility],...void 0!==i.segments?{segments:i.segments}:{}}});return{...n,geometry:r,inputs:e,palette:structuredClone(a.palette)}}(function(t){const e=t.joints;if(!e?.length)return;const n=structuredClone(t);for(const t of e)dM({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);yM(n);const s=t=>JSON.stringify({nodes:[...t.nodes].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0),inputs:[...t.inputs].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0)});s(n.document.model)!==s(t.document.model)&&Nx("JOINT_DRIFT","joints","the joints' nodes are not what their records make; the asset was edited apart from its joints")})(a),g();const y={evaluate:g};s&&n&&(KS.set(s,{kernel:Ix,joints:e,compiled:y}),JS&&QS(s));return y}(t,!0)}function XS(t){return t.placement??"floor"}const KS=new WeakMap,JS=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function QS(t){if(t&&"object"==typeof t&&!Object.isFrozen(t)){Object.freeze(t);for(const e of Object.values(t))QS(e)}}function ZS(t,e,n,s,i={}){const[o,r]=Kv[e],a=(t,s)=>{const a={x:0,y:0,z:0};return a[e]=n,a[o]=t+(i[o]??0),a[r]=s+(i[r]??0),[a.x,a.y,a.z]};if("polygon"===t.kind)return t.points.map(t=>a(t[o],t[r]));if("ellipse"===t.kind)return Array.from({length:s},(e,n)=>{const i=2*Math.PI*n/s;return a(t.radius[o]*Math.cos(i),t.radius[r]*Math.sin(i))});const c=t.size[o]/2,l=t.size[r]/2,h=t.corner?.[o]??0,d=t.corner?.[r]??0;if(!(h>0&&d>0))return[a(-c,-l),a(c,-l),a(c,l),a(-c,l)];const u=[];for(const[t,e,n]of[[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI],[1,-1,3*Math.PI/2]])for(let s=0;s<=8;s++){const i=n+s/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(i),e*(l-d)+d*Math.sin(i)))}return u}function tA(t,e){return function(t,e){const n=t.extrusion;if(n){const s=[...ZS(n.section,n.axis,n.start,e),...ZS(n.section,n.axis,n.end,e)],i=t.cavity;if(i){const t=c_(n.section,n.axis,i.wall);if("section"in t){const o=n.start+("open"===i.start?0:i.start.closed),r=n.end-("open"===i.end?0:i.end.closed);s.push(...ZS(t.section,n.axis,o,e,t.centre),...ZS(t.section,n.axis,r,e,t.centre))}}return s}const s=t.loft;if(s){const t={x:0,y:0,z:0,...s.apex,[s.axis]:s.end};return[...ZS(s.section,s.axis,s.start,e),[t.x,t.y,t.z]]}const i=t.revolution,[o,r]=Kv[i.axis],a=(t,n)=>ZS({kind:"ellipse",radius:{[o]:n,[r]:n}},i.axis,t,e);if("taper"===i.profile.kind)return[...a(i.profile.start,Math.max(i.profile.startRadius,1e-9)),...a(i.profile.end,Math.max(i.profile.endRadius,1e-9))];const{radial:c,axial:l}=i.profile,h=[];for(let t=1;t<6;t++){const e=t/6*Math.PI;h.push(...a(l*Math.cos(e),c*Math.sin(e)))}return h.push(...a(l,1e-9).slice(0,1),...a(-l,1e-9).slice(0,1)),h}(t,e??12)}function eA(t,e,n){return t.map(([t,s,i])=>[e[0][0]*t+e[0][1]*s+e[0][2]*i+n[0],e[1][0]*t+e[1][1]*s+e[1][2]*i+n[1],e[2][0]*t+e[2][1]*s+e[2][2]*i+n[2]])}function nA(t,e,n={}){return function(t,e,n={}){const s=[];for(const i of t){if(!("pose"in i))continue;if(!1===i.visible)continue;const t=i.key?e.get(i.key):i.id,o=i.shape,r=i.pose.r,a=jv.map((t,e)=>Gw(o,[r[e][0],r[e][1],r[e][2]])),c=B_(o),l={part:t,centre:{x:i.pose.t[0]+(a[0].max+a[0].min)/2,y:i.pose.t[1]+(a[1].max+a[1].min)/2,z:i.pose.t[2]+(a[2].max+a[2].min)/2},extent:{x:a[0].max-a[0].min,y:a[1].max-a[1].min,z:a[2].max-a[2].min},dims:jv.map(t=>c[t].max-c[t].min),rotation:r};n.points&&(l.points=eA(tA(i.shape,i.segments),r,i.pose.t)),s.push(l)}return s}(t.map(t=>"pose"in t?{...t,visible:!0}:t),e,n)}function sA(t){const e=new Map;for(const n of t.document.model.nodes)for(const t of Object.values(n.outputs))e.set(t,n.id);return e}const iA=t=>Math.round(1e6*t)/1e6;const oA=(t,e,n=1)=>({terms:[...t.terms,...e.terms.map(t=>({ref:t.ref,k:t.k*n}))],c:t.c+e.c*n}),rA=t=>{const e=new Map;for(const n of t.terms)e.set(n.ref,(e.get(n.ref)??0)+n.k);return{terms:[...e].filter(([,t])=>0!==t).map(([t,e])=>({ref:t,k:e})),c:t.c}},aA=(t,e)=>{const n=new Map;for(const s of[...rA(t).terms,...rA(e).terms])n.set(s.ref,Math.max(n.get(s.ref)??0,s.k));return{terms:[...n].map(([t,e])=>({ref:t,k:e})),c:Math.max(t.c,e.c)}},cA=(t,e)=>{const n=t.constants.find(t=>t.id===e);return n?{terms:[],c:n.value}:{terms:[{ref:e,k:1}],c:0}};function lA(t,e,n=new Set,s=0){t.inputs.some(t=>t.id===e&&"state"===t.role)&&n.add(e);const i=s<256?Bx(t,e):void 0;for(const e of i?.args??[])"string"==typeof e&&lA(t,e,n,s+1);return n}function hA(t,e){const n=new Set;for(let s=e;s;s=ow(t,s))for(const{motion:e}of sM(t,s))"axis-slide@1"===e.op&&lA(t,e.args[3],n);const s=[...n].sort();return s.length>10?{many:s}:s.length<=1?["min","max"]:Array.from({length:2**s.length},(t,e)=>Object.fromEntries(s.map((t,n)=>[t,e>>n&1?"max":"min"])))}const dA=(t,e)=>`${t} is slid by ${e.length} controls; this reading goes over at most 10 of them corner by corner`;function uA(t,e,n,s,i){const o=Object.fromEntries(i.map(t=>[t,"min"])),r=MA(t,e,n,s,o);if("string"==typeof r)return r;let a={terms:[],c:0};for(const c of i){const i=MA(t,e,n,s,{...o,[c]:"max"});if("string"==typeof i)return i;const l=kA(t,oA(i,r,-1));if(!l)return`${n}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;a=oA(a,l)}return[oA(r,a,-1),oA(r,a)]}function pA(t,e,n,s){const i=t=>"object"==typeof s?"min"===s[t.id]?t.min:t.max:"start"===s?e.stateDefaults[t.id]??t.min:"min"===s?t.min:t.max,o=e=>t.inputs.find(t=>t.id===e&&"state"===t.role),r=(e,n=0)=>{if(o(e))return!1;const s=n<256?Bx(t,e):void 0;return!s||s.args.every(t=>"string"!=typeof t||r(t,n+1))},a=(e,n=0)=>{const s=(e=>t.constants.find(t=>t.id===e)?.value)(e);if(void 0!==s)return{terms:[],c:s};const c=o(e);if(c)return{terms:[],c:i(c)};const l=n<256?Bx(t,e):void 0;if("add@1"===l?.op){let t={terms:[],c:0};for(const e of l.args){const s=a(e,n+1);if(!s)return null;t=oA(t,s)}return t}if("mul@1"===l?.op&&2===l.args.length){const s=e=>t.constants.find(t=>t.id===e);if(!l.args.every(s)&&l.args.some(t=>s(t)&&"ratio"!==s(t).unit))return r(e)?{terms:[{ref:e,k:1}],c:0}:null;const[i,o]=l.args.map(t=>a(t,n+1));return i&&o?i.terms.length?o.terms.length?null:oA({terms:[],c:0},i,o.c):oA({terms:[],c:0},o,i.c):null}return r(e)?{terms:[{ref:e,k:1}],c:0}:null};return a(n.args[3])}const fA=()=>({x:{terms:[],c:0},y:{terms:[],c:0},z:{terms:[],c:0}}),mA=(t,e)=>Object.fromEntries(jv.map((n,s)=>[n,jv.reduce((n,i,o)=>t[s][o]?oA(n,e[i],t[s][o]):n,{terms:[],c:0})])),gA=t=>null!==t&&Number.isFinite(t)&&Math.abs(t/90-Math.round(t/90))<1e-9;function yA(t,e,n){const s=Hx(t,`${n}.pose`),i=(s?.args.slice(3,6)??[]).map(n=>pw(t,e,n));return i.every(t=>0===t)?null:i.every(gA)?mw(i):"other"}const bA=(t,e)=>sM(t,e).some(t=>"axis-turn@1"===t.motion.op),vA=(t,e,n)=>(Hx(t,`${n}.seat.rigid`)?.args.slice(3,6)??[]).some(n=>0!==pw(t,e,n));function _A(t,e,n){for(let s=n;s;s=ow(t,s)){if(bA(t,s))return!0;if("other"===yA(t,e,s)||vA(t,e,s))return!0}return!1}function xA(t,e,n){let s=Sw;for(let i=n;i;i=ow(t,i)){const n=yA(t,e,i);if("other"===n)return null;n&&(s=gw(n,s))}return s}function wA(t,e,n,s,i){let o=i??fA();for(let r=n;r;r=ow(t,r)){const a=Hx(t,`${r}.pose`);if(!a)return`${r} has no pose this command can read`;if(r!==n||i){const n=yA(t,e,r);if("other"===n)return`${r} is turned by other than quarter turns, so what it carries is not a box this command can add up`;n&&(o=mA(n,o))}for(const[e,n]of jv.entries())o[n]=oA(o[n],cA(t,a.args[e]));for(const{motion:n}of sM(t,r)){if("axis-slide@1"!==n.op)return`${r} turns, so its reach is not a box this command can add up`;const i=n.args.slice(0,3).map(e=>t.constants.find(t=>t.id===e)?.value??null);if(i.some(t=>null===t))return`${r}'s slide axis is not a constant`;if(i.some(t=>0!==t)){const a=pA(t,e,n,s);if(!a)return`${r}'s travel is not a distance this command can read`;for(const[t,e]of jv.entries())i[t]&&(o[e]=oA(o[e],a,i[t]))}}const c=Hx(t,`${r}.seat.rigid`);if(c){if(c.args.slice(3,6).some(n=>0!==pw(t,e,n)))return`${r} is seated turned, which this command does not add up`;for(const[e,n]of jv.entries())o[n]=oA(o[n],cA(t,c.args[e]))}}return o}function MA(t,e,n,s,i){const o=wA(t,e,n,i);return"string"==typeof o?o:o[s]}function SA(t,e,n=0){if(n>64)return null;const s=t.constants.find(t=>t.id===e);if(s)return{terms:[],c:s.value};if(t.inputs.some(t=>t.id===e))return{terms:[{ref:e,k:1}],c:0};const i=Bx(t,e);if("add@1"===i?.op){let e={terms:[],c:0};for(const s of i.args){const i=SA(t,s,n+1);if(!i)return null;e=oA(e,i)}return e}if("mul@1"===i?.op&&2===i.args.length){const s=e=>t.constants.find(t=>t.id===e);if(!i.args.every(s)&&i.args.some(t=>s(t)&&"ratio"!==s(t).unit))return AA(t,e)?{terms:[{ref:e,k:1}],c:0}:null;const[o,r]=i.args.map(e=>SA(t,e,n+1));if(!o||!r)return null;if(!o.terms.length)return oA({terms:[],c:0},r,o.c);if(!r.terms.length)return oA({terms:[],c:0},o,r.c)}return AA(t,e)?{terms:[{ref:e,k:1}],c:0}:null}function AA(t,e,n=0){if(n>64)return!1;const s=t.inputs.find(t=>t.id===e);if(s)return"state"!==s.role&&(/^size\.[xyz]$/.test(s.id)||s.min>=0);const i=Bx(t,e),o=e=>(t.constants.find(t=>t.id===e)?.value??-1)>0;return"geomean@1"===i?.op?i.args.every(e=>AA(t,e,n+1)):"div@1"===i?.op?AA(t,i.args[0],n+1)&&o(i.args[1]):"mul@1"===i?.op&&(2===i.args.length&&(AA(t,i.args[0],n+1)&&o(i.args[1])||o(i.args[0])&&AA(t,i.args[1],n+1)))}function kA(t,e){let n={terms:[],c:0};const s=Gx(t,e);for(const e of s.terms){const s=SA(t,e.ref);if(!s){const s=CA(t,e.ref);if(!s)return null;n=oA(n,s,Math.abs(e.k));continue}for(const i of s.terms){if(!AA(t,i.ref))return null;n=oA(n,{terms:[{ref:i.ref,k:Math.abs(i.k*e.k)}],c:0})}n.c+=Math.abs(s.c*e.k)}return n.c+=Math.abs(s.c),n}function EA(t,e){const n=Bx(t,e);if("geomean@1"===n?.op&&!AA(t,e))return{root:[n.args[0],n.args[1]]};if("div@1"!==n?.op)return;const s=Bx(t,n.args[0]),i="mul@1"===s?.op?t.constants.find(t=>t.id===s.args[1]&&"ratio"===t.unit)?.value:void 0,o=i?Bx(t,s.args[0]):void 0;return"mul@1"===o?.op&&o.args[0]===o.args[1]?{point:{radius:o.args[0],sign:i>0?1:-1}}:void 0}function TA(t,e,n,s=0){const i=Gx(t,e);let o=[{terms:[],c:i.c}];for(const e of i.terms){let i=[{terms:[e],c:0}];const r=s<64?EA(t,e.ref):void 0;if(r){const o=e.k>0?n:!n;let a;if("root"in r){const e=r.root.map(e=>TA(t,{terms:[{ref:e,k:1}],c:0},o,s+1));a=o?e[0].flatMap(t=>e[1].map(e=>oA({terms:[],c:0},oA(t,e),.5))):e.flat()}else{a=r.point.sign>0===o?TA(t,{terms:[{ref:r.point.radius,k:r.point.sign}],c:0},o,s+1):[{terms:[],c:0}]}i=a.map(t=>oA({terms:[],c:0},t,e.k))}o=o.flatMap(t=>i.map(e=>oA(t,e)))}return o.map(rA)}function CA(t,e,n=!1){const s=Bx(t,e),i=EA(t,e);if(i&&"point"in i)return kA(t,{terms:[{ref:i.point.radius,k:1}],c:0});if(!i&&(!n||"max@1"!==s?.op&&"min@1"!==s?.op))return null;const o=s.args.map(e=>{const n=Gx(t,{terms:[{ref:e,k:1}],c:0});let s={terms:[],c:Math.abs(n.c)};for(const e of n.terms){const n=SA(t,e.ref)?kA(t,{terms:[e],c:0}):CA(t,e.ref,!0);if(!n)return null;s=oA(s,n,Math.abs(e.k))}return s});return o.some(t=>!t)?null:"geomean@1"===s.op?oA({terms:[],c:0},oA(o[0],o[1]),.5):o.reduce((t,e)=>aA(t,e))}const OA=(t,e)=>[0,1,2].map(n=>t[0][n]*e[0]+t[1][n]*e[1]+t[2][n]*e[2]),PA=t=>t.mid.map((e,n)=>Math.min(1,Math.abs(e)+t.spread[n]));function IA(t,e){const n=t.map((t,n)=>Math.max(-1,t-e[n])),s=t.map((t,n)=>Math.min(1,t+e[n]));return{mid:n.map((t,e)=>(t+s[e])/2),spread:n.map((t,e)=>(s[e]-t)/2)}}function DA(t,e){return IA(OA(e,t.mid),[0,1,2].map(n=>t.spread.reduce((t,s,i)=>t+Math.abs(e[i][n])*s,0)))}function zA(t,e,n,s){if(!s)return[t-Math.hypot(e,n),t+Math.hypot(e,n)];const[i,o]=s,r=s=>t+e*Math.cos(s)+n*Math.sin(s);let a=Math.min(r(i),r(o)),c=Math.max(r(i),r(o));const l=2*Math.PI;for(const t of[Math.atan2(n,e),Math.atan2(n,e)+Math.PI])for(let e=t+Math.ceil((i-t)/l)*l;e<=o;e+=l)a=Math.min(a,r(e)),c=Math.max(c,r(e));return[a,c]}function RA(t,e,n){const s=[[0,-e[2],e[1]],[e[2],0,-e[0]],[-e[1],e[0],0]],i=(t,n)=>e[t]*e[n],o=(t,n)=>(t===n?1:0)-e[t]*e[n],r=(t,e)=>s[t][e];if(n&&Math.abs(n[1]-n[0])<1e-12){const e=n[0];return DA(t,[0,1,2].map(t=>[0,1,2].map(n=>i(t,n)+o(t,n)*Math.cos(e)+r(t,n)*Math.sin(e))))}const a=(e,n)=>[0,1,2].reduce((s,i)=>s+e(i,n)*t.mid[i],0),c=[0,1,2].map(t=>zA(a(i,t),a(o,t),a(r,t),n)),l=[0,1,2].map(e=>t.spread.reduce((t,s,a)=>{const[c,l]=zA(i(a,e),o(a,e),r(a,e),n);return t+Math.max(Math.abs(c),Math.abs(l))*s},0));return IA(c.map(([t,e])=>(t+e)/2),c.map(([t,e],n)=>(e-t)/2+l[n]))}function jA(t,e,n=0){if(n>64)return null;const s=t.constants.find(t=>t.id===e);if(s)return"deg"===s.unit?[s.value,s.value]:null;const i=t.inputs.find(t=>t.id===e);if(i){if("state"!==i.role||"deg"!==i.unit)return null;const{min:t,max:e}=i;return Number.isFinite(t)&&Number.isFinite(e)&&e-t<360?[t,e]:null}const o=Bx(t,e);if("add@1"===o?.op){let e=0,s=0;for(const i of o.args){const o=jA(t,i,n+1);if(!o)return null;e+=o[0],s+=o[1]}return s-e<360?[e,s]:null}if("mul@1"===o?.op&&2===o.args.length){const e=e=>t.constants.find(t=>t.id===e&&"ratio"===t.unit)?.value,[s,i]=o.args,r=e(s)??e(i),a=void 0!==e(s)?jA(t,i,n+1):void 0!==e(i)?jA(t,s,n+1):null;if(void 0===r||!a)return null;const c=[a[0]*r,a[1]*r].sort((t,e)=>t-e);return c[1]-c[0]<360?c:null}return null}function $A(t,e,n){const s=[];for(let e=n;e;e=ow(t,e))s.push(e);const i=s.reduce((n,s,i)=>bA(t,s)||"other"===yA(t,e,s)||vA(t,e,s)?i:n,-1);if(i<0)return`${n} is carried by no turn`;const o=s[i],r=ow(t,o),a=r?xA(t,e,r):Sw;if(!a)return`${o} is carried by a part turned by other than quarter turns`;const c=dw(t,n,n),{shape:l}=Vx(t,n,n),h=I_(l)?.faces,d=Object.fromEntries(jv.map(t=>[t,uw(l,h,t)])),u=e=>e.map(e=>t.constants.find(t=>t.id===e)?.value),p=o=>{let r={mid:OA(a,o),spread:[0,0,0]},l={terms:[],c:0};const h=t=>Math.abs(t)<1e-12,p=(e,n)=>{const s=u(e);if(s.every(t=>void 0!==t)){const t=s.reduce((t,e,n)=>t+r.mid[n]*e+r.spread[n]*Math.abs(e),0),e=PA(r),n=Math.hypot(...s.map((t,n)=>e[n]>0?t:0));return l=oA(l,{terms:[],c:Math.min(t,n)}),null}for(const[s,i]of e.entries()){if(h(r.mid[s])||(l=oA(l,cA(t,i),r.mid[s])),h(r.spread[s]))continue;const e=kA(t,cA(t,i));if(!e)return`${n} is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,e,r.spread[s])}return null},f=n=>{const s=(n=>n.map(n=>pw(t,e,n)))(n);if(!s.every(t=>0===t))if(s.every(t=>null!==t&&Number.isFinite(t)))r=DA(r,(([t,e,n])=>gw(gw(Cw("x",t),Cw("y",e)),Cw("z",n)))(s));else{const t=Math.min(1,PA(r).reduce((t,e)=>t+e,0));r={mid:[0,0,0],spread:[t,t,t]}}};for(let n=i;n>=0;n--){const o=s[n],a=Hx(t,`${o}.seat.rigid`);if(a){if(n<i){const t=p(a.args.slice(0,3),`where ${o} is fastened`);if(t)return t}f(a.args.slice(3,6))}for(const{motion:n,through:s,back:i}of sM(t,o)){if(s){const t=p(s.args.slice(0,3),`the point ${o} turns about`);if(t)return t}const a=u(n.args.slice(0,3));if(a.some(t=>void 0===t))return`${o}'s ${"axis-turn@1"===n.op?"turn":"slide"} axis is not a constant`;const c=Math.hypot(...a),h=a.map(t=>t/c);if("axis-turn@1"===n.op){const e=jA(t,n.args[3]);r=RA(r,h,e&&[e[0]*Math.PI/180,e[1]*Math.PI/180])}else{if("axis-slide@1"!==n.op)return`${o} moves by ${n.op}, which this command does not add up`;{const s=r.mid.reduce((t,e,n)=>t+e*h[n],0),i=r.spread.reduce((t,e,n)=>t+e*Math.abs(h[n]),0),a=[...lA(t,n.args[3])].sort();if(a.length>10)return`${o}'s slide reads ${a.length} controls; how far it reaches is read over at most 10`;const c=a.length<=1?["min","max"]:Array.from({length:2**a.length},(t,e)=>Object.fromEntries(a.map((t,n)=>[t,e>>n&1?"max":"min"]))),d=c.map(s=>pA(t,e,n,s));if(d.some(t=>!t))return`${o}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;const[u,p]=2===d.length?d:[null,null],f=t=>!rA(t).terms.length&&Math.abs(t.c)<1e-12,m=e=>e.c>=0&&rA(e).terms.every(e=>e.k>0&&AA(t,e.ref)),g=u&&p?f(u)?p:f(p)?u:null:null,y=g&&(m(g)?1:m(oA({terms:[],c:0},g,-1))?-1:0);if(g&&y)l=oA(l,g,y*(Math.max(y*s,0)+i));else{const e=d.reduce((e,n)=>{const s=e&&kA(t,n);return s&&e&&aA(e,s)},{terms:[],c:0});if(!e)return`${o}'s travel is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,e,Math.abs(s)+i)}}}if(i){const t=p(i.args.slice(0,3),`the point ${o} turns about`);if(t)return t}}const c=Hx(t,`${o}.pose`);if(!c)return`${o} has no pose this command can read`;const h=p(c.args.slice(0,3),`${o}'s place`);if(h)return h;f(c.args.slice(3,6))}for(const[e,s]of jv.entries()){const i=r.mid[e],o=r.spread[e];if(h(i)&&h(o))continue;const a=d[s];if(a){const e=i>0?a[1]:a[0];if(h(i)||(l=oA(l,{terms:[{ref:e.ref,k:e.k*i}],c:0})),h(o))continue;const s=a.reduce((e,n)=>{const s=e&&kA(t,{terms:[{ref:n.ref,k:n.k}],c:0});return s&&e&&aA(e,s)},{terms:[],c:0});if(!s)return`${n}'s size is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,s,o);continue}const u=kA(t,{terms:[{ref:c[s].ref,k:.5*c[s].k}],c:0});if(!u)return`${n}'s size is not a sum of sizes, so how far it reaches cannot be bounded`;l=oA(l,u,Math.min(1,Math.abs(i)+o))}return rA(l)},f={},m={};for(const[t,e]of jv.entries()){const n=[0,0,0];n[t]=1;const s=p(n);if("string"==typeof s)return s;n[t]=-1;const i=p(n);if("string"==typeof i)return i;f[e]=s,m[e]=i}const g=Hx(t,`${o}.seat.rigid`),y=Object.fromEntries(jv.map((e,n)=>[e,g?cA(t,g.args[n]):{terms:[],c:0}])),b=[],v=r?hA(t,r):["min"];if(!Array.isArray(v))return dA(r,v.many);for(const n of v){const s=r?wA(t,e,r,n,structuredClone(y)):y;if("string"==typeof s)return s;b.push(s)}return{centres:b,up:f,down:m}}function LA(t){const e=t.document.model,n=[],s=[],i={x:[],y:[],z:[]},o={x:[],y:[],z:[]},r={low:{x:[],y:[],z:[]},high:{x:[],y:[],z:[]}},a=(t,n)=>{const s=rA(oA(t,n,-1));return s.c>=-1e-9&&s.terms.every(t=>t.k>0&&AA(e,t.ref))},c=(t,e,n)=>{const s=r[t][e],i=(e,n)=>"high"===t?a(e,n):a(n,e);s.some(t=>i(t,n))||(r[t][e]=[...s.filter(t=>!i(n,t)),n])},l=t=>Hx(e,`${t}.repeat`),h=(n,s)=>{const i=function(t,e,n,s=!1){const{shape:i}=Vx(t,e,n),o=I_(i);if(o&&!s){const t={};for(const e of jv){const n=o.measure[e];if("profile"===n)t[e]={offsets:hw(i,e)};else{const s=uw(i,o.faces,e);t[e]=s?{offsets:s}:n.map(t=>({ref:i.args[t.arg],k:t.k}))}}return t}const r=dw(t,e,n);return{x:[r.x],y:[r.y],z:[r.z]}}(e,n,n,s),o=s?Sw:xA(e,t,n);if(!o)throw new Xv("EDIT_TARGET",n,`${n} is turned by other than quarter turns`);return Object.fromEntries(jv.map((t,e)=>{const n=o[e].findIndex(t=>0!==t),s=i[jv[n]];return[t,lw(s)&&o[e][n]<0?{offsets:s.offsets.map(t=>({...t,k:-t.k}))}:s]}))},d=n=>{const s=l(n),i=String(s.params?.axis??"").toLowerCase(),o=ow(e,n),r=o&&xA(e,t,o);if(!o||!jv.includes(i)||!r||jv.some((t,e)=>1!==r[e][e]))return`${n} is a row whose run this command cannot read`;const a=function(t,e,n,s,i=!0){const o=dw(t,n,s),r=fw(t,e,n,s,i),a={};return jv.forEach((t,e)=>a[t]=o[jv[r[e].findIndex(t=>0!==t)]]),a}(e,t,o,o,!1)[i],c={terms:[{ref:a.ref,k:.5*a.k}],c:0},d=hA(e,o);if(!Array.isArray(d))return dA(o,d.many);const u=d.map(n=>MA(e,t,o,i,n)),p=u.find(t=>"string"==typeof t);if(p)return String(p);const f=h(n,!1)[i];if(lw(f))return`${n} is a row of a drawn section along its section; how far each copy reaches is not added up`;const m=f[0],g={terms:[{ref:m.ref,k:m.k}],c:0},y=(t.joints??[]).find(t=>t.body1.part===n&&t.repeat)?.repeat;let b;if(y?.rise){const t=y.rise.mm;let e;if(void 0!==y.count)e={terms:[],c:(y.count-1)*t};else{if("number"!=typeof y.pitch)return`${n} is a rising row whose pitch follows a length; how far it rises is not added up`;e={terms:[{ref:a.ref,k:a.k*t/y.pitch},{ref:m.ref,k:-m.k*t/y.pitch}],c:0}}b={axis:y.rise.axis.toLowerCase(),up:t>0,reach:e}}return{axis:i,lows:u.map(t=>oA(t,c,-1)),highs:u.map(t=>oA(t,c,1)),extent:g,climb:b}};for(const r of e.nodes.filter(t=>"place@1"===t.op||"member@1"===t.op&&(l(t.id)||Ux(e,t.id)))){const a=_A(e,t,r.id);let u={};try{u=h(r.id,a)}catch(t){s.push({part:r.id,reason:t instanceof Xv?t.message:"not a part whose size this command can read"});continue}const p=[];let f;for(let t="member@1"===r.op?r.id:null;t;t=ow(e,t)){if(!l(t))continue;const e=d(t);if("string"==typeof e){f=e;break}p.push({part:t,run:e})}if(f){s.push({part:r.id,reason:f});continue}const m=new Set(p.map(t=>t.run.axis)),g=(t,e,n,s)=>{const i=p.map(t=>t.run.climb).filter(t=>t&&t.axis===s&&(t.up?1:-1)===e);i.length&&n[s].push(i.reduce((t,e)=>oA(t,e.reach),t))};if(a){const a=$A(e,t,r.id);if("string"==typeof a){s.push({part:r.id,reason:a});continue}if(n.push(r.id),p.length){for(const{run:t}of p){for(const e of t.lows)i[t.axis].push(oA(e,a.down[t.axis],-1));for(const e of t.highs)o[t.axis].push(oA(e,a.up[t.axis],1))}for(const t of a.centres)for(const e of jv.filter(t=>!m.has(t))){const n=oA(t[e],a.down[e],-1),s=oA(t[e],a.up[e],1);i[e].push(n),o[e].push(s),g(n,-1,i,e),g(s,1,o,e)}continue}for(const t of a.centres)for(const e of jv)c("low",e,rA(oA(t[e],a.down[e],-1))),c("high",e,rA(oA(t[e],a.up[e],1)));continue}const y=hA(e,r.id);if(!Array.isArray(y)&&p.some(t=>t.part!==r.id)){s.push({part:r.id,reason:dA(r.id,y.many)});continue}const b=jv.map(n=>({axis:n,at:Array.isArray(y)?y.map(s=>MA(e,t,r.id,n,s)):uA(e,t,r.id,n,y.many)})).map(t=>({axis:t.axis,at:"string"==typeof t.at?[t.at]:t.at})),v=b.flatMap(t=>t.at).find(t=>"string"==typeof t);if(v){s.push({part:r.id,reason:String(v)});continue}let _;for(const{part:n,run:s}of p){if(n===r.id){i[s.axis].push(...s.lows),o[s.axis].push(...s.highs);continue}const a=y.map(i=>MA(e,t,n,s.axis,i)),c=a.find(t=>"string"==typeof t);if(c){_=String(c);break}const l=b.find(t=>t.axis===s.axis).at,h=oA({terms:[],c:0},s.extent,.5),d=u[s.axis];if(lw(d)){_=`${r.id} is a drawn section carried along a row; how far each copy reaches is not added up`;break}for(const[t,e]of l.entries()){const n=oA(e,a[t],-1);for(const t of d){const e={terms:[{ref:t.ref,k:.5*t.k}],c:0};for(const t of s.lows)i[s.axis].push(oA(oA(oA(t,h),n),e,-1));for(const t of s.highs)o[s.axis].push(oA(oA(oA(t,h,-1),n),e))}}}if(_)s.push({part:r.id,reason:_});else{n.push(r.id);for(const t of b){if(m.has(t.axis))continue;const e=u[t.axis],n=new Set;for(const s of t.at){const r=JSON.stringify([s.terms.map(t=>[t.ref,t.k]).sort(),s.c]);if(n.has(r))continue;if(n.add(r),lw(e)){for(const n of e.offsets){const e=oA(s,{terms:[{ref:n.ref,k:n.k}],c:0});i[t.axis].push(e),o[t.axis].push(e),g(e,-1,i,t.axis),g(e,1,o,t.axis)}continue}const a=e.map(t=>({terms:[{ref:t.ref,k:.5*t.k}],c:0}));for(const e of a){const n=oA(s,e,-1),r=oA(s,e,1);i[t.axis].push(n),o[t.axis].push(r),g(n,-1,i,t.axis),g(r,1,o,t.axis)}}}}}return{parts:n,skipped:s,low:i,high:o,reaches:r}}const FA=(t,e)=>e.terms.reduce((e,n)=>e+n.k*(t[n.ref]??NaN),e.c);function NA(t,e={}){const n=structuredClone(t),{parts:s,skipped:i,low:o,high:r,reaches:a}=LA(n);for(const t of jv)o[t].push(...a.low[t]),r[t].push(...a.high[t]);if(function(t,e,n){for(const s of jv)e[s]=e[s].flatMap(e=>TA(t,e,!1)),n[s]=n[s].flatMap(e=>TA(t,e,!0))}(n.document.model,o,r),!s.length)return;const c=Px(n.document.model).evaluate({...n.designInputs,...n.stateDefaults,...e}).values,l=Object.fromEntries(jv.map(t=>[t,{min:rw(Math.min(...o[t].map(t=>FA(c,t)))),max:rw(Math.max(...r[t].map(t=>FA(c,t))))}]));return{bounds:l,parts:s,skipped:i}}function HA(t){const e=t.document.capabilities.slotLayout;if(!e)return;const n=t.document.model.nodes;return{label:e.label,role:e.role,anchors:e.anchors.map(t=>({id:t.id,part:n.find(e=>"place@1"===e.op&&e.outputs?.placed===t.pose.placement)?.id,face:n.find(e=>"feature@1"===e.op&&e.outputs?.pose===t.pose.feature)?.params?.name})),layout:structuredClone(e.layout)}}function BA(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,s=t.document.capabilities.bindings.map(t=>{const s="string"==typeof t.pose?null:t.pose,i=s?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===s.placement):null,o=s?Bx(e,s.feature):null,r=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:i?.id??null,face:o?.params?.name??null,...t.accepts?{accepts:[...t.accepts]}:{},capacity:t.capacity,region:3===r.length&&r.every(t=>"number"==typeof t)?{x:r[0],y:r[1],z:r[2]}:null}}),i=JM(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),s=Bx(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:s?.params?.name??null,...t.accepts?{accepts:[...t.accepts]}:{},capacity:t.capacity,region:{x:t.allowed.width,y:t.allowed.height,z:t.allowed.depth},slot:{tier:t.tier,slot:t.slot,anchorId:t.anchorId,tierPosition:{...t.tierPosition},tierRotation:t.tierRotation,offset:{...t.offset},rotation:t.rotation}}});return[...s,...i]}function GA(t){const e=(t,e,n)=>{throw new Xv("ITEM_SNAPSHOT",t,e,n)},n=t;n&&"object"==typeof n&&"string"==typeof n.revision&&Array.isArray(n.items)||e("snapshot","a revision and a list of items",{reason:"item-snapshot-shape"});const s=new Set,i=new Map;n.items.forEach((t,n)=>{const o=`items[${n}]`;t&&"string"==typeof t.itemId&&t.itemId&&"string"==typeof t.slotId&&t.slotId||e(o,"an item id and a slot id",{reason:"item-snapshot-shape"}),(!Number.isSafeInteger(t.stackIndex)||t.stackIndex<0)&&e(`${o}.stackIndex`,"a whole number from 0",{reason:"item-snapshot-shape"}),void 0!==t.type&&"string"!=typeof t.type&&e(`${o}.type`,"a type name",{reason:"item-snapshot-shape"}),void 0===t.dims||t.dims&&["width","depth","height"].every(e=>(t=>"number"==typeof t&&Number.isFinite(t))(t.dims[e])&&t.dims[e]>0)||e(`${o}.dims`,"three positive numbers in mm",{reason:"item-invalid-dimensions",item:t.itemId}),s.has(t.itemId)&&e(o,`${t.itemId} is in the snapshot twice`,{reason:"item-duplicate",item:t.itemId}),s.add(t.itemId),i.set(t.slotId,[...i.get(t.slotId)??[],t.stackIndex])});for(const[t,n]of i){const s=[...n].sort((t,e)=>t-e);s.forEach((n,i)=>{n!==i&&e("items",`the stack in ${t} has ${s.join(", ")}; each height once, from 0`,{reason:"item-stack-index",slot:t,heights:s})})}}function UA(t){const e=t.material,n=e.emissive?.on?`on:${e.emissive.token}:${e.emissive.intensity}`:"off";return`${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${n}`}const VA=t=>JSON.stringify([t.shape.provider,t.shape.dimensions,t.shape.extrusion?[t.shape.extrusion.axis,t.shape.extrusion.section.kind,t.shape.cavity??null]:t.shape.revolution?[t.shape.revolution.axis,t.shape.revolution.profile.kind]:t.shape.loft?[t.shape.loft.axis,"loft"]:t.shape.mesh?[t.shape.mesh.asset,t.shape.mesh.node??null]:null,t.segments??null,UA(t),!1!==t.visible]);function WA(t,e){const n=function(t,e){const n=e??rS(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=sA(t),o=t=>{const e=void 0===t?void 0:s.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!o("string"==typeof n?.[0]?n[0]:t.id)||!!e&&o(i.get(e))}}(t,e),s=sA(t),i=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target));return t=>{const e=new Set;for(const o of t){if(!("pose"in o)||n(o))continue;const t=o.key?s.get(o.key):o.id;void 0!==t&&i.has(t)||e.add(o.id)}return e}}function YA(t){const e=function(t){return new Set((t.dataInterface?.bindings??[]).flatMap(t=>"table"===t.rule?t.targets.parts??[]:[]))}(t),n=new Set(e);if(e.size)for(const s of t.document.model.nodes)if(e.has(s.id))for(const t of Object.values(s.outputs))n.add(t);return n}const qA=t=>!!t.shape?.mesh,XA=t=>`${UA(t)}|${!1!==t.visible?"shown":"hidden"}`;function KA(t,e={}){const n=[],s=new Set,i=new Map;for(const o of t){if(!("pose"in o))continue;if(e.own?.has(o.id)||"string"==typeof o.key&&e.own?.has(o.key)){n.push(o.id),s.add(o.id);continue}const t="key"in o&&"string"==typeof o.key?o.key:void 0;if(!t){n.push(o.id);continue}const r=i.get(t)??[];r.push(o),i.set(t,r)}const o=[],r=[];for(const[t,e]of i){const s=new Map;for(const t of e){const e=VA(t),n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}for(const[i,a]of s)qA(e.find(t=>t.id===a[0]))?(n.push(...a),r.push({member:t,ids:a,reason:"mesh"})):a.length>1?o.push({key:`${t}|${i}`,member:t,ids:a}):(n.push(...a),r.push({member:t,ids:a,reason:1===e.length?"one-copy":"copies-differ"}))}const a=[];if(e.still?.size){const i=new Map(t.map(t=>[t.id,t])),o=new Map;for(const t of n){const n=i.get(t);if(!n||s.has(t)||!e.still.has(t)||n.material.transparent||qA(n))continue;const r=XA(n),a=o.get(r);a?a.push(t):o.set(r,[t])}const r=new Set;for(const[t,e]of o)e.length<2||(a.push({key:t,ids:e}),e.forEach(t=>r.add(t)));r.size&&n.splice(0,n.length,...n.filter(t=>!r.has(t)))}const c=[];if(e.carried?.size){const i=new Map(t.map(t=>[t.id,t])),o=new Map;for(const t of n){const n=i.get(t),r=e.carried.get(t);if(!n||s.has(t)||void 0===r||e.still?.has(t)||n.material.transparent||qA(n))continue;const a=`${r}|${XA(n)}`,c=o.get(a);c?c.ids.push(t):o.set(a,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of o)n.length<2||(c.push({key:t,carrier:e,ids:n}),n.forEach(t=>r.add(t)));r.size&&n.splice(0,n.length,...n.filter(t=>!r.has(t)))}const l=new Map(t.map(t=>[t.id,t])),h=n.reduce((t,e)=>t+Math.max((t=>l.get(t)?.shape?.mesh?.primitives??1)(e),1)-1,0);return{batches:o,merged:a,carried:c,alone:n,unbatched:r,meshDraws:h}}const JA=Uv[0];function QA(t,e,n,s={}){const[i,o]=Kv[e],r=s[i]??0,a=s[o]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[i],t[o]]);else if("ellipse"===t.kind){const e=t.radius[i],s=t.radius[o];c=Array.from({length:n},(t,i)=>{const o=2*Math.PI*i/n;return[e*Math.cos(o),s*Math.sin(o)]})}else{const e=t.size[i]/2,n=t.size[o]/2,s=t.corner?.[i]??0,r=t.corner?.[o]??0;if(s>0&&r>0){c=[];for(const[t,i,o]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=JA;a++){const l=o+a/JA*(Math.PI/2);c.push([t*(e-s)+s*Math.cos(l),i*(n-r)+r*Math.sin(l)])}}else c=[[-e,-n],[e,-n],[e,n],[-e,n]]}return c=c.map(([t,e])=>[t+r,e+a]),ZA(c)<0?c.reverse():c}const ZA=t=>t.reduce((e,n,s)=>e+n[0]*t[(s+1)%t.length][1]-t[(s+1)%t.length][0]*n[1],0)/2;function tk(t){const e=[...t].sort((t,e)=>t[0]-e[0]||t[1]-e[1]).map(([t,e])=>[t,e]);if(e.length<3)return e;const n=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]),s=[];for(const t of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],t)<=1e-9;)s.pop();s.push(t)}const i=[];for(let t=e.length-1;t>=0;t--){const s=e[t];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],s)<=1e-9;)i.pop();i.push(s)}return s.slice(0,-1).concat(i.slice(0,-1))}const ek=t=>"shape"in t&&"pose"in t&&!!t.shape;function nk(t,e,n,s={}){const[i,o]=Kv.y;return QA(t,"y",n,s).map(([t,n])=>{const s={x:0,y:e,z:0};return s[i]=t,s[o]=n,[s.x,s.y,s.z]})}const sk=(t,e,n,s={})=>({allowed:{width:t,depth:e,height:n},...s}),ik=(t,e,n)=>({tierNo:t,anchorId:n.anchorId,mount:n.mount??"ON",position:{x:0,y:n.y??0,z:0},rotation:0,layout:e}),ok=t=>`fork_${t}`;function rk(t,e,n,s,i){return{tiers:[ik(1,{pattern:"GRID",rows:2,cols:2,pitch:{x:t.width/2,z:t.depth/2},order:e,origin:n,slot:sk(t.width/2,t.depth/2,t.slotHeight,s)},{anchorId:i})]}}const ak={agvTandem:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:2,pitch:t.width/2,axis:"X",origin:"MAX",slot:sk(t.width/2,t.depth,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),agvParallel:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:2,pitch:t.depth/2,axis:"Z",origin:"MIN",slot:sk(t.width,t.depth/2,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),agv2x2:(t,e,n={})=>rk(t,"COL_MAJOR",{x:"MAX",z:"MIN"},e,n.anchor??wM),bufferPort2x2:(t,e,n={})=>rk(t,"ROW_MAJOR",{x:"MIN",z:"MIN"},e,n.anchor??wM),multiBufferPort:(t,e,n={})=>({tiers:[ik(1,{pattern:"ROW",count:4,pitch:t.width/4,axis:"X",origin:"MIN",slot:sk(t.width/4,t.depth,t.slotHeight,e)},{anchorId:n.anchor??wM})]}),dualTierConveyor(t,e,n,s={}){const i=sk(t.width,t.depth,t.slotHeight,n),o=s.anchor??wM;return{tiers:[ik(1,{pattern:"SINGLE",slot:i},{anchorId:o}),ik(2,{pattern:"SINGLE",slot:{...i}},{anchorId:o,y:e})]}},craneTwinFork(t,e,n={}){const s=sk(t.width,t.depth,t.slotHeight,e),i=n.forks??[ok(1),ok(2)];return{tiers:[1,2].map(t=>ik(t,{pattern:"SINGLE",slot:{...s}},{anchorId:i[t-1]}))}},floorBlock:(t,e,n,s,i,o={})=>({tiers:[ik(1,{pattern:"GRID",rows:e,cols:n,pitch:{x:t.width/n,z:t.depth/e},slot:sk(t.width/n,t.depth/e,t.slotHeight,{...i,stackLimit:s})},{anchorId:o.anchor??wM})]}),single:(t,e,n,s={})=>({tiers:[ik(1,{pattern:"SINGLE",slot:sk(e.width,e.depth,e.slotHeight,n)},{anchorId:s.anchor??wM,mount:t})]})},ck={single:[],agvTandem:[],agvParallel:[],agv2x2:[],bufferPort2x2:[],multiBufferPort:[],dualTierConveyor:[{key:"upperElevation",integer:!1}],craneTwinFork:[],floorBlock:[{key:"rows",integer:!0},{key:"cols",integer:!0},{key:"stackLimit",integer:!0}]},lk=Object.keys(ck);function hk(t,e){const n=EM(t,{anchors:[...e]});if(n.length)return n;const s=TM(t);if(s.length)return s;const i=[],o=t=>Array.isArray(t)&&0===t.length;return t.tiers.forEach((t,e)=>{const n=t.layout;"CUSTOM"===n.pattern?n.slots.forEach((t,n)=>o(t.accepts)&&i.push(xM("ACCEPTS_EMPTY",`tiers[${e}].layout.slots[${n}].accepts`))):o(n.slot.accepts)&&i.push(xM("ACCEPTS_EMPTY",`tiers[${e}].layout.slot.accepts`))}),i}function dk(t,e,n){const s=null!=e?{source:"override",raw:e}:t?{source:"figure",raw:t}:void 0;if(!s)return{source:"none",status:"none",issues:[]};const i=hk(s.raw,n);return i.length?{source:s.source,status:"invalid",issues:i,refusal:{code:"SLOT_LAYOUT",details:{reason:"slot-layout-issues",issues:i}}}:{source:s.source,status:"valid",layout:s.raw,issues:[]}}function uk(t,e){const n=t.document.capabilities.slotLayout,s=dk(n?.layout,e,(n?.anchors??[]).map(t=>t.id));if("override"!==s.source)return{asset:t,effective:s};const i=structuredClone(t);return"valid"===s.status&&i.document.capabilities.slotLayout?i.document.capabilities.slotLayout.layout=structuredClone(s.layout):delete i.document.capabilities.slotLayout,{asset:i,effective:s}}function pk(t,e){const[n,s,i]=[Number(t?.state?.width),Number(t?.state?.height),Number(t?.state?.depth)];return[n,s,i].every(t=>Number.isFinite(t)&&t>0)?{width:n*e,depth:s*e,height:i*e}:null}function fk(t,e){const n=new Map;for(const s of t._items??[]){if(e&&s===e.item)continue;const t=s?.[_v];"string"==typeof t&&t&&(n.get(t)??n.set(t,[]).get(t)).push(s)}return e&&(n.get(e.slotId)??n.set(e.slotId,[]).get(e.slotId)).push(e.item),n}function mk(t,e=""){return gk(t,fk(t),e).snapshot}function gk(t,e,n){const s=new Map,i=new Set,o=[];let r=0;for(const[n,a]of e)a.forEach((e,a)=>{let c=hh(e);c&&!i.has(c)||(c=`#${r}`),r++,i.add(c),s.set(e,c);const l=t.itemTypeOf?.(e)??null,h=t.itemDimsOf?.(e)??null;o.push({itemId:c,slotId:n,stackIndex:a,...l?{type:l}:{},...h?{dims:h}:{}})});return{snapshot:{revision:n,items:o},ids:s}}function yk(t){return{tier:0,slotNo:0,anchorId:t.anchorId,mount:t.mount??"ON",tierPosition:{...t.frame.position},tierRotation:t.frame.rotation,offset:{x:0,z:0},allowed:{width:1/0,depth:1/0,height:1/0},stackLimit:1/0,rotation:0}}function bk(t,e){const n=FM(t),s=e?.position.y??0;return{position:{x:n.position.x,y:n.position.y+s,z:n.position.z},rotation:n.rotation,scale:e?.scale??1}}function vk(t,e,n,s,i,o){if(!t.itemShownDimsOf)return;let r=0;for(const a of s){const s=i.get(a),c=t.itemDimsOf?.(a)??("seated"===s.status?null:t.itemShownDimsOf(a,n,e)),l="seated"===s.status?s.inSlot:c?GM(c,n,r,o):null;if(!l||!c)return;r+=c.height*l.scale,"seated"!==s.status&&i.set(a,{...s,inSlot:l,inAnchor:bk(n,l),shrunk:l.scale<1,dims:c})}}function _k(t,e){const n=t.effectiveLayout?.layout,s=new Map((t.outsideSlots?.()??[]).map(t=>[t.id,t])),i=fk(t,e),o=new Map,r=new Map;for(const[e,n]of i){const i=s.get(e);if(!i){r.set(e,n);continue}const a=yk(i);let c=0,l=!0;n.forEach((n,s)=>{const r=t.itemDimsOf?.(n)??null,h={slotId:e,stackIndex:s,outside:!0,anchorId:i.anchorId,shrunk:!1,dims:r},d=l&&r?GM(r,a,c,0):null;if(!d){const t=l?"size-unknown":"below-unknown";return l=!1,o.set(n,{...h,status:"unconfirmed",why:t,inSlot:null,inAnchor:bk(a,null)})}c+=r.height,o.set(n,{...h,status:"seated",inSlot:d,inAnchor:bk(a,d)})}),vk(t,e,a,n,o,0)}const{snapshot:a,ids:c}=gk(t,r,""),l=new Map(function(t,e,n={}){GA(e);const s=n.margin??NM,i=new Map;for(const t of e.items)i.set(t.slotId,[...i.get(t.slotId)??[],t]);const o=new Map;for(const[e,r]of i){const i=[...r].sort((t,e)=>t.stackIndex-e.stackIndex),a=t?jM(e):null,c=a?zM(t,a):null;let l=0,h=!0;i.forEach((t,r)=>{const a=KM(c,{type:t.type,dims:t.dims??null},i.slice(0,r).map(t=>({type:t.type,dims:t.dims??null})),n.normalizeType?{normalizeType:n.normalizeType}:{}),d={itemId:t.itemId,slotId:e,stackIndex:t.stackIndex,fit:a};if(!c)return o.set(t.itemId,{...d,status:"unplaced",why:"slot-absent",seat:null,shrunk:!1});if(!h)return o.set(t.itemId,{...d,status:"unconfirmed",why:"below-unknown",seat:null,shrunk:!1});const u=t.dims?GM(t.dims,c,l,s):null;if(!u)return h=!1,o.set(t.itemId,{...d,status:"unconfirmed",why:"size-unknown",seat:null,shrunk:!1});l+=t.dims.height*u.scale,o.set(t.itemId,{...d,status:"seated",seat:u,shrunk:u.scale<1})})}return e.items.map(t=>o.get(t.itemId))}(n,a).map(t=>[t.itemId,t]));for(const[e,s]of c){const i=l.get(s),r=n?jM(i.slotId):null,a=r?zM(n,r):null;o.set(e,{slotId:i.slotId,stackIndex:i.stackIndex,status:i.status,...i.why?{why:i.why}:{},fit:i.fit,outside:!1,anchorId:a?.anchorId??null,inSlot:i.seat,inAnchor:a&&"unplaced"!==i.status?bk(a,i.seat):null,shrunk:i.shrunk,dims:t.itemDimsOf?.(e)??null})}for(const[e,s]of r){const i=n?jM(e):null,r=i?zM(n,i):null;r&&vk(t,e,r,s,o,NM)}return o}class xk{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const wk=new xk,Mk=[{id:"__default__",maxCount:1/0}];function Sk(t){const e={id:RM({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function Ak(t,e,n){const s=t.itemTypeOf?t.itemTypeOf(n):n?.state?.type??n?.type;return e.accepts?!!s&&e.accepts.includes(s):!e.allowedTypes?.length||!!s&&e.allowedTypes.includes(s)}function kk(t){var e;return e=class extends t{get slotLayout(){}get effectiveLayout(){const t=this.slotLayout,e=this.state?.slotLayout,n=this.slotAnchors(),s=n.join("\n"),i=this.__effectiveLayout;if(i&&i.declared===t&&i.override===e&&i.anchors===s)return i.value;const o=dk(t,e,n);return this.__effectiveLayout={declared:t,override:e,anchors:s,value:o},o}slotAnchors(){return[wM]}anchorObject3D(t){const e=this._realObject?.object3d;return t===wM&&e?function(t){let e=t.userData.itemAnchor;if(!e||e.parent!==t){const n=new w.Group;n.name="item-anchor";const s=n.updateMatrix.bind(n);n.updateMatrix=()=>{const t=n.parent?.scale;t&&n.scale.set(1/(t.x||1),1/(t.y||1),1/(t.z||1)),s()},t.add(n),t.userData.itemAnchor=n,e=n}return e.updateMatrix(),e}(e):null}outsideSlots(){return[]}itemTypeOf(t){const e=Wl(this);if(e)return Yl(e,t)?.code??null;const n=t?.state?.type??t?.type;return"string"==typeof n&&n?n:null}get mmPerSceneUnit(){return rh(this).mmPerUnit}itemDimsOf(t){const e=pk(t,this.mmPerSceneUnit);return e||(Wl(this)?null:Pv(t))}itemShownDimsOf(t,e,n){if(!Wl(this))return null;const{width:s,depth:i,height:o}=e.allowed;if(![s,i,o].every(t=>Number.isFinite(t)&&t>0))return Pv(t);return{width:s,depth:i,height:o/(Number.isFinite(e.stackLimit)&&e.stackLimit>0?e.stackLimit:1)}}itemSeatOf(t,e){const n=e??t?.[_v];if("string"!=typeof n||!n)return null;return _k(this,t?.[_v]===n&&this._items?.includes(t)?void 0:{item:t,slotId:n}).get(t)??null}get slots(){const t=this.effectiveLayout.layout;if(!t)return[];const e=[];for(const n of $M(t)){const s=zM(t,n);s&&e.push(Sk(s))}return e}slotById(t){const e=this.outsideSlots().find(e=>e.id===t);if(e)return{id:e.id,maxCount:1/0};const n=this.effectiveLayout.layout;if(n){const e=jM(t),s=e?zM(n,e):null;return s?Sk(s):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,s){const i=this.effectiveLayout.layout,o=i?jM(t):null,r=o?zM(i,o):null,a=r?UM(e,r,n,s):null;return a?{...a,anchorId:r.anchorId}:null}get arrangementStrategy(){return wk}canReceive(t,e){const n=null!==(void 0!==e?.slotId?this._slotIfAvailable(this.slotById(e.slotId),t):this.findSlot(t));return ep.log({role:"target",contract:"canReceive",component:this,args:{carrier:yv(t)},result:n}),n}findSlot(t){const e=this.slots.length?this.slots:Mk;for(const n of e){if(!Ak(this,n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),s=this._countOccupied(n.id);if(!(s>=e))return ep.log({role:"target",contract:"findSlot",component:this,args:{carrier:yv(t)},result:{slotId:n.id,occupied:s,max:e}}),n}return ep.log({role:"target",contract:"findSlot",component:this,args:{carrier:yv(t)},result:null}),null}acceptanceRotation(t,e){}deliveryWorldRotation(t){const e=this.acceptanceRotation?.(t);if(!e)return;const n=this._realObject?.object3d;if(!n)return;n.updateWorldMatrix(!0,!1);const s=new w.Quaternion;n.getWorldQuaternion(s);const i=new w.Quaternion(e.x,e.y,e.z,e.w);return s.clone().multiply(i)}deliveryWorldPosition(t){const e=this._realObject,n=e?.object3d;if(!n)return;n.updateWorldMatrix(!0,!1);const s=new w.Vector3;n.getWorldPosition(s);const i=this._receivingSurfaceLocalY();if(null!==i){const t=new w.Vector3(0,i,0);return n.localToWorld(t),{x:s.x,y:t.y,z:s.z}}return{x:s.x,y:s.y,z:s.z}}attachPointFor(t,e){const n=e?.slotId??t?.[_v];if(!n)return null;if("none"!==this.effectiveLayout.status||this.outsideSlots().length){const e=this.itemSeatOf(t,n),s=e?.anchorId&&e.inAnchor?this.anchorObject3D(e.anchorId):null;if(!e||!s)return null;const i=this.mmPerSceneUnit,o=e.inAnchor;return{attach:s,localPosition:{x:o.position.x/i,y:o.position.y/i,z:o.position.z/i},localRotation:{x:0,y:o.rotation*Math.PI/180,z:0},carryPolicy:"slot",displayScale:o.scale,slotId:n,seat:e}}const s=this.slots.find(t=>t.id===n);return s?{position:s.localPosition??{x:0,y:0,z:0},rotation:s.localRotation??{x:0,y:0,z:0},slotId:s.id}:null}placementFor(t,e={}){const n=t&&"object"==typeof t&&"state"in t?t:void 0,s=n?n.state??{}:t??{},i={width:Number(s.width)||0,height:Number(s.height)||0,depth:Number(s.depth)||0},o=e.slot??this.slots.find(t=>{const e=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<e});if(!o)return null;const r=e.index??this._countOccupied(o.id),a=e.occupantCount??r,c=this.arrangementStrategy.positionAt(r,o,a,n??{state:{...i}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+i.width/2-l/2,u=c.y+i.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-i.depth/2:i.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:o.localPosition&&Number.isFinite(o.localPosition.z)?o.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??i,o)??void 0;return b?{position:{x:d,y:y,z:u},rotation:b}:{position:{x:d,y:y,z:u}}}_zPosFromSeatY(t,e,n){const s=this._realObject,i=s?.receivingSurfaceY??0,o=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===i&&!o)return null;const r=Number(e)||0,a=s?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-r/2:r/2)+(s?.geometricOffsetY??0)-i}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!Ak(this,t,e))return null;const n=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<n?t:null}_countOccupied(t){const e=this._items;if(e)return e.filter(e=>e?.[_v]===t).length;const n=this.components;return n?n.filter(e=>e.parent===this&&e[_v]===t).length:0}},e.__hasCapacity=!0,e}function Ek(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,o=t.height??0;if(i<=0||o<=0)return[];const r="number"==typeof t.rotation?t.rotation:0,a=Math.cos(r),c=Math.sin(r),l=n+i/2,h=s+o/2,d="inbound"===e?-1:1;return[{lx:-i/2,lz:0,odx:-1,odz:0},{lx:i/2,lz:0,odx:1,odz:0},{lx:0,lz:-o/2,odx:0,odz:-1},{lx:0,lz:o/2,odx:0,odz:1}].map(t=>{var e,n;return{worldPos:(e=t.lx,n=t.lz,{x:l+e*a-n*c,z:h+e*c+n*a}),direction:{x:d*(t.odx*a-t.odz*c),z:d*(t.odx*c+t.odz*a)},halfSpan:0!==t.odx?o/2:i/2}})}function Tk(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,o=t.height??0;if(i<=0||o<=0)return{inbounds:[],outbounds:[]};const r="number"==typeof t.rotation?t.rotation:0,a=e??"reverse"===t.status,c="vertical"===t.orientation||"horizontal"!==t.orientation&&i<o,l=n+i/2,h=s+o/2,d=c?o/2:i/2,u=c?0:1,p=c?1:0,f=Math.cos(r),m=Math.sin(r),g=(t,e)=>({x:l+t*f-e*m,z:h+t*m+e*f}),y=c?{lx:0,lz:-d}:{lx:-d,lz:0},b=c?{lx:0,lz:d}:{lx:d,lz:0},v=g(y.lx,y.lz),_=g(b.lx,b.lz),x={x:u*f-p*m,z:u*m+p*f},w=Math.hypot(x.x,x.z)||1,M={x:x.x/w,z:x.z/w},S={x:-M.x,z:-M.z},A=(c?i:o)/2;return a?{inbounds:[{worldPos:_,direction:S,halfSpan:A}],outbounds:[{worldPos:v,direction:S,halfSpan:A}]}:{inbounds:[{worldPos:v,direction:M,halfSpan:A}],outbounds:[{worldPos:_,direction:M,halfSpan:A}]}}function Ck(t){const e=t.left??0,n=t.top??0,s=t.width??0,i=t.height??0;if(s<=0||i<=0)return null;const o="number"==typeof t.rotation?t.rotation:0,r="vertical"===t.orientation||"horizontal"!==t.orientation&&s<i,a=e+s/2,c=n+i/2,l=r?i/2:s/2,h=Math.cos(o),d=Math.sin(o),u=(t,e)=>({x:a+t*h-e*d,z:c+t*d+e*h});return{start:r?u(0,-l):u(-l,0),end:r?u(0,l):u(l,0)}}function Ok(t){const e=t.cx??0,n=t.cy??0,s=Math.abs(t.rx??100),i=Math.abs(t.ry??100),o=t.ratio??50,r=(s+s*o/100)/2,a=(i+i*o/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(s<=0||i<=0)return{inbounds:[],outbounds:[]};const d={x:e+r*Math.sin(c),z:n-a*Math.cos(c)},u={x:e+r*Math.sin(l),z:n-a*Math.cos(l)},p={x:Math.cos(c),z:Math.sin(c)},f={x:Math.cos(l),z:Math.sin(l)};return h?{inbounds:[{worldPos:u,direction:{x:-f.x,z:-f.z}}],outbounds:[{worldPos:d,direction:{x:-p.x,z:-p.z}}]}:{inbounds:[{worldPos:d,direction:p}],outbounds:[{worldPos:u,direction:f}]}}function Pk(t){const e=Tk(t),n=e.outbounds[0];if(!n)return{inbounds:Ek(t,"inbound"),outbounds:[]};const s=Ek(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,s=t.worldPos.z-n.worldPos.z;return Math.hypot(e,s)>1}),i=n.direction,o=[];for(const t of s){const e=t.direction.x*i.x+t.direction.z*i.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+i.x,s=t.direction.z+i.z,r=Math.hypot(n,s)||1;o.push({worldPos:t.worldPos,direction:{x:n/r,z:s/r},halfSpan:t.halfSpan})}return{inbounds:[...s,...o],outbounds:e.outbounds}}function Ik(t,e,n={}){const s=n.distance??5,i=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<i)return!1;const o=t.worldPos.x-e.worldPos.x,r=t.worldPos.z-e.worldPos.z;if("number"==typeof t.halfSpan&&"number"==typeof e.halfSpan){const n=t.direction.x,i=t.direction.z;if(Math.abs(o*n+r*i)>s)return!1;const a=Math.abs(o*-i+r*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(o,r)<=s}function Dk(t,e,n,s=0){const i=n.width??0,o=n.height??0;if(i<=0||o<=0)return!1;const r=(n.left??0)+i/2,a=(n.top??0)+o/2,c="number"==typeof n.rotation?n.rotation:0,l=Math.cos(-c),h=Math.sin(-c),d=t-r,u=e-a,p=d*l-u*h,f=d*h+u*l;return Math.abs(p)<=i/2+s&&Math.abs(f)<=o/2+s}function zk(t,e,n){const s=n.width??0,i=n.height??0;if(s<=0||i<=0)return 1/0;const o=(n.left??0)+s/2,r=(n.top??0)+i/2;let a=t.x-o,c=t.z-r,l=e.x,h=e.z;const d="number"==typeof n.rotation?n.rotation:0;if(0!==d){const t=Math.cos(-d),e=Math.sin(-d),n=a*e+c*t,s=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=s}const u=s/2,p=i/2;let f=-1/0,m=1/0;if(Math.abs(l)<1e-9){if(a<-u||a>u)return 1/0}else{const t=(-u-a)/l,e=(u-a)/l;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}if(Math.abs(h)<1e-9){if(c<-p||c>p)return 1/0}else{const t=(-p-c)/h,e=(p-c)/h;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}return m<f?1/0:f>=0?f:m>=0?Math.min(-f,m):-m}function Rk(t,e,n,s=6){return!!Dk(t.worldPos.x,t.worldPos.z,e,s)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function jk(t,e,n){return t.outbounds.map(t=>{const s=[];for(const i of e){let e=null;for(const s of i.topology.inbounds){if(!Ik(t,s,n))continue;const i=t.worldPos.x-s.worldPos.x,o=t.worldPos.z-s.worldPos.z,r=Math.hypot(i,o);(null===e||r<e)&&(e=r)}if(null===e&&i.bounds){const s=i.topology.outbounds[0]?.direction,o=!(i.topology.outbounds&&i.topology.outbounds.length)?n?.sinkMargin??30:6;if(Rk(t,i.bounds,s,o)){const n=zk(t.worldPos,t.direction,i.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(i.bounds.left??0)+(i.bounds.width??0)/2,s=(i.bounds.top??0)+(i.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-s)+1e3}}}null!==e&&s.push({id:i.id,dist:e})}return 0===s.length?null:(s.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),s[0].id)})}function $k(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const s=new Map,i=new Set;for(const n of t){const o=t.filter(t=>t.id!==n.id),r=jk(n.topology,o,e);s.set(n.id,r);for(const t of r)null!=t&&i.add(t)}const o=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const o=s.get(t)??[];o.includes(e)||(o.push(e),s.set(t,o),i.add(e))};for(const e of t)if(e.links){for(const t of e.links.downstream??[])o(e.id,t);for(const t of e.links.upstream??[])o(t,e.id)}const r=new Set,a=new Set;for(const e of t){(s.get(e.id)??[]).some(t=>null!=t)||r.add(e.id),i.has(e.id)||a.add(e.id)}return{nodes:n,out:s,sinks:r,sources:a}}function Lk(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const s=new Set([e]);for(const i of function(t,e,n){const s=n.get(e);if(s)return s;const i=new Set,o=[e],r=new Set([e]);for(;o.length;){const e=o.shift();for(const n of t.out.get(e)??[])null!=n&&(i.add(n),r.has(n)||(r.add(n),o.push(n)))}return n.set(e,i),i}(t,e,n))s.add(i);return s})}function Fk(t,e,n,s){return e===n?0:function(t,e,n){const s=n.get(e);if(s)return s;const i=new Map([[e,0]]),o=[e];for(;o.length;){const e=o.shift(),n=i.get(e);for(const s of t.out.get(e)??[])null==s||i.has(s)||(i.set(s,n+1),o.push(s))}return n.set(e,i),i}(t,e,s).get(n)??1/0}function Nk(t,e,n){const s=t.out.get(e)??[],i=new Map,o=[];for(let e=0;e<s.length;e++){const r=s[e];if(null==r)continue;const a=r===n?0:Fk(t,r,n,i);a!==1/0&&o.push({i:e,hops:1+a})}return o.sort((t,e)=>t.hops-e.hops||t.i-e.i),o.map(t=>t.i)}function Hk(t,e,n){const s=Nk(t,e,n);return s.length?s[0]:-1}function Bk(t,e,n){return e===n||Nk(t,e,n).length>0}function Gk(t,e){const n=new Set;for(const s of Lk(t,e))for(const e of s)t.sinks.has(e)&&n.add(e);return n}function Uk(t,e,n){return Vk(t,e,n).map(t=>t.index)}function Vk(t,e,n){const s=n instanceof Set?n:new Set(n);if(0===s.size)return[];const i=t.out.get(e)??[],o=new Map,r=[...s].sort(),a=[];for(let e=0;e<i.length;e++){const n=i[e];if(null==n)continue;let s=1/0,c="";for(const e of r){const i=1+(n===e?0:Fk(t,n,e,o));i<s&&(s=i,c=e)}s!==1/0&&a.push({index:e,hops:s,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function Wk(t,e={}){const n=[],s=e.loopCapableIds??new Set,i=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const s=t.nodes.get(e);if(!s||!s.topology.outbounds?.length)continue;const i=(t.out.get(e)??[]).some(t=>null!=t);i||n.push({severity:"error",code:"orphan-source",nodeId:e,message:`source 노드 "${e}" 가 outgoing edge 0 — 아무 데도 carrier 를 보낼 수 없음`})}for(const e of[...t.nodes.keys()].sort()){const s=(t.out.get(e)??[]).some(t=>null!=t);s||(i.has(e)||t.sources.has(e)||n.push({severity:"error",code:"dead-end",nodeId:e,message:`노드 "${e}" 가 outgoing 0 인데 RoutingTarget 자격 없음 — routing 미정의 종착`}))}const o=function(t){const e=[],n=[...t.nodes.keys()].sort(),s=new Set,i=[],o=new Set,r=n=>{s.add(n),i.push(n),o.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(o.has(a)){const t=i.indexOf(a),n=i.slice(t),s=n.indexOf([...n].sort()[0]),o=[...n.slice(s),...n.slice(0,s)],r=o.join("→");e.some(t=>t.join("→")===r)||e.push(o)}else s.has(a)||r(a);i.pop(),o.delete(n)};for(const t of n)s.has(t)||r(t);return e.sort((t,e)=>t[0].localeCompare(e[0])||t.length-e.length),e}(t);for(const t of o){const e=t.some(t=>s.has(t));e||n.push({severity:"error",code:"cycle",cycle:t,message:`의도 cycle 자격 (isLoop) 없는 cycle: ${t.join(" → ")} → ${t[0]}`})}const r=e.routingWeights;if(r)for(const[t,e]of[...r].sort((t,e)=>t[0].localeCompare(e[0])))(!Number.isFinite(e)||e<=0)&&n.push({severity:"warning",code:"invalid-weight",nodeId:t,message:`RoutingTarget "${t}" 의 routingWeight=${e} — weight ≤ 0 비정상, weight 정책에서 제외됨`});const a=new Set;for(const e of t.out.values())for(const t of e)null!=t&&a.add(t);for(const e of[...i].sort())t.nodes.has(e)&&(a.has(e)||n.push({severity:"warning",code:"unreachable-target",nodeId:e,message:`RoutingTarget "${e}" 에 incoming edge 0 — 누구도 이쪽으로 carrier 를 보내지 않음`}));return n.sort((t,e)=>t.code!==e.code?t.code.localeCompare(e.code):(t.nodeId??"").localeCompare(e.nodeId??"")),n}function Yk(t,e){if(!t)return[];const n=[],s=new Set,i=t=>{if(!t||s.has(t))return;if(s.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,s=t.refid??t.state?.refid,i="string"==typeof e&&e.length>0?e:null!=s?String(s):void 0;if(i)try{const e=t.getSegmentTopology(),s=t.state??{},o={left:s.left,top:s.top,width:s.width,height:s.height,rotation:s.rotation};e&&n.push({id:i,topology:e,bounds:o})}catch{}}const o=t?.components;if(Array.isArray(o))for(const t of o)i(t)};return i(t),n}function qk(t,e){const n=t.state?.targetRef??t.state?.downstreamRef;if("string"==typeof n&&n.length>0)return n;if("function"!=typeof t.getSegmentTopology)return null;const s=t.getSegmentTopology();if(!s||0===s.outbounds.length)return null;const i=Yk(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),o=jk(s,i,e);for(const t of o)if(t)return t;return null}function Xk(t){return!!t&&"function"==typeof t.routingConstraints}function Kk(t){return!!t&&"function"==typeof t.acceptedCarrierData}function Jk(t,e=16){const n=[],s=t.parent??t.rootModel??t.root;if(!s)return n;const i=qk(t);if(!i)return n;const o=tE(s,i);if(!o)return n;const r=[{segment:o,accumulated:{},pathIds:[i],visited:new Set([i])}];for(;r.length>0;){const t=r.shift();if(t.pathIds.length>e)continue;const i=Xk(t.segment)?t.segment.routingConstraints():null;if(i&&i.length>0)for(const e of i)for(const i of e.candidates){const o=Qk(t.accumulated,i);if(!o)continue;const a=Zk(t.segment,e.portId,s);a&&!t.visited.has(a.state?.id??"")?r.push({segment:a,accumulated:o,pathIds:[...t.pathIds,a.state?.id??"?"],visited:new Set([...t.visited,a.state?.id??""])}):n.push({data:o,weight:1,pathIds:[...t.pathIds,`${e.portId}`],destination:e.portId})}else{if(Kk(t.segment)){const e=t.segment.acceptedCarrierData(),s=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:s});else for(const i of e){const e=Qk(t.accumulated,i);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:s})}continue}const e=qk(t.segment);if(!e||t.visited.has(e)){n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:t.pathIds[t.pathIds.length-1]});continue}const i=tE(s,e);if(!i)continue;r.push({segment:i,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function Qk(t,e){const n={...t};for(const[t,s]of Object.entries(e)){if(t in n&&n[t]!==s)return null;n[t]=s}return n}function Zk(t,e,n){if("straight"===e&&t.state?.downstreamRef)return tE(n,t.state.downstreamRef);const s=tE(n,e);if(s)return s;const i=qk(t);return i?tE(n,i):null}function tE(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,s=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const i=t.components;if(Array.isArray(i))for(const t of i){const e=s(t);if(e)return e}return null};return s(t)}function eE(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function nE(t,e,n=5,s=[],i=n){const o=t.length,r=new Array(o).fill(void 0),a=new Set,c=(e,n)=>"start"===n?t[e].start:t[e].end,l=[],h=new Map,d=[],u=new Map;for(const t of s){const e=Array.isArray(t),n=e?t:t.positions,s=e?void 0:t.kind;if(!n.length)continue;const i=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:i});s&&u.set(i,s)}const p=(t,e)=>{const s=c(t,e),i=h.get(`${t}:${"end"===e?"start":"end"}`),o=[];for(const t of d)eE(t.pos,s)<=n&&!o.includes(t.pt)&&o.push(t.pt);for(let t=0;t<l.length;t++)eE(l[t].pos,s)<=n&&!o.includes(t)&&o.push(t);let r=o.find(t=>t!==i)??-1;r<0&&(r=l.length,l.push({pos:s,members:[]})),l[r].members.push({seg:t,end:e}),h.set(`${t}:${e}`,r)};for(let t=0;t<o;t++)p(t,"start"),p(t,"end");const f=new Set,m=new Set,g=new Set;{const t=t=>{let e=-1,n=1/0;for(let s=0;s<l.length;s++){const i=eE(l[s].pos,t);i<n&&(n=i,e=s)}for(const s of d){const i=eE(s.pos,t);i<n&&(n=i,e=s.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:s}=t(n.pos);e>=0&&s<=i&&(f.add(e),("source"===n.kind?m:g).add(e))}}for(const[t,e]of u)f.add(t),("source"===e?m:g).add(t);const y=(t,e)=>"end"===e!==r[t],b=[],v=(e,n)=>{if(void 0===r[e])return r[e]=n,void b.push(e);r[e]!==n&&a.add(t[e].id)},_=t=>{for(const e of["start","end"]){const n=h.get(`${t}:${e}`);if(void 0===n)continue;const s=l[n];if(2!==s.members.length||f.has(n))continue;const i=s.members[0],o=i.seg===t&&i.end===e?s.members[1]:i;if(o.seg===t)continue;const a="end"===e!==r[t],c="end"===o.end!==!a;v(o.seg,c)}},x=()=>{for(;b.length;)_(b.shift())},w=t=>{let e=-1,n="start",s=1/0;for(let i=0;i<o;i++)for(const o of["start","end"]){const r=eE(c(i,o),t.pos);r<s&&(s=r,e=i,n=o)}if(e<0||s>i)return;const r="source"===t.kind?"end"===n:"start"===n;v(e,r)};for(const t of e)"source"===t.kind&&w(t);x();for(const t of e)"sink"===t.kind&&w(t);x();let M=!0;for(;M;){M=!1;for(const t of l){if(t.members.length<3)continue;const e=t.members.filter(t=>void 0===r[t.seg]);if(1!==e.length)continue;let n=0,s=0;for(const e of t.members)void 0!==r[e.seg]&&(y(e.seg,e.end)?n++:s++);const i=e[0];let o;0===s&&n>0?o="end"===i.end:0===n&&s>0&&(o="start"===i.end),void 0!==o&&(r[i.seg]=o,b.push(i.seg),x(),M=!0)}}if(r.some(t=>void 0===t)&&m.size>0&&g.size>0){const t=t=>{const e=new Array(l.length).fill(1/0),n=[];for(const s of t)e[s]=0,n.push(s);for(;n.length;){const t=n.shift();for(const s of l[t].members){const i=h.get(`${s.seg}:${"start"===s.end?"end":"start"}`);void 0!==i&&e[i]>e[t]+1&&(e[i]=e[t]+1,n.push(i))}}return e},e=t(m),n=t(g);for(let t=0;t<o;t++){if(void 0!==r[t])continue;const s=h.get(`${t}:start`),i=h.get(`${t}:end`);if(void 0===s||void 0===i)continue;if(l[s].members.length<2||l[i].members.length<2)continue;if(e[s]===1/0||e[i]===1/0||n[s]===1/0||n[i]===1/0)continue;let o;e[s]!==e[i]?o=e[s]<e[i]:n[s]!==n[i]&&(o=n[i]<n[s]),void 0!==o&&(r[t]=!o,b.push(t))}x()}const S=new Map;for(let e=0;e<o;e++)S.set(t[e].id,void 0===r[e]?"unknown":r[e]?"reverse":"forward");return{directions:S,conflicts:[...a]}}function sE(...t){}function iE(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function oE(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}function*rE(t){if(!t)return;("function"==typeof t.getSegmentTopology||t.flowOrientable)&&(yield t);const e=t.components;if(Array.isArray(e))for(const t of e)yield*rE(t)}function aE(t,e,n){const s=e.width??0,i=e.height??0;if(s<=0||i<=0)return!1;const o=(e.left??0)+s/2,r=(e.top??0)+i/2,a="number"==typeof e.rotation?e.rotation:0,c=t.x-o,l=t.z-r,h=Math.cos(-a),d=Math.sin(-a),u=c*h-l*d,p=c*d+l*h;return Math.abs(u)<=s/2+n&&Math.abs(p)<=i/2+n}function cE(t){const e=[],n=[],s=[],i=[];for(const o of rE(t)){const t=oE(o);if(!t)continue;if(o.flowOrientable){const n=Ck(o.state??{});n&&e.push({id:t,start:n.start,end:n.end});continue}if("function"==typeof o.openings){const t=o.state??{};(t.width??0)>0&&(t.height??0)>0&&i.push(t);continue}let r;try{r=o.getSegmentTopology()}catch{continue}if(!r)continue;const a=r.inbounds??[],c=r.outbounds??[],l="function"==typeof o.routingDestination;if(0===a.length&&c.length>0)for(const t of c)n.push({pos:{x:t.worldPos.x,z:t.worldPos.z},kind:"source"});else if(a.length>0&&(0===c.length||l))for(const t of a)n.push({pos:{x:t.worldPos.x,z:t.worldPos.z},kind:"sink"});else if(a.length>0||c.length>0){const t=[];for(const e of a)t.push({x:e.worldPos.x,z:e.worldPos.z});for(const e of c)t.push({x:e.worldPos.x,z:e.worldPos.z});t.length&&s.push({positions:t})}}for(const t of i){const i=[];for(const n of e)for(const e of[n.start,n.end])aE(e,t,16)&&i.push(e);let o=!1,r=!1;for(const e of n)aE(e.pos,t,16)&&("sink"===e.kind?o=!0:r=!0);const a=o&&!r?"sink":r&&!o?"source":void 0;(i.length>=2||a&&i.length>=1)&&s.push({positions:i,kind:a})}if(0===e.length||0===n.length)return new Map;return nE(e,n,8,s,60).directions}function lE(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:cE(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const s=oE(t),i=s?n.map.get(s):void 0;return"reverse"===i||"forward"!==i&&void 0}function hE(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function dE(t,e,n,s){if(!t||!e)return null;const i=[],o=t=>{if(!t||t===s)return;if(og(t,e)&&hE(t)){const e=function(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}(t);e&&i.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const r=t.components;if(Array.isArray(r))for(const t of r)o(t)};return o(t),0===i.length?null:(i.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),i[0])}function uE(t){return!!t&&"function"==typeof t.routingDestination}function pE(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}function*fE(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*fE(t)}function mE(t){const e=[],n=new Map,s=new Map,i=new Set,o=[];for(const r of fE(t)){"function"==typeof r?.registerWithHost&&o.push(r);const t="function"==typeof r?.getSegmentTopology,a="function"==typeof r?.routingLinks?r.routingLinks():void 0,c=!(!a||!((a.downstream?.length??0)>0||(a.upstream?.length??0)>0));if(!(t||uE(r)||c||hE(r)))continue;const l=pE(r);if(!l)continue;let h={inbounds:[],outbounds:[]};if(t){try{h=r.getSegmentTopology()}catch{continue}if(!h)continue}const d=r.state??{},u={left:d.left,top:d.top,width:d.width,height:d.height,rotation:d.rotation};if(e.push({id:l,topology:h,bounds:u,links:a}),s.set(l,r),uE(r)){i.add(l);const t=r.routingDestination();if("string"==typeof t&&t.length>0){const e=n.get(t)??[];e.push(l),n.set(t,e)}}}return{nodes:e,destToSinks:n,components:s,routingTargetIds:i,stationClients:o}}function gE(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:s,components:i,routingTargetIds:o,stationClients:r}=mE(t),a=$k(n);!function(t,e){if(!t)return;const n=t=>{if(!t)return;"function"==typeof t.clearStations&&t.clearStations();const e=t.components;if(Array.isArray(e))for(const t of e)n(t)};n(t);const s=[...e].sort((t,e)=>{const n=pE(t)??"",s=pE(e)??"";return n.localeCompare(s)});for(const e of s){const n=e.declaredHostRef?.();let s=null;if(n&&(s=t.findById?.(n)??null),!s){const n=e.hostCapability?.(),i=e.hostFacingPoint?.();n&&i&&(s=dE(t,n,i,e)?.component??null)}s&&"function"==typeof e.registerWithHost&&e.registerWithHost(s)}const i=e=>{if(!e)return;if(hE(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const s=t.findById?.(n);s&&e.registerDivertStation(n,s)}const n=e.components;if(Array.isArray(n))for(const t of n)i(t)};i(t)}(t,r);const c=new Set;for(const[t,e]of i){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of o){const e=i.get(t);if("function"==typeof e?.routingWeight){const n=e.routingWeight();"number"==typeof n&&(!Number.isFinite(n)||n<=0)&&l.set(t,n)}}const h=Wk(a,{routingTargetIds:o,loopCapableIds:c,routingWeights:l});if(h.length>0&&"undefined"!=typeof console){const t=h.filter(t=>"error"===t.severity),e=h.filter(t=>"warning"===t.severity);t.length>0?console.warn(`[FlowGraph] ${t.length} error(s) / ${e.length} warning(s):`,h):console.info(`[FlowGraph] ${e.length} warning(s):`,h)}e={graph:a,destToSinks:s,components:i,issues:h},t.__flowGraph=e}return e}function yE(t){return gE(t)?.issues??[]}function bE(t){const e=gE(t);return e&&e.graph.nodes.size>0?e.graph:null}function vE(t,e){return gE(t)?.destToSinks.get(e)??[]}function _E(t,e){return gE(t)?.components.get(e)}function xE(t){const e=gE(t);return e?[...e.destToSinks.keys()]:[]}function wE(t){return pE(t)}function ME(t){const e="number"==typeof t?.inventoryCount?t.inventoryCount:"function"==typeof t?.size?t.size():0,n=t?.state?.capacity;return"number"==typeof n&&n>0?e/n:e}function SE(t,e,n,s,i){if(1===s.length)return s[0];switch(t){case"index":default:return s[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),s[t%s.length]}case"weight":{const t=s.map(t=>function(t){if("function"==typeof t?.routingWeight){const e=t.routingWeight();if("number"==typeof e&&Number.isFinite(e)&&e>0)return e}return 1}(i.get(t.target))),o=t.reduce((t,e)=>t+e,0);if(o<=0)return s[0];const r=n.counters.get(e)??0;n.counters.set(e,r+1);let a=r%o;for(let e=0;e<s.length;e++){if(a<t[e])return s[e];a-=t[e]}return s[s.length-1]}case"utilization":{let t=1/0,e=s[0];for(const n of s){const s=ME(i.get(n.target));s<t&&(t=s,e=n)}return e}}}function AE(t,e,n){const s=t?.root;if(!s)return null;const i=e?.state?.meta?.destination;if("string"!=typeof i||0===i.length)return null;const o=gE(s);if(!o||0===o.graph.nodes.size)return null;const r=pE(t);if(!r)return null;let a=o.destToSinks.get(i)??[];0===a.length&&(a=[i]);const c=Vk(o.graph,r,a);if(0===c.length)return null;const l=o.graph.out.get(r)??[],h=c.filter(t=>{const n=l[t.index],s=n?o.components.get(n):null;return!s||"function"!=typeof s.canReceive||s.canReceive(e)});if(0===h.length)return l[c[0].index]??null;const d=n?.policy??function(t,e){const n=t?.state?.balancingPolicy;if(n)return n;const s=e?.state?.routingBalancingPolicy;return s||"round-robin"}(t,s),u=SE(d,r,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(s),h,o.components);return l[u.index]??null}cg({name:"Capacity",description:"Item 을 *보유(keep)* 하는 측면 — slot 위상 / 수용 판정(canReceive/findSlot) / 3D 안착(placementFor/attachPointFor/acceptanceRotation) / delivery 좌표 질의 / 점유 수. 이동(receive/dispatch 등)은 Transferable 소관.",methods:["get slotLayout","get slots","slotById","slotSeatTransform","get arrangementStrategy","canReceive","findSlot","placementFor","attachPointFor","acceptanceRotation","deliveryWorldRotation","deliveryWorldPosition","_countOccupied"],sourceFile:"src/items/capacity-mixin.ts"}),cg({name:"PlacementSurface",description:"carrier 가 holder 위 *정확히 어디에 앉는가* 의 단일 진입점 — placementFor(carrier, ctx) → SeatingPose (holder object3d local frame, 순수 함수). I1 접촉 (밑면 = 받침 상면) / I2 frame-explicit (parent-child 비가정 — Sovereign handover 와 reparent 양쪽이 같은 값 소비) / I3 순수성 / I4 per-carrier 치수. default 구현은 Capacity(FlowNode) 가 기존 receivingSurfaceY + ArrangementStrategy + acceptanceRotation 합성과 수치 동일하게 제공.",methods:["placementFor"],models:["CarrierDims","PlacementContext","SeatingPose"],sourceFile:"src/items/capacity-mixin.ts"});try{globalThis.__operatoBuildFlowGraph=(t,e)=>{try{return e?.force&&t&&delete t.__flowGraph,bE(t)}catch{return null}}}catch{}function kE(t,e,n){const s=AE(t,e,n);if(null==s)return null;const i=t?.root,o=_E(i,s)??i?.findById?.(s)??null;return o?{targetId:s,component:o,origin:"explicit"}:null}function EE(t){const e=t?.root,n=bE(e),s=wE(t);if(!n||!s)return null;const i=(n.out.get(s)??[]).find(Boolean);if(!i)return null;const o=_E(e,i)??e?.findById?.(i)??null;return o?{id:i,component:o}:null}function TE(t){const e=wE(t);return e?CE(t?.root,e):[]}function CE(t,e){if(!t||!e)return[];const n=bE(t);if(!n)return[];const s=new Set;for(const i of Gk(n,e)){const e=_E(t,i);if(uE(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&s.add(t)}}return[...s]}function OE(t,e){if(!t||!e)return[];const n=bE(t);if(!n)return[];const s=new Map;for(const t of n.out.values())for(const e of t)null!=e&&s.set(e,(s.get(e)??0)+1);const i=new Map;for(const o of Gk(n,e)){const e=_E(t,o);if(!uE(e))continue;const n=e.routingDestination();if("string"!=typeof n||0===n.length)continue;let r=null;if("function"==typeof e.routingWeight){const t=e.routingWeight();"number"==typeof t&&Number.isFinite(t)&&t>0&&(r=t)}null===r&&(r=s.get(o)??0,0===r&&(r=1)),i.set(n,(i.get(n)??0)+r)}return[...i].map(([t,e])=>({value:t,weight:e}))}function PE(t){return bE(t)}function IE(t){const e=bE(t);if(!e)return[];const n=new Set,s=new Set,i=t=>{if(!t)return;const o=wE(t);if(o&&e.nodes.has(o)){uE(t)&&n.add(o);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&s.add(o)}const r=t.components;if(Array.isArray(r))for(const t of r)i(t)};return i(t),Wk(e,{routingTargetIds:n,loopCapableIds:s})}function DE(t){if(0===t.length)return;const e=t.reduce((t,e)=>t+e.weight,0);if(e<=0)return t[Math.floor(Math.random()*t.length)].value;const n=Math.random()*e;let s=0;for(const e of t)if(s+=e.weight,n<s)return e.value;return t[t.length-1].value}const zE={next:kE,downstream:EE,reachableDestinations:TE,reachableDestinationsFrom:CE,reachableDestinationsWeightedFrom:OE,pickWeightedDestination:DE,graphFor:PE,validate:IE};function RE(t){try{t()}catch(t){Ns("[holdable] a listener of a handover failed; the handover stands",t)}}function jE(t){if(!t?.traverse||!t.matrixWorld)return null;t.updateWorldMatrix(!0,!0);const e=t.matrixWorld.clone().invert(),n=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0];return t.traverse(t=>{const i=t.isMesh?t.geometry:null;if(!i)return;i.boundingBox||i.computeBoundingBox?.();const o=i.boundingBox;if(!o)return;const r=t.matrixWorld.clone().premultiply(e),a=o.min.constructor;for(const t of[o.min.x,o.max.x])for(const e of[o.min.y,o.max.y])for(const i of[o.min.z,o.max.z]){const o=new a(t,e,i).applyMatrix4(r);[o.x,o.y,o.z].forEach((t,e)=>{n[e]=Math.min(n[e],t),s[e]=Math.max(s[e],t)})}}),Number.isFinite(n[0])?{x:s[0]-n[0],y:s[1]-n[1],z:s[2]-n[2]}:null}function $E(t){let e=0;for(let n=t;n&&!n.isRootModel?.();n=n.parent)e+=n.state?.rotation||0;return e}function LE(t){const e=t?.shownSize;return e&&[e.width,e.height,e.depth].every(Number.isFinite)?{...e}:null}function FE(t,e){if("function"!=typeof t?.toScene)return null;try{const n=t.bounds,s=t.center,i=t.toScene(s.x,s.y),o={x:i.x,y:i.y,rotation:$E(e),width:n.width,height:n.height};return Object.values(o).every(Number.isFinite)?o:null}catch{return null}}function NE(t){var e;return e=class extends t{constructor(){super(...arguments),this._items=[]}get items(){return this._items}containsItem(t){return-1!==this._items.indexOf(t)}attachPointFor(e,n){const s=t.prototype?.attachPointFor;return"function"==typeof s?s.call(this,e,n):null}addItem(t,e){if(!t||this.containsItem(t))return;const n=t.parent;if(n&&"function"==typeof n.removeItem&&n!==this&&n.removeItem(t,!0),this._items.push(t),t.parent=this,t.delegate_on?.(this),uh(this,t),!e?.silent&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}t.held?.(this)}removeItem(t,e){if(!t)return;const n=this._items.indexOf(t);if(-1!==n)if(this._items.splice(n,1),t.parent=null,t.delegate_off?.(this),this._reseatSlot(t[_v]),e)t._realObject?.setTransientDisplayScale?.(1);else{if(ph(t),function(t){const e=t?._realObject?.object3d;if(!e?.parent)return;let n=e.parent;for(;n.parent;)n=n.parent;n!==e.parent&&(n.updateWorldMatrix?.(!0,!1),e.updateWorldMatrix?.(!0,!1),n.attach(e))}(t),t._realObject?.setTransientDisplayScale?.(1,{x:1,y:1,z:1}),"function"==typeof this.trigger)try{this.trigger("release",this,t,n)}catch{}t.released?.(this)}}forEachItem(t,e){this._items.forEach(t,e)}handoverIn(t,e){if(!t)return;const n=e?.slotId,s=e?.toParent3D,i=s?null:this.attachPointFor?.(t,{slotId:n}),o=e?.animated?function(t){const e=t?._realObject?.object3d;let n=null;if(e?.parent){e.updateWorldMatrix(!0,!1);const t=e.position.clone(),s=e.quaternion.clone(),i=e.scale.clone();e.matrixWorld.decompose(t,s,i),n={position:t,quaternion:s,scale:i}}return{world3D:n,world2D:t?.parent?FE(t,t.parent):null,shown:LE(t),content:n?jE(e):null}}(t):null,r=t.parent,a=r===this?t[_v]:void 0;r&&("function"==typeof r.removeComponent&&-1!==r._components?.indexOf?.(t)&&r.removeComponent(t,!0),r!==this&&"function"==typeof r.removeItem&&-1!==r._items?.indexOf?.(t)&&r.removeItem(t,!0));const c=-1===this._items.indexOf(t);c&&(this._items.push(t),t.delegate_on?.(this)),t.parent=this,void 0!==n&&(t[_v]=n),uh(this,t);const l=!!t._realObject?.object3d;l&&this.seatHeldItem(t,{toParent3D:s,slotId:n,point:i}),void 0!==a&&a!==t[_v]&&this._reseatSlot(a),c&&RE(()=>this.trigger?.("hold",this,t,this._items.length-1)),l||this.seatHeldItem(t,{toParent3D:s,slotId:n,point:i}),RE(()=>t.held?.(this)),o&&function(t,e,n,s){const i=t.root?.transitionEffect;if(!i)return;const o=s.duration??2e3,r=s.ease??"inout",a=e._realObject?.object3d;if(n.world3D&&a?.parent){const t={pos:a.position.clone(),quat:a.quaternion.clone()},s={x:a.scale.x,y:a.scale.y,z:a.scale.z},c=a.parent;c.updateWorldMatrix(!0,!1);const l=c.matrixWorld.clone().invert(),h=a.matrixWorld.clone().compose(n.world3D.position,n.world3D.quaternion,n.world3D.scale).premultiply(l),d=a.position.clone(),u=a.quaternion.clone(),p=a.scale.clone();h.decompose(d,u,p);const f=(t,e)=>t&&e&&t>0&&e>0?t/e:1,m=n.content?jE(a):null,g=LE(e),y=n.content&&m?{x:p.x*f(n.content.x,m.x),y:p.y*f(n.content.y,m.y),z:p.z*f(n.content.z,m.z)}:{x:p.x*f(n.shown?.width,g?.width),y:p.y*f(n.shown?.depth,g?.depth),z:p.z*f(n.shown?.height,g?.height)};return void i.begin(e,{from3D:{pos:d,quat:u,fromScale:y,toScale:s},to3D:t,duration:o,ease:r,keepSuppressed:!0,placementAfter:e._realObject.placement})}const c=n.world2D?FE(e,t):null;n.world2D&&c&&i.begin(e,{fromWorld:n.world2D,toWorld:c,duration:o,ease:r})}(this,t,o,e),RE(()=>this._bumpReceived?.(t))}seatHeldItem(t,e={}){const n=t._realObject,s=n?.object3d;if(s){let i,o,r=e.toParent3D,a="world-preserve",c=1,l=null;if(!r){const n=void 0!==e.point?e.point:this.attachPointFor?.(t,{slotId:e.slotId});n?.attach&&(r=n.attach,i=n.localPosition,o=n.localRotation,a=n.carryPolicy??"world-preserve",c=n.displayScale??1,l=n.seat?.dims??null)}r&&s.parent!==r&&(r.updateWorldMatrix?.(!0,!1),s.updateWorldMatrix?.(!0,!1),r.attach(s),n.suppressTransform=!0),r&&(i&&s.position.set(i.x,i.y,i.z),"world-preserve"!==a?o?s.rotation.set(o.x,o.y,o.z):s.quaternion.identity():o&&s.rotation.set(o.x,o.y,o.z),n?.setTransientPlacement?.({policy:"carried",meta:{carryPolicy:a}}),n?.setTransientDisplayScale?.(c,function(t){if(!t?.matrixWorld)return;let e=t;for(;e.parent;)e=e.parent;t.updateWorldMatrix?.(!0,!1);const n=t.matrixWorld.elements,s=t=>Math.hypot(n[t],n[t+1],n[t+2]),i=e.scale??{x:1,y:1,z:1};return{x:s(0)/(i.x||1),y:s(4)/(i.y||1),z:s(8)/(i.z||1)}}(r)),t.takeSeatDims?.(l))}}_reseatSlot(t){if(null!=t)for(const e of this._items.slice())e?.[_v]===t&&e._realObject?.object3d&&this.seatHeldItem(e,{slotId:t})}handoverOut(t){this.removeItem(t),this._bumpDispatched?.(t)}dispose(){const t=this._items.slice();this._items.length=0;for(const e of t){ph(e);try{e.dispose?.()}catch{}}super.dispose?.()}_drawItems(t){const e=this.root?.transitionEffect;for(const t of this._items)e?.isReparenting?.(t)||t.draw?.(this.getContext?.(t))}_captureItems(t,e,n,s,i){for(let o=this._items.length-1;o>=0;o--){const r=this._items[o],a="static"===r.position?r.capture?.(t,e,i):r.capture?.(n,s,i);if(a)return a}return null}postrender(t){super.postrender?.(t);const e=this;if("popup"===e.position)return;const n=this._items;if(!n||0===n.length)return;t.save();const s=e.bounds;!e.showOverflow&&s&&(t.beginPath(),t.rect(s.left,s.top,s.width,s.height),t.clip(),t.closePath());const{left:i=0,top:o=0}=e.state??{};t.translate(i,o),this._drawItems(t),t.translate(-i,-o),t.restore()}capture(t,e,n){const s=this,i=this._items;if(i&&i.length>0&&!s.app?.isEditMode&&(!s.app||s.app.isEditMode||!s.hidden)){const i=s.fromParent?.(t,e);if(i&&s.contains?.(i.x,i.y)){const o=s.bounds,r=this._captureItems(i.x-o.left,i.y-o.top,t,e,n);if(r)return r}}return super.capture?.(t,e,n)}},e.capabilities=Object.freeze([...t.capabilities??[],"Holdable"]),e}function HE(t,e,n){return void 0!==n?t._slotIfAvailable(t.slotById(n),e):t.findSlot(e)}function BE(t){var e;return e=class extends t{reserve(t,e){const n=HE(this,t,e?.slotId);return n?{slot:n,token:Symbol("slot-reservation")}:null}release(t){}async receive(t,e={}){ep.log({role:"target",contract:"receive:enter",component:this,args:{carrier:yv(t),options:e}});const n=this.reserve(t,e);if(!n){ep.log({role:"target",contract:"receive:reject",component:this,args:{carrier:yv(t)},result:{reason:"no-slot"}}),this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:"no-slot"});const e=new Error("receive rejected: no-slot");throw e.reason="no-slot",e}this.commit(n,t,e)}commit(t,e,n={}){const s=t.slot,i=this._countOccupied(s.id),o=this.arrangementStrategy.positionAt(i,s,i,e);ep.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:i,slotId:s.id,occupantCount:i,carrier:yv(e)},result:o});const r=function(t,e,n,s,i){const o={},r=t.placementFor?.(e,{slot:n,index:s,occupantCount:s})??null;if(ep.log({role:"target",contract:"placementFor",component:t,args:{carrier:yv(e),slotId:n.id,index:s},result:r}),r){const s=e.state??{},i=t.state??{};o.left=r.position.x-(Number(s.width)||0)/2+(Number(i.width)||0)/2,o.top=r.position.z-(Number(s.height)||0)/2+(Number(i.height)||0)/2;const a=t._zPosFromSeatY(r.position.y,s.depth,n);null!==a&&(o.zPos=a),r.rotation&&vv(o,r.rotation)}else{if(i&&(o.left=i.x,o.top=i.y),0!==(t._realObject?.receivingSurfaceY??0))o.zPos=0;else if(n.localPosition&&Number.isFinite(n.localPosition.z)){const e=t._realObject?.geometricOffsetY??0;o.zPos=n.localPosition.z+e}const s=t.acceptanceRotation?.(e,n);ep.log({role:"target",contract:"acceptanceRotation",component:t,args:{carrier:yv(e),slotId:n.id},result:s}),s&&vv(o,s)}const a=t.normalizePose?.(e,n);return"function"==typeof t.normalizePose&&ep.log({role:"target",contract:"normalizePose",component:t,args:{carrier:yv(e),slotId:n.id},result:a}),a&&Object.assign(o,a),o}(this,e,s,i,o),a=e._realObject;let c,l;a?.object3d&&(a.object3d.updateWorldMatrix(!0,!1),c=new w.Vector3,l=new w.Quaternion,a.object3d.getWorldPosition(c),a.object3d.getWorldQuaternion(l));const{animated:h=!1,duration:d,ease:u}=n;if("function"==typeof this.handoverIn?this.handoverIn(e,{slotId:s.id}):(e[_v]=s.id,this.reparent?.(e,{animated:h,duration:d,ease:u})),!h&&e._realObject&&(e._realObject.suppressTransform=!1),Object.keys(r).length){try{e.setState?.(r)}catch(t){Ns("[transferable] the received item's state could not be set; the handover stands",t)}ep.log({role:"target",contract:"receive:setState",component:this,args:{carrier:yv(e),keys:Object.keys(r)}})}this.trigger("transfer-received",{type:"transfer-received",component:e,container:this,slotId:s.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),ep.log({role:"target",contract:"receive:done",component:this,args:{carrier:yv(e),slotId:s.id}})}async dispatch(t,e,n={}){const s=new op({source:this,target:e,carrier:t,options:n}),i=await s.execute();"rolled-back"!==i.phase?this.trigger("transfer-dispatched",{type:"transfer-dispatched",component:t,container:this,target:e}):this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:i.rejectReason??"rejected"})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e="rejected"){this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:e})}canAccept(t,e){const n=(()=>{const n=this.slots;if(!n.length)return{ok:!1,reason:"no-slots-defined"};if(void 0!==e?.slotId){if(!this.slotById(e.slotId))return{ok:!1,reason:"slot-absent"};const n=HE(this,t,e.slotId);return n?{ok:!0,slot:n}:{ok:!1,reason:"slot-unavailable"}}const s=this.findSlot(t);if(!s){const e=t?.state?.type??t?.type;for(const t of n)if(!t.allowedTypes?.length||!e||t.allowedTypes.includes(e))return{ok:!1,reason:"all-slots-full"};return{ok:!1,reason:"type-not-accepted"}}return{ok:!0,slot:s}})();return ep.log({role:"target",contract:"canAccept",component:this,args:{carrier:yv(t)},result:n.ok?{ok:!0,slotId:n.slot.id}:{ok:!1,reason:n.reason}}),n}accept(t,e){return this.receive(t,e)}},e.__hasTransferable=!0,e}function GE(t){var e;const n=!!t.__hasCapacity,s=!!t.__hasTransferable,i=n?t:kk(t),o=s?i:BE(i),r=[...t.capabilities??[]];n||r.push("Capacity","PlacementSurface"),s||r.push("Transferable"),r.push("Holdable","FlowNode");const a=(e=class extends(NE(o)){get isFlowNode(){return!0}containable(t){return!!t&&!0===t.isItem}get showMoveHandle(){return!1}inboundPorts(){return[]}outboundPorts(){return[]}_bumpReceived(t){const e=this.state?.received??0;this.setState?.({received:e+1})}_bumpDispatched(t){const e=this.state?.dispatched??0;this.setState?.({dispatched:e+1})}_bumpRejected(t,e){const n=this.state?.rejected??0;this.setState?.({rejected:n+1})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e){}resolveDownstream(){const t=this.state?.downstreamRef;if(!t)return[];return(this.root?.findAll?.(t)??[]).map(t=>t?.state?.id).filter(Boolean)}routingLinks(){return{downstream:this.resolveDownstream()}}},function(t,e,n){"symbol"==typeof e&&(e=e.description?"[".concat(e.description,"]"):""),Object.defineProperty(t,"name",{configurable:!0,value:n?"".concat(n," ",e):e})}(e,"FlowNodeMixed"),e.capabilities=Object.freeze(r),e.isFlowNode=!0,e);return wv(a)}function UE(t){return!!t&&!0===t.isFlowNode}cg({name:"Holdable",description:"어떤 Component 든 item(데이타바인딩 동적 물건) 을 보유하는 capability. _items + add/remove/forEach + handover + hold/release event + dispose cascade. Container(정적 _components) 와 직교 — 컨테이너 비의존.",methods:["addItem","removeItem","forEachItem","containsItem","handoverIn","handoverOut","_drawItems","_captureItems","dispose"],sourceFile:"src/components/mixins/holdable.ts"}),cg({name:"Transferable",description:"Item 을 노드 간에 옮기는 *이동(move)* 측면. 수용 트랜잭션 라이프사이클(reserve → commit → release)과 receive/accept/dispatch/route 를 제공. 보유(keep — slots/findSlot/canReceive 등)는 Capacity 소관.",methods:["reserve","commit","release","receive","accept","canAccept","dispatch","route","resolveRoute","rejectRoute"],sourceFile:"src/transfer/transferable-mixin.ts"}),cg({name:"FlowNode",description:"Flow graph 의 노드 — 구조 (inbound/outbound port + slot) + flow (route + 5-phase transfer stat). 보유(_items/handover)는 Holdable base 위임. 모든 flow 컴포넌트의 base — Storable/Mobile/Processable 의도가 위에 직교로 적용.",methods:["inboundPorts","outboundPorts","slotIds","slotAt","route","resolveRoute","rejectRoute"],models:["Port","SlotInfo","Vec3"],sourceFile:"src/flow/flow-node.ts"});const VE={x:0,y:0,z:0,w:1};function WE(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function YE(t,e){const n=t.rotation,s=e.rotation,i=e.position,o=n.w*i.x+n.y*i.z-n.z*i.y,r=n.w*i.y+n.z*i.x-n.x*i.z,a=n.w*i.z+n.x*i.y-n.y*i.x,c=-n.x*i.x-n.y*i.y-n.z*i.z,l=o*n.w+c*-n.x+r*-n.z-a*-n.y,h=r*n.w+c*-n.y+a*-n.x-o*-n.z,d=a*n.w+c*-n.z+o*-n.y-r*-n.x,u={x:n.w*s.x+n.x*s.w+n.y*s.z-n.z*s.y,y:n.w*s.y-n.x*s.z+n.y*s.w+n.z*s.x,z:n.w*s.z+n.x*s.y-n.y*s.x+n.z*s.w,w:n.w*s.w-n.x*s.x-n.y*s.y-n.z*s.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const qE={east:{axis:{x:1,y:0,z:0},yaw:0,idSuffix:"east"},west:{axis:{x:-1,y:0,z:0},yaw:Math.PI,idSuffix:"west"},south:{axis:{x:0,y:0,z:1},yaw:-Math.PI/2,idSuffix:"south"},north:{axis:{x:0,y:0,z:-1},yaw:Math.PI/2,idSuffix:"north"}};function XE(t){const{carrierWorld:e,width:n,depth:s,entryHeight:i,mountLocalY:o,approachDistance:r,sides:a,toolType:c,tolerance:l,priority:h}=t,d="number"==typeof o?{position:{x:0,y:o,z:0},rotation:{...VE}}:void 0,u=n/2,p=s/2;return a.map(t=>{const n=qE[t],s="string"==typeof c?c:c[t]??"unknown",o={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:i,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:WE(n.yaw)},a={position:{x:o.position.x+n.axis.x*r,y:i,z:o.position.z+n.axis.z*r},rotation:WE(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:s,approach:YE(e,a),engage:YE(e,o),...d?{mount:d}:{},tolerance:l,priority:h}})}function KE(t){const{carrierWorld:e,topY:n,approachDistance:s,toolType:i,mountLocalY:o,tolerance:r,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...VE}};return{id:c??"top",toolType:i,approach:YE(e,{position:{x:0,y:n+s,z:0},rotation:{...VE}}),engage:YE(e,l),..."number"==typeof o?{mount:{position:{x:0,y:o,z:0},rotation:{...VE}}}:{},tolerance:r,priority:a}}function JE(t,e){return t.filter(t=>t.toolType===e.toolType)}function QE(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,s=t.approach.position.y-e.y,i=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+s*s+i*i)}});return n.sort((t,e)=>{const n=t.f.priority??0,s=e.f.priority??0;return n!==s?n-s:t.dist-e.dist}),n[0].f}class ZE{constructor(t){this.owner=t}positionAt(t,e,n,s){if(0!==t)return null;const i=this.owner?.state?.width??0,o=this.owner?.state?.height??0,r=s?.state?.width??0,a=s?.state?.height??0;return{x:Math.max(0,(i-r)/2),y:Math.max(0,(o-a)/2),z:0}}capacity(t){return t.maxCount??1}}let tT=1;function eT(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const nT={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class sT{constructor(t=nT){this._byResource=new Map,this._byReserver=new Map,this._listeners=new Set,this._conflictLog=[],this._maxConflictLog=1e3,this._yieldPolicy=t}add(t){const e={...t,id:"res-"+tT++},n=(this._byResource.get(e.resource)??[]).filter(t=>eT(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const s=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}}),i=s.every(t=>"b-yields"===t.decision);if(i){const s=n.slice();for(const t of s)this._remove(t),this._emit({kind:"evicted",reservation:t,by:e});return this._insert(e),this._emit({kind:"added",reservation:e}),this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:s,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:s}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:s}}conflictLog(){return[...this._conflictLog]}setMaxConflictLog(t){this._maxConflictLog=Math.max(1,t)}_appendConflictLog(t){this._conflictLog.push(t),this._conflictLog.length>this._maxConflictLog&&this._conflictLog.shift()}conflicts(t,e){return(this._byResource.get(t)??[]).filter(t=>eT(t.timeWindow,e))}release(t){this._remove(t)&&this._emit({kind:"released",reservation:t})}releaseAllOf(t){const e=(this._byReserver.get(t)??[]).slice();for(const t of e)this._remove(t),this._emit({kind:"released",reservation:t});return e}forResource(t){return[...this._byResource.get(t)??[]]}forReserver(t){return[...this._byReserver.get(t)??[]]}all(){const t=[];for(const e of this._byResource.values())t.push(...e);return t}clear(){this._byResource.clear(),this._byReserver.clear(),this._conflictLog.length=0}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}_insert(t){let e=this._byResource.get(t.resource);e||(e=[],this._byResource.set(t.resource,e));const n=e.findIndex(e=>e.timeWindow.startSimMs>t.timeWindow.startSimMs);n<0?e.push(t):e.splice(n,0,t);let s=this._byReserver.get(t.reserverId);s||(s=[],this._byReserver.set(t.reserverId,s)),s.push(t)}_remove(t){const e=this._byResource.get(t.resource);if(!e)return!1;const n=e.findIndex(e=>e.id===t.id);if(n<0)return!1;e.splice(n,1),0===e.length&&this._byResource.delete(t.resource);const s=this._byReserver.get(t.reserverId);if(s){const e=s.findIndex(e=>e.id===t.id);e>=0&&s.splice(e,1),0===s.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const iT=new sT;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=iT);class oT{constructor(){this.nodes=new Map,this.edges=new Map,this.laneEndpoints=new Map}addNode(t){this.nodes.has(t.id)||(this.nodes.set(t.id,t),this.edges.set(t.id,[]))}addEdge(t){const e=this.edges.get(t.fromNode);if(!e)throw new Error(`NavGraph.addEdge: source node not found: ${t.fromNode}`);if(!this.nodes.has(t.toNode))throw new Error(`NavGraph.addEdge: target node not found: ${t.toNode}`);e.push(t)}edgesFrom(t){return this.edges.get(t)??[]}findNearestNode(t){let e=null,n=1/0;for(const s of this.nodes.values()){const i=rT(s.position,t);i<n&&(n=i,e=s)}return e}}function rT(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}function aT(t,e){return Math.sqrt(rT(t,e))}function cT(t,e,n={}){const s=new oT,i=n.defaultSpeed??100;for(const e of t){const t=e.geometry.centerPoints;if(t.length<2)continue;const n=`${e.id}:start`,o=`${e.id}:end`;s.addNode({id:n,position:t[0],type:"lane-start"}),s.addNode({id:o,position:t[t.length-1],type:"lane-end"}),s.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:o});let r=0;for(let e=1;e<t.length;e++)r+=aT(t[e-1],t[e]);const a=r/(e.speedLimit??i)*1e3;s.addEdge({fromNode:n,toNode:o,resource:e.id,distance:r,durationMs:a,forward:!0}),"twoway"===e.direction&&s.addEdge({fromNode:o,toNode:n,resource:e.id,distance:r,durationMs:a,forward:!1})}for(const t of e){if(t.lanes.length<2)continue;const e=[];for(const n of t.lanes){const i=s.laneEndpoints.get(n);if(!i)continue;const o=s.nodes.get(i.startNodeId).position,r=s.nodes.get(i.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=s.laneEndpoints.get(e);if(!t)continue;const i=s.nodes.get(t.startNodeId).position,h=s.nodes.get(t.endNodeId).position;a+=Math.min(rT(o,i),rT(o,h)),c+=Math.min(rT(r,i),rT(r,h)),l++}if(0===l)continue;const h=a<c?i.startNodeId:i.endNodeId;e.push({laneId:n,nodeId:h,pos:s.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let i=0;i<e.length;i++){if(n===i)continue;const o=e[n],r=e[i],a=aT(o.pos,r.pos);s.addEdge({fromNode:o.nodeId,toNode:r.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return s}function lT(t,e,n,s={}){const i=t.nodes.get(e),o=t.nodes.get(n);if(!i||!o)return null;const r=s.speed?.max??100,a=e=>{const n=function(t,e){return Math.sqrt(function(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}(t,e))}(t.nodes.get(e).position,o.position);return n/r*1e3},c=new Map,l=new Set,h=new Set,d={nodeId:e,gScore:0,fScore:a(e)};c.set(e,d),l.add(e);const u=s.startSimMs??0,p=s.deadlineSimMs;for(;l.size>0;){let e=null,s=null;for(const t of l){const n=c.get(t);(!s||n.fScore<s.fScore||n.fScore===s.fScore&&t<e)&&(s=n,e=t)}if(!s||!e)return null;if(e===n){const t=[];let e=s,n=0;for(;e&&e.cameFromEdge;){const s=e.cameFromEdge,i=u+(e.gScore-s.durationMs);t.unshift({resource:s.resource,timeWindow:{startSimMs:i,endSimMs:i+s.durationMs},fromPos:s.fromPos,toPos:s.toPos}),n+=s.distance,e=c.get(s.fromNodeId)}const i=s.gScore;return void 0!==p&&u+i>p?null:{segments:t,totalDurationMs:i,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=s.gScore+n.durationMs,i=c.get(n.toNode);if(!i||e<i.gScore){const s=t.nodes.get(n.fromNode),i=t.nodes.get(n.toNode),o={nodeId:n.toNode,gScore:e,fScore:e+a(n.toNode),cameFromEdge:{fromNodeId:n.fromNode,resource:n.resource,distance:n.distance,durationMs:n.durationMs,fromPos:s.position,toPos:i.position}};c.set(n.toNode,o),l.add(n.toNode)}}}return null}function hT(t,e,n=0,s){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:s}))}const dT={closed:!0,round:0,divisions:24};class uT{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const s=t[e].x-t[e-1].x,i=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(s*s+i*i))}this.cumulative=n,this.length=n[n.length-1]??0}sample(t){const e=this.length;if(0===this.points.length)return{x:0,y:0,theta:0};if(0===e)return{x:this.points[0].x,y:this.points[0].y,theta:0};let n=t;this.closed?n=(t%e+e)%e:n<0?n=0:n>e&&(n=e);const s=this.cumulative;let i=0,o=s.length-2;for(;i<o;){const t=i+o>>1;s[t+1]<=n?i=t+1:o=t}const r=s[i+1]-s[i],a=r>0?(n-s[i])/r:0,c=this.points[i],l=this.points[i+1],h=l.x-c.x,d=l.y-c.y;return{x:c.x+h*a,y:c.y+d*a,theta:0===h&&0===d?0:Math.atan2(d,h)}}}function pT(t,e={}){const n={...dT,...e},s=t.length;if(0===s)return new uT([],n.closed);if(1===s)return new uT([{x:t[0].x,y:t[0].y}],n.closed);const i=[],o=(t,e)=>{if(i.length>0){const n=i[i.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}i.push({x:t,y:e})},r=(n.closed,s);for(let e=0;e<r;e++){const i=0===e?n.closed?s-1:-1:e-1,r=e===s-1?n.closed?0:-1:e+1,a=i>=0?t[i]:null,c=t[e],l=r>=0?t[r]:null;if(a&&a.x===c.x&&a.y===c.y)continue;const h=a&&l?Lo(c,n.round):0;let d,u,p,f;if(a){const t=Math.sqrt((a.x-c.x)**2+(a.y-c.y)**2),e=0!==t?Math.atan2(a.x-c.x,a.y-c.y):0,n=Math.min(h,t/2);d=Math.sin(e)*n+c.x,u=Math.cos(e)*n+c.y}else d=c.x,u=c.y;if(l){const t=Math.sqrt((l.x-c.x)**2+(l.y-c.y)**2),e=0!==t?Math.atan2(l.x-c.x,l.y-c.y):0,n=Math.min(h,t/2);p=Math.sin(e)*n+c.x,f=Math.cos(e)*n+c.y}else p=c.x,f=c.y;if(o(d,u),h>0&&a&&l)for(let t=1;t<=n.divisions;t++){const e=t/n.divisions,s=1-e;o(s*s*d+2*s*e*c.x+e*e*p,s*s*u+2*s*e*c.y+e*e*f)}else d===p&&u===f||o(p,f);if(l&&zo(c)){const t=Lo(l,n.round),e=Math.sqrt((c.x-l.x)**2+(c.y-l.y)**2),s=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,i=Math.min(t,e/2),r=Ro({x:p,y:f},{x:Math.sin(s)*i+l.x,y:Math.cos(s)*i+l.y},c.bulge);if(r){let t=r.endAngle-r.startAngle;if(r.clockwise)for(;t>0;)t-=2*Math.PI;else for(;t<0;)t+=2*Math.PI;for(let e=1;e<=n.divisions;e++){const s=e/n.divisions,i=r.startAngle+t*s;o(r.cx+r.radius*Math.cos(i),r.cy+r.radius*Math.sin(i))}}}}if(n.closed&&i.length>0){const t=i[0],e=i[i.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&i.push({x:t.x,y:t.y})}return new uT(i,n.closed)}function fT(t,e){return pT(t,e).length}function mT(t){return t?/forklift|agv|amr|oht|tugger|worker/i.test(t)?"mobile":/conveyor|sorter|induct|chute|belt/i.test(t)?"flow":/rack|shelf|stocker|cell/i.test(t)?"cell":/pallet|box|parcel|crate|drum|tray/i.test(t)?"atomic":/robot[-_]?arm|crane|lift/i.test(t)?"articulated":/spawn[-_]?point|sink[-_]?point/i.test(t)?"boundary":"":""}function gT(t){const e=[];let n=t.parent;for(;n&&!n.isRootModel?.();){const t=n.state?.id??n.constructor?.name;t&&e.unshift(t),n=n.parent}return e.join(" › ")}function yT(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",s={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:mT(n),parentId:t.parent?.state?.id,parentPath:gT(t)},i=t._realObject?.object3d;if(i){i.updateWorldMatrix?.(!0,!1);const t=i.matrixWorld?.elements;t&&(s.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(s.isItem=!0),!0===t.isMover&&(s.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(s.isHolder=!0),"function"==typeof t.pickupFrames)try{s.isPickable=t.pickupFrames().length>0}catch{s.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?s.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(s.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,s]of Object.entries(t.state))"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s&&null!==s||(e[n]=s);s.state=e}if(e){const e=t.components??[];s.childIds=e.map(t=>t.state?.id).filter(Boolean)}return s}function bT(t){function e(t,n){if(!t)return;n.push(yT(t));const s=t.components??[];for(const t of s)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const s=e.components??[];for(const e of s){const s=n(t,e);if(s)return s}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const s=n(e,t?.rootModel??t);if(!s)return null;const i={...yT(s)};if("function"==typeof s.pickupFrames)try{i.pickupFrames=s.pickupFrames()}catch{}if("object"==typeof s.slots)try{i.slots=Array.isArray(s.slots)?s.slots:"function"==typeof s.slots?s.slots():[]}catch{}if("function"==typeof s.acceptanceRotation)try{i.acceptanceWorldQuat=s.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof s.deliveryWorldPosition)try{i.deliveryWorldPosition=s.deliveryWorldPosition(null)}catch{}return i},simStatus(){let e=0;const n=[t?.rootModel??t];for(;n.length>0;){const t=n.pop();if(!t)continue;!0===t.isItem&&e++;const s=t.components??[];for(const t of s)n.push(t)}return{simTime:bo.now,realTime:"undefined"!=typeof performance?performance.now():Date.now(),speed:bo.speed,paused:bo.isPaused,carrierCount:e}},transferLog(){const t={};rp.flows().forEach((e,n)=>{t[n]=e});const e={};rp.targetCounts().forEach((t,n)=>{e[n]=t});const n={};return rp.rejectReasonCounts().forEach((t,e)=>{n[e]=t}),{entries:rp.toJSON(),stats:rp.stats(),flows:t,targetCounts:e,rejectReasonCounts:n}},reservations(){const t=[...iT.all()],e={},n={};for(const s of t)(e[s.resource]??=[]).push(s),(n[s.reserverId]??=[]).push(s);for(const t of Object.values(e))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);for(const t of Object.values(n))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);return{simTime:bo.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=iT.conflictLog(),e={},n={};let s=0,i=0;for(const o of t)e[o.resource]=(e[o.resource]??0)+1,n[o.proposed.reserverId]=(n[o.proposed.reserverId]??0)+1,"rejected"===o.outcome?s++:i++;return{simTime:bo.now,log:[...t],total:t.length,rejected:s,preempted:i,byResource:e,byReserver:n}}}}function vT(t){const e=bT(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let _T=0;const xT=new FinalizationRegistry(()=>{_T--});class wT{static get residents(){return _T}static get residentsCount(){return _T}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,_T++,xT.register(this,_T)}dispose(){if(this.disposer)for(const t in this.references)this.disposer(t,this.references[t]);this.references={},this.counters={}}get ids(){return Object.keys(this.references)}create(t){return new Promise((e,n)=>{this.creator?this.creator(t,n=>{n.release=()=>{this.disposer?.(t,n),delete n.release,Hs("RELEASED",t)},e(n)},n):n(Error("Reference id("+t+") could not be created. Reference creator should be defined."))})}add(t,e){const n=new Promise((n,s)=>{const i=this.references[t];if(i)i===e?s(Error("Reference ID and target duplicate")):e?s(Error("Reference ID duplicate")):n(i);else{const i=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)i(e);else{if(!this.creator)return void s(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,i,s)}}});return this.references[t]||(this.references[t]=n),n}async get(t,e=!1){let n=this.references[t];if(n){if(!(n instanceof Promise)){if(!(t in this.counters))throw new Error("No Reference Count");return this.counters[t]++,n}if(e)return n=await n,this.counters[t]++,n}if(e)return await this.add(t);throw new Error("No References for "+t)}_id(t){for(const e in this.references){if(this.references[e]===t)return e}}release(t){const e=this._id(t);if(!e)return void Fs("No Referenced ID");const n=this.references[e];n&&(this.counters[e]--,0==this.counters[e]&&(this.disposer?.(e,n),delete this.references[e],delete this.counters[e],delete t.release,Hs("RELEASED",e)))}}const MT={},ST={};let AT=[];function kT(t){const e=t.target,n="SCRIPT"===e.tagName?MT:ST,s=e.src||e.href;n[s]=!0,AT.forEach((t,e)=>{if(!t)return;const{resolve:i,scripts:o,styles:r}=t;if(n===MT){const t=o.indexOf(s);t>-1&&t<o.length-1&&TT(o[t+1])}o.some(t=>!MT[t])||r?.some(t=>!ST[t])||(i(),AT[e]=null)}),AT=AT.filter(Boolean)}function ET(t){if("string"==typeof t)return;const e=t.target,n=e.src,s="SCRIPT"===e.tagName?MT:ST;AT.forEach((e,i)=>{if(!e)return;const{reject:o,scripts:r,styles:a}=e;(s===MT&&r.includes(n)||s===ST&&!!a?.includes(n))&&(o(t),AT[i]=null)}),AT=AT.filter(Boolean),delete s[n],document.head.removeChild(e)}function TT(t){MT[t]=!1;const e=document.createElement("script");e.onload=kT,e.onerror=ET,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class CT{static load(t,e){const n="string"==typeof t?[t]:t,s="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||s&&!Array.isArray(s))return void e(new Error("invalid sources for load"));let i,o=!0;if(s?.forEach(t=>{t in ST||function(t){ST[t]=!1;const e=document.createElement("link");e.onload=kT,e.onerror=ET,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),ST[t]||(o=!1)}),n&&n.length>0)for(const t of n)t in MT?MT[t]||(o=!1):i??=t;if(i)TT(i);else if(o)return void t();AT.push({resolve:t,reject:e,scripts:n,styles:s})})}}const OT="0.0.0";function PT(t){if(!(t>0))return 1;let e=0;if(!(t&t-1))return t;for(;0!=t;)t>>=1,e+=1;return 1<<e}function IT(t){const{lineWidth:e=0}=t.state;let{width:n,height:s}=t.bounds;n+=e,s+=e;const i=PT(2*n),o=PT(2*s),r=Zp(i,o),a=new w.CanvasTexture(r);return DT(r,t,2),a.needsUpdate=!0,a.wrapS=w.RepeatWrapping,a.wrapT=w.RepeatWrapping,a.offset.set(0,1-2*s/o),a.repeat.set(2*n/i,2*s/o),a.magFilter=w.NearestFilter,a.minFilter=w.LinearFilter,a.colorSpace=w.SRGBColorSpace,a}function DT(t,e,n){const{lineWidth:s=0}=e.state;let{left:i,top:o}=e.bounds;i-=s/2,o-=s/2;const r=t.getContext("2d");r.scale(n,n),r.translate(-i,-o),e.render(r),e.postrender(r)}function zT(t,e,n=2){const s=t.getContext("2d");s&&(s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,t.width,t.height),DT(t,e,n))}const RT=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class jT extends Du{get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}constructor(t){super(t),this._origInvalidate=t.invalidate.bind(t),t.invalidate=()=>{this._origInvalidate(),this._refreshTextureNow()}}getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds;if(!t||!e)return;const n=Nd(this.component.state.material3d),s=new w.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const i=IT(this.component),o=new w.MeshStandardMaterial({map:i});Gd(o,n),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=n.castShadow,this.object3d.receiveShadow=n.receiveShadow}updateDimension(){const{width:t,height:e}=this.component.bounds;this.setDimensionScale(t,1,e)}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}_debouncedRebuild(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=void 0,this._rebuildTexture()},100)}_rebuildTexture(){this.clear(),this.build(),this.updateTransform(),this.updateDimension(),this.updateHidden()}_refreshTextureNow(){const t=this.object3d.material,e=t?.map;if(!e)return;const n=e.source?.data;n&&(zT(n,this.component,2),e.needsUpdate=!0)}updateFillStyle(){this._debouncedRebuild()}updateStrokeStyle(){this._debouncedRebuild()}updateText(){this._debouncedRebuild()}onchange(t,e){super.onchange(t,e);for(const e of Object.keys(t))if(!RT.has(e)){this._debouncedRebuild();break}}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),t.transparent=!0,this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}clear(){return this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),bu(this.object3d),super.clear()}dispose(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),this._origInvalidate&&(this.component.invalidate=this._origInvalidate,this._origInvalidate=void 0),super.dispose()}}const $T=new Map;function LT(t){return Math.round(1e3*t)/1e3}function FT(t){return new w.Color(t).getHexString()}const NT={material(t,e,n){const s=t+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+FT(t.color)),null!=t.metalness&&e.push("m"+LT(t.metalness)),null!=t.roughness&&e.push("r"+LT(t.roughness)),null!=t.opacity&&e.push("o"+LT(t.opacity)),null!=t.emissive&&e.push("E"+FT(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+LT(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+LT(t.envMapIntensity)),null!=t.side&&e.push("s"+t.side),t.transparent&&e.push("t"),t.flatShading&&e.push("f"),!1===t.depthWrite&&e.push("dw0"),t.map&&e.push("M"+(t.map.uuid??"")),e.join("|")}(e);let i=$T.get(s);return i||$T.set(s,i=function(t){const e=new w.MeshStandardMaterial;return e.userData.__bankOwned=!0,null!=t.color&&e.color.set(t.color),null!=t.emissive&&e.emissive.set(t.emissive),null!=t.metalness&&(e.metalness=t.metalness),null!=t.roughness&&(e.roughness=t.roughness),null!=t.emissiveIntensity&&(e.emissiveIntensity=t.emissiveIntensity),null!=t.envMapIntensity&&(e.envMapIntensity=t.envMapIntensity),null!=t.side&&(e.side=t.side),null!=t.map&&(e.map=t.map),null!=t.flatShading&&(e.flatShading=t.flatShading),null!=t.depthWrite&&(e.depthWrite=t.depthWrite),null!=t.opacity&&(e.opacity=t.opacity),null!=t.transparent?e.transparent=t.transparent:null!=t.opacity&&t.opacity<1&&(e.transparent=!0),e}(e)),null==n?i:ou(i,{color:n})},get size(){return $T.size},has(t){const e=t+"::";for(const t of $T.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of $T.values())au(t),t.dispose();$T.clear()}};class HT extends Du{getObject3dInstance(){return new w.Mesh}build(){super.build(),this.buildGeometry(),this.buildMaterial(),this.updateDimension()}updateAlpha(){if(this.canShareMaterial)return void super.updateAlpha();const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}updateFillStyle(){if(this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const{fillStyle:t,alpha:e=1}=this.component.state,n=this.object3d.material;if(!n)return;const s=Du.buildFillStyleTexture(this.component);s?(n.map&&n.map.dispose(),s.needsUpdate=!0,n.map=s,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(du(t))),hu(n,0,t)}updateStrokeStyle(){const t=this.object3d.getObjectByName("__edgeLines__");t&&(this.object3d.remove(t),bu(t));const{strokeStyle:e}=this.component.state;if(!e||"transparent"===e||"none"===e)return;const n=this.object3d.geometry;if(!n?.getAttribute("position"))return;const s=new w.EdgesGeometry(n),i=new w.LineBasicMaterial({color:e}),o=new w.LineSegments(s,i);o.name="__edgeLines__",this.object3d.add(o)}updateDimension(){const{width:t,height:e}=this.component.bounds,{depth:n=1}=this.component.state;if(!this.object3d)return;this.object3d.geometry.computeBoundingBox();const s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,o=s.max.y-s.min.y,r=s.max.z-s.min.z;this.setDimensionScale(t/i,n/o,e/r)}}get canShareMaterial(){return void 0===this.materialSharingIssue}get materialSharingIssue(){const{fillStyle:t}=this.component.state;if(!t||"object"!=typeof t)return;const e=t.type;return"pattern"===e?"무늬(pattern) fillStyle 은 인스턴스마다 캔버스 텍스처가 필요하다":"gradient"===e?"그라디언트 fillStyle 은 인스턴스마다 캔버스 텍스처가 필요하다":`fillStyle 이 색 문자열이 아니다 (type: ${String(e)})`}get requiresSharedMaterial(){return!0===this.component.constructor.requiresSharedMaterial}get materialSharing(){const t=this.materialSharingIssue,e=void 0===t,n=this.requiresSharedMaterial,s={shared:e,required:n,violated:n&&!e};return void 0!==t&&(s.reason=t),e&&(s.bankKey=this.materialBankKey),s}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=Nd(this.component.state.material3d),e=lu(this.component.state.fillStyle);return{metalness:t.metalness,roughness:t.roughness,emissive:t.emissive,emissiveIntensity:t.emissiveIntensity,envMapIntensity:t.envMapIntensity,side:Bd(t.side),flatShading:t.flatShading,opacity:e,transparent:e<1}}buildMaterial(){if(!this.canShareMaterial){const t=Nd(this.component.state.material3d),e=new w.MeshStandardMaterial({transparent:!0});return Gd(e,t),void(this.object3d.material=e)}this.applyBankMaterial()}applyBankMaterial(){const{fillStyle:t}=this.component.state,e=lu(t)>0&&"string"==typeof t?du(t):void 0;ru(this.object3d),this.object3d.material=NT.material(this.materialBankKey,this.materialSpec(),e)}updateMaterial3d(){if(super.updateMaterial3d(),this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const t=this.object3d.material;t&&Gd(t,Nd(this.component.state.material3d))}clear(){return ru(this.object3d),bu(this.object3d),super.clear()}}function BT(t,e,n,s){return[["bold",t],["italic",e],[n+"px",!0],[s,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function GT(t){let e=0;if(!((t=Math.abs(t)||1)&t-1))return t;for(;0!=t;)t>>=1,e+=1;return 1<<e}function UT(t,e,n){const{bold:s=!1,italic:i=!1,fontFamily:o="Serif",fontSize:r=10,fontColor:a="black",textAlign:c="center",textBaseline:l="middle",width:h=t.width,height:d=t.height,offsetX:u=0,offsetY:p=0}=n||{},f=t.getContext("2d");let m,g;f.imageSmoothingEnabled=!1,f.fillStyle=a,f.strokeStyle=a,f.font=BT(s,i,r,o),"left"===c||"start"===c?(f.textAlign="left",m=u):"right"===c||"end"===c?(f.textAlign="right",m=u+h):(f.textAlign="center",m=u+h/2);const y=1.2*r,b=String(e).split("\n"),v=y*b.length;g="top"===l||"hanging"===l?p+.1*r:"bottom"===l||"alphabetic"===l?p+d-v+.1*r:p+(d-v)/2+.1*r,f.textBaseline="top";for(const t of b)f.fillText(t,m,g),g+=y}function VT(t,e,n,s){const i=GT(2*e),o=GT(2*n),r=Zp(i,o),a=r.getContext("2d"),{fillStyle:c}=s||{};if(c&&"object"==typeof c&&c.colorStops?.length){const t=vu(c,2*e,2*n);t&&a.drawImage(t,0,0)}a.scale(2,2),"string"==typeof c&&""!==c&&"transparent"!==c&&(a.fillStyle=c,a.fillRect(0,0,e,n)),UT(r,t,s);const l=new w.CanvasTexture(r);return l.needsUpdate=!0,l.wrapS=w.RepeatWrapping,l.wrapT=w.RepeatWrapping,l.offset.set(0,1-2*n/o),l.repeat.set(2*e/i,2*n/o),l.minFilter=w.LinearFilter,l.colorSpace=w.SRGBColorSpace,l}function WT(t,e,n,s,i,o,r){const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const t=2*n,c=2*s,l=GT(t),h=GT(c),d=Zp(l,h),u=d.getContext("2d");if(o.color&&(u.fillStyle=o.color,u.fillRect(0,0,t,c)),o.fitPattern)u.drawImage(a,0,0,t,c);else{const e=2*(o.width||a.naturalWidth),n=2*(o.height||a.naturalHeight),s=2*(o.offsetX||0),i=2*(o.offsetY||0);let r=0,l=0;switch(o.align){case"center":r=(t-e)/2,l=(c-n)/2;break;case"left-top":break;case"left-bottom":l=c-n;break;case"right-top":r=t-e;break;case"right-bottom":r=t-e,l=c-n;break;case"left":l=(c-n)/2;break;case"right":r=t-e,l=(c-n)/2;break;case"top":r=(t-e)/2;break;case"bottom":r=(t-e)/2,l=c-n}const h=s+r,d=i+l;if(o.noRepeat)u.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,h,d,e,n);else{u.save(),u.rect(0,0,t,c),u.clip();const s=h>0?h-Math.ceil(h/e)*e:h;for(let i=d>0?d-Math.ceil(d/n)*n:d;i<c;i+=n)for(let o=s;o<t;o+=e)u.drawImage(a,0,0,a.naturalWidth,a.naturalHeight,o,i,e,n);u.restore()}}e&&(u.scale(2,2),UT(d,e,i));const p=new w.CanvasTexture(d);p.needsUpdate=!0,p.wrapS=w.RepeatWrapping,p.wrapT=w.RepeatWrapping,p.offset.set(0,1-c/h),p.repeat.set(t/l,c/h),p.minFilter=w.LinearFilter,p.colorSpace=w.SRGBColorSpace,r(p)},a.onerror=()=>{const t=VT(e,n,s,i);r(t)},a.src=t}function YT(t,e){let{bold:n=!1,italic:s=!1,fontFamily:i="Serif",fontSize:o=10,lineHeight:r="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=BT(n,s,o,i),a.style.lineHeight=String(r),a.style.whiteSpace="pre",a.style.position="absolute",a.textContent=t,document.body.appendChild(a);const c=a.getBoundingClientRect();return document.body.removeChild(a),{width:c.width,height:c.height}}class qT extends HT{get zPriority(){return Su.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){this.updateDimension()}get materialSharingIssue(){return"텍스트는 인스턴스마다 글자 텍스처를 재질에 얹는다"}updateStrokeStyle(){}updateFillStyle(){this.updateText()}updateDimension(){const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const i=new w.PlaneGeometry(n,s);i.rotateX(-Math.PI/2),this.object3d.geometry=i}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:s=!1,italic:i=!1,fontFamily:o="Serif",fontSize:r=10,fontColor:a="black",textAlign:c="center",textBaseline:l="middle",fillStyle:h}=this.component.state,d=Math.abs(e)||1,u=Math.abs(n)||1,p=this.component.text,f=h&&"none"!==h?h:"transparent",m={bold:s,italic:i,fontFamily:o,fontSize:r,fontColor:a,textAlign:c,textBaseline:l,width:d,height:u,fillStyle:f};if("object"==typeof f&&"pattern"===f?.type&&f.image){return void WT(this.component.app.url(h.image),p,d,u,m,h,e=>{t.map&&t.map.dispose(),t.map=e,t.color.set(16777215),t.needsUpdate=!0})}const g=VT(p,d,u,m);g?(t.map&&t.map.dispose(),t.map=g,t.color.set(16777215),g.needsUpdate=!0):"string"==typeof h&&(""!==h&&"transparent"!==h?t.color.set(du(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}hf("text",t=>new qT(t));const XT={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function KT(t){const e=t.model?.type??"";return"texture"===(XT[e]??"css3d")?new jT(t):new af(t)}hf("html-overlay-element",KT),hf("html-overlay-container",KT);class JT{setShape({extrudedShape:t,extrudedOptions:e}){this.extrudedShape=t,this.bb=new w.Box2,this.bb.setFromPoints(this.extrudedShape?.extractPoints(0).shape),this.extrudedOptions=e}generateTopUV(t,e,n,s,i){const o=e[3*n],r=e[3*n+1],a=e[3*s],c=e[3*s+1],l=e[3*i],h=e[3*i+1],d=this.bb,u=d.max.x-d.min.x,p=d.max.y-d.min.y;return[new w.Vector2((o-d.min.x)/u,1-(r-d.min.y)/p),new w.Vector2((a-d.min.x)/u,1-(c-d.min.y)/p),new w.Vector2((l-d.min.x)/u,1-(h-d.min.y)/p)]}generateSideWallUV(t,e,n,s,i,o){const r=e[3*n],a=e[3*n+1],c=e[3*n+2],l=e[3*s],h=e[3*s+1],d=e[3*s+2],u=e[3*i],p=e[3*i+1],f=e[3*i+2],m=e[3*o],g=e[3*o+1],y=e[3*o+2],b=this.extrudedOptions?.depth||100,v=this.bb,_=v.max.x-v.min.x,x=v.max.y-v.min.y;return Math.abs(a-h)<.01?[new w.Vector2(r/_,1-c/b),new w.Vector2(l/_,1-d/b),new w.Vector2(u/_,1-f/b),new w.Vector2(m/_,1-y/b)]:[new w.Vector2(a/x,1-c/b),new w.Vector2(h/x,1-d/b),new w.Vector2(p/x,1-f/b),new w.Vector2(g/x,1-y/b)]}}function QT(t,e){const n=t/2,s=e/2;return{points:[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}]}}function ZT(t,e,n){const s=Math.max(3,Math.floor(n)),i=[];for(let n=0;n<s;n++){const o=n/s*Math.PI*2;i.push({x:t*Math.cos(o),y:e*Math.sin(o)})}return{points:i,segments:s}}function tC(t){if(0===t.length)return[];let e=1/0,n=1/0,s=-1/0,i=-1/0;for(const o of t)o.x<e&&(e=o.x),o.x>s&&(s=o.x),o.y<n&&(n=o.y),o.y>i&&(i=o.y);const o=(e+s)/2,r=(n+i)/2,a=t.map(t=>({x:t.x-o,y:t.y-r})),c=a[0],l=a[a.length-1];return a.length>1&&Math.abs(c.x-l.x)<1e-9&&Math.abs(c.y-l.y)<1e-9&&a.pop(),a}class eC extends Du{clear(){return this._mesh=void 0,super.clear()}get shape(){return null}topOutline(){const t=this.shape;if(!t||"function"!=typeof t.getPoints)return null;const e=this.outlineDivisions,n=t.getPoints(e);if(!n||n.length<3)return null;const s=tC(n);return s.length<3?null:{points:s}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new JT),this._boundUVGenerator}build(){super.build();const t=this.effectiveDepth,e=this.shape;if(!e)return;const n=this.boundUVGenerator;n&&n.setShape({extrudedShape:e,extrudedOptions:{depth:t}});const s=this.createGeometry(e),i=this.createMaterials();this._mesh=new w.Mesh(s,i),this._mesh.rotation.x=-Math.PI/2,this._mesh.rotation.y=-Math.PI,this._mesh.rotation.z=-Math.PI,this._mesh.castShadow=!0,this.object3d.add(this._mesh),this.updateFillStyle(),this.updateStrokeStyle()}createGeometry(t){const e=this.effectiveDepth,{lineWidth:n=0}=this.component.state,s={steps:1,depth:e,bevelEnabled:n>0,bevelThickness:0,bevelSize:n,bevelSegments:1,UVGenerator:this.boundUVGenerator},i=new w.ExtrudeGeometry(t,s);return i.center(),i}createMaterials(){const t=Nd(this.component.state.material3d),e=new w.MeshStandardMaterial;Gd(e,t);const n=new w.MeshStandardMaterial;return Gd(n,t),[e,n]}createTexture(){const{width:t,height:e}=this.component.bounds,n=GT(t),s=GT(e),i=Zp(n,s);this.component.render(i.getContext("2d"));const o=new w.CanvasTexture(i);return o.needsUpdate=!0,o.wrapS=w.RepeatWrapping,o.wrapT=w.RepeatWrapping,o.offset.set(0,1-e/s),o.repeat.set(t/n,e/s),o.minFilter=w.LinearFilter,o}getMaterials(){if(!this._mesh)return;const t=this._mesh.material;return Array.isArray(t)?t:void 0}updateMaterial3d(){super.updateMaterial3d();const t=this.getMaterials();if(!t)return;const e=Nd(this.component.state.material3d);for(const n of t)Gd(n,e)}updateAlpha(){const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,s=this.getMaterials();s&&(hu(s[0],0,e),hu(s[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(du(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,s=this.component.hasTextProperty?this.component.text:"";if(!s){const t=Du.buildFillStyleTexture(this.component);return t?(e.map&&e.map.dispose(),e.map=t,e.color.set(16777215)):(e.map&&(e.map.dispose(),e.map=null),e.color.set(du(n))),void(e.needsUpdate=!0)}const{bold:i=!1,italic:o=!1,fontFamily:r="Serif",fontSize:a=10,fontColor:c="black",textAlign:l="center",textBaseline:h="middle",paddingTop:d=0,paddingLeft:u=0,paddingRight:p=0,paddingBottom:f=0}=this.component.state,{width:m,height:g}=this.component.bounds,y=Math.abs(m)||1,b=Math.abs(g)||1,v={bold:i,italic:o,fontFamily:r,fontSize:a,fontColor:c,textAlign:l,textBaseline:h,width:Math.max(y-u-p,0),height:Math.max(b-d-f,0),fillStyle:n,offsetX:u,offsetY:d};if("object"==typeof n&&"pattern"===n?.type&&n.image){return void WT(this.component.app.url(n.image),s,y,b,v,n,t=>{e.map&&e.map.dispose(),e.map=t,e.color.set(16777215),e.needsUpdate=!0})}e.map&&e.map.dispose();const _=VT(s,y,b,v);e.map=_,e.color.set(16777215),e.needsUpdate=!0}updateDimension(){super.updateDimension()}onchange(t,e){if("path"in t&&this._mesh){const t=this._mesh.geometry,e=this.shape;if(e){const n=this.createGeometry(e);this._mesh.geometry=n,t.dispose()}}super.onchange(t,e)}}class nC extends eC{get shape(){const{cx:t=0,cy:e=0,rx:n=1,ry:s=1,startAngle:i=0,endAngle:o=2*Math.PI,anticlockwise:r=!1}=this.component.state,a=new w.EllipseCurve(t,e,Math.abs(n),Math.abs(s),i,o,r,0);return new w.Shape(a.getPoints(50))}}hf("ellipse",t=>new nC(t));class sC extends eC{get shape(){const{width:t,height:e,round:n=0}=this.component.state,s=fc(n,t,e);if(s>0){const n=s,i=new w.Path;return i.moveTo(n,0),i.lineTo(t-n,0),i.quadraticCurveTo(t,0,t,n),i.lineTo(t,e-n),i.quadraticCurveTo(t,e,t-n,e),i.lineTo(n,e),i.quadraticCurveTo(0,e,0,e-n),i.lineTo(0,n),i.quadraticCurveTo(0,0,n,0),new w.Shape(i.getPoints(12))}const i=new w.Shape;return i.moveTo(0,0),i.lineTo(t,0),i.lineTo(t,e),i.lineTo(0,e),i.lineTo(0,0),i}}function iC(t,e={}){const n=e.round??0,s=e.divisions??24;if(!t||0===t.length)return new w.Shape;const i=t.some(t=>zo(t)),o=n>0||t.some(t=>Lo(t,0)>0);if(i||o){const e=new w.Path;for(let s=0;s<t.length;s++){const i=t[(s-1+t.length)%t.length],o=t[s],r=t[(s+1)%t.length];if(i.x===o.x&&i.y===o.y)continue;const a=Lo(o,n);let c=Math.sqrt((i.x-o.x)**2+(i.y-o.y)**2),l=0!==c?Math.atan2(i.x-o.x,i.y-o.y):0;const h=Math.sin(l)*Math.min(a,c/2)+o.x,d=Math.cos(l)*Math.min(a,c/2)+o.y;c=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),l=0!==c?Math.atan2(r.x-o.x,r.y-o.y):0;const u=Math.sin(l)*Math.min(a,c/2)+o.x,p=Math.cos(l)*Math.min(a,c/2)+o.y;if(0===s?e.moveTo(h,d):e.lineTo(h,d),a>0&&e.quadraticCurveTo(o.x,o.y,u,p),zo(o)){const t=Lo(r,n),s=Math.sqrt((o.x-r.x)**2+(o.y-r.y)**2),i=0!==s?Math.atan2(o.x-r.x,o.y-r.y):0,a=Ro({x:u,y:p},{x:Math.sin(i)*Math.min(t,s/2)+r.x,y:Math.cos(i)*Math.min(t,s/2)+r.y},o.bulge);a&&e.absarc(a.cx,a.cy,a.radius,a.startAngle,a.endAngle,a.clockwise)}}return new w.Shape(e.getPoints(s))}const r=new w.Shape;for(let e=0;e<t.length;e++)0===e?r.moveTo(t[e].x,t[e].y):r.lineTo(t[e].x,t[e].y);return r}hf("rect",t=>new sC(t));class oC extends eC{get shape(){const{path:t=[],round:e=0}=this.component.state;return iC(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(eC.prototype).build.call(this);const t=this.effectiveDepth,e=this.shape;if(!e)return;const n=this.boundUVGenerator,s=this.minMax;if(n&&void 0!==s.minX&&void 0!==s.maxX&&void 0!==s.minY&&void 0!==s.maxY){const e=new w.Shape;e.moveTo(s.minX,s.minY),e.lineTo(s.maxX,s.minY),e.lineTo(s.maxX,s.maxY),e.lineTo(s.minX,s.maxY),e.closePath(),n.setShape({extrudedShape:e,extrudedOptions:{depth:t}})}else n&&n.setShape({extrudedShape:e,extrudedOptions:{depth:t}});const i=this.createGeometry(e),o=this.createMaterials();this._mesh=new w.Mesh(i,o),this._mesh.rotation.x=-Math.PI/2,this._mesh.rotation.y=-Math.PI,this._mesh.rotation.z=-Math.PI,this._mesh.castShadow=!0,this.object3d.add(this._mesh),this.updateFillStyle(),this.updateStrokeStyle()}createGeometry(t){const e=this.effectiveDepth,{lineWidth:n=0}=this.component.state,s={steps:1,depth:e,bevelEnabled:n>0,bevelThickness:0,bevelSize:n,bevelSegments:1,UVGenerator:this.boundUVGenerator},i=new w.ExtrudeGeometry(t,s),o=this.minMax;if(void 0!==o.minX&&void 0!==o.maxX&&void 0!==o.minY&&void 0!==o.maxY){const t=(o.minX+o.maxX)/2,e=(o.minY+o.maxY)/2;i.translate(-t,-e,0),i.computeBoundingBox();const n=i.boundingBox;n&&i.translate(0,0,-(n.min.z+n.max.z)/2)}else i.center();return i}get minMax(){if(!this._minMax){const{path:t}=this.component.state;let e,n,s,i;t.forEach((t,o)=>{if(0==o)return e=s=t.x,void(n=i=t.y);e=Math.min(e,t.x),s=Math.max(s,t.x),n=Math.min(n,t.y),i=Math.max(i,t.y)}),this._minMax={minX:e,minY:n,maxX:s,maxY:i}}return this._minMax}}hf("polygon",t=>new oC(t));class rC extends eC{get shape(){const{cx:t=0,cy:e=0,rx:n=1,ry:s=1,ratio:i=50,startAngle:o=0,endAngle:r=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=Math.abs(n),l=Math.abs(s),h=new w.EllipseCurve(t,e,c,l,o,r,a,0),d=new w.Shape(h.getPoints(50)),u=c/100*i,p=l/100*i;if(u>0&&p>0){const n=new w.EllipseCurve(t,e,u,p,o,r,a,0),s=new w.Path(n.getPoints(50));d.holes.push(s)}return d}}hf("donut",t=>new rC(t));class aC extends eC{get shape(){const{x1:t=0,y1:e=0,x2:n=0,y2:s=0,x3:i=0,y3:o=0,round:r=0}=this.component.state,a=[{x:t,y:e},{x:n,y:s},{x:i,y:o}];if(r>0){const t=new w.Path;for(let e=0;e<a.length;e++){const n=a[(e-1+a.length)%a.length],s=a[e],i=a[(e+1)%a.length];let o=Math.sqrt((n.x-s.x)**2+(n.y-s.y)**2),c=0!==o?Math.atan2(n.x-s.x,n.y-s.y):0;const l=Math.sin(c)*Math.min(r,o/2)+s.x,h=Math.cos(c)*Math.min(r,o/2)+s.y;o=Math.sqrt((i.x-s.x)**2+(i.y-s.y)**2),c=0!==o?Math.atan2(i.x-s.x,i.y-s.y):0;const d=Math.sin(c)*Math.min(r,o/2)+s.x,u=Math.cos(c)*Math.min(r,o/2)+s.y;0===e?t.moveTo(l,h):t.lineTo(l,h),t.quadraticCurveTo(s.x,s.y,d,u)}return new w.Shape(t.getPoints(12))}const c=new w.Shape;return c.moveTo(t,e),c.lineTo(n,s),c.lineTo(i,o),c.closePath(),c}}hf("triangle",t=>new aC(t));class cC extends eC{get shape(){const{ratio:t=30,wing:e=5,cx:n=0,cy:s=0,rx:i=1,ry:o=1}=this.component.state;if(e<3)return null;const r=Math.PI/2,a=2*Math.PI/e,c=i-t/100*i,l=o-t/100*o,h=new w.Shape;h.moveTo(n+i*Math.cos(-r),s+o*Math.sin(-r)),h.lineTo(n+(i-c)*(Math.cos(a-r)+Math.cos(0-r))/2,s+(o-l)*(Math.sin(a-r)+Math.sin(0-r))/2);for(let t=1;t<e;t++)h.lineTo(n+i*Math.cos(a*t-r),s+o*Math.sin(a*t-r)),h.lineTo(n+(i-c)*(Math.cos(a*(t+1)-r)+Math.cos(a*t-r))/2,s+(o-l)*(Math.sin(a*(t+1)-r)+Math.sin(a*t-r))/2);return h.closePath(),h}}hf("star",t=>new cC(t));const lC=[8,12,16],hC={cylinder:25,sphere:32},dC=128;function uC(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(dC,Math.max(3,Math.floor(t))):e}function pC(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(dC,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function fC(t){return lC.includes(t)}const mC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"},{type:"number",label:"height-segments",name:"heightSegments",property:"heightSegments"}],help:"scene/component/sphere"};class gC extends HT{buildGeometry(){const t=this.component.state,e=uC(t.segments,hC.sphere),n=pC(t.heightSegments,e);this.object3d.geometry=Av.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,s=n??t;this.setDimensionScale(2*t,2*s,2*e)}get effectiveDepth(){const{rx:t=0,rz:e}=this.component.state,n=e??t;return Math.max(2*n,1)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return ZT(t,e,uC(this.component.state.segments,hC.sphere))}}t.Sphere=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new gC(this)}get nature(){return mC}},t.Sphere=ug([ov("sphere")],t.Sphere);class yC extends Du{getObject3dInstance(){return new w.Sprite}build(){super.build(),this.buildMaterial()}get cz(){const{zPos:t=0}=this.component.state,{height:e}=this.component.bounds,{tz:n=0}=this.component.delta(),s=this.component.parent?._realObject;return t+n+e/2-(s?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}updateFillStyle(){const{fillStyle:t}=this.component.state,e=this.object3d.material;if(!e)return;const n=Du.buildFillStyleTexture(this.component);n?(e.map&&e.map.dispose(),n.needsUpdate=!0,e.map=n):"string"==typeof t&&("transparent"!==t?e.color.set(du(t)):e.opacity=0)}}class bC extends yC{buildMaterial(){const t=this.object3d.material;t&&t.dispose(),this.object3d.material=new w.SpriteMaterial({map:IT(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:s=1,height:i=1}=n?.bounds??{},{scale:o=1}=this.component.state;return{x:o*t/s,y:o*e/i,z:o}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const vC={mutable:!1,resizable:!0,rotatable:!0,properties:[]};t.Sprite=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new bC(this)}get nature(){return vC}},t.Sprite=ug([ov("sprite")],t.Sprite);const _C={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class xC extends HT{buildGeometry(){this.object3d.geometry=Av.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?QT(t,e):null}}t.Cube=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new xC(this)}get nature(){return _C}},t.Cube=ug([ov("cube")],t.Cube);const wC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class MC extends HT{buildGeometry(){const t=uC(this.component.state.segments,hC.cylinder);this.object3d.geometry=Av.primitive({kind:"cylinder",segments:t})}updateDimension(){const{rx:t=0,ry:e=0,depth:n=1}=this.component.state;this.setDimensionScale(2*t,n,2*e)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return ZT(t,e,uC(this.component.state.segments,hC.cylinder))}}t.Cylinder=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new MC(this)}get nature(){return wC}},t.Cylinder=ug([ov("cylinder")],t.Cylinder);const SC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class AC extends Du{get zPriority(){return Su.DECAL}build(){super.build();const{width:t=1,height:e=1,depth:n=1}=this.component.state;this.object3d.add(this.createCube(t,e,n));const s=this.createTextureBoard(t,n);s.position.set(0,0,.5*e+1),this.object3d.add(s)}createCube(t,e,n){const{boxColor:s="#ccaa76"}=this.component.state,i=Nd(this.component.state.material3d),o=new w.BoxGeometry(t,n,e),r=new w.MeshStandardMaterial({color:s,side:w.FrontSide});Gd(r,i);const a=new w.Mesh(o,r);return a.castShadow=i.castShadow,a.receiveShadow=i.receiveShadow,a}createTextureBoard(t,e){const n=Nd(this.component.state.material3d),{fillStyle:s="#ccaa76"}=this.component.state,i=Du.buildFillStyleTexture(this.component),o=new w.MeshStandardMaterial(i?{map:i}:{color:s||"#ccaa76",side:w.FrontSide});Gd(o,n);const r=new w.PlaneGeometry(t,e,1,1),a=new w.Mesh(r,o);return a.castShadow=n.castShadow,a.receiveShadow=n.receiveShadow,a}updateMaterial3d(){super.updateMaterial3d();const t=Nd(this.component.state.material3d);this.object3d.traverse(e=>{if(e.isMesh){const n=e.material;n&&Gd(n,t),e.castShadow=t.castShadow,e.receiveShadow=t.receiveShadow}})}updateFillStyle(){this.update()}onchange(t,e){super.onchange(t,e),"boxColor"in t&&this.update()}}var kC;t.Banner=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return SC}buildRealObject(){return new AC(this)}},t.Banner=ug([ov("banner")],t.Banner);const EC={far:1e5,fov:80,near:1,zoom:1},TC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"near",name:"near"},{type:"number",label:"far",name:"far"},{type:"number",label:"fov",name:"fov"},{type:"number",label:"zoom",name:"zoom"},{type:"checkbox",label:"show-helper",name:"showHelper"}],help:"scene/component/camera"};class CC extends Du{getObject3dInstance(){return new w.Mesh}updateCamera(){const{near:t=EC.near,far:e=EC.far,fov:n=EC.fov,zoom:s=EC.zoom,showHelper:i}=this.component.state;this.camera.far=e,this.camera.fov=n,this.camera.near=t,this.camera.zoom=s,i?this.helper||(this.helper=new w.CameraHelper(this.camera),this.object3d.add(this.helper)):this.helper&&(this.object3d.remove(this.helper),delete this.helper)}build(){super.build();const{width:t=0,height:e=0,depth:n=0,fillStyle:s="lightgray"}=this.component.state;this.object3d.geometry=new w.BoxGeometry(t,n,e);const i=Nd(this.component.state.material3d),o=new w.MeshStandardMaterial({color:s});Gd(o,i),this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.receiveShadow,this.camera=new w.PerspectiveCamera,this.camera.position.set(0,0,0),this.object3d.add(this.camera),this.object3d.lookAt(0,0,0),this.updateCamera()}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}}t.Camera=kC=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return kC._image||(kC._image=new Image,kC._image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA1IAAANSAQMAAABV6G1EAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAABlBMVEX6+voBAQGV71ZvAAAFO0lEQVR42u3dMZLkNBiGYakUKFRIqKOISxDvETiCTBEQcgQOQE7clyAi8REm7KDXIhgYoMa/7fbIX+2K9w022MCP/25Z28GW5RwRERERERERERERERERERERERERERERERERERERERERERERERHRl9mv7fdPn7879sf8Mcq3J3r5EJXaUy3Wddrcd6qNybx9F2/lZ63H+nVCa9Oe9elZa5ksa/dDbE+3fsm4v27C89bd+i6W3l+XdcnSWtuxyvPW+hqorbWb0Jr7Pl3m4tjfVMIZ625d6L5pxTPWw7rQY9P6pqu1dF8aq5d83cE3rXrGWluIxV6h53eotv4c1FigureLn7Nm66ZvvZf8SSues16sD2jubz2sC839fmvYiz7t//LJna27wsr7VjlnNWtPeHTfNlae2bZvnaTePUd+74fqV2LNxv6zdN8O3z9HSWhlc4F+dOvdsKbe2+F7q+zPddq6W2ts6r31vrN825/rtPWwvvcL5losy11uxQNz5U6fYT4w12mrWf80TUNZdetXal/LtwNW6WOFI1Y9bU3GVnfFXM9bneZKwrmKcK4qnKsK52q6uULTzRWFVjpkta/OykKrCq02puWFVhRaSWjlQa0itJrO8oNaQWgloZWFVhnUqjrLN50VBrWi0MpCqwitOqjVdFYQWlFopUGtLLSq0GpjWl5oRaGVBrWy0KpCq+ksP6gVhFYSWllolUGtqrNW/jvBZVYY1IpCKwutIrTqoFbTWUFoxUGtJLSK0KpCq41peaEVhVYa1MpCqwqtprP8oFYUWklo5UGtIrSazvJCKwxqRaGVhVYZ1Ko664ems34UWj8Nav0stBoWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhbW/9L6RWgp37WofIek8j2cyveLTkqrCq0itLLQSkJL+Q5k5budle/HVr73e/24gAHenZ6FlvK9+srzAoLQUp65oDy3QnoeRxFaWWgpz2pRnncThJbyzCDpuUtVaBWhlYWW8qwx5RlqynPovNBSnuUnPaOwCK0stJLQUp4BqjzbVHk+rFNaVWgVoZWFlvJc6Si0lGdzK88cV57bLj2PvgitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqwitLLSS0IpCKwgtL7Sc0qpCqxyyahcrH7JKFysJ54rCuYJwLi+cywnn+vdlLp+rCOfKwrnStXP95zLxiJX7WEFoeaHljO/xEqsaf9/FWqz1bM+VzloP655df2uxrnP9XPHKue7OeMDsuWInyx+Y67T1Yv0gs+cKvay6P5fvZZULrdnYFBbbcr2sdKF1MxbZFdZkLLItq3aay6/vJ102eusD2rJKl633nw/o3n+uxbrpLSv1svL6M95hQ3xYNz33t16sC21Zoc+28Xahm+u+Ic7WhbYs1+dRfrvQ5LpvHOaFNq3SZ8n/faEt6twDtli7wrJpxT6P1183/di0Ti36u3XT903Ld1qGrzf9smmdWhyTddNzf8t8UqdtK/dZGq8P2DZ1ZnHcrQ/osWO5PkvDuby7NE58Yctk7Qq3PSv3+bpc3F0aJ56wF+uLX9xu6eOb4es9z/vWc0vR3oZuByjnf2t/fP/54B/2WvvWEREREREREREREREREREREREREREREREREREREREREREREREREX2J/QlrTpqHD8xO1gAAAABJRU5ErkJggg=="),kC._image}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,kC.image,e,n,s,i)}buildRealObject(){return new CC(this)}get nature(){return TC}},t.Camera=kC=ug([ov("camera")],t.Camera);const OC={mutable:!1,resizable:!0,rotatable:!0,properties:[...sv],"value-property":"source",help:"scene/component/gltf-object"};t.GLTFObject=class extends(iv(mc(pc))){get nature(){return OC}},t.GLTFObject=ug([ov("gltf-object")],t.GLTFObject);const PC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"light-type",name:"lightType",property:{options:["","point","directional"]}},{type:"number",label:"intensity",name:"intensity"},{type:"number",label:"distance",name:"distance"},{type:"number",label:"decay",name:"decay"},{type:"checkbox",label:"cast-shadow",name:"castShadow"},{type:"number",label:"near",name:"near",placeholder:"0.5"},{type:"number",label:"far",name:"far",placeholder:"1000"},{type:"number",label:"fov",name:"fov",placeholder:"90"},{type:"number",label:"zoom",name:"zoom",placeholder:"1"},{type:"checkbox",label:"show-helper",name:"showHelper"}],help:"scene/component/light"};class IC extends Du{updatePointLight(){const{lightType:t="point",distance:e=0,intensity:n=10,decay:s=1,fillStyle:i="white",castShadow:o,near:r=.5,far:a=1e3,fov:c=90,zoom:l=1,showHelper:h}=this.component.state;if(this.object3d.color=new w.Color(i),"point"==t&&(this.object3d.distance=e,this.object3d.decay=s),this.object3d.intensity=n,this.object3d.castShadow=o,o){const t=this.object3d.shadow?.camera;t.far=a,t.near=r,t.fov=c,t.zoom=l}if(h){const t=this.object3d.shadow?.camera;this.helper||(this.helper=new w.CameraHelper(t),this.object3d.add(this.helper))}else this.helper&&(this.object3d.remove(this.helper),delete this.helper)}getObject3dInstance(){const{lightType:t="point"}=this.component.state;return"point"==t?new w.PointLight:new w.DirectionalLight}update(){this.clear(),this.build(),this.updateDimension(),this.updateHidden(),this.updatePointLight()}}t.PointLight=class extends Vy{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new IC(this)}get anchors(){return[]}get nature(){return PC}},t.PointLight=ug([ov("light")],t.PointLight);const DC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class zC extends HT{buildGeometry(){this.object3d.geometry=Av.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?QT(t,e):null}}t.Wall=class extends(mc(pc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new zC(this)}get nature(){return DC}},t.Wall=ug([ov("wall")],t.Wall);const RC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"},{type:"checkbox",label:"hide-in-2d-view",name:"hideIn2DView"},{type:"checkbox",label:"hide-in-3d-view",name:"hideIn3DView"}],help:"scene/component/floor-plate"};class jC extends Du{get zPriority(){return Su.FLOOR}get receivingSurfaceY(){return this.placementSurfaceY()}resolveShadow(){const t=this.component.state,e=t.material3d,{alpha:n=1,fillStyle:s}=t,i=n>=.9&&"none"!==s;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??i}}updateHidden(){const t=this.component.state,e=!!this.component.app?.isViewMode;this.object3d.visible=!(t.hidden||e&&t.hideIn3DView)}clear(){return this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0),this._mesh=void 0,super.clear()}build(){super.build();const{width:t,height:e,depth:n=1}=this.component.state;if(!t||!e)return;const s=Math.abs(t),i=Math.abs(e),o=Math.max(n,.5),r=new w.BoxGeometry(s,o,i),a=this._buildTopMaterial(),c=this._buildSideMaterial(),l=[c,c,a,c,c,c];this._mesh=new w.Mesh(r,l),this._mesh.position.y=0;const{cast:h,receive:d}=this.resolveShadow();this._mesh.castShadow=h,this._mesh.receiveShadow=d,this.object3d.add(this._mesh)}_buildTopMaterial(){const{alpha:t=1,fillStyle:e}=this.component.state,n=Nd(this.component.state.material3d),s=Du.buildFillStyleTexture(this.component);if(s){this._topTexture=s;const t=new w.MeshStandardMaterial({map:s,side:w.DoubleSide});return hu(t,0,e),t.depthWrite=t.opacity>=.9,Gd(t,n),t}const i="string"==typeof e&&"none"!==e?du(e):"#e0e0e0",o=new w.MeshStandardMaterial({color:i,side:w.DoubleSide});return hu(o,0,e),o.depthWrite=o.opacity>=.9,Gd(o,n),o}_buildSideMaterial(){const{strokeStyle:t,alpha:e=1}=this.component.state,n="string"==typeof t&&t?du(t):"#999999",s=Nd(this.component.state.material3d),i=new w.MeshStandardMaterial({color:n});return Gd(i,s),i.side=w.DoubleSide,hu(i,0,t),i.depthWrite=i.opacity>=.9,i}updateAlpha(){if(!this._mesh)return;const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,s=this._mesh.material;for(let t=0;t<s.length;t++){const i=s[t];hu(i,0,2===t?e:n),i.depthWrite=i.opacity>=.9}}updateFillStyle(){if(!this._mesh)return;this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0);const t=this._mesh.material;t[2].dispose(),t[2]=this._buildTopMaterial()}updateStrokeStyle(){if(!this._mesh)return;const t=this._mesh.material,e=this._buildSideMaterial();for(let n=0;n<t.length;n++)2!==n&&(t[n].dispose(),t[n]=e)}}t.FloorPlate=class extends Kl{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new jC(this)}get nature(){return RC}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}},t.FloorPlate.requires3d=!0,t.FloorPlate=ug([ov("floor-plate")],t.FloorPlate);function $C(t,e={}){const n=e.size??5,s=e.color??4500172,i=e.emissive??2245734,o=new w.SphereGeometry(n,16,12),r=new w.MeshStandardMaterial({color:s,emissive:i,emissiveIntensity:.15,metalness:.3,roughness:.4,transparent:!0,opacity:.35}),a=new w.Mesh(o,r);e.position&&a.position.set(e.position[0],e.position[1],e.position[2]),a.userData.alwaysRaycast=!0,a.scale.setScalar(1),a.visible=e.visible??!(!0===t.app?.isViewMode);const c=()=>{r.emissiveIntensity=.9,r.opacity=.95,a.scale.setScalar(1.35),t.invalidate?.()},l=()=>{r.emissiveIntensity=.15,r.opacity=.35,a.scale.setScalar(1),t.invalidate?.()};return t.on("mouseenter",c),t.on("mouseleave",l),a.userData.dispose=()=>{t.off("mouseenter",c),t.off("mouseleave",l)},a}class LC extends HT{get zPriority(){return Su.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1,i=new w.PlaneGeometry(n,s);i.rotateX(-Math.PI/2),this.object3d.geometry=i}updateDimension(){this.update()}build(){super.build();const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,s=Math.abs(e)||1,i=Math.max(2,.04*Math.min(n,s));this.object3d.add($C(this.component,{size:i,position:[n/2-i,i,-s/2+i]}))}}const FC={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let NC=class extends(ev(mc(pc))){buildRealObject(){return new LC(this)}get nature(){return FC}};NC=ug([ov("decal")],NC);class HC extends Du{getObject3dInstance(){return new w.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const BC="#dde2e8",GC="#9c9c9c",UC="#e8e8ec",VC=.35;function WC(t,e,n,s,i){if(!e.visible)return new w.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=e.alpha*n,r="wall"===s?BC:"floor"===s?GC:UC,a=new w.MeshStandardMaterial({metalness:0,roughness:"wall"===s?.6:.85,transparent:o<1,opacity:o,side:i?w.BackSide:w.DoubleSide});return function(t,e,n,s,i,o){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const s=!o,r=Du.buildFillStyleTexture(e,n,{mirror:s,rotation:i});if(r)return t.map&&t.map.dispose(),t.map=r,void t.color.set("#ffffff")}t.color.set(s)}}(a,t,e.fillStyle,r,e.rotation,e.mirror),a}class YC extends HC{get zPriority(){return Su.BACKDROP}get position(){if(this.component.state.fitToBoard){return{x:0,y:super.position.y,z:0}}return super.position}build(){super.build();const t=this.component.state;let e=t.width,n=t.height;if(t.fitToBoard){const t=this.component.rootModel,s=t?.state;s&&Number.isFinite(s.width)&&Number.isFinite(s.height)&&(e=s.width,n=s.height)}const s=this.effectiveDepth||Math.min(e,n)||200,i=t.alpha??1,o=!1!==t.seeThrough,r={east:this._resolveFace("east",BC,!0,VC),west:this._resolveFace("west",BC,!0,VC),north:this._resolveFace("north",BC,!0,VC),south:this._resolveFace("south",BC,!0,VC),floor:this._resolveFace("floor",GC,!0,1),ceiling:this._resolveFace("ceiling",UC,!0,1)},a=[WC(this.component,r.east,i,"wall",o),WC(this.component,r.west,i,"wall",o),WC(this.component,r.ceiling,i,"ceiling",o),WC(this.component,r.floor,i,"floor",o),WC(this.component,r.south,i,"wall",o),WC(this.component,r.north,i,"wall",o)],c=new w.BoxGeometry(e,s,n),l=new w.Mesh(c,a);if(l.receiveShadow=!0,this.object3d.add(l),this.component.app?.isEditMode){const t=new w.LineBasicMaterial({color:4473941,transparent:!0,opacity:.7}),e=new w.LineSegments(new w.EdgesGeometry(c),t);this.object3d.add(e)}const h=Math.max(2,.04*Math.min(e,n,s));this.object3d.add($C(this.component,{size:h,position:[e/2,s/2+h,-n/2]}))}_resolveFace(t,e,n,s){const i=this.component.state,o=i.faces?.[t]??{},r=o.visible,a=o.alpha,c=o.rotation,l=90===c||180===c||270===c?c:0;return{fillStyle:o.fillStyle??e,visible:"boolean"==typeof r?r:n,alpha:"number"==typeof a&&Number.isFinite(a)?a:s,rotation:l,mirror:!0===o.mirror}}updateDimension(){}onchange(t,e){["alpha","width","height","depth","fitToBoard","faces","seeThrough"].some(e=>e in t)?this.update():super.onchange(t,e)}updateAlpha(){}}const qC={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"checkbox",label:"fit-to-board",name:"fitToBoard"},{type:"checkbox",label:"see-through",name:"seeThrough"},{type:"backdrop-faces",label:"",name:"faces"}],help:"scene/component/backdrop"};let XC=class extends(ev(mc(pc))){buildRealObject(){return new YC(this)}get workEnvironmentCeiling(){const t=this.state,e=this.rootModel?.state,n=t.fitToBoard&&e&&Number.isFinite(e.width)&&Number.isFinite(e.height),s=n?e.width:Math.abs(Number(t.width)||0),i=n?e.height:Math.abs(Number(t.height)||0),o=Number(t.depth)||Math.min(s,i)||200,r=Number(t.zPos)||0,a=e?.placement;return"inverted"===a?r:"space"===a?r+o/2:r+o}get nature(){return qC}added(t){super.added?.(t),this.state.fitToBoard&&(this._syncFromRoot(!0),this._attachRootListener())}async ready(){await super.ready(),this.state.fitToBoard&&this._syncFromRoot(!1)}removed(t){this._detachRootListener(),super.removed?.(t)}dispose(){this._detachRootListener(),super.dispose?.()}onchange(t,e){"fitToBoard"in t&&(t.fitToBoard?(this._syncFromRoot(!0),this._attachRootListener()):this._detachRootListener()),super.onchange?.(t,e)}_syncFromRoot(t=!1){const e=this.rootModel;if(!e||e===this)return;const n=e.state;if(!n)return;const s={},i=Number.isFinite(n.width)?n.width:this.state.width,o=Number.isFinite(n.height)?n.height:this.state.height;i!==this.state.width&&(s.width=i),o!==this.state.height&&(s.height=o);const r=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(r!==this.state.left&&(s.left=r),a!==this.state.top&&(s.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(i,o);e!==t&&(s.depth=e)}}Object.keys(s).length>0&&this.set(s)}_attachRootListener(){if(this._onRootChange)return;const t=this.rootModel;t&&t!==this&&(this._onRootChange=t=>{("width"in t||"height"in t||"left"in t||"top"in t)&&this._syncFromRoot()},t.on?.("change",this._onRootChange))}_detachRootListener(){if(!this._onRootChange)return;const t=this.rootModel;t?.off?.("change",this._onRootChange),this._onRootChange=void 0}};function KC(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function JC(t,e,n,s){const i=[];for(let o=1;o<=s;o++){const r=o/s,a=1-r;i.push(new w.Vector3(a*a*t.x+2*a*r*e.x+r*r*n.x,a*a*t.y+2*a*r*e.y+r*r*n.y,a*a*t.z+2*a*r*e.z+r*r*n.z))}return i}XC=ug([ov("backdrop")],XC);class QC extends Du{getObject3dInstance(){return new w.Group}get gizmoTransformable(){return!0}get syncZPosOffset(){return 0}get geometricOffsetY(){return 0}syncFromObject3D(){}applyDimensionFromGizmo(t){}build(){super.build(),this._buildLine()}get smoothedPath(){const t=this.worldPath;if(t.length<2)return t;const{round:e=0}=this.component.state;if(e<=0||t.length<3)return t;const n=[];n.push(t[0]);for(let s=1;s<t.length;s++){const i=t[s-1],o=t[s],r=t[s+1];if(!r){n.push(o);break}const a=i.x-o.x,c=i.y-o.y,l=i.z-o.z,h=Math.sqrt(a*a+c*c+l*l),d=Math.min(e,h/2),u=r.x-o.x,p=r.y-o.y,f=r.z-o.z,m=Math.sqrt(u*u+p*p+f*f),g=Math.min(e,m/2),y=h>0?new w.Vector3(o.x+a/h*d,o.y+c/h*d,o.z+l/h*d):o.clone(),b=m>0?new w.Vector3(o.x+u/m*g,o.y+p/m*g,o.z+f/m*g):o.clone();n.push(y),n.push(...JC(y,o,b,8))}return n}_buildLine(){const t=this.smoothedPath;if(t.length<2)return;const{strokeStyle:e,lineWidth:n=2,alpha:s=1,lineDash:i,begin:o="none",beginSize:r="size5",end:a="none",endSize:c="size5"}=this.component.state,l=Math.max(n,1),p="string"==typeof e&&"transparent"!==e?du(e):"#000000",f=new w.Color(p),m=this._getResolution(),g=o,y=a,b=KC(g,l),v=KC(y,l),_=t[0],x=t[t.length-1],M=(new w.Vector3).subVectors(t[1],_).normalize(),S=(new w.Vector3).subVectors(t[t.length-2],x).normalize(),A=[...t];b>0&&(A[0]=_.clone().add(M.clone().multiplyScalar(b))),v>0&&(A[A.length-1]=x.clone().add(S.clone().multiplyScalar(v)));const k=new u.LineGeometry;k.setPositions(A.flatMap(t=>[t.x,t.y,t.z]));const E=function(t,e){switch(t){case"round-dot":return{dashSize:e,gapSize:e};case"square-dot":return{dashSize:2*e,gapSize:e};case"dash":return{dashSize:4*e,gapSize:1.5*e};case"dash-dot":return{dashSize:4*e,gapSize:2*e};case"long-dash":return{dashSize:6*e,gapSize:3*e};case"long-dash-dot":return{dashSize:6*e,gapSize:2*e};case"long-dash-dot-dot":return{dashSize:6*e,gapSize:e};default:return null}}(i,l),T=new d.LineMaterial({color:f.getHex(),linewidth:l,worldUnits:!0,transparent:s<1,opacity:s,resolution:m,dashed:!!E,dashSize:E?.dashSize??1,gapSize:E?.gapSize??1,dashScale:1});if(this._line2=new h.Line2(k,T),this._line2.computeLineDistances(),this.object3d.add(this._line2),"none"!==g){const t=nf(g,ef(r,l));if(t){const e=(new w.Quaternion).setFromUnitVectors(new w.Vector3(1,0,0),M.clone().negate());this._placeTip(t,_,e,f,s,m)}}if("none"!==y){const t=nf(y,ef(c,l));if(t){const e=(new w.Quaternion).setFromUnitVectors(new w.Vector3(1,0,0),S.clone().negate());this._placeTip(t,x,e,f,s,m)}}}_placeTip(t,e,n,s,i,o){const r=t.mesh||t.line2||t.group;if(r){if(r.position.copy(e),r.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(s),e.transparent=i<1,e.opacity=i}else if(t.line2){const e=t.line2.material;e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution.copy(o)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution&&e.resolution.copy(o)}});this.object3d.add(r)}}_getResolution(){const t=this.threeContainer?.renderer3d;if(t){return t.getSize(new w.Vector2)}return new w.Vector2(window.innerWidth,window.innerHeight)}onGizmoDragEnd(t){const e=this._component,n=e.path;if(!n||n.length<2)return;const s=this.object3d,{width:i=0,height:o=0}=e.parent?.bounds??{},{x:r,y:a}=e.center,c=s.position,l=s.rotation,h=s.scale,d=this.position;if(Math.abs(c.x-d.x)<.001&&Math.abs(c.y-d.y)<.001&&Math.abs(c.z-d.z)<.001&&Math.abs(l.x)<.001&&Math.abs(l.y)<.001&&Math.abs(l.z)<.001&&Math.abs(h.x-1)<.001&&Math.abs(h.y-1)<.001&&Math.abs(h.z-1)<.001)return;const u=QC.computeBakedPath(n,{x:r,y:a},{width:i,height:o},s);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(t,e,n,s){const i=n.width,o=n.height,r=e.x,a=e.y;return s.updateMatrixWorld(!0),t.map(t=>{const e=new w.Vector3(t.x-r,t.z||0,t.y-a).applyMatrix4(s.matrixWorld),n={x:e.x+i/2,y:e.z+o/2};return Math.abs(e.y)>.001&&(n.z=e.y),n})}updateStrokeStyle(){this.updateDimension()}updateAlpha(){this.updateDimension()}updateDimension(){this.clear(),this.build()}onchange(t,e){("path"in t||"from"in t||"to"in t)&&(this.updateDimension(),this.updatePosition()),("round"in t||"lineDash"in t||"lineWidth"in t||"begin"in t||"end"in t||"beginSize"in t||"endSize"in t)&&this.updateDimension(),super.onchange(t,e)}clear(){for(;this.object3d.children.length>0;){const t=this.object3d.children[0];this.object3d.remove(t),bu(t)}return this._line2=void 0,super.clear()}}class ZC extends QC{get worldPath(){const t=this.component.path;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center,s=this.component,i=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return t.map((s,r)=>{const a=t.length>1?r/(t.length-1):0;return new w.Vector3(s.x-e,s.z||i+(o-i)*a,s.y-n)})}}hf("line",t=>new ZC(t));class tO extends QC{get worldPath(){const t=this.component.path;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center;return t.map(t=>new w.Vector3(t.x-e,t.z||0,t.y-n))}}hf("polyline",t=>new tO(t));class eO extends QC{get worldPath(){const t=this.component.drawPath;if(!t||t.length<2)return[];const{x:e,y:n}=this.component.center,s=this.component,i=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return t.map((s,r)=>{const a=t.length>1?r/(t.length-1):0;return new w.Vector3(s.x-e,s.z||i+(o-i)*a,s.y-n)})}}function nO(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}hf("ortholine",t=>new eO(t)),hf("group",t=>new HC(t));class sO{constructor(t){this._count=0,this._placements=[],this._geometry=t.geometry,this._material=t.material,this._capacity=Math.max(1,t.capacity??16),this._name=t.name??"instanced",this._castShadow=t.castShadow??!0,this._receiveShadow=t.receiveShadow??!1,this.object3d=new w.Group,this.object3d.name=this._name,this._mesh=this._makeMesh(this._capacity),this.object3d.add(this._mesh)}_makeMesh(t){const e=new w.InstancedMesh(this._geometry,this._material,t);return e.name=this._name+"__instances",e.castShadow=this._castShadow,e.receiveShadow=this._receiveShadow,e.instanceMatrix.setUsage(w.DynamicDrawUsage),e.count=0,e}get mesh(){return this._mesh}get material(){return this._material}set material(t){this._material=t,this._mesh.material=t}get count(){return this._count}get capacity(){return this._capacity}place(t){const e=t.length;if(e>this._capacity){const t=nO(e,this._capacity);this.object3d.remove(this._mesh),this._mesh.dispose(),this._capacity=t,this._mesh=this._makeMesh(t),this.object3d.add(this._mesh)}this._placements.length=e;for(let n=0;n<e;n++){const e=t[n];this._placements[n]=e,this._writeMatrix(n,e),void 0!==e.color&&this._writeColor(n,e.color)}this._count=e,this._mesh.count=e,this.commit()}setCount(t){if(t>this._capacity){const e=nO(t,this._capacity),n=this._mesh.frustumCulled;this.object3d.remove(this._mesh),this._mesh.dispose(),this._capacity=e,this._mesh=this._makeMesh(e),this._mesh.frustumCulled=n,this.object3d.add(this._mesh)}this._placements.length=0,this._count=t,this._mesh.count=t}setMatrix(t,e){t<0||t>=this._count||this._mesh.setMatrixAt(t,e)}update(t,e){t<0||t>=this._count||(this._placements[t]=e,this._writeMatrix(t,e),void 0!==e.color&&this._writeColor(t,e.color),this.commit())}setRotation(t,e){if(t<0||t>=this._count)return;const n=this._placements[t];n&&(n.rotation=e,this._writeMatrix(t,n))}commitMatrices(){this._mesh.instanceMatrix.needsUpdate=!0}setColor(t,e){t<0||t>=this._count||(this._writeColor(t,e),this._mesh.instanceColor&&(this._mesh.instanceColor.needsUpdate=!0))}indexOf(t){return t>=0&&t<this._count?t:-1}commit(){this._mesh.instanceMatrix.needsUpdate=!0,this._mesh.instanceColor&&(this._mesh.instanceColor.needsUpdate=!0),this._mesh.computeBoundingSphere()}dispose(){this.object3d.remove(this._mesh),this._mesh.dispose(),this._placements.length=0,this._count=0}_writeMatrix(t,e){const n=sO;n._p.set(e.position.x,e.position.y,e.position.z);const s=e.rotation;n._e.set(s?.x??0,s?.y??0,s?.z??0),n._q.setFromEuler(n._e);const i=e.scale;"number"==typeof i?n._s.set(i,i,i):n._s.set(i?.x??1,i?.y??1,i?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){sO._c.set(e),this._mesh.setColorAt(t,sO._c)}}function iO(t,e,n){const s=Math.max(1,Math.floor(t.x??1)),i=Math.max(1,Math.floor(t.y??1)),o=Math.max(1,Math.floor(t.z??1)),r=e.x??0,a=e.y??0,c=e.z??0,l=n?.x??0,h=n?.y??0,d=n?.z??0,u=[];for(let t=0;t<i;t++)for(let e=0;e<o;e++)for(let n=0;n<s;n++)u.push({position:{x:l+n*r,y:h+t*a,z:d+e*c}});return u}sO._m=new w.Matrix4,sO._p=new w.Vector3,sO._q=new w.Quaternion,sO._e=new w.Euler,sO._s=new w.Vector3,sO._c=new w.Color;class oO extends Du{build(){super.build()}update(){}}const rO={far:1e5,fov:80,near:1,zoom:1};class aO extends Du{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new w.PerspectiveCamera}updateCamera(){const{near:t=rO.near,far:e=rO.far,fov:n=rO.fov,zoom:s=rO.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=s}}class cO extends HT{buildGeometry(){const{width:t,height:e}=this.component.state.dimension;this.object3d.geometry=new w.PlaneGeometry(t,e)}buildMaterial(){this.object3d.material=new w.MeshStandardMaterial({opacity:0,side:w.DoubleSide,blending:w.NoBlending})}}class lO extends Du{getObject3dInstance(){return new w.Scene}dispose(){for(const t of this.object3d.children)bu(t);this._animationMixer&&(this._animationMixer.stopAllAction(),this._animationMixer.uncacheRoot(this.object3d),this._animationMixer=void 0),super.dispose()}clear(){return this._floor&&(this.object3d.remove(this._floor),this._floor.material instanceof Array?this._floor.material.forEach(t=>t.dispose()):this._floor.material.dispose(),this._floor.geometry.dispose(),delete this._floor),super.clear()}get floor(){return this._floor}set floor(t){this._floor&&(this.object3d.remove(this._floor),this._floor.clear(),delete this._floor),t&&(this._floor=t,this.object3d.add(t)),this.component.invalidate()}build(){super.build(),this.floor=Tf(this.component)}updateTransform(){}updateDimension(){}updatePosition(){}updateRotate(){}updateScale(){}updateAlpha(){}updateHidden(){}get animationMixer(){return this._animationMixer||(this._animationMixer=new w.AnimationMixer(this.object3d)),this._animationMixer}}const hO=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class dO extends Du{get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}constructor(t){super(t),this._origInvalidate=t.invalidate.bind(t),t.invalidate=()=>{this._origInvalidate(),this._refreshTextureNow()}}getObject3dInstance(){return new w.Mesh}build(){super.build();const{width:t,height:e}=this.component.bounds;if(!t||!e)return;const n=Nd(this.component.state.material3d),s=new w.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const i=IT(this.component),o=new w.MeshStandardMaterial({map:i});Gd(o,n),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=n.castShadow,this.object3d.receiveShadow=n.receiveShadow}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;hu(this.object3d.material,0,e)}get dimension(){const{width:t,height:e}=this.component.bounds;return{width:t||1,height:e||1,depth:1}}get scale(){const t=super.scale,{width:e,height:n}=this.dimension;return{x:t.x*e,y:t.y,z:t.z*n}}updateDimension(){this.updateTransform()}_debouncedRebuild(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=void 0,this.update()},100)}_refreshTextureNow(){const t=this.object3d.material,e=t?.map;if(!e)return;const n=e.source?.data;n&&(zT(n,this.component,2),e.needsUpdate=!0)}update(){this.clear(),this.build(),this.updateDimension(),this.updateTransform(),this.updateHidden()}onchange(t,e){super.onchange(t,e);for(const e of Object.keys(t))if(!hO.has(e)){this._debouncedRebuild();break}}updateFillStyle(){this._debouncedRebuild()}updateStrokeStyle(){this._debouncedRebuild()}updateText(){this._debouncedRebuild()}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Nd(this.component.state.material3d);Gd(t,e),t.transparent=!0,this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}clear(){return this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),bu(this.object3d),super.clear()}dispose(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=void 0),this._origInvalidate&&(this.component.invalidate=this._origInvalidate,this._origInvalidate=void 0),super.dispose()}}const uO={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"precision",name:"precision",property:{options:[{display:"High",value:"highp"},{display:"Medium",value:"mediump"},{display:"Low",value:"lowp"}]}},{type:"checkbox",label:"anti-alias",name:"antialias",property:"antialias"},{type:"checkbox",label:"3dmode",name:"threed",property:"threed"},{type:"checkbox",label:"figure-lod",name:"lodEnabled",property:"lodEnabled"},{type:"checkbox",label:"auto-rotate",name:"autoRotate",property:"autoRotate"},{type:"checkbox",label:"debug",name:"debug",property:"debug"}],help:"scene/component/three-container"};function pO(t){if(Array.isArray(t))return`[${t.map(pO).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${pO(e[t])}`).join(",")}}`}return JSON.stringify(t)}t.ThreeContainer=class extends Cy{constructor(){super(...arguments),this._capability=new rm}get sceneManager(){return this._capability.sceneManager}get cameraManager(){return this._capability.cameraManager}get rendererManager(){return this._capability.rendererManager}get lightManager(){return this._capability.lightManager}get controlsManager(){return this._capability.controlsManager}get eventManager(){return this._capability.eventManager}get hasEnvironment(){return this._capability.hasEnvironment}containable(t){return!0}is3dContainer(){return!0}getLightingConfig(){return{hemisphere:{skyColor:16777215,groundColor:14540253,intensity:1},directional:{color:16777215,intensity:1.2,attachToCamera:!0,castShadow:!1}}}getCss3DSceneAttribute(){return"three-container:css3d-renderer"}init_scene3d(){this._capability.isInitialized&&this._capability.destroy(),this._capability.init(this,{lightingConfig:this.getLightingConfig(),css3DSceneAttribute:this.getCss3DSceneAttribute(),skipEnvironment:!0,skipPostprocessing:!0,skipShadowMap:!0}),this._capability.buildOverlays(),this._capability.resize(),this.onchangeData&&this.onchangeData(this.data,this.data)}destroy_scene3d(){this.stop(),this._capability.destroy()}stop(){}resize(){this._capability.resize()}get scene3d(){return this._capability.isInitialized||this.init_scene3d(),this._capability.scene3d}get renderer3d(){return this._capability.renderer3d}get mixer(){return this._capability.mixer}get css3DScene(){return this._capability.css3DScene}get css3DRenderer(){return this._capability.css3DRenderer}render_threed(){this._capability.renderThreeD()}get _parentIs3dMode(){return!!this.rootModel?.is3dMode}render(t){this._parentIs3dMode||(this.app.isViewMode&&this.setState("threed",!0),!this.state.threed||this._capability.noSupportWebgl?super.render(t):this._capability.camera&&this._capability.renderCSS3D())}postrender(t){if(this._parentIs3dMode)return;const{left:e,top:n,debug:s,threed:i}=this.state;let{width:o,height:r}=this.bounds;if(o=Math.floor(o),r=Math.floor(r),i){if(this._capability.isInitialized||this.init_scene3d(),this._capability.noSupportWebgl)return void this._capability.showWebglNoSupportText(t,this.state.width,this.state.height);if(!this._capability.renderer3d)return;this._capability.renderThreeD();const i=this._capability.domElement;if(!i||!i.width||!i.height)return;t.drawImage(i,0,0,i.width,i.height,e,n,o,r),s&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return xc.get("three")}get nature(){return uO}getObjectByRaycast(){return this._capability.getObjectByRaycast()}getObjectsByRaycast(){return this._capability.getObjectsByRaycast()}onchange(t,e){(t.hasOwnProperty("width")||t.hasOwnProperty("height"))&&this._capability.destroy(),this._capability.onchange(t)}onmousedown(t){this._capability.onMouseDown(t)}onmouseup(t){this._capability.onMouseUp(t)}onmousemove(t){this._capability.onMouseMove(t)}onmouseleave(t){this._capability.onMouseLeave(t)}onwheel(t){this._capability.onWheel(t)&&this.invalidate()}ondblclick(t){this._capability.onDblClick(t)&&this.invalidate()}ondragstart(t){this._capability.onDragStart(t)}ondragmove(t){this._capability.onDragMove(t)&&this.invalidate()}ondragend(t){this._capability.onDragEnd(t)&&this.invalidate()}ontouchstart(t){this._capability.onTouchStart(t)}onpan(t){this._capability.onPan(t)&&this.invalidate()}ontouchend(t){this._capability.onTouchEnd(t)}onkeydown(t){this._capability.onKeyDown(t)}onpinch(t){this._capability.onPinch(t)&&this.invalidate()}ondoubletap(){this._capability.onDoubleTap(),this.invalidate()}},t.ThreeContainer=ug([ov("3d-container")],t.ThreeContainer),df(t=>new jT(t));const fO=new Map;function mO(t){const e=function(t){const e=pO(t),n=t=>{let n=t>>>0;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619)>>>0;return n.toString(16).padStart(8,"0")};return n(2166136261)+n(2538058380)}(t),n=`${e}|${Ix}`,s=fO.get(n);if(s)return fO.delete(n),fO.set(n,s),s;const i=structuredClone(t),o=new Map;for(const t of i.document.model.nodes)for(const e of Object.values(t.outputs))o.set(e,t.id);const r={key:n,fingerprint:e,kernel:Ix,compiled:qS(i),document:rS(i.document),looks:new Map(i.appearance.map(t=>[t.target,t])),writers:o,asset:i};return fO.set(n,r),fO.size>256&&fO.delete(fO.keys().next().value),r}let gO=null;function yO(t){gO=t}function bO(t,e=[],n,s){gO?.registerType?.(t,e,n,s)}const vO=$v,_O=new Map,xO=new Map,wO=new Set;function MO(t,e){if(!vO.includes(t.name)&&!Fv(t.name))throw new Error(`능력 이름 ${t.name} 은 공용 넷도, <이름공간>.<이름> 도 아니다`);const n={descriptor:t,...e?{mixin:e}:{}};xO.set(t.name,n),_O.clear();for(const t of[...wO])t();return()=>{if(xO.get(t.name)===n){xO.delete(t.name),_O.clear();for(const t of[...wO])t()}}}function SO(){return[...xO.values()].map(t=>t.descriptor).sort((t,e)=>Number(Fv(t.name))-Number(Fv(e.name)))}const AO=t=>xO.get(t)?.descriptor;function kO(t){return wO.add(t),()=>wO.delete(t)}MO({name:"Capacity",label:"Capacity",note:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",version:"1",needs:[]},t=>kk(t)),MO({name:"Holdable",label:"Holdable",note:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",version:"1",needs:[]},t=>NE(t)),MO({name:"Transferable",label:"Transferable",note:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",version:"1",needs:Object.entries(Hv).flatMap(([t,e])=>"Transferable"===t?[e]:[])},t=>BE(t)),MO({name:"FlowNode",label:"FlowNode",note:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다",version:"1",needs:[]},t=>GE(t));const EO=t=>xO.get(t).mixin;function TO(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:t.accepts?[...t.accepts]:[]}))}function CO(t,e){const n=[...new Set(t)],s=n.filter(t=>!vO.includes(t)&&!Fv(t));if(s.length>0)throw new Error(`모르는 능력이다: ${s.join(" · ")} — 쓸 수 있는 것은 ${vO.join(" · ")}, 또는 <이름공간>.<이름>`);const i=[];let o=n.filter(t=>!!vO.includes(t)||(!!xO.has(t)||(i.push({code:"CAPABILITY_UNREGISTERED",severity:"warning",name:t}),!1)));const r=t=>"item"===t?!!e?.item:o.includes(t);for(let t=!0;t;){t=!1;for(const e of o){const n=xO.get(e).descriptor.needs.filter(t=>Array.isArray(t)?!t.some(r):!r(t)).map(t=>Array.isArray(t)?t.join(" 이나 "):t);if(n.length){if(!Fv(e))throw new Error(`${e} 은 혼자 설 수 없다 — ${n.join(", ")} 가 함께 있어야 한다`);i.push({code:"CAPABILITY_NEEDS",severity:"warning",name:e,reasons:n}),o=o.filter(t=>t!==e),t=!0;break}}}return e&&(o=o.filter(t=>{const n=xO.get(t).descriptor,s=n.check?.(e.document.capabilities.extensions?.[t],e)??[];return!s.length||(i.push({code:"CAPABILITY_SETTINGS",severity:"warning",name:t,reasons:s}),!1)})),{names:o,issues:i}}function OO(t,e=[],n,s){const i=CO(e,s);for(const t of i.issues)console.warn(`[figure] ${t.code} ${t.name}${t.reasons?` — ${t.reasons.join(" · ")}`:""}`);const o=new Set(i.names),r=`${[...o].sort().join("+")}|${n??""}`,a=_O.get(r);if(a)return a;const c=[...o].filter(t=>Fv(t)),l=new Set([...o].filter(t=>!Fv(t))),h=0===l.size?t:(d=PO(function(t,e){if(e.has("FlowNode"))return EO("FlowNode")(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=EO(t)(n));return e.has("Holdable")&&(n=wv(n)),n}(t,l),l),class extends d{get _places(){const t=TP(this.state);return t?BA(t):null}get slots(){const t=this._places;return t?.length?TO(t):super.slots??[]}get effectiveLayout(){return CP(this.state)??super.effectiveLayout}get _itemsBound(){const t=BO(this.state?.type)?.compiled.asset;return!!t?.dataInterface?.bindings.some(t=>"table"!==t.rule&&"items"===t.behavior.kind)}_itemsFromData(){return!this._itemsBound&&(super._itemsFromData?.()??!0)}_keyedById(){return this._itemsBound||(super._keyedById?.()??!1)}_createItemFromRecord(t){if(!this._itemsBound)return super._createItemFromRecord(t);const e=this.slots.find(e=>e.id===t.slotId)?.allowedTypes??[],n=t.itemType??(1===e.length?e[0]:void 0);return new zv({...n?{type:n}:{},...t.itemState??{},id:t.itemId})}_syncItemsFromData(){if(!this._itemsBound||"function"!=typeof this._reconcileItems)return;const t=(this.figureInputs?.data?.items??[]).flatMap(t=>[...t.records].map((t,e)=>({r:t,i:e})).sort((t,e)=>(t.r.stack??t.i)-(e.r.stack??e.i)).map(({r:e})=>({slotId:e.place??t.slot??"",itemId:e.id,...e.type?{itemType:e.type}:{},itemState:{id:e.id,...void 0!==e.status?{status:e.status}:{}}})));this._reconcileItems(t)}onchange(t,e){super.onchange?.(t,e),"data"in t&&this._syncItemsFromData()}async ready(){await(super.ready?.()),this._syncItemsFromData()}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,s=e?.slotId??t?.[_v],i=this._places;return i&&s&&i.some(t=>t.id===s)?this._realObject?.placeAttachment?.(s,t)??n():n()}});var d;const u=c.length?PO(c.reduce((t,e)=>xO.get(e).mixin?.(t)??t,class extends h{}),o):h,p=void 0===n?u:function(t,e){const n=class extends t{};return Object.defineProperty(n,"placement",{value:e,enumerable:!0}),Object.defineProperty(n,"name",{value:`${t.name??"Figure"}·${e}`}),n}(u,n);return _O.set(r,p),p}function PO(t,e){const n=t.capabilities??[],s=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(s),configurable:!0}),t}function IO(t){return zO(t,t=>!!xO.get(t)?.mixin)}function DO(t){return zO(t,()=>!0)}function zO(t,e){const{names:n}=CO(t.document.capabilities.names??[],t),s=[];for(const i of n){const n=xO.get(i).descriptor.takes?.(t.document.capabilities.extensions?.[i],t);if(!n)continue;const o={...n,items:!!n.items&&e(i)},r=new Set(o.parts??[]),a=new Set(o.inputs??[]);for(const e of t.dataInterface?.bindings??[])if(!s.some(t=>t.id===e.id&&t.whole))if("table"===e.rule){const t=(e.targets.parts??[]).filter(t=>r.has(t)),n=(e.targets.inputs??[]).filter(t=>a.has(t));if(!t.length&&!n.length)continue;const o=!e.targets.group&&t.length===(e.targets.parts??[]).length&&n.length===(e.targets.inputs??[]).length;s.push({id:e.id,capability:i,whole:o,parts:t,inputs:n})}else("items"===e.behavior.kind&&o.items||"state"===e.behavior.kind&&a.has(e.behavior.input))&&s.push({id:e.id,capability:i,whole:!0,parts:[],inputs:"state"===e.behavior.kind?[e.behavior.input]:[]})}return s}function RO(t){const{names:e}=CO(t.document.capabilities.names??[],t),n=[];let s=function(t,e){if(!e.length||!t.dataInterface)return t;const n=t.dataInterface.bindings.flatMap(t=>{const n=e.filter(e=>e.id===t.id);if(!n.length)return[t];if("table"!==t.rule||n.some(t=>t.whole))return[];const s=(t.targets.parts??[]).filter(t=>!n.some(e=>e.parts.includes(t))),i=(t.targets.inputs??[]).filter(t=>!n.some(e=>e.inputs.includes(t)));if(!s.length&&!i.length&&!t.targets.group)return[];const o=Object.fromEntries(Object.entries(t.table).map(([t,e])=>{const{color:n,effect:o,values:r,...a}=e,c=r&&Object.fromEntries(Object.entries(r).filter(([t])=>i.includes(t)));return[t,{...a,...s.length?{...void 0!==n?{color:n}:{},...void 0!==o?{effect:o}:{}}:{},...c&&Object.keys(c).length?{values:c}:{}}]})),r={...s.length?{parts:s}:{},...i.length?{inputs:i}:{},...t.targets.group?{group:t.targets.group}:{}};return[{...t,targets:r,table:o}]});return{...t,dataInterface:{...t.dataInterface,bindings:n}}}(t,IO(t));for(const i of e){const e=xO.get(i).descriptor,o=e.dataInterface?.(t.document.capabilities.extensions?.[i],t);if(!o||!o.bindings.length&&!o.schema?.length)continue;const r=s.dataInterface??{version:"figure-data-interface-2",schema:[],bindings:[]},a=[...r.schema,...(o.schema??[]).filter(t=>!r.schema.some(e=>e.name===t.name))],c={...s,dataInterface:{...r,schema:a,bindings:[...r.bindings,...o.bindings]}};try{qS(c),s=c}catch(t){n.push({code:"CAPABILITY_SETTINGS",severity:"warning",name:i,reasons:[t instanceof Error?t.message:String(t)]})}}return{asset:s,issues:n}}function jO(){_O.clear()}const $O=new Map,LO=new Set;function FO(t){return LO.add(t),()=>LO.delete(t)}function NO(){for(const t of[...LO])t()}function HO(t,e){qS(e);const{asset:n,issues:s}=RO(e);for(const t of s)console.warn(`[figure] ${t.code} ${t.name} — ${t.reasons?.join(" · ")}`);const i={type:t,compiled:mO(n)};return $O.set(t,i),bO(t,n.document.capabilities.names??[],n.placement,n),NO(),i}function BO(t){return $O.get(t)??null}function GO(t){return $O.has(t)}function UO(t){const e=$O.delete(t);return e&&NO(),e}function VO(){$O.clear(),NO()}const WO=Math.cos(40*Math.PI/180);function YO(t){const[e,n]=Kv[t];return([s,i],o)=>{const r={x:0,y:0,z:0};return r[e]=s,r[n]=i,r[t]=o,new w.Vector3(r.x,r.y,r.z)}}class qO{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,s,i,o){for(const[r,a]of[[t,s],[e,i],[n,o]])this.positions.push(r.x,r.y,r.z),this.normals.push(a.x,a.y,a.z)}facing(t,e,n,s){(new w.Vector3).subVectors(e,t).cross((new w.Vector3).subVectors(n,t)).dot(s)<0?this.tri(t,n,e,s,s,s):this.tri(t,e,n,s,s,s)}geometry(){const t=new w.BufferGeometry;return t.setAttribute("position",new w.Float32BufferAttribute(this.positions,3)),t.setAttribute("normal",new w.Float32BufferAttribute(this.normals,3)),t}}function XO(t,e,n,s,i,o){const r=YO(n),a=e.length,c=e.map((t,n)=>{const s=e[(n+1)%a],i=s[0]-t[0],r=s[1]-t[1],c=Math.hypot(i,r)||1;return[o*r/c,-o*i/c]}),l=t=>r(t,0),h=(t,e)=>{const n=c[t],s=c[e];return n[0]*s[0]+n[1]*s[1]<WO?l(n):l([n[0]+s[0],n[1]+s[1]]).normalize()};for(let n=0;n<a;n++){const o=e[n],d=e[(n+1)%a],u=h(n,(n-1+a)%a),p=h(n,(n+1)%a),f=r(o,s),m=r(d,s),g=r(d,i),y=r(o,i),b=l(c[n]);(new w.Vector3).subVectors(m,f).cross((new w.Vector3).subVectors(g,f)).dot(b)>=0?(t.tri(f,m,g,u,p,p),t.tri(f,g,y,u,p,u)):(t.tri(f,g,m,u,p,p),t.tri(f,y,g,u,u,p))}}function KO(t,e,n,s,i,o){const r=YO(n),a=r([0,0],i),c=e.map(([t,e])=>new w.Vector2(t,e)),l=o?[o.map(([t,e])=>new w.Vector2(t,e))]:[],h=w.ShapeUtils.triangulateShape(c,l),d=[...e,...o??[]];for(const[e,n,i]of h)t.facing(r(d[e],s),r(d[n],s),r(d[i],s),a)}const JO=new Map;let QO=0,ZO=67108864;function tP(){return{entries:JO.size,bytes:QO,limit:ZO}}function eP(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),s=t.extrusion,i=t.cavity,o=t.revolution,r=t.loft,a=t.mesh,c=a?`${a.asset}:${a.node??"-"}:${["x","y","z"].map(t=>`${Math.round(1e6*a.bounds[t].min)/1e6}~${Math.round(1e6*a.bounds[t].max)/1e6}`).join(",")}`:s?`${s.axis}:${s.section.kind}:${i?`${"open"===i.start?"o":"c"}${"open"===i.end?"o":"c"}`:"-"}`:o?`${o.axis}:${o.profile.kind}`:r?`${r.axis}:point`:"";return`${t.provider}|${c}|${n}|s${e}|p1`}function nP(t,e=12,n=1/0){const s=eP(t,e),i=JO.get(s);if(i)return i.users++,i.geometry;const o=iP(t,e),r=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(o);if(QO+r>ZO||r>n)throw o.dispose(),new Error("figure: geometry bank budget exceeded");return o.userData.figureKey=s,JO.set(s,{geometry:o,users:1,bytes:r}),QO+=r,o}function sP(t){const e=t.userData.figureKey;if(!e)return;const n=JO.get(e);n&&--n.users<=0&&(JO.delete(e),QO-=n.bytes,n.geometry.dispose())}function iP(t,e=12){if("extrude"===t.provider&&t.extrusion)return function(t,e){const n=t.extrusion,s=QA(n.section,n.axis,e),i=new qO;XO(i,s,n.axis,n.start,n.end,1);const o=t.cavity,r=o&&c_(n.section,n.axis,o.wall);if(!o||!r||!("section"in r))return KO(i,s,n.axis,n.start,-1),KO(i,s,n.axis,n.end,1),i.geometry();const a=QA(r.section,n.axis,e,r.centre),c=n.start+("open"===o.start?0:o.start.closed),l=n.end-("open"===o.end?0:o.end.closed);return XO(i,a,n.axis,c,l,-1),"open"===o.start?KO(i,s,n.axis,n.start,-1,a):(KO(i,s,n.axis,n.start,-1),KO(i,a,n.axis,c,1)),"open"===o.end?KO(i,s,n.axis,n.end,1,a):(KO(i,s,n.axis,n.end,1),KO(i,a,n.axis,l,-1)),i.geometry()}(t,e);if("revolve"===t.provider&&t.revolution)return function(t,e){const n=t.profile;let s;return"half-ellipse"===n.kind?s=new w.SphereGeometry(1,e,Math.max(2,Math.round(e/2))).scale(n.radial,n.axial,n.radial):(s=new w.CylinderGeometry(n.endRadius,n.startRadius,n.end-n.start,e),s.translate(0,(n.start+n.end)/2,0)),"x"===t.axis&&s.rotateZ(-Math.PI/2),"z"===t.axis&&s.rotateX(Math.PI/2),s}(t.revolution,e);const n=t.loft;if("loft"===t.provider&&n)return function(t){const[e,n]=Kv[t.axis],s=YO(t.axis),i=QA(t.section,t.axis,0),o=s([t.apex[e],t.apex[n]],t.end),r=new qO;KO(r,i,t.axis,t.start,t.end>t.start?-1:1);const a=i.length;for(let e=0;e<a;e++){const n=s(i[e],t.start),c=s(i[(e+1)%a],t.start),l=(new w.Vector3).subVectors(c,n).cross((new w.Vector3).subVectors(o,n)).normalize();r.tri(n,c,o,l,l,l)}return r.geometry()}(n);const s=t.mesh;if("mesh"===t.provider&&s){const t=s.bounds,e=new w.BoxGeometry(t.x.max-t.x.min,t.y.max-t.y.min,t.z.max-t.z.min);return e.translate((t.x.min+t.x.max)/2,(t.y.min+t.y.max)/2,(t.z.min+t.z.max)/2),e}return new w.BufferGeometry}const oP=new Map;let rP=0,aP=0,cP=67108864;function lP(t,e=1/0){const n=(t=>t.map(t=>eP(t.shape,t.segments)).join(";"))(t),s=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const s=t.pose.r,i=t.pose.t;e.set([s[0][0],s[0][1],s[0][2],s[1][0],s[1][1],s[1][2],s[2][0],s[2][1],s[2][2],i[0],i[1],i[2]],12*n)}),e}(t),i=oP.get(n),o=i?.find(t=>function(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}(t.poses,s));if(o)return o.users++,o;const r=t.map(t=>nP(t.shape,t.segments));try{const o=r.map(t=>t.index?.count??t.getAttribute("position")?.count??0),a=o.reduce((t,e)=>t+e,0),c=6*a*4;if(c>e)throw new Error("figure: LOD transition budget exceeded");if(aP+c>cP)return null;const l=new Float32Array(3*a),h=new Float32Array(3*a),d=new Int32Array(t.length+1),u=new w.Matrix4,p=new w.Matrix3;let f=0;t.forEach((t,e)=>{d[e]=f/3;const{r:n,t:s}=t.pose;u.set(n[0][0],n[0][1],n[0][2],s[0],n[1][0],n[1][1],n[1][2],s[1],n[2][0],n[2][1],n[2][2],s[2],0,0,0,1),p.getNormalMatrix(u);const i=u.elements,a=p.elements,c=r[e].getAttribute("position"),m=r[e].getAttribute("normal"),g=r[e].index;for(let t=0;t<o[e];t++,f++){const e=g?g.getX(t):t,n=c.getX(e),s=c.getY(e),o=c.getZ(e);if(l[3*f]=i[0]*n+i[4]*s+i[8]*o+i[12],l[3*f+1]=i[1]*n+i[5]*s+i[9]*o+i[13],l[3*f+2]=i[2]*n+i[6]*s+i[10]*o+i[14],!m)continue;const r=m.getX(e),d=m.getY(e),u=m.getZ(e),p=a[0]*r+a[3]*d+a[6]*u,y=a[1]*r+a[4]*d+a[7]*u,b=a[2]*r+a[5]*d+a[8]*u,v=Math.hypot(p,y,b)||1;h[3*f]=p/v,h[3*f+1]=y/v,h[3*f+2]=b/v}}),d[t.length]=f/3;const m=new w.BufferGeometry;m.setAttribute("position",new w.BufferAttribute(l,3)),m.setAttribute("normal",new w.BufferAttribute(h,3)),m.computeBoundingSphere(),m.computeBoundingBox();const g={geometry:m,starts:d,users:1,bytes:c,poses:s};return m.userData.figureMergedKey=n,m.userData.figureMergedEntry=g,i?i.push(g):oP.set(n,[g]),rP++,aP+=c,g}finally{for(const t of r)sP(t)}}function hP(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,s=void 0===e?void 0:oP.get(e);!n||!s?.includes(n)||--n.users>0||(s.splice(s.indexOf(n),1),s.length||oP.delete(e),rP--,aP-=n.bytes,n.geometry.dispose())}function dP(){let t=0;for(const e of oP.values())for(const n of e)t+=n.users;return{entries:rP,users:t,bytes:aP,limit:cP}}let uP;function pP(t){uP=t}function fP(t){return uP?.(t)}async function mP(t,e=Nu.loadGLTF){const n=fP(t.asset);if(!n)return;let s,i;try{s=await e(n)}catch{return}if(void 0===t.node)i=s.scene.clone(!0);else{const e=function(t,e){let n;return t.scene.traverse(s=>{n||t.parser?.associations?.get(s)?.nodes!==e||(n=s)}),n}(s,t.node);if(!e)return;s.scene.updateMatrixWorld(!0);const n=new w.Vector3;e.matrixWorld.decompose(new w.Vector3,new w.Quaternion,n),i=e.clone(!0),i.position.set(0,0,0),i.quaternion.identity(),i.scale.copy(n)}const o=new w.Group;return o.name="figure-mesh-file",o.add(i),o.scale.setScalar(t.scale),o.traverse(t=>{t.raycast=()=>{}}),o}const gP=t=>1e-9*Math.round(t/1e-9)+0;class yP{static carrierJudgeOf(t){let e=yP.carrierJudges.get(t);return e||yP.carrierJudges.set(t,e=function(t,e){const n=e??rS(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))i.set(t,e);const o=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target)),r=t=>"string"==typeof t&&(n[t]?.length??0)>0,a=new Map,c=t=>{const e=a.get(t);if(void 0!==e)return e;const n=i.get(t),s="compose@1"!==n?.op||"string"!=typeof n.args[0]||r(n.args[1])?t:c(n.args[0]);return a.set(t,s),s};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||o.has(n.id))continue;const t=s.get(n.id),i="place@1"===t?.op?t.args[1]:void 0;"string"==typeof i&&r(i)&&!r(t.args[0])&&e.set(n.id,c(i))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=yP.stillJudges.get(t);return e||yP.stillJudges.set(t,e=WA(t.asset,t.document.dependence)),e}constructor(t,e={}){this._lodRevision=0,this._lodGeometryRevision=0,this.boundsAt=-1,this.semanticBounds=new w.Box3,this.group=new w.Group,this.meshes=new Map,this.batches=new Map,this.merged=new Map,this.carried=new Map,this.places=new Map,this.size=null,this.design={},this.designRefused=[],this.external={},this.clipTimes=new Map,this.groupRuns=new Map,this.dataStates={},this.commanded=new Map,this.paletteOverrides={},this.partColours={},this.flags=new Map,this.materials=new Map,this.dressed=new Map,this.drawnWith=new Map,this.lastDrawn=null,this.slots=[],this.generation=-1,this.files=new Map,this.clamped=[],this.partEffects=new Map,this.opacity=1,this.effectClock=0,this.blinkDark=!1,this.compiled=mO(t),this.own=YA(t),this.theme=e.theme??{},this.merge=!1!==e.merge,this._renderLevel=e.renderLevel??"full",this.onFileArrived=e.onFileArrived,this.group.name=`figure:${t.name}`}dressWithFile(t,e,n){const s=n.shape?.mesh,i=this.files.get(t);if(!s)return void(i&&this.undressFile(t,e,n));const o=`${s.asset}:${s.node??"-"}`;if(i?.key===o)return i.scale=s.scale,void i.object?.scale.setScalar(s.scale);i&&this.undressFile(t,e,n);const r={key:o,scale:s.scale};this.files.set(t,r),mP({asset:s.asset,...void 0!==s.node?{node:s.node}:{},scale:s.scale}).then(n=>{n&&this.files.get(t)===r&&this.meshes.get(t)===e&&(n.scale.setScalar(r.scale),r.object=n,e.add(n),e.material=yP.HIDDEN_BOX,this.onFileArrived?.())})}undressFile(t,e,n){const s=this.files.get(t);this.files.delete(t),s?.object&&s.object.parent?.remove(s.object),e&&n&&e.material===yP.HIDDEN_BOX&&(e.material=this.materialFor(n))}get asset(){return this.compiled.asset}get renderLevel(){return this._renderLevel}get lodRevision(){return this._lodRevision}get lodGeometryRevision(){return this._lodGeometryRevision}bodyMatrix(t,e,n){const s=this.slots[t];if(s&&"mesh"in s)return n.copy(s.mesh.matrix);if(s&&"entry"in s)return s.entry.set.mesh.getMatrixAt(s.index,n),n;if(s&&"rides"in s){const t=s.rides,i=12*t.ids.indexOf(e.id),o=t.relative;return n.set(o[i],o[i+1],o[i+2],o[i+9],o[i+3],o[i+4],o[i+5],o[i+10],o[i+6],o[i+7],o[i+8],o[i+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(yP.matrixOf(e.pose)):n.identity()}lodBounds(t){if(this.boundsAt!==this._lodRevision){this.semanticBounds.makeEmpty();const t=new w.Matrix4,e=new w.Box3;this.lastDrawn?.geometry.forEach((n,s)=>{if(!("shape"in n)||!("pose"in n)||!1===n.visible)return;let i=yP.shapeBounds.get(n.shape);if(!i){const t=B_(n.shape);i=new w.Box3(new w.Vector3(t.x.min,t.y.min,t.z.min),new w.Vector3(t.x.max,t.y.max,t.z.max)),yP.shapeBounds.set(n.shape,i)}this.semanticBounds.union(e.copy(i).applyMatrix4(this.bodyMatrix(s,n,t)))}),this.boundsAt=this._lodRevision}return t.copy(this.semanticBounds)}setRenderLevel(t){if(!["full","medium","coarse"].includes(t))throw new Error(`figure: unknown render level ${t}`);if(t===this._renderLevel)return!0;const e=this._renderLevel,n=this.lastDrawn;if(this.lastLodError=void 0,!n||n.geometry.every(n=>Yv(n,e)===Yv(n,t)))return this._renderLevel=t,!0;const s=new w.Matrix4,i=n.geometry.map((t,e)=>{if(!("pose"in t))return t;const n=this.bodyMatrix(e,t,s).elements;return{...t,pose:{r:[[n[0],n[4],n[8]],[n[1],n[5],n[9]],[n[2],n[6],n[10]]],t:[n[12],n[13],n[14]]}}}),o={...n,geometry:i},r=qv(o,t),a=[],c=[],l=tP().bytes+dP().bytes,h=()=>yP.LOD_TRANSITION_LIMIT_BYTES-(tP().bytes+dP().bytes-l);try{const t=new Set;for(const e of r.geometry){if(!("shape"in e))continue;const n=eP(e.shape,e.segments);t.has(n)||(t.add(n),a.push(nP(e.shape,e.segments,h())))}const e=KA(r.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf,own:this.own}:{own:this.own}),n=new Map(r.geometry.map(t=>[t.id,t]));for(const t of[...e.merged,...e.carried]){let e=t.ids.map(t=>n.get(t));if("carrier"in t){const t=(new w.Matrix4).copy(yP.matrixOf(e[0].pose)).invert(),n=new w.Matrix4;e=e.map(e=>{const s=n.multiplyMatrices(t,yP.matrixOf(e.pose)).elements,i=t=>gP(s[t]);return{...e,pose:{r:[[i(0),i(4),i(8)],[i(1),i(5),i(9)],[i(2),i(6),i(10)]],t:[i(12),i(13),i(14)]}}})}const s=lP(e,h());s&&c.push(s.geometry)}if(tP().bytes+dP().bytes-l>yP.LOD_TRANSITION_LIMIT_BYTES)throw new Error("figure: LOD transition budget exceeded")}catch(t){this.lastLodError=t instanceof Error?t.message:String(t);for(const t of c)hP(t);for(const t of a)sP(t);return!1}try{return this._renderLevel=t,this.draw(o,this.generation),!0}finally{for(const t of c)hP(t);for(const t of a)sP(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(Vv.x)&&e(Vv.y)&&e(Vv.z)?{x:t[Vv.x],y:t[Vv.y],z:t[Vv.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const s of["x","y","z"]){const i=e.find(t=>t.id===Vv[s]);if(!i)continue;const o=t[s],r=Math.min(Math.max(o,i.min??-1/0),i.max??1/0);r!==o&&this.clamped.push({axis:s,asked:o,used:r,bound:r>o?"min":"max"}),n[s]=r}this.size=n}get drawnSize(){return this.size?{...this.size}:null}setDesignInputs(t){const e=[],n=new Set((this.asset.publicInputs??[]).map(t=>t.input)),s=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),i={};for(const[o,r]of Object.entries(t??{})){const t=s.get(o);let a;n.has(o)&&t?"number"==typeof r&&Number.isFinite(r)?(r<t.min||r>t.max)&&(a=`outside ${t.min}…${t.max}`):a="not a number":a="not an input the figure lets a board set",a?(e.push({input:o,value:r,reason:a}),o in this.design&&(i[o]=this.design[o])):i[o]=r}try{this.compiled.document.evaluate({...this.evaluationInputs(),...i}),this.design=i}catch(t){for(const[n,s]of Object.entries(i))e.push({input:n,value:s,reason:t instanceof Error?t.message:String(t)})}this.designRefused=e}get designValues(){return{...this.design}}setState(t){this.external={...t}}static clipOf(t){return t.clip}get clips(){return[...new Set((this.asset.drivers??[]).map(t=>yP.clipOf(t)))]}get motionPlan(){return this.motionPlanOf??=zS(this.asset)}get independentClips(){return this.motionPlan.independentClips}setMotionSettings(t){const e=this.motionPlan;let n;for(const[s,{group:i}]of e.groups){const o=t[s]??{clip:i.defaultClip,speed:0,paused:!1},r=this.groupRuns.get(s);r?(r.clip!==o.clip&&(n??=this.drivenValues(),r.from=Object.fromEntries(e.groups.get(s).states.map(t=>[t,n[t]])),r.clip=o.clip,r.time=0,r.elapsed=0),r.speed=o.speed,r.paused=o.paused):this.groupRuns.set(s,{clip:o.clip,time:0,speed:o.speed,paused:o.paused,elapsed:0})}}restartMotion(t){const e=this.groupRuns.get(t);if(!e)return!1;const n=this.drivenValues();return e.from=Object.fromEntries(this.motionPlan.groups.get(t).states.map(t=>[t,n[t]])),e.time=0,e.elapsed=0,!0}get motionRuns(){return Object.fromEntries([...this.groupRuns].map(([t,e])=>[t,{clip:e.clip,time:e.time,speed:e.speed,paused:e.paused,blending:!!e.from}]))}setDataStates(t){let e;for(const[n,{sourceMode:s}]of Object.entries(t))"commanded"!==s||this.commanded.has(n)||(e??={...this.asset.stateDefaults,...this.stateOverrides()},this.commanded.set(n,e[n]));for(const e of[...this.commanded.keys()])"commanded"!==t[e]?.sourceMode&&this.commanded.delete(e);this.dataStates={...t}}advance(t){if(!(t>0))return!1;let e=!1;for(const[n,s]of this.groupRuns)!s.paused&&s.speed>0&&(s.time+=t*s.speed,s.from&&(s.elapsed+=t,s.elapsed>=this.motionPlan.groups.get(n).group.transitionSeconds&&(s.from=void 0)),e=!0);if(this.advanceEffects(t)&&(e=!0),this.commanded.size){const n=new Map(this.asset.document.model.inputs.map(t=>[t.id,t]));for(const[s,i]of this.commanded){const o=this.dataStates[s]?.value;if(void 0===o||i===o)continue;const r=n.get(s);this.commanded.set(s,VS(i,o,{min:r.min,max:r.max,sweep:this.asset.stateInputs?.[s]?.sweep},t)),e=!0}}return e}get moving(){for(const t of this.groupRuns.values())if(!t.paused&&t.speed>0)return!0;for(const t of this.partEffects.values())if("blink"===t.kind)return!0;for(const[t,e]of this.commanded)if(this.dataStates[t]&&this.dataStates[t].value!==e)return!0;return!1}drivenValues(){const t=this.motionPlan;if(!t.clips.size)return{};const e={},n={};for(const e of t.independentClips)n[e]=this.clipTime(e);for(const[s,{group:i}]of t.groups){const t=this.groupRuns.get(s);e[s]=t?.clip??i.defaultClip,n[e[s]]=t?.time??0}const s={...$S(t,e,n)};for(const[e,{group:n,states:i}]of t.groups){const o=this.groupRuns.get(e);if(!o?.from)continue;const r=n.transitionSeconds>0?Math.min(1,o.elapsed/n.transitionSeconds):1,a=Object.fromEntries(i.map(t=>[t,s[t]]));Object.assign(s,LS(t,o.from,a,r))}return s}setPaletteOverrides(t){const e={...t},n=Object.keys(e).length===Object.keys(this.paletteOverrides).length&&Object.entries(e).every(([t,e])=>this.paletteOverrides[t]===e);n||(this.paletteOverrides=e,this.repaint())}setPartColours(t){const e={...t},n=Object.keys(e).length===Object.keys(this.partColours).length&&Object.entries(e).every(([t,e])=>this.partColours[t]===e);n||(this.partColours=e,this.repaint())}setPartEffects(t){const e=new Map;for(const[n,s]of Object.entries(t))!s||"blink"!==s.kind&&"glow"!==s.kind||e.set(n,{kind:s.kind,hz:s.hz&&s.hz>0?s.hz:1});const n=e.size===this.partEffects.size&&[...e].every(([t,e])=>this.partEffects.get(t)?.kind===e.kind&&this.partEffects.get(t)?.hz===e.hz);n||(this.partEffects=e,this.repaint())}setOpacity(t){const e=Number.isFinite(t)&&t>0&&t<1?t:1;e!==this.opacity&&(this.opacity=e,this.repaint())}partOf(t){return t.key?this.compiled.writers.get(t.key):t.id}advanceEffects(t){const e=[...this.partEffects.values()].find(t=>"blink"===t.kind);if(!e)return!1;this.effectClock+=t;const n=this.effectClock*e.hz%1>=.5;return n!==this.blinkDark&&(this.blinkDark=n,this.repaint(),!0)}get palette(){return{...this.asset.palette,...this.paletteOverrides}}repaint(){const t=new Map((this.lastDrawn?.geometry??[]).map(t=>[t.id,t]));for(const[e,n]of this.meshes){const s=t.get(e);s&&n.material!==yP.HIDDEN_BOX&&(n.material=this.materialFor(s))}for(const e of this.batches.values()){const n=t.get(e.ids[0]);n&&(e.set.material=this.materialFor(n))}for(const e of[...this.merged.values(),...this.carried.values()]){const n=t.get(e.ids[0]);n&&(e.mesh.material=this.materialFor(n))}this.lastDrawn&&(this.lastDrawn={...this.lastDrawn,palette:this.palette})}setClipTime(t,e){this.clipTimes.set(t,e)}clipTime(t){return this.clipTimes.get(t)??0}setTime(t){for(const e of this.clips)this.clipTimes.set(e,t)}stateOverrides(){const{states:t}=this.inputsRead(),e=this.drivenValues();for(const[n,{value:s,sourceMode:i}]of Object.entries(this.dataStates))t.has(n)&&(e[n]="commanded"===i?this.commanded.get(n)??s:s);for(const[n,s]of Object.entries(this.external))t.has(n)&&(e[n]=s);return e}inputsRead(){const t=this.asset.document.model.inputs;return this.inputFacts??={units:new Map(t.map(t=>[t.id,t.unit])),states:new Set(t.filter(t=>"state"===t.role).map(t=>t.id))}}get externalState(){return{...this.external}}update(){const t=this.evaluationInputs();this.evaluator??=this.compiled.document.evaluator({changes:!0});const e=this.evaluator.advance(t),n=this.carried.size>0&&this.carriedAt!==this.designKey();if("poses"===e.kind&&e.generation===this.generation&&!n&&!this.movesMerged(e.bodies))return this.movePoses(e);const s="changes"===e.kind?this.fromChanges(e,t):null;this.draw(s??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const s=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||s.has(n)||!t.structure&&!t.changed(n))continue;const i=!0===t.read(n);this.flags.get(n)!==i&&s.add(n),this.flags.set(n,i)}const i=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),o=new Int32Array(i.length).fill(-1);for(let e=0;e<t.bodies.length;e++){if(!t.shapes[e])return null;o[t.bodies[e]]=e}for(let e=0;e<i.length;e++){const n=o[e],r=i[e];if(n<0&&!(r&&s.size&&void 0!==this.flagOf(r)&&s.has(this.flagOf(r))))continue;const a=t.structure?t.structure.ids[e]:r.id,c=t.structure?t.structure.keys[e]:r.key,l={id:a},h=t.structure?t.structure.paths[e]:r.path;void 0!==h&&(l.path=h),void 0!==c&&(l.key=c);const d=t.structure?t.structure.indexes[e]:r.index;if(void 0!==d&&(l.index=d),n>=0){const e=t.poses,s=12*n;l.shape=t.shapes[n],l.pose={r:[[e[s],e[s+1],e[s+2]],[e[s+3],e[s+4],e[s+5]],[e[s+6],e[s+7],e[s+8]]],t:[e[s+9],e[s+10],e[s+11]]}}else l.shape=r.shape,l.pose=r.pose;i[e]=this.dressBody(l)}const r=new Map((t.structure?[]:n.bindings).map(t=>[t.id,t]));for(const e of t.places)r.set(e.id,e);return{geometry:i,bindings:[...r.values()],inputs:e,palette:this.palette}}flagOf(t){return this.compiled.looks.get(t.key?this.compiled.writers.get(t.key):t.id)?.visibility}dressBody(t){return this.dressOne(t,t=>!0===this.flags.get(t)).dressed}dressOne(t,e){const n=t.key?this.compiled.writers.get(t.key):t.id,s=this.compiled.looks.get(n);if(!s)throw new Error(`figure: no appearance for ${n}`);const i=void 0===s.visibility||e(s.visibility);let o=this.materials.get(n);o||this.materials.set(n,o=structuredClone(s.material));const r={...t,material:o,visible:i};return void 0!==s.segments&&(r.segments=s.segments),{dressed:r,visible:i,ref:s.visibility}}evaluation(){return this.evaluate()}movesMerged(t){if(!this.merged.size)return!1;for(let e=0;e<t.length;e++){const n=this.slots[t[e]];if(n&&"merged"in n)return!0}return!1}movePoses(t){t.bodies.length&&this._lodRevision++;const e=yP.matrix,n=new Set;for(let s=0;s<t.bodies.length;s++){const i=this.slots[t.bodies[s]];if(!i)continue;const o=t.poses,r=12*s;if(e.set(o[r],o[r+1],o[r+2],o[r+9],o[r+3],o[r+4],o[r+5],o[r+10],o[r+6],o[r+7],o[r+8],o[r+11],0,0,0,1),!("merged"in i)&&!("rides"in i))if("mesh"in i){i.mesh.matrix.copy(e),i.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(i.id);t&&(t.pose=void 0)}else i.entry.set.setMatrix(i.index,e),n.add(i.entry)}for(const t of this.batches.values())n.has(t)?(t.settled=!1,t.set.commitMatrices(),t.set.mesh.boundingSphere=null,t.set.mesh.frustumCulled=!1):t.settled||(t.set.commit(),t.set.mesh.frustumCulled=!0,t.settled=!0);for(const e of t.places){const t=this.places.get(e.id);t&&yP.pose(t,e.pose)}}draw(t,e){this.lastDrawn=t,this._lodRevision++,this._lodGeometryRevision++,t=qv(t,this._renderLevel);const n=this.planOf(t.geometry),s=new Map(t.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),i=this.drawCarried(n,s,this.drawMerged(n,s)),o=new Set;for(const t of i){const e=s.get(t);if(!("pose"in e))continue;o.add(t);let n=this.meshes.get(t);const i=!1!==e.visible,r=this.drawnWith.get(t);if(!n||!r||r.shape!==e.shape||r.segments!==e.segments){const s=nP(e.shape,e.segments);n?n.geometry!==s?(sP(n.geometry),n.geometry=s):sP(s):(n=new w.Mesh(s,this.materialFor(e)),n.name=t,n.matrixAutoUpdate=!1,this.meshes.set(t,n),i&&this.group.add(n))}r&&r.pose===e.pose||yP.pose(n,e.pose),this.dressWithFile(t,n,e),this.drawnWith.set(t,{shape:e.shape,segments:e.segments,pose:e.pose}),n.castShadow=i,i&&n.parent!==this.group?this.group.add(n):i||n.parent!==this.group||this.group.remove(n)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),this.undressFile(t,void 0),sP(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const r=new Set;for(const t of n.batches){r.add(t.key);const e=s.get(t.ids[0]);if(!("pose"in e))continue;let n=this.batches.get(t.key);if(!n){const s=nP(e.shape,e.segments);n={set:new sO({geometry:s,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:s},this.batches.set(t.key,n)}const{set:i}=n,o=i.count!==t.ids.length;i.setCount(t.ids.length);const a=i.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=s.get(t);if(!("pose"in n))return;yP.matrixOf(n.pose);const o=yP.matrix.elements;for(let t=0;t<16&&!c;t++)a[16*e+t]!==Math.fround(o[t])&&(c=!0);i.setMatrix(e,yP.matrix)}),n.ids=t.ids,o||!c&&!n.settled?(i.commit(),i.mesh.frustumCulled=!0,n.settled=!0):c&&(n.settled=!1,i.commitMatrices(),i.mesh.boundingSphere=null,i.mesh.frustumCulled=!1);const l=!1!==e.visible;l&&i.object3d.parent!==this.group?this.group.add(i.object3d):l||i.object3d.parent!==this.group||this.group.remove(i.object3d)}for(const[t,e]of this.batches)r.has(t)||(e.set.object3d.parent===this.group&&this.group.remove(e.set.object3d),e.set.dispose(),sP(e.geometry),this.batches.delete(t));for(const e of t.bindings){const t=this.places.get(e.id);t&&yP.pose(t,e.pose)}const a=new Map;for(const t of this.batches.values())t.ids.forEach((e,n)=>a.set(e,{entry:t,index:n}));for(const t of this.merged.values())for(const e of t.ids)a.set(e,{merged:t});const c=new Map;for(const t of this.carried.values())t.ids.forEach((e,n)=>0===n?c.set(e,t.mesh):a.set(e,{rides:t}));this.slots=t.geometry.map(t=>{const e=this.meshes.get(t.id)??c.get(t.id);return e?{mesh:e,id:t.id}:a.get(t.id)??null}),this.generation=e}drawMerged(t,e){const n=[...t.alone],s=new Set;for(const i of t.merged){const t=i.ids.map(t=>e.get(t));let o=this.merged.get(i.key);const r=o&&o.ids.length===t.length&&t.every((t,e)=>t.id===o.ids[e]&&t.shape===o.made[e].shape&&t.segments===o.made[e].segments&&t.pose===o.made[e].pose);if(!r){const e=lP(t.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!e){n.push(...i.ids);continue}if(o)hP(o.mesh.geometry),o.mesh.geometry=e.geometry,o.ids=i.ids,o.starts=e.starts;else{const n=new w.Mesh(e.geometry,this.materialFor(t[0]));n.name=`figure-merged:${this.merged.size}`,n.matrixAutoUpdate=!1,n.castShadow=!0,o={mesh:n,ids:i.ids,starts:e.starts,made:[]},this.merged.set(i.key,o)}o.made=t.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose}))}s.add(i.key);const a=!1!==t[0].visible;a&&o.mesh.parent!==this.group?this.group.add(o.mesh):a||o.mesh.parent!==this.group||this.group.remove(o.mesh)}for(const[t,e]of this.merged)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),hP(e.mesh.geometry),this.merged.delete(t));return n}drawCarried(t,e,n){const s=new Set,i=new w.Matrix4,o=new w.Matrix4;for(const r of t.carried){const t=r.ids.map(t=>e.get(t));i.copy(yP.matrixOf(t[0].pose)).invert();const a=t.map(t=>{const e=o.multiplyMatrices(i,yP.matrixOf(t.pose)).elements,n=t=>gP(e[t]);return{r:[[n(0),n(4),n(8)],[n(1),n(5),n(9)],[n(2),n(6),n(10)]],t:[n(12),n(13),n(14)]}}),c=new Float64Array(a.flatMap(t=>[...t.r.flat(),...t.t]));let l=this.carried.get(r.key);const h=l&&l.ids.length===t.length&&t.every((t,e)=>t.id===l.ids[e]&&t.shape===l.made[e].shape&&t.segments===l.made[e].segments)&&c.every((t,e)=>t===l.relative[e]);if(!h){const e=lP(t.map((t,e)=>({shape:t.shape,segments:t.segments,pose:a[e]})));if(!e){n.push(...r.ids);continue}if(l)hP(l.mesh.geometry),l.mesh.geometry=e.geometry,l.ids=r.ids,l.starts=e.starts;else{const n=new w.Mesh(e.geometry,this.materialFor(t[0]));n.name=`figure-carried:${this.carried.size}`,n.matrixAutoUpdate=!1,n.castShadow=!0,l={mesh:n,ids:r.ids,starts:e.starts,made:[],relative:c},this.carried.set(r.key,l)}l.made=t.map(t=>({shape:t.shape,segments:t.segments})),l.relative=c}yP.pose(l.mesh,t[0].pose),s.add(r.key);const d=!1!==t[0].visible;d&&l.mesh.parent!==this.group?this.group.add(l.mesh):d||l.mesh.parent!==this.group||this.group.remove(l.mesh)}for(const[t,e]of this.carried)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),hP(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),n}designKey(){const t=this.size;let e=t?`${t.x},${t.y},${t.z}`:"-";for(const t in this.design)e+=`|${t}=${this.design[t]}`;return e}placeNode(t){let e=this.places.get(t);if(e)return e;if(!BA(this.asset).some(e=>e.id===t))return null;e=new w.Object3D,e.name=`place:${t}`,e.matrixAutoUpdate=!1,this.places.set(t,e),this.group.add(e);const n=this.evaluator&&this.lastDrawn?this.placeNow(t):this.evaluation().bindings.find(e=>e.id===t);return n&&yP.pose(e,n.pose),e}placeNow(t){try{return this.evaluator.place(t)}catch(e){if("NOT_BOUND"!==e.code)throw e;return this.evaluation().bindings.find(e=>e.id===t)}}static pose(t,e){t.matrix.copy(yP.matrixOf(e)),t.matrixWorldNeedsUpdate=!0}planOf(t){const e=this.planned,n=t.filter(t=>"pose"in t);if(e&&e.ids.length===n.length&&n.every((t,n)=>t.id===e.ids[n]&&t.shape===e.shapes[n]&&t.segments===e.segments[n]&&!1!==t.visible===e.shown[n]))return e.plan;const s=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===s.length&&s.every((t,n)=>t===e.ids[n])||(this.stillOf=yP.stillJudgeOf(this.compiled)(t),this.carriedOf=yP.carrierJudgeOf(this.compiled)(t));const i=this.merge?this.stillOf:void 0,o=KA(t,i?{still:i,carried:this.carriedOf,own:this.own}:{own:this.own});return this.planned={ids:s,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:o,still:i},o}static matrixOf(t){const e=t.r,n=t.t;return yP.matrix.set(e[0][0],e[0][1],e[0][2],n[0],e[1][0],e[1][1],e[1][2],n[1],e[2][0],e[2][1],e[2][2],n[2],0,0,0,1)}bodyAt(t,e,n){if(t.isMesh&&this.meshes.get(t.name)===t)return t.name;for(const n of this.batches.values())if(n.set.mesh===t&&void 0!==e){const t=n.set.indexOf(e);return t>=0?n.ids[t]:void 0}for(const e of[...this.merged.values(),...this.carried.values()]){if(e.mesh!==t||void 0===n)continue;const{starts:s}=e;if(n<0||n>=s[s.length-1])return;let i=0,o=e.ids.length-1;for(;i<o;){const t=i+o+1>>1;s[t]<=n?i=t:o=t-1}return e.ids[i]}}drawOf(t){const e=this.meshes.get(t);if(e)return e.parent===this.group?{kind:"alone",object:e}:void 0;for(const e of this.batches.values()){const n=e.ids.indexOf(t);if(n>=0)return e.set.object3d.parent===this.group?{kind:"copy",object:e.set.mesh,index:n}:void 0}for(const e of this.merged.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"merged",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}for(const e of this.carried.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"carried",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}}get draws(){let t=0;for(const e of this.batches.values())e.set.object3d.parent===this.group&&(t+=e.set.count);return{batches:[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).length,merged:[...this.merged.values()].filter(t=>t.mesh.parent===this.group).length,carried:[...this.carried.values()].filter(t=>t.mesh.parent===this.group).length,alone:[...this.meshes.values()].filter(t=>t.parent===this.group).length,instances:t}}evaluationInputs(){const t={...this.asset.designInputs,...this.design,...this.asset.stateDefaults,...this.stateOverrides()};return this.size&&(t[Vv.x]=this.size.x,t[Vv.y]=this.size.y,t[Vv.z]=this.size.z),t}evaluate(){const t=this.evaluationInputs();return this.evaluator??=this.compiled.document.evaluator({changes:!0}),this.dress(this.evaluator.evaluate(t),t)}evaluateOnce(){const t=this.evaluationInputs(),e=this.compiled.document.evaluate(t),n=e.values,s=e.geometry.map(t=>this.dressOne(t,t=>!0===n[t]).dressed);return{geometry:s,bindings:e.bindings,inputs:t,palette:this.palette}}dress(t,e){const n=this.dressed,s=new Map,i=t.geometry.map(e=>{const i=n.get(e.id),o=this.dressOne(e,e=>!0===t.values[e]);return void 0!==o.ref&&this.flags.set(o.ref,o.visible),i&&i.body===e&&i.visible===o.visible?(s.set(e.id,i),i.dressed):(s.set(e.id,{body:e,visible:o.visible,dressed:o.dressed}),o.dressed)});return this.dressed=s,{geometry:i,bindings:t.bindings,inputs:e,palette:this.palette}}colourOf(t){return this.paletteOverrides[t]??this.theme[t]??this.asset.palette[t]??"#9a9a9a"}materialFor(t){const e=t.material,n=Fd[e.preset??"default"]??Fd.default,s=this.partOf(t),i=this.partEffects.get(s),o=!!e.emissive?.on||"glow"===i?.kind,r=o&&e.emissive?this.colourOf(e.emissive.token):this.partColours[s]??this.colourOf(e.token),a="blink"===i?.kind&&this.blinkDark?function(t){const e=/^#([0-9a-f]{6})$/i.exec(t);if(!e)return"#202020";const n=parseInt(e[1],16),s=t=>Math.round(.25*(n>>t&255)).toString(16).padStart(2,"0");return`#${s(16)}${s(8)}${s(0)}`}(r):r,c="glow"===i?.kind?.8:o&&e.emissive?e.emissive.intensity:0,l=(e.transparent?n.opacity??.3:1)*this.opacity,h=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${l}|${o?"on":"off"}|${a}|${c}`;return NT.material(h,{color:a,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:(e.transparent??!1)||l<1,opacity:l,emissive:a,emissiveIntensity:c})}meshOf(t){return this.meshes.get(t)}drawnIds(){const t=[...this.meshes.values()].filter(t=>t.parent===this.group).map(t=>t.name),e=[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).flatMap(t=>t.ids),n=[...this.merged.values(),...this.carried.values()].filter(t=>t.mesh.parent===this.group).flatMap(t=>t.ids);return[...t,...e,...n]}dispose(){for(const t of this.meshes.values())t.parent===this.group&&this.group.remove(t),sP(t.geometry);this.meshes.clear();for(const t of[...this.files.keys()])this.undressFile(t,void 0);this.drawnWith.clear(),this.dressed.clear();for(const t of this.batches.values())t.set.object3d.parent===this.group&&this.group.remove(t.set.object3d),t.set.dispose(),sP(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),hP(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),hP(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}yP.shapeBounds=new WeakMap,yP.LOD_TRANSITION_LIMIT_BYTES=16777216,yP.matrix=new w.Matrix4,yP.carrierJudges=new WeakMap,yP.stillJudges=new WeakMap,yP.HIDDEN_BOX=new w.MeshBasicMaterial({visible:!1});const bP=["x","y","z"],vP=new WeakMap;function _P(t){let e=vP.get(t);return e||vP.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,s=bP.every(t=>"number"==typeof n[Vv[t]]&&e.some(e=>e.id===Vv[t])),i={};if(s)for(const t of bP){const n=e.find(e=>e.id===Vv[t]);i[t]={min:n.min??0,max:n.max??1/0}}const o=e=>{const n=function(t,e={}){const n=Object.keys(e).length?{...t,designInputs:{...t.designInputs,...e}}:t,s=nA(qS(n).evaluate().geometry,sA(n));return Object.fromEntries(jv.map(t=>[t,s.length?{min:iA(Math.min(...s.map(e=>e.centre[t]-e.extent[t]/2))),max:iA(Math.max(...s.map(e=>e.centre[t]+e.extent[t]/2)))}:{min:0,max:0}]))}(t,e?kP(e):{});return{box:{x:Math.max(n.x.max-n.x.min,1e-6),y:Math.max(n.y.max-n.y.min,1e-6),z:Math.max(n.z.max-n.z.min,1e-6)},centre:{x:(n.x.min+n.x.max)/2,y:(n.y.min+n.y.max)/2,z:(n.z.min+n.z.max)/2}}},r=s?{x:n[Vv.x],y:n[Vv.y],z:n[Vv.z]}:null,a=!s||"uniform"===t.sizing,c=o(r),l={};if(r&&a){const t=Math.min(2,...bP.map(t=>i[t].max/r[t])),e=Math.max(.5,...bP.map(t=>i[t].min/r[t])),n=t>1?t:e<1?e:1;if(1!==n){const t=o({x:r.x*n,y:r.y*n,z:r.z*n}).box;for(const e of bP)l[e]=(t[e]-c.box[e])/(r[e]*(n-1))}}else if(r)for(const t of bP){const{min:e,max:n}=i[t],s=r[t],a=n>s?Math.min(n,2*s):e<s?Math.max(e,s/2):s;if(a===s)continue;const h=o({...r,[t]:a}).box;l[t]=(h[t]-c.box[t])/(a-s)}const h=(t,e)=>{if(!r)return e;const n=l[t]??0;return Math.abs(n)>1e-9?r[t]+(e-c.box[t])/n:r[t]};return{evaluated:s,proportional:a,limits:i,authoredInputs:r,authored:c,bodyAt:o,inputFor:h}}(t)),e}function xP(t){return _P(t).proportional}function wP(t){return{..._P(t).authored.box}}function MP(t,e){const n=t.bounds?.width??Number(t.state.width??0),s=t.bounds?.height??Number(t.state.height??0),i=SP(t),o=rh(t).mmPerUnit;return AP(e,{x:n*o,z:s*o,y:void 0===i?void 0:i*o})}function SP(t){const e=t=>"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0;return e(t.state.depth)??e(t.effectiveDepth)}function AP(t,e,n=[]){const s=_P(t),i=n.find(t=>void 0!==e[t])??"x",o=(t,e)=>{const n=s.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!s.evaluated){const t=Math.max(e[i]/s.authored.box[i],1e-6),n=e=>({x:e.x*t,y:e.y*t,z:e.z*t});return{inputs:null,scale:t,box:n(s.authored.box),centre:n(s.authored.centre)}}const r=s.authoredInputs;let a;if(s.proportional){let t=Math.max(s.inputFor(i,e[i])/r[i],1e-6);for(const e of bP){const n=s.limits[e];n&&(t=Math.min(Math.max(t,n.min/r[e]),n.max/r[e]))}a={x:r.x*t,y:r.y*t,z:r.z*t}}else a={x:o("x",s.inputFor("x",e.x)),y:o("y",void 0!==e.y?s.inputFor("y",e.y):r.y),z:o("z",s.inputFor("z",e.z))};return{inputs:a,scale:1,...s.bodyAt(a)}}const kP=t=>Object.fromEntries(bP.map(e=>[Vv[e],t[e]])),EP=new WeakMap;function TP(t){const e=BO(String(t?.type??""));if(!e)return null;const n=t?.slotLayout;return null==n?e.compiled.asset:mO(uk(e.compiled.asset,n).asset).asset}function CP(t){const e=BO(String(t?.type??""));return e?uk(e.compiled.asset,t?.slotLayout).effective:null}const OP={single:"Single slot",agvTandem:"AGV tandem (front/rear)",agvParallel:"AGV parallel (left/right)",agv2x2:"AGV 2×2",bufferPort2x2:"Buffer port 2×2",multiBufferPort:"Multi-buffer port (4)",dualTierConveyor:"Dual-tier conveyor",craneTwinFork:"Crane twin fork",floorBlock:"Floor block"},PP={upperElevation:"Upper tier elevation (mm)",rows:"Rows",cols:"Columns",stackLimit:"Stack limit"},IP=t=>Math.round(1e3*t)/1e3;function DP(t,e){const n={};for(const s of t){const t=e.find(t=>t.id===s.part);if(!t?.shape)continue;const i=B_(t.shape);n[s.id]={width:IP(i.x.max-i.x.min),depth:IP(i.z.max-i.z.min)}}return n}function zP(t,e){const n=new Map(e.filter(t=>t.shape).map(t=>[t.id,RP(t)]));if(!n.size)return{};const s=Math.max(...[...n.values()].map(t=>t.max)),i=Math.min(...[...n.values()].map(t=>t.min)),o={};for(const e of t){const t=e.part?n.get(e.part):void 0;t&&(o[e.id]=IP(Math.max(0,"bottom"===e.face?t.min-i:s-t.max)))}return o}function RP(t){const e=B_(t.shape),n=[(e.x.min+e.x.max)/2,(e.y.min+e.y.max)/2,(e.z.min+e.z.max)/2],s=[(e.x.max-e.x.min)/2,(e.y.max-e.y.min)/2,(e.z.max-e.z.min)/2],i=t.pose?.r?.[1]??[0,1,0],o=(t.pose?.t?.[1]??0)+i[0]*n[0]+i[1]*n[1]+i[2]*n[2],r=Math.abs(i[0])*s[0]+Math.abs(i[1])*s[1]+Math.abs(i[2])*s[2];return{min:o-r,max:o+r}}function jP(t){const e=t?.state,n=BO(String(e?.type??"")),s=n?.compiled.asset.document.capabilities.slotLayout;if(!s)return;const i=s.anchors.map(t=>t.id),o=uk(n.compiled.asset,e?.slotLayout).effective,r={anchor:i[0],...i.length>=2?{forks:[i[0],i[1]]}:{}},a=function(t,e){const n=HA(e)?.anchors??[];try{const s=new yP(e);s.setSize(MP(t,e).inputs);const i=t.state.designInputs;return i&&"object"==typeof i&&s.setDesignInputs(i),DP(n,s.evaluateOnce().geometry)}catch{return{}}}(t,n.compiled.asset),c=Wl(t),l=t._items??[];return{effective:s.layout,canUseDefault:null!=e?.slotLayout,live:!0,unit:"mm",anchors:(HA(n.compiled.asset)?.anchors??s.anchors).map(t=>({id:t.id,..."part"in t&&t.part?{part:t.part,face:t.face}:{}})),anchorFaces:a,presetSize:a[i[0]??""]??{},validate:t=>hk(t,i),...c?{itemTypes:[...c.types.values()].map(t=>({code:t.code,name:t.name}))}:{},items:l.map(e=>({id:String(e.state?.id??""),slot:e[_v],code:e.state?.type,type:t.itemTypeOf?t.itemTypeOf(e):e.state?.type??null,dims:t.itemDimsOf?.(e)??null})),presets:lk.map(t=>({key:t,label:OP[t],params:ck[t].map(t=>({key:t.key,label:PP[t.key]??t.key,integer:t.integer})),build:(e,n)=>function(t,e,n={},s={}){const i=ak,o={single:()=>i.single(s.mount??"ON",e,void 0,s),agvTandem:()=>i.agvTandem(e,void 0,s),agvParallel:()=>i.agvParallel(e,void 0,s),agv2x2:()=>i.agv2x2(e,void 0,s),bufferPort2x2:()=>i.bufferPort2x2(e,void 0,s),multiBufferPort:()=>i.multiBufferPort(e,void 0,s),dualTierConveyor:()=>i.dualTierConveyor(e,n.upperElevation,void 0,s),craneTwinFork:()=>i.craneTwinFork(e,void 0,s),floorBlock:()=>i.floorBlock(e,n.rows,n.cols,n.stackLimit,void 0,s)}[t](),r=Object.fromEntries(ck[t].map(t=>[t.key,n[t.key]]));return{...o,preset:{key:t,size:{width:e.width,depth:e.depth,slotHeight:e.slotHeight},params:r}}}(t,e,n,r)})),notes:"invalid"===o.status?[{level:"error",code:"OVERRIDE_INVALID",issue:o.issues[0]}]:[]}}const $P="@figure",LP=[],FP=new Set;function NP(t){return FP.add(t),()=>FP.delete(t)}function HP(t){for(const e of[...FP])e(t)}function BP(t){return LP.push(t),HP(),()=>{const e=LP.indexOf(t);e<0||(LP.splice(e,1),HP())}}function GP(t){const e=new Map;for(const{binding:n}of t?.bindings??[])"table"===n.rule&&n.legend&&!e.has(n.legend.role)&&e.set(n.legend.role,n);return e}const UP=t=>!!t&&"object"==typeof t&&!Array.isArray(t),VP=t=>t?.rootModel?.state??t?.root?.state??{};function WP(t,e){const n={},s=[],i=(t=>{const e=t?.root;return e?.style??e?._style})(t);let o=!1;const r=(t,e,n,r)=>{if(!o&&"string"==typeof n&&n){if(n!==$P)return i&&Object.prototype.hasOwnProperty.call(i,n)?{legend:i[n],source:r,name:n}:void s.push({role:t,binding:e.id,reason:"legend-absent",name:n,source:r});o=!0}};for(const[a,c]of GP(e)){let e;o=!1;for(const n of LP)try{const s=n({component:t,binding:c,role:a});if(null!=s){e={legend:s,source:"resolver"};break}}catch(t){s.push({role:a,binding:c.id,reason:"resolver-failed",source:"resolver",value:t instanceof Error?t.message:String(t)})}const l=t?.state?.legends;e??=r(a,c,UP(l)?l[a]:void 0,"component");const h=VP(t).legends;e??=r(a,c,UP(h)?h[a]:void 0,"board"),!e&&!o&&i&&Object.prototype.hasOwnProperty.call(i,a)&&(e={legend:i[a],source:"domain",name:a}),e&&(n[a]=e)}return{legends:n,notes:s}}function YP(t){let e=t;if("string"==typeof e)try{e=JSON.parse(e)}catch{return null}return UP(e)?e:null}class qP extends Du{constructor(){super(...arguments),this.rig=null,this.lodEpoch=0}get renderLevel(){return this.rig?.renderLevel??"full"}get lodRevision(){return this.lodEpoch+(this.rig?.lodRevision??0)}get lodGeometryRevision(){return this.lodEpoch+(this.rig?.lodGeometryRevision??0)}get lodError(){return this.rig?.lastLodError}lodBounds(t){return this.rig?(this.rig.group.updateWorldMatrix(!0,!1),this.rig.lodBounds(t).applyMatrix4(this.rig.group.matrixWorld)):t.makeEmpty()}setRenderLevel(t){return this.rig?.setRenderLevel(t)??!0}get figure(){return BO(this.component.state.type)}getObject3dInstance(){return new w.Group}build(){super.build();const t=this.figure;t&&(this.rig=new yP(TP(this.component.state)??t.compiled.asset,{onFileArrived:()=>this.component.invalidate?.()}),this.lodEpoch+=1e6,this.object3d.add(this.rig.group),this.size(),this.seat(),this.rig.setDesignInputs(this.designInputs),this.rig.setState(this.parameters),this.rig.setOpacity(this.opacity),this.applyInputs(),this.followLegendSources(),this.rig.update(),this.reseatHeld(),this.startTicking())}followLegendSources(){const t=this.component.figureInputs;if(this.unfollowLegends||!GP(t?.dataPlan).size)return;const e=()=>this.inputsChanged(),n=this.component.rootModel,s=t=>{t&&"legends"in t&&e()},i=NP(t=>{for(let n=this.component;n;n=n.parent)if(void 0===t||n===t)return e()});n?.on?.("change",s),this.unfollowLegends=()=>{i(),n?.off?.("change",s)}}inputsChanged(){this.applyInputs(),this.startTicking(),this.refresh()}applyInputs(){const t=this.component.figureInputs;if(!this.rig||!t)return;GP(t.dataPlan).size&&t.setThemes(WP(this.component,t.dataPlan));const e=t.data,n={},s={};for(const[t,i]of Object.entries(e.parts))i.color&&(n[t]=i.color),i.effect&&(s[t]=i.effect);this.rig.setDataStates(e.states),this.rig.setPaletteOverrides(e.palette),this.rig.setPartColours(n),this.rig.setPartEffects(s),this.rig.setMotionSettings(t.motion)}get inputIssues(){return this.component.figureInputs?.diagnostics()??[]}get motionRuns(){return this.rig?.motionRuns??{}}restartMotion(t){const e=this.rig?.restartMotion(t)??!1;return e&&this.refresh(),e}get designInputs(){const t=this.component.state.designInputs;return t&&"object"==typeof t?t:{}}get parameters(){const t=this.component.state.parameters;return t&&"object"==typeof t?t:{}}get clipSpeeds(){const t=this.component.state.clips;return t&&"object"==typeof t?t:{}}clipTime(t){return this.rig?.clipTime(t)??0}onchange(t,e){super.onchange(t,e),"designInputs"in t&&this.updateDesignInputs(),"parameters"in t&&this.updateParameters(),"clips"in t&&this.updateClips(),("data"in t||"figureValues"in t||"motion"in t||"legends"in t)&&this.inputsChanged(),"slotLayout"in t&&this.update()}applied(){const t=this.figure?.compiled.asset;return t?MP(this.component,t):null}get mmPerUnit(){return rh(this.component).mmPerUnit}instanceSize(){return this.applied()?.inputs??null}get effectiveDepth(){const t=this.applied()?.box.y;return void 0===t?super.effectiveDepth:t/this.mmPerUnit}get effectiveZPos(){const t=this.component.state.zPos;if("number"==typeof t&&Number.isFinite(t))return t;const e=this.component.effectiveZPos;return"number"==typeof e&&Number.isFinite(e)?e:"ceiling"!==this.figure?.compiled.asset.placement?super.effectiveZPos:XP(this.placementMode,this.sceneHeights.ceiling,this.effectiveDepth)}updateDimension(){this.rig&&(this.size(),this.seat(),this.refresh())}size(){if(!this.rig)return;const t=this.applied();this.rig.setSize(t?.inputs??null),this.rig.group.scale.setScalar((t?.inputs?1:t?.scale??1)/this.mmPerUnit)}seat(){if(!this.rig)return;const t=this.figure?.compiled.asset.placement,e=this.applied()?.centre??{x:0,z:0},n=this.mmPerUnit;if(this.rig.group.position.x=-e.x/n,"wall"===t)return this.rig.group.position.y=0,void(this.rig.group.position.z=-this.component.bounds.height/2);if(this.rig.group.position.z=-e.z/n,"ceiling"===t)return void(this.rig.group.position.y=this.effectiveDepth/2);const s=this.effectiveDepth,i=this.effectiveDepth-s,o="center"===t?i/2:0;this.rig.group.position.y=-this.effectiveDepth/2+o}get sizeClamps(){return this.rig?.clamped??[]}get opacity(){const t=Number(this.component.effectiveOpacity);return Number.isFinite(t)&&t>0&&t<1?t:1}updateDesignInputs(){this.rig&&(this.rig.setDesignInputs(this.designInputs),this.refresh())}updateParameters(){this.rig&&(this.rig.setState(this.parameters),this.refresh())}updateClips(){this.rig&&(this.startTicking(),this.refresh())}refresh(){this.rig&&(this.rig.update(),this.component.invalidate?.())}startTicking(){const t=this.rig?.asset;!this.unsubscribe&&t&&(t.drivers?.length||t.dataInterface)&&(this.unsubscribe=_o.subscribe(t=>this.advance(t),{description:`Figure[${this.component.state.type}].drivers`,component:this.component,getTargets:()=>this.rig?[this.rig.group]:[]}))}tick(t){const e=this.rig;if(!e)return;const n=this.clipSpeeds;let s=!1;for(const i of e.independentClips){const o=n[i]??0;Number.isFinite(o)&&0!==o&&(e.setClipTime(i,e.clipTime(i)+t/1e3*o),s=!0)}e.advance(t/1e3)&&(s=!0),s&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,s=n?.placeNode(t);if(!n||!s)return;const i=n.asset.document.capabilities.slotLayout;if(i&&JM(i).some(e=>e.id===t))return this.slotAttachment(t,s,e);const o=BA(n.asset).find(e=>e.id===t)?.face,r=o&&vM[o]||[0,0,0],a=e?this.itemDimsOf(e):null,c=t=>(t??0)/2;return{attach:s,localPosition:{x:r[0]*c(a?.width),y:r[1]*c(a?.height),z:r[2]*c(a?.depth)}}}itemDimsOf(t){const e=this.component,n=e.itemDimsOf?e.itemDimsOf(t):pk(t,this.mmPerUnit);if(n)return n;const s=t.shownSizeOutOfSeat,i=this.mmPerUnit;return s?{width:s.width*i,depth:s.height*i,height:s.depth*i}:null}slotAttachment(t,e,n){const s=this.component,i=n?s.itemSeatOf?.(n,t)??null:null,o=i?.inSlot;return{attach:e,localPosition:o?{x:o.position.x,y:o.position.y,z:o.position.z}:{x:0,y:0,z:0},localRotation:{x:0,y:0,z:0},carryPolicy:"slot",displayScale:o?.scale??1,...i?{seat:i}:{}}}clear(){return this.unsubscribe?.(),this.unsubscribe=void 0,this.unfollowLegends?.(),this.unfollowLegends=void 0,this.keepHeld(),this.rig?.dispose(),this.rig=null,super.clear()}keepHeld(){const t=this.rig?.group;if(!t)return;const e=[],n=t=>{for(const s of t.children){const t=s.userData?.context;t instanceof Du&&t!==this?e.push(s):n(s)}};n(t);for(const t of e)t.parent!==this.object3d&&this.object3d.attach(t)}reseatHeld(){const t=this.component;if(this.rig&&t.seatHeldItem)for(const e of t._items??[]){const n=e[_v];"string"==typeof n&&this.rig.placeNode(n)&&t.seatHeldItem(e,{slotId:n})}}}function XP(t,e,n){switch(t){case"inverted":return e;case"space":return e-n/2;default:return e-n}}function KP(t,e,n=1,s={},i={}){const o=new yP(t.compiled.asset);o.setSize(e),o.setPaletteOverrides(s);const r=o.evaluateOnce(),a=new Map(r.geometry.map(t=>[t.id,t])),c=function(t,e){const n=[];for(const s of t){if(!1===s.visible||!ek(s))continue;let t;try{t=eA(tA(s.shape,s.segments),s.pose.r,s.pose.t)}catch{continue}if(t.length<3)continue;const i=t=>t.map(t=>[t[0],t[2]]),o=Math.abs(s.pose.r[1][1]-1)<1e-6,r=s.shape.extrusion;let a;const c=[];if(o&&"y"===r?.axis){const t=(t,e)=>i(eA(nk(t,r.end,s.segments??12,e),s.pose.r,s.pose.t));a=t(r.section);const e=s.shape.cavity;if(e&&"open"===e.end){const n=c_(r.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=tk(i(t));const l=s.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:s.id,color:e[h]??"#9a9a9a",outline:a,holes:c,top:Math.max(...t.map(t=>t[1])),transparent:!!l.transparent})}return n.sort((t,e)=>t.top-e.top)}(r.geometry,r.palette).map(e=>{const n=i[(e=>{const n=a.get(e);return n?.key?t.compiled.writers.get(n.key):e})(e.id)??""];return n&&!a.get(e.id)?.material.emissive?.on?{...e,color:n}:e}),l=1===n?c:c.map(t=>({...t,outline:t.outline.map(([t,e])=>[t*n,e*n]),holes:t.holes.map(t=>t.map(([t,e])=>[t*n,e*n]))}));return{shapes:l,size:o.drawnSize}}const JP=Object.freeze({states:{},palette:{},motion:{},parts:{},pose:{},items:[]}),QP=t=>"number"==typeof t&&Number.isFinite(t),ZP=t=>!!t&&"object"==typeof t&&!Array.isArray(t);function tI(t,e){return null==e?null:"number"===t.kind?QP(e)?void 0!==t.min&&e<t.min||void 0!==t.max&&e>t.max?"out-of-range":null:"type-mismatch":"boolean"===t.kind?"boolean"==typeof e?null:"type-mismatch":"text"===t.kind?"string"!=typeof e?"type-mismatch":t.values&&!t.values.includes(e)?"value-unknown":null:"list"===t.kind?Array.isArray(e)?null:"not-a-list":ZP(e)?null:"not-a-record"}function eI(t,e,n,s,i){if(!ZP(t))return t;const o=e[n];if(!Object.prototype.hasOwnProperty.call(t,o.name))return t;const r=s?`${s}.${o.name}`:o.name;let a=t[o.name];const c=n===e.length-1;if(c&&"string"==typeof a)try{a=JSON.parse(a)}catch{return i.push({reason:"json-unreadable",path:r}),{...t,[o.name]:void 0}}else if(!c){const t=(s,o,r)=>o>0?Array.isArray(s)?s.map((e,n)=>t(e,o-1,`${r}[${n}]`)):s:eI(s,e,n+1,r,i);a=t(a,o.lists,r)}return{...t,[o.name]:a}}class nI{constructor(t){this.plan=t,this.bindings=t.bindings.map(t=>{const e=t.binding,n={};if("table"!==e.rule&&"items"===e.behavior.kind)for(const t of["id","type","place","stack","status"]){const s=e.behavior[t];s&&(n[t]=Js(s))}const s="table"===e.rule?t=>t:mi({param:e.param},null,e.rule,e.param,void 0);return{ready:t,read:Js(e.accessor),turn:s,element:n}})}read(t){const e=[],n=[],s=void 0===t.live||null===t.live?void 0:function(t,e,n){if(!e.length||!ZP(t))return t;let s=t;for(const t of e)s=eI(s,t.split(".").map(t=>{const e=(t.match(/\[\]/g)??[]).length;return{name:t.replace(/\[\]/g,""),lists:e}}),0,"",n);return s}(t.live,this.plan.jsonFields,e);void 0===s||ZP(s)||e.push({reason:"not-a-record",path:""});const i=t.manual??null,o={states:{},palette:{},motion:{},parts:{},pose:{},items:[]},r={};for(const{ready:t,read:a,turn:c,element:l}of this.bindings){const h=t.binding;if("table"!==h.rule&&"items"===h.behavior.kind){const n=void 0===s?void 0:a(s);o.items.push({binding:h.id,...h.behavior.slot?{slot:h.behavior.slot}:{},records:this.records(t,n,l,e)});continue}let d,u="absent";const p=void 0===s?void 0:a(s);if(null!=p){const n=tI(t.node,p);n&&e.push({reason:n,path:h.accessor,value:p}),[d,u]=[p,"live"]}else if(i&&void 0!==i[h.accessor]&&null!==i[h.accessor]){const e=tI(t.node,i[h.accessor]);e&&n.push({reason:e,path:h.accessor,value:i[h.accessor]}),[d,u]=[i[h.accessor],"manual"]}else{const e="default"in t.node?t.node.default:void 0;void 0!==e&&([d,u]=[e,"default"])}r[h.id]={value:d,source:u},"absent"!==u&&"table"!==h.rule&&sI(o,h,c(d))}return{result:o,values:r,liveIssues:e,manualIssues:n}}records(t,e,n,s){const i=t.binding;if(null==e||""===e)return[];if("list"!==t.node.kind){const n=tI(t.node,e);return n?(s.push({reason:n,path:i.accessor,value:e}),[]):[{id:String(e)}]}if(!Array.isArray(e))return s.push({reason:"not-a-list",path:i.accessor,value:e}),[];const o=[];return e.forEach((e,r)=>{const a=o=>{const a=n[o]?.(e),c=t.itemNodes?.[o],l=c?tI(c,a):null;return l&&s.push({reason:l,path:`${i.accessor}[${r}].${i.behavior[o]}`,value:a}),null===a?void 0:a},c=a("id");if(void 0===c||""===c)return void s.push({reason:"item-id-missing",path:`${i.accessor}[${r}]`});const[l,h,d,u]=[a("type"),a("place"),a("stack"),a("status")];o.push({id:String(c),...void 0!==l?{type:String(l)}:{},...void 0!==h?{place:String(h)}:{},...QP(d)?{stack:d}:{},...void 0!==u?{status:String(u)}:{}})}),o}}function sI(t,e,n){if(null==n)return;const s=e.behavior;"state"===s.kind?t.states[s.input]={value:n,sourceMode:s.sourceMode}:"palette"===s.kind?t.palette[s.token]=n:"motion-clip"===s.kind?t.motion[s.group]={...t.motion[s.group],clip:n}:"motion-speed"===s.kind?t.motion[s.group]={...t.motion[s.group],speed:n}:"motion-paused"===s.kind?t.motion[s.group]={...t.motion[s.group],paused:n}:"pose"===s.kind&&(t.pose[s.axis]={value:n,seconds:s.seconds??0})}const iI=t=>!!t&&"object"==typeof t&&!Array.isArray(t);class oI{constructor(t){this.asset=t,this.live=null,this.liveEpoch=-1/0,this.manualValues={},this.manualMotion={},this.result=JP,this.values={},this.motionSettings={},this.refused=[],this.legends={},this.legendNotes=[],this.notes=[],this.uses={},this.dataPlan=function(t){if(void 0===t.dataInterface)return null;PS(t);const e=structuredClone(t.dataInterface),n=e.bindings.map(t=>{const n=xS(e.schema,_S(t.accessor)).node;let s;if("table"!==t.rule&&"items"===t.behavior.kind&&"list"===n.kind){const e=n.item;s={};for(const n of["id","type","place","stack","status"]){const i=t.behavior[n];i&&(s[n]=xS("object"===e.kind?e.fields:[],_S(i)).node)}}return Object.freeze({binding:Object.freeze(t),node:n,...s?{itemNodes:Object.freeze(s)}:{}})}),s=[],i=(t,e)=>{for(const n of t){const t=e?`${e}.${n.name}`:n.name;n.json&&s.push(t);let o=n,r=t;for(;"list"===o.kind;)r=`${r}[]`,o=o.item;"object"===o.kind&&i(o.fields,r)}};return i(e.schema,""),Object.freeze({schema:Object.freeze(e.schema),bindings:Object.freeze(n),jsonFields:Object.freeze(s)})}(t),this.reader=this.dataPlan?new nI(this.dataPlan):null,this.motionPlan=zS(t),this.recompute()}setData(t,e){if(void 0!==e){if(e<this.liveEpoch)return{accepted:!1,skipped:!0,issues:[]};this.liveEpoch=e}if(null==t||!this.reader)return this.live=null,this.clear("live"),this.recompute(),{accepted:!0,issues:[]};const{liveIssues:n}=this.reader.read({live:t,manual:null});return n.length?this.refuse({source:"live",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:n}):(this.live=t,this.clear("live"),this.recompute(),{accepted:!0,issues:[]})}setManual(t){const e=[],n=t.figureValues??{};if(iI(n))if(this.reader){const{manualIssues:t}=this.reader.read({manual:n});t.length?e.push({source:"manual",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:t}):this.manualValues={...n}}else Object.keys(n).length&&e.push({source:"manual",severity:"refused",code:"DATA_INTERFACE",reason:"no-data-interface"});else e.push({source:"manual",severity:"refused",code:"DATA_VALUE",reason:"data-values-refused",issues:[{reason:"not-a-record",path:"figureValues"}]});const s=t.motion??{};try{if(!iI(s))throw new Xv("MOTION_SETTING","motion","a setting per group",{reason:"motion-setting",why:"group-unknown",group:""});RS(this.motionPlan,s,null),this.manualMotion={...s}}catch(t){if(!(t instanceof Xv))throw t;const n=t.details;e.push({source:"motion",severity:"refused",code:"MOTION_SETTING",reason:n?.why??n?.reason??"motion-setting",group:n?.group})}return this.clear("manual"),this.clear("motion"),this.refused.push(...e),this.recompute(),{accepted:!e.length,issues:e}}setThemes(t){const e=t.legends??{},n=t.notes??[],s=Object.keys(e),i=s.length===Object.keys(this.legends).length&&s.every(t=>this.legends[t]&&this.legends[t].legend===e[t].legend&&this.legends[t].source===e[t].source&&this.legends[t].name===e[t].name)&&JSON.stringify(n)===JSON.stringify(this.legendNotes);return!i&&(this.legends={...e},this.legendNotes=[...n],this.recompute(),!0)}get data(){return this.result}get tableUses(){return this.uses}get dataValues(){return this.values}get motion(){return this.motionSettings}diagnostics(){return[...this.refused,...this.notes]}refuse(t){return this.clear(t.source),this.refused.push(t),{accepted:!1,issues:[t]}}clear(t){this.refused=this.refused.filter(e=>e.source!==t)}recompute(){const t=this.legendNotes.map(t=>({source:"legend",severity:"note",code:"LEGEND_ABSENT",reason:t.reason,binding:t.binding,role:t.role,...void 0!==t.name?{legend:t.name}:{},...void 0!==t.value?{value:t.value}:{}}));if(this.uses={},this.reader){const e=this.reader.read({live:this.live,manual:this.manualValues});this.result=e.result,this.values=e.values;for(const{binding:e}of this.dataPlan.bindings)"table"===e.rule&&this.showTable(e,t)}this.notes=t,this.motionSettings=RS(this.motionPlan,this.manualMotion,this.result.motion)}showTable(t,e){const n=t.legend?.role,s=n?this.legends[n]:void 0,i=(i,o,r={})=>e.push({source:"legend",severity:"note",code:i,reason:o,binding:t.id,...n?{role:n}:{},...s?.name?{legend:s.name}:{},...r});let o=t.table,r="figure";if(s){const t=YP(s.legend);t?[o,r]=[t,s.source]:i("LEGEND_SHAPE","not-a-table",{value:"string"==typeof s.legend?s.legend.slice(0,80):s.legend})}const a=this.values[t.id],c=e=>this.uses[t.id]={value:a?.value,key:e,source:r,..."figure"!==r&&s?.name?{legend:s.name}:{}};if(!a||"absent"===a.source)return void c(null);const l=function(t,e,n,s){const i=Object.keys(n);if("code"===t)return Qs(e,Object.fromEntries(i.map(t=>[t,t])))??null;const o=[];for(const t of i){if("default"===t)continue;const e=ES(t);e?o.push({min:Number.isFinite(e[0])?e[0]:null,max:Number.isFinite(e[1])?e[1]:null,result:t}):s(t)}return ti(e,o,Object.prototype.hasOwnProperty.call(n,"default")?"default":void 0)??null}(t.lookup,a.value,o,t=>i("LEGEND_VALUE","not-an-interval",{key:t}));if(c(l),null===l)return void i("CODE_UNMATCHED","code-unmatched",{value:a.value});const h=o[l],d="string"==typeof h&&pS(h)?{color:h}:iI(h)?h:null;if(!d)return void i("LEGEND_VALUE","not-a-look",{key:l,value:h});const u=(t,e,n)=>i("LEGEND_VALUE","not-taken",{key:l,column:t,value:e,...void 0!==n?{id:n}:{}}),{parts:p=[],inputs:f=[],group:m}=t.targets,g=this.result;if(p.length&&void 0!==d.color)if(pS(d.color))for(const t of p)g.parts[t]={...g.parts[t],color:d.color};else u("color",d.color);if(p.length&&void 0!==d.effect){const t=d.effect,e=void 0===t?.hz||"number"==typeof t.hz&&Number.isFinite(t.hz)&&t.hz>0;if(iI(t)&&("blink"===t.kind||"glow"===t.kind)&&e)for(const e of p)g.parts[e]={...g.parts[e],effect:{kind:t.kind,...void 0!==t.hz?{hz:t.hz}:{}}};else u("effect",d.effect)}if(f.length&&void 0!==d.values)if(iI(d.values))for(const[t,e]of Object.entries(d.values)){if(!f.includes(t))continue;const n=this.ranges.get(t);"number"!=typeof e||!Number.isFinite(e)||n&&(e<n.min||e>n.max)?u("values",e,t):g.states[t]={value:e,sourceMode:"observed"}}else u("values",d.values);if(void 0!==m){const t=this.motionPlan.groups.get(m)?.group.clips??[],e={...g.motion[m]};void 0!==d.clip&&("string"==typeof d.clip&&t.includes(d.clip)?e.clip=d.clip:u("clip",d.clip,m)),void 0!==d.speed&&("number"==typeof d.speed&&d.speed>=0&&d.speed<=3?e.speed=d.speed:u("speed",d.speed,m)),void 0!==d.paused&&("boolean"==typeof d.paused?e.paused=d.paused:u("paused",d.paused,m)),Object.keys(e).length&&(g.motion[m]=e)}}get ranges(){return this._ranges??=new Map(this.asset.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,{min:t.min,max:t.max}]))}}const rI=["x","z","y","heading"];class aI{constructor(t){this.component=t,this.runs=new Map}aim(t){const e=this.now(),n={};for(const s of rI){const i=t[s];if(!i||!Number.isFinite(i.value))continue;const o=this.runs.get(s);(o?o.to:e[s])!==i.value&&(i.seconds>0?this.runs.set(s,{from:e[s],to:i.value,seconds:i.seconds,elapsed:0}):(this.runs.delete(s),n[s]=i.value))}Object.keys(n).length&&this.write(n),this.runs.size&&this.startTicking()}advance(t){if(!this.runs.size)return!1;const e={};for(const[n,s]of this.runs){s.elapsed=Math.min(s.seconds,s.elapsed+t);const i=s.elapsed/s.seconds;e[n]=s.from+(s.to-s.from)*i,i>=1&&this.runs.delete(n)}return this.write(e),this.runs.size||this.stopTicking(),!0}dispose(){this.runs.clear(),this.stopTicking()}startTicking(){this.unsubscribe||(this.unsubscribe=_o.subscribe(t=>this.advance(t/1e3),{description:`Figure[${this.component.state.type}].pose`,component:this.component}))}stopTicking(){this.unsubscribe?.(),this.unsubscribe=void 0}get mmPerUnit(){return rh(this.component).mmPerUnit}now(){const t=this.component.state,e=t=>"number"==typeof t&&Number.isFinite(t)?t:0,n=this.mmPerUnit;return{x:(e(t.left)+e(t.width)/2)*n,z:(e(t.top)+e(t.height)/2)*n,heading:180*e(t.rotation)/Math.PI,y:e(t.zPos)*n}}write(t){const e=this.component.state,n=this.mmPerUnit,s={};void 0!==t.x&&(s.left=t.x/n-(e.width??0)/2),void 0!==t.z&&(s.top=t.z/n-(e.height??0)/2),void 0!==t.heading&&(s.rotation=t.heading*Math.PI/180),void 0!==t.y&&(s.zPos=t.y/n),this.component.setState?this.component.setState(s):this.component.set?.(s)}}const cI=t=>{const e=Wl(t),n=e?Yl(e,t)?.figure:t?.itemTypeCode??t?.state?.type;return"string"==typeof n?BO(n):null};Ov({keyFor(t){const e=cI(t);return e?`${e.type}|${e.compiled.fingerprint}|${rh(t).mmPerUnit}`:null},lookFor(t){const e=cI(t);if(!e)return null;const n=rh(t).mmPerUnit,s=wP(e.compiled.asset),i=new hI({type:e.type,left:0,top:0,width:s.x/n,height:s.z/n,depth:s.y/n,...void 0!==t.state.data?{data:t.state.data}:{}});return i.parent=t,{key:`${e.type}|${e.compiled.fingerprint}|${n}`,component:i,depth:s.y/n,fitTo({width:t,depth:s,height:o}){const r={x:t,z:s,y:o},a=["x","z","y"].map(t=>AP(e.compiled.asset,r,[t]).box),c=1e-6,l=t=>t.x*t.y*t.z,h=a.filter(e=>e.x<=t+c&&e.z<=s+c&&e.y<=o+c),d=h.length?h.reduce((t,e)=>l(e)>l(t)?e:t):a.reduce((t,e)=>l(e)<l(t)?e:t);i.set({width:d.x/n,height:d.z/n,depth:d.y/n})},dispose(){i._realObject?.dispose(),i.dispose()}}},dimsOf(t){const e=cI(t);if(!e)return null;const n=wP(e.compiled.asset);return{width:n.x,depth:n.z,height:n.y}},subscribe:FO});const lI={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"select",label:"lod",name:"lod",placeholder:"Auto",property:{options:[{display:"Auto",value:"auto"},{display:"Full",value:"full"}]}}],help:"scene/component/figure"};class hI extends(mc(pc)){constructor(){super(...arguments),this.onPicked=(t=[],e=[])=>{t.includes(this)!==e.includes(this)&&this.invalidate()}}static registerType(t,e=[],n,s){const i=uc.register(t);if(i&&!(i===hI||i.prototype instanceof hI))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const o=OO(hI,e,n,s);uc.register(t,o)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=BO(this.state.type);if(!t)return lI;const e=t.compiled.asset,n=e.document.model.inputs,s=(e.publicInputs??[]).flatMap(t=>{const s=n.find(e=>e.id===t.input);return s?[{key:t.input,label:t.label,unit:s.unit,min:s.min,max:s.max,default:e.designInputs[t.input]}]:[]}),i=n.filter(t=>"state"===t.role).map(t=>({key:t.id,label:e.stateInputs?.[t.id]?.label??t.id,unit:t.unit,min:t.min,max:t.max,default:e.stateDefaults[t.id]})),o=new Set((e.motionGroups??[]).flatMap(t=>t.clips)),r=[...new Set((e.drivers??[]).map(t=>t.clip))].filter(t=>!o.has(t)).map(t=>({key:t,label:t,min:0,max:3})),a=new Map((e.dataInterface?function(t){const e=[],n=new Map,s=(t,e)=>n.set(t,[...n.get(t)??[],e]),i=t=>t.replace(/\[\d+\]/g,"[]");for(const e of t.bindings)if(s(i(e.accessor),e.id),"table"!==e.rule&&"items"===e.behavior.kind)for(const t of[e.behavior.id,e.behavior.type,e.behavior.place,e.behavior.stack,e.behavior.status])t&&s(`${i(e.accessor)}[].${i(t)}`,e.id);const o=(t,s,i)=>{for(const r of t){const t=s?`${s}.${r.name}`:r.name;e.push({path:t,depth:i,name:r.name,...r.label?{label:r.label}:{},node:r,json:!!r.json,bindings:n.get(t)??[]});let a=r,c=t;for(;"list"===a.kind;)c=`${c}[]`,a=a.item;"object"===a.kind&&o(a.fields,c,i+1)}};return o(t.schema,"",0),e}(e.dataInterface):[]).map(t=>[t.path,t.label??t.name])),c=new Set,l=(this.figureInputs?.dataPlan?.bindings??[]).flatMap(({binding:t,node:e})=>{if("table"!==t.rule&&"items"===t.behavior.kind||c.has(t.accessor))return[];c.add(t.accessor);const n=a.get(t.accessor.replace(/\[\d+\]/g,"[]"))??t.accessor;return"number"===e.kind?[{key:t.accessor,label:n,unit:e.unit,min:e.min,max:e.max,default:e.default}]:"boolean"===e.kind?[{key:t.accessor,label:n,kind:"boolean",default:e.default}]:"text"===e.kind&&e.values?[{key:t.accessor,label:n,kind:"enum",values:[...e.values],default:e.default}]:[]}),h=(e.motionGroups??[]).flatMap(t=>[{key:`${t.id}.clip`,label:t.label,kind:"enum",values:[...t.clips],default:t.defaultClip},{key:`${t.id}.speed`,label:t.label,unit:"×",min:0,max:3,default:0},{key:`${t.id}.paused`,label:t.label,kind:"boolean",unit:"‖",default:!1}]),d=[...lI.properties];s.length&&d.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:s}}),i.length&&d.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:i}}),r.length&&d.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),e.dataInterface&&d.push({type:"figure-data",label:"figure-data",name:"data"}),l.length&&d.push({type:"number-map",label:"data-values",name:"figureValues",property:{entries:l}}),GP(this.figureInputs?.dataPlan).size&&d.push({type:"figure-legends",label:"figure-legends",name:"legends"}),h.length&&d.push({type:"number-map",label:"motion-groups",name:"motion",property:{entries:h,nested:!0}});for(const t of(this.constructor.capabilities??[]).filter(t=>Fv(t)))for(const e of AO(t)?.properties??[])d.some(t=>t.name===e.name)||d.push(e);return e.document.capabilities.slotLayout&&d.push({type:"slot-layout",label:"slot-layout",name:"slotLayout",property:{options:t=>jP(t[0])}}),d.length===lI.properties.length?lI:{...lI,properties:d}}get figureInputs(){const t=BO(this.state.type);if(t){if(this._inputs?.fingerprint!==t.compiled.fingerprint){const e=new oI(t.compiled.asset);e.setManual({figureValues:this.state.figureValues,motion:this.state.motion}),e.setData(this.state.data),this._inputs={fingerprint:t.compiled.fingerprint,inputs:e}}return this._inputs.inputs}}buildRealObject(){return GO(this.state.type)?new qP(this):void 0}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state,o=BO(this.state.type);if(!o)return void this.renderPlace(t,e,n,s,i);const r=this.topView(o,s,i),a=this.mmPerUnit,{centre:c}=this.appliedAt(o.compiled.asset,s,i,this.askedDepth),l=e+s/2-c.x,h="wall"===o.compiled.asset.placement?n:n+i/2-c.z,d=Number(this.effectiveOpacity),u=Number.isFinite(d)&&d>0&&d<1?d:1;for(const e of r.shapes)if(!(e.outline.length<3)){t.save(),t.fillStyle=e.color,e.transparent&&(t.globalAlpha=.35),t.globalAlpha*=u,t.beginPath();for(const n of[e.outline,...e.holes])if(!(n.length<3)){t.moveTo(l+n[0][0]/a,h+n[0][1]/a);for(let e=1;e<n.length;e++)t.lineTo(l+n[e][0]/a,h+n[e][1]/a);t.closePath()}t.fill("evenodd"),t.restore()}this.picked&&this.renderMotionRange(t,o,s,i,l,h)}get picked(){return!!this.app?.isEditMode&&(this.root?.selected??[]).includes(this)}renderMotionRange(t,e,n,s,i,o){const r=e.compiled.asset,a=this.mmPerUnit,c=function(t,e){let n=EP.get(t);n||EP.set(t,n=new Map);const s=e.inputs?`${e.inputs.x}|${e.inputs.y}|${e.inputs.z}`:"authored";n.has(s)||n.set(s,NA(t,e.inputs?kP(e.inputs):{})?.bounds??null);const i=n.get(s);if(!i||e.inputs)return i;const o=e.scale;return Object.fromEntries(bP.map(t=>[t,{min:i[t].min*o,max:i[t].max*o}]))}(r,AP(r,{x:n*a,z:s*a,y:void 0===this.askedDepth?void 0:this.askedDepth*a}));if(!c)return;const l="wall"===r.placement?c.y:c.z;t.save(),t.strokeStyle="rgba(80, 120, 200, 0.7)",t.lineWidth=1,t.setLineDash([6,4]),t.beginPath(),t.rect(i+c.x.min/a,o+l.min/a,(c.x.max-c.x.min)/a,(l.max-l.min)/a),t.stroke(),t.restore()}topView(t,e,n){const s=this.appliedAt(t.compiled.asset,e,n,this.askedDepth),i=s.inputs,o=this.figureInputs;o&&GP(o.dataPlan).size&&o.setThemes(WP(this,o.dataPlan));const r=this.figureInputs?.data.palette??{},a=Object.fromEntries(Object.entries(this.figureInputs?.data.parts??{}).flatMap(([t,e])=>e.color?[[t,e.color]]:[])),c=`${t.compiled.fingerprint}|${i?`${i.x}|${i.y}|${i.z}`:`x${s.scale}`}|${JSON.stringify(r)}|${JSON.stringify(a)}`;return this._top?.key!==c&&(this._top={key:c,view:KP(t,i,s.scale,r,a)}),this._top.view}get mmPerUnit(){return rh(this).mmPerUnit}appliedAt(t,e,n,s,i){const o=this.mmPerUnit,r=AP(t,{x:e*o,z:n*o,y:void 0===s?void 0:s*o},i),a=r.box,c=r.centre;return{...r,box:{x:a.x/o,y:a.y/o,z:a.z/o},centre:{x:c.x/o,y:c.y/o,z:c.z/o}}}get askedDepth(){return SP(this)}adjustResize(t,e,n){const s=BO(this.state.type);if(!s)return super.adjustResize(t,e,n);const i=s.compiled.asset,o=xP(i),r=super.adjustResize(t,e,n),a=this.bounds,c=[];Math.abs(r.width-a.width)>1e-6&&c.push("x"),Math.abs(r.height-a.height)>1e-6&&c.push("z");const{box:l}=this.appliedAt(i,r.width,r.height,o?void 0:this.askedDepth,c);return{left:Math.abs(r.left-a.left)>1e-6?r.left+r.width-l.x:r.left,top:Math.abs(r.top-a.top)>1e-6?r.top+r.height-l.z:r.top,width:l.x,height:l.z}}added(t){super.added(t),this.root?.on?.("selected",this.onPicked),this.fitBoxToFigure([])}get figurePose(){return this._pose??=new aI(this)}async ready(){await super.ready();const t=this.figureInputs?.data.pose;t&&this.figurePose.aim(t)}onchange(t,e){if(super.onchange(t,e),this._inputs&&(("figureValues"in t||"motion"in t)&&this._inputs.inputs.setManual({figureValues:this.state.figureValues,motion:this.state.motion}),"data"in t&&this._inputs.inputs.setData(t.data)),"data"in t){const t=this.figureInputs?.data.pose;t&&this.figurePose.aim(t)}const n=[];"width"in t&&n.push("x"),"height"in t&&n.push("z"),"depth"in t&&n.push("y"),n.length&&this.fitBoxToFigure(n)}removed(t){this.root?.off?.("selected",this.onPicked),this._pose?.dispose(),super.removed(t)}fitBoxToFigure(t){if(!this.rootModel)return;const e=BO(this.state.type);if(!e)return;const n=e.compiled.asset,s=xP(n),{width:i=0,height:o=0}=this.state;if(!(i>0&&o>0)){const t=wP(n),e=t.x/this.mmPerUnit,s=t.z/this.mmPerUnit,{left:r=0,top:a=0}=this.state;return void this.set({left:r+i/2-e/2,top:a+o/2-s/2,width:e,height:s})}const{box:r}=this.appliedAt(n,i,o,this.askedDepth,t),a={};Math.abs(r.x-i)>1e-6&&(a.width=r.x),Math.abs(r.z-o)>1e-6&&(a.height=r.z);const c=this.state.depth,l="number"==typeof c&&Number.isFinite(c)&&c>0?c:void 0;(void 0!==l&&Math.abs(r.y-l)>1e-6||s&&void 0===this.askedDepth&&t.includes("y"))&&(a.depth=r.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,s,i){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,s,i),t.stroke(),t.restore()}postrender(t){uc.prototype.postrender.call(this,t)}}yO(hI);const dI={"palette.primary":"#154473","palette.accent":"#f79c40","palette.neutral":"#96989b","palette.dark":"#27292c","palette.light":"#d6d7d9","palette.surface":"#56585b","palette.status-danger":"#f61b30","palette.status-warning":"#e68d1a","palette.status-info":"#158bde","palette.status-success":"#1cb648"},uI=new Map([["default",dI]]);let pI="default",fI=0;function mI(){return fI}function gI(t,e){uI.set(t,e),t===pI&&fI++}function yI(t){if(!uI.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...uI.keys()].join(", ")}`);t!==pI&&(pI=t,fI++)}function bI(){return pI}function vI(){return uI.get(pI)}function _I(t){const e=vI()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${pI}'). 쓸 수 있는 것 — ${Object.keys(vI()).join(", ")}`);return e}const xI=dI["palette.neutral"];function wI(){uI.clear(),uI.set("default",dI),pI="default",fI++}const MI={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},SI=["shape","segments"],AI=["color","preset","transparent","glow"];function kI(t,e){let n;try{n=iP(t,e)}catch{return null}if(!n?.getAttribute("position"))return null;const s=n.clone();n.dispose(),s.computeBoundingBox();const i=s.boundingBox,o=i.getCenter(new w.Vector3),r=i.getSize(new w.Vector3);return s.translate(-o.x,-o.y,-o.z),s.scale(1/(r.x||1),1/(r.y||1),1/(r.z||1)),s.computeBoundingBox(),s.getAttribute("normal")||s.computeVertexNormals(),{geometry:s,extent:r,centre:o}}class EI extends Du{build(){super.build();const t=this.component.state,e=t.shape?kI(t.shape,t.segments):null;if(!e)return;const n=new w.Mesh(e.geometry,this.material());n.castShadow=!0,n.receiveShadow=!0,this.object3d.add(n),this.mesh=n,this.updateDimension(),t.shape?.mesh&&this.dressWithFile(n,t.shape.mesh,e)}dressWithFile(t,e,n){mP({asset:e.asset,...void 0!==e.node?{node:e.node}:{},scale:e.scale}).then(e=>{if(!e||this.mesh!==t)return;const s=new w.Group;s.scale.set(1/(n.extent.x||1),1/(n.extent.y||1),1/(n.extent.z||1)),e.position.set(-n.centre.x,-n.centre.y,-n.centre.z),s.add(e),t.add(s),t.material=EI.HIDDEN_BOX,this.component.invalidate?.()})}clear(){return this.mesh?.geometry.dispose(),this.mesh=void 0,super.clear()}onchange(t,e){const n=e=>e.some(e=>e in t);n(SI)?this.update():(super.onchange(t,e),n(AI)&&this.mesh&&this.mesh.material!==EI.HIDDEN_BOX&&(this.mesh.material=this.material()))}updateDimension(){const{width:t=1,height:e=1}=this.component.bounds;this.setDimensionScale(t||1,this.effectiveDepth||1,e||1)}material(){const t=this.component.state,e=Fd[t.preset??"default"]??Fd.default,n=t.color??"#9a9a9a",s=t.transparent??!1,i=t.glow,o=i?i.color:n,r=i?i.intensity:0;return NT.material(`figure-part|${n}|${t.preset??"default"}|${s}|${i?`${i.color}:${r}`:"-"}`,{color:o,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:s,opacity:s?e.opacity??.3:1,emissive:o,emissiveIntensity:r})}}EI.HIDDEN_BOX=new w.MeshBasicMaterial({visible:!1});class TI extends(mc(pc)){static registerType(){uc.register("figure-part",TI)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return MI}buildRealObject(){return new EI(this)}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state;t.beginPath(),t.rect(e,n,s,i),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var CI;TI.registerType(),t.Model=void 0,(CI=t.Model||(t.Model={})).compile=kl,CI.duplicate=El,CI.select=Fa,CI.match=ja,Ss.registerResidents(()=>({componentResidentsCount:uc.residentsCount,sceneResidentsCount:lp.residentsCount,referenceMapResidentsCount:wT.residentsCount,sceneResidents:uc.residents}));var OI=Object.freeze({__proto__:null,AbsoluteLayout:Mc,Animation:la,AudioPlayer:Ab,BULGE_EPSILON:Do,get Banner(){return t.Banner},Banner3D:AC,BoxSelectionManager:Xf,COMMON_PLACEHOLDER_PROPERTIES:Yy,CORE_PLACEHOLDER_TYPES:Jy,get Camera(){return t.Camera},Camera3D:CC,CameraBookmarkManager:qf,CameraManager:If,Capacity:kk,CapacityEventTracker:cv,CardLayout:Ac,CenteringQueueStrategy:hv,CenteringSlotStrategy:ZE,Component:uc,Connectable:xm,Container:Cy,ContainerAbstract:Kl,ControlsManager:jf,get Cube(){return t.Cube},Cube3D:xC,get Cylinder(){return t.Cylinder},Cylinder3D:MC,DEFAULT:zi,DEFAULT_CEILING:Cu,DEFAULT_PALETTE:dI,DEFAULT_PLACEMENT:wu,DEFAULT_SEAT_MARGIN:NM,DPPX:Pi,DRAWING_DISPLAY_UNITS:Jl,DataLagTracker:bh,DataSource:tv,DefaultLoadingOverlayRenderer:Zd,Donut:Ub,DonutExtrude:rC,EMPTY_FIGURE_DATA:JP,Ellipse:Vy,EllipseExtrude:nC,EventManager3D:$f,EventMap:Qc,FIGURE_CAPABILITIES:vO,FIGURE_OWN_TABLE:$P,FPS:Jp,FigureDataReader:nI,FigureInputs:oI,FigureInstance:hI,FigurePart:TI,FigurePartRealObject:EI,FixedSlotStrategy:xk,get FloorPlate(){return t.FloorPlate},FlowEngine:zE,FlowNode:GE,GESTURES:Ii,get GLTFObject(){return t.GLTFObject},GLTF_BASE_URL_ALIAS:nv,GenericObject:Ky,GeometryBank:Av,GifView:Mb,GizmoManager:Nf,GizmoOperationManager:Gf,GlobalRef:Db,GltfComponent:iv,GridStacking:pv,Group:Tb,HOLDER_ANCHOR:wM,HTMLAbsoluteLayout:wc,HTMLOverlayContainer:Pb,HTMLOverlayElement:db,Holdable:NE,ITEM_TYPES_THEME:Hl,ITEM_TYPE_CODE_MAX:64,ImageView:hb,InfoWindow:vc,InstancedSet:sO,InteractionManager:Uf,Item:zv,ItemRealObject:Rv,ItemsDataBinding:wv,KEYEVENTS:Di,Layer:Cp,Layout:xc,LightManager:zf,LightObject:IC,Line:Gy,Line3D:ZC,LinearHorizontalLayout:Ec,LinearVerticalLayout:Cc,LoadTracker:xh,LoadingOverlay:Vd,LocalRef:Ob,MATERIAL_PRESETS:Fd,MAX_SEGMENTS:dC,MAX_UNDO_SIZE:30,MIN_SEGMENTS:3,MODE_ADD:3,MODE_EDIT:1,MODE_PASTE_DATABIND:5,MODE_PASTE_STYLE:4,MODE_SHIFT:2,MODE_VIEW:0,MaterialBank:NT,get Model(){return t.Model},MoveHandle:ql,NOTHING:Ci,NavGraph:oT,Node:Xb,OrthoLine:cb,OrthoLine3D:eO,PIXEL_RATIO:Qp,PLACEHOLDER_THEMES:Wy,Path:Fb,PatternStacking:uv,PlacementManager:Vf,get PointLight(){return t.PointLight},Polygon:eb,PolygonContainer:sb,PolygonExtrude:oC,PolygonPathPolyline:uT,Polyline:rb,Polyline3D:tO,Popup:jb,PopupContainer:Lb,Pose6DOF:il,RealObject:Du,RealObjectCamera:aO,RealObjectDomElement:af,RealObjectDomTexture:jT,RealObjectDummy:oO,RealObjectExternalModel:ju,RealObjectExtrude:eC,RealObjectGLTF:Nu,RealObjectGroup:HC,RealObjectLine:QC,RealObjectMesh:HT,RealObjectPlane:cO,RealObjectPlane2D:dO,RealObjectScene:lO,RealObjectService:Kb,RealObjectSprite:yC,RealObjectSprite2D:bC,RealObjectText:qT,Rect:Sm,RectExtrude:sC,RectPath:mc,ReferenceMap:wT,RendererManager:Df,ReservationTable:sT,RootContainer:yh,Ruler:km,SCALE_MIN:cu,SCENE_MODE:Oi,SEGMENT_DEFAULTS:hC,SEGMENT_PRESETS:lC,SHORTCUT_SECTIONS:pm,Scene:lp,SceneManager:Pf,ScenePopup:Tp,SceneSearchEngine:Vu,ScriptLoader:CT,SearchOverlay:Yu,ServiceComponent:Qb,Shape:pc,get Sphere(){return t.Sphere},Sphere3D:gC,get Sprite(){return t.Sprite},Star:Yb,StarExtrude:cC,TRANSFER_SLOT_KEY:_v,TableLayout:Oc,Text:kb,ThreeCapability:rm,get ThreeContainer(){return t.ThreeContainer},ThreeDOnly:ev,Tracker:Xu,Transfer:op,TransitionEffect:Nl,Triangle:Hb,TriangleExtrude:aC,UNIT_DIMENSION:uu,UNIT_ROTATE:mu,UNIT_SCALE:pu,UNIT_TRANSLATE:fu,UNTOKENED_COLOR:xI,ValueHolder:Zb,VertexGizmoManager:tm,VolumeStacking:fv,get Wall(){return t.Wall},Wall3D:zC,Z_PRIORITY:Su,acquireFigureGeometry:nP,activePalette:vI,activePaletteName:bI,addressOfSlotId:jM,allDestinations:xE,anchorsConnect:Ik,animate:ca,applyAlpha:hu,applyMaterial3dProps:Gd,applyPolicy:SE,applySeatingRotation:vv,applyStackLayout:mv,applyZPriorityToMaterials:ku,arcSegmentTopology:Ok,autoWireBackPressure:lv,buildArrow3D:of,buildContractInspector:bT,buildCoordinateGround:yf,buildFigureGeometry:iP,buildFlowGraph:$k,buildNavGraph:cT,buildShapeFromPolygonPath:iC,buildTether:vp,bulgeFromDrag:$o,bulgeHandlePosition:jo,calibratedMmPerUnit:oh,canReach:Bk,capability:rg,ceilingZPos:XP,centerOnBBox:tC,chooseNearestPickupFrame:QE,clearTether:xp,collectAdjacentSegments:Yk,compile:da,componentForNode:_E,computeArcParams:Ro,computeFlowMap:cE,computeStackPositions:dv,cornerHandlePosition:Fo,cornerRadiusFromDrag:No,create:dp,createCanvas:Zp,createCanvasTexture:IT,createFloor:Tf,createRealObjectFor:uf,createSelectionHandle3D:$C,dataLagTracker:vh,debug:Hs,deliversInto:Rk,delta:ra,displayToMm:ih,disposeCoordinateGround:xf,disposeObject3D:bu,disposeTether:wp,downstream:EE,drawTextTexture:UT,drawingScaleFor:rh,drawingScaleOf:th,drawingToMm:nh,effectiveCornerRadius:Lo,ellipseOutline:ZT,enumerateDataScenarios:Jk,error:Fs,figureAnchorFacesOf:DP,figureAnchorRoomOf:zP,figureAssetFor:TP,figureAssetWithCapabilities:RO,figureBindingsResting:IO,figureBindingsTakenOver:DO,figureCapabilitiesAssembled:CO,figureCapabilityDescriptorOf:AO,figureCapabilityDescriptors:SO,figureClassFor:OO,figureLegendRolesOf:GP,figureLegendSourcesChanged:HP,figureLegendTableOf:YP,figureMeshObjectOf:mP,figureMeshUrlOf:fP,figurePlacementSlotLayoutOptions:jP,figureSectionOutline:QA,figureSlotLayoutOfPlacement:CP,fillStyleOpacity:lu,filterByToolType:JE,filterShortcuts:fm,findNearestWithCapability:dE,flattenPolygonPath:pT,flowGraphFor:bE,flowGraphIssues:yE,flowReverseFor:lE,fontStyle:BT,footprint2D:gv,frameClock:_o,ftId:iE,ftrace:sE,getAllCapabilityMeta:hg,getCapabilityMeta:lg,getFigure:BO,getPose:ll,getWorldPose:hl,globalSimClock:bo,gltfNatureProperties:sv,graphFor:PE,gridCellOf:IM,gridPlacements:iO,gridSlotNo:PM,hasArc:zo,hasCapability:og,hasCapacity:rv,hasFigure:GO,inferCapacity:av,inferDownstreamId:qk,inferFlowDirections:nE,initFontFamilyWatcher:ji,inspector:Ud,installContractInspector:vT,isFlowNode:UE,isGenericPlaceholder:Qy,isGeometricHost:hE,isItemTypeTable:Vl,isParted:zu,isRoutingTarget:uE,isSegmentPreset:fC,isStateDriven:Mu,isThreedEnabled:Bu,itemById:dh,itemIdOf:hh,itemLookDimsOf:Pv,itemSeatsOf:_k,itemTypeEntryOf:Yl,itemTypeTableOf:Wl,itemTypesFromThemes:Ul,judgeItemFit:KM,layoutIssue:xM,matchOutbounds:jk,metrics:Ss,mmToDisplay:sh,mmToDrawing:eh,next:kE,nextHop:Hk,nextHops:Nk,nextHopsToAny:Uk,nextHopsToAnyDetailed:Vk,niceGridStep:mf,nodeIdOf:wE,occupancySnapshotOf:mk,onFigureCapabilitiesChanged:kO,onFigureLegendSourcesChanged:NP,onFiguresChanged:FO,opaqueColor:du,paletteVersion:mI,partAtByIndex:Ru,persistenceIssues:TM,pickFigureLegends:WP,pickWeightedDestination:DE,planPathAStar:lT,planToReservations:hT,pointInRotatedRect:Dk,polygonOffsetForPriority:Au,polygonPathLength:fT,projectToScreen:mp,quatFromYaw:WE,rayAbsDistanceToRect:zk,reachableByOutbound:Lk,reachableDestinations:TE,reachableDestinationsFrom:CE,reachableDestinationsWeightedFrom:OE,reachableSinks:Gk,readItemTypes:Gl,receiptToJSON:sp,recommendsLogarithmicDepthForSky:Of,rectFaceAnchors:Ek,rectOutline:QT,rectangularFootprintFrames:XE,registerCapabilityMeta:cg,registerDefaultRealObjectFactory:df,registerFigure:HO,registerFigureCapability:MO,registerFigureLegendResolver:BP,registerFigureType:bO,registerPalette:gI,registerRealObjectFactory:hf,registerTypeResolver:vl,releaseFigureGeometry:sP,renderCanvasTexture:DT,renderPlaceholder:qy,reservationTable:iT,resetFigureClasses:jO,resetFigures:VO,resetPalettes:wI,resolveAnchorWorldPosition:bp,resolveHeightSegments:pC,resolveLegend:Qs,resolveLegendEntries:ti,resolveMaterial3d:Nd,resolveNextHop:AE,resolveSegments:uC,resolveSlot:zM,resolveToken:_I,resolveUnknownTypes:xl,resolveVariant:ou,rotatedFootprint:BM,rulerPixelsPerTick:ah,sceneComponent:ov,sceneHeightsOf:Ou,seatInSlot:GM,seatTransform:UM,setActivePalette:yI,setFigureMeshResolver:pP,setItemLookProvider:Ov,setPose:dl,setThreedEnabled:Gu,setWorldPose:ul,sinksForDestination:vE,slotAddresses:$M,slotCount:CM,slotFrame:FM,slotIdOf:RM,slotNumbers:OM,slotSpaceWarnings:XM,slotsFromBindings:TO,stackSeatTransforms:VM,standardYieldPolicy:nT,stopFPSMeasure:Kp,straightSegmentEndpoints:Ck,straightSegmentMultiInbound:Pk,straightSegmentTopology:Tk,textBounds:YT,textTexture:VT,toThreeSide:Bd,topApproachFrame:KE,transferLog:rp,transferTracer:ep,uniformZ:Ho,unitFigurePartGeometry:kI,unknownTypesOf:_l,unregisterFigure:UO,unresolvedReasonOf:yl,updateDefaultFontFamily:Ri,updateTether:_p,useFigureComponent:yO,validate:IE,validateFlowGraph:Wk,validateSlotLayout:EM,version:OT,warn:Ns});const PI=globalThis;"undefined"==typeof globalThis||PI.scene||(PI.scene=OI),t.AbsoluteLayout=Mc,t.Animation=la,t.AudioPlayer=Ab,t.BULGE_EPSILON=Do,t.Banner3D=AC,t.BoxSelectionManager=Xf,t.COMMON_PLACEHOLDER_PROPERTIES=Yy,t.CORE_PLACEHOLDER_TYPES=Jy,t.Camera3D=CC,t.CameraBookmarkManager=qf,t.CameraManager=If,t.Capacity=kk,t.CapacityEventTracker=cv,t.CardLayout=Ac,t.CenteringQueueStrategy=hv,t.CenteringSlotStrategy=ZE,t.Component=uc,t.Connectable=xm,t.Container=Cy,t.ContainerAbstract=Kl,t.ControlsManager=jf,t.Cube3D=xC,t.Cylinder3D=MC,t.DEFAULT=zi,t.DEFAULT_CEILING=Cu,t.DEFAULT_PALETTE=dI,t.DEFAULT_PLACEMENT=wu,t.DEFAULT_SEAT_MARGIN=NM,t.DPPX=Pi,t.DRAWING_DISPLAY_UNITS=Jl,t.DataLagTracker=bh,t.DataSource=tv,t.DefaultLoadingOverlayRenderer=Zd,t.Donut=Ub,t.DonutExtrude=rC,t.EMPTY_FIGURE_DATA=JP,t.Ellipse=Vy,t.EllipseExtrude=nC,t.EventManager3D=$f,t.EventMap=Qc,t.FIGURE_CAPABILITIES=vO,t.FIGURE_OWN_TABLE=$P,t.FPS=Jp,t.FigureDataReader=nI,t.FigureInputs=oI,t.FigureInstance=hI,t.FigurePart=TI,t.FigurePartRealObject=EI,t.FixedSlotStrategy=xk,t.FlowEngine=zE,t.FlowNode=GE,t.GESTURES=Ii,t.GLTF_BASE_URL_ALIAS=nv,t.GenericObject=Ky,t.GeometryBank=Av,t.GifView=Mb,t.GizmoManager=Nf,t.GizmoOperationManager=Gf,t.GlobalRef=Db,t.GltfComponent=iv,t.GridStacking=pv,t.Group=Tb,t.HOLDER_ANCHOR=wM,t.HTMLAbsoluteLayout=wc,t.HTMLOverlayContainer=Pb,t.HTMLOverlayElement=db,t.Holdable=NE,t.ITEM_TYPES_THEME=Hl,t.ITEM_TYPE_CODE_MAX=64,t.ImageView=hb,t.InfoWindow=vc,t.InstancedSet=sO,t.InteractionManager=Uf,t.Item=zv,t.ItemRealObject=Rv,t.ItemsDataBinding=wv,t.KEYEVENTS=Di,t.Layer=Cp,t.Layout=xc,t.LightManager=zf,t.LightObject=IC,t.Line=Gy,t.Line3D=ZC,t.LinearHorizontalLayout=Ec,t.LinearVerticalLayout=Cc,t.LoadTracker=xh,t.LoadingOverlay=Vd,t.LocalRef=Ob,t.MATERIAL_PRESETS=Fd,t.MAX_SEGMENTS=dC,t.MAX_UNDO_SIZE=30,t.MIN_SEGMENTS=3,t.MODE_ADD=3,t.MODE_EDIT=1,t.MODE_PASTE_DATABIND=5,t.MODE_PASTE_STYLE=4,t.MODE_SHIFT=2,t.MODE_VIEW=0,t.MaterialBank=NT,t.MoveHandle=ql,t.NOTHING=Ci,t.NavGraph=oT,t.Node=Xb,t.OrthoLine=cb,t.OrthoLine3D=eO,t.PIXEL_RATIO=Qp,t.PLACEHOLDER_THEMES=Wy,t.Path=Fb,t.PatternStacking=uv,t.PlacementManager=Vf,t.Polygon=eb,t.PolygonContainer=sb,t.PolygonExtrude=oC,t.PolygonPathPolyline=uT,t.Polyline=rb,t.Polyline3D=tO,t.Popup=jb,t.PopupContainer=Lb,t.Pose6DOF=il,t.RealObject=Du,t.RealObjectCamera=aO,t.RealObjectDomElement=af,t.RealObjectDomTexture=jT,t.RealObjectDummy=oO,t.RealObjectExternalModel=ju,t.RealObjectExtrude=eC,t.RealObjectGLTF=Nu,t.RealObjectGroup=HC,t.RealObjectLine=QC,t.RealObjectMesh=HT,t.RealObjectPlane=cO,t.RealObjectPlane2D=dO,t.RealObjectScene=lO,t.RealObjectService=Kb,t.RealObjectSprite=yC,t.RealObjectSprite2D=bC,t.RealObjectText=qT,t.Rect=Sm,t.RectExtrude=sC,t.RectPath=mc,t.ReferenceMap=wT,t.RendererManager=Df,t.ReservationTable=sT,t.RootContainer=yh,t.Ruler=km,t.SCALE_MIN=cu,t.SCENE_MODE=Oi,t.SEGMENT_DEFAULTS=hC,t.SEGMENT_PRESETS=lC,t.SHORTCUT_SECTIONS=pm,t.Scene=lp,t.SceneManager=Pf,t.ScenePopup=Tp,t.SceneSearchEngine=Vu,t.ScriptLoader=CT,t.SearchOverlay=Yu,t.ServiceComponent=Qb,t.Shape=pc,t.Sphere3D=gC,t.Star=Yb,t.StarExtrude=cC,t.TRANSFER_SLOT_KEY=_v,t.TableLayout=Oc,t.Text=kb,t.ThreeCapability=rm,t.ThreeDOnly=ev,t.Tracker=Xu,t.Transfer=op,t.TransitionEffect=Nl,t.Triangle=Hb,t.TriangleExtrude=aC,t.UNIT_DIMENSION=uu,t.UNIT_ROTATE=mu,t.UNIT_SCALE=pu,t.UNIT_TRANSLATE=fu,t.UNTOKENED_COLOR=xI,t.ValueHolder=Zb,t.VertexGizmoManager=tm,t.VolumeStacking=fv,t.Wall3D=zC,t.Z_PRIORITY=Su,t.acquireFigureGeometry=nP,t.activePalette=vI,t.activePaletteName=bI,t.addressOfSlotId=jM,t.allDestinations=xE,t.anchorsConnect=Ik,t.animate=ca,t.applyAlpha=hu,t.applyMaterial3dProps=Gd,t.applyPolicy=SE,t.applySeatingRotation=vv,t.applyStackLayout=mv,t.applyZPriorityToMaterials=ku,t.arcSegmentTopology=Ok,t.autoWireBackPressure=lv,t.buildArrow3D=of,t.buildContractInspector=bT,t.buildCoordinateGround=yf,t.buildFigureGeometry=iP,t.buildFlowGraph=$k,t.buildNavGraph=cT,t.buildShapeFromPolygonPath=iC,t.buildTether=vp,t.bulgeFromDrag=$o,t.bulgeHandlePosition=jo,t.calibratedMmPerUnit=oh,t.canReach=Bk,t.capability=rg,t.ceilingZPos=XP,t.centerOnBBox=tC,t.chooseNearestPickupFrame=QE,t.clearTether=xp,t.collectAdjacentSegments=Yk,t.compile=da,t.componentForNode=_E,t.computeArcParams=Ro,t.computeFlowMap=cE,t.computeStackPositions=dv,t.cornerHandlePosition=Fo,t.cornerRadiusFromDrag=No,t.create=dp,t.createCanvas=Zp,t.createCanvasTexture=IT,t.createFloor=Tf,t.createRealObjectFor=uf,t.createSelectionHandle3D=$C,t.dataLagTracker=vh,t.debug=Hs,t.deliversInto=Rk,t.delta=ra,t.displayToMm=ih,t.disposeCoordinateGround=xf,t.disposeObject3D=bu,t.disposeTether=wp,t.downstream=EE,t.drawTextTexture=UT,t.drawingScaleFor=rh,t.drawingScaleOf=th,t.drawingToMm=nh,t.effectiveCornerRadius=Lo,t.ellipseOutline=ZT,t.enumerateDataScenarios=Jk,t.error=Fs,t.figureAnchorFacesOf=DP,t.figureAnchorRoomOf=zP,t.figureAssetFor=TP,t.figureAssetWithCapabilities=RO,t.figureBindingsResting=IO,t.figureBindingsTakenOver=DO,t.figureCapabilitiesAssembled=CO,t.figureCapabilityDescriptorOf=AO,t.figureCapabilityDescriptors=SO,t.figureClassFor=OO,t.figureLegendRolesOf=GP,t.figureLegendSourcesChanged=HP,t.figureLegendTableOf=YP,t.figureMeshObjectOf=mP,t.figureMeshUrlOf=fP,t.figurePlacementSlotLayoutOptions=jP,t.figureSectionOutline=QA,t.figureSlotLayoutOfPlacement=CP,t.fillStyleOpacity=lu,t.filterByToolType=JE,t.filterShortcuts=fm,t.findNearestWithCapability=dE,t.flattenPolygonPath=pT,t.flowGraphFor=bE,t.flowGraphIssues=yE,t.flowReverseFor=lE,t.fontStyle=BT,t.footprint2D=gv,t.frameClock=_o,t.ftId=iE,t.ftrace=sE,t.getAllCapabilityMeta=hg,t.getCapabilityMeta=lg,t.getFigure=BO,t.getPose=ll,t.getWorldPose=hl,t.globalSimClock=bo,t.gltfNatureProperties=sv,t.graphFor=PE,t.gridCellOf=IM,t.gridPlacements=iO,t.gridSlotNo=PM,t.hasArc=zo,t.hasCapability=og,t.hasCapacity=rv,t.hasFigure=GO,t.inferCapacity=av,t.inferDownstreamId=qk,t.inferFlowDirections=nE,t.initFontFamilyWatcher=ji,t.inspector=Ud,t.installContractInspector=vT,t.isFlowNode=UE,t.isGenericPlaceholder=Qy,t.isGeometricHost=hE,t.isItemTypeTable=Vl,t.isParted=zu,t.isRoutingTarget=uE,t.isSegmentPreset=fC,t.isStateDriven=Mu,t.isThreedEnabled=Bu,t.itemById=dh,t.itemIdOf=hh,t.itemLookDimsOf=Pv,t.itemSeatsOf=_k,t.itemTypeEntryOf=Yl,t.itemTypeTableOf=Wl,t.itemTypesFromThemes=Ul,t.judgeItemFit=KM,t.layoutIssue=xM,t.matchOutbounds=jk,t.metrics=Ss,t.mmToDisplay=sh,t.mmToDrawing=eh,t.next=kE,t.nextHop=Hk,t.nextHops=Nk,t.nextHopsToAny=Uk,t.nextHopsToAnyDetailed=Vk,t.niceGridStep=mf,t.nodeIdOf=wE,t.occupancySnapshotOf=mk,t.onFigureCapabilitiesChanged=kO,t.onFigureLegendSourcesChanged=NP,t.onFiguresChanged=FO,t.opaqueColor=du,t.paletteVersion=mI,t.partAtByIndex=Ru,t.persistenceIssues=TM,t.pickFigureLegends=WP,t.pickWeightedDestination=DE,t.planPathAStar=lT,t.planToReservations=hT,t.pointInRotatedRect=Dk,t.polygonOffsetForPriority=Au,t.polygonPathLength=fT,t.projectToScreen=mp,t.quatFromYaw=WE,t.rayAbsDistanceToRect=zk,t.reachableByOutbound=Lk,t.reachableDestinations=TE,t.reachableDestinationsFrom=CE,t.reachableDestinationsWeightedFrom=OE,t.reachableSinks=Gk,t.readItemTypes=Gl,t.receiptToJSON=sp,t.recommendsLogarithmicDepthForSky=Of,t.rectFaceAnchors=Ek,t.rectOutline=QT,t.rectangularFootprintFrames=XE,t.registerCapabilityMeta=cg,t.registerDefaultRealObjectFactory=df,t.registerFigure=HO,t.registerFigureCapability=MO,t.registerFigureLegendResolver=BP,t.registerFigureType=bO,t.registerPalette=gI,t.registerRealObjectFactory=hf,t.registerTypeResolver=vl,t.releaseFigureGeometry=sP,t.renderCanvasTexture=DT,t.renderPlaceholder=qy,t.reservationTable=iT,t.resetFigureClasses=jO,t.resetFigures=VO,t.resetPalettes=wI,t.resolveAnchorWorldPosition=bp,t.resolveHeightSegments=pC,t.resolveLegend=Qs,t.resolveLegendEntries=ti,t.resolveMaterial3d=Nd,t.resolveNextHop=AE,t.resolveSegments=uC,t.resolveSlot=zM,t.resolveToken=_I,t.resolveUnknownTypes=xl,t.resolveVariant=ou,t.rotatedFootprint=BM,t.rulerPixelsPerTick=ah,t.sceneComponent=ov,t.sceneHeightsOf=Ou,t.seatInSlot=GM,t.seatTransform=UM,t.setActivePalette=yI,t.setFigureMeshResolver=pP,t.setItemLookProvider=Ov,t.setPose=dl,t.setThreedEnabled=Gu,t.setWorldPose=ul,t.sinksForDestination=vE,t.slotAddresses=$M,t.slotCount=CM,t.slotFrame=FM,t.slotIdOf=RM,t.slotNumbers=OM,t.slotSpaceWarnings=XM,t.slotsFromBindings=TO,t.stackSeatTransforms=VM,t.standardYieldPolicy=nT,t.stopFPSMeasure=Kp,t.straightSegmentEndpoints=Ck,t.straightSegmentMultiInbound=Pk,t.straightSegmentTopology=Tk,t.textBounds=YT,t.textTexture=VT,t.toThreeSide=Bd,t.topApproachFrame=KE,t.transferLog=rp,t.transferTracer=ep,t.uniformZ=Ho,t.unitFigurePartGeometry=kI,t.unknownTypesOf=_l,t.unregisterFigure=UO,t.unresolvedReasonOf=yl,t.updateDefaultFontFamily=Ri,t.updateTether=_p,t.useFigureComponent=yO,t.validate=IE,t.validateFlowGraph=Wk,t.validateSlotLayout=EM,t.version=OT,t.warn=Ns});
|
|
73
73
|
//# sourceMappingURL=things-scene-min.js.map
|