@hatiolab/things-scene 10.1.80 → 10.1.81

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/things-scene.mjs CHANGED
@@ -47,5 +47,5 @@ import*as t from"three";import{Color as e,LinearSRGBColorSpace as n,SRGBColorSpa
47
47
  </button>`:D}
48
48
  ${n?z`<button class="closable" @click=${this.closeContainer}>close</button>`:D}
49
49
  </div>
50
- `,this.element)}catch(t){}}onchangeMinimized(){const{minimized:t}=this.state;t?this.setState("height",24):this.setState("height",this.get("height"))}}rg=new WeakMap,Cc.memoize(lg.prototype,"bounds",!0),Cc.register("container",lg);const hg=Math.sqrt(3),dg=2;function ug(t,e,n,i,s){const r=5+s,o=n.x,a=n.y,c=i.x,l=i.y;if(Math.abs(o-c)>r&&Math.abs(a-l)>r){const n=(l-a)/(c-o),i=a-n*o;if(Math.abs(e-(n*t+i))>r)return!1}let h,d,u,p;return o>c?(d=o,h=c):(d=c,h=o),a>l?(p=a,u=l):(p=l,u=a),!(d+5<t)&&(!(h-5>t)&&(!(p+5<e)&&!(u-5>e)))}function pg(t,e,n,i=2){for(let s=0;s<n.length-1;s++)if(ug(t,e,n[s],n[s+1],i))return!0;return!1}function fg(t,e,n,i){if("arrow"!=t.slice(-5))return n;const s=Math.atan2(i.y-n.y,i.x-n.x),r=1.5*e;return{x:n.x+Math.cos(s)*r,y:n.y+Math.sin(s)*r}}function mg(t,e,n){let{lineWidth:i=dg,strokeStyle:s="#000000",lineCap:r=!1,alpha:o=1,begin:a="none",end:c="none",beginSize:l="size5",endSize:h="size5"}=n;if(("none"!=a||"none"!=c)&&(i=Number(i)||dg,t.lineCap=r,t.lineWidth=i,t.strokeStyle=s,t.fillStyle=s,t.globalAlpha*=o,"none"!=a&&gg(t,e[0],e[1],i,a,yg(l,i)),"none"!=c)){const n=e.length;gg(t,e[n-1],e[n-2],i,c,yg(h,i))}}function gg(t,e,n,i,s,r){const{x:o,y:a}=e,c=Math.atan2(n.y-a,n.x-o);switch(t.beginPath(),t.translate(o,a),t.rotate(c),s){case"oval":t.ellipse(0,0,r.X,r.Y,0,0,2*Math.PI),t.fill();break;case"diamond":t.moveTo(-r.X,0),t.lineTo(0,-r.Y),t.lineTo(r.X,0),t.lineTo(0,r.Y),t.fill();break;case"arrow":t.moveTo(0,0),t.lineTo(hg*r.X,-r.Y),t.lineTo(hg*r.X,r.Y),t.fill();break;case"sharp-arrow":t.moveTo(0,0),t.lineTo(hg*r.X,-r.Y),t.lineTo(-r.X/1.5+hg*r.X,0),t.lineTo(hg*r.X,r.Y),t.fill();break;case"open-arrow":t.moveTo(hg*r.X+i,-r.Y),t.lineTo(i,0),t.lineTo(hg*r.X+i,r.Y),t.stroke();break;case"cross":t.moveTo(-r.X,-r.Y),t.lineTo(r.X,r.Y),t.moveTo(r.X,-r.Y),t.lineTo(-r.X,r.Y),t.stroke()}t.rotate(-c),t.translate(-o,-a),t.closePath()}function yg(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 bg="N",vg="S",_g="E",xg="W";class wg{constructor({component:t,anchor:e,position:n,self:i}){this.component=t,this._anchorName=e,this._position=n,this.self=i}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 _g;const n=e.position;return n.y<=t.top?bg:n.y>=t.top+t.height?vg:n.x<=t.left?xg:_g}get boundaryPosition(){const t=this.anchor;if(t){let{position:e}=t,n=0,i=0;switch(this.direction){case vg:i=20;break;case bg:i=-20;break;case xg:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+i};const s=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(s.x,s.y)}}}class Mg extends Cc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const i=t.get(n.component)||n.component;this.set(e,{...n,component:i})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const i=this.root?.findByRefid?.(t);if(!i)return;this._fromEnd=new wg({component:i,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 i=this.root?.findByRefid?.(t);if(!i)return;this._toEnd=new wg({component:i,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:i,round:s=0}=this.state;let r=this.drawPath;mg(t,r,this.state),t.beginPath();const o=fg(e,i,r[0],r[1]),a=fg(n,i,r[r.length-1],r[r.length-2]),c=r[0];r=[o,...r.slice(1,-1),a];let l={x:o.x,y:o.y};if(t.moveTo(o.x,o.y),r.length>=2&&Xr(c)){const e=r[1],n=Zr(e,s),i=Math.sqrt((o.x-e.x)**2+(o.y-e.y)**2),a=0!==i?Math.atan2(o.x-e.x,o.y-e.y):0,l=Math.sin(a)*Math.min(n,i/2)+e.x,h=Math.cos(a)*Math.min(n,i/2)+e.y,d=Kr({x:o.x,y:o.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<r.length;e++){const n=l;l=r[e];const i=r[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!i){t.lineTo(l.x,l.y);break}const o=Zr(l,s);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(o,a/2)+l.x,d=Math.cos(c)*Math.min(o,a/2)+l.y;const u=o>0||0!==a?{x:h,y:d}:l;a=Math.sqrt((i.x-l.x)*(i.x-l.x)+(i.y-l.y)*(i.y-l.y)),c=0!==a?Math.atan2(i.x-l.x,i.y-l.y):0,h=Math.sin(c)*Math.min(o,a/2)+l.x,d=Math.cos(c)*Math.min(o,a/2)+l.y;const p=o>0||0!==a?{x:h,y:d}:l;if(t.lineTo(u.x,u.y),o>0&&t.quadraticCurveTo(l.x,l.y,p.x,p.y),Xr(l)){const e=Zr(i,s),n=Math.sqrt((l.x-i.x)**2+(l.y-i.y)**2),r=0!==n?Math.atan2(l.x-i.x,l.y-i.y):0,o=Math.sin(r)*Math.min(e,n/2)+i.x,a=Math.cos(r)*Math.min(e,n/2)+i.y,c=Kr({x:p.x,y:p.y},{x:o,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 pg(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:i,x2:s,y2:r}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:i},this.toEnd?.position||e?.position||{x:s,y:r}]}set path(t){const[e,n]=t,{from:i,to:s}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...i,position:e},to:{...s,position:n}})}get textBounds(){const t=this.drawPath;let e,n,i=0;for(let s=1;s<t.length;s++){const r=t[s-1],o=t[s],a=(r.x-o.x)*(r.x-o.x)+(r.y-o.y)*(r.y-o.y);a>i&&(i=Math.ceil(a),e=r,n=o)}let{paddingTop:s,paddingLeft:r,paddingRight:o,paddingBottom:a}=this.state;return a||=0,s||=0,r||=0,o||=0,{left:Math.min(e.x,n.x)+r,top:Math.min(e.y,n.y)+s,width:Math.max(Math.abs(e.x-n.x)-r-o,0),height:Math.max(Math.abs(e.y-n.y)-s-a,0)}}get decorators(){return this.app.isEditMode?["decotag"]:[]}}Mg.getTipNeckPos=fg,Mg.containedInPath=pg,Mg.drawEndTips=mg,Cc.register("line",Mg);const Sg={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 Ag extends(lm(Tc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:i,ry:s,startAngle:r,endAngle:o,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(i),Math.abs(s),0,r||0,o||2*Math.PI,a),void 0!==r&&void 0!==o&&(t.lineTo(e,n),t.closePath())}get path(){const{cx:t,cy:e,rx:n,ry:i}=this.state;return[{x:t-n,y:e-i},{x:t+n,y:e-i},{x:t+n,y:e+i},{x:t-n,y:e+i}]}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:i,rx:s,ry:r}=this.state,o=(t-n)/(2*s-.5),a=(e-i)/(2*r-.5);return o*o+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:i,rx:s,ry:r}=t.model,o=2*Math.PI*e,a=n+s*Math.cos(o),c=i+r*Math.sin(o);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:i,height:s}=t.bounds,r=e+i/2,o=n+s/2;return[{name:"TOP",position:{x:r,y:n}},{name:"RIGHT",position:{x:e+i,y:o}},{name:"BOTTOM",position:{x:r,y:n+s}},{name:"LEFT",position:{x:e,y:o}}]}(this)}get nature(){return Sg}}Cc.memoize(Ag.prototype,"path",!1),Cc.register("ellipse",Ag);const Eg={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"}},kg=[{type:"string",label:"placeholder-label",name:"placeholderLabel",description:'사용자에게 표시할 추가 라벨 (예: "Stocker A1")'},{type:"string",label:"hint",name:"placeholderHint",description:"구체화 시 참고 — 도면의 원본 식별자 / VLM 라벨 등"}];function Cg(t,e,n,i,s){const{left:r,top:o,width:a,height:c}=e,l=Math.max(a,1),h=Math.max(c,1);t.save(),t.fillStyle=n.fill,t.fillRect(r,o,l,h),t.strokeStyle=n.stroke,t.lineWidth=1.5,t.setLineDash([4,3]),t.strokeRect(r,o,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,r+l/2,o+h/2),t.restore());const d=i?`${n.label}: ${i}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,r+l/2,o+h-4),t.restore()),s&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${s}`,r+l-4,o+4),t.restore())}const Tg={mutable:!1,resizable:!0,rotatable:!0,properties:[...kg,{type:"placeholder-convert",label:"",name:"_convert"}],help:"scene/component/placeholder"};class Og extends(Pc(Tc)){get nature(){return Tg}render(t){const{placeholderLabel:e,placeholderHint:n}=this.state;Cg(t,this.bounds,Eg.object,e,n)}}Cc.register("placeholder",Og);const Pg=["placeholder"];function Ig(t,e=[]){return!!t&&(!!Pg.includes(t)||e.includes(t))}const Dg={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 i=n[e+1];n[e+1]={...i||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},zg={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 Rg extends Tc{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 i=!1;return n.forEach((s,r)=>{const o=(r+n.length+1)%n.length,a=s.x,c=s.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(i=!i)}),i}get controls(){const t=this.path;return t.map((e,n)=>{const i=t[n+1>=t.length?0:n+1];return{x:(e.x+i.x)/2,y:(e.y+i.y)/2,handler:Dg}})}get nature(){return zg}}Cc.memoize(Rg.prototype,"controls",!1),Cc.register("polygon",Rg);const jg=[];class Lg extends(ih(Rg)){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 Lc.get(this.get("layout"))||Nc}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:i=!1}="boolean"==typeof e?{ghost:e}:e,s=t.parent;if(s){if(this===s)return;s.removeComponent(t,n||i)}const r=this._components.push(t)-1;i&&(t._silentAdd=!0),t.parent=this,t.added(this),n||i||this.trigger("add",this,t,r),t.delegate_on(this),i?(s&&this.root?._removeTraverse?.(t),this.trigger("add",this,t,r),t.trigger("added",this,t,r),delete t._silentAdd):n||t.trigger("added",this,t,r),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 i=t.parent;i&&i.removeComponent(t,n);const s=this._components.splice(0,e);this._components=s.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||jg).indexOf(t)}size(){return(this._components||jg).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let i=this._components.splice(0,n);const s=this._components.splice(1);this._components=i.concat(s),t=Math.max(0,t),t=Math.min(t,this._components.length),i=this._components.splice(0,t),this._components=i.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),i=this._components.splice(1);this._components=n.concat(i,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),i=this._components.splice(1);this._components=this._components.concat(n,i)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return ec(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let i=this.components.length-1;i>=0;i--){const s=this.components[i].findAll(t,...e);s&&(n=n.concat(s))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return ec(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const i=this.components[n].findFirst(t,...e);if(null!=i)return i}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 i=this.fromParent(t,e);if(!this.contains(i.x,i.y))return!1;const s=this.bounds;i.x-=s.left,i.y-=s.top;const r=this.layout.capturables(this);for(let s=r.length-1;s>=0;s--){const o=r[s];let a;if(a="static"==o.position?o.capture(i.x,i.y,n):o.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:i,top:s,width:r,height:o}=this.bounds;for(let e=0;e<t.length;e++){const a=this.fromParent(t[e].x,t[e].y);if(a.x<i||a.x>i+r||a.y<s||a.y>s+o)return!1;a.x-=i,a.y-=s,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const i=a[t];if(!i.isContainer())continue;const s=i.capturePath(n,e);if(s)return s}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:i=0,width:s,height:r}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,i,s,r),t.clip(),t.closePath()),t.translate(n,i),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,-i),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>Cc.memoize(Lg.prototype,t,!1));const Fg={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 i=n[e];n[e]={...i||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},Ng={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 $g extends Mg{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 i=t[n],s=t[n+1];0==n&&e.push({x:i.x,y:i.y,handler:Fg}),e.push({x:(i.x+s.x)/2,y:(i.y+s.y)/2,handler:Fg}),n==t.length-2&&e.push({x:s.x,y:s.y,handler:Fg})}return e}get nature(){return Ng}}Cc.register("polyline",$g);const Hg={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 Bg extends Mg{get pathExtendable(){return!1}get drawPath(){const t=this.path[0],e=this.path[1],{component:n,direction:i,boundaryPosition:s=t}=this.fromEnd||{},{component:r,direction:o,boundaryPosition:a=e}=this.toEnd||{},c=[s,a],l=[];s&&l.push(s);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:s.x,top:s.y,width:0,height:0};d=d||u;let p=r?.bounds;p&&(h=r.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,E,k,C,T=0,O=0;d.left+d.width<p.left?(w=0,M=1,k=i,C=o,v=(d.left+d.width+p.left)/2,T=p.left-v):p.left+p.width<d.left&&(w=1,M=0,k=o,C=i,v=(d.left+p.width+p.left)/2,T=d.left-v),d.top+d.height<p.top?(x=0,S=1,A=i,E=o,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,A=o,E=i,_=(d.top+p.height+p.top)/2,O=d.top-_);const P=[];if(v&&T>O){let t,e,n;switch(C){case xg:switch(k){case _g:P.push({x:v,y:c[w].y}),P.push({x:v,y:c[M].y});break;case xg: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 bg:case vg:e=k===vg?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 _g:switch(k){case _g: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 xg:e=void 0!==_?_:c[w].y<c[M].y?b.top-.5*T:b.top+b.height+.5*T,n=e;break;case vg:e=void 0!==_?Math.max(_,c[w].y):b.top+b.height,n=e;break;case bg: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 vg:switch(k){case _g:e=c[w].y,n=c[w].y>c[M].y?c[w].y:m[M].top+m[M].height;break;case xg:e=_?Math.max(_,m[M].top+m[M].height):b.top+b.height,n=e;break;case vg:e=b.top+b.height,n=e;break;case bg: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 bg:switch(k){case _g:e=c[w].y,n=c[w].y<c[M].y?c[w].y:m[M].top;break;case xg:e=_?Math.min(_,m[M].top):b.top,n=e;break;case vg:e=void 0!==_?Math.max(_,c[w].y):c[w].y,n=void 0!==_?Math.min(_,c[M].y):c[M].y;break;case bg: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(E){case bg:switch(A){case vg:P.push({x:c[x].x,y:_}),P.push({x:c[S].x,y:_});break;case bg: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 xg: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 _g: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 vg:switch(A){case xg:e=b.left,n=e;break;case _g:e=void 0!==v?Math.max(v,c[x].x):b.left+b.width,n=e;break;case bg: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 vg: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 _g:switch(A){case xg: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 _g:e=b.left+b.width,n=e;break;case bg:e=void 0!==v?Math.max(v,c[S].x):b.left+b.width,n=e;break;case vg: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 xg:switch(A){case xg:e=b.left,n=e;break;case _g: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 bg:e=b.left,n=e;break;case vg: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(i){case bg:switch(o){case bg:e=b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case vg: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 _g: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 xg: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 vg:switch(o){case bg: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 vg:case _g:case xg: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 xg:switch(o){case bg: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 vg: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 _g: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 xg: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 _g:switch(o){case bg: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 vg: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 _g:case xg: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 i=n[e-1];return t.x!==i.x||t.y!==i.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const i=n[e-1],s=n[e+1];return!(t.x===i.x&&t.x===s.x||t.y===i.y&&t.y===s.y)})}get nature(){return Hg}}Cc.register("ortholine",Bg);const Yg={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 Gg extends(Pc(Tc)){static get noimage(){return Gg.NOIMAGE||(Gg.NOIMAGE=new Image,Gg.NOIMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABIBAMAAAD7Se1QAAAAIVBMVEUAAABHcEwBAQEREREBAQEEBAQGBgYLCwsDAwMDAwMICAi6HF9tAAAAC3RSTlNNAEAERiMYCS41Eac10lYAAAEgSURBVHhe7dY9asQwEAXgh7DNertNiJy48pIitY3SB7bYdk0ukL1BDDmA9gZecoH4pmFQ3MQayUMguPBrNPD4wD9TCMvJmt3M/AtYwXOlXiWgqADVCUBD46MAnGhMBaCiUQmAm8VA/Eh/eWl9Fn5WcxD+OLuRrUYJDKLluwH2InACUgkoACSdADxQc50Bytadb9RkM0CT13TcvlCT1HFg8UTHvasuUVACCa3El6u2UdD8LFTlKhUFFgA+d3dj10aABkUN72N3jAADCrJq7PIIsPidcxBoTHIIAjMFmyCwmGYIAA1P9gFgfCANAOsDSccCDW+uLDB+kLGg94OkZoAGkwsDDAe2DOg5oPxAg03rBR88OHpBz4N8UVeHFSwma74BTW6Ge4rIRa4AAAAASUVORK5CYII="),Gg.NOIMAGE}dispose(){super.dispose(),this._offcanvas=null,this._image=null}render(t){const{left:e,top:n,width:i,height:s,isGray:r=!1,alpha:o=1,src:a}=this.state;if(this.prepareIf(!this._image&&a),t.beginPath(),t.globalAlpha*=o,this._image&&this._image.complete)if(r&&this._offcanvas)t.drawImage(this._offcanvas,e,n,i,s);else try{t.drawImage(this._image,e,n,i,s)}catch(r){t.drawImage(Gg.noimage,e,n,i,s)}else!this.app.isViewMode&&t.drawImage(Gg.noimage,e,n,i,s)}get nature(){return Yg}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:i}=this.state;if(n){this._image=new Image;try{i&&(this._image.crossOrigin=i),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=Cc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const i=function(t,e,n){let i;try{i=t.getImageData(0,0,e,n)}catch(t){return Qi("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const s=i.data;for(let t=0;t<e*n*4;t+=4){const e=s[t],n=s[t+1],r=s[t+2],o=Math.floor((e+n+r)/3);i.data[t]=o,i.data[t+1]=o,i.data[t+2]=o}return i}(n,t,e);n.putImageData(i,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])}}Cc.register("image-view",Gg);class Vg extends(sg(Pc(Cc))){is3dish(){return!0}prerender(){}}var Ug,Wg,qg={},Xg={},Kg={};function Qg(){if(Wg)return Xg;Wg=1,Object.defineProperty(Xg,"__esModule",{value:!0});var t=function(){if(Ug)return Kg;Ug=1,Object.defineProperty(Kg,"__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,i,s=0,r=function(t){for(var n=0,i=0;i<t;i++)e.charCodeAt(s>>3)&1<<(7&s)&&(n|=1<<i),s++;return n},o=[],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(i=n,(n=r(l))!==a){if(n===c)break;if(n<h.length)i!==a&&h.push(h[i].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[i].concat(h[i][0]))}o.push.apply(o,h[n]),h.length===1<<l&&l<12&&l++}else d();return o},t}();return Kg.SuperGifUtils=t,Kg}(),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 i=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=i.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(i.splice(0,3)),e.userInput=i.shift(),e.transparencyGiven=i.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 i=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,i),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),i=t.length/e,s=function(i,s){var r=t.slice(s*e,(s+1)*e);n.splice.apply(n,[i*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2],a=0,c=0;c<4;c++)for(var l=r[c];l<i;l+=o[c])s(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 Xg.SuperGifParser=e,Xg}var Jg,Zg,ty={};var ey=function(){if(Zg)return qg;Zg=1,Object.defineProperty(qg,"__esModule",{value:!0});var t=Qg(),e=function(){if(Jg)return ty;Jg=1,Object.defineProperty(ty,"__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 ty.SuperGifStream=t,ty}(),n=function(){function n(t,e){var n=this;for(var i 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[i]=e[i];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,i=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 s=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(s.data[4*n+0]=i[t][0],s.data[4*n+1]=i[t][1],s.data[4*n+2]=i[t][2],s.data[4*n+3]=255)}),this.frame.putImageData(s,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 i=this;if(this.loadSetup(n)){var s=new XMLHttpRequest;s.open("GET",t,!0),"overrideMimeType"in s?s.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in s?s.responseType="arraybuffer":s.setRequestHeader("Accept-Charset","x-user-defined"),s.onloadstart=function(){i.initialized||i.init()},s.onload=function(){if(200===s.status){var t=s.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){i.parseStream(n)},0)}else i.handleError("xhr - response")},s.onerror=function(){i.handleError("xhr")},s.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return qg.SuperGif=n,qg}();const ny={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 iy extends Vg{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 ey.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 ny}get tagName(){return"div"}}Cc.register("gif-view",iy);const sy={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 ry extends(Pc(Tc)){static get image(){return ry.IMAGE||(ry.IMAGE=new Image,ry.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="),ry.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:i,height:s}=this.state;t.beginPath(),this.drawImage(t,ry.image,e,n,i,s)}get nature(){return sy}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 Qi(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])}}Cc.register("audio",ry);class oy extends(Pc(Cc)){is3dish(){return!0}}Cc.register("text",oy);const ay=["refid","left","top","width","height","rotation","animation","zPos"];class cy extends lg{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=ay.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{});return super.set(n,void 0)}capture(t,e,n){const i=super.capture(t,e,n);if(i!==this)return i}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,i=t.height/e.height;this.path=this.path.map(s=>({x:t.left+(s.x-e.left)*n,y:t.top+(s.y-e.top)*i})),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*i}})});else{const e=t.bounds,s=t.center,r={x:s.x*(1-n),y:s.y*(1-i)},o=e.width*(1-n),a=e.height*(1-i),c=-(r.x-o/2),l=-(r.y-a/2);t.bounds={left:e.left+c,top:e.top+l,width:e.width*n,height:e.height*i}}})}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=Cc.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)}}Cc.memoize(cy.prototype,"bounds",!0),Cc.register("group",cy);const ly={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 hy extends(Pc(Tc)){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,i=n.width/e.width,s=n.height/e.height;return"both"===this.model.fit?{x:i,y:s}:{x:Math.min(i,s),y:Math.min(i,s)}}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,i=this.refScale;t.translate(n.x,n.y),t.scale(i.x,i.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:i,height:s}=this.bounds;t.beginPath(),t.rect(e,n,i,s)}get nature(){return ly}get hasTextProperty(){return!1}}Cc.memoize(hy.prototype,"ref",!1),Cc.memoize(hy.prototype,"refScale",!1),Cc.register("local-ref",hy);class dy extends(sg(rh)){render(t){}is3dish(){return!0}get layout(){return Lc.get(this.get("layout"))||Fc}}const uy={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 py extends dy{dispose(){this._releaseRef(),super.dispose()}get nature(){return uy}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 i=(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,i);try{await i}catch(t){Qi(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})}}Cc.register("global-ref",py);const fy="center-middle",my={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",fy,"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 gy extends(Pc(Tc)){static get image(){return gy._image||(gy._image=new Image,gy._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"),gy._image}async ready(){await super.ready(),this.show&&this.onchangeShow(!0)}render(t){const{left:e,top:n,width:i,height:s}=this.bounds;t.beginPath(),this.drawImage(t,gy.image,e,n,i,s)}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"),i=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;yp.show(this,this.getState("board"),{origin:this.getState("origin")||fy,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:i,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(){yp.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 my}}Cc.register("popup",gy);const yy={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 by extends lg{get nature(){return yy}isPopupContainer(){return!0}}Cc.register("popup-container",by);class vy extends Cc{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 i=!1;return n.forEach((s,r)=>{const o=(r+n.length+1)%n.length,a=s.x,c=s.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(i=!i)}),i}}Cc.register("path",vy);const _y={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 xy extends Tc{is3dish(){return!0}contains(t,e){const{x1:n,y1:i,x2:s,y2:r,x3:o,y3:a}=this.state,c=[n,i,s,r,o,a];let l=!1;for(let n=0;n<c.length;n+=2){const i=(n+2)%c.length,s=c[n],r=c[n+1],o=c[i+1];r>e!=o>e&&t<(c[i]-s)*(e-r)/(o-r)+s&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:i,x3:s,y3:r}=this.state;return[{x:t,y:e},{x:n,y:i},{x:s,y:r}]}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 _y}}Cc.memoize(xy.prototype,"path",!1),Cc.register("triangle",xy);const wy={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"}],help:"scene/component/donut"},My={ondragmove:function(t,e,n){let{cx:i,rx:s}=n.model;s=Math.abs(s);let r=(n.fromParent(t.x,t.y).x-i)/s*100;r=r>=100||r<=-100?100:Math.abs(r),n.set({ratio:r})}};class Sy extends Ag{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:i,rx:s,ry:r,startAngle:o,endAngle:a,anticlockwise:c}=this.state;s=Math.abs(s),r=Math.abs(r),t.beginPath(),t.ellipse(n,i,s,r,0,o||0,a||2*Math.PI,c),t.moveTo(n+s/100*e,i),t.ellipse(n,i,s/100*e,r/100*e,0,o||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:i,rx:s,ry:r,ratio:o}=this.state;s=Math.abs(s),r=Math.abs(r);const a=(t-n)/(2*s-.5),c=(e-i)/(2*r-.5),l=(t-n)/(s/100*o*2-.5),h=(e-i)/(r/100*o*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:i}=this.state;return n=Math.abs(n),[{x:t+n/100*i,y:e,handler:My}]}get nature(){return wy}}Cc.memoize(Sy.prototype,"controls",!1),Cc.register("donut",Sy);const Ay={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"},Ey={ondragmove:function(t,e,n){const{cy:i,ry:s}=n.model;let r=(n.fromParent(t.x,t.y).y-i)/s*100+100;r>=100?r=100:r<=0&&(r=0),n.set({ratio:r})}};class ky extends Ag{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:i,cy:s,rx:r,ry:o}=this.state;if(n<3)return;const a=1.5707963267948966,c=2*Math.PI/n,l=r-e/100*r,h=o-e/100*o;t.save(),t.beginPath(),t.translate(i,s),t.moveTo(r*Math.cos(-a),o*Math.sin(-a)),t.lineTo((r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let e=1;e<n;e++)t.lineTo(r*Math.cos(c*e-a),o*Math.sin(c*e-a)),t.lineTo((r-l)*(Math.cos(c*(e+1)-a)+Math.cos(c*e-a))/2,(o-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:i}=this.state;return[{x:t,y:e-n+n*(i/100),handler:Ey}]}get nature(){return Ay}}Cc.memoize(ky.prototype,"controls",!1),Cc.register("star",ky);const Cy={mutable:!1,resizable:!1,rotatable:!1,properties:[]};class Ty extends(lm(Tc)){is3dish(){return!1}isDescendible(){return!1}render(t){const{cx:e,cy:n,anticlockwise:i}=this.state,s=this.app?.scale||1;t.beginPath(),t.scale(1/s,1/s),t.ellipse(e,n,Math.abs(Ty.RADIUS),Math.abs(Ty.RADIUS),0,0,2*Math.PI,i),t.scale(s,s),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-Ty.RADIUS,y:e-Ty.RADIUS},{x:t+Ty.RADIUS,y:e-Ty.RADIUS},{x:t+Ty.RADIUS,y:e+Ty.RADIUS},{x:t-Ty.RADIUS,y:e+Ty.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:i}=this.state,s=(t-n)/(2*Ty.RADIUS-.5),r=(e-i)/(2*Ty.RADIUS-.5);return s*s+r*r<.25}outline(t){const{cx:e,cy:n}=this.state;return this.toScene(e,n)}get nature(){return Cy}}Ty.RADIUS=5,Cc.memoize(Ty.prototype,"path",!1),Cc.register("node",Ty);class Oy extends Mu{getObject3dInstance(){return new t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds,i=this.component.state.depth||.5*Math.min(e,n),s=.15*Math.min(e,n,i),r=new R(1,1,1,4,s/Math.min(e,n,i));r.scale(e,i,n),this.object3d.geometry=r,this.object3d.material=new t.MeshStandardMaterial({color:"#5090d0",transparent:!0,opacity:.35,roughness:.6,metalness:.1,side:t.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 i=this.object3d.geometry.boundingBox;if(i){const s=i.max.x-i.min.x,r=i.max.y-i.min.y,o=i.max.z-i.min.z;this.setDimensionScale(t/s,n/r,e/o)}}updateFillStyle(){}updateStrokeStyle(){}updateText(){}clear(){return hu(this.object3d),super.clear()}}const Py="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 Iy extends(Pc(Cc)){static get icon(){return Iy._defaultIcon||(Iy._defaultIcon=new Image,Iy._defaultIcon.src=Py),Iy._defaultIcon}get serviceName(){}get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Oy(this)}render(t){if(this.app?.isViewMode)return;const{left:e,top:n,width:i,height:s}=this.bounds,r=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,r,e,n,i,s),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 Dy(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 i;i=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-i,this.animate({step:t=>{this._anim_alpha=i*(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=Vr(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(xi(t)))}}}function zy(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 Ry(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 jy="$base_url",Ly=[{type:"gltf-preset",label:"preset",name:"preset"},{type:"gltf-selector",label:"url",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:jy,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 i=this.parentNode?.querySelector("[name=playTargets]");i&&(i.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 Fy(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:i,height:s}=this.bounds;t.beginPath();const r=this._topViewSnapshot;if(r)return void t.drawImage(r,e,n,i,s);this._ensureTopViewSnapshot(),t.rect(e,n,i,s),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const o=this.getState("src"),a=o&&o.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(i,s));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+i/2,n+s/2,.9*i)}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=Ou.getTopViewCache(t);if(e)return this._topViewSnapshot=e,void this.invalidate();this._snapshotLoading=!0;const n=this.app.url(t);Ou.loadGLTF(n).then(e=>{if(this._snapshotLoading=!1,this.getState("src")!==t)return;const n=Ou.getTopViewCache(t);if(n)return this._topViewSnapshot=n,void this.invalidate();const i=Ou.renderTopView(e.scene);Ou.setTopViewCache(t,i),this._topViewSnapshot=i,this.invalidate()}).catch(()=>{this._snapshotLoading=!1})}buildRealObject(){return new Ou(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:i=1}=t;this.setState({width:e,height:n,depth:i}),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,i=this.state.depth||1,s=Of([(t.width??e)/e,(t.height??n)/n,(t.depth??i)/i]);return s?{...t,width:Math.round(e*s),height:Math.round(n*s),depth:Math.round(i*s)}: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 Ny(t){return function(e){return Array.isArray(t)?t.forEach(t=>{Cc.register(t,e)}):Cc.register(t,e),e}}function $y(t){return!!t&&"function"==typeof t.capacity&&"function"==typeof t.available}function Hy(t){if($y(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 By{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 Yy(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()),i=e.onAvailable(()=>t.resumeEmit());return Hy(e).isFull&&t.pauseEmit(),()=>{n?.(),i?.()}}class Gy{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,i){const s=e.maxCount??1/0;if(t<0||t>=s)return null;const r=this.owner?.state?.width??0,o=this.owner?.state?.height??0,a=i?.state?.width??0,c=i?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(o-c)/2),z:0}:{x:Math.max(0,(r-a)/2),y:t*this.itemSpacing,z:0}}capacity(t){return t.maxCount??1/0}}function Vy(t,e,n,i,s,r,o){const a=n.w,c=n.h,l=i.w,h=i.h,d=i.d,u=[],p=l+s,f=h+s,m=Math.max(1,Math.floor((a+s)/p)),g=Math.max(1,Math.floor((c+s)/f)),y=m*g,b=r&&r>0?Math.floor(r):4;if("row"===t||"column"===t){const n=o?.advanceAlongX??!1,i=o?.reverse??!1,s=n?m:g,r=n?g:m,l=(t,e,i)=>((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,i);let h=0;for(let n=0;n<s&&h<e;n++){const o=i?s-1-n:n;if("column"===t)for(let t=0;t<r&&h<e;t++)for(let n=0;n<b&&h<e;n++)l(o,t,n),h++;else for(let t=0;t<b&&h<e;t++)for(let n=0;n<r&&h<e;n++)l(o,n,t),h++}return u}if("pyramid"===t){let t=e,n=0;for(;t>0;){const e=Math.max(1,m-n),i=Math.max(1,g-n),s=e*i,o=Math.min(t,s);for(let t=0;t<o;t++){const s=t%e,r=Math.floor(t/e),o=-a/2+(s+(m-e)/2+.5)*p,l=-c/2+(r+(g-i)/2+.5)*f;u.push({x:o,y:n*d+d/2,z:l})}if(t-=o,n++,1===e&&1===i){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(r&&n>=r)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),i=n%y,s=i%m,o=Math.floor(i/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(s+.5)*p+g,_=-c/2+(o+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),r&&e>=r-1&&i===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(r&&e>=r)break;const i=n%y,s=i%m,o=Math.floor(i/m);let l=-a/2+(s+.5)*p;const h=-c/2+(o+.5)*f;"staggered"===t&&e%2==1&&(l+=p/2),u.push({x:l,y:e*d+d/2,z:h})}return u}class Uy{constructor(t,e={}){this.pattern=t,this.defaults=e}layout(t,e,n,i={}){const s=i.gap??this.defaults.gap??0,r=i.heightLimit??this.defaults.heightLimit,o=i.fill??this.defaults.fill;return Vy(this.pattern,t,e,n,s,r,o).map(t=>({position:t}))}}class Wy{constructor(t,e,n={}){this.cols=t,this.rows=e,this.defaults=n}layout(t,e,n,i={}){const s=Math.max(1,this.cols),r=Math.max(1,this.rows),o=s*r,a=i.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/o),i=e%o,a=i%s,d=Math.floor(i/s);h.push({position:{x:(a-(s-1)/2)*c,z:(d-(r-1)/2)*l,y:t*n.d+n.d/2}})}return h}}class qy{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,i=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-i)/(e.h+i))),pitchX:e.w+n,pitchZ:e.h+i}}capacity(t,e,n){const{cols:i,rows:s}=this.grid(t,e);return i*s*Math.max(1,Math.floor(n))}layout(t,e,n,i={}){const{cols:s,rows:r,pitchX:o,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=i.heightLimit?Math.max(1,Math.floor(i.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=s*r,p=s*(h?l:1),f=s*r*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,i,l;if(d){const n=Math.floor(t/p),r=t%p;e=r%s,l=Math.floor(r/s),i=n}else{l=Math.floor(t/u);const n=t%u;e=n%s,i=Math.floor(n/s)}this.fillFromFar&&(i=r-1-i),g.push({position:{x:(e-(s-1)/2)*o,z:(i-(r-1)/2)*a,y:l*c+n.d/2}})}return g}}function Xy(t,e,n,i=0){for(let s=0;s<e.length;s++){const r=e[s],o=n[s];r&&o&&(r.parent!==t&&t.attach(r),r.position.set(o.position.x,i+o.position.y,o.position.z),o.rotation?r.quaternion.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.quaternion.identity())}}function Ky(t,e,n,i=.12){const s=e.left+e.width/2,r=e.top+e.height/2,o=Math.min(n.w,n.h)*i,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let i=a.get(t);i||(i={x:s+e.position.x-n.w/2+o,y:r+e.position.z-n.h/2+o,w:n.w-2*o,h:n.h-2*o,count:0},a.set(t,i)),i.count++}return[...a.values()]}function Qy(t){return{id:t?.state?.id??t?.id??t?.refid,type:t?.state?.type??t?.type}}const Jy=new t.Euler;function Zy(e,n){Jy.setFromQuaternion(new t.Quaternion(n.x,n.y,n.z,n.w),"YXZ"),e.rotationX=Jy.x,e.rotation=-Jy.y,e.rotationY=Jy.z}const tb="_transferSlotId",eb=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 nb(t){return class extends t{async ready(){await super.ready();const t=this.state?.data;Array.isArray(t)&&0===this._items.length&&!this.isRecordStorage&&this._reconcileItems(t)}set data(t){if(Array.isArray(t)){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.isRecordStorage)return this.state?.data??[];const t=this._exportSlotRecords();return 0===t.length?this.state?.data:t}_reconcileItems(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=t[tb];null!=e&&n.set(String(e),t)}for(const[t,i]of n)if(!e.has(t)){try{this.removeItem(i,!0)}catch{}try{i?.dispose?.()}catch{}}for(const[t,i]of e){if(n.has(t))continue;if(null==i.itemId)continue;const e=this._createItemFromRecord(i);if(e){e[tb]=t;try{this.handoverIn(e)}catch{}}}for(const[t,i]of e){const e=n.get(t);if(e&&(i.itemState&&"function"==typeof e.setState))try{e.setState(i.itemState)}catch{}}}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,i=[];for(const t of this._items){const e=t[tb];null!=e?n.set(String(e),t):i.push(t)}for(const i of t){const t=n.get(i)??null;e.push(this._slotRecordOf(i,t))}for(const t of i)e.push(this._slotRecordOf("",t));for(const[i,s]of n)t.includes(i)||e.push(this._slotRecordOf(i,s));return e}_recordKey(t){return 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 i of n)i in e&&void 0!==e[i]&&(t[i]=e[i]);return Object.keys(t).length>0?t:void 0}const i={};for(const t of Object.keys(e))eb.has(t)||t.startsWith("_")||(i[t]=e[t]);return Object.keys(i).length>0?i:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=Cc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}class ib{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const sb=new ib,rb=["x","y","z"],ob=["Capacity","Holdable","Transferable","FlowNode"],ab=Object.freeze({Transferable:["Capacity","FlowNode"]}),cb=["S","M","L","XL"],lb=[8,12,16,24,32,48],hb=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function db(t,e){const n="shape"in t?t.shape:void 0,i=n?.extrusion?.section,s="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===i?.kind||"rectangle"===i?.kind&&Object.values(i.corner??{}).some(t=>t>0));if(!s||"full"===e)return t.segments;const r=t.segments??12,o=Math.ceil(r/("medium"===e?2:4));return Math.min(r,lb.find(t=>t>=o)??r)}function ub(t,e){if("full"===e)return t;let n=!1;const i=t.geometry.map(t=>{const i=db(t,e);return i===t.segments?t:(n=!0,{...t,segments:i})});return n?{...t,geometry:i}:t}class pb extends Error{code;path;details;constructor(t,e,n,i){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==i&&(this.details=i)}}const fb=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),mb=1e-6,gb=256,yb=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function bb(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const vb=t=>fb[t],_b=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function xb(t,e){const[n,i]=vb(e);if("rectangle"===t.kind){const e=[];for(const s of[n,i]){const n=t.size[s];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:s}):e.push({code:"NON_FINITE",at:`size.${s}`})}if(!t.corner)return e;for(const s of[n,i]){const n=t.corner[s];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:s}):Number.isFinite(t.size[s])&&n>t.size[s]/2+mb&&e.push({code:"CORNER_TOO_LARGE",axis:s,max:t.size[s]/2}):e.push({code:"NON_FINITE",at:`corner.${s}`})}return e.length||t.corner[n]>0==t.corner[i]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:i}),e}if("ellipse"===t.kind){const e=[];for(const s of[n,i]){const n=t.radius[s];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:s}):e.push({code:"NON_FINITE",at:`radius.${s}`})}return e}return function(t,e){const[n,i]=vb(e),s=[],r=new Set;for(const e of t){"string"==typeof e.id&&yb.test(e.id)?r.has(e.id)?s.push({code:"DUPLICATE_POINT_ID",point:e.id}):r.add(e.id):s.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,i])"number"==typeof e[t]&&Number.isFinite(e[t])||s.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&s.push({code:"TOO_FEW_POINTS",count:t.length});t.length>gb&&s.push({code:"TOO_MANY_POINTS",count:t.length,limit:gb});if(s.length)return s;const o=t.length,a=function(t,e){const[n,i]=vb(e);return t.map(t=>[t[n],t[i]])}(t,e),c=e=>bb(t[e].id,t[(e+1)%o].id),l=mb,h=a.map((t,e)=>Math.hypot(a[(e+1)%o][0]-t[0],a[(e+1)%o][1]-t[1]));if(h.forEach((t,e)=>{t<=l&&s.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),s.length)return s;for(let t=0;t<o;t++){const e=a[t],n=a[(t+1)%o],i=a[(t+2)%o],r=(n[0]-e[0])*(i[1]-n[1])-(n[1]-e[1])*(i[0]-n[0]),d=(n[0]-e[0])*(i[0]-n[0])+(n[1]-e[1])*(i[1]-n[1]);Math.abs(r)<=l*h[t]&&d<0&&s.push({code:"SIDES_FOLD",sides:[c(t),c((t+1)%o)]})}for(let t=0;t<o;t++)for(let e=t+1;e<o;e++){if(e===t+1||0===t&&e===o-1)continue;const n=Sb(a[t],a[(t+1)%o],a[e],a[(e+1)%o],l);n&&s.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(s.length)return s;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[i,s]=t[n],[r,o]=t[(n+1)%t.length];e+=i*o-r*s}return e}(a))/2<=l&&s.push({code:"ZERO_AREA"});return s}(t.points,e)}const wb=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function Mb(t,e,n){const i=n[0]-e[0],s=n[1]-e[1],r=i*i+s*s,o=r?Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/r)):0;return Math.hypot(t[0]-e[0]-o*i,t[1]-e[1]-o*s)}function Sb(t,e,n,i,s){const r=wb(n,i,t),o=wb(n,i,e),a=wb(t,e,n),c=wb(t,e,i),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>s*n&&e<-s*n||t<-s*n&&e>s*n;if(h(r,o,Math.hypot(i[0]-n[0],i[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(Mb(t,n,i),Mb(e,n,i),Mb(n,t,e),Mb(i,t,e))<=s?"touch":null}function Ab(t,e){const[n,i]=vb(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,s]=[n,i].sort(),r=[e,s].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!_b(t))return r;const o=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${s}${n}`,shape:"curved"})));return[...r,...o]}const s=t.points;return s.map((t,e)=>{const n=s[(e+1)%s.length];return{id:bb(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function Eb(t,e,n){const[i,s]=vb(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const r=[i,s].flatMap(t=>[`${t}-`,`${t}+`]);for(const t of r){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 o=t=>n[t],a=(t,e)=>e-o(`${t}-`)-o(`${t}+`),c={[i]:(o(`${i}-`)-o(`${i}+`))/2,[s]:(o(`${s}-`)-o(`${s}+`))/2};if("rectangle"===t.kind){const e={[i]:a(i,t.size[i]),[s]:a(s,t.size[s])};if(!(e[i]>0&&e[s]>0))return{refused:"NO_ROOM_INSIDE"};if(!_b(t))return{section:{kind:"rectangle",size:e},centre:c};const n=e=>Math.max(t.corner[e]-Math.max(o(`${e}-`),o(`${e}+`)),0),r={[i]:n(i),[s]:n(s)};return{section:{kind:"rectangle",size:e,...r[i]>0&&r[s]>0?{corner:r}:{}},centre:c}}const l={[i]:a(i,2*t.radius[i])/2,[s]:a(s,2*t.radius[s])/2};return l[i]>0&&l[s]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const kb=(t,e)=>Object.fromEntries(rb.map(n=>[n,n===t?e:0]));function Cb(t,e,n){const[i,s]=fb[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return kb(t,n.id.endsWith("+")?1:-1)}const r=t.points.find(t=>t.id===n.from),o=t.points.find(t=>t.id===n.to),a=o[i]-r[i],c=o[s]-r[s],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[i]=c/l||0,h[s]=-a/l||0,h}const Tb=(t,e,n)=>{throw new pb(t,e,n)},Ob=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],Pb=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),Ib=["rectangle","ellipse","polygon","portal"],Db=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function zb(t,e){const n=t??{},i=n.axis;rb.includes(i)||Tb("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const s=n.section;Ib.includes(s)||Tb("PARAM",e,`section is ${Ib.join(", ")}, not ${String(n.section)}`);const r=[...fb[i]].sort(),[o,a]=r,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===s||Tb("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===s?String(n.points??"").split("."):[];"polygon"===s?((l.length<3||l.some(t=>!Db.test(t)))&&Tb("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&Tb("PARAM",e,"a point is named twice")):void 0!==n.points&&Tb("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==s&&"ellipse"!==s&&"portal"!==s||(u.across={[o]:d(),[a]:d()}),c&&(u.corner={[o]:d(),[a]:d()}),"portal"===s&&(u.jamb=d(),u.head=d()),"polygon"===s&&(u.point=Object.fromEntries(l.map(t=>[t,{[o]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==s&&"ellipse"!==s&&Tb("SECTION_KIND",e,`a ${s} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const i=n[t];return"open"!==i&&"closed"!==i&&Tb("PARAM",e,`${t} is open or closed`),i};p={id:n.cavity,start:t("cavity-start"),end:t("cavity-end")},u.wall=Object.fromEntries([o,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"]||Tb("PARAM",e,"the ends of an inside need the inside");return{axis:i,plane:r,section:s,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const Rb=(t,e=1)=>[{arg:t,k:e}];function jb(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const i=t.args?.[0],s=t.args?.[1],r=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(i));return"mul@1"!==r?.op||2!==r.args.length||r.args[0]!==s||-.5!==e.constants.find(t=>t.id===r.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function Lb(t,e){const n=zb(t.params,t.id),[i,s]=n.plane,r={},o={},a={},[c,l]=Pb[n.axis],h=jb(t,e);if(r[n.axis]=Rb(1),o[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[i,s])r[t]="profile",o[t]={refused:"SECTION_CORNERS"};return{measure:r,edit:o,faces:a,kind:"polygon"}}const d=n.arg.across,u="ellipse"===n.section?2:1;for(const t of[i,s])r[t]=Rb(d[t],u),o[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[i]]&&t.args[d[i]]===t.args[d[s]]&&(o[s]={arg:d[s],k:u,sameAs:i}),"portal"===n.section){const[t,e]=Pb[i],[c,l]=Pb[s];return a[t]={axis:i,normal:-1,plane:[{arg:d[i],k:-.5}]},a[e]={axis:i,normal:1,plane:[{arg:d[i],k:.5}]},a[c]={axis:s,normal:-1,plane:[]},a[l]={axis:s,normal:1,plane:[{arg:d[s],k:1}]},a[`opening-${t}`]={axis:i,normal:1,plane:[{arg:d[i],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:i,normal:-1,plane:[{arg:d[i],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:s,normal:-1,plane:[{arg:d[s],k:1},{arg:n.arg.head,k:-1}]},{measure:r,edit:o,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[i,s]){const[e,n]=Pb[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[i,s]){const[n,i]=Pb[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${i}`]={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:r,edit:o,faces:a,kind:n.section}}function Fb(t,e){const n=t??{},i=n.axis;return rb.includes(i)||Tb("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&Tb("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:i,profile:n.profile,count:"taper"===n.profile?4:2}}function Nb(t,e){const n=Fb(t.params,t.id),[i,s]=[...fb[n.axis]].sort(),r={},o={};if("half-ellipse"===n.profile)return r[n.axis]=Rb(1,2),o[n.axis]={arg:1,k:2},r[i]=r[s]=Rb(0,2),o[i]={arg:0,k:2},o[s]={arg:0,k:2,sameAs:i},{measure:r,edit:o,faces:{},kind:"sphere"};const[a,c]=Pb[n.axis];r[n.axis]=Rb(1),o[n.axis]={arg:1,k:1};r[i]=r[s]=[{arg:2,k:2},{arg:3,k:2}],o[i]={arg:3,k:2,with:[2]},o[s]={arg:3,k:2,with:[2],sameAs:i};const l=jb(t,e);return{measure:r,edit:o,faces:{[a]:{axis:n.axis,normal:-1,plane:l.lo},[c]:{axis:n.axis,normal:1,plane:l.hi}},kind:"taper"}}function $b(t,e){const n=t??{};"polygon"!==n.section&&Tb("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||Tb("PARAM",e,"a loft has no corners and no inside");const i=zb(n,e),[s,r]=i.plane;return{...i,apex:{[s]:i.count,[r]:i.count+1},count:i.count+2}}function Hb(t,e){const n=$b(t.params,t.id),i={},s={},[r]=Pb[n.axis];i[n.axis]=Rb(1),s[n.axis]={arg:1,k:1};for(const t of n.plane)i[t]="profile",s[t]={refused:"SECTION_CORNERS"};return{measure:i,edit:s,faces:{[r]:{axis:n.axis,normal:-1,plane:jb(t,e).lo}},kind:"pyramid"}}function Bb(t,e){return"extrude@1"===t?.op?Lb(t,e):"revolve@1"===t?.op?Nb(t,e):"loft@1"===t?.op?Hb(t,e):void 0}const Yb=(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 Gb(t,e,n){const i=rb.find(t=>t!==e&&t!==n),[s,r]=fb[i];let o=0;for(let e=0;e<t.length;e++){const n=t[e],i=t[(e+1)%t.length];o+=n[s]*i[r]-i[s]*n[r]}return o>0?t:[t[0],...t.slice(1).reverse()]}function Vb(t,e){const[n,i]=fb[e];let s=0;const r=t.points;for(let t=0;t<r.length;t++){const e=r[t],o=r[(t+1)%r.length];s+=e[n]*o[i]-o[n]*e[i]}return s}function Ub(t,e,n){const i=zb(n.params,e),[s,r]=i.plane,o=t[0],a=t[1];a>0||Tb("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:o,length:a};let l;if("polygon"===i.section){const e=i.points.map(e=>({id:e,[s]:t[i.arg.point[e][s]],[r]:t[i.arg.point[e][r]]}));e.forEach(t=>{c[`point.${t.id}.${s}`]=t[s],c[`point.${t.id}.${r}`]=t[r]}),l={kind:"polygon",points:e}}else if("portal"===i.section){const n=t[i.arg.across[s]],o=t[i.arg.across[r]],a=t[i.arg.jamb],h=t[i.arg.head];n>0&&o>0&&a>0&&h>0&&2*a<n&&h<o||Tb("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${s}`]:n,[`size.${r}`]:o,jamb:a,head:h}),l=function(t,e,n,i,s,r){const o=-n/2,a=n/2,c=o+s,l=a-s,h=i-r,d=(n,i,s)=>({id:n,[t]:i,[e]:s});return{kind:"polygon",points:Gb([d("p1",o,0),d("p2",o,i),d("p3",a,i),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(s,r,n,o,a,h)}else{const e={[s]:t[i.arg.across[s]],[r]:t[i.arg.across[r]]},n="ellipse"===i.section?"radius":"size";if(c[`${n}.${s}`]=e[s],c[`${n}.${r}`]=e[r],"ellipse"===i.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},i.rounded){const n={[s]:t[i.arg.corner[s]],[r]:t[i.arg.corner[r]]};c[`corner.${s}`]=n[s],c[`corner.${r}`]=n[r],(n[s]>0||n[r]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=xb(l,i.axis);h.length&&Tb("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`),"polygon"!==l.kind||"polygon"!==i.section||Vb(l,i.axis)>0||Tb("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:i.axis,section:l,start:o,end:o+a};let u;if(i.cavity){const n=Object.fromEntries(Object.entries(i.arg.wall).map(([e,n])=>[e,t[n]]));u={id:i.cavity.id,wall:n,start:"open"===i.cavity.start?"open":{closed:t[i.arg.startClosed]},end:"open"===i.cavity.end?"open":{closed:t[i.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 s=function(t,e=[]){const{axis:n,section:i,start:s,end:r}=t;if(!(r-s>0))return{refused:{code:"SPAN_NOT_POSITIVE"}};if(e.length>1)return{refused:{code:"CAVITY_COUNT",count:e.length}};const o=e[0];let a;if(o){const t=Eb(i,n,o.wall);if("refused"in t)return{refused:{code:"CAVITY",cavity:o.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=o[t];if("open"!==e&&!(e.closed>0))return{refused:{code:"CAVITY_END_NOT_POSITIVE",cavity:o.id,end:t}}}if(!(r-s-e(o.start)-e(o.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:o.id}}}const c=Ab(i,n),l=[{id:"start-face",kind:"plane",normal:kb(n,-1),..."open"===o?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:kb(n,1),..."open"===o?.end?{open:!0}:{}}];for(const t of c)l.push("flat"===t.shape?{id:`side-face:${t.id}`,kind:"plane",normal:Cb(i,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"===i.kind)for(const t of i.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===i.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...fb[n]].sort();for(const n of["-","+"])for(const i of["-","+"])l.push({id:`edge:${t}${n}${e}${i}`,kind:"edge"})}if(o&&a){for(const t of Ab(a,n)){const e=`cavity-wall:${o.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const i=Cb(a,n,t);l.push({id:e,kind:"plane",normal:{x:-i.x||0,y:-i.y||0,z:-i.z||0}})}}"open"!==o.start&&l.push({id:`cavity-start:${o.id}`,kind:"plane",normal:kb(n,1)}),"open"!==o.end&&l.push({id:`cavity-end:${o.id}`,kind:"plane",normal:kb(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in s&&Tb("GEOMETRY_DOMAIN",e,`the inside is not valid: ${s.refused.code}${"refused"in s.refused?` ${s.refused.refused}`:""}`)}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:Yb(Lb(n).faces,t)}}function Wb(t,e,n){const i=Fb(n.params,e),s=Yb(Nb(n).faces,t);if("half-ellipse"===i.profile){const[n,r]=t;return n>0&&r>0||Tb("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:r},revolution:{axis:i.axis,profile:{kind:"half-ellipse",radial:n,axial:r}},faces:s}}const[r,o,a,c]=t;return o>0&&a>=0&&c>=0&&a+c>0||Tb("GEOMETRY_DOMAIN",e,"a positive length and radii of 0 or more, not both 0, required"),{provider:"revolve",dimensions:{start:r,length:o,startRadius:a,endRadius:c},revolution:{axis:i.axis,profile:{kind:"taper",start:r,end:r+o,startRadius:a,endRadius:c}},faces:s}}function qb(t,e,n){const i=$b(n.params,e),[s,r]=i.plane,o=t[0],a=t[1];a>0||Tb("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:o,length:a},l=i.points.map(e=>({id:e,[s]:t[i.arg.point[e][s]],[r]:t[i.arg.point[e][r]]}));l.forEach(t=>{c[`point.${t.id}.${s}`]=t[s],c[`point.${t.id}.${r}`]=t[r]});const h={kind:"polygon",points:l},d=xb(h,i.axis);d.length&&Tb("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`),Vb(h,i.axis)>0||Tb("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[s]:t[i.apex[s]],[r]:t[i.apex[r]]};return Number.isFinite(u[s])&&Number.isFinite(u[r])||Tb("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${s}`]=u[s],c[`apex.${r}`]=u[r],{provider:"loft",dimensions:c,loft:{axis:i.axis,section:h,start:o,end:o+a,apex:u},faces:Yb(Hb(n).faces,t)}}function Xb(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 Kb={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const i=zb(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a ${i.section} push takes ${i.count} lengths, not ${t.length}`),[Xb("extrude",n,Lb(n).faces)]},run:(t,e,n)=>[Ub(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const i=Fb(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a ${i.profile} turn takes ${i.count} lengths, not ${t.length}`),[Xb("revolve",n,Nb(n).faces)]},run:(t,e,n)=>[Wb(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const i=$b(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a loft of ${i.points.length} points takes ${i.count} lengths, not ${t.length}`),[Xb("loft",n,Hb(n).faces)]},run:(t,e,n)=>[qb(t,e,n)]}};function Qb(t){const e={};if(t.extrusion){const n=t.extrusion,[i,s]=fb[n.axis];e[n.axis]={min:n.start,max:n.end};const r=n.section;for(const t of[i,s])if("rectangle"===r.kind)e[t]={min:-r.size[t]/2,max:r.size[t]/2};else if("ellipse"===r.kind)e[t]={min:-r.radius[t],max:r.radius[t]};else{const n=r.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 fb[n.axis]){const i=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...i),max:Math.max(...i)}}return e}const n=t.revolution,[i,s]=fb[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[i,s])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[i,s])e[n]={min:-t,max:t}}return e}function Jb(t,e){"string"!=typeof t&&Zb("PARAM",e,"layout required"),t.startsWith("L")||Zb("PARAM",e,"layout starts with L");const n=t.slice(1).split(".").map(t=>""===t?[]:t.split("_").map(Number));return(6!==n.length||n.some(t=>!t.length||t.some(t=>!Number.isSafeInteger(t)||t<0)))&&Zb("PARAM",e,"layout is six groups of term counts, each with one candidate or more"),n}const Zb=(t,e,n)=>{throw new pb(t,e,n)},tv={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]},ev=[1,0,0],nv=[0,0,0],iv=[0,1,0],sv={kind:"count"},rv={kind:"flag"};tv.count=[sv,1];const ov=(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 av(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||Zb("SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||Zb("SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||Zb("SCHEMA",i,`unknown ${s}`)}function cv(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||Zb("ID",e,"invalid id"),t}function lv(t,e){return"number"==typeof t&&Number.isFinite(t)||Zb("NON_FINITE",e,String(t)),t}function hv(t,e){return Object.hasOwn(tv,t)||Zb("UNIT",e,String(t)),tv[t]}function dv(t,e,n){(t.length!==e.length||t.some((t,n)=>!ov(t,e[n])))&&Zb("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}const uv={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&ov(t[0],t[1])||Zb("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)||Zb("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)||Zb("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&Zb("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>(dv(t,[iv],e),[nv]),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=>ov(e,t[0])))&&Zb("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&Zb("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))&&Zb("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)ov(t[n],t[0])||Zb("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),ov(t[n+1],t[2])||Zb("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],i=(t.length-1)/2,s=e=>t[1+2*e],r=e=>t[2+2*e];for(let t=1;t<i;t++)s(t)>s(t-1)||Zb("DOMAIN",e,`keys out of order: at[${t}] = ${s(t)} is not after at[${t-1}] = ${s(t-1)}`);if(n<=s(0))return[r(0)];if(n>=s(i-1))return[r(i-1)];let o=0;for(;o<i-2&&s(o+1)<=n;)o++;const a=(n-s(o))/(s(o+1)-s(o));return[r(o)+(r(o+1)-r(o))*a]}},"at-least@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&ov(t[0],t[1])||Zb("TYPE",e,"at-least compares two scalars of the same dimension"),[rv]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>ov(e,t[0])))&&Zb("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.max(...t)]},"min@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>ov(e,t[0])))&&Zb("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.min(...t)]},"affine-bounds@1":{ports:["xmin","xmax","ymin","ymax","zmin","zmax"],params:["layout"],types(t,e,n){const i=Jb(n.params.layout,e);let s=0;for(const n of i)for(const i of n){ov(t[s++],ev)||Zb("TYPE",e,`candidate constant ${s-1} is a length`);for(let n=0;n<i;n++)ov(t[s++],ev)||Zb("TYPE",e,`term value ${s-1} is a length`),ov(t[s++],nv)||Zb("TYPE",e,`term ratio ${s-1} is a ratio`)}return s!==t.length&&Zb("TYPE",e,`the layout takes ${s} arguments; ${t.length} were given`),Array(6).fill(ev)},run:(t,e,n)=>{const i=Jb(n.params.layout,e);let s=0;return i.map((e,n)=>{const i=e.map(e=>{let n=t[s++];for(let i=0;i<e;i++)n+=t[s++]*t[s++];return n});return n%2==0?Math.min(...i):Math.max(...i)})}},"between@1":{ports:["length","center"],types:(t,e)=>(dv(t,[ev,ev,ev,ev],e),[ev,ev]),run:([t,e,n,i],s)=>{(n<0||i<0)&&Zb("DOMAIN",s,"negative margin");const r=e-t-n-i;return r>0||Zb("NO_SPACE",s,`available=${e-t}; margins=${n+i}; deficit=${Math.max(0,-r)}; positive length required`),[r,(t+e+n-i)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>(dv(t,[ev,ev,ev],e),Array(6).fill(ev)),run:([t,e,n],i)=>([t,e,n].some(t=>!(t>0))&&Zb("GEOMETRY_DOMAIN",i,"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)=>(dv(t,[ev,ev],e),Array(4).fill(ev)),run:([t,e],n)=>(t>0&&e>0||Zb("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}})}},pv=(t,e)=>({kind:"transform",from:t,to:e}),fv=()=>[[1,0,0],[0,1,0],[0,0,1]],mv=t=>t[0].map((e,n)=>t.map(t=>t[n])),gv=(t,e)=>t.reduce((t,n,i)=>t+n*e[i],0),yv=(t,e,n,i)=>0+t[0]*e+t[1]*n+t[2]*i,bv=(t,e)=>3===t.length&&3===e.length?[yv(t[0],e[0],e[1],e[2]),yv(t[1],e[0],e[1],e[2]),yv(t[2],e[0],e[1],e[2])]:t.map(t=>gv(t,e)),vv=(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=>mv(e).map(e=>gv(t,e)));const[n,i,s]=e;return t.map(t=>[yv(t,n[0],i[0],s[0]),yv(t,n[1],i[1],s[1]),yv(t,n[2],i[2],s[2])])},_v=(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]),xv=(t,e)=>({r:vv(t.r,e.r),t:_v(bv(t.r,e.t),t.t)}),wv=t=>{const e=mv(t.r);return{r:e,t:bv(e,t.t.map(t=>-t))}};function Mv(t,e,n=[]){av(t.params,e,n,t.id);for(const i of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])cv(t.params[i],t.id)}function Sv(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&Zb("TYPE",e,"rigid transforms required")}Object.assign(uv,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>(dv(t,[ev,ev,ev,ev,ev,nv,sv],e),[{kind:"layout"}]),run:([t,e,n,i,s,r,o],a)=>{t>=0&&e>=0&&n>=0&&i>0&&s>0&&r>=0&&r<=1&&Number.isSafeInteger(o)&&o>=0&&o<=1e4||Zb("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<i?0:1+Math.floor((c-i)/s);l>o&&Zb("RESOURCE_LIMIT",a,`count=${l}, limit=${o}`);const h=l?c-i-(l-1)*s:0;return[{centers:Array.from({length:l},(t,n)=>e+i/2+r*h+n*s),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>(dv(t,[sv,ev,ev,ev,ev,nv,sv],e),[{kind:"layout"}]),run:([t,e,n,i,s,r,o],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(o)&&o>=0&&o<=1e4&&e>=0&&n>=0&&i>=0&&s>0&&r>=0&&r<=1||Zb("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>o&&Zb("RESOURCE_LIMIT",a,"fixed count exceeds limit"),!t)return[{centers:[],count:0}];const c=e-n-i-s;return(c<0||t>1&&c/(t-1)<s)&&Zb("NO_SPACE",a,"fixed count non-overlapping items do not fit"),[{centers:1===t?[n+s/2+r*c]:Array.from({length:t},(e,i)=>n+s/2+i*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)||Zb("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)||Zb("AXIS",e,n.params.axis);const i=4===t.length;return!i||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&ov(t[3],ev)||Zb("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!i||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&Zb("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,i],s,r)=>{t.count*e.members.length>1e4&&Zb("RESOURCE_LIMIT",s,"expanded geometry count > 10000");const o=["x","y","z"].indexOf(r.params.axis),a=["x","y","z"].indexOf(r.params.riseAxis),c=[];for(let s=0;s<t.count;s++)for(const l of e.members){const e=[0,0,0];e[o]=t.centers[s],void 0!==i&&(e[a]=s*i);const h=[r.id,s,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:s,shape:l.shape,pose:xv(xv(n,{r:fv(),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&&ov(t[1],sv)||Zb("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,i)=>{const s=t.items.find(t=>t.index===e&&t.key===i.params.member);return s||Zb("TARGET_ABSENT",n,`${i.params.member}[${e}]`),[{shape:s.shape,pose:s.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(dv(t,[ev,ev,ev,iv,iv,iv],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i,s,r])=>{const o=Math.cos(i),a=Math.sin(i),c=Math.cos(s),l=Math.sin(s),h=Math.cos(r),d=Math.sin(r);return[{r:vv(vv([[1,0,0],[0,o,-a],[0,a,o]],[[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)=>(dv(t,[nv,nv,nv,iv],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i],s)=>{const r=Math.hypot(t,e,n);Math.abs(r-1)>1e-6&&Zb("AXIS",s,"unit axis required");const o=t/r,a=e/r,c=n/r,l=Math.cos(i),h=Math.sin(i),d=1-l;return[{r:[[l+o*o*d,o*a*d-c*h,o*c*d+a*h],[a*o*d+c*h,l+a*a*d,a*c*d-o*h],[c*o*d-a*h,c*a*d+o*h,l+c*c*d]],t:[0,0,0]}]}},"axis-slide@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(dv(t,[nv,nv,nv,ev],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i],s)=>{const r=Math.hypot(t,e,n);return Math.abs(r-1)>1e-6&&Zb("AXIS",s,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/r*i,e/r*i,n/r*i]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(Sv(t,e,2),t[1].to!==t[0].from&&Zb("FRAME_TYPE",e,"composition intermediate frame mismatch"),[pv(t[1].from,t[0].to)]),run:([t,e])=>[xv(t,e)]},"attach@1":{ports:["pose"],types(t,e){Sv(t,e,3);const[n,i,s]=t;return n.from===i.to&&i.from===s.from||Zb("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[pv(s.to,n.to)]},run:([t,e,n])=>[xv(xv(t,e),wv(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>(dv(t,[ev,ev,ev],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||Zb("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[_v(bv(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&ov(t[0],t[1])||Zb("FRAME_TYPE",e,"distance requires points in same frame"),[ev]),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||Zb("TYPE",e,"shape required");const i=Object.keys(t[0].faces);return[...i,"centre",..."revolve"!==t[0].provider||i.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||Zb("UNKNOWN_FEATURE",e,n.params.name),[pv(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const i=function(t,e){const n=Qb(t),i=rb.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return i;const s=t.faces[e],r={x:0,y:1,z:2};if(s){const n=[...i];if(n[r[s.axis]]=s.at,t.loft)for(const e of fb[t.loft.axis]){const i=t.loft.section.points.map(t=>t[e]);n[r[e]]=(Math.min(...i)+Math.max(...i))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,o=t.cavity,a=o.wall;for(const t of fb[e.axis])t!==s.axis&&(n[r[t]]=i[r[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(s.axis!==e.axis){const t=e.start+("open"===o.start?0:o.start.closed),i=e.end-("open"===o.end?0:o.end.closed);n[r[e.axis]]=(t+i)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(Pb).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]).find(([t])=>t===e);if(!t)return;const s=[...i];return s[r[t[1]]]=t[2]<0?n[t[1]].min:n[t[1]].max,s}}(t,n.params.name);return i||Zb("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:i}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||Zb("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})}}),uv["member@1"]={...uv["place@1"],geometry:void 0},Object.assign(uv,Kb);for(const[t,e]of Object.entries(uv))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const Av=[];for(const[t,e]of Object.entries(uv))e.pure=!Av.includes(t);const Ev=["add@1","mul@1","div@1","sin@1","geomean@1","curve@1","at-least@1","max@1","min@1","affine-bounds@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(uv))e.pure&&Ev.includes(t)&&(e.poseForm="run");function kv(t,e,n){return Array.isArray(e)?lv(t,n):"flag"===e.kind?("boolean"!=typeof t&&Zb("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&Zb("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&Iv(t)?zv(t,n):"placed"===e.kind&&Pv(t,"shape","pose")&&jv.has(t.shape)&&Iv(t.pose)?zv(t.pose,n):(Rv(t,n),"shape"===e.kind&&t&&"object"==typeof t&&jv.add(t)),t)}function Cv(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++)Cv(t[e]);else for(const e in t)Cv(t[e]);return t}function Tv(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(Iv(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 i=0;i<t.length;i++)n[i]=Tv(t[i],e)}else{n={};for(const i in t)n[i]=Tv(t[i],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(uv).filter(t=>!uv[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(uv).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(uv).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(uv));const Ov=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],Pv=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let i=0;for(const s in t)if(Object.hasOwn(t,s)){if(i>1||s!==(0===i?e:n))return!1;i++}return 2===i},Iv=t=>Pv(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function Dv(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const i=t[n];"number"==typeof i?Number.isFinite(i)||Zb("NON_FINITE",e,String(i)):Rv(i,e)}}function zv(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const i=t.r[n];Array.isArray(i)?Dv(i,e):Rv(i,e)}Dv(t.t,e)}function Rv(t,e){if("number"==typeof t)Number.isFinite(t)||Zb("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&Rv(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]])))&&jv.has(t))return;for(let i=0;i<n.length;i++)Rv(t[n[i]],e)}}const jv=new WeakSet,Lv=["transform","placed","assembly","collection","point"],Fv=t=>Array.isArray(t)||Lv.includes(t?.kind)?void 0:String(t?.kind??"value");function Nv(t){return function(t){av(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||Zb("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||Zb("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,i=new Map,s=new Map,r=new Map,o=[],a=[],c=(t,e)=>{cv(t,e),n.has(t)&&Zb("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)av(t,["id","unit","min","max"],["role"],"input"),c(t.id,"input"),i.set(t.id,hv(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&Zb("SCHEMA",t.id,"unknown input role"),"state"===t.role&&s.set(t.id,new Set([t.id])),lv(t.min,t.id)>lv(t.max,t.id)&&Zb("RANGE",t.id,"min > max"),"count"===t.unit&&(kv(t.min,sv,t.id),kv(t.max,sv,t.id));for(const t of e.constants)av(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),i.set(t.id,hv(t.unit,t.id)[0]),kv(t.value,i.get(t.id),t.id);for(const t of e.nodes){av(t,["id","op","args","outputs"],["params"],"node"),cv(t.id,"node"),r.has(t.id)&&Zb("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(uv,t.op)||Zb("OPERATOR",t.id,t.op),uv[t.op].params?Mv(t,uv[t.op].params,uv[t.op].optionalParams):Object.hasOwn(t,"params")&&Zb("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||Zb("SCHEMA",t.id,"args array required"),t.args.forEach(e=>cv(e,t.id)),av(t.outputs,uv[t.op].ports,[],t.id);for(const e of Object.values(t.outputs))c(e,t.id);r.set(t.id,t)}const l=new Set,h=new Set,d=[],u=t=>{h.has(t)&&Zb("CYCLE",t,[...a,t].join(" -> ")),a.push(t),h.add(t),d.push({n:r.get(t),at:0,inputTypes:[]})};for(const t of r.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 s=e.args[t.at];if(n.has(s)||Zb("UNKNOWN_REFERENCE",e.id,s),!i.has(s)){u(n.get(s));continue}t.inputTypes.push(i.get(s)),t.at++;continue}const r=uv[e.op],c=r.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of s.get(t)??[])p.add(e);p.size&&(void 0===r.state&&Zb("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===r.state&&Zb("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),r.ports.forEach((t,n)=>i.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>s.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),o.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)||Zb("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||Zb("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||Zb("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=lv(e,t.id);return(n<t.min||n>t.max)&&Zb("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`),kv(n*hv(t.unit,t.id)[1],i.get(t.id),t.id)}function b(t,n){g(t);const s=new Map,r=[],a=new Map,c=new Set;for(const n of e.inputs)s.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)s.set(t.id,lv(t.value*hv(t.unit,t.id)[1],t.id));for(const t of o){const e=uv[t.op],n=t.args.map(t=>s.get(t)),o=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{s.set(t.outputs[e],kv(o[n],i.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const i=Ov(e.geometry(n,o,t),t.id);a.set(t.id,i),r.push(...i)}}return{result:{values:Object.fromEntries(s),geometry:r},kept:{input:{...t},values:s,bodies:a}}}return{outputTypes:Object.fromEntries([...i].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...s].map(([t,e])=>[t,[...e].sort()])),order:o.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,i=0,s=[],r=0;const o=(t,e)=>{const n=e||t.length!==s.length||t.some((t,e)=>t!==s[e]);return n&&i++,s=t,n},a=(t,e)=>(o(t.geometry.map(t=>t.id),e),t),c=t=>{r++;const n=e;if(e=void 0,!n)return e=_(b(t).kept),a({values:{...e.values},geometry:e.geometry.slice()},!0);const i=A(t,n,!0);return e=n,a(i,!1)},l=(t,n)=>{const s=++r,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=o(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 E=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[E]=g[t]+n,S[E]=e.shape??null;const i=12*E;if(e.pose){const t=e.pose.r,n=e.pose.t;M[i]=t[0][0],M[i+1]=t[0][1],M[i+2]=t[0][2],M[i+3]=t[1][0],M[i+4]=t[1][1],M[i+5]=t[1][2],M[i+6]=t[2][0],M[i+7]=t[2][1],M[i+8]=t[2][2],M[i+9]=n[0],M[i+10]=n[1],M[i+11]=n[2]}else M.fill(NaN,i,i+12);E++});const k=d.epoch,C=()=>{r!==s&&Zb("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:i,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{C();const e=h().slot.get(t);return void 0===e&&Zb("TARGET_ABSENT",t,"no such value"),Tv(d.slots[e],new Map)},changed:t=>{C();const e=h().slot.get(t);return void 0!==e&&(y||d.mark[e]===k||!!c?.moved.has(e))}}},h=()=>v();return{evaluate:c,advance(s,o){if(e&&!o){const o=++r,a=e;e=void 0;const h=S(s,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{r!==o&&Zb("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:i,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(s,h.why);return{kind:"evaluation",result:c(s),generation:i,why:h.why}}const a={code:!!e?o:"NOT_BOUND"};if(t.changes)return l(s,a);return{kind:"evaluation",result:c(s),generation:i,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||Zb("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&Zb("TARGET_ABSENT",t,"no such value");const i=e.fast;if(!i)return Tv(e.slots[n],new Map);const s=h().nodes.find(t=>t.outs.includes(n));if(s&&i.wrote.has(s.index)&&!i.moved.has(n)){return Tv(s.op.run(s.args.map(t=>i.slots[t]),s.n.id,s.n)[s.outs.indexOf(n)],new Map)}return Tv(i.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],s=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>s(t.id)),e.constants.forEach(t=>s(t.id));const r=o.map((e,n)=>{const r=uv[e.op];return r.ports.forEach(t=>s(e.outputs[t])),{n:e,op:r,index:n,args:e.args.map(e=>t.get(e)),outs:r.ports.map(n=>t.get(e.outputs[n])),types:r.ports.map(t=>i.get(e.outputs[t]))}}),a=n.map(()=>[]);for(const t of r)for(const e of t.args)a[e].push(t.index);const c=t=>{const e=new Uint8Array(r.length),n=[...t];for(;n.length;){const t=n.pop();for(const i of a[t])e[i]||(e[i]=1,n.push(...r[i].outs))}const i=[];return e.forEach((t,e)=>t&&i.push(e)),i},l=r.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:r,readers:a,reach:e.inputs.map((t,e)=>c([e])),always:h,shapes:r.filter(t=>t.op.geometry).map(t=>t.index),shapeSlot:n.map(t=>"shape"===i.get(t)?.kind)},p}function _(t,n=!0){const i=v(),s=i.keys.map(e=>t.values.get(e));s.forEach((t,e)=>i.shapeSlot[e]&&Cv(t));const r=i.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of i.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:s,bodies:r,shown:r.map(()=>{}),values:n,geometry:[],mark:new Int32Array(i.keys.length),ran:new Int32Array(i.nodes.length),epoch:0,pending:{nodes:new Set(i.shapes.filter(t=>r[t])),slots:new Set(i.keys.keys())}}}const o=new Map,a=r.map(t=>t?.map(t=>Tv(t,o))),c={};i.keys.forEach((t,e)=>c[t]=Tv(s[e],o));const l=[];for(const t of i.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:s,bodies:r,shown:a,values:c,geometry:l,mark:new Int32Array(i.keys.length),ran:new Int32Array(i.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),s=f.get(n);if(s)return s;const r=v(),o=t.forbidden??{},a=new Set(t.external??[]),c={inputs:e.inputs.map((t,e)=>{const n=Fv(i.get(t.id));if(n)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:n};if(Object.hasOwn(o,t.id))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:o[t.id]};for(const n of r.reach[e]){const e=r.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,i]of e.outs.entries()){const s=Fv(e.types[n]);if(s)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:s};const a=r.keys[i];if(Object.hasOwn(o,a))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:o[a]}}}return{fast:!0}}),terminal:r.nodes.map(t=>"repeat@1"===t.n.op&&!t.n.params?.within&&t.outs.every(t=>!r.readers[t].length&&!a.has(r.keys[t]))),visits:new Map};return f.set(n,c),c}function w(t,e){const n=v();if(1===t.length)return n.reach[t[0]];const i=t.join();let s=e.visits.get(i);if(!s){const r=new Set;for(const e of t)for(const t of n.reach[e])r.add(t);s=[...r].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(i,s)}return s}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let i=0;for(const s of e.shapes)n[s]=i,i+=t.bodies[s]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:i,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,i){const s=v();g(t);const r=n.fast?.raw??n.raw,o=[],a=[];for(let n=0;n<e.inputs.length;n++){const i=e.inputs[n],s=t[i.id];s!==r[n]&&(a.push(y(i,s)),o.push(n))}for(const t of o)if(!i.inputs[t].fast)return{why:i.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;o.forEach((n,i)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[i],c.mark[n]=l});const h=w(o,i),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,i=e.t,s=12*p;d[p++]=t,u[s]=n[0][0],u[s+1]=n[0][1],u[s+2]=n[0][2],u[s+3]=n[1][0],u[s+4]=n[1][1],u[s+5]=n[1][2],u[s+6]=n[2][0],u[s+7]=n[2][1],u[s+8]=n[2][2],u[s+9]=i[0],u[s+10]=i[1],u[s+11]=i[2]};for(const t of h){const e=s.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const r=new Array(e.args.length);for(let t=0;t<e.args.length;t++)r[t]=c.slots[e.args[t]];if(i.terminal[t]){const[n,i,s,o]=r,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!==o&&(e[h]=t*o),d.push(xv(s,{r:fv(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of i.members){const i=xv(d[t],n.pose);Rv(i,e.n.id),f(u++,i)}c.wrote.add(t);continue}const o=e.op.run(r,e.n.id,e.n);if(e.outs.forEach((t,n)=>{c.slots[t]=kv(o[n],e.types[n],e.n.id),c.mark[t]=l,c.moved.add(t)}),e.op.geometry){const n=e.op.geometry(r,o,e.n),i=Array.isArray(n)?n:[n];let s=c.start[t];for(const t of i)f(s++,t.pose);c.wrote.add(t)}}return{result:{kind:"poses",generation:0,bodies:d.slice(0,p),poses:u.slice(0,12*p),read:t=>{const e=s.slot.get(t);return void 0===e&&Zb("TARGET_ABSENT",t,"no such value"),Tv(c.slots[e],new Map)},changed:t=>{const e=s.slot.get(t);return void 0!==e&&c.mark[e]===l}}}}function A(t,n,i){const s=v();g(t),n.fast=void 0;const r=++n.epoch,o=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,i)=>{const s=t[e.id];s!==n.raw[i]&&(n.slots[i]=y(e,s),n.raw[i]=s,n.mark[i]=r,o.push(i),c>=0&&(l=!0),c=i)}),l||s.always.length){const t=[];for(const e of[...o.map(t=>s.reach[t]),s.always])for(const i of e)n.ran[i]!==r&&(n.ran[i]=r,t.push(i));a=t.sort((t,e)=>t-e)}else a=c>=0?s.reach[c]:[];const h=[];for(const t of a){const e=s.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===r))continue;const i=e.args.map(t=>n.slots[t]),a=e.op.run(i,e.n.id,e.n);e.outs.forEach((t,i)=>{n.slots[t]=kv(a[i],e.types[i],e.n.id),s.shapeSlot[t]&&Cv(n.slots[t]),n.mark[t]=r,o.push(t)}),e.op.geometry&&(n.bodies[t]=Ov(e.op.geometry(i,a,e.n),e.n.id),n.pending.nodes.add(t),h.push(t))}for(const t of o)n.pending.slots.add(t);if(!i){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of o)n.values[s.keys[t]]=void 0;return h}return E(n),{values:{...n.values},geometry:n.geometry.slice()}}function E(t){const e=v(),{nodes:n,slots:i}=t.pending;if(!n.size&&!i.size)return;const s=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>Tv(t,s));for(const n of i)t.values[e.keys[n]]=Tv(t.slots[n],s);if(n.size){const n=[];for(const i of e.shapes){const e=t.shown[i];e&&n.push(...e)}t.geometry=n}n.clear(),i.clear()}}(t)}function $v(t,e,n){const i=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 i=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return i(n.min)&&i(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(i)throw new pb(i.code,n,i.message)}const Hv=(t,e,n)=>{throw new pb(t,e,n)},Bv={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 Yv(t,e,n){const{types:i,writers:s,model:r,assetFrame:o}=t;e&&"object"==typeof e&&!Array.isArray(e)||Hv("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||Hv("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||Hv("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||Hv("SCHEMA",n,"nonempty string required"),Object.hasOwn(i,t)||Hv("TARGET_ABSENT",n,t),i[t]),c=a(e.placement),l=a(e.feature),h=s.get(e.placement),d=s.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=s.get(h.args[0]),e="repeat@1"===t?.op?s.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||Hv("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=s.get(h.params.member),"member@1"!==p?.op&&Hv("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),r.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&Hv("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&&Hv("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required");"feature@1"!==d?.op&&Hv("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===o&&"transform"===l.kind||Hv("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&Hv("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=i[d.args[0]].provider,m=d.params.name,g=i[d.args[0]].faces,y=g?.[m];y||Hv("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&Hv("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 Gv(t,e,n,i,s={}){const[r,o]=fb[e],a=(t,i)=>{const a={x:0,y:0,z:0};return a[e]=n,a[r]=t+(s[r]??0),a[o]=i+(s[o]??0),[a.x,a.y,a.z]};if("polygon"===t.kind)return t.points.map(t=>a(t[r],t[o]));if("ellipse"===t.kind)return Array.from({length:i},(e,n)=>{const s=2*Math.PI*n/i;return a(t.radius[r]*Math.cos(s),t.radius[o]*Math.sin(s))});const c=t.size[r]/2,l=t.size[o]/2,h=t.corner?.[r]??0,d=t.corner?.[o]??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 i=0;i<=8;i++){const s=n+i/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(s),e*(l-d)+d*Math.sin(s)))}return u}function Vv(t,e){return function(t,e){const n=t.extrusion;if(n){const i=[...Gv(n.section,n.axis,n.start,e),...Gv(n.section,n.axis,n.end,e)],s=t.cavity;if(s){const t=Eb(n.section,n.axis,s.wall);if("section"in t){const r=n.start+("open"===s.start?0:s.start.closed),o=n.end-("open"===s.end?0:s.end.closed);i.push(...Gv(t.section,n.axis,r,e,t.centre),...Gv(t.section,n.axis,o,e,t.centre))}}return i}const i=t.loft;if(i){const t={x:0,y:0,z:0,...i.apex,[i.axis]:i.end};return[...Gv(i.section,i.axis,i.start,e),[t.x,t.y,t.z]]}const s=t.revolution,[r,o]=fb[s.axis],a=(t,n)=>Gv({kind:"ellipse",radius:{[r]:n,[o]:n}},s.axis,t,e);if("taper"===s.profile.kind)return[...a(s.profile.start,Math.max(s.profile.startRadius,1e-9)),...a(s.profile.end,Math.max(s.profile.endRadius,1e-9))];const{radial:c,axial:l}=s.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 Uv(t,e,n){return t.map(([t,i,s])=>[e[0][0]*t+e[0][1]*i+e[0][2]*s+n[0],e[1][0]*t+e[1][1]*i+e[1][2]*s+n[1],e[2][0]*t+e[2][1]*i+e[2][2]*s+n[2]])}function Wv(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 qv=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function Xv(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const Kv="holder",Qv=t=>"number"==typeof t&&Number.isFinite(t),Jv=t=>Qv(t)&&t>0,Zv=t=>Number.isSafeInteger(t)&&t>0;function t_(t,e,n){const i=t?.allowed;if(i&&"object"==typeof i)for(const t of["width","depth","height"])Jv(i[t])||n.push(Xv("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(Xv("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||Zv(t.stackLimit)||t.stackLimit===1/0||n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||Qv(t.rotation)||n.push(Xv("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(Xv("ARRAY_REQUIRED",`${e}.accepts`))}function e_(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[Xv("TIERS_REQUIRED","tiers")];const i=e.anchors?new Set(e.anchors):null,s=new Set;return t.tiers.forEach((t,e)=>{const r=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(Xv("OBJECT_REQUIRED",r));if(Zv(t.tierNo)?s.has(t.tierNo)?n.push(Xv("TIER_NUMBER_DUPLICATE",`${r}.tierNo`,{tierNo:t.tierNo})):s.add(t.tierNo):n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${r}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?i&&!i.has(t.anchorId)&&n.push(Xv("ANCHOR_UNKNOWN",`${r}.anchorId`,{anchorId:t.anchorId})):n.push(Xv("ANCHOR_REQUIRED",`${r}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(Xv("MOUNT_INVALID",`${r}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])Qv(t.position[e])||n.push(Xv("FINITE_NUMBER_REQUIRED",`${r}.position.${e}`));else n.push(Xv("OBJECT_REQUIRED",`${r}.position`));Qv(t.rotation)||n.push(Xv("FINITE_NUMBER_REQUIRED",`${r}.rotation`));const o=t.layout;switch(o?.pattern){case"SINGLE":t_(o.slot,`${r}.layout.slot`,n);break;case"ROW":Zv(o.count)||n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.count`)),Jv(o.pitch)||n.push(Xv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch`)),"X"!==o.axis&&"Z"!==o.axis&&n.push(Xv("AXIS_INVALID",`${r}.layout.axis`)),t_(o.slot,`${r}.layout.slot`,n);break;case"GRID":Zv(o.rows)||n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.rows`)),Zv(o.cols)||n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.cols`)),Jv(o.pitch?.x)||n.push(Xv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.x`)),Jv(o.pitch?.z)||n.push(Xv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.z`)),t_(o.slot,`${r}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(o.slots)){n.push(Xv("ARRAY_REQUIRED",`${r}.layout.slots`));break}o.slots.length||n.push(Xv("SLOTS_REQUIRED",`${r}.layout.slots`));const t=new Set;o.slots.forEach((e,i)=>{const s=`${r}.layout.slots[${i}]`;Zv(e?.slotNo)?t.has(e.slotNo)?n.push(Xv("SLOT_NUMBER_DUPLICATE",`${s}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(Xv("POSITIVE_INTEGER_REQUIRED",`${s}.slotNo`)),Qv(e?.offset?.x)&&Qv(e?.offset?.z)||n.push(Xv("FINITE_NUMBER_REQUIRED",`${s}.offset`)),t_(e,s,n)});break}default:n.push(Xv("PATTERN_INVALID",`${r}.layout.pattern`))}}),n}function n_(t,e=""){const n=[],i=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>i(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,s]of Object.entries(t))i(s,e?`${e}.${n}`:n)}else n.push(Xv("NOT_PERSISTABLE",e,{value:String(t)}))};return i(t,e),n}function i_(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 s_(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:i_(t)},(t,e)=>e+1)}function r_(t,e,n,i,s="ROW_MAJOR"){switch(s){case"ROW_MAJOR":return(n-1)*e+i;case"COL_MAJOR":return(i-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?i:e-i+1);case"SERPENTINE_COL":return(i-1)*t+(i%2==1?n:t-n+1)}}function o_(t,e,n,i="ROW_MAJOR"){const s=n-1;switch(i){case"ROW_MAJOR":return{r:Math.floor(s/e)+1,c:s%e+1};case"COL_MAJOR":return{r:s%t+1,c:Math.floor(s/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(s/e)+1,n=s%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(s/t)+1,n=s%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const a_=(t,e)=>e&&0!==t?-t:t;function c_(t,e,n={}){const i=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!i||!Zv(e.slot))return null;const s=i.layout;let r,o,a;switch(s.pattern){case"SINGLE":if(1!==e.slot)return null;r=s.slot,o={x:0,z:0};break;case"ROW":{if(e.slot>s.count)return null;const t=a_((e.slot-1-(s.count-1)/2)*s.pitch,"MAX"===s.origin);r=s.slot,o="X"===s.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>s.rows*s.cols)return null;const{r:t,c:n}=o_(s.rows,s.cols,e.slot,s.order),i=s.origin??{x:"MIN",z:"MIN"};r=s.slot,o={x:a_((n-1-(s.cols-1)/2)*s.pitch.x,"MAX"===i.x),z:a_((t-1-(s.rows-1)/2)*s.pitch.z,"MAX"===i.z)};break}case"CUSTOM":{const t=s.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:i.tierNo,slotNo:e.slot,name:a,anchorId:i.anchorId,mount:i.mount,tierPosition:{...i.position},tierRotation:i.rotation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function l_(t){return`t${t.tier}_s${t.slot}`}function h_(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*d_(t){for(const e of t?.tiers??[])for(const t of s_(e.layout))yield{tier:e.tierNo,slot:t}}function u_(t,e,n){if(!n)return{x:t,z:e};const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=t=>Math.round(1e9*t)/1e9;return{x:o(t*s+e*r),z:o(-t*r+e*s)}}function p_(t){const e=u_(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 f_=.05,m_=t=>!!t&&Jv(t.width)&&Jv(t.depth)&&Jv(t.height);function g_(t,e){const n=e*Math.PI/180,i=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n)),r=t=>Math.round(1e9*t)/1e9;return{width:r(t.width*i+t.depth*s),depth:r(t.width*s+t.depth*i)}}function y_(t,e,n=0,i=.05){if(!m_(t))return null;if(!Qv(n)||!Qv(i)||i<0||i>=1)return null;const s=g_(t,e.rotation),r=Math.min(1,Math.min(e.allowed.width/s.width,e.allowed.depth/s.depth)*(1-i)),o=t.height*r;return{position:{x:0,y:("HANG"===e.mount?-1:1)*(n+o/2),z:0},rotation:0,scale:r}}function b_(t,e,n=0,i=.05){const s=y_(t,e,n,i);if(!s)return null;const r=p_(e);return{position:{x:r.position.x,y:r.position.y+s.position.y,z:r.position.z},rotation:r.rotation,scale:s.scale}}function v_(t,e,n=.05){let i=0;return t.map(t=>{const s=t?b_(t,e,i,n):null;return s&&(i+=t.height*s.scale),s})}const __=1e-6;function x_(t,e){const n=p_(t),i=t.allowed.width/2,s=t.allowed.depth/2,r=[[-i,-s],[i,-s],[i,s],[-i,s]].map(([t,e])=>{const i=u_(t,e,n.rotation);return{x:n.position.x+i.x,z:n.position.z+i.z}}),o=u_(1,0,n.rotation),a=u_(0,1,n.rotation),c="HANG"===t.mount?-1:1,l=[n.position.y,n.position.y+c*t.allowed.height],h=r.map(t=>t.x);return{tierIndex:e,tier:t.tier,slot:t.slotNo,corners:r,axes:[o,a],y0:Math.min(...l),y1:Math.max(...l),minX:Math.min(...h),maxX:Math.max(...h)}}function w_(t,e){for(const n of[...t.axes,...e.axes]){const i=t.corners.map(t=>t.x*n.x+t.z*n.z),s=e.corners.map(t=>t.x*n.x+t.z*n.z);if(Math.min(Math.max(...i),Math.max(...s))-Math.max(Math.min(...i),Math.min(...s))<=__)return!1}return!0}function M_(t,e={}){const n=[],i=new Map;t.tiers.forEach((e,n)=>{const s=i.get(e.anchorId)??[];i.set(e.anchorId,s);for(const i of s_(e.layout))s.push(x_(c_(t,{tier:e.tierNo,slot:i}),n))});for(const[t,s]of i){const i=e.anchorFaces?.[t];if(i)for(const t of s)t.corners.some(t=>Math.abs(t.x)-i.width/2>__||Math.abs(t.z)-i.depth/2>__)&&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 r=[...s].sort((t,e)=>t.minX-e.minX);for(let t=0;t<r.length;t++){const e=r[t];for(let i=t+1;i<r.length&&r[i].minX<e.maxX-__;i++){const t=r[i];if(Math.min(e.y1,t.y1)-Math.max(e.y0,t.y0)<=__)continue;if(!w_(e,t))continue;const[s,o]=e.tierIndex<t.tierIndex||e.tierIndex===t.tierIndex&&e.slot<t.slot?[e,t]:[t,e];n.push({code:"SLOT_OVERLAP",path:`tiers[${o.tierIndex}]`,params:{tier:o.tier,slot:o.slot,otherTier:s.tier,otherSlot:s.slot}})}}}return n}function S_(t,e,n=[],i={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const s=i.normalizeType??(t=>null==t?"":String(t)),r=[];let o=!1;if(t.accepts){const n=s(e.type);n?t.accepts.map(s).includes(n)||r.push("TYPE_NOT_ACCEPTED"):o=!0}if(n.length+1>t.stackLimit&&r.push("STACK_LIMIT_EXCEEDED"),m_(e.dims)){const i=g_(e.dims,t.rotation);if(i.width>t.allowed.width&&r.push("WIDTH_EXCEEDED"),i.depth>t.allowed.depth&&r.push("DEPTH_EXCEEDED"),n.every(t=>m_(t.dims))){n.reduce((t,e)=>t+e.dims.height,e.dims.height)>t.allowed.height&&r.push("HEIGHT_EXCEEDED")}else o=!0}else o=!0;return r.length?{verdict:"NG",reasons:o?[...r,"SPEC_UNKNOWN"]:r}:o?{verdict:"UNKNOWN",reasons:["SPEC_UNKNOWN"]}:{verdict:"OK",reasons:[]}}function A_(t){if(!t?.layout||!Array.isArray(t.anchors))return[];const e=new Map(t.anchors.map(t=>[t.id,t])),n=[];for(const i of d_(t.layout)){const s=c_(t.layout,i),r=s&&e.get(s.anchorId);if(!s||!r)continue;const o=l_(i);n.push({id:o,label:`${t.label} ${o}`,role:t.role,frame:r.frame,pose:{...r.pose},anchorId:r.id,accepts:[...s.accepts??[]],capacity:s.stackLimit,tier:s.tier,slot:s.slotNo,...s.name?{name:s.name}:{},tierPosition:{...s.tierPosition},tierRotation:s.tierRotation,offset:{...s.offset},rotation:s.rotation,mount:s.mount,allowed:{...s.allowed}})}return n}const E_=["floor","ceiling","center","wall"],k_=(t,e,n)=>{throw new pb(t,e,n)},C_={left:"x",right:"x",bottom:"y",top:"y",back:"z",front:"z"},T_=["fixed","revolute","prismatic"],O_={left:-1,right:1,bottom:-1,top:1,back:-1,front:1};function P_(t){const e=t.mimic;return e&&"object"==typeof e?Object.hasOwn(e,"sum")?Array.isArray(e.sum)?e.sum:[]:[{joint:e.joint,multiplier:e.multiplier}]:[]}function I_(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 D_={joint:((...t)=>t)("id","type","body0","body1","origin","axis","lowerLimit","upperLimit","travel","state","mimic","repeat"),body0:((...t)=>t)("part","face","plane"),body1:((...t)=>t)("part","face"),origin:((...t)=>t)("facing","gap","align","turn","twist"),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)("joint","multiplier","offset","sum"),leader:((...t)=>t)("joint","multiplier"),repeat:((...t)=>t)("axis","pitch","count","rise"),rise:((...t)=>t)("axis","mm")};const z_=(t,e)=>t.nodes.find(t=>t.id===e),R_=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function j_(t,e,n){const i=z_(t,e),s="member@1"===i?.op&&(!!z_(t,`${e}.repeat`)||void 0!==function(t,e){const n=z_(t,e);if("member@1"!==n?.op||z_(t,`${e}.repeat`))return;const i=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return i?String(i.id).replace(/\.assembly$/,""):void 0}(t,e));i&&("place@1"===i.op||s)||k_("TARGET_ABSENT",n,`${e} is not a placed part`);const r=R_(t,i.args[0]);r||k_("TARGET_ABSENT",n,`${e} has no shape`);const o=z_(t,`${e}.pose`);return o&&"rigid@1"===o.op||k_("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:i,shape:r,pose:o}}function L_(t,e,n,i){return j_(t,n,i).pose.args.slice(3,6).map(n=>function(t,e,n){const i=t.constants.find(t=>t.id===n);if(i)return i.value;const s=t.inputs.find(t=>t.id===n);return s&&"state"!==s.role?e.designInputs[n]??null:null}(t,e,n))}const F_=t=>rb.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", ");function N_(t,e,n,i,s){const r=L_(t,e,n,i);if(r.every(t=>0===t))return[[1,0,0],[0,1,0],[0,0,1]];r.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&k_("EDIT_TARGET",i,`${n} is turned (${F_(r)}); only quarter turns keep its faces level with the axes`);const o=$_(r);{const s=j_(t,n,i).pose,o=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...r.map(e=>Q_(t,"deg",e,"a"))];for(const i of o)rx(e,i,sx(t,n,i)?i:void 0)}return o}function $_(t){const[e,n,i]=t.map(t=>t*Math.PI/180),s=t=>Math.round(Math.cos(t)),r=t=>Math.round(Math.sin(t)),o=[[1,0,0],[0,s(e),-r(e)],[0,r(e),s(e)]],a=[[s(n),0,r(n)],[0,1,0],[-r(n),0,s(n)]],c=[[s(i),-r(i),0],[r(i),s(i),0],[0,0,1]];return H_(H_(o,a),c)}const H_=(t,e)=>t.map(t=>e[0].map((n,i)=>t.reduce((t,n,s)=>t+n*e[s][i],0))),B_=t=>t.map(t=>({ref:t.ref,k:-t.k})),Y_=t=>t.map(t=>({ref:t.ref,k:t.k/2})),G_={x:["left","right"],y:["bottom","top"],z:["back","front"]};function V_(t,e,n){const{shape:i}=j_(t,e,n),s=function(t,e){const n=Bb(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}(i,t);return s||k_("EDIT_TARGET",n,`${e} is a ${i.op}; it has no flat face to fasten by`),{shape:i,faces:s}}function U_(t,e){if("centre"!==e.body1.face)return e.body1.face;const n=`joints.${e.id}.body1.face`;"part"in e.body0||k_("JOINT_SCHEMA",n,"a part stands on the mounting plane by a face of its own, not by its centre");const i=e.body0.face;if(Object.hasOwn(C_,i))return Object.keys(C_).find(t=>C_[t]===C_[i]&&O_[t]===-O_[i]);const s=V_(t,e.body0.part,n).faces[e.body0.face];return s||k_("JOINT_SCHEMA",n,`${e.body0.part} has no face ${e.body0.face}`),Object.keys(C_).find(t=>C_[t]===s.axis&&O_[t]===-s.normal)}const W_=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function q_(t,e,n){const{shape:i,faces:s}=V_(t,e,n),r={},o=Bb(i,t).measure;for(const t of rb){const[e,n]=G_[t].map(t=>s[t]),a=o[t],c=a&&"profile"!==a?W_(i,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?W_(i,e):[...W_(i,n),...B_(c)],h=n?W_(i,n):[...W_(i,e),...c];r[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(B_(h))}}return r}function X_(t,e,n,i){const s=q_(t,n,i),r=N_(t,e,n,i),o={};return rb.forEach((t,e)=>{const n=r[e].findIndex(t=>0!==t),i=s[rb[n]];i&&(o[t]=r[e][n]>0?i:{lo:B_(i.hi),hi:B_(i.lo),centred:i.centred})}),o}function K_(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 i=`${e}.${t}`;for(let s=2;n.has(i)||n.has(`${i}.value`);s++)i=`${e}.${t}.${s}`;return n.add(i),n.add(`${i}.value`),i}}function Q_(t,e,n,i){const s=t.constants.find(t=>t.unit===e&&t.value===n);if(s)return s.id;const r=`${i}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:r,unit:e,value:n}),r}function J_(t,e,n,i,s,r){let o=n;if(1!==i){const n=e(`${r}.times`);t.nodes.push({id:n,op:"mul@1",args:[o,Q_(t,"ratio",i,"k")],outputs:{value:`${n}.value`}}),o=`${n}.value`}if(0!==s){const n=e(`${r}.plus`);t.nodes.push({id:n,op:"add@1",args:[o,Q_(t,"mm",s,"d")],outputs:{value:`${n}.value`}}),o=`${n}.value`}return o}function Z_(t,e,n,i,s,r){if(void 0===i)return Q_(t,"mm",0,"d");if("number"==typeof i)return Number.isFinite(i)||k_("SCHEMA",r,"a finite length is required"),Q_(t,"mm",i,"d");i&&"object"==typeof i&&(Object.hasOwn(i,"sum")||i.from)||k_("SCHEMA",r,"a length is a number of millimetres, or something to follow");const{terms:o,plus:a,sum:c}=I_(i),l=tx(t,e,o,a,r);return c?J_(t,n,ex(t,n,l,`${s}.sum`),1,a,s):J_(t,n,l[0].ref,l[0].k,a,s)}function tx(t,e,n,i,s){return Array.isArray(n)&&n.length||k_("SCHEMA",s,"a sum has one term or more"),Number.isFinite(i)||k_("SCHEMA",s,"finite times and plus required"),n.map((i,r)=>{const o=n.length>1?`${s}.sum.${r}`:s;return i&&"object"==typeof i&&i.from||k_("SCHEMA",o,"a length is a number of millimetres, or something to follow"),Number.isFinite(i.times??1)||k_("SCHEMA",o,"finite times and plus required"),{ref:nx(t,e,i.from,o),k:i.times??1}})}function ex(t,e,n,i){const s=n.filter(t=>0!==t.k);if(!s.length)return Q_(t,"mm",0,"d");let r="";for(const[n,o]of s.entries()){const s=J_(t,e,o.ref,o.k,0,`${i}.${n}`);if(r){const o=e(`${i}.${n}.sum`);t.nodes.push({id:o,op:"add@1",args:[r,s],outputs:{value:`${o}.value`}}),r=`${o}.value`}else r=s}return r}function nx(t,e,n,i){if(n&&"object"==typeof n||k_("SCHEMA",i,"a dimension source is required"),"instance"===n.of){const s=`size.${n.axis}`;return t.inputs.some(t=>t.id===s)||k_("TARGET_ABSENT",i,`the instance has no ${s}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const i=z_(t,`sizing.size.${e}`);return i||k_("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),i.outputs.value}(t,n.axis,i):s}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||k_("TARGET_ABSENT",i,`${n.input} is not an input of this asset`),"state"===e.role&&k_("EDIT_TARGET",i,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?ix(t,n.part,n.axis,i):k_("SCHEMA",i,`${String(n.of)} is not a dimension source`)}function ix(t,e,n,i){const s=j_(t,e,i).shape,r=Bb(s);if(r){const o=r.edit[n];if("refused"in o)return k_("EDIT_TARGET",i,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(o.sameAs)return ix(t,e,o.sameAs,i);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(z_(t,a))return c;const l=s.args[o.arg],h=Q_(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),s.args=s.args.map(t=>t===l?c:t);const d=z_(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return k_("EDIT_TARGET",i,`${e} is a ${s.op}; it is not a shape with measures`)}const sx=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role);function rx(t,e,n){const i=t.document.model,s=new Set([...Rx(t.occupancy),...Rx(t.document.capabilities),...Rx(t.joints)]),r=t=>i.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||s.has(t);if(r(e))return;const o=i.inputs.findIndex(t=>t.id===e);if(o>=0){if(e!==n)return;return i.inputs.splice(o,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const a=R_(i,e);if(a&&"place@1"!==a.op&&!Object.values(a.outputs).some(t=>t!==e&&r(t))){i.nodes=i.nodes.filter(t=>t!==a);for(const e of a.args)rx(t,e)}}function ox(t,e){if(!z_(t,`${e}.chain`)&&!z_(t,`${e}.repeat`))return null;const n=z_(t,`${e}.seat.rigid`)??z_(t,`${e}.motion`),i=/^(.*)\.local$/.exec(String(n?.params?.to));return i&&i[1]!==e?i[1]:null}function ax(t,e,n){const i=t.document.model,s=e.to,r=`${e.part} to ${s?.plane??s?.part}`;if(s&&"object"==typeof s||k_("SCHEMA",r,"a target face, or the plane the figure is mounted on, is required"),void 0!==s.plane)return function(t,e,n){const i=t.document.model,s=e.to;"mounting-plane"!==s.plane&&k_("SCHEMA",n,`${String(s.plane)} is not a plane a part can stand on`);void 0!==e.facing&&"meet"!==e.facing&&k_("SCHEMA",n,"a part standing on the plane meets it; flush says nothing here");const r=function(t){return t.placement??"floor"}(t),o=function(t){return"wall"===t?["back"]:["bottom","top"]}(r),a="wall"===r?"z":"y";o.includes(e.face)||k_("ATTACH_FACE",n,"wall"===r?`${String(e.face)} faces along ${C_[e.face]??"no axis"}; the figure hangs on a wall, the plane Z = 0, so a part is fastened to it by its back`:`${String(e.face)} faces along ${C_[e.face]??"no axis"}; the plane faces along y, so a part stands on it by its bottom or hangs from it by its top`);ox(i,e.part)&&!e.replace&&k_("ATTACH_REPLACED",n,`${e.part} is already fastened to ${ox(i,e.part)}; pass replace to stand it on the plane instead`);const c=X_(i,t,e.part,n);c[a]&&Object.hasOwn(V_(i,e.part,n).faces,e.face)||k_("EDIT_TARGET",n,`${e.part} has no flat ${e.face} face`);const l=K_(i,`${e.part}.on.plane`),h="top"===e.face?-1:1,d=Z_(i,t,l,e.gap,`gap.${a}`,n),u={x:"",y:"",z:""};u[a]=ex(i,l,[...B_(h>0?c[a].lo:c[a].hi),{ref:d,k:h}],`stand.${a}`);const p=Q_(i,"mm",0,"d"),f={x:p,y:p,z:p};f[a]=u[a];for(const s of rb.filter(t=>t!==a)){const r=e.align?.[s]??"centre",o=c[s];if("centre"===r)u[s]=Q_(i,"mm",0,"d");else if("object"==typeof r&&r&&Object.hasOwn(r,"mm"))u[s]=Z_(i,t,l,r.mm,`align.${s}`,n);else{if(("min"===r||"max"===r)&&hx(i,s)){o||k_("ATTACH_FACE",n,`${e.part} has no edges along ${s} to line up with the figure's side`);const a="min"===r?-1:1;u[s]=ex(i,l,[{ref:nx(i,t,{of:"instance",axis:s},n),k:.5*a}],`figure-edge.${s}`),f[s]=ex(i,l,B_("min"===r?o.lo:o.hi),`own-edge.${s}`);continue}k_("SCHEMA",n,`the plane has no edges to line ${e.part} up with on ${s}; declare the figure's size, or give the centre or a measured offset`)}o&&!o.centred&&(f[s]=ex(i,l,B_([...Y_(o.lo),...Y_(o.hi)]),`own-centre.${s}`))}const m=rb.map(t=>t===a?p:u[t]);return lx(t,e.part,t.document.capabilities.assetFrame,{seat:[m[0],m[1],m[2]],pose:[f.x,f.y,f.z]}),t}(t,e,r);e.part===s.part&&k_("ATTACH_CYCLE",r,"a part cannot be fastened to itself");const o="centre"===e.face;o||Object.hasOwn(C_,String(e.face))||k_("SCHEMA",r,`${String(e.face)} is not a face`);const a=V_(i,s.part,r),c=Object.hasOwn(a.faces,String(s.face))?a.faces[s.face]:void 0;c||k_("SCHEMA",r,`${s.part} has no face ${String(s.face)}; it has ${Object.keys(a.faces).join(", ")}`);const l=e.facing??"meet";"meet"!==l&&"flush"!==l&&k_("SCHEMA",r,`${String(l)} is neither meet nor flush`);const h=c.axis,d=c.normal;o&&"meet"!==l&&k_("ATTACH_FACE",r,`${e.part} fastened by its centre sits on ${s.face}; flush has no meaning for a centre`),o&&(e={...e,face:Object.keys(C_).find(t=>C_[t]===h&&O_[t]===-d)}),C_[e.face]!==h&&k_("ATTACH_FACE",r,`${e.face} faces along ${C_[e.face]} and ${s.face} along ${h}; fastening them would need a turn, which this command does not do`);const u=Object.keys(C_).find(t=>C_[t]===h&&O_[t]===("meet"===l?-d:d));"meet"===l&&e.face!==u&&k_("ATTACH_FACE",r,`to meet ${s.face}, ${e.part} offers its ${u}; pass flush to lay ${e.face} in the same plane instead`),"flush"===l&&e.face!==u&&k_("ATTACH_FACE",r,`to lie flush with ${s.face}, ${e.part} offers its ${u}`),ox(i,e.part)&&!e.replace&&k_("ATTACH_REPLACED",r,`${e.part} is already fastened to ${ox(i,e.part)}; pass replace to move it, or detach it first`);for(let t=s.part;t;t=ox(i,t))t===e.part&&k_("ATTACH_CYCLE",r,`${s.part} already hangs from ${e.part}`);const p=q_(i,s.part,r),f=X_(i,t,e.part,r),m=f[h];m&&Object.hasOwn(V_(i,e.part,r).faces,e.face)||o||k_("EDIT_TARGET",r,`${e.part} has no flat ${e.face} face`);const g=K_(i,`${e.part}.on.${s.part}`),y="meet"===l?d:-d,b=Z_(i,t,g,e.gap,`gap.${h}`,r),v=Q_(i,"mm",0,"d"),_={x:"",y:"",z:""},x={x:v,y:v,z:v};_[h]=ex(i,g,[...W_(a.shape,c),...o?[{ref:b,k:y}]:[]],`seat.${h}`);const w=o?m&&!m.centred?[...Y_(m.lo),...Y_(m.hi)]:[]:O_[e.face]>0?m.hi:m.lo;x[h]=o?w.length?ex(i,g,B_(w),`along.${h}`):v:ex(i,g,[...B_(w),{ref:b,k:y}],`along.${h}`);for(const n of rb.filter(t=>t!==h)){const o=e.align?.[n]??"centre",a=p[n],c=f[n],l=t=>t&&!t.centred?[...Y_(t.lo),...Y_(t.hi)]:[],h=(t,e)=>l(t).length?ex(i,g,l(t),e):Q_(i,"mm",0,"d"),d=()=>l(c).length?ex(i,g,B_(l(c)),`own-centre.${n}`):v;if("centre"===o)_[n]=h(a,`centre.${n}`),x[n]=d();else if("object"==typeof o&&o&&Object.hasOwn(o,"mm")){const e=Z_(i,t,g,o.mm,`align.${n}`,r);_[n]=l(a).length?ex(i,g,[...l(a),{ref:e,k:1}],`align.${n}.from-centre`):e,x[n]=d()}else"min"===o||"max"===o?(a||k_("ATTACH_FACE",r,`${s.part} has no edges along ${n} to line ${e.part} up with; give the centre or a measured offset`),c||k_("ATTACH_FACE",r,`${e.part} has no edges along ${n} to line up; give the centre or a measured offset`),_[n]=ex(i,g,"min"===o?a.lo:a.hi,`edge.${n}`),x[n]=ex(i,g,B_("min"===o?c.lo:c.hi),`own-edge.${n}`)):k_("SCHEMA",r,`${String(o)} is not an alignment`)}if(n&&n.deg){const[o,a]=Mx[h];for(const t of[o,a]){const i=e.align?.[t]??"centre";"min"!==i&&"max"!==i||k_("ATTACH_FACE",r,`${e.part} is twisted ${cx(n.deg)}° about ${h}; its sides are not level with ${s.part}'s edges -- place it by the centre or a distance`)}const c=n=>{const s=e.align?.[n]??"centre",o=f[n],a=o&&!o.centred?B_([...Y_(o.lo),...Y_(o.hi)]):[];return"object"==typeof s&&s&&Object.hasOwn(s,"mm")?[{ref:Z_(i,t,g,s.mm,`twist.${n}`,r),k:1},...a]:a},[l,d]=[c(o),c(a)],u=t=>{const e=Math.round(1e12*t)/1e12;return 0===e?0:e},m=String(cx(n.deg)).replace("-","m").replace(".","_"),y=t=>{const e=`twist.${t}.${m}`,s=n.deg*Math.PI/180;return i.constants.some(t=>t.id===e)||i.constants.push({id:e,unit:"ratio",value:u("cos"===t?Math.cos(s):"sin"===t?Math.sin(s):-Math.sin(s))}),e},b=(t,e,n)=>{const s=g(n);return i.nodes.push({id:s,op:"mul@1",args:[t,e],outputs:{value:`${s}.value`}}),`${s}.value`},v=(t,e,n)=>{const s=g(n);return i.nodes.push({id:s,op:"add@1",args:[t,e],outputs:{value:`${s}.value`}}),`${s}.value`};for(const t of[o,a]){const e=p[t];_[t]=e&&!e.centred?ex(i,g,[...Y_(e.lo),...Y_(e.hi)],`twist-centre.${t}`):Q_(i,"mm",0,"d")}const w=ex(i,g,l,`twist-own.${o}`),M=ex(i,g,d,`twist-own.${a}`);x[o]=v(b(w,y("cos"),`twisted.${o}.cos`),b(M,y("nsin"),`twisted.${o}.sin`),`twisted.${o}`),x[a]=v(b(w,y("sin"),`twisted.${a}.sin`),b(M,y("cos"),`twisted.${a}.cos`),`twisted.${a}`)}return lx(t,e.part,`${s.part}.local`,{seat:[_.x,_.y,_.z],pose:[x.x,x.y,x.z]}),t}const cx=t=>Math.round(1e6*t)/1e6;function lx(t,e,n,i){const s=t.document.model,{place:r,pose:o}=j_(s,e,e),a=i?o.args.slice(0,3):[];i&&(o.args=[...i.pose,...o.args.slice(3)]),o.params={...o.params,to:`${e}.seat`};const c=z_(s,`${e}.motion`),l=Q_(s,"mm",0,"d"),h=Q_(s,"deg",0,"a");let d=z_(s,`${e}.seat.rigid`);d||(d={id:`${e}.seat.rigid`,op:"rigid@1",args:[l,l,l,h,h,h],outputs:{pose:`${e}.seat.value`},params:{}},s.nodes.push(d));const u=i?d.args.slice(0,3):[];i&&(d.args=[...i.seat,...d.args.slice(3)]),d.params={from:c?`${e}.joint`:`${e}.seat`,to:n};let p=z_(s,`${e}.turned`);c?(c.params={...c.params,from:`${e}.seat`,to:`${e}.joint`},p?p.args=[c.outputs.pose,o.outputs.pose]:(p={id:`${e}.turned`,op:"compose@1",args:[c.outputs.pose,o.outputs.pose],outputs:{pose:`${e}.turned.value`}},s.nodes.push(p))):p&&(s.nodes=s.nodes.filter(t=>t!==p));let f=z_(s,`${e}.chain`);f||(f={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},s.nodes.push(f)),f.args=[d.outputs.pose,c?p.outputs.pose:o.outputs.pose];const m=/^(.*)\.local$/.exec(n);let g=z_(s,`${e}.world`);if(m&&m[1]!==e){const t=z_(s,`${m[1]}.world`)?.outputs?.pose??z_(s,`${m[1]}.chain`)?.outputs?.pose??z_(s,`${m[1]}.turned`)?.outputs?.pose??z_(s,`${m[1]}.pose`).outputs.pose;g?g.args=[t,f.outputs.pose]:(g={id:`${e}.world`,op:"compose@1",args:[t,f.outputs.pose],outputs:{pose:`${e}.world.value`}},s.nodes.push(g)),r.args=[r.args[0],g.outputs.pose]}else g&&(s.nodes=s.nodes.filter(t=>t!==g)),r.args=[r.args[0],f.outputs.pose];for(const n of[...a,...u])rx(t,n,sx(s,e,n)?n:void 0)}const hx=(t,e)=>t.inputs.find(t=>t.id===qv[e]),dx=t=>t.state?.id??t.id;function ux(t,e){const n=t.document.model,i=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||k_("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[i,s]of Object.entries(t))void 0===s||e.includes(i)||k_("JOINT_SCHEMA",n,`${i} is a field this kernel does not know`)},i=(t,e)=>n(t,D_.source,e),s=(t,e)=>{if(t&&"object"==typeof t&&(n(t,D_.measure,e),i(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[s,r]of t.sum.entries())n(r,D_.term,`${e}.sum.${s}`),i(r?.from,`${e}.sum.${s}.from`)};n(t,D_.joint,e),n(t.body0,D_.body0,`${e}.body0`),n(t.body1,D_.body1,`${e}.body1`);const r=t.origin;if(n(r,D_.origin,`${e}.origin`),r&&"object"==typeof r){s(r.gap,`${e}.origin.gap`),n(r.turn,D_.axes,`${e}.origin.turn`),n(r.align,D_.axes,`${e}.origin.align`);for(const[t,i]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(i,D_.alignment,`${e}.origin.align.${t}`),s(i?.mm,`${e}.origin.align.${t}.mm`)}if(t.travel&&"object"==typeof t.travel&&(n(t.travel,D_.travel,`${e}.travel`),i(t.travel.source,`${e}.travel.source`),Array.isArray(t.travel.sum)&&s({sum:t.travel.sum},`${e}.travel`)),n(t.state,D_.state,`${e}.state`),n(t.mimic,D_.mimic,`${e}.mimic`),Array.isArray(t.mimic?.sum))for(const[i,s]of t.mimic.sum.entries())n(s,D_.leader,`${e}.mimic.sum.${i}`);n(t.repeat,D_.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(s(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,D_.rise,`${e}.repeat.rise`))}(e,i),T_.includes(e.type)||k_("JOINT_SCHEMA",i,`${String(e.type)} is not a joint type; ${T_.join(", ")}`),e.body1&&"string"==typeof e.body1.part||k_("JOINT_SCHEMA",i,"a joint carries a part (body1)"),j_(n,e.body1.part,i),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||k_("JOINT_SCHEMA",i,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&j_(n,e.body0.part,i);const s=(t.joints??[]).filter(t=>t.id!==e.id),r=s.find(t=>t.body1.part===e.body1.part);if(r&&k_("JOINT_TREE",i,`${e.body1.part} already hangs from ${"part"in r.body0?r.body0.part:"the mounting plane"} by ${r.id}; a part has one joint above it`),"part"in e.body0){const t=t=>s.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&k_("ATTACH_CYCLE",i,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const s=t(n);n=s&&"part"in s?s.part:void 0}}const o="fixed"!==e.type,a=void 0!==e.lowerLimit||void 0!==e.upperLimit;if(o&&!["X","Y","Z"].includes(e.axis)&&k_("JOINT_SCHEMA",i,`a ${e.type} joint has an axis, X, Y or Z`),o||void 0===e.axis&&!a&&void 0===e.mimic&&void 0===e.travel||k_("JOINT_SCHEMA",i,"a fixed joint has no axis, limits, mimic or travel"),void 0!==e.travel&&"prismatic"!==e.type&&k_("JOINT_SCHEMA",i,"only a prismatic joint travels a length"),"prismatic"===e.type&&e.travel&&!a&&(e.lowerLimit=0,e.upperLimit=1),o&&!e.mimic&&(a||"prismatic"===e.type)){const[t,n]=[e.lowerLimit,e.upperLimit];Number.isFinite(t)&&Number.isFinite(n)&&t<n||k_("JOINT_SCHEMA",i,`a ${e.type} joint has both limits, lower below upper`)}if(e.mimic){!Object.hasOwn(e.mimic,"sum")||Array.isArray(e.mimic.sum)&&e.mimic.sum.length||k_("JOINT_SCHEMA",i,"a mimic sum follows one joint or more");const t=new Set;for(const n of P_(e)){const r=s.find(t=>t.id===n?.joint);r&&"fixed"!==r.type||k_("JOINT_SCHEMA",i,`${String(n?.joint)} is not a moving joint to follow`),t.has(r.id)&&k_("JOINT_SCHEMA",i,`${r.id} is followed twice; a sum names each joint once`),t.add(r.id),r.mimic&&k_("JOINT_SCHEMA",i,`${r.id} follows another joint; follow the one it follows`),"prismatic"===r.type!=("prismatic"===e.type)&&k_("JOINT_SCHEMA",i,`${r.id} ${"prismatic"===r.type?"slides":"turns"}; a joint follows ones that move the same way: a slide a slide, a turn a turn`),Number.isFinite(n.multiplier)||k_("JOINT_SCHEMA",i,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||k_("JOINT_SCHEMA",i,"a mimic's offset is a number in the joint's unit")}void 0===e.origin?.twist||Number.isFinite(e.origin.twist)||k_("JOINT_SCHEMA",`${i}.origin.twist`,"a twist is a number of degrees"),e.origin?.turn&&Object.values(e.origin.turn).some(t=>!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&k_("JOINT_SCHEMA",`${i}.origin.turn`,"a turn is in quarter turns; an angle about the face's normal is its twist");const c=[...s,e],l=t=>c.find(e=>e.body1.part===t&&"part"in e.body0),h=t=>{for(let e=l(t);e;e=l(e.body0.part))if(e.repeat)return e};if(e.repeat){const t=e=>c.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?h(e.body0.part):void 0);t;t="part"in t.body0?h(t.body0.part):void 0)n.push(t);const s=t(e.body1.part).map(t=>c.find(e=>e.body1.part===t)).filter(t=>t.repeat),r=[...n,...s].find(t=>t.repeat.axis===e.repeat.axis);r&&k_("JOINT_SCHEMA",`${i}.repeat`,`${r.body1.part}'s row runs along ${r.repeat.axis} too; a row inside a row runs along another axis`)}if(e.repeat){const n=e.repeat,s=`${i}.repeat`;"part"in e.body0||k_("JOINT_SCHEMA",s,"a row fills the part it is fastened to; the mounting plane has no length to fill"),["X","Y","Z"].includes(n.axis)||k_("JOINT_SCHEMA",s,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===C_[U_(t.document.model,e)]&&k_("JOINT_SCHEMA",s,`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:(t=>{const e=I_(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)})(n.pitch))||k_("GEOMETRY_DOMAIN",s,"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<=100||k_("GEOMETRY_DOMAIN",s,"a row has 1 to 100 copies"),void 0!==n.rise&&(n.rise&&["X","Y","Z"].includes(n.rise.axis)&&n.rise.axis!==n.axis||k_("JOINT_SCHEMA",`${s}.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||k_("GEOMETRY_DOMAIN",`${s}.rise`,"a rise is a length in mm, not zero"))}}function px(t,e){const n=t.document.model,i=e.body1.part,{pose:s}=j_(n,i,i),r="part"in e.body0?e.body0.part:void 0,o=`joints.${e.id}`,a=r?gx(_x(t,r,o)):fx,c=!mx(a),l=rb.map(t=>e.origin?.turn?.[t]??0),h=U_(n,e),d=C_[h],u=e.origin?.twist?H_(Sx(d,e.origin.twist),$_(l)):$_(l),p=H_(a,u),f=Ax(yx(a,bx[h]),`${e.body1.part}'s ${h}`,r??"",a,o),m=yx(a,rb.map(t=>t===d?1:0)),g=(e.origin?.twist??0)*Math.sign(m[rb.indexOf(f.axis)]),{quarter:y,deg:b}=function(t,e,n,i){const s=rb.indexOf(e),[r,o]=Mx[e].map(t=>rb.indexOf(t));let a;for(const e of Ex){const i=H_(t,gx(e));if(Math.abs(i[s][s]-1)>1e-9)continue;const c=180*Math.atan2(i[o][r],i[r][r])/Math.PI,l=Math.abs(((c-n)%360+540)%360-180);(!a||l<a.off-1e-9)&&(a={quarter:e,deg:Math.abs(c)<1e-9?0:c,off:l})}a||k_("ATTACH_FACE",i,`the part would stand turned about more than the face's normal (${F_(kx(t))})`);return{quarter:a.quarter,deg:a.off<1e-6?n:cx(a.deg)}}(p,f.axis,g,o),v=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...(c||e.origin?.twist?wx(y):l).map(t=>Q_(n,"deg",t,"a"))];for(const e of v)rx(t,e,sx(n,i,e)?e:void 0);const _=t=>c&&Object.hasOwn(bx,t)?vx(Ax(yx(a,bx[t]),t,r??"",a,o).vector):t;if(ax(t,{kind:"attach",part:i,face:_(e.body1.face),to:"plane"in e.body0?{plane:"mounting-plane"}:{part:e.body0.part,face:_(e.body0.face)},...e.origin?.facing?{facing:e.origin.facing}:{},...void 0!==e.origin?.gap?{gap:e.origin.gap}:{},...e.origin?.align?{align:c?Cx(r?gx(xx(t,r,o)):a,e.origin.align,o):e.origin.align}:{},replace:!0},b?{deg:b}:void 0),b){const e=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...kx(p).map(t=>Q_(n,"deg",t,"a"))];for(const n of e)rx(t,n)}if(e.repeat&&c&&k_("JOINT_SCHEMA",`joints.${e.id}.repeat`,`${r} stands turned; a row across a turned part is not covered yet`),"fixed"===e.type)return void(e.repeat&&Tx(t,e));const x="prismatic"===e.type?"slide":"turn",w="prismatic"===e.type?e.travel?"ratio":"mm":"deg",M=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},S=P_(e).map(e=>({leader:(t.joints??[]).find(t=>t.id===e.joint),k:e.multiplier})),A=yx(a,rb.map(t=>t===e.axis.toLowerCase()?1:0)),E=A.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);E<0&&k_("JOINT_SCHEMA",o,`${r} stands twisted; the axis ${e.axis} is not level with an axis in it`),function(t,e,n,i=1){const s=t.document.model,r=e.part;j_(s,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&k_("SCHEMA",r,"a slide or a turn is required");rb.includes(e.motion.axis)||k_("SCHEMA",r,`${String(e.motion.axis)} is not an axis`);z_(s,`${e.part}.motion`),0;z_(s,`${e.part}.motion`)&&zx(t,{part:e.part});const o=e.motion.frame??"attachment",a=Dx(t,e.part);"asset"===o&&a!==t.document.capabilities.assetFrame?k_("MOTION_FRAME",r,`${e.part} is fastened into ${a}; an axis in the asset frame would have to be re-expressed there, which this command does not do`):"attachment"!==o&&"asset"!==o&&k_("SCHEMA",r,`${String(o)} is not a frame for the axis`);const c=e.state,l=K_(s,`${e.part}.motion`);let h=c?.id;if(n){if(n.sum)for(const[t,e]of n.terms.entries()){const n=l(`mimic.${t}`);if(s.nodes.push({id:n,op:"mul@1",args:[e.of,Q_(s,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=l(`mimic.${t}.sum`);s.nodes.push({id:e,op:"add@1",args:[h,`${n}.value`],outputs:{value:`${e}.value`}}),h=`${e}.value`}else h=`${n}.value`}else{const t=l("mimic");s.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,Q_(s,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),h=`${t}.value`}if(n.c){const t=l("mimic.offset"),i="slide"===e.motion.kind?"mm":"deg";s.nodes.push({id:t,op:"add@1",args:[h,Q_(s,i,n.c,"d")],outputs:{value:`${t}.value`}}),h=`${t}.value`}}else{c&&"string"==typeof c.id&&c.id.trim()||k_("SCHEMA",r,"a state input id is required");const n=s.inputs.find(t=>t.id===c.id&&"state"===t.role&&t.unit===c.unit&&t.min===c.min&&t.max===c.max);if(n);else if(s.inputs.some(t=>t.id===c.id)){if((s.nodes.some(t=>t.args.includes(c.id))||(t.drivers??[]).some(t=>t.state===c.id)||t.appearance.some(t=>t.visibility===c.id))&&k_("DUPLICATE_WRITER",r,`${c.id} already exists`),s.inputs=s.inputs.filter(t=>t.id!==c.id),delete t.stateDefaults[c.id],t.stateInputs?.[c.id]){const{[c.id]:e,...n}=t.stateInputs;t.stateInputs=n}}const i="turn"===e.motion.kind?["deg"]:["mm","ratio"];i.includes(c.unit)||k_("SCHEMA",r,`a ${e.motion.kind} takes a ${i.join(" or ")} control, not ${String(c.unit)}`),Number.isFinite(c.min)&&Number.isFinite(c.max)&&c.max>c.min||k_("SCHEMA",r,"a range with max above min is required");const o=c.start??c.min;o>=c.min&&o<=c.max||k_("SCHEMA",r,"the starting value is outside the range"),n||(s.inputs.push({id:c.id,unit:c.unit,min:c.min,max:c.max,role:"state"}),t.stateDefaults[c.id]=o),void 0===c.label&&void 0===c.sweep||(t.stateInputs={...t.stateInputs??{}},t.stateInputs[c.id]={...void 0!==c.label?{label:c.label}:{},...void 0!==c.sweep?{sweep:c.sweep}:{}})}if("slide"===e.motion.kind&&"ratio"===c.unit){e.travel||k_("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let i;if(Object.hasOwn(n,"sum")){const e=n.plus??0;i=J_(s,l,ex(s,l,tx(s,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?nx(s,t,n.source,r):Q_(s,"mm",n.plus??0,"d");i=n.source?J_(s,l,e,n.times??1,n.plus??0,"travel"):e}const o=l("distance");s.nodes.push({id:o,op:"mul@1",args:[h,i],outputs:{value:`${o}.value`}}),h=`${o}.value`}else"slide"===e.motion.kind&&e.travel&&k_("SCHEMA",r,"a mm control is the distance; travel would say it twice");const d=rb.map(t=>Q_(s,"ratio",t===e.motion.axis?i:0,"axis"));if(s.nodes.push({id:`${e.part}.motion`,op:"slide"===e.motion.kind?"axis-slide@1":"axis-turn@1",args:[...d,h],outputs:{pose:`${e.part}.motion.value`},params:{from:`${e.part}.seat`,to:a}}),lx(t,e.part,a),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||k_("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||k_("SCHEMA",r,"a clip runs for a positive number of seconds"),t.drivers=[...t.drivers??[],{id:`${e.part}/${n.name}`,clip:n.name,state:c.id,time:{unit:"s",duration:n.duration},keys:structuredClone(n.keys),interpolation:"linear",loop:n.loop??"wrap",accumulates:n.accumulates??!1}]}}(t,{part:i,motion:{kind:x,axis:rb[E]},state:{id:dx(e),unit:w,min:M.min,max:M.max,start:e.state?.start??Math.min(M.max,Math.max(M.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:S.map(({leader:t,k:e})=>({of:z_(n,`${t.body1.part}.motion`)?.args[3]??dx(t),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,A[E]>0?1:-1),e.repeat&&Tx(t,e)}const fx=[[1,0,0],[0,1,0],[0,0,1]],mx=t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)),gx=t=>t[0].map((e,n)=>t.map(t=>t[n])),yx=(t,e)=>t.map(t=>t.reduce((t,n,i)=>t+n*e[i],0)),bx={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]},vx=t=>Object.keys(bx).find(e=>bx[e].every((e,n)=>e===t[n]));function _x(t,e,n){const i=(t.joints??[]).find(t=>t.body1.part===e),s=i?rb.map(t=>i.origin?.turn?.[t]??0):L_(t.document.model,t,e,n);s.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&k_("EDIT_TARGET",n,`${e} is turned (${F_(s)}); fastening to a turned part by its faces is covered only for quarter turns`);const r=s.every(t=>0===t)?fx:$_(s);return i?.origin?.twist?H_(Sx(C_[U_(t.document.model,i)],i.origin.twist),r):r}function xx(t,e,n){const i=(t.joints??[]).find(t=>t.body1.part===e);if(!i?.origin?.twist)return _x(t,e,n);const s=rb.map(t=>i.origin?.turn?.[t]??0);return s.every(t=>0===t)?fx:$_(s)}function wx(t){const e=t=>{const e=90*Math.round(180*t/Math.PI/90);return 0===e?0:e},n=Math.abs(t[0][2])<1?[e(Math.atan2(-t[1][2],t[2][2])),e(Math.asin(t[0][2])),e(Math.atan2(-t[0][1],t[0][0]))]:[e(Math.atan2(t[1][0],t[1][1])),e(Math.asin(t[0][2])),0];if(!$_(n).every((e,n)=>e.every((e,i)=>e===t[n][i])))throw new Error(`no turn gives ${JSON.stringify(t)}`);return n}const Mx={x:["y","z"],y:["z","x"],z:["x","y"]};function Sx(t,e){const n=Math.cos(e*Math.PI/180),i=Math.sin(e*Math.PI/180),[s,r]=Mx[t].map(t=>rb.indexOf(t)),o=[[1,0,0],[0,1,0],[0,0,1]];return o[s][s]=n,o[s][r]=-i,o[r][s]=i,o[r][r]=n,o}function Ax(t,e,n,i,s){const r=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);return r<0&&k_("ATTACH_FACE",s,`${n} stands twisted (${F_(kx(gx(i)))}); ${e} is not level with an axis in it`),{axis:rb[r],vector:t.map(t=>Math.abs(t)<1e-9?0:Math.sign(t))}}const Ex=(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const i of[0,90,180,270]){const s=$_([e,n,i]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===s[e][n])))||t.push(s)}return t})();function kx(t){const e=t=>{const e=cx(180*t/Math.PI);return 0===e?0:e},n=Math.max(-1,Math.min(1,t[0][2]));return Math.abs(n)<1-1e-12?[e(Math.atan2(-t[1][2],t[2][2])),e(Math.asin(n)),e(Math.atan2(-t[0][1],t[0][0]))]:[e(Math.atan2(t[1][0],t[1][1])),e(Math.asin(n)),0]}function Cx(t,e,n){const i={};for(const[s,r]of Object.entries(e)){const e=yx(t,rb.map(t=>t===s?1:0)),o=e.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);o<0&&k_("ATTACH_FACE",n,`the parent stands twisted; placing along ${s} is not level with an axis in it -- place it by the centre`);const a=Math.sign(e[o]),c=rb[o];"centre"===r||a>0?i[c]=r:"min"===r||"max"===r?i[c]="min"===r?"max":"min":"number"==typeof r.mm?i[c]={mm:-r.mm}:k_("SCHEMA",n,`an offset that follows another value cannot be turned over onto ${c}; give it as a number`)}return i}function Tx(t,e){const n=t.document.model,i=e.body1.part,s=e.body0.part,r=`joints.${e.id}.repeat`,o=e.repeat.axis.toLowerCase(),a=rb.indexOf(o),c=q_(n,s,r)[o];c||k_("EDIT_TARGET",r,`${s} has no two faces along ${o}; there is no length to fill`);const l=X_(n,t,i,r)[o],h=l?void 0:function(t,e,n,i,s){const{shape:r}=j_(t,n,s),o="revolve@1"===r.op&&"taper"===r.params?.profile?{along:r.params.axis,radii:[r.args[3],r.args[2]]}:void 0;if(!o)return;const a=N_(t,e,n,s),c=rb[a[rb.indexOf(i)].findIndex(t=>0!==t)];if(c===o.along)return;const l=`${n}.width.${c}`;if(!z_(t,l)){const e=Q_(t,"mm",0,"d"),n=Q_(t,"ratio",2,"k"),[i,s]=o.radii;t.nodes.push({id:l,op:"affine-bounds@1",args:[e,e,i,n,e,s,n,e,e,e,e],outputs:{xmin:`${l}.unused.xmin`,xmax:`${l}.value`,ymin:`${l}.unused.ymin`,ymax:`${l}.unused.ymax`,zmin:`${l}.unused.zmin`,zmax:`${l}.unused.zmax`},params:{layout:"L0.1_1.0.0.0.0"}})}return`${l}.value`}(n,t,i,o,r);l||h||k_("EDIT_TARGET",r,`${i} has no two faces along ${o}; its copies cannot be spaced`);const{place:d,pose:u}=j_(n,i,r),p=z_(n,`${i}.seat.rigid`),f=K_(n,`${i}.row`),m=Q_(n,"mm",0,"d");p.args=p.args.map((t,e)=>e===a?ex(n,f,c.lo,"start"):t);const g=h||l.centred?m:ex(n,f,B_([...Y_(l.lo),...Y_(l.hi)]),"own-centre");u.args=u.args.map((t,e)=>e===a?g:t);const y=ex(n,f,[...c.hi,...B_(c.lo)],"length"),b=h??ex(n,f,[...l.hi,...B_(l.lo)],"extent"),v=Q_(n,"ratio",.5,"k"),_=Q_(n,"count",100,"limit"),x=e.repeat.count;n.nodes.push(void 0===x?{id:`${i}.layout`,op:"fit-pitch@1",args:[y,m,m,b,Z_(n,t,f,e.repeat.pitch,"pitch",r),v,_],outputs:{layout:`${i}.layout.value`}}:{id:`${i}.layout`,op:"fixed-count@1",args:[Q_(n,"count",x,"count"),y,m,m,b,v,_],outputs:{layout:`${i}.layout.value`}}),d.op="member@1",d.args=[d.args[0],z_(n,`${i}.turned`)?.outputs?.pose??u.outputs.pose],n.nodes.push({id:`${i}.assembly`,op:"assembly@1",args:[d.outputs.placed],outputs:{assembly:`${i}.assembly.value`}});const w=z_(n,`${s}.world`)?.outputs?.pose??z_(n,`${s}.chain`)?.outputs?.pose??z_(n,`${s}.turned`)?.outputs?.pose??z_(n,`${s}.pose`)?.outputs?.pose;let M=p.outputs.pose;w&&(n.nodes.push({id:`${i}.row`,op:"compose@1",args:[w,p.outputs.pose],outputs:{pose:`${i}.row.value`}}),M=`${i}.row.value`),n.nodes=n.nodes.filter(t=>t.id!==`${i}.chain`&&t.id!==`${i}.world`);const S=e.repeat.rise;n.nodes.push({id:`${i}.repeat`,op:"repeat@1",args:[`${i}.layout.value`,`${i}.assembly.value`,M,...S?[Q_(n,"mm",S.mm,"rise")]:[]],outputs:{collection:`${i}.repeat.value`},params:{axis:o,...S?{riseAxis:S.axis.toLowerCase()}:{}}})}function Ox(t,e){const n=t.document.model,i=e.body1.part;!function(t,e){const n=t.document.model,i=z_(n,e);if("member@1"!==i?.op||!z_(n,`${e}.repeat`))return;const s=z_(n,`${e}.layout`),r=z_(n,`${e}.repeat`)?.args[3],o=new Set([`${e}.layout`,`${e}.assembly`,`${e}.repeat`,`${e}.row`]),a=n.nodes.filter(t=>o.has(t.id)||t.id.startsWith(`${e}.row.`));n.nodes=n.nodes.filter(t=>!a.includes(t)),i.op="place@1";for(const e of[...s?.args??[],...r?[r]:[]])rx(t,e)}(t,i),z_(n,`${i}.motion`)&&zx(t,{part:i});const{pose:s,place:r}=j_(n,i,i),o=new Set([`${i}.seat.rigid`,`${i}.chain`,`${i}.world`,`${i}.turned`]);n.nodes=n.nodes.filter(t=>!o.has(t.id)&&!t.id.startsWith(`${i}.on.`));const a=Q_(n,"mm",0,"d"),c=s.args.slice(0,3);s.args=[a,a,a,...s.args.slice(3)],s.params={...s.params,to:t.document.capabilities.assetFrame};for(const e of c)rx(t,e,sx(n,i,e)?e:void 0);r.args=[r.args[0],s.outputs.pose]}function Px(t){const e=[];if(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}),t.travel){const n=t.travel;e.push({at:"travel",get:()=>Object.hasOwn(n,"sum")?{sum:n.sum,...void 0!==n.plus?{plus:n.plus}:{}}:n.source?{from:n.source,...void 0!==n.times?{times:n.times}:{},...void 0!==n.plus?{plus:n.plus}:{}}:n.plus??0,set:e=>{const n=I_(e);t.travel=n?n.sum?{sum:n.terms,...n.plus?{plus:n.plus}:{}}:{source:n.terms[0].from,...void 0!==n.terms[0].times?{times:n.terms[0].times}:{},...void 0!==e.plus?{plus:e.plus}:{}}:{plus:e}}})}for(const n of Object.keys(t.origin?.align??{})){const i=t.origin.align[n];i&&"object"==typeof i&&Object.hasOwn(i,"mm")&&e.push({at:`align.${n}`,get:()=>i.mm,set:t=>i.mm=t})}return e}function Ix(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:i}of Px(n))for(const s of I_(i())?.terms??[])"part"===s?.from?.of&&ix(t.document.model,s.from.part,s.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],i=new Map(t.map(t=>[t.body1.part,t]));for(;n.length<t.length;){const s=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?i.get(t.body0.part):void 0;return(!n||e.has(n.id))&&P_(t).every(t=>e.has(t.joint))});s.length||k_("JOINT_TREE","joints","the joints do not make a tree");for(const t of s)e.add(t.id),n.push(t)}return n}(e),i={...t.stateDefaults};for(const e of t.document.model.nodes)"member@1"!==e.op||z_(t.document.model,`${e.id}.repeat`)||(e.op="place@1");for(const e of[...n].reverse())Ox(t,e);for(const e of n)px(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const i=z_(n,`${t.body1.part}.assembly`),s=r=>{for(const o of e.filter(t=>"part"in t.body0&&t.body0.part===r)){if(o.repeat){const e=z_(n,`${o.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},i.args.push(e.outputs.collection);continue}const e=z_(n,o.body1.part);e.op="member@1",i.args.push(e.outputs.placed),s(o.body1.part)}};s(t.body1.part)}}(t,e);for(const e of n)"fixed"===e.type||e.mimic||void 0===i[dx(e)]||(t.stateDefaults[dx(e)]=i[dx(e)])}const Dx=(t,e)=>{const n=ox(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame};function zx(t,e){const n=t.document.model,i=z_(n,`${e.part}.motion`);i||k_("EDIT_TARGET",e.part,`${e.part} does not move`);const s=i.args[3],r=z_(n,`${e.part}.seat.rigid`)?.params?.to??i.params.to,o=n.inputs.find(t=>t.id===s&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(R_(n,s)?.args??[]).includes(t.id));return n.nodes=n.nodes.filter(t=>t!==i),lx(t,e.part,r),rx(t,s,s),o&&!n.nodes.some(t=>t.args.includes(o.id))&&(n.inputs=n.inputs.filter(t=>t!==o),delete t.stateDefaults[o.id],t.stateInputs&&delete t.stateInputs[o.id],t.drivers&&(t.drivers=t.drivers.filter(t=>t.state!==o.id)),t.drivers&&!t.drivers.length&&delete t.drivers,t.stateInputs&&!Object.keys(t.stateInputs).length&&delete t.stateInputs),t}const Rx=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};function jx(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,i=t.document.capabilities.bindings.map(t=>{const i="string"==typeof t.pose?null:t.pose,s=i?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===i.placement):null,r=i?R_(e,i.feature):null,o=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:s?.id??null,face:r?.params?.name??null,accepts:[...t.accepts],capacity:t.capacity,region:3===o.length&&o.every(t=>"number"==typeof t)?{x:o[0],y:o[1],z:o[2]}:null}}),s=A_(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),i=R_(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:i?.params?.name??null,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[...i,...s]}const Lx=(t,e,n)=>{throw new pb(t,e,n)};function Fx(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||Lx("SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||Lx("SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||Lx("SCHEMA",i,`unknown ${s}`)}const Nx=(t,e)=>{"string"==typeof t&&t.trim()||Lx("SCHEMA",e,"nonempty string required")};function $x(t,e){return function(t,e){const n=Nv(t),i=structuredClone(e),s=n.outputTypes,r=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),o=new Map;Fx(i,["version","assetFrame","bindings"],["names","slotLayout"],"capabilities"),"r3-capability-3"!==i.version&&Lx("VERSION","capabilities",i.version);if(Nx(i.assetFrame,"assetFrame"),void 0!==i.names){Array.isArray(i.names)||Lx("SCHEMA","names","array required");for(const t of i.names)ob.includes(t)||Lx("CAPABILITY_NAME","names",`${String(t)} is not one of ${ob.join(", ")}`);new Set(i.names).size!==i.names.length&&Lx("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(ab))i.names.includes(t)&&!e.some(t=>i.names.includes(t))&&Lx("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}Array.isArray(i.bindings)||Lx("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(Nx(t,e),Object.hasOwn(s,t)||Lx("TARGET_ABSENT",e,t),s[t]),l=(t,e,n)=>{const s=c(t,e);("transform"!==s.kind||s.to!==i.assetFrame||void 0!==n&&s.from!==n)&&Lx("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>Yv({types:s,writers:r,model:t,assetFrame:i.assetFrame},e,n),d=new Map;for(const t of i.bindings){Fx(t,["id","label","role","frame","pose","accepts","capacity"],["region","contacts"],"binding");for(const e of["id","label","frame"])Nx(t[e],e);if(a.has(t.id)&&Lx("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||Lx("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&&Lx("FRAME_TYPE",t.id,"binding frame must be the selected feature frame"),d.set(t.id,e)}if(Array.isArray(t.accepts)&&t.accepts.length||Lx("SCHEMA",t.id,"nonempty accepts required"),t.accepts.forEach(e=>Nx(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&Lx("SCHEMA",t.id,"duplicate accepted type"),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&Lx("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){Fx(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&Lx("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||Lx("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&Lx("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||Lx("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const i of t.contacts){const s=h(i,t.id),r=JSON.stringify([i.placement,i.feature]);e.has(r)&&Lx("DUPLICATE_CONTACT",t.id,r),e.add(r),n.push(s)}o.set(t.id,n)}}const u=[];if(void 0!==i.slotLayout){const t=i.slotLayout;Fx(t,["label","role","anchors","layout"],[],"slotLayout"),Nx(t.label,"slotLayout.label"),["seat","grip"].includes(t.role)||Lx("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),Array.isArray(t.anchors)&&t.anchors.length||Lx("SCHEMA","slotLayout.anchors","at least one anchor required");const e=new Map;t.anchors.forEach((t,n)=>{const i=`slotLayout.anchors[${n}]`;Fx(t,["id","frame","pose"],[],i),Nx(t.id,`${i}.id`),Nx(t.frame,`${i}.frame`),e.has(t.id)&&Lx("SCHEMA",`${i}.id`,`duplicate anchor ${t.id}`),"string"==typeof t.pose&&Lx("SLOT_LAYOUT_FACE",`${i}.pose`,"an anchor is a face of a part");const s=h(t.pose,i);s.frame!==t.frame&&Lx("FRAME_TYPE",i,"anchor frame must be the selected feature frame");const r=s.normal[1];r||Lx("SLOT_LAYOUT_FACE",`${i}.pose`,"an anchor is a horizontal face (its normal along Y)"),e.set(t.id,{surface:s,up:r})});const n=e_(t.layout,{anchors:e.keys()}),s=n.length?n:n_(t.layout);s.length&&Lx("SLOT_LAYOUT",`slotLayout.layout.${s[0].path}`,s.map(t=>`${t.code} at ${t.path}`).join("; "));for(const n of A_(t)){n.accepts.length||Lx("SCHEMA",n.id,"nonempty accepts required"),n.accepts.forEach(t=>Nx(t,n.id)),new Set(n.accepts).size!==n.accepts.length&&Lx("SCHEMA",n.id,"duplicate accepted type"),(!Number.isSafeInteger(n.capacity)||n.capacity<1)&&Lx("CAPACITY",n.id,"positive integer capacity required"),a.has(n.id)&&Lx("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=[...i.bindings,...u];function f(t,e){const n=t.pose.r,i=p_(e),s=[i.position.x,i.position.y*e.up,i.position.z],r=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*s[n],0)),o=i.rotation*Math.PI/180,a=Math.cos(o),c=Math.sin(o),l=[[a,0,c],[0,1,0],[-c,0,a]],h=n.map(t=>l[0].map((e,n)=>t.reduce((t,e,i)=>t+e*l[i][n],0)));return{...t,pose:{r:h,t:r}}}function m(t,e,n){const i=t=>function(t,e){const n=t[e.placement],i=t[e.feature],s=n.pose.r,r=s.map(t=>t.reduce((t,n,i)=>t+n*e.normal[i],0)),o=s.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*i.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,i=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);i||Hv("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=i.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:s.map(t=>[...t]),t:o},normal:r,provenance:"verified-planar-surface"}}(e,t);let s=null;if(t.allowed)s={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)&&Lx("REGION_DOMAIN",t.id,"positive region dimensions required"),s={kind:t.region.kind,dimensions:n}}let r={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];Fx(e,["type","occupied"],[],t.id+".request"),Nx(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&Lx("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const i=[];t.accepts.includes(e.type)||i.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&i.push("CAPACITY_FULL"),r={status:i.length?"failed":"satisfied",reasons:i}}const a=(o.get(t.id)??[]).map(i),c=d.has(t.id)?i(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:s,contacts:a,checks:{declaration:{status:"satisfied"},eligibility:r,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 Fx(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)),...(o.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(s),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={})=>{Fx(n,[],[...a],"requests");const i=Object.keys(n).length>0,s=e.advance(t,i?"REQUESTS":void 0);if("evaluation"===s.kind)return{...s,result:y(s.result,n)};if("changes"===s.kind){const t=p.filter(t=>i||s.structure||v.get(t.id).some(t=>s.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,s.read(t)])),n));return{...s,places:t}}const r=p.filter(t=>v.get(t.id).some(t=>s.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,s.read(t)])),n));return{kind:"poses",generation:s.generation,bodies:s.bodies,poses:s.poses,places:r}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const i=p.find(e=>e.id===t);return i||Lx("TARGET_ABSENT",t,"no such place"),Fx(n,[],[...a],"requests"),m(i,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const Hx=1048576;function Bx(t,e){throw new pb(t,"document",e)}function Yx(t){return(new TextEncoder).encode(t).byteLength}function Gx(t){const e=new Set;!function t(n,i){if(i>64&&Bx("DOCUMENT_LIMIT","nesting exceeds 64"),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||Bx("JSON_VALUE","nonfinite number"));"object"!=typeof n&&Bx("JSON_VALUE","only JSON values are allowed"),e.has(n)&&Bx("JSON_VALUE","cycle");const s=Array.isArray(n);s||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||Bx("JSON_VALUE","plain objects required"),e.add(n);const r=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(r)){if(s&&"length"===e)continue;"string"!=typeof e&&Bx("JSON_VALUE","symbols unsupported");const o=r[e];o.enumerable&&Object.hasOwn(o,"value")||Bx("JSON_VALUE","hidden properties and accessors unsupported"),!s||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||Bx("JSON_VALUE","extra array property"),t(o.value,i+1)}s&&Object.keys(n).length!==n.length&&Bx("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function Vx(t){if(Gx(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new pb("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new pb("VERSION","document","unsupported document version");if(Yx(JSON.stringify(t))>Hx)throw new pb("DOCUMENT_LIMIT","document","over 1 MiB");const e=t;if(!Array.isArray(e.model?.nodes)||e.model.nodes.length>8192)throw new pb("DOCUMENT_LIMIT","document","maximum 8192 nodes");return $x(e.model,e.capabilities)}const Ux=(t,e,n)=>{throw new pb(t,e,n)};function Wx(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function qx(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const i=n[n.length-1];if(e>=i.at)return i.value;let s=0;for(;s<n.length-2&&n[s+1].at<=e;)s++;const r=n[s],o=n[s+1];if("step"===t.interpolation)return r.value;const a=o.at-r.at;return r.value+(e-r.at)/a*(o.value-r.value)}function Xx(t,e,n="other"){Number.isFinite(e)||Ux("DRIVER_TIME",t.id,"finite time required");const i=Math.max(0,e),s=t.time.duration,r=t.keys[0].value,o=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=qx(t,Math.min(i/s,1));else{const e=Math.floor(i/s);a=qx(t,(i-e*s)/s),t.accumulates&&(a+=e*(o.value-r))}return t.accumulates?"deg"===n||"rad"===n?function(t,e){const n="deg"===e?360:2*Math.PI,i=n/2,s=((t+i)%n+n)%n-i;return s===i?-i:s}(a,n):Ux("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}const Kx=(t,e,n)=>{throw new pb(t,e,n)};function Qx(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||Kx("ASSET_SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||Kx("ASSET_SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||Kx("ASSET_SCHEMA",i,`unknown ${s}`)}function Jx(t){return function(t){Gx(t);const e=Zx(t);Yx(JSON.stringify(e))>Hx&&Kx("DOCUMENT_LIMIT","asset","over 1 MiB");Qx(e,["version","name","document","designInputs","stateDefaults","palette","appearance"],["occupancy","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs"],"asset"),void 0===e.placement||E_.includes(e.placement)||Kx("ASSET_SCHEMA","placement",`one of ${E_.join(", ")} required`);"figure-asset-1"!==e.version&&Kx("VERSION","asset",e.version);"string"==typeof e.name&&e.name.trim()||Kx("ASSET_SCHEMA","name","nonempty name required");const n=structuredClone(e),i=Vx(n.document),s=n.document.model,r=s.inputs.filter(t=>"state"!==t.role).map(t=>t.id),o=s.inputs.filter(t=>"state"===t.role).map(t=>t.id);Qx(n.designInputs,r,[],"designInputs"),void 0===n.detailLevel||(t=>cb.includes(t))(n.detailLevel)||Kx("ASSET_SCHEMA","detailLevel",`${String(n.detailLevel)} is not a detail level; ${cb.join(", ")}`);if(void 0!==n.sizing){"uniform"!==n.sizing&&Kx("ASSET_SCHEMA","sizing",`${String(n.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])s.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||Kx("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(Qx(n.stateDefaults,o,[],"stateDefaults"),void 0!==n.publicInputs){Array.isArray(n.publicInputs)||Kx("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,i]of n.publicInputs.entries()){const n=`publicInputs[${e}]`;Qx(i,["input","label"],["hint"],n),$v(s.inputs,i.input,`${n}.input`),"string"==typeof i.label&&i.label.trim()||Kx("ASSET_SCHEMA",`${n}.label`,"a name shown on the board"),void 0!==i.hint&&"string"!=typeof i.hint&&Kx("ASSET_SCHEMA",`${n}.hint`,"one line"),t.has(i.input)&&Kx("PUBLIC_INPUT",`${n}.input`,`${i.input} is listed twice`),t.add(i.input)}}n.palette&&"object"==typeof n.palette&&!Array.isArray(n.palette)||Kx("ASSET_SCHEMA","palette","token to hex color map required");for(const[t,e]of Object.entries(n.palette))t.trim()&&"string"==typeof e&&/^#[0-9a-f]{6}$/i.test(e)||Kx("PALETTE","palette","six digit hex color required");const a=t=>{"string"==typeof t&&Object.hasOwn(n.palette,t)||Kx("PALETTE",String(t),"unresolved color token")},c=new Map(s.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),l=new Map(s.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),h=new Map;Array.isArray(n.appearance)||Kx("ASSET_SCHEMA","appearance","array required");for(const t of n.appearance){if(Qx(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=i.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||Kx("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(l.has(t.target)&&!h.has(t.target)||Kx("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),Qx(t.material,["token"],["preset","transparent","emissive"],"material"),a(t.material.token),void 0===t.material.preset||["default","metal","glass","plastic","wood","ceramic","rubber"].includes(t.material.preset)||Kx("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&Kx("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;Qx(e,["token","intensity","on"],[],"emissive"),a(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&Kx("MATERIAL","emissive","invalid intensity or switch")}const e=c.get(l.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)||Kx("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&Kx("QUALITY","segments","segments unsupported on this provider"),h.set(t.target,t)}h.size!==l.size&&Kx("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==n.occupancy){if(Qx(n.occupancy,["bounds"],["contact"],"occupancy"),void 0!==n.occupancy.contact){const t=n.occupancy.contact;Qx(t,["plane","surface"],[],"occupancy.contact"),"mounting-plane"!==t.plane&&Kx("OCCUPANCY","occupancy.contact",`${String(t.plane)} is not a plane the figure can be mounted on`),Yv({types:i.outputTypes,writers:c,model:s,assetFrame:n.document.capabilities.assetFrame},t.surface,"occupancy.contact.surface")}Qx(n.occupancy.bounds,["x","y","z"],[],"occupancy.bounds");const t=JSON.stringify([1,0,0]);for(const e of["x","y","z"]){Qx(n.occupancy.bounds[e],["min","max"],[],`occupancy.bounds.${e}`);for(const s of["min","max"]){const r=`occupancy.bounds.${e}.${s}`,o=n.occupancy.bounds[e][s];"string"==typeof o&&JSON.stringify(i.outputTypes[o])===t||Kx("OCCUPANCY",r,`${String(o)} is not a length value in the graph`),i.dependence[o]?.length&&Kx("OCCUPANCY_STATE",r,`${o} depends on state input ${i.dependence[o].join(", ")}; the occupancy is state-independent`)}}}(function(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||Ux("DRIVER","drivers","array required");const n=Wx(t),i=new Set,s=new Set,r=new Map;for(const t of e){const e=`drivers.${String(t?.id??"?")}`,o=t=>t&&"object"==typeof t?Object.keys(t).sort():null;JSON.stringify(o(t))!==JSON.stringify(["accumulates","clip","id","interpolation","keys","loop","state","time"])&&Ux("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||Ux("DRIVER",e,"id required"),i.has(t.id)&&Ux("DRIVER",e,"duplicate driver id"),i.add(t.id),"string"==typeof t.clip&&t.clip.trim()||Ux("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||Ux("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`),s.has(t.state)&&Ux("DRIVER_STATE",e,`two drivers write ${t.state}; one writer per state`),s.add(t.state),JSON.stringify(o(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||Ux("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||Ux("DRIVER_TIME",e,"positive duration in seconds required");const a=r.get(t.clip);void 0===a?r.set(t.clip,t.time.duration):a!==t.time.duration&&Ux("DRIVER_TIME",e,`clip "${t.clip}" already runs for ${a} s; one clip is one clock, so every driver in it shares a duration`),(!Array.isArray(t.keys)||t.keys.length<2)&&Ux("DRIVER_KEYS",e,"at least two keys required");let c=-1/0;for(const n of t.keys)JSON.stringify(o(n))!==JSON.stringify(["at","value"])&&Ux("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||Ux("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>c||Ux("DRIVER_KEYS",e,"key at values must strictly increase"),c=n.at,Number.isFinite(n.value)||Ux("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&Ux("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||Ux("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||Ux("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&Ux("DRIVER",e,"accumulates must be a boolean");const l=n.get(t.state);t.accumulates&&"deg"!==l&&"rad"!==l&&Ux("DRIVER_STATE",e,`an accumulating driver writes an angle; ${t.state} is in ${l}`)}})(n),function(t){const e=t.stateInputs;if(void 0===e)return;e&&"object"==typeof e&&!Array.isArray(e)||Ux("STATE_INPUT","stateInputs","object required");const n=Wx(t);for(const[t,i]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||Ux("STATE_INPUT",e,`${t} is not a state input of this asset`),i&&"object"==typeof i&&!Array.isArray(i)||Ux("STATE_INPUT",e,"object required");for(const t of Object.keys(i))"label"!==t&&"sweep"!==t&&Ux("STATE_INPUT",e,`unknown ${t}`);void 0===i.label||"string"==typeof i.label&&i.label.trim()||Ux("STATE_INPUT",e,"label must be a nonempty string"),void 0===i.sweep||Number.isFinite(i.sweep)&&i.sweep>=0||Ux("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(n),void 0===n.joints||Array.isArray(n.joints)||Kx("ASSET_SCHEMA","joints","joints is a list");function d(t={}){Qx(t,[],o,"state overrides");const e={...n.designInputs,...n.stateDefaults,...t},s=i.evaluate(e),r=t=>t.key?c.get(t.key)?.id:t.id,a=new Map(n.appearance.map((t,e)=>[t.target,e])),l=s.geometry.map((t,e)=>({g:t,i:e,at:a.get(r(t))??Number.MAX_SAFE_INTEGER})).sort((t,e)=>t.at-e.at||t.i-e.i).map(t=>t.g).map(t=>{const e=r(t),n=h.get(e);return n||Kx("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(n.material),visible:void 0===n.visibility||s.values[n.visibility],...void 0!==n.segments?{segments:n.segments}:{}}});return{...s,geometry:l,inputs:e,palette:structuredClone(n.palette)}}return function(t){const e=t.joints;if(!e?.length)return;const n=structuredClone(t);for(const t of e)ux({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);Ix(n);const i=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)});i(n.document.model)!==i(t.document.model)&&k_("JOINT_DRIFT","joints","the joints' nodes are not what their records make; the asset was edited apart from its joints")}(n),d(),{evaluate:d}}(t)}function Zx(t){const e=t,n=e?.occupancy&&"object"==typeof e.occupancy?e.occupancy.placement:void 0;if(void 0===n)return t;void 0!==e.placement&&e.placement!==n&&Kx("PLACEMENT_CONFLICT","placement",`the asset says ${String(e.placement)} and its room says ${String(n)}; keep one`);const{placement:i,...s}=e.occupancy;return{...e,placement:n,occupancy:s}}const tw="0.4.3";function ew(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 nw=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"]:null,t.segments??null,ew(t),!1!==t.visible]);function iw(t,e){const n=function(t,e){const n=e??Vx(t.document).dependence,i=new Map(t.document.model.nodes.map(t=>[t.id,t])),s=Wv(t),r=t=>{const e=void 0===t?void 0:i.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!r("string"==typeof n?.[0]?n[0]:t.id)||!!e&&r(s.get(e))}}(t,e),i=Wv(t),s=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target));return t=>{const e=new Set;for(const r of t){if(!("pose"in r)||n(r))continue;const t=r.key?i.get(r.key):r.id;void 0!==t&&s.has(t)||e.add(r.id)}return e}}const sw=t=>`${ew(t)}|${!1!==t.visible?"shown":"hidden"}`;function rw(t,e={}){const n=[],i=new Map;for(const e of t){if(!("pose"in e))continue;const t="key"in e&&"string"==typeof e.key?e.key:void 0;if(!t){n.push(e.id);continue}const s=i.get(t)??[];s.push(e),i.set(t,s)}const s=[],r=[];for(const[t,e]of i){const i=new Map;for(const t of e){const e=nw(t),n=i.get(e);n?n.push(t.id):i.set(e,[t.id])}for(const[o,a]of i)a.length>1?s.push({key:`${t}|${o}`,member:t,ids:a}):(n.push(...a),r.push({member:t,ids:a,reason:1===e.length?"one-copy":"copies-differ"}))}const o=[];if(e.still?.size){const i=new Map(t.map(t=>[t.id,t])),s=new Map;for(const t of n){const n=i.get(t);if(!n||!e.still.has(t)||n.material.transparent)continue;const r=sw(n),o=s.get(r);o?o.push(t):s.set(r,[t])}const r=new Set;for(const[t,e]of s)e.length<2||(o.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 a=[];if(e.carried?.size){const i=new Map(t.map(t=>[t.id,t])),s=new Map;for(const t of n){const n=i.get(t),r=e.carried.get(t);if(!n||void 0===r||e.still?.has(t)||n.material.transparent)continue;const o=`${r}|${sw(n)}`,a=s.get(o);a?a.ids.push(t):s.set(o,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of s)n.length<2||(a.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)))}return{batches:s,merged:o,carried:a,alone:n,unbatched:r}}const ow=lb[0];function aw(t,e,n,i={}){const[s,r]=fb[e],o=i[s]??0,a=i[r]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[s],t[r]]);else if("ellipse"===t.kind){const e=t.radius[s],i=t.radius[r];c=Array.from({length:n},(t,s)=>{const r=2*Math.PI*s/n;return[e*Math.cos(r),i*Math.sin(r)]})}else{const e=t.size[s]/2,n=t.size[r]/2,i=t.corner?.[s]??0,o=t.corner?.[r]??0;if(i>0&&o>0){c=[];for(const[t,s,r]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=ow;a++){const l=r+a/ow*(Math.PI/2);c.push([t*(e-i)+i*Math.cos(l),s*(n-o)+o*Math.sin(l)])}}else c=[[-e,-n],[e,-n],[e,n],[-e,n]]}return c=c.map(([t,e])=>[t+o,e+a]),cw(c)<0?c.reverse():c}const cw=t=>t.reduce((e,n,i)=>e+n[0]*t[(i+1)%t.length][1]-t[(i+1)%t.length][0]*n[1],0)/2;function lw(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]),i=[];for(const t of e){for(;i.length>=2&&n(i[i.length-2],i[i.length-1],t)<=1e-9;)i.pop();i.push(t)}const s=[];for(let t=e.length-1;t>=0;t--){const i=e[t];for(;s.length>=2&&n(s[s.length-2],s[s.length-1],i)<=1e-9;)s.pop();s.push(i)}return i.slice(0,-1).concat(s.slice(0,-1))}const hw=t=>"shape"in t&&"pose"in t&&!!t.shape;function dw(t,e,n,i={}){const[s,r]=fb.y;return aw(t,"y",n,i).map(([t,n])=>{const i={x:0,y:e,z:0};return i[s]=t,i[r]=n,[i.x,i.y,i.z]})}const uw=[{id:"__default__",maxCount:1/0}];function pw(t){const e={id:l_({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function fw(t,e){const n=e?.state?.type??e?.type;return t.accepts?!!n&&t.accepts.includes(n):!t.allowedTypes?.length||!!n&&t.allowedTypes.includes(n)}function mw(e){var n;return n=class extends e{get slotLayout(){}get slots(){const t=this.slotLayout;if(!t)return[];const e=[];for(const n of d_(t)){const i=c_(t,n);i&&e.push(pw(i))}return e}slotById(t){const e=this.slotLayout;if(e){const n=h_(t),i=n?c_(e,n):null;return i?pw(i):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,i){const s=this.slotLayout,r=s?h_(t):null,o=r?c_(s,r):null,a=o?b_(e,o,n,i):null;return a?{...a,anchorId:o.anchorId}:null}get arrangementStrategy(){return sb}canReceive(t,e){const n=null!==(void 0!==e?.slotId?this._slotIfAvailable(this.slotById(e.slotId),t):this.findSlot(t));return Gu.log({role:"target",contract:"canReceive",component:this,args:{carrier:Qy(t)},result:n}),n}findSlot(t){const e=this.slots.length?this.slots:uw;for(const n of e){if(!fw(n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),i=this._countOccupied(n.id);if(!(i>=e))return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:{slotId:n.id,occupied:i,max:e}}),n}return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:null}),null}acceptanceRotation(t,e){}deliveryWorldRotation(e){const n=this.acceptanceRotation?.(e);if(!n)return;const i=this._realObject?.object3d;if(!i)return;i.updateWorldMatrix(!0,!1);const s=new t.Quaternion;i.getWorldQuaternion(s);const r=new t.Quaternion(n.x,n.y,n.z,n.w);return s.clone().multiply(r)}deliveryWorldPosition(e){const n=this._realObject,i=n?.object3d;if(!i)return;i.updateWorldMatrix(!0,!1);const s=new t.Vector3;i.getWorldPosition(s);const r=this._receivingSurfaceLocalY();if(null!==r){const e=new t.Vector3(0,r,0);return i.localToWorld(e),{x:s.x,y:e.y,z:s.z}}return{x:s.x,y:s.y,z:s.z}}attachPointFor(t){const e=t?.[tb];if(!e)return null;const n=this.slots.find(t=>t.id===e);return n?{position:n.localPosition??{x:0,y:0,z:0},rotation:n.localRotation??{x:0,y:0,z:0},slotId:n.id}:null}placementFor(t,e={}){const n=t&&"object"==typeof t&&"state"in t?t:void 0,i=n?n.state??{}:t??{},s={width:Number(i.width)||0,height:Number(i.height)||0,depth:Number(i.depth)||0},r=e.slot??this.slots.find(t=>{const e=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<e});if(!r)return null;const o=e.index??this._countOccupied(r.id),a=e.occupantCount??o,c=this.arrangementStrategy.positionAt(o,r,a,n??{state:{...s}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+s.width/2-l/2,u=c.y+s.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-s.depth/2:s.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:r.localPosition&&Number.isFinite(r.localPosition.z)?r.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??s,r)??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 i=this._realObject,s=i?.receivingSurfaceY??0,r=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===s&&!r)return null;const o=Number(e)||0,a=i?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-o/2:o/2)+(i?.geometricOffsetY??0)-s}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!fw(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?.[tb]===t).length;const n=this.components;return n?n.filter(e=>e.parent===this&&e[tb]===t).length:0}},n.__hasCapacity=!0,n}function gw(t,e){const n=t.left??0,i=t.top??0,s=t.width??0,r=t.height??0;if(s<=0||r<=0)return[];const o="number"==typeof t.rotation?t.rotation:0,a=Math.cos(o),c=Math.sin(o),l=n+s/2,h=i+r/2,d="inbound"===e?-1:1;return[{lx:-s/2,lz:0,odx:-1,odz:0},{lx:s/2,lz:0,odx:1,odz:0},{lx:0,lz:-r/2,odx:0,odz:-1},{lx:0,lz:r/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?r/2:s/2}})}function yw(t,e){const n=t.left??0,i=t.top??0,s=t.width??0,r=t.height??0;if(s<=0||r<=0)return{inbounds:[],outbounds:[]};const o="number"==typeof t.rotation?t.rotation:0,a=e??"reverse"===t.status,c="vertical"===t.orientation||"horizontal"!==t.orientation&&s<r,l=n+s/2,h=i+r/2,d=c?r/2:s/2,u=c?0:1,p=c?1:0,f=Math.cos(o),m=Math.sin(o),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?s:r)/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 bw(t){const e=t.left??0,n=t.top??0,i=t.width??0,s=t.height??0;if(i<=0||s<=0)return null;const r="number"==typeof t.rotation?t.rotation:0,o="vertical"===t.orientation||"horizontal"!==t.orientation&&i<s,a=e+i/2,c=n+s/2,l=o?s/2:i/2,h=Math.cos(r),d=Math.sin(r),u=(t,e)=>({x:a+t*h-e*d,z:c+t*d+e*h});return{start:o?u(0,-l):u(-l,0),end:o?u(0,l):u(l,0)}}function vw(t){const e=t.cx??0,n=t.cy??0,i=Math.abs(t.rx??100),s=Math.abs(t.ry??100),r=t.ratio??50,o=(i+i*r/100)/2,a=(s+s*r/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(i<=0||s<=0)return{inbounds:[],outbounds:[]};const d={x:e+o*Math.sin(c),z:n-a*Math.cos(c)},u={x:e+o*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 _w(t){const e=yw(t),n=e.outbounds[0];if(!n)return{inbounds:gw(t,"inbound"),outbounds:[]};const i=gw(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,i=t.worldPos.z-n.worldPos.z;return Math.hypot(e,i)>1}),s=n.direction,r=[];for(const t of i){const e=t.direction.x*s.x+t.direction.z*s.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+s.x,i=t.direction.z+s.z,o=Math.hypot(n,i)||1;r.push({worldPos:t.worldPos,direction:{x:n/o,z:i/o},halfSpan:t.halfSpan})}return{inbounds:[...i,...r],outbounds:e.outbounds}}function xw(t,e,n={}){const i=n.distance??5,s=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<s)return!1;const r=t.worldPos.x-e.worldPos.x,o=t.worldPos.z-e.worldPos.z;if("number"==typeof t.halfSpan&&"number"==typeof e.halfSpan){const n=t.direction.x,s=t.direction.z;if(Math.abs(r*n+o*s)>i)return!1;const a=Math.abs(r*-s+o*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(r,o)<=i}function ww(t,e,n,i=0){const s=n.width??0,r=n.height??0;if(s<=0||r<=0)return!1;const o=(n.left??0)+s/2,a=(n.top??0)+r/2,c="number"==typeof n.rotation?n.rotation:0,l=Math.cos(-c),h=Math.sin(-c),d=t-o,u=e-a,p=d*l-u*h,f=d*h+u*l;return Math.abs(p)<=s/2+i&&Math.abs(f)<=r/2+i}function Mw(t,e,n){const i=n.width??0,s=n.height??0;if(i<=0||s<=0)return 1/0;const r=(n.left??0)+i/2,o=(n.top??0)+s/2;let a=t.x-r,c=t.z-o,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,i=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=i}const u=i/2,p=s/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 Sw(t,e,n,i=6){return!!ww(t.worldPos.x,t.worldPos.z,e,i)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function Aw(t,e,n){return t.outbounds.map(t=>{const i=[];for(const s of e){let e=null;for(const i of s.topology.inbounds){if(!xw(t,i,n))continue;const s=t.worldPos.x-i.worldPos.x,r=t.worldPos.z-i.worldPos.z,o=Math.hypot(s,r);(null===e||o<e)&&(e=o)}if(null===e&&s.bounds){const i=s.topology.outbounds[0]?.direction,r=!(s.topology.outbounds&&s.topology.outbounds.length)?n?.sinkMargin??30:6;if(Sw(t,s.bounds,i,r)){const n=Mw(t.worldPos,t.direction,s.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(s.bounds.left??0)+(s.bounds.width??0)/2,i=(s.bounds.top??0)+(s.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-i)+1e3}}}null!==e&&i.push({id:s.id,dist:e})}return 0===i.length?null:(i.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),i[0].id)})}function Ew(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const i=new Map,s=new Set;for(const n of t){const r=t.filter(t=>t.id!==n.id),o=Aw(n.topology,r,e);i.set(n.id,o);for(const t of o)null!=t&&s.add(t)}const r=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const r=i.get(t)??[];r.includes(e)||(r.push(e),i.set(t,r),s.add(e))};for(const e of t)if(e.links){for(const t of e.links.downstream??[])r(e.id,t);for(const t of e.links.upstream??[])r(t,e.id)}const o=new Set,a=new Set;for(const e of t){(i.get(e.id)??[]).some(t=>null!=t)||o.add(e.id),s.has(e.id)||a.add(e.id)}return{nodes:n,out:i,sinks:o,sources:a}}function kw(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const i=new Set([e]);for(const s of function(t,e,n){const i=n.get(e);if(i)return i;const s=new Set,r=[e],o=new Set([e]);for(;r.length;){const e=r.shift();for(const n of t.out.get(e)??[])null!=n&&(s.add(n),o.has(n)||(o.add(n),r.push(n)))}return n.set(e,s),s}(t,e,n))i.add(s);return i})}function Cw(t,e,n,i){return e===n?0:function(t,e,n){const i=n.get(e);if(i)return i;const s=new Map([[e,0]]),r=[e];for(;r.length;){const e=r.shift(),n=s.get(e);for(const i of t.out.get(e)??[])null==i||s.has(i)||(s.set(i,n+1),r.push(i))}return n.set(e,s),s}(t,e,i).get(n)??1/0}function Tw(t,e,n){const i=t.out.get(e)??[],s=new Map,r=[];for(let e=0;e<i.length;e++){const o=i[e];if(null==o)continue;const a=o===n?0:Cw(t,o,n,s);a!==1/0&&r.push({i:e,hops:1+a})}return r.sort((t,e)=>t.hops-e.hops||t.i-e.i),r.map(t=>t.i)}function Ow(t,e,n){const i=Tw(t,e,n);return i.length?i[0]:-1}function Pw(t,e,n){return e===n||Tw(t,e,n).length>0}function Iw(t,e){const n=new Set;for(const i of kw(t,e))for(const e of i)t.sinks.has(e)&&n.add(e);return n}function Dw(t,e,n){return zw(t,e,n).map(t=>t.index)}function zw(t,e,n){const i=n instanceof Set?n:new Set(n);if(0===i.size)return[];const s=t.out.get(e)??[],r=new Map,o=[...i].sort(),a=[];for(let e=0;e<s.length;e++){const n=s[e];if(null==n)continue;let i=1/0,c="";for(const e of o){const s=1+(n===e?0:Cw(t,n,e,r));s<i&&(i=s,c=e)}i!==1/0&&a.push({index:e,hops:i,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function Rw(t,e={}){const n=[],i=e.loopCapableIds??new Set,s=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const i=t.nodes.get(e);if(!i||!i.topology.outbounds?.length)continue;(t.out.get(e)??[]).some(t=>null!=t)||n.push({severity:"error",code:"orphan-source",nodeId:e,message:`source 노드 "${e}" 가 outgoing edge 0 — 아무 데도 carrier 를 보낼 수 없음`})}for(const e of[...t.nodes.keys()].sort()){(t.out.get(e)??[]).some(t=>null!=t)||(s.has(e)||t.sources.has(e)||n.push({severity:"error",code:"dead-end",nodeId:e,message:`노드 "${e}" 가 outgoing 0 인데 RoutingTarget 자격 없음 — routing 미정의 종착`}))}const r=function(t){const e=[],n=[...t.nodes.keys()].sort(),i=new Set,s=[],r=new Set,o=n=>{i.add(n),s.push(n),r.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(r.has(a)){const t=s.indexOf(a),n=s.slice(t),i=n.indexOf([...n].sort()[0]),r=[...n.slice(i),...n.slice(0,i)],o=r.join("→");e.some(t=>t.join("→")===o)||e.push(r)}else i.has(a)||o(a);s.pop(),r.delete(n)};for(const t of n)i.has(t)||o(t);return e.sort((t,e)=>t[0].localeCompare(e[0])||t.length-e.length),e}(t);for(const t of r){const e=t.some(t=>i.has(t));e||n.push({severity:"error",code:"cycle",cycle:t,message:`의도 cycle 자격 (isLoop) 없는 cycle: ${t.join(" → ")} → ${t[0]}`})}const o=e.routingWeights;if(o)for(const[t,e]of[...o].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[...s].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 jw(t,e){if(!t)return[];const n=[],i=new Set,s=t=>{if(!t||i.has(t))return;if(i.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,i=t.refid??t.state?.refid,s="string"==typeof e&&e.length>0?e:null!=i?String(i):void 0;if(s)try{const e=t.getSegmentTopology(),i=t.state??{},r={left:i.left,top:i.top,width:i.width,height:i.height,rotation:i.rotation};e&&n.push({id:s,topology:e,bounds:r})}catch{}}const r=t?.components;if(Array.isArray(r))for(const t of r)s(t)};return s(t),n}function Lw(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 i=t.getSegmentTopology();if(!i||0===i.outbounds.length)return null;const s=Aw(i,jw(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),e);for(const t of s)if(t)return t;return null}function Fw(t){return!!t&&"function"==typeof t.routingConstraints}function Nw(t){return!!t&&"function"==typeof t.acceptedCarrierData}function $w(t,e=16){const n=[],i=t.parent??t.rootModel??t.root;if(!i)return n;const s=Lw(t);if(!s)return n;const r=Yw(i,s);if(!r)return n;const o=[{segment:r,accumulated:{},pathIds:[s],visited:new Set([s])}];for(;o.length>0;){const t=o.shift();if(t.pathIds.length>e)continue;const s=Fw(t.segment)?t.segment.routingConstraints():null;if(s&&s.length>0)for(const e of s)for(const s of e.candidates){const r=Hw(t.accumulated,s);if(!r)continue;const a=Bw(t.segment,e.portId,i);a&&!t.visited.has(a.state?.id??"")?o.push({segment:a,accumulated:r,pathIds:[...t.pathIds,a.state?.id??"?"],visited:new Set([...t.visited,a.state?.id??""])}):n.push({data:r,weight:1,pathIds:[...t.pathIds,`${e.portId}`],destination:e.portId})}else{if(Nw(t.segment)){const e=t.segment.acceptedCarrierData(),i=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:i});else for(const s of e){const e=Hw(t.accumulated,s);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:i})}continue}const e=Lw(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 s=Yw(i,e);if(!s)continue;o.push({segment:s,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function Hw(t,e){const n={...t};for(const[t,i]of Object.entries(e)){if(t in n&&n[t]!==i)return null;n[t]=i}return n}function Bw(t,e,n){if("straight"===e&&t.state?.downstreamRef)return Yw(n,t.state.downstreamRef);const i=Yw(n,e);if(i)return i;const s=Lw(t);return s?Yw(n,s):null}function Yw(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,i=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const s=t.components;if(Array.isArray(s))for(const t of s){const e=i(t);if(e)return e}return null};return i(t)}function Gw(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function Vw(t,e,n=5,i=[],s=n){const r=t.length,o=new Array(r).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 i){const e=Array.isArray(t),n=e?t:t.positions,i=e?void 0:t.kind;if(!n.length)continue;const s=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:s});i&&u.set(s,i)}const p=(t,e)=>{const i=c(t,e),s=h.get(`${t}:${"end"===e?"start":"end"}`),r=[];for(const t of d)Gw(t.pos,i)<=n&&!r.includes(t.pt)&&r.push(t.pt);for(let t=0;t<l.length;t++)Gw(l[t].pos,i)<=n&&!r.includes(t)&&r.push(t);let o=r.find(t=>t!==s)??-1;o<0&&(o=l.length,l.push({pos:i,members:[]})),l[o].members.push({seg:t,end:e}),h.set(`${t}:${e}`,o)};for(let t=0;t<r;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 i=0;i<l.length;i++){const s=Gw(l[i].pos,t);s<n&&(n=s,e=i)}for(const i of d){const s=Gw(i.pos,t);s<n&&(n=s,e=i.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:i}=t(n.pos);e>=0&&i<=s&&(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!==o[t],b=[],v=(e,n)=>{if(void 0===o[e])return o[e]=n,void b.push(e);o[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 i=l[n];if(2!==i.members.length||f.has(n))continue;const s=i.members[0],r=s.seg===t&&s.end===e?i.members[1]:s;if(r.seg===t)continue;const a="end"===e!==o[t],c="end"===r.end!==!a;v(r.seg,c)}},x=()=>{for(;b.length;)_(b.shift())},w=t=>{let e=-1,n="start",i=1/0;for(let s=0;s<r;s++)for(const r of["start","end"]){const o=Gw(c(s,r),t.pos);o<i&&(i=o,e=s,n=r)}if(e<0||i>s)return;const o="source"===t.kind?"end"===n:"start"===n;v(e,o)};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===o[t.seg]);if(1!==e.length)continue;let n=0,i=0;for(const e of t.members)void 0!==o[e.seg]&&(y(e.seg,e.end)?n++:i++);const s=e[0];let r;0===i&&n>0?r="end"===s.end:0===n&&i>0&&(r="start"===s.end),void 0!==r&&(o[s.seg]=r,b.push(s.seg),x(),M=!0)}}if(o.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 i of t)e[i]=0,n.push(i);for(;n.length;){const t=n.shift();for(const i of l[t].members){const s=h.get(`${i.seg}:${"start"===i.end?"end":"start"}`);void 0!==s&&e[s]>e[t]+1&&(e[s]=e[t]+1,n.push(s))}}return e},e=t(m),n=t(g);for(let t=0;t<r;t++){if(void 0!==o[t])continue;const i=h.get(`${t}:start`),s=h.get(`${t}:end`);if(void 0===i||void 0===s)continue;if(l[i].members.length<2||l[s].members.length<2)continue;if(e[i]===1/0||e[s]===1/0||n[i]===1/0||n[s]===1/0)continue;let r;e[i]!==e[s]?r=e[i]<e[s]:n[i]!==n[s]&&(r=n[s]<n[i]),void 0!==r&&(o[t]=!r,b.push(t))}x()}const S=new Map;for(let e=0;e<r;e++)S.set(t[e].id,void 0===o[e]?"unknown":o[e]?"reverse":"forward");return{directions:S,conflicts:[...a]}}function Uw(...t){}function Ww(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function qw(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*Xw(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*Xw(t)}function Kw(t,e,n){const i=e.width??0,s=e.height??0;if(i<=0||s<=0)return!1;const r=(e.left??0)+i/2,o=(e.top??0)+s/2,a="number"==typeof e.rotation?e.rotation:0,c=t.x-r,l=t.z-o,h=Math.cos(-a),d=Math.sin(-a),u=c*h-l*d,p=c*d+l*h;return Math.abs(u)<=i/2+n&&Math.abs(p)<=s/2+n}function Qw(t){const e=[],n=[],i=[],s=[];for(const r of Xw(t)){const t=qw(r);if(!t)continue;if(r.flowOrientable){const n=bw(r.state??{});n&&e.push({id:t,start:n.start,end:n.end});continue}if("function"==typeof r.openings){const t=r.state??{};(t.width??0)>0&&(t.height??0)>0&&s.push(t);continue}let o;try{o=r.getSegmentTopology()}catch{continue}if(!o)continue;const a=o.inbounds??[],c=o.outbounds??[],l="function"==typeof r.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&&i.push({positions:t})}}for(const t of s){const s=[];for(const n of e)for(const e of[n.start,n.end])Kw(e,t,16)&&s.push(e);let r=!1,o=!1;for(const e of n)Kw(e.pos,t,16)&&("sink"===e.kind?r=!0:o=!0);const a=r&&!o?"sink":o&&!r?"source":void 0;(s.length>=2||a&&s.length>=1)&&i.push({positions:s,kind:a})}if(0===e.length||0===n.length)return new Map;return Vw(e,n,8,i,60).directions}function Jw(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:Qw(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const i=qw(t),s=i?n.map.get(i):void 0;return"reverse"===s||"forward"!==s&&void 0}function Zw(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function tM(t,e,n,i){if(!t||!e)return null;const s=[],r=t=>{if(!t||t===i)return;if(Wm(t,e)&&Zw(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&&s.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const o=t.components;if(Array.isArray(o))for(const t of o)r(t)};return r(t),0===s.length?null:(s.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),s[0])}function eM(t){return!!t&&"function"==typeof t.routingDestination}function nM(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*iM(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*iM(t)}function sM(t){const e=[],n=new Map,i=new Map,s=new Set,r=[];for(const o of iM(t)){"function"==typeof o?.registerWithHost&&r.push(o);const t="function"==typeof o?.getSegmentTopology,a="function"==typeof o?.routingLinks?o.routingLinks():void 0,c=!(!a||!((a.downstream?.length??0)>0||(a.upstream?.length??0)>0));if(!(t||eM(o)||c||Zw(o)))continue;const l=nM(o);if(!l)continue;let h={inbounds:[],outbounds:[]};if(t){try{h=o.getSegmentTopology()}catch{continue}if(!h)continue}const d=o.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}),i.set(l,o),eM(o)){s.add(l);const t=o.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:i,routingTargetIds:s,stationClients:r}}function rM(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:i,components:s,routingTargetIds:r,stationClients:o}=sM(t),a=Ew(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 i=[...e].sort((t,e)=>{const n=nM(t)??"",i=nM(e)??"";return n.localeCompare(i)});for(const e of i){const n=e.declaredHostRef?.();let i=null;if(n&&(i=t.findById?.(n)??null),!i){const n=e.hostCapability?.(),s=e.hostFacingPoint?.();n&&s&&(i=tM(t,n,s,e)?.component??null)}i&&"function"==typeof e.registerWithHost&&e.registerWithHost(i)}const s=e=>{if(!e)return;if(Zw(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const i=t.findById?.(n);i&&e.registerDivertStation(n,i)}const n=e.components;if(Array.isArray(n))for(const t of n)s(t)};s(t)}(t,o);const c=new Set;for(const[t,e]of s){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of r){const e=s.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=Rw(a,{routingTargetIds:r,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:i,components:s,issues:h},t.__flowGraph=e}return e}function oM(t){return rM(t)?.issues??[]}function aM(t){const e=rM(t);return e&&e.graph.nodes.size>0?e.graph:null}function cM(t,e){return rM(t)?.destToSinks.get(e)??[]}function lM(t,e){return rM(t)?.components.get(e)}function hM(t){const e=rM(t);return e?[...e.destToSinks.keys()]:[]}function dM(t){return nM(t)}function uM(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 pM(t,e,n,i,s){if(1===i.length)return i[0];switch(t){case"index":default:return i[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),i[t%i.length]}case"weight":{const t=i.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}(s.get(t.target))),r=t.reduce((t,e)=>t+e,0);if(r<=0)return i[0];const o=n.counters.get(e)??0;n.counters.set(e,o+1);let a=o%r;for(let e=0;e<i.length;e++){if(a<t[e])return i[e];a-=t[e]}return i[i.length-1]}case"utilization":{let t=1/0,e=i[0];for(const n of i){const i=uM(s.get(n.target));i<t&&(t=i,e=n)}return e}}}function fM(t,e,n){const i=t?.root;if(!i)return null;const s=e?.state?.meta?.destination;if("string"!=typeof s||0===s.length)return null;const r=rM(i);if(!r||0===r.graph.nodes.size)return null;const o=nM(t);if(!o)return null;let a=r.destToSinks.get(s)??[];0===a.length&&(a=[s]);const c=zw(r.graph,o,a);if(0===c.length)return null;const l=r.graph.out.get(o)??[],h=c.filter(t=>{const n=l[t.index],i=n?r.components.get(n):null;return!i||"function"!=typeof i.canReceive||i.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 i=e?.state?.routingBalancingPolicy;return i||"round-robin"}(t,i),u=pM(d,o,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(i),h,r.components);return l[u.index]??null}Km({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"}),Km({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,aM(t)}catch{return null}}}catch{}function mM(t,e,n){const i=fM(t,e,n);if(null==i)return null;const s=t?.root,r=lM(s,i)??s?.findById?.(i)??null;return r?{targetId:i,component:r,origin:"explicit"}:null}function gM(t){const e=t?.root,n=aM(e),i=dM(t);if(!n||!i)return null;const s=(n.out.get(i)??[]).find(Boolean);if(!s)return null;const r=lM(e,s)??e?.findById?.(s)??null;return r?{id:s,component:r}:null}function yM(t){const e=dM(t);return e?bM(t?.root,e):[]}function bM(t,e){if(!t||!e)return[];const n=aM(t);if(!n)return[];const i=new Set;for(const s of Iw(n,e)){const e=lM(t,s);if(eM(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&i.add(t)}}return[...i]}function vM(t,e){if(!t||!e)return[];const n=aM(t);if(!n)return[];const i=new Map;for(const t of n.out.values())for(const e of t)null!=e&&i.set(e,(i.get(e)??0)+1);const s=new Map;for(const r of Iw(n,e)){const e=lM(t,r);if(!eM(e))continue;const n=e.routingDestination();if("string"!=typeof n||0===n.length)continue;let o=null;if("function"==typeof e.routingWeight){const t=e.routingWeight();"number"==typeof t&&Number.isFinite(t)&&t>0&&(o=t)}null===o&&(o=i.get(r)??0,0===o&&(o=1)),s.set(n,(s.get(n)??0)+o)}return[...s].map(([t,e])=>({value:t,weight:e}))}function _M(t){return aM(t)}function xM(t){const e=aM(t);if(!e)return[];const n=new Set,i=new Set,s=t=>{if(!t)return;const r=dM(t);if(r&&e.nodes.has(r)){eM(t)&&n.add(r);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&i.add(r)}const o=t.components;if(Array.isArray(o))for(const t of o)s(t)};return s(t),Rw(e,{routingTargetIds:n,loopCapableIds:i})}function wM(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 i=0;for(const e of t)if(i+=e.weight,n<i)return e.value;return t[t.length-1].value}const MM={next:mM,downstream:gM,reachableDestinations:yM,reachableDestinationsFrom:bM,reachableDestinationsWeightedFrom:vM,pickWeightedDestination:wM,graphFor:_M,validate:xM};function SM(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 i=t.prototype?.attachPointFor;return"function"==typeof i?i.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,!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&&(this._items.splice(n,1),t.parent=null,!e)){if("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=t.parent;n&&("function"==typeof n.removeComponent&&-1!==n._components?.indexOf?.(t)&&n.removeComponent(t,!0),n!==this&&"function"==typeof n.removeItem&&-1!==n._items?.indexOf?.(t)&&n.removeItem(t,!0));const i=-1===this._items.indexOf(t);if(i&&this._items.push(t),t.parent=this,i&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}const s=t._realObject,r=s?.object3d;if(r){let n,i,o=e?.toParent3D,a="world-preserve";if(!o){const s=this.attachPointFor?.(t,{slotId:e?.slotId});s?.attach&&(o=s.attach,n=s.localPosition,i=s.localRotation,a=s.carryPolicy??"world-preserve")}o&&r.parent!==o&&(o.updateWorldMatrix?.(!0,!1),r.updateWorldMatrix?.(!0,!1),o.attach(r),s.suppressTransform=!0),o&&(n&&r.position.set(n.x,n.y,n.z),"world-preserve"!==a?i?r.rotation.set(i.x,i.y,i.z):r.quaternion.identity():i&&r.rotation.set(i.x,i.y,i.z),s?.setTransientPlacement?.({policy:"carried",meta:{carryPolicy:a}}))}t.held?.(this),this._bumpReceived?.(t)}handoverOut(t){this.removeItem(t),this._bumpDispatched?.(t)}dispose(){const t=this._items.slice();this._items.length=0;for(const e of t)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,i,s){for(let r=this._items.length-1;r>=0;r--){const o=this._items[r],a="static"===o.position?o.capture?.(t,e,s):o.capture?.(n,i,s);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 i=e.bounds;!e.showOverflow&&i&&(t.beginPath(),t.rect(i.left,i.top,i.width,i.height),t.clip(),t.closePath());const{left:s=0,top:r=0}=e.state??{};t.translate(s,r),this._drawItems(t),t.translate(-s,-r),t.restore()}capture(t,e,n){const i=this,s=this._items;if(s&&s.length>0&&(!i.app||i.app.isEditMode||!i.hidden)){const s=i.fromParent?.(t,e);if(s&&i.contains?.(s.x,s.y)){const r=i.bounds,o=this._captureItems(s.x-r.left,s.y-r.top,t,e,n);if(o)return o}}return super.capture?.(t,e,n)}},e.capabilities=Object.freeze([...t.capabilities??[],"Holdable"]),e}function AM(e){var n;return(n=class extends e{reserve(t,e){const n=this.findSlot(t);return n?{slot:n,token:Symbol("slot-reservation")}:null}release(t){}async receive(t,e={}){Gu.log({role:"target",contract:"receive:enter",component:this,args:{carrier:Qy(t),options:e}});const n=this.reserve(t,e);if(!n){Gu.log({role:"target",contract:"receive:reject",component:this,args:{carrier:Qy(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(e,n,i={}){const s=e.slot,r=this._countOccupied(s.id),o=this.arrangementStrategy.positionAt(r,s,r,n);Gu.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:r,slotId:s.id,occupantCount:r,carrier:Qy(n)},result:o}),n[tb]=s.id;const a=n._realObject;let c,l;a?.object3d&&(a.object3d.updateWorldMatrix(!0,!1),c=new t.Vector3,l=new t.Quaternion,a.object3d.getWorldPosition(c),a.object3d.getWorldQuaternion(l));const{animated:h=!1,duration:d,ease:u}=i;"function"==typeof this.handoverIn?this.handoverIn(n,{slotId:s.id}):this.reparent?.(n,{animated:h,duration:d,ease:u}),!h&&n._realObject&&(n._realObject.suppressTransform=!1);{const t={},e=this.placementFor?.(n,{slot:s,index:r,occupantCount:r})??null;if(Gu.log({role:"target",contract:"placementFor",component:this,args:{carrier:Qy(n),slotId:s.id,index:r},result:e}),e){const i=n.state??{},r=this.state??{};t.left=e.position.x-(Number(i.width)||0)/2+(Number(r.width)||0)/2,t.top=e.position.z-(Number(i.height)||0)/2+(Number(r.height)||0)/2;const o=this._zPosFromSeatY(e.position.y,i.depth,s);null!==o&&(t.zPos=o),e.rotation&&Zy(t,e.rotation)}else{o&&(t.left=o.x,t.top=o.y);if(0!==(this._realObject?.receivingSurfaceY??0))t.zPos=0;else if(s.localPosition&&Number.isFinite(s.localPosition.z)){const e=this._realObject?.geometricOffsetY??0;t.zPos=s.localPosition.z+e}const e=this.acceptanceRotation?.(n,s);Gu.log({role:"target",contract:"acceptanceRotation",component:this,args:{carrier:Qy(n),slotId:s.id},result:e}),e&&Zy(t,e)}const i=this.normalizePose?.(n,s);"function"==typeof this.normalizePose&&Gu.log({role:"target",contract:"normalizePose",component:this,args:{carrier:Qy(n),slotId:s.id},result:i}),i&&Object.assign(t,i),Object.keys(t).length&&(n.setState?.(t),Gu.log({role:"target",contract:"receive:setState",component:this,args:{carrier:Qy(n),keys:Object.keys(t)}}))}this.trigger("transfer-received",{type:"transfer-received",component:n,container:this,slotId:s.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),Gu.log({role:"target",contract:"receive:done",component:this,args:{carrier:Qy(n),slotId:s.id}})}async dispatch(t,e,n={}){const i=new qu({source:this,target:e,carrier:t,options:n,physical:async()=>{delete t[tb]}}),s=await i.execute();"rolled-back"!==s.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:s.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){const e=(()=>{const e=this.slots;if(!e.length)return{ok:!1,reason:"no-slots-defined"};const n=this.findSlot(t);if(!n){const n=t?.state?.type??t?.type;for(const t of e)if(!t.allowedTypes?.length||!n||t.allowedTypes.includes(n))return{ok:!1,reason:"all-slots-full"};return{ok:!1,reason:"type-not-accepted"}}return{ok:!0,slot:n}})();return Gu.log({role:"target",contract:"canAccept",component:this,args:{carrier:Qy(t)},result:e.ok?{ok:!0,slotId:e.slot.id}:{ok:!1,reason:e.reason}}),e}accept(t,e){return this.receive(t,e)}}).__hasTransferable=!0,n}function EM(t){var e;const n=!!t.__hasCapacity,i=!!t.__hasTransferable,s=n?t:mw(t),r=i?s:AM(s),o=[...t.capabilities??[]];n||o.push("Capacity","PlacementSurface"),i||o.push("Transferable"),o.push("Holdable","FlowNode");const a=(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=class extends(SM(r)){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()}}},"FlowNodeMixed"),e.capabilities=Object.freeze(o),e.isFlowNode=!0,e);return nb(a)}function kM(t){return!!t&&!0===t.isFlowNode}Km({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"}),Km({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"}),Km({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 CM={x:0,y:0,z:0,w:1};function TM(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function OM(t,e){const n=t.rotation,i=e.rotation,s=e.position,r=n.w*s.x+n.y*s.z-n.z*s.y,o=n.w*s.y+n.z*s.x-n.x*s.z,a=n.w*s.z+n.x*s.y-n.y*s.x,c=-n.x*s.x-n.y*s.y-n.z*s.z,l=r*n.w+c*-n.x+o*-n.z-a*-n.y,h=o*n.w+c*-n.y+a*-n.x-r*-n.z,d=a*n.w+c*-n.z+r*-n.y-o*-n.x,u={x:n.w*i.x+n.x*i.w+n.y*i.z-n.z*i.y,y:n.w*i.y-n.x*i.z+n.y*i.w+n.z*i.x,z:n.w*i.z+n.x*i.y-n.y*i.x+n.z*i.w,w:n.w*i.w-n.x*i.x-n.y*i.y-n.z*i.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const PM={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 IM(t){const{carrierWorld:e,width:n,depth:i,entryHeight:s,mountLocalY:r,approachDistance:o,sides:a,toolType:c,tolerance:l,priority:h}=t,d="number"==typeof r?{position:{x:0,y:r,z:0},rotation:{...CM}}:void 0,u=n/2,p=i/2;return a.map(t=>{const n=PM[t],i="string"==typeof c?c:c[t]??"unknown",r={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:s,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:TM(n.yaw)},a={position:{x:r.position.x+n.axis.x*o,y:s,z:r.position.z+n.axis.z*o},rotation:TM(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:i,approach:OM(e,a),engage:OM(e,r),...d?{mount:d}:{},tolerance:l,priority:h}})}function DM(t){const{carrierWorld:e,topY:n,approachDistance:i,toolType:s,mountLocalY:r,tolerance:o,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...CM}};return{id:c??"top",toolType:s,approach:OM(e,{position:{x:0,y:n+i,z:0},rotation:{...CM}}),engage:OM(e,l),..."number"==typeof r?{mount:{position:{x:0,y:r,z:0},rotation:{...CM}}}:{},tolerance:o,priority:a}}function zM(t,e){return t.filter(t=>t.toolType===e.toolType)}function RM(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,i=t.approach.position.y-e.y,s=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+i*i+s*s)}});return n.sort((t,e)=>{const n=t.f.priority??0,i=e.f.priority??0;return n!==i?n-i:t.dist-e.dist}),n[0].f}class jM{constructor(t){this.owner=t}positionAt(t,e,n,i){if(0!==t)return null;const s=this.owner?.state?.width??0,r=this.owner?.state?.height??0,o=i?.state?.width??0,a=i?.state?.height??0;return{x:Math.max(0,(s-o)/2),y:Math.max(0,(r-a)/2),z:0}}capacity(t){return t.maxCount??1}}let LM=1;function FM(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const NM={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class $M{constructor(t=NM){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-"+LM++},n=(this._byResource.get(e.resource)??[]).filter(t=>FM(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const i=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}});if(i.every(t=>"b-yields"===t.decision)){const i=n.slice();for(const t of i)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:i,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:i}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:i}}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=>FM(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 i=this._byReserver.get(t.reserverId);i||(i=[],this._byReserver.set(t.reserverId,i)),i.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 i=this._byReserver.get(t.reserverId);if(i){const e=i.findIndex(e=>e.id===t.id);e>=0&&i.splice(e,1),0===i.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const HM=new $M;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=HM);class BM{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 i of this.nodes.values()){const s=YM(i.position,t);s<n&&(n=s,e=i)}return e}}function YM(t,e){const n=t.x-e.x,i=t.y-e.y,s=t.z-e.z;return n*n+i*i+s*s}function GM(t,e){return Math.sqrt(YM(t,e))}function VM(t,e,n={}){const i=new BM,s=n.defaultSpeed??100;for(const e of t){const t=e.geometry.centerPoints;if(t.length<2)continue;const n=`${e.id}:start`,r=`${e.id}:end`;i.addNode({id:n,position:t[0],type:"lane-start"}),i.addNode({id:r,position:t[t.length-1],type:"lane-end"}),i.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:r});let o=0;for(let e=1;e<t.length;e++)o+=GM(t[e-1],t[e]);const a=o/(e.speedLimit??s)*1e3;i.addEdge({fromNode:n,toNode:r,resource:e.id,distance:o,durationMs:a,forward:!0}),"twoway"===e.direction&&i.addEdge({fromNode:r,toNode:n,resource:e.id,distance:o,durationMs:a,forward:!1})}for(const t of e){if(t.lanes.length<2)continue;const e=[];for(const n of t.lanes){const s=i.laneEndpoints.get(n);if(!s)continue;const r=i.nodes.get(s.startNodeId).position,o=i.nodes.get(s.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=i.laneEndpoints.get(e);if(!t)continue;const s=i.nodes.get(t.startNodeId).position,h=i.nodes.get(t.endNodeId).position;a+=Math.min(YM(r,s),YM(r,h)),c+=Math.min(YM(o,s),YM(o,h)),l++}if(0===l)continue;const h=a<c?s.startNodeId:s.endNodeId;e.push({laneId:n,nodeId:h,pos:i.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let s=0;s<e.length;s++){if(n===s)continue;const r=e[n],o=e[s],a=GM(r.pos,o.pos);i.addEdge({fromNode:r.nodeId,toNode:o.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return i}function UM(t,e,n,i={}){const s=t.nodes.get(e),r=t.nodes.get(n);if(!s||!r)return null;const o=i.speed?.max??100,a=e=>{const n=t.nodes.get(e);var i,s;return(i=n.position,s=r.position,Math.sqrt(function(t,e){const n=t.x-e.x,i=t.y-e.y,s=t.z-e.z;return n*n+i*i+s*s}(i,s)))/o*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=i.startSimMs??0,p=i.deadlineSimMs;for(;l.size>0;){let e=null,i=null;for(const t of l){const n=c.get(t);(!i||n.fScore<i.fScore||n.fScore===i.fScore&&t<e)&&(i=n,e=t)}if(!i||!e)return null;if(e===n){const t=[];let e=i,n=0;for(;e&&e.cameFromEdge;){const i=e.cameFromEdge,s=u+(e.gScore-i.durationMs);t.unshift({resource:i.resource,timeWindow:{startSimMs:s,endSimMs:s+i.durationMs},fromPos:i.fromPos,toPos:i.toPos}),n+=i.distance,e=c.get(i.fromNodeId)}const s=i.gScore;return void 0!==p&&u+s>p?null:{segments:t,totalDurationMs:s,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=i.gScore+n.durationMs,s=c.get(n.toNode);if(!s||e<s.gScore){const i=t.nodes.get(n.fromNode),s=t.nodes.get(n.toNode),r={nodeId:n.toNode,gScore:e,fScore:e+a(n.toNode),cameFromEdge:{fromNodeId:n.fromNode,resource:n.resource,distance:n.distance,durationMs:n.durationMs,fromPos:i.position,toPos:s.position}};c.set(n.toNode,r),l.add(n.toNode)}}}return null}function WM(t,e,n=0,i){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:i}))}const qM={closed:!0,round:0,divisions:24};class XM{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const i=t[e].x-t[e-1].x,s=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(i*i+s*s))}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 i=this.cumulative;let s=0,r=i.length-2;for(;s<r;){const t=s+r>>1;i[t+1]<=n?s=t+1:r=t}const o=i[s+1]-i[s],a=o>0?(n-i[s])/o:0,c=this.points[s],l=this.points[s+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 KM(t,e={}){const n={...qM,...e},i=t.length;if(0===i)return new XM([],n.closed);if(1===i)return new XM([{x:t[0].x,y:t[0].y}],n.closed);const s=[],r=(t,e)=>{if(s.length>0){const n=s[s.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}s.push({x:t,y:e})},o=(n.closed,i);for(let e=0;e<o;e++){const s=0===e?n.closed?i-1:-1:e-1,o=e===i-1?n.closed?0:-1:e+1,a=s>=0?t[s]:null,c=t[e],l=o>=0?t[o]:null;if(a&&a.x===c.x&&a.y===c.y)continue;const h=a&&l?Zr(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(r(d,u),h>0&&a&&l)for(let t=1;t<=n.divisions;t++){const e=t/n.divisions,i=1-e;r(i*i*d+2*i*e*c.x+e*e*p,i*i*u+2*i*e*c.y+e*e*f)}else d===p&&u===f||r(p,f);if(l&&Xr(c)){const t=Zr(l,n.round),e=Math.sqrt((c.x-l.x)**2+(c.y-l.y)**2),i=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,s=Math.min(t,e/2),o=Kr({x:p,y:f},{x:Math.sin(i)*s+l.x,y:Math.cos(i)*s+l.y},c.bulge);if(o){let t=o.endAngle-o.startAngle;if(o.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 i=e/n.divisions,s=o.startAngle+t*i;r(o.cx+o.radius*Math.cos(s),o.cy+o.radius*Math.sin(s))}}}}if(n.closed&&s.length>0){const t=s[0],e=s[s.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&s.push({x:t.x,y:t.y})}return new XM(s,n.closed)}function QM(t,e){return KM(t,e).length}function JM(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 ZM(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 tS(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",i={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:JM(n),parentId:t.parent?.state?.id,parentPath:ZM(t)},s=t._realObject?.object3d;if(s){s.updateWorldMatrix?.(!0,!1);const t=s.matrixWorld?.elements;t&&(i.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(i.isItem=!0),!0===t.isMover&&(i.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(i.isHolder=!0),"function"==typeof t.pickupFrames)try{i.isPickable=t.pickupFrames().length>0}catch{i.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?i.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(i.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,i]of Object.entries(t.state))"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i&&null!==i||(e[n]=i);i.state=e}if(e){const e=t.components??[];i.childIds=e.map(t=>t.state?.id).filter(Boolean)}return i}function eS(t){function e(t,n){if(!t)return;n.push(tS(t));const i=t.components??[];for(const t of i)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const i=e.components??[];for(const e of i){const i=n(t,e);if(i)return i}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const i=n(e,t?.rootModel??t);if(!i)return null;const s={...tS(i)};if("function"==typeof i.pickupFrames)try{s.pickupFrames=i.pickupFrames()}catch{}if("object"==typeof i.slots)try{s.slots=Array.isArray(i.slots)?i.slots:"function"==typeof i.slots?i.slots():[]}catch{}if("function"==typeof i.acceptanceRotation)try{s.acceptanceWorldQuat=i.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof i.deliveryWorldPosition)try{s.deliveryWorldPosition=i.deliveryWorldPosition(null)}catch{}return s},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 i=t.components??[];for(const t of i)n.push(t)}return{simTime:Dr.now,realTime:"undefined"!=typeof performance?performance.now():Date.now(),speed:Dr.speed,paused:Dr.isPaused,carrierCount:e}},transferLog(){const t={};Xu.flows().forEach((e,n)=>{t[n]=e});const e={};Xu.targetCounts().forEach((t,n)=>{e[n]=t});const n={};return Xu.rejectReasonCounts().forEach((t,e)=>{n[e]=t}),{entries:Xu.toJSON(),stats:Xu.stats(),flows:t,targetCounts:e,rejectReasonCounts:n}},reservations(){const t=[...HM.all()],e={},n={};for(const i of t)(e[i.resource]??=[]).push(i),(n[i.reserverId]??=[]).push(i);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:Dr.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=HM.conflictLog(),e={},n={};let i=0,s=0;for(const r of t)e[r.resource]=(e[r.resource]??0)+1,n[r.proposed.reserverId]=(n[r.proposed.reserverId]??0)+1,"rejected"===r.outcome?i++:s++;return{simTime:Dr.now,log:[...t],total:t.length,rejected:i,preempted:s,byResource:e,byReserver:n}}}}function nS(t){const e=eS(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let iS=0;const sS=new FinalizationRegistry(()=>{iS--});class rS{static get residents(){return iS}static get residentsCount(){return iS}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,iS++,sS.register(this,iS)}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,Zi("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,i)=>{const s=this.references[t];if(s)s===e?i(Error("Reference ID and target duplicate")):e?i(Error("Reference ID duplicate")):n(s);else{const s=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)s(e);else{if(!this.creator)return void i(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,s,i)}}});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 Qi("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,Zi("RELEASED",e)))}}const oS={},aS={};let cS=[];function lS(t){const e=t.target,n="SCRIPT"===e.tagName?oS:aS,i=e.src||e.href;n[i]=!0,cS.forEach((t,e)=>{if(!t)return;const{resolve:s,scripts:r,styles:o}=t;if(n===oS){const t=r.indexOf(i);t>-1&&t<r.length-1&&dS(r[t+1])}r.some(t=>!oS[t])||o?.some(t=>!aS[t])||(s(),cS[e]=null)}),cS=cS.filter(Boolean)}function hS(t){if("string"==typeof t)return;const e=t.target,n=e.src,i="SCRIPT"===e.tagName?oS:aS;cS.forEach((e,s)=>{if(!e)return;const{reject:r,scripts:o,styles:a}=e;(i===oS&&o.includes(n)||i===aS&&!!a?.includes(n))&&(r(t),cS[s]=null)}),cS=cS.filter(Boolean),delete i[n],document.head.removeChild(e)}function dS(t){oS[t]=!1;const e=document.createElement("script");e.onload=lS,e.onerror=hS,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class uS{static load(t,e){const n="string"==typeof t?[t]:t,i="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||i&&!Array.isArray(i))return void e(new Error("invalid sources for load"));let s,r=!0;if(i?.forEach(t=>{t in aS||function(t){aS[t]=!1;const e=document.createElement("link");e.onload=lS,e.onerror=hS,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),aS[t]||(r=!1)}),n&&n.length>0)for(const t of n)t in oS?oS[t]||(r=!1):s??=t;if(s)dS(s);else if(r)return void t();cS.push({resolve:t,reject:e,scripts:n,styles:i})})}}const pS="0.0.0";function fS(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 mS(e){const{lineWidth:n=0}=e.state;let{width:i,height:s}=e.bounds;i+=n,s+=n;const r=fS(2*i),o=fS(2*s),a=Bp(r,o),c=new t.CanvasTexture(a);return gS(a,e,2),c.needsUpdate=!0,c.wrapS=t.RepeatWrapping,c.wrapT=t.RepeatWrapping,c.offset.set(0,1-2*s/o),c.repeat.set(2*i/r,2*s/o),c.magFilter=t.NearestFilter,c.minFilter=t.LinearFilter,c.colorSpace=t.SRGBColorSpace,c}function gS(t,e,n){const{lineWidth:i=0}=e.state;let{left:s,top:r}=e.bounds;s-=i/2,r-=i/2;const o=t.getContext("2d");o.scale(n,n),o.translate(-s,-r),e.render(o),e.postrender(o)}function yS(t,e,n=2){const i=t.getContext("2d");i&&(i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,t.width,t.height),gS(t,e,n))}const bS=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class vS extends Mu{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 t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds;if(!e||!n)return;const i=Id(this.component.state.material3d),s=new t.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const r=mS(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,i),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.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;nu(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&&(yS(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(!bS.has(e)){this._debouncedRebuild();break}}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Id(this.component.state.material3d);Rd(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),hu(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 _S=new Map;function xS(t){return Math.round(1e3*t)/1e3}function wS(e){return new t.Color(e).getHexString()}const MS={material(e,n,i){const s=e+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+wS(t.color)),null!=t.metalness&&e.push("m"+xS(t.metalness)),null!=t.roughness&&e.push("r"+xS(t.roughness)),null!=t.opacity&&e.push("o"+xS(t.opacity)),null!=t.emissive&&e.push("E"+wS(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+xS(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+xS(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("|")}(n);let r=_S.get(s);return r||_S.set(s,r=function(e){const n=new t.MeshStandardMaterial;return n.userData.__bankOwned=!0,null!=e.color&&n.color.set(e.color),null!=e.emissive&&n.emissive.set(e.emissive),null!=e.metalness&&(n.metalness=e.metalness),null!=e.roughness&&(n.roughness=e.roughness),null!=e.emissiveIntensity&&(n.emissiveIntensity=e.emissiveIntensity),null!=e.envMapIntensity&&(n.envMapIntensity=e.envMapIntensity),null!=e.side&&(n.side=e.side),null!=e.map&&(n.map=e.map),null!=e.flatShading&&(n.flatShading=e.flatShading),null!=e.depthWrite&&(n.depthWrite=e.depthWrite),null!=e.opacity&&(n.opacity=e.opacity),null!=e.transparent?n.transparent=e.transparent:null!=e.opacity&&e.opacity<1&&(n.transparent=!0),n}(n)),null==i?r:Qd(r,{color:i})},get size(){return _S.size},has(t){const e=t+"::";for(const t of _S.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of _S.values())Zd(t),t.dispose();_S.clear()}};class SS extends Mu{getObject3dInstance(){return new t.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;nu(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 i=Mu.buildFillStyleTexture(this.component);i?(n.map&&n.map.dispose(),i.needsUpdate=!0,n.map=i,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(iu(t))),nu(n,0,t)}updateStrokeStyle(){const e=this.object3d.getObjectByName("__edgeLines__");e&&(this.object3d.remove(e),hu(e));const{strokeStyle:n}=this.component.state;if(!n||"transparent"===n||"none"===n)return;const i=this.object3d.geometry;if(!i?.getAttribute("position"))return;const s=new t.EdgesGeometry(i),r=new t.LineBasicMaterial({color:n}),o=new t.LineSegments(s,r);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 i=this.object3d.geometry.boundingBox;if(i){const s=i.max.x-i.min.x,r=i.max.y-i.min.y,o=i.max.z-i.min.z;this.setDimensionScale(t/s,n/r,e/o)}}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,i={shared:e,required:n,violated:n&&!e};return void 0!==t&&(i.reason=t),e&&(i.bankKey=this.materialBankKey),i}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=Id(this.component.state.material3d),e=eu(this.component.state.fillStyle);return{metalness:t.metalness,roughness:t.roughness,emissive:t.emissive,emissiveIntensity:t.emissiveIntensity,envMapIntensity:t.envMapIntensity,side:zd(t.side),flatShading:t.flatShading,opacity:e,transparent:e<1}}buildMaterial(){if(!this.canShareMaterial){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial({transparent:!0});return Rd(n,e),void(this.object3d.material=n)}this.applyBankMaterial()}applyBankMaterial(){const{fillStyle:t}=this.component.state,e=eu(t)>0&&"string"==typeof t?iu(t):void 0;Jd(this.object3d),this.object3d.material=MS.material(this.materialBankKey,this.materialSpec(),e)}updateMaterial3d(){if(super.updateMaterial3d(),this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const t=this.object3d.material;t&&Rd(t,Id(this.component.state.material3d))}clear(){return Jd(this.object3d),hu(this.object3d),super.clear()}}function AS(t,e,n,i){return[["bold",t],["italic",e],[n+"px",!0],[i,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function ES(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 kS(t,e,n){const{bold:i=!1,italic:s=!1,fontFamily:r="Serif",fontSize:o=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=AS(i,s,o,r),"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*o,b=String(e).split("\n"),v=y*b.length;g="top"===l||"hanging"===l?p+.1*o:"bottom"===l||"alphabetic"===l?p+d-v+.1*o:p+(d-v)/2+.1*o,f.textBaseline="top";for(const t of b)f.fillText(t,m,g),g+=y}function CS(e,n,i,s){const r=ES(2*n),o=ES(2*i),a=Bp(r,o),c=a.getContext("2d"),{fillStyle:l}=s||{};if(l&&"object"==typeof l&&l.colorStops?.length){const t=du(l,2*n,2*i);t&&c.drawImage(t,0,0)}c.scale(2,2),"string"==typeof l&&""!==l&&"transparent"!==l&&(c.fillStyle=l,c.fillRect(0,0,n,i)),kS(a,e,s);const h=new t.CanvasTexture(a);return h.needsUpdate=!0,h.wrapS=t.RepeatWrapping,h.wrapT=t.RepeatWrapping,h.offset.set(0,1-2*i/o),h.repeat.set(2*n/r,2*i/o),h.minFilter=t.LinearFilter,h.colorSpace=t.SRGBColorSpace,h}function TS(e,n,i,s,r,o,a){const c=new Image;c.crossOrigin="anonymous",c.onload=()=>{const e=2*i,l=2*s,h=ES(e),d=ES(l),u=Bp(h,d),p=u.getContext("2d");if(o.color&&(p.fillStyle=o.color,p.fillRect(0,0,e,l)),o.fitPattern)p.drawImage(c,0,0,e,l);else{const t=2*(o.width||c.naturalWidth),n=2*(o.height||c.naturalHeight),i=2*(o.offsetX||0),s=2*(o.offsetY||0);let r=0,a=0;switch(o.align){case"center":r=(e-t)/2,a=(l-n)/2;break;case"left-top":break;case"left-bottom":a=l-n;break;case"right-top":r=e-t;break;case"right-bottom":r=e-t,a=l-n;break;case"left":a=(l-n)/2;break;case"right":r=e-t,a=(l-n)/2;break;case"top":r=(e-t)/2;break;case"bottom":r=(e-t)/2,a=l-n}const h=i+r,d=s+a;if(o.noRepeat)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,h,d,t,n);else{p.save(),p.rect(0,0,e,l),p.clip();const i=h>0?h-Math.ceil(h/t)*t:h;for(let s=d>0?d-Math.ceil(d/n)*n:d;s<l;s+=n)for(let r=i;r<e;r+=t)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,r,s,t,n);p.restore()}}n&&(p.scale(2,2),kS(u,n,r));const f=new t.CanvasTexture(u);f.needsUpdate=!0,f.wrapS=t.RepeatWrapping,f.wrapT=t.RepeatWrapping,f.offset.set(0,1-l/d),f.repeat.set(e/h,l/d),f.minFilter=t.LinearFilter,f.colorSpace=t.SRGBColorSpace,a(f)},c.onerror=()=>{const t=CS(n,i,s,r);a(t)},c.src=e}function OS(t,e){let{bold:n=!1,italic:i=!1,fontFamily:s="Serif",fontSize:r=10,lineHeight:o="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=AS(n,i,r,s),a.style.lineHeight=String(o),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 PS extends SS{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){this.updateDimension()}updateStrokeStyle(){}updateFillStyle(){this.updateText()}updateDimension(){const{width:e,height:n}=this.component.state,i=Math.abs(e)||1,s=Math.abs(n)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const r=new t.PlaneGeometry(i,s);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:i=!1,italic:s=!1,fontFamily:r="Serif",fontSize:o=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:i,italic:s,fontFamily:r,fontSize:o,fontColor:a,textAlign:c,textBaseline:l,width:d,height:u,fillStyle:f};if("object"==typeof f&&"pattern"===f?.type&&f.image){return void TS(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=CS(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(iu(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}Jp("text",t=>new PS(t));const IS={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function DS(t){const e=t.model?.type??"";return"texture"===(IS[e]??"css3d")?new vS(t):new Xp(t)}Jp("html-overlay-element",DS),Jp("html-overlay-container",DS);class zS{setShape({extrudedShape:e,extrudedOptions:n}){this.extrudedShape=e,this.bb=new t.Box2,this.bb.setFromPoints(this.extrudedShape?.extractPoints(0).shape),this.extrudedOptions=n}generateTopUV(e,n,i,s,r){const o=n[3*i],a=n[3*i+1],c=n[3*s],l=n[3*s+1],h=n[3*r],d=n[3*r+1],u=this.bb,p=u.max.x-u.min.x,f=u.max.y-u.min.y;return[new t.Vector2((o-u.min.x)/p,1-(a-u.min.y)/f),new t.Vector2((c-u.min.x)/p,1-(l-u.min.y)/f),new t.Vector2((h-u.min.x)/p,1-(d-u.min.y)/f)]}generateSideWallUV(e,n,i,s,r,o){const a=n[3*i],c=n[3*i+1],l=n[3*i+2],h=n[3*s],d=n[3*s+1],u=n[3*s+2],p=n[3*r],f=n[3*r+1],m=n[3*r+2],g=n[3*o],y=n[3*o+1],b=n[3*o+2],v=this.extrudedOptions?.depth||100,_=this.bb,x=_.max.x-_.min.x,w=_.max.y-_.min.y;return Math.abs(c-d)<.01?[new t.Vector2(a/x,1-l/v),new t.Vector2(h/x,1-u/v),new t.Vector2(p/x,1-m/v),new t.Vector2(g/x,1-b/v)]:[new t.Vector2(c/w,1-l/v),new t.Vector2(d/w,1-u/v),new t.Vector2(f/w,1-m/v),new t.Vector2(y/w,1-b/v)]}}function RS(t,e){const n=t/2,i=e/2;return{points:[{x:-n,y:-i},{x:n,y:-i},{x:n,y:i},{x:-n,y:i}]}}function jS(t,e,n){const i=Math.max(3,Math.floor(n)),s=[];for(let n=0;n<i;n++){const r=n/i*Math.PI*2;s.push({x:t*Math.cos(r),y:e*Math.sin(r)})}return{points:s,segments:i}}function LS(t){if(0===t.length)return[];let e=1/0,n=1/0,i=-1/0,s=-1/0;for(const r of t)r.x<e&&(e=r.x),r.x>i&&(i=r.x),r.y<n&&(n=r.y),r.y>s&&(s=r.y);const r=(e+i)/2,o=(n+s)/2,a=t.map(t=>({x:t.x-r,y:t.y-o})),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 FS extends Mu{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 i=LS(n);return i.length<3?null:{points:i}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new zS),this._boundUVGenerator}build(){super.build();const e=this.effectiveDepth,n=this.shape;if(!n)return;const i=this.boundUVGenerator;i&&i.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const s=this.createGeometry(n),r=this.createMaterials();this._mesh=new t.Mesh(s,r),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(e){const n=this.effectiveDepth,{lineWidth:i=0}=this.component.state,s={steps:1,depth:n,bevelEnabled:i>0,bevelThickness:0,bevelSize:i,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,s);return r.center(),r}createMaterials(){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial;Rd(n,e);const i=new t.MeshStandardMaterial;return Rd(i,e),[n,i]}createTexture(){const{width:e,height:n}=this.component.bounds,i=ES(e),s=ES(n),r=Bp(i,s);this.component.render(r.getContext("2d"));const o=new t.CanvasTexture(r);return o.needsUpdate=!0,o.wrapS=t.RepeatWrapping,o.wrapT=t.RepeatWrapping,o.offset.set(0,1-n/s),o.repeat.set(e/i,n/s),o.minFilter=t.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=Id(this.component.state.material3d);for(const n of t)Rd(n,e)}updateAlpha(){const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,i=this.getMaterials();i&&(nu(i[0],0,e),nu(i[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(iu(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,i=this.component.hasTextProperty?this.component.text:"";if(!i){const t=Mu.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(iu(n))),void(e.needsUpdate=!0)}const{bold:s=!1,italic:r=!1,fontFamily:o="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:s,italic:r,fontFamily:o,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 TS(this.component.app.url(n.image),i,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 _=CS(i,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 NS extends FS{get shape(){const{cx:e=0,cy:n=0,rx:i=1,ry:s=1,startAngle:r=0,endAngle:o=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=new t.EllipseCurve(e,n,Math.abs(i),Math.abs(s),r,o,a,0);return new t.Shape(c.getPoints(50))}}Jp("ellipse",t=>new NS(t));class $S extends FS{get shape(){const{width:e,height:n,round:i=0}=this.component.state,s=Oc(i,e,n);if(s>0){const i=s,r=new t.Path;return r.moveTo(i,0),r.lineTo(e-i,0),r.quadraticCurveTo(e,0,e,i),r.lineTo(e,n-i),r.quadraticCurveTo(e,n,e-i,n),r.lineTo(i,n),r.quadraticCurveTo(0,n,0,n-i),r.lineTo(0,i),r.quadraticCurveTo(0,0,i,0),new t.Shape(r.getPoints(12))}const r=new t.Shape;return r.moveTo(0,0),r.lineTo(e,0),r.lineTo(e,n),r.lineTo(0,n),r.lineTo(0,0),r}}function HS(e,n={}){const i=n.round??0,s=n.divisions??24;if(!e||0===e.length)return new t.Shape;const r=e.some(t=>Xr(t)),o=i>0||e.some(t=>Zr(t,0)>0);if(r||o){const n=new t.Path;for(let t=0;t<e.length;t++){const s=e[(t-1+e.length)%e.length],r=e[t],o=e[(t+1)%e.length];if(s.x===r.x&&s.y===r.y)continue;const a=Zr(r,i);let c=Math.sqrt((s.x-r.x)**2+(s.y-r.y)**2),l=0!==c?Math.atan2(s.x-r.x,s.y-r.y):0;const h=Math.sin(l)*Math.min(a,c/2)+r.x,d=Math.cos(l)*Math.min(a,c/2)+r.y;c=Math.sqrt((o.x-r.x)**2+(o.y-r.y)**2),l=0!==c?Math.atan2(o.x-r.x,o.y-r.y):0;const u=Math.sin(l)*Math.min(a,c/2)+r.x,p=Math.cos(l)*Math.min(a,c/2)+r.y;if(0===t?n.moveTo(h,d):n.lineTo(h,d),a>0&&n.quadraticCurveTo(r.x,r.y,u,p),Xr(r)){const t=Zr(o,i),e=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),s=0!==e?Math.atan2(r.x-o.x,r.y-o.y):0,a=Kr({x:u,y:p},{x:Math.sin(s)*Math.min(t,e/2)+o.x,y:Math.cos(s)*Math.min(t,e/2)+o.y},r.bulge);a&&n.absarc(a.cx,a.cy,a.radius,a.startAngle,a.endAngle,a.clockwise)}}return new t.Shape(n.getPoints(s))}const a=new t.Shape;for(let t=0;t<e.length;t++)0===t?a.moveTo(e[t].x,e[t].y):a.lineTo(e[t].x,e[t].y);return a}Jp("rect",t=>new $S(t));class BS extends FS{get shape(){const{path:t=[],round:e=0}=this.component.state;return HS(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(FS.prototype).build.call(this);const e=this.effectiveDepth,n=this.shape;if(!n)return;const i=this.boundUVGenerator,s=this.minMax;if(i&&void 0!==s.minX&&void 0!==s.maxX&&void 0!==s.minY&&void 0!==s.maxY){const n=new t.Shape;n.moveTo(s.minX,s.minY),n.lineTo(s.maxX,s.minY),n.lineTo(s.maxX,s.maxY),n.lineTo(s.minX,s.maxY),n.closePath(),i.setShape({extrudedShape:n,extrudedOptions:{depth:e}})}else i&&i.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const r=this.createGeometry(n),o=this.createMaterials();this._mesh=new t.Mesh(r,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(e){const n=this.effectiveDepth,{lineWidth:i=0}=this.component.state,s={steps:1,depth:n,bevelEnabled:i>0,bevelThickness:0,bevelSize:i,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,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;r.translate(-t,-e,0),r.computeBoundingBox();const n=r.boundingBox;n&&r.translate(0,0,-(n.min.z+n.max.z)/2)}else r.center();return r}get minMax(){if(!this._minMax){const{path:t}=this.component.state;let e,n,i,s;t.forEach((t,r)=>{if(0==r)return e=i=t.x,void(n=s=t.y);e=Math.min(e,t.x),i=Math.max(i,t.x),n=Math.min(n,t.y),s=Math.max(s,t.y)}),this._minMax={minX:e,minY:n,maxX:i,maxY:s}}return this._minMax}}Jp("polygon",t=>new BS(t));class YS extends FS{get shape(){const{cx:e=0,cy:n=0,rx:i=1,ry:s=1,ratio:r=50,startAngle:o=0,endAngle:a=2*Math.PI,anticlockwise:c=!1}=this.component.state,l=Math.abs(i),h=Math.abs(s),d=new t.EllipseCurve(e,n,l,h,o,a,c,0),u=new t.Shape(d.getPoints(50)),p=l/100*r,f=h/100*r;if(p>0&&f>0){const i=new t.EllipseCurve(e,n,p,f,o,a,c,0),s=new t.Path(i.getPoints(50));u.holes.push(s)}return u}}Jp("donut",t=>new YS(t));class GS extends FS{get shape(){const{x1:e=0,y1:n=0,x2:i=0,y2:s=0,x3:r=0,y3:o=0,round:a=0}=this.component.state,c=[{x:e,y:n},{x:i,y:s},{x:r,y:o}];if(a>0){const e=new t.Path;for(let t=0;t<c.length;t++){const n=c[(t-1+c.length)%c.length],i=c[t],s=c[(t+1)%c.length];let r=Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2),o=0!==r?Math.atan2(n.x-i.x,n.y-i.y):0;const l=Math.sin(o)*Math.min(a,r/2)+i.x,h=Math.cos(o)*Math.min(a,r/2)+i.y;r=Math.sqrt((s.x-i.x)**2+(s.y-i.y)**2),o=0!==r?Math.atan2(s.x-i.x,s.y-i.y):0;const d=Math.sin(o)*Math.min(a,r/2)+i.x,u=Math.cos(o)*Math.min(a,r/2)+i.y;0===t?e.moveTo(l,h):e.lineTo(l,h),e.quadraticCurveTo(i.x,i.y,d,u)}return new t.Shape(e.getPoints(12))}const l=new t.Shape;return l.moveTo(e,n),l.lineTo(i,s),l.lineTo(r,o),l.closePath(),l}}Jp("triangle",t=>new GS(t));class VS extends FS{get shape(){const{ratio:e=30,wing:n=5,cx:i=0,cy:s=0,rx:r=1,ry:o=1}=this.component.state;if(n<3)return null;const a=Math.PI/2,c=2*Math.PI/n,l=r-e/100*r,h=o-e/100*o,d=new t.Shape;d.moveTo(i+r*Math.cos(-a),s+o*Math.sin(-a)),d.lineTo(i+(r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,s+(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let t=1;t<n;t++)d.lineTo(i+r*Math.cos(c*t-a),s+o*Math.sin(c*t-a)),d.lineTo(i+(r-l)*(Math.cos(c*(t+1)-a)+Math.cos(c*t-a))/2,s+(o-h)*(Math.sin(c*(t+1)-a)+Math.sin(c*t-a))/2);return d.closePath(),d}}Jp("star",t=>new VS(t));const US=new Map;function WS(t){return t.userData.__bankOwned=!0,t}const qS={primitive(e){const n="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}}(e);let i=US.get(n);return i||US.set(n,i=WS(function(e){switch(e.kind){case"box":return new t.BoxGeometry(1,1,1);case"plane":return new t.PlaneGeometry(1,1);case"cylinder":return new t.CylinderGeometry(.5,.5,1,e.segments??16);case"sphere":return new t.SphereGeometry(.5,e.segments??16,e.heightSegments??Math.max(2,Math.round((e.segments??16)/2)))}}(e))),i},shaped(t,e){const n="shaped::"+t;let i=US.get(n);return i||US.set(n,i=WS(e())),i},owns:t=>!0===t.userData?.__bankOwned,get size(){return US.size},has:t=>US.has("primitive::"+t)||US.has("shaped::"+t),dispose(){for(const t of US.values())t.dispose();US.clear()}},XS=[8,12,16],KS={cylinder:25,sphere:32},QS=3,JS=128;function ZS(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(JS,Math.max(3,Math.floor(t))):e}function tA(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(JS,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function eA(t){return XS.includes(t)}const nA={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 iA extends SS{buildGeometry(){const t=this.component.state,e=ZS(t.segments,KS.sphere),n=tA(t.heightSegments,e);this.object3d.geometry=qS.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,i=n??t;this.setDimensionScale(2*t,2*i,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 jS(t,e,ZS(this.component.state.segments,KS.sphere))}}let sA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new iA(this)}get nature(){return nA}};sA=tg([Ny("sphere")],sA);class rA extends Mu{getObject3dInstance(){return new t.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(),i=this.component.parent?._realObject;return t+n+e/2-(i?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;nu(this.object3d.material,0,e)}updateFillStyle(){const{fillStyle:t}=this.component.state,e=this.object3d.material;if(!e)return;const n=Mu.buildFillStyleTexture(this.component);n?(e.map&&e.map.dispose(),n.needsUpdate=!0,e.map=n):"string"==typeof t&&("transparent"!==t?e.color.set(iu(t)):e.opacity=0)}}class oA extends rA{buildMaterial(){const e=this.object3d.material;e&&e.dispose(),this.object3d.material=new t.SpriteMaterial({map:mS(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:i=1,height:s=1}=n?.bounds??{},{scale:r=1}=this.component.state;return{x:r*t/i,y:r*e/s,z:r}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const aA={mutable:!1,resizable:!0,rotatable:!0,properties:[]};let cA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new oA(this)}get nature(){return aA}};cA=tg([Ny("sprite")],cA);const lA={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class hA extends SS{buildGeometry(){this.object3d.geometry=qS.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?RS(t,e):null}}let dA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new hA(this)}get nature(){return lA}};dA=tg([Ny("cube")],dA);const uA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class pA extends SS{buildGeometry(){const t=ZS(this.component.state.segments,KS.cylinder);this.object3d.geometry=qS.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 jS(t,e,ZS(this.component.state.segments,KS.cylinder))}}let fA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new pA(this)}get nature(){return uA}};fA=tg([Ny("cylinder")],fA);const mA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class gA extends Mu{get zPriority(){return gu.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 i=this.createTextureBoard(t,n);i.position.set(0,0,.5*e+1),this.object3d.add(i)}createCube(e,n,i){const{boxColor:s="#ccaa76"}=this.component.state,r=Id(this.component.state.material3d),o=new t.BoxGeometry(e,i,n),a=new t.MeshStandardMaterial({color:s,side:t.FrontSide});Rd(a,r);const c=new t.Mesh(o,a);return c.castShadow=r.castShadow,c.receiveShadow=r.receiveShadow,c}createTextureBoard(e,n){const i=Id(this.component.state.material3d),{fillStyle:s="#ccaa76"}=this.component.state,r=Mu.buildFillStyleTexture(this.component),o=new t.MeshStandardMaterial(r?{map:r}:{color:s||"#ccaa76",side:t.FrontSide});Rd(o,i);const a=new t.PlaneGeometry(e,n,1,1),c=new t.Mesh(a,o);return c.castShadow=i.castShadow,c.receiveShadow=i.receiveShadow,c}updateMaterial3d(){super.updateMaterial3d();const t=Id(this.component.state.material3d);this.object3d.traverse(e=>{if(e.isMesh){const n=e.material;n&&Rd(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()}}let yA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return mA}buildRealObject(){return new gA(this)}};var bA;yA=tg([Ny("banner")],yA);const vA={far:1e5,fov:80,near:1,zoom:1},_A={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 xA extends Mu{getObject3dInstance(){return new t.Mesh}updateCamera(){const{near:e=vA.near,far:n=vA.far,fov:i=vA.fov,zoom:s=vA.zoom,showHelper:r}=this.component.state;this.camera.far=n,this.camera.fov=i,this.camera.near=e,this.camera.zoom=s,r?this.helper||(this.helper=new t.CameraHelper(this.camera),this.object3d.add(this.helper)):this.helper&&(this.object3d.remove(this.helper),delete this.helper)}build(){super.build();const{width:e=0,height:n=0,depth:i=0,fillStyle:s="lightgray"}=this.component.state;this.object3d.geometry=new t.BoxGeometry(e,i,n);const r=Id(this.component.state.material3d),o=new t.MeshStandardMaterial({color:s});Rd(o,r),this.object3d.material=o,this.object3d.castShadow=r.castShadow,this.object3d.receiveShadow=r.receiveShadow,this.camera=new t.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=Id(this.component.state.material3d);Rd(t,e),this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}}let wA=bA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return bA._image||(bA._image=new Image,bA._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=="),bA._image}render(t){const{left:e,top:n,width:i,height:s}=this.bounds;t.beginPath(),this.drawImage(t,bA.image,e,n,i,s)}buildRealObject(){return new xA(this)}get nature(){return _A}};wA=bA=tg([Ny("camera")],wA);const MA={mutable:!1,resizable:!0,rotatable:!0,properties:[...Ly],"value-property":"source",help:"scene/component/gltf-object"};let SA=class extends(Fy(Pc(Tc))){get nature(){return MA}};SA=tg([Ny("gltf-object")],SA);const AA={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 EA extends Mu{updatePointLight(){const{lightType:e="point",distance:n=0,intensity:i=10,decay:s=1,fillStyle:r="white",castShadow:o,near:a=.5,far:c=1e3,fov:l=90,zoom:h=1,showHelper:d}=this.component.state;if(this.object3d.color=new t.Color(r),"point"==e&&(this.object3d.distance=n,this.object3d.decay=s),this.object3d.intensity=i,this.object3d.castShadow=o,o){const t=this.object3d.shadow?.camera;t.far=c,t.near=a,t.fov=l,t.zoom=h}if(d){const e=this.object3d.shadow?.camera;this.helper||(this.helper=new t.CameraHelper(e),this.object3d.add(this.helper))}else this.helper&&(this.object3d.remove(this.helper),delete this.helper)}getObject3dInstance(){const{lightType:e="point"}=this.component.state;return"point"==e?new t.PointLight:new t.DirectionalLight}update(){this.clear(),this.build(),this.updateDimension(),this.updateHidden(),this.updatePointLight()}}let kA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new EA(this)}get anchors(){return[]}get nature(){return AA}};kA=tg([Ny("light")],kA);const CA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class TA extends SS{buildGeometry(){this.object3d.geometry=qS.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?RS(t,e):null}}let OA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new TA(this)}get nature(){return CA}};OA=tg([Ny("wall")],OA);const PA={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 IA extends Mu{get zPriority(){return gu.FLOOR}get receivingSurfaceY(){return this.placementSurfaceY()}resolveShadow(){const t=this.component.state,e=t.material3d,{alpha:n=1,fillStyle:i}=t,s=n>=.9&&"none"!==i;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??s}}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:e,height:n,depth:i=1}=this.component.state;if(!e||!n)return;const s=Math.abs(e),r=Math.abs(n),o=Math.max(i,.5),a=new t.BoxGeometry(s,o,r),c=this._buildTopMaterial(),l=this._buildSideMaterial(),h=[l,l,c,l,l,l];this._mesh=new t.Mesh(a,h),this._mesh.position.y=0;const{cast:d,receive:u}=this.resolveShadow();this._mesh.castShadow=d,this._mesh.receiveShadow=u,this.object3d.add(this._mesh)}_buildTopMaterial(){const{alpha:e=1,fillStyle:n}=this.component.state,i=Id(this.component.state.material3d),s=Mu.buildFillStyleTexture(this.component);if(s){this._topTexture=s;const e=new t.MeshStandardMaterial({map:s,side:t.DoubleSide});return nu(e,0,n),e.depthWrite=e.opacity>=.9,Rd(e,i),e}const r="string"==typeof n&&"none"!==n?iu(n):"#e0e0e0",o=new t.MeshStandardMaterial({color:r,side:t.DoubleSide});return nu(o,0,n),o.depthWrite=o.opacity>=.9,Rd(o,i),o}_buildSideMaterial(){const{strokeStyle:e,alpha:n=1}=this.component.state,i="string"==typeof e&&e?iu(e):"#999999",s=Id(this.component.state.material3d),r=new t.MeshStandardMaterial({color:i});return Rd(r,s),r.side=t.DoubleSide,nu(r,0,e),r.depthWrite=r.opacity>=.9,r}updateAlpha(){if(!this._mesh)return;const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,i=this._mesh.material;for(let t=0;t<i.length;t++){const s=i[t];nu(s,0,2===t?e:n),s.depthWrite=s.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)}}let DA=class extends rh{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new IA(this)}get nature(){return PA}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}};DA.requires3d=!0,DA=tg([Ny("floor-plate")],DA);function zA(e,n={}){const i=n.size??5,s=n.color??4500172,r=n.emissive??2245734,o=new t.SphereGeometry(i,16,12),a=new t.MeshStandardMaterial({color:s,emissive:r,emissiveIntensity:.15,metalness:.3,roughness:.4,transparent:!0,opacity:.35}),c=new t.Mesh(o,a);n.position&&c.position.set(n.position[0],n.position[1],n.position[2]),c.userData.alwaysRaycast=!0,c.scale.setScalar(1),c.visible=n.visible??!(!0===e.app?.isViewMode);const l=()=>{a.emissiveIntensity=.9,a.opacity=.95,c.scale.setScalar(1.35),e.invalidate?.()},h=()=>{a.emissiveIntensity=.15,a.opacity=.35,c.scale.setScalar(1),e.invalidate?.()};return e.on("mouseenter",l),e.on("mouseleave",h),c.userData.dispose=()=>{e.off("mouseenter",l),e.off("mouseleave",h)},c}class RA extends SS{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:e,height:n}=this.component.state,i=Math.abs(e)||1,s=Math.abs(n)||1,r=new t.PlaneGeometry(i,s);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateDimension(){this.update()}build(){super.build();const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,i=Math.abs(e)||1,s=Math.max(2,.04*Math.min(n,i));this.object3d.add(zA(this.component,{size:s,position:[n/2-s,s,-i/2+s]}))}}const jA={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let LA=class extends(Ry(Pc(Tc))){buildRealObject(){return new RA(this)}get nature(){return jA}};LA=tg([Ny("decal")],LA);class FA extends Mu{getObject3dInstance(){return new t.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const NA="#dde2e8",$A="#9c9c9c",HA="#e8e8ec",BA=.35;function YA(e,n,i,s,r){if(!n.visible)return new t.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=n.alpha*i,a="wall"===s?NA:"floor"===s?$A:HA,c=new t.MeshStandardMaterial({metalness:0,roughness:"wall"===s?.6:.85,transparent:o<1,opacity:o,side:r?t.BackSide:t.DoubleSide});return function(t,e,n,i,s,r){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const i=!r,o=Mu.buildFillStyleTexture(e,n,{mirror:i,rotation:s});if(o)return t.map&&t.map.dispose(),t.map=o,void t.color.set("#ffffff")}t.color.set(i)}}(c,e,n.fillStyle,a,n.rotation,n.mirror),c}class GA extends FA{get zPriority(){return gu.BACKDROP}get position(){if(this.component.state.fitToBoard){return{x:0,y:super.position.y,z:0}}return super.position}build(){super.build();const e=this.component.state;let n=e.width,i=e.height;if(e.fitToBoard){const t=this.component.rootModel,e=t?.state;e&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&(n=e.width,i=e.height)}const s=this.effectiveDepth||Math.min(n,i)||200,r=e.alpha??1,o=!1!==e.seeThrough,a={east:this._resolveFace("east",NA,!0,BA),west:this._resolveFace("west",NA,!0,BA),north:this._resolveFace("north",NA,!0,BA),south:this._resolveFace("south",NA,!0,BA),floor:this._resolveFace("floor",$A,!0,1),ceiling:this._resolveFace("ceiling",HA,!0,1)},c=[YA(this.component,a.east,r,"wall",o),YA(this.component,a.west,r,"wall",o),YA(this.component,a.ceiling,r,"ceiling",o),YA(this.component,a.floor,r,"floor",o),YA(this.component,a.south,r,"wall",o),YA(this.component,a.north,r,"wall",o)],l=new t.BoxGeometry(n,s,i),h=new t.Mesh(l,c);if(h.receiveShadow=!0,this.object3d.add(h),this.component.app?.isEditMode){const e=new t.LineBasicMaterial({color:4473941,transparent:!0,opacity:.7}),n=new t.LineSegments(new t.EdgesGeometry(l),e);this.object3d.add(n)}const d=Math.max(2,.04*Math.min(n,i,s));this.object3d.add(zA(this.component,{size:d,position:[n/2,s/2+d,-i/2]}))}_resolveFace(t,e,n,i){const s=this.component.state,r=s.faces?.[t]??{},o=r.visible,a=r.alpha,c=r.rotation,l=90===c||180===c||270===c?c:0;return{fillStyle:r.fillStyle??e,visible:"boolean"==typeof o?o:n,alpha:"number"==typeof a&&Number.isFinite(a)?a:i,rotation:l,mirror:!0===r.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 VA={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 UA=class extends(Ry(Pc(Tc))){buildRealObject(){return new GA(this)}get nature(){return VA}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 i={},s=Number.isFinite(n.width)?n.width:this.state.width,r=Number.isFinite(n.height)?n.height:this.state.height;s!==this.state.width&&(i.width=s),r!==this.state.height&&(i.height=r);const o=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(o!==this.state.left&&(i.left=o),a!==this.state.top&&(i.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(s,r);e!==t&&(i.depth=e)}}Object.keys(i).length>0&&this.set(i)}_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 WA(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function qA(e,n,i,s){const r=[];for(let o=1;o<=s;o++){const a=o/s,c=1-a;r.push(new t.Vector3(c*c*e.x+2*c*a*n.x+a*a*i.x,c*c*e.y+2*c*a*n.y+a*a*i.y,c*c*e.z+2*c*a*n.z+a*a*i.z))}return r}UA=tg([Ny("backdrop")],UA);class XA extends Mu{getObject3dInstance(){return new t.Group}get gizmoTransformable(){return!0}get syncZPosOffset(){return 0}get geometricOffsetY(){return 0}syncFromObject3D(){}applyDimensionFromGizmo(t){}build(){super.build(),this._buildLine()}get smoothedPath(){const e=this.worldPath;if(e.length<2)return e;const{round:n=0}=this.component.state;if(n<=0||e.length<3)return e;const i=[];i.push(e[0]);for(let s=1;s<e.length;s++){const r=e[s-1],o=e[s],a=e[s+1];if(!a){i.push(o);break}const c=r.x-o.x,l=r.y-o.y,h=r.z-o.z,d=Math.sqrt(c*c+l*l+h*h),u=Math.min(n,d/2),p=a.x-o.x,f=a.y-o.y,m=a.z-o.z,g=Math.sqrt(p*p+f*f+m*m),y=Math.min(n,g/2),b=d>0?new t.Vector3(o.x+c/d*u,o.y+l/d*u,o.z+h/d*u):o.clone(),v=g>0?new t.Vector3(o.x+p/g*y,o.y+f/g*y,o.z+m/g*y):o.clone();i.push(b),i.push(...qA(b,o,v,8))}return i}_buildLine(){const e=this.smoothedPath;if(e.length<2)return;const{strokeStyle:n,lineWidth:i=2,alpha:s=1,lineDash:r,begin:o="none",beginSize:a="size5",end:c="none",endSize:l="size5"}=this.component.state,h=Math.max(i,1),d="string"==typeof n&&"transparent"!==n?iu(n):"#000000",u=new t.Color(d),p=this._getResolution(),f=o,m=c,g=WA(f,h),y=WA(m,h),b=e[0],v=e[e.length-1],_=(new t.Vector3).subVectors(e[1],b).normalize(),x=(new t.Vector3).subVectors(e[e.length-2],v).normalize(),A=[...e];g>0&&(A[0]=b.clone().add(_.clone().multiplyScalar(g))),y>0&&(A[A.length-1]=v.clone().add(x.clone().multiplyScalar(y)));const E=new S;E.setPositions(A.flatMap(t=>[t.x,t.y,t.z]));const k=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}}(r,h),C=new M({color:u.getHex(),linewidth:h,worldUnits:!0,transparent:s<1,opacity:s,resolution:p,dashed:!!k,dashSize:k?.dashSize??1,gapSize:k?.gapSize??1,dashScale:1});if(this._line2=new w(E,C),this._line2.computeLineDistances(),this.object3d.add(this._line2),"none"!==f){const e=Vp(f,Gp(a,h));if(e){const n=(new t.Quaternion).setFromUnitVectors(new t.Vector3(1,0,0),_.clone().negate());this._placeTip(e,b,n,u,s,p)}}if("none"!==m){const e=Vp(m,Gp(l,h));if(e){const n=(new t.Quaternion).setFromUnitVectors(new t.Vector3(1,0,0),x.clone().negate());this._placeTip(e,v,n,u,s,p)}}}_placeTip(t,e,n,i,s,r){const o=t.mesh||t.line2||t.group;if(o){if(o.position.copy(e),o.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(i),e.transparent=s<1,e.opacity=s}else if(t.line2){const e=t.line2.material;e.color.copy(i),e.transparent=s<1,e.opacity=s,e.resolution.copy(r)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(i),e.transparent=s<1,e.opacity=s,e.resolution&&e.resolution.copy(r)}});this.object3d.add(o)}}_getResolution(){const e=this.threeContainer?.renderer3d;if(e){return e.getSize(new t.Vector2)}return new t.Vector2(window.innerWidth,window.innerHeight)}onGizmoDragEnd(t){const e=this._component,n=e.path;if(!n||n.length<2)return;const i=this.object3d,{width:s=0,height:r=0}=e.parent?.bounds??{},{x:o,y:a}=e.center,c=i.position,l=i.rotation,h=i.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=XA.computeBakedPath(n,{x:o,y:a},{width:s,height:r},i);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(e,n,i,s){const r=i.width,o=i.height,a=n.x,c=n.y;return s.updateMatrixWorld(!0),e.map(e=>{const n=new t.Vector3(e.x-a,e.z||0,e.y-c).applyMatrix4(s.matrixWorld),i={x:n.x+r/2,y:n.z+o/2};return Math.abs(n.y)>.001&&(i.z=n.y),i})}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),hu(t)}return this._line2=void 0,super.clear()}}class KA extends XA{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center,s=this.component,r=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((s,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(s.x-n,s.z||r+(o-r)*c,s.y-i)})}}Jp("line",t=>new KA(t));class QA extends XA{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center;return e.map(e=>new t.Vector3(e.x-n,e.z||0,e.y-i))}}Jp("polyline",t=>new QA(t));class JA extends XA{get worldPath(){const e=this.component.drawPath;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center,s=this.component,r=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((s,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(s.x-n,s.z||r+(o-r)*c,s.y-i)})}}function ZA(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}Jp("ortholine",t=>new JA(t)),Jp("group",t=>new FA(t));class tE{constructor(e){this._count=0,this._placements=[],this._geometry=e.geometry,this._material=e.material,this._capacity=Math.max(1,e.capacity??16),this._name=e.name??"instanced",this._castShadow=e.castShadow??!0,this._receiveShadow=e.receiveShadow??!1,this.object3d=new t.Group,this.object3d.name=this._name,this._mesh=this._makeMesh(this._capacity),this.object3d.add(this._mesh)}_makeMesh(e){const n=new t.InstancedMesh(this._geometry,this._material,e);return n.name=this._name+"__instances",n.castShadow=this._castShadow,n.receiveShadow=this._receiveShadow,n.instanceMatrix.setUsage(t.DynamicDrawUsage),n.count=0,n}get mesh(){return this._mesh}get count(){return this._count}get capacity(){return this._capacity}place(t){const e=t.length;if(e>this._capacity){const t=ZA(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=ZA(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=tE;n._p.set(e.position.x,e.position.y,e.position.z);const i=e.rotation;n._e.set(i?.x??0,i?.y??0,i?.z??0),n._q.setFromEuler(n._e);const s=e.scale;"number"==typeof s?n._s.set(s,s,s):n._s.set(s?.x??1,s?.y??1,s?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){tE._c.set(e),this._mesh.setColorAt(t,tE._c)}}function eE(t,e,n){const i=Math.max(1,Math.floor(t.x??1)),s=Math.max(1,Math.floor(t.y??1)),r=Math.max(1,Math.floor(t.z??1)),o=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<s;t++)for(let e=0;e<r;e++)for(let n=0;n<i;n++)u.push({position:{x:l+n*o,y:h+t*a,z:d+e*c}});return u}tE._m=new t.Matrix4,tE._p=new t.Vector3,tE._q=new t.Quaternion,tE._e=new t.Euler,tE._s=new t.Vector3,tE._c=new t.Color;class nE extends Mu{build(){super.build()}update(){}}const iE={far:1e5,fov:80,near:1,zoom:1};class sE extends Mu{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new t.PerspectiveCamera}updateCamera(){const{near:t=iE.near,far:e=iE.far,fov:n=iE.fov,zoom:i=iE.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=i}}class rE extends SS{buildGeometry(){const{width:e,height:n}=this.component.state.dimension;this.object3d.geometry=new t.PlaneGeometry(e,n)}buildMaterial(){this.object3d.material=new t.MeshStandardMaterial({opacity:0,side:t.DoubleSide,blending:t.NoBlending})}}class oE extends Mu{getObject3dInstance(){return new t.Scene}dispose(){for(const t of this.object3d.children)hu(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=yf(this.component)}updateTransform(){}updateDimension(){}updatePosition(){}updateRotate(){}updateScale(){}updateAlpha(){}updateHidden(){}get animationMixer(){return this._animationMixer||(this._animationMixer=new t.AnimationMixer(this.object3d)),this._animationMixer}}const aE=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class cE extends Mu{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 t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds;if(!e||!n)return;const i=Id(this.component.state.material3d),s=new t.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const r=mS(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,i),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.receiveShadow}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;nu(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&&(yS(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(!aE.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=Id(this.component.state.material3d);Rd(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),hu(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 lE={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"};let hE=class extends lg{constructor(){super(...arguments),this._capability=new qf}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:i,threed:s}=this.state;let{width:r,height:o}=this.bounds;if(r=Math.floor(r),o=Math.floor(o),s){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 s=this._capability.domElement;if(!s||!s.width||!s.height)return;t.drawImage(s,0,0,s.width,s.height,e,n,r,o),i&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return Lc.get("three")}get nature(){return lE}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()}};hE=tg([Ny("3d-container")],hE),Zp(t=>new vS(t));let dE=null;function uE(t){dE=t}function pE(t,e=[],n){dE?.registerType?.(t,e,n)}function fE(t){if(Array.isArray(t))return`[${t.map(fE).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${fE(e[t])}`).join(",")}}`}return JSON.stringify(t)}const mE=new Map;function gE(t){const e=function(t){const e=fE(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}|${tw}`,i=mE.get(n);if(i)return mE.delete(n),mE.set(n,i),i;const s=Zx(structuredClone(t)),r=new Map;for(const t of s.document.model.nodes)for(const e of Object.values(t.outputs))r.set(e,t.id);const o={key:n,fingerprint:e,kernel:tw,compiled:Jx(s),document:Vx(s.document),looks:new Map(s.appearance.map(t=>[t.target,t])),writers:r,asset:s};return mE.set(n,o),mE.size>256&&mE.delete(mE.keys().next().value),o}const yE=new Map;function bE(t,e){Jx(e);const n={type:t,compiled:gE(e)};return yE.set(t,n),pE(t,e.document.capabilities.names??[],Zx(e).placement),n}function vE(t){return yE.get(t)??null}function _E(t){return yE.has(t)}function xE(t){return yE.delete(t)}function wE(){yE.clear()}const ME=["x","y","z"],SE=new WeakMap;function AE(t){let e=SE.get(t);return e||SE.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,i=ME.every(t=>"number"==typeof n[hb[t]]&&e.some(e=>e.id===hb[t])),s={};if(i)for(const t of ME){const n=e.find(e=>e.id===hb[t]);s[t]={min:n.min??0,max:n.max??1/0}}const r=Nv(t.document.model),o=t.occupancy?.bounds,a=e=>{if(!o)return{x:1,y:1,z:1};const n={...t.designInputs,...t.stateDefaults};if(e)for(const t of ME)n[hb[t]]=e[t];const i=r.evaluate(n).values,s=t=>Math.max((i[o[t].max]??0)-(i[o[t].min]??0),1e-6);return{x:s("x"),y:s("y"),z:s("z")}},c=i?{x:n[hb.x],y:n[hb.y],z:n[hb.z]}:null,l=!i||"uniform"===t.sizing,h=a(c),d={};if(c&&l){const t=Math.min(2,...ME.map(t=>s[t].max/c[t])),e=Math.max(.5,...ME.map(t=>s[t].min/c[t])),n=t>1?t:e<1?e:1;if(1!==n){const t=a({x:c.x*n,y:c.y*n,z:c.z*n});for(const e of ME)d[e]=(t[e]-h[e])/(c[e]*(n-1))}}else if(c)for(const t of ME){const{min:e,max:n}=s[t],i=c[t],r=n>i?Math.min(n,2*i):e<i?Math.max(e,i/2):i;if(r===i)continue;const o=a({...c,[t]:r});d[t]=(o[t]-h[t])/(r-i)}return{evaluated:i,proportional:l,limits:s,authoredInputs:c,authored:h,occupancyAt:a,inputFor:(t,e)=>{if(!c)return e;const n=d[t]??0;return Math.abs(n)>1e-9?c[t]+(e-h[t])/n:c[t]}}}(t)),e}function EE(t){return AE(t).proportional}function kE(t,e,n=[]){const i=AE(t),s=n.find(t=>void 0!==e[t])??"x",r=(t,e)=>{const n=i.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!i.evaluated){const t=Math.max(e[s]/i.authored[s],1e-6);return{inputs:null,scale:t,occupancy:{x:i.authored.x*t,y:i.authored.y*t,z:i.authored.z*t}}}const o=i.authoredInputs;let a;if(i.proportional){let t=Math.max(i.inputFor(s,e[s])/o[s],1e-6);for(const e of ME){const n=i.limits[e];n&&(t=Math.min(Math.max(t,n.min/o[e]),n.max/o[e]))}a={x:o.x*t,y:o.y*t,z:o.z*t}}else a={x:r("x",i.inputFor("x",e.x)),y:r("y",void 0!==e.y?i.inputFor("y",e.y):o.y),z:r("z",i.inputFor("z",e.z))};return{inputs:a,scale:1,occupancy:i.occupancyAt(a)}}const CE=Math.cos(40*Math.PI/180);function TE(e){const[n,i]=fb[e];return([s,r],o)=>{const a={x:0,y:0,z:0};return a[n]=s,a[i]=r,a[e]=o,new t.Vector3(a.x,a.y,a.z)}}class OE{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,i,s,r){for(const[o,a]of[[t,i],[e,s],[n,r]])this.positions.push(o.x,o.y,o.z),this.normals.push(a.x,a.y,a.z)}facing(e,n,i,s){(new t.Vector3).subVectors(n,e).cross((new t.Vector3).subVectors(i,e)).dot(s)<0?this.tri(e,i,n,s,s,s):this.tri(e,n,i,s,s,s)}geometry(){const e=new t.BufferGeometry;return e.setAttribute("position",new t.Float32BufferAttribute(this.positions,3)),e.setAttribute("normal",new t.Float32BufferAttribute(this.normals,3)),e}}function PE(e,n,i,s,r,o){const a=TE(i),c=n.length,l=n.map((t,e)=>{const i=n[(e+1)%c],s=i[0]-t[0],r=i[1]-t[1],a=Math.hypot(s,r)||1;return[o*r/a,-o*s/a]}),h=t=>a(t,0),d=(t,e)=>{const n=l[t],i=l[e];return n[0]*i[0]+n[1]*i[1]<CE?h(n):h([n[0]+i[0],n[1]+i[1]]).normalize()};for(let i=0;i<c;i++){const o=n[i],u=n[(i+1)%c],p=d(i,(i-1+c)%c),f=d(i,(i+1)%c),m=a(o,s),g=a(u,s),y=a(u,r),b=a(o,r),v=h(l[i]);(new t.Vector3).subVectors(g,m).cross((new t.Vector3).subVectors(y,m)).dot(v)>=0?(e.tri(m,g,y,p,f,f),e.tri(m,y,b,p,f,p)):(e.tri(m,y,g,p,f,f),e.tri(m,b,y,p,p,f))}}function IE(e,n,i,s,r,o){const a=TE(i),c=a([0,0],r),l=n.map(([e,n])=>new t.Vector2(e,n)),h=o?[o.map(([e,n])=>new t.Vector2(e,n))]:[],d=t.ShapeUtils.triangulateShape(l,h),u=[...n,...o??[]];for(const[t,n,i]of d)e.facing(a(u[t],s),a(u[n],s),a(u[i],s),c)}const DE=new Map;let zE=0,RE=67108864;function jE(){return{entries:DE.size,bytes:zE,limit:RE}}function LE(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),i=t.extrusion,s=t.cavity,r=t.revolution,o=t.loft,a=i?`${i.axis}:${i.section.kind}:${s?`${"open"===s.start?"o":"c"}${"open"===s.end?"o":"c"}`:"-"}`:r?`${r.axis}:${r.profile.kind}`:o?`${o.axis}:point`:"";return`${t.provider}|${a}|${n}|s${e}|p1`}function FE(t,e=12,n=1/0){const i=LE(t,e),s=DE.get(i);if(s)return s.users++,s.geometry;const r=$E(t,e),o=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(r);if(zE+o>RE||o>n)throw r.dispose(),new Error("figure: geometry bank budget exceeded");return r.userData.figureKey=i,DE.set(i,{geometry:r,users:1,bytes:o}),zE+=o,r}function NE(t){const e=t.userData.figureKey;if(!e)return;const n=DE.get(e);n&&--n.users<=0&&(DE.delete(e),zE-=n.bytes,n.geometry.dispose())}function $E(e,n=12){if("extrude"===e.provider&&e.extrusion)return function(t,e){const n=t.extrusion,i=aw(n.section,n.axis,e),s=new OE;PE(s,i,n.axis,n.start,n.end,1);const r=t.cavity,o=r&&Eb(n.section,n.axis,r.wall);if(!r||!o||!("section"in o))return IE(s,i,n.axis,n.start,-1),IE(s,i,n.axis,n.end,1),s.geometry();const a=aw(o.section,n.axis,e,o.centre),c=n.start+("open"===r.start?0:r.start.closed),l=n.end-("open"===r.end?0:r.end.closed);return PE(s,a,n.axis,c,l,-1),"open"===r.start?IE(s,i,n.axis,n.start,-1,a):(IE(s,i,n.axis,n.start,-1),IE(s,a,n.axis,c,1)),"open"===r.end?IE(s,i,n.axis,n.end,1,a):(IE(s,i,n.axis,n.end,1),IE(s,a,n.axis,l,-1)),s.geometry()}(e,n);if("revolve"===e.provider&&e.revolution)return function(e,n){const i=e.profile;let s;return"half-ellipse"===i.kind?s=new t.SphereGeometry(1,n,Math.max(2,Math.round(n/2))).scale(i.radial,i.axial,i.radial):(s=new t.CylinderGeometry(i.endRadius,i.startRadius,i.end-i.start,n),s.translate(0,(i.start+i.end)/2,0)),"x"===e.axis&&s.rotateZ(-Math.PI/2),"z"===e.axis&&s.rotateX(Math.PI/2),s}(e.revolution,n);const i=e.loft;return"loft"===e.provider&&i?function(e){const[n,i]=fb[e.axis],s=TE(e.axis),r=aw(e.section,e.axis,0),o=s([e.apex[n],e.apex[i]],e.end),a=new OE;IE(a,r,e.axis,e.start,e.end>e.start?-1:1);const c=r.length;for(let n=0;n<c;n++){const i=s(r[n],e.start),l=s(r[(n+1)%c],e.start),h=(new t.Vector3).subVectors(l,i).cross((new t.Vector3).subVectors(o,i)).normalize();a.tri(i,l,o,h,h,h)}return a.geometry()}(i):new t.BufferGeometry}const HE=new Map;let BE=0,YE=0,GE=67108864;function VE(e,n=1/0){const i=(t=>t.map(t=>LE(t.shape,t.segments)).join(";"))(e),s=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const i=t.pose.r,s=t.pose.t;e.set([i[0][0],i[0][1],i[0][2],i[1][0],i[1][1],i[1][2],i[2][0],i[2][1],i[2][2],s[0],s[1],s[2]],12*n)}),e}(e),r=HE.get(i),o=r?.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 a=e.map(t=>FE(t.shape,t.segments));try{const o=a.map(t=>t.getAttribute("position")?.count??0),c=o.reduce((t,e)=>t+e,0),l=6*c*4;if(l>n)throw new Error("figure: LOD transition budget exceeded");if(YE+l>GE)return null;const h=new Float32Array(3*c),d=new Float32Array(3*c),u=new Int32Array(e.length+1),p=new t.Matrix4,f=new t.Matrix3;let m=0;e.forEach((t,e)=>{u[e]=m/3;const{r:n,t:i}=t.pose;p.set(n[0][0],n[0][1],n[0][2],i[0],n[1][0],n[1][1],n[1][2],i[1],n[2][0],n[2][1],n[2][2],i[2],0,0,0,1),f.getNormalMatrix(p);const s=p.elements,r=f.elements,c=a[e].getAttribute("position"),l=a[e].getAttribute("normal");for(let t=0;t<o[e];t++,m++){const e=c.getX(t),n=c.getY(t),i=c.getZ(t);if(h[3*m]=s[0]*e+s[4]*n+s[8]*i+s[12],h[3*m+1]=s[1]*e+s[5]*n+s[9]*i+s[13],h[3*m+2]=s[2]*e+s[6]*n+s[10]*i+s[14],!l)continue;const o=l.getX(t),a=l.getY(t),u=l.getZ(t),p=r[0]*o+r[3]*a+r[6]*u,f=r[1]*o+r[4]*a+r[7]*u,g=r[2]*o+r[5]*a+r[8]*u,y=Math.hypot(p,f,g)||1;d[3*m]=p/y,d[3*m+1]=f/y,d[3*m+2]=g/y}}),u[e.length]=m/3;const g=new t.BufferGeometry;g.setAttribute("position",new t.BufferAttribute(h,3)),g.setAttribute("normal",new t.BufferAttribute(d,3)),g.computeBoundingSphere(),g.computeBoundingBox();const y={geometry:g,starts:u,users:1,bytes:l,poses:s};return g.userData.figureMergedKey=i,g.userData.figureMergedEntry=y,r?r.push(y):HE.set(i,[y]),BE++,YE+=l,y}finally{for(const t of a)NE(t)}}function UE(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,i=void 0===e?void 0:HE.get(e);!n||!i?.includes(n)||--n.users>0||(i.splice(i.indexOf(n),1),i.length||HE.delete(e),BE--,YE-=n.bytes,n.geometry.dispose())}function WE(){let t=0;for(const e of HE.values())for(const n of e)t+=n.users;return{entries:BE,users:t,bytes:YE,limit:GE}}const qE=t=>1e-9*Math.round(t/1e-9)+0;class XE{static carrierJudgeOf(t){let e=XE.carrierJudges.get(t);return e||XE.carrierJudges.set(t,e=function(t,e){const n=e??Vx(t.document).dependence,i=new Map(t.document.model.nodes.map(t=>[t.id,t])),s=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))s.set(t,e);const r=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target)),o=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=s.get(t),i="compose@1"!==n?.op||"string"!=typeof n.args[0]||o(n.args[1])?t:c(n.args[0]);return a.set(t,i),i};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||r.has(n.id))continue;const t=i.get(n.id),s="place@1"===t?.op?t.args[1]:void 0;"string"==typeof s&&o(s)&&!o(t.args[0])&&e.set(n.id,c(s))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=XE.stillJudges.get(t);return e||XE.stillJudges.set(t,e=iw(t.asset,t.document.dependence)),e}constructor(e,n={}){this._lodRevision=0,this._lodGeometryRevision=0,this.boundsAt=-1,this.semanticBounds=new t.Box3,this.group=new t.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.flags=new Map,this.materials=new Map,this.dressed=new Map,this.drawnWith=new Map,this.lastDrawn=null,this.slots=[],this.generation=-1,this.clamped=[],this.compiled=gE(e),this.theme=n.theme??{},this.merge=!1!==n.merge,this._renderLevel=n.renderLevel??"full",this.group.name=`figure:${e.name}`}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 i=this.slots[t];if(i&&"mesh"in i)return n.copy(i.mesh.matrix);if(i&&"entry"in i)return i.entry.set.mesh.getMatrixAt(i.index,n),n;if(i&&"rides"in i){const t=i.rides,s=12*t.ids.indexOf(e.id),r=t.relative;return n.set(r[s],r[s+1],r[s+2],r[s+9],r[s+3],r[s+4],r[s+5],r[s+10],r[s+6],r[s+7],r[s+8],r[s+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(XE.matrixOf(e.pose)):n.identity()}lodBounds(e){if(this.boundsAt!==this._lodRevision){this.semanticBounds.makeEmpty();const e=new t.Matrix4,n=new t.Box3;this.lastDrawn?.geometry.forEach((i,s)=>{if(!("shape"in i)||!("pose"in i)||!1===i.visible)return;let r=XE.shapeBounds.get(i.shape);if(!r){const e=Qb(i.shape);r=new t.Box3(new t.Vector3(e.x.min,e.y.min,e.z.min),new t.Vector3(e.x.max,e.y.max,e.z.max)),XE.shapeBounds.set(i.shape,r)}this.semanticBounds.union(n.copy(r).applyMatrix4(this.bodyMatrix(s,i,e)))}),this.boundsAt=this._lodRevision}return e.copy(this.semanticBounds)}setRenderLevel(e){if(!["full","medium","coarse"].includes(e))throw new Error(`figure: unknown render level ${e}`);if(e===this._renderLevel)return!0;const n=this._renderLevel,i=this.lastDrawn;if(this.lastLodError=void 0,!i||i.geometry.every(t=>db(t,n)===db(t,e)))return this._renderLevel=e,!0;const s=new t.Matrix4,r=i.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={...i,geometry:r},a=ub(o,e),c=[],l=[],h=jE().bytes+WE().bytes,d=()=>XE.LOD_TRANSITION_LIMIT_BYTES-(jE().bytes+WE().bytes-h);try{const e=new Set;for(const t of a.geometry){if(!("shape"in t))continue;const n=LE(t.shape,t.segments);e.has(n)||(e.add(n),c.push(FE(t.shape,t.segments,d())))}const n=rw(a.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf}:{}),i=new Map(a.geometry.map(t=>[t.id,t]));for(const e of[...n.merged,...n.carried]){let n=e.ids.map(t=>i.get(t));if("carrier"in e){const e=(new t.Matrix4).copy(XE.matrixOf(n[0].pose)).invert(),i=new t.Matrix4;n=n.map(t=>{const n=i.multiplyMatrices(e,XE.matrixOf(t.pose)).elements,s=t=>qE(n[t]);return{...t,pose:{r:[[s(0),s(4),s(8)],[s(1),s(5),s(9)],[s(2),s(6),s(10)]],t:[s(12),s(13),s(14)]}}})}const s=VE(n,d());s&&l.push(s.geometry)}if(jE().bytes+WE().bytes-h>XE.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 l)UE(t);for(const t of c)NE(t);return!1}try{return this._renderLevel=e,this.draw(o,this.generation),!0}finally{for(const t of l)UE(t);for(const t of c)NE(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(hb.x)&&e(hb.y)&&e(hb.z)?{x:t[hb.x],y:t[hb.y],z:t[hb.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const i of["x","y","z"]){const s=e.find(t=>t.id===hb[i]);if(!s)continue;const r=t[i],o=Math.min(Math.max(r,s.min??-1/0),s.max??1/0);o!==r&&this.clamped.push({axis:i,asked:r,used:o,bound:o>r?"min":"max"}),n[i]=o}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)),i=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),s={};for(const[r,o]of Object.entries(t??{})){const t=i.get(r);let a;n.has(r)&&t?"number"==typeof o&&Number.isFinite(o)?(o<t.min||o>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:r,value:o,reason:a}),r in this.design&&(s[r]=this.design[r])):s[r]=o}try{this.compiled.document.evaluate({...this.evaluationInputs(),...s}),this.design=s}catch(t){for(const[n,i]of Object.entries(s))e.push({input:n,value:i,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=>XE.clipOf(t)))]}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{units:t,states:e}=this.inputsRead(),n={};for(const e of this.asset.drivers??[]){if(e.state in this.external)continue;const i=t.get(e.state);n[e.state]=Xx(e,this.clipTime(XE.clipOf(e)),"deg"===i||"rad"===i?i:"other")}for(const[t,i]of Object.entries(this.external))e.has(t)&&(n[t]=i);return n}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 i="changes"===e.kind?this.fromChanges(e,t):null;this.draw(i??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const i=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||i.has(n)||!t.structure&&!t.changed(n))continue;const s=!0===t.read(n);this.flags.get(n)!==s&&i.add(n),this.flags.set(n,s)}const s=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),r=new Int32Array(s.length).fill(-1);for(let e=0;e<t.bodies.length;e++){if(!t.shapes[e])return null;r[t.bodies[e]]=e}for(let e=0;e<s.length;e++){const n=r[e],o=s[e];if(n<0&&!(o&&i.size&&void 0!==this.flagOf(o)&&i.has(this.flagOf(o))))continue;const a=t.structure?t.structure.ids[e]:o.id,c=t.structure?t.structure.keys[e]:o.key,l={id:a},h=t.structure?t.structure.paths[e]:o.path;void 0!==h&&(l.path=h),void 0!==c&&(l.key=c);const d=t.structure?t.structure.indexes[e]:o.index;if(void 0!==d&&(l.index=d),n>=0){const e=t.poses,i=12*n;l.shape=t.shapes[n],l.pose={r:[[e[i],e[i+1],e[i+2]],[e[i+3],e[i+4],e[i+5]],[e[i+6],e[i+7],e[i+8]]],t:[e[i+9],e[i+10],e[i+11]]}}else l.shape=o.shape,l.pose=o.pose;s[e]=this.dressBody(l)}const o=new Map((t.structure?[]:n.bindings).map(t=>[t.id,t]));for(const e of t.places)o.set(e.id,e);return{geometry:s,bindings:[...o.values()],inputs:e,palette:{...this.asset.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,i=this.compiled.looks.get(n);if(!i)throw new Error(`figure: no appearance for ${n}`);const s=void 0===i.visibility||e(i.visibility);let r=this.materials.get(n);r||this.materials.set(n,r=structuredClone(i.material));const o={...t,material:r,visible:s};return void 0!==i.segments&&(o.segments=i.segments),{dressed:o,visible:s,ref:i.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=XE.matrix,n=new Set;for(let i=0;i<t.bodies.length;i++){const s=this.slots[t.bodies[i]];if(!s)continue;const r=t.poses,o=12*i;if(e.set(r[o],r[o+1],r[o+2],r[o+9],r[o+3],r[o+4],r[o+5],r[o+10],r[o+6],r[o+7],r[o+8],r[o+11],0,0,0,1),!("merged"in s)&&!("rides"in s))if("mesh"in s){s.mesh.matrix.copy(e),s.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(s.id);t&&(t.pose=void 0)}else s.entry.set.setMatrix(s.index,e),n.add(s.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&&XE.pose(t,e.pose)}}draw(e,n){this.lastDrawn=e,this._lodRevision++,this._lodGeometryRevision++,e=ub(e,this._renderLevel);const i=this.planOf(e.geometry),s=new Map(e.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),r=this.drawCarried(i,s,this.drawMerged(i,s)),o=new Set;for(const e of r){const n=s.get(e);if(!("pose"in n))continue;o.add(e);let i=this.meshes.get(e);const r=!1!==n.visible,a=this.drawnWith.get(e);if(!i||!a||a.shape!==n.shape||a.segments!==n.segments){const s=FE(n.shape,n.segments);i?i.geometry!==s?(NE(i.geometry),i.geometry=s):NE(s):(i=new t.Mesh(s,this.materialFor(n)),i.name=e,i.matrixAutoUpdate=!1,this.meshes.set(e,i),r&&this.group.add(i))}a&&a.pose===n.pose||XE.pose(i,n.pose),this.drawnWith.set(e,{shape:n.shape,segments:n.segments,pose:n.pose}),i.castShadow=r,r&&i.parent!==this.group?this.group.add(i):r||i.parent!==this.group||this.group.remove(i)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),NE(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const a=new Set;for(const t of i.batches){a.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 i=FE(e.shape,e.segments);n={set:new tE({geometry:i,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:i},this.batches.set(t.key,n)}const{set:i}=n,r=i.count!==t.ids.length;i.setCount(t.ids.length);const o=i.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=s.get(t);if(!("pose"in n))return;XE.matrixOf(n.pose);const r=XE.matrix.elements;for(let t=0;t<16&&!c;t++)o[16*e+t]!==Math.fround(r[t])&&(c=!0);i.setMatrix(e,XE.matrix)}),n.ids=t.ids,r||!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)a.has(t)||(e.set.object3d.parent===this.group&&this.group.remove(e.set.object3d),e.set.dispose(),NE(e.geometry),this.batches.delete(t));for(const t of e.bindings){const e=this.places.get(t.id);e&&XE.pose(e,t.pose)}const c=new Map;for(const t of this.batches.values())t.ids.forEach((e,n)=>c.set(e,{entry:t,index:n}));for(const t of this.merged.values())for(const e of t.ids)c.set(e,{merged:t});const l=new Map;for(const t of this.carried.values())t.ids.forEach((e,n)=>0===n?l.set(e,t.mesh):c.set(e,{rides:t}));this.slots=e.geometry.map(t=>{const e=this.meshes.get(t.id)??l.get(t.id);return e?{mesh:e,id:t.id}:c.get(t.id)??null}),this.generation=n}drawMerged(e,n){const i=[...e.alone],s=new Set;for(const r of e.merged){const e=r.ids.map(t=>n.get(t));let o=this.merged.get(r.key);if(!(o&&o.ids.length===e.length&&e.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))){const n=VE(e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!n){i.push(...r.ids);continue}if(o)UE(o.mesh.geometry),o.mesh.geometry=n.geometry,o.ids=r.ids,o.starts=n.starts;else{const i=new t.Mesh(n.geometry,this.materialFor(e[0]));i.name=`figure-merged:${this.merged.size}`,i.matrixAutoUpdate=!1,i.castShadow=!0,o={mesh:i,ids:r.ids,starts:n.starts,made:[]},this.merged.set(r.key,o)}o.made=e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose}))}s.add(r.key);const a=!1!==e[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),UE(e.mesh.geometry),this.merged.delete(t));return i}drawCarried(e,n,i){const s=new Set,r=new t.Matrix4,o=new t.Matrix4;for(const a of e.carried){const e=a.ids.map(t=>n.get(t));r.copy(XE.matrixOf(e[0].pose)).invert();const c=e.map(t=>{const e=o.multiplyMatrices(r,XE.matrixOf(t.pose)).elements,n=t=>qE(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)]}}),l=new Float64Array(c.flatMap(t=>[...t.r.flat(),...t.t]));let h=this.carried.get(a.key);if(!(h&&h.ids.length===e.length&&e.every((t,e)=>t.id===h.ids[e]&&t.shape===h.made[e].shape&&t.segments===h.made[e].segments)&&l.every((t,e)=>t===h.relative[e]))){const n=VE(e.map((t,e)=>({shape:t.shape,segments:t.segments,pose:c[e]})));if(!n){i.push(...a.ids);continue}if(h)UE(h.mesh.geometry),h.mesh.geometry=n.geometry,h.ids=a.ids,h.starts=n.starts;else{const i=new t.Mesh(n.geometry,this.materialFor(e[0]));i.name=`figure-carried:${this.carried.size}`,i.matrixAutoUpdate=!1,i.castShadow=!0,h={mesh:i,ids:a.ids,starts:n.starts,made:[],relative:l},this.carried.set(a.key,h)}h.made=e.map(t=>({shape:t.shape,segments:t.segments})),h.relative=l}XE.pose(h.mesh,e[0].pose),s.add(a.key);const d=!1!==e[0].visible;d&&h.mesh.parent!==this.group?this.group.add(h.mesh):d||h.mesh.parent!==this.group||this.group.remove(h.mesh)}for(const[t,e]of this.carried)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),UE(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),i}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(e){let n=this.places.get(e);if(n)return n;if(!jx(this.asset).some(t=>t.id===e))return null;n=new t.Object3D,n.name=`place:${e}`,n.matrixAutoUpdate=!1,this.places.set(e,n),this.group.add(n);const i=this.evaluator&&this.lastDrawn?this.placeNow(e):this.evaluation().bindings.find(t=>t.id===e);return i&&XE.pose(n,i.pose),n}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(XE.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 i=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===i.length&&i.every((t,n)=>t===e.ids[n])||(this.stillOf=XE.stillJudgeOf(this.compiled)(t),this.carriedOf=XE.carrierJudgeOf(this.compiled)(t));const s=this.merge?this.stillOf:void 0,r=rw(t,s?{still:s,carried:this.carriedOf}:{});return this.planned={ids:i,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:r,still:s},r}static matrixOf(t){const e=t.r,n=t.t;return XE.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:i}=e;if(n<0||n>=i[i.length-1])return;let s=0,r=e.ids.length-1;for(;s<r;){const t=s+r+1>>1;i[t]<=n?s=t:r=t-1}return e.ids[s]}}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[hb.x]=this.size.x,t[hb.y]=this.size.y,t[hb.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;return{geometry:e.geometry.map(t=>this.dressOne(t,t=>!0===n[t]).dressed),bindings:e.bindings,inputs:t,palette:{...this.asset.palette}}}dress(t,e){const n=this.dressed,i=new Map,s=t.geometry.map(e=>{const s=n.get(e.id),r=this.dressOne(e,e=>!0===t.values[e]);return void 0!==r.ref&&this.flags.set(r.ref,r.visible),s&&s.body===e&&s.visible===r.visible?(i.set(e.id,s),s.dressed):(i.set(e.id,{body:e,visible:r.visible,dressed:r.dressed}),r.dressed)});return this.dressed=i,{geometry:s,bindings:t.bindings,inputs:e,palette:{...this.asset.palette}}}colourOf(t){return this.theme[t]??this.asset.palette[t]??"#9a9a9a"}materialFor(t){const e=t.material,n=Pd[e.preset??"default"]??Pd.default,i=!!e.emissive?.on,s=i&&e.emissive?this.colourOf(e.emissive.token):this.colourOf(e.token),r=i&&e.emissive?e.emissive.intensity:0,o=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${i?"on":"off"}|${s}|${r}`;return MS.material(o,{color:s,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:e.transparent??!1,opacity:e.transparent?n.opacity??.3:1,emissive:s,emissiveIntensity:r})}meshOf(t){return this.meshes.get(t)}drawnIds(){return[...[...this.meshes.values()].filter(t=>t.parent===this.group).map(t=>t.name),...[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).flatMap(t=>t.ids),...[...this.merged.values(),...this.carried.values()].filter(t=>t.mesh.parent===this.group).flatMap(t=>t.ids)]}dispose(){for(const t of this.meshes.values())t.parent===this.group&&this.group.remove(t),NE(t.geometry);this.meshes.clear(),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(),NE(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),UE(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),UE(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}XE.shapeBounds=new WeakMap,XE.LOD_TRANSITION_LIMIT_BYTES=16777216,XE.matrix=new t.Matrix4,XE.carrierJudges=new WeakMap,XE.stillJudges=new WeakMap;class KE extends Mu{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 vE(this.component.state.type)}getObject3dInstance(){return new t.Group}build(){super.build();const t=this.figure;t&&(this.rig=new XE(t.compiled.asset),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.update(),this.startTicking())}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()}applied(){const t=this.figure?.compiled.asset;if(!t)return null;const{width:e,height:n}=this.component.bounds,i=this.component.state.depth;return kE(t,{x:e,z:n,y:"number"==typeof i&&Number.isFinite(i)&&i>0?i:void 0})}instanceSize(){return this.applied()?.inputs??null}get effectiveDepth(){return this.applied()?.occupancy.y??super.effectiveDepth}get effectiveZPos(){const t=this.component.state.zPos;return"number"==typeof t&&Number.isFinite(t)?t:"ceiling"!==this.figure?.compiled.asset.placement?super.effectiveZPos:function(t,e,n){switch(t){case"inverted":return e;case"space":return e-n/2;default:return e-n}}(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)}seat(){if(!this.rig)return;const t=this.figure?.compiled.asset.placement;if("wall"===t)return this.rig.group.position.y=0,void(this.rig.group.position.z=-this.component.bounds.height/2);this.rig.group.position.z=0;const e=this.effectiveDepth,n=this.effectiveDepth-e,i="ceiling"===t?n:"center"===t?n/2:0;this.rig.group.position.y=-this.effectiveDepth/2+i}get sizeClamps(){return this.rig?.clamped??[]}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.drivers??[];this.unsubscribe||0===t.length||(this.unsubscribe=Rr.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 i=!1;for(const s of e.clips){const r=n[s]??0;Number.isFinite(r)&&0!==r&&(e.setClipTime(s,e.clipTime(s)+t/1e3*r),i=!0)}i&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,i=n?.placeNode(t);if(!n||!i)return;const s=jx(n.asset).find(e=>e.id===t)?.face,r=s&&Bv[s]||[0,0,0],o=t=>{const n=Number(e?.state?.[t]);return Number.isFinite(n)&&n>0?n/2:0};return{attach:i,localPosition:{x:r[0]*o("width"),y:r[1]*o("depth"),z:r[2]*o("height")}}}clear(){return this.unsubscribe?.(),this.unsubscribe=void 0,this.rig?.dispose(),this.rig=null,super.clear()}}function QE(t,e,n=1){const i=new XE(t.compiled.asset);i.setSize(e);const s=i.evaluateOnce(),r=function(t,e){const n=[];for(const i of t){if(!1===i.visible||!hw(i))continue;let t;try{t=Uv(Vv(i.shape,i.segments),i.pose.r,i.pose.t)}catch{continue}if(t.length<3)continue;const s=t=>t.map(t=>[t[0],t[2]]),r=Math.abs(i.pose.r[1][1]-1)<1e-6,o=i.shape.extrusion;let a;const c=[];if(r&&"y"===o?.axis){const t=(t,e)=>s(Uv(dw(t,o.end,i.segments??12,e),i.pose.r,i.pose.t));a=t(o.section);const e=i.shape.cavity;if(e&&"open"===e.end){const n=Eb(o.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=lw(s(t));const l=i.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:i.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)}(s.geometry,s.palette);return{shapes:1===n?r:r.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]))})),size:i.drawnSize}}const JE=ob,ZE=Object.freeze({Capacity:t=>mw(t),Holdable:t=>SM(t),Transferable:t=>AM(t),FlowNode:t=>EM(t)}),tk=Object.freeze({Capacity:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",Holdable:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",Transferable:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",FlowNode:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다"});function ek(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:[...t.accepts]}))}const nk=new Map;function ik(t,e=[],n){const i=new Set(e),s=[...i].filter(t=>!JE.includes(t));if(s.length>0)throw new Error(`모르는 능력이다: ${s.join(" · ")} — 쓸 수 있는 것은 ${JE.join(" · ")}`);for(const[t,e]of Object.entries(ab))if(i.has(t)&&!e.some(t=>i.has(t)))throw new Error(`${t} 은 혼자 설 수 없다 — ${e.join(" 이나 ")} 가 함께 있어야 한다`);const r=`${[...i].sort().join("+")}|${n??""}`,o=nk.get(r);if(o)return o;const a=0===i.size?t:(c=function(t,e){const n=t.capabilities??[],i=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(i),configurable:!0}),t}(function(t,e){if(e.has("FlowNode"))return ZE.FlowNode(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=ZE[t](n));return n}(t,i),i),class extends c{get _places(){const t=vE(this.state?.type)?.compiled.asset;return t?jx(t):null}get slots(){const t=this._places;return t?.length?ek(t):super.slots??[]}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,i=e?.slotId??t?.[tb],s=this._places;return s&&i&&s.some(t=>t.id===i)?this._realObject?.placeAttachment?.(i,t)??n():n()}});var c;const l=void 0===n?a: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}(a,n);return nk.set(r,l),l}function sk(){nk.clear()}const rk={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 ok extends(Pc(Tc)){static registerType(t,e=[],n){const i=Cc.register(t);if(i&&!(i===ok||i.prototype instanceof ok))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const s=ik(ok,e,n);Cc.register(t,s)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=vE(this.state.type);if(!t)return rk;const e=t.compiled.asset,n=e.document.model.inputs,i=(e.publicInputs??[]).flatMap(t=>{const i=n.find(e=>e.id===t.input);return i?[{key:t.input,label:t.label,unit:i.unit,min:i.min,max:i.max,default:e.designInputs[t.input]}]:[]}),s=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]})),r=[...new Set((e.drivers??[]).map(t=>t.clip))].map(t=>({key:t,label:t,min:0,max:3})),o=[...rk.properties];return i.length&&o.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:i}}),s.length&&o.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:s}}),r.length&&o.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),o.length===rk.properties.length?rk:{...rk,properties:o}}buildRealObject(){return _E(this.state.type)?new KE(this):void 0}render(t){const{left:e=0,top:n=0,width:i=0,height:s=0}=this.state,r=vE(this.state.type);if(!r)return void this.renderPlace(t,e,n,i,s);const o=this.topView(r,i,s),a=e+i/2,c="wall"===r.compiled.asset.placement?n:n+s/2;for(const e of o.shapes)if(!(e.outline.length<3)){t.save(),t.fillStyle=e.color,e.transparent&&(t.globalAlpha=.35),t.beginPath();for(const n of[e.outline,...e.holes])if(!(n.length<3)){t.moveTo(a+n[0][0],c+n[0][1]);for(let e=1;e<n.length;e++)t.lineTo(a+n[e][0],c+n[e][1]);t.closePath()}t.fill("evenodd"),t.restore()}}topView(t,e,n){const i=kE(t.compiled.asset,{x:e,z:n,y:this.askedDepth}),s=i.inputs,r=`${t.compiled.fingerprint}|${s?`${s.x}|${s.y}|${s.z}`:`x${i.scale}`}`;return this._top?.key!==r&&(this._top={key:r,view:QE(t,s,i.scale)}),this._top.view}get askedDepth(){const t=this.state.depth;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0}adjustResize(t,e,n){const i=vE(this.state.type);if(!i)return super.adjustResize(t,e,n);const s=i.compiled.asset,r=EE(s),o=super.adjustResize(t,e,n),a=this.bounds,c=[];Math.abs(o.width-a.width)>1e-6&&c.push("x"),Math.abs(o.height-a.height)>1e-6&&c.push("z");const{occupancy:l}=kE(s,{x:o.width,z:o.height,y:r?void 0:this.askedDepth},c);return{left:Math.abs(o.left-a.left)>1e-6?o.left+o.width-l.x:o.left,top:Math.abs(o.top-a.top)>1e-6?o.top+o.height-l.z:o.top,width:l.x,height:l.z}}added(t){super.added(t),this.fitBoxToFigure([])}onchange(t,e){super.onchange(t,e);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)}fitBoxToFigure(t){const e=vE(this.state.type);if(!e)return;const n=e.compiled.asset,i=EE(n),{width:s=0,height:r=0}=this.state,{occupancy:o}=kE(n,{x:s,z:r,y:this.askedDepth},t),a={};Math.abs(o.x-s)>1e-6&&(a.width=o.x),Math.abs(o.z-r)>1e-6&&(a.height=o.z);const c=this.askedDepth;(void 0!==c&&Math.abs(o.y-c)>1e-6||i&&void 0===c&&t.includes("y"))&&(a.depth=o.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,i,s){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,i,s),t.stroke(),t.restore()}postrender(t){Cc.prototype.postrender.call(this,t)}}uE(ok);const ak={"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"},ck=new Map([["default",ak]]);let lk="default",hk=0;function dk(){return hk}function uk(t,e){ck.set(t,e),t===lk&&hk++}function pk(t){if(!ck.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...ck.keys()].join(", ")}`);t!==lk&&(lk=t,hk++)}function fk(){return lk}function mk(){return ck.get(lk)}function gk(t){const e=mk()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${lk}'). 쓸 수 있는 것 — ${Object.keys(mk()).join(", ")}`);return e}const yk=ak["palette.neutral"];function bk(){ck.clear(),ck.set("default",ak),lk="default",hk++}const vk={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},_k=["shape","segments"],xk=["color","preset","transparent","glow"];function wk(e,n){let i;try{i=$E(e,n)}catch{return null}if(!i?.getAttribute("position"))return null;const s=i.clone();i.dispose(),s.computeBoundingBox();const r=s.boundingBox,o=r.getCenter(new t.Vector3),a=r.getSize(new t.Vector3);return s.translate(-o.x,-o.y,-o.z),s.scale(1/(a.x||1),1/(a.y||1),1/(a.z||1)),s.computeBoundingBox(),s.getAttribute("normal")||s.computeVertexNormals(),{geometry:s,extent:a,centre:o}}class Mk extends Mu{build(){super.build();const e=this.component.state,n=e.shape?wk(e.shape,e.segments):null;if(!n)return;const i=new t.Mesh(n.geometry,this.material());i.castShadow=!0,i.receiveShadow=!0,this.object3d.add(i),this.mesh=i,this.updateDimension()}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(_k)?this.update():(super.onchange(t,e),n(xk)&&this.mesh&&(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=Pd[t.preset??"default"]??Pd.default,n=t.color??"#9a9a9a",i=t.transparent??!1,s=t.glow,r=s?s.color:n,o=s?s.intensity:0;return MS.material(`figure-part|${n}|${t.preset??"default"}|${i}|${s?`${s.color}:${o}`:"-"}`,{color:r,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:i,opacity:i?e.opacity??.3:1,emissive:r,emissiveIntensity:o})}}class Sk extends(Pc(Tc)){static registerType(){Cc.register("figure-part",Sk)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return vk}buildRealObject(){return new Mk(this)}render(t){const{left:e=0,top:n=0,width:i=0,height:s=0}=this.state;t.beginPath(),t.rect(e,n,i,s),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var Ak;Sk.registerType(),function(t){t.compile=Bl,t.duplicate=Yl,t.select=ec,t.match=Ja}(Ak||(Ak={})),ji.registerResidents(()=>({componentResidentsCount:Cc.residentsCount,sceneResidentsCount:Ju.residentsCount,referenceMapResidentsCount:rS.residentsCount,sceneResidents:Cc.residents}));var Ek=Object.freeze({__proto__:null,AbsoluteLayout:Nc,Animation:Aa,AudioPlayer:ry,BULGE_EPSILON:qr,get Banner(){return yA},Banner3D:gA,BoxSelectionManager:Lf,CAPABILITY_MIXINS:ZE,COMMON_PLACEHOLDER_PROPERTIES:kg,CORE_PLACEHOLDER_TYPES:Pg,get Camera(){return wA},Camera3D:xA,CameraBookmarkManager:jf,CameraManager:xf,Capacity:mw,CapacityEventTracker:By,CardLayout:Hc,CenteringQueueStrategy:Gy,CenteringSlotStrategy:jM,Component:Cc,Connectable:lm,Container:lg,ContainerAbstract:rh,ControlsManager:Af,get Cube(){return dA},Cube3D:hA,get Cylinder(){return fA},Cylinder3D:pA,DEFAULT:Ks,DEFAULT_CEILING:_u,DEFAULT_PALETTE:ak,DEFAULT_PLACEMENT:fu,DEFAULT_SEAT_MARGIN:f_,DPPX:Ws,DataLagTracker:hh,DataSource:zy,DefaultLoadingOverlayRenderer:Vd,Donut:Sy,DonutExtrude:YS,Ellipse:Ag,EllipseExtrude:NS,EventManager3D:Ef,EventMap:fl,FIGURE_CAPABILITIES:JE,FIGURE_CAPABILITY_NOTES:tk,FPS:$p,FigureInstance:ok,FigurePart:Sk,FigurePartRealObject:Mk,FixedSlotStrategy:ib,get FloorPlate(){return DA},FlowEngine:MM,FlowNode:EM,GESTURES:qs,get GLTFObject(){return SA},GLTF_BASE_URL_ALIAS:jy,GenericObject:Og,GeometryBank:qS,GifView:iy,GizmoManager:Cf,GizmoOperationManager:Pf,GlobalRef:py,GltfComponent:Fy,GridStacking:Wy,Group:cy,HOLDER_ANCHOR:Kv,HTMLAbsoluteLayout:Fc,HTMLOverlayContainer:dy,HTMLOverlayElement:Vg,Holdable:SM,ImageView:Gg,InfoWindow:Rc,InstancedSet:tE,InteractionManager:If,ItemsDataBinding:nb,KEYEVENTS:Xs,Layer:bp,Layout:Lc,LightManager:Mf,LightObject:EA,Line:Mg,Line3D:KA,LinearHorizontalLayout:Yc,LinearVerticalLayout:Vc,LoadTracker:ph,LoadingOverlay:Ld,LocalRef:hy,MATERIAL_PRESETS:Pd,MAX_SEGMENTS:JS,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:MS,get Model(){return Ak},MoveHandle:ih,NOTHING:Fs,NavGraph:BM,Node:Ty,OrthoLine:Bg,OrthoLine3D:JA,PIXEL_RATIO:Hp,PLACEHOLDER_THEMES:Eg,Path:vy,PatternStacking:Uy,PlacementManager:Df,get PointLight(){return kA},Polygon:Rg,PolygonContainer:Lg,PolygonExtrude:BS,PolygonPathPolyline:XM,Polyline:$g,Polyline3D:QA,Popup:gy,PopupContainer:by,Pose6DOF:_l,RealObject:Mu,RealObjectCamera:sE,RealObjectDomElement:Xp,RealObjectDomTexture:vS,RealObjectDummy:nE,RealObjectExternalModel:Eu,RealObjectExtrude:FS,RealObjectGLTF:Ou,RealObjectGroup:FA,RealObjectLine:XA,RealObjectMesh:SS,RealObjectPlane:rE,RealObjectPlane2D:cE,RealObjectScene:oE,RealObjectService:Oy,RealObjectSprite:rA,RealObjectSprite2D:oA,RealObjectText:PS,Rect:um,RectExtrude:$S,RectPath:Pc,ReferenceMap:rS,RendererManager:wf,ReservationTable:$M,RootContainer:lh,Ruler:fm,SCALE_MIN:tu,SCENE_MODE:Vs,SEGMENT_DEFAULTS:KS,SEGMENT_PRESETS:XS,SHORTCUT_SECTIONS:em,Scene:Ju,SceneManager:_f,ScenePopup:yp,SceneSearchEngine:Ru,ScriptLoader:uS,SearchOverlay:Lu,ServiceComponent:Iy,Shape:Tc,get Sphere(){return sA},Sphere3D:iA,get Sprite(){return cA},Star:ky,StarExtrude:VS,TRANSFER_SLOT_KEY:tb,TableLayout:Uc,Text:oy,ThreeCapability:qf,get ThreeContainer(){return hE},ThreeDOnly:Ry,Tracker:Nu,Transfer:qu,TransitionEffect:nh,Triangle:xy,TriangleExtrude:GS,UNIT_DIMENSION:su,UNIT_ROTATE:au,UNIT_SCALE:ru,UNIT_TRANSLATE:ou,UNTOKENED_COLOR:yk,ValueHolder:Dy,VertexGizmoManager:Bf,VolumeStacking:qy,get Wall(){return OA},Wall3D:TA,Z_PRIORITY:gu,acquireFigureGeometry:FE,activePalette:mk,activePaletteName:fk,addressOfSlotId:h_,allDestinations:hM,anchorsConnect:xw,animate:Sa,applyAlpha:nu,applyMaterial3dProps:Rd,applyPolicy:pM,applySeatingRotation:Zy,applyStackLayout:Xy,applyZPriorityToMaterials:bu,arcSegmentTopology:vw,autoWireBackPressure:Yy,buildArrow3D:Wp,buildContractInspector:eS,buildCoordinateGround:of,buildFigureGeometry:$E,buildFlowGraph:Ew,buildNavGraph:VM,buildShapeFromPolygonPath:HS,buildTether:cp,bulgeFromDrag:Jr,bulgeHandlePosition:Qr,canReach:Pw,capability:qm,centerOnBBox:LS,chooseNearestPickupFrame:RM,clearTether:hp,collectAdjacentSegments:jw,compile:ka,componentForNode:lM,computeArcParams:Kr,computeFlowMap:Qw,computeStackPositions:Vy,cornerHandlePosition:to,cornerRadiusFromDrag:eo,create:tp,createCanvas:Bp,createCanvasTexture:mS,createFloor:yf,createRealObjectFor:tf,createSelectionHandle3D:zA,dataLagTracker:dh,debug:Zi,deliversInto:Sw,delta:wa,disposeCoordinateGround:hf,disposeObject3D:hu,disposeTether:dp,downstream:gM,drawTextTexture:kS,effectiveCornerRadius:Zr,ellipseOutline:jS,enumerateDataScenarios:$w,error:Qi,figureClassFor:ik,figureSectionOutline:aw,fillStyleOpacity:eu,filterByToolType:zM,filterShortcuts:nm,findNearestWithCapability:tM,flattenPolygonPath:KM,flowGraphFor:aM,flowGraphIssues:oM,flowReverseFor:Jw,fontStyle:AS,footprint2D:Ky,frameClock:Rr,ftId:Ww,ftrace:Uw,getAllCapabilityMeta:Jm,getCapabilityMeta:Qm,getFigure:vE,getPose:Al,getWorldPose:El,globalSimClock:Dr,gltfNatureProperties:Ly,graphFor:_M,gridCellOf:o_,gridPlacements:eE,gridSlotNo:r_,hasArc:Xr,hasCapability:Wm,hasCapacity:$y,hasFigure:_E,inferCapacity:Hy,inferDownstreamId:Lw,inferFlowDirections:Vw,initFontFamilyWatcher:Js,inspector:jd,installContractInspector:nS,isFlowNode:kM,isGenericPlaceholder:Ig,isGeometricHost:Zw,isParted:Su,isRoutingTarget:eM,isSegmentPreset:eA,isStateDriven:mu,isThreedEnabled:Iu,judgeItemFit:S_,layoutIssue:Xv,matchOutbounds:Aw,metrics:ji,next:mM,nextHop:Ow,nextHops:Tw,nextHopsToAny:Dw,nextHopsToAnyDetailed:zw,niceGridStep:sf,nodeIdOf:dM,opaqueColor:iu,paletteVersion:dk,partAtByIndex:Au,persistenceIssues:n_,pickWeightedDestination:wM,planPathAStar:UM,planToReservations:WM,pointInRotatedRect:ww,polygonOffsetForPriority:yu,polygonPathLength:QM,projectToScreen:sp,quatFromYaw:TM,rayAbsDistanceToRect:Mw,reachableByOutbound:kw,reachableDestinations:yM,reachableDestinationsFrom:bM,reachableDestinationsWeightedFrom:vM,reachableSinks:Iw,receiptToJSON:Uu,recommendsLogarithmicDepthForSky:vf,rectFaceAnchors:gw,rectOutline:RS,rectangularFootprintFrames:IM,registerCapabilityMeta:Km,registerDefaultRealObjectFactory:Zp,registerFigure:bE,registerFigureType:pE,registerPalette:uk,registerRealObjectFactory:Jp,registerTypeResolver:Rl,releaseFigureGeometry:NE,renderCanvasTexture:gS,renderPlaceholder:Cg,reservationTable:HM,resetFigureClasses:sk,resetFigures:wE,resetPalettes:bk,resolveAnchorWorldPosition:ap,resolveHeightSegments:tA,resolveMaterial3d:Id,resolveNextHop:fM,resolveSegments:ZS,resolveSlot:c_,resolveToken:gk,resolveUnknownTypes:Ll,resolveVariant:Qd,rotatedFootprint:g_,sceneComponent:Ny,seatInSlot:y_,seatTransform:b_,setActivePalette:pk,setPose:kl,setThreedEnabled:Du,setWorldPose:Cl,sinksForDestination:cM,slotAddresses:d_,slotCount:i_,slotFrame:p_,slotIdOf:l_,slotNumbers:s_,slotSpaceWarnings:M_,slotsFromBindings:ek,stackSeatTransforms:v_,standardYieldPolicy:NM,stopFPSMeasure:Np,straightSegmentEndpoints:bw,straightSegmentMultiInbound:_w,straightSegmentTopology:yw,textBounds:OS,textTexture:CS,toThreeSide:zd,topApproachFrame:DM,transferLog:Xu,transferTracer:Gu,uniformZ:no,unitFigurePartGeometry:wk,unknownTypesOf:jl,unregisterFigure:xE,unresolvedReasonOf:Dl,updateDefaultFontFamily:Qs,updateTether:lp,useFigureComponent:uE,validate:xM,validateFlowGraph:Rw,validateSlotLayout:e_,version:pS,warn:Ji});const kk=globalThis;"undefined"==typeof globalThis||kk.scene||(kk.scene=Ek);export{Nc as AbsoluteLayout,Aa as Animation,ry as AudioPlayer,qr as BULGE_EPSILON,yA as Banner,gA as Banner3D,Lf as BoxSelectionManager,ZE as CAPABILITY_MIXINS,kg as COMMON_PLACEHOLDER_PROPERTIES,Pg as CORE_PLACEHOLDER_TYPES,wA as Camera,xA as Camera3D,jf as CameraBookmarkManager,xf as CameraManager,mw as Capacity,By as CapacityEventTracker,Hc as CardLayout,Gy as CenteringQueueStrategy,jM as CenteringSlotStrategy,Cc as Component,lm as Connectable,lg as Container,rh as ContainerAbstract,Af as ControlsManager,dA as Cube,hA as Cube3D,fA as Cylinder,pA as Cylinder3D,Ks as DEFAULT,_u as DEFAULT_CEILING,ak as DEFAULT_PALETTE,fu as DEFAULT_PLACEMENT,f_ as DEFAULT_SEAT_MARGIN,Ws as DPPX,hh as DataLagTracker,zy as DataSource,Vd as DefaultLoadingOverlayRenderer,Sy as Donut,YS as DonutExtrude,Ag as Ellipse,NS as EllipseExtrude,Ef as EventManager3D,fl as EventMap,JE as FIGURE_CAPABILITIES,tk as FIGURE_CAPABILITY_NOTES,$p as FPS,ok as FigureInstance,Sk as FigurePart,Mk as FigurePartRealObject,ib as FixedSlotStrategy,DA as FloorPlate,MM as FlowEngine,EM as FlowNode,qs as GESTURES,SA as GLTFObject,jy as GLTF_BASE_URL_ALIAS,Og as GenericObject,qS as GeometryBank,iy as GifView,Cf as GizmoManager,Pf as GizmoOperationManager,py as GlobalRef,Fy as GltfComponent,Wy as GridStacking,cy as Group,Kv as HOLDER_ANCHOR,Fc as HTMLAbsoluteLayout,dy as HTMLOverlayContainer,Vg as HTMLOverlayElement,SM as Holdable,Gg as ImageView,Rc as InfoWindow,tE as InstancedSet,If as InteractionManager,nb as ItemsDataBinding,Xs as KEYEVENTS,bp as Layer,Lc as Layout,Mf as LightManager,EA as LightObject,Mg as Line,KA as Line3D,Yc as LinearHorizontalLayout,Vc as LinearVerticalLayout,ph as LoadTracker,Ld as LoadingOverlay,hy as LocalRef,Pd as MATERIAL_PRESETS,JS as MAX_SEGMENTS,Us as MAX_UNDO_SIZE,QS as MIN_SEGMENTS,Bs as MODE_ADD,$s as MODE_EDIT,Gs as MODE_PASTE_DATABIND,Ys as MODE_PASTE_STYLE,Hs as MODE_SHIFT,Ns as MODE_VIEW,MS as MaterialBank,Ak as Model,ih as MoveHandle,Fs as NOTHING,BM as NavGraph,Ty as Node,Bg as OrthoLine,JA as OrthoLine3D,Hp as PIXEL_RATIO,Eg as PLACEHOLDER_THEMES,vy as Path,Uy as PatternStacking,Df as PlacementManager,kA as PointLight,Rg as Polygon,Lg as PolygonContainer,BS as PolygonExtrude,XM as PolygonPathPolyline,$g as Polyline,QA as Polyline3D,gy as Popup,by as PopupContainer,_l as Pose6DOF,Mu as RealObject,sE as RealObjectCamera,Xp as RealObjectDomElement,vS as RealObjectDomTexture,nE as RealObjectDummy,Eu as RealObjectExternalModel,FS as RealObjectExtrude,Ou as RealObjectGLTF,FA as RealObjectGroup,XA as RealObjectLine,SS as RealObjectMesh,rE as RealObjectPlane,cE as RealObjectPlane2D,oE as RealObjectScene,Oy as RealObjectService,rA as RealObjectSprite,oA as RealObjectSprite2D,PS as RealObjectText,um as Rect,$S as RectExtrude,Pc as RectPath,rS as ReferenceMap,wf as RendererManager,$M as ReservationTable,lh as RootContainer,fm as Ruler,tu as SCALE_MIN,Vs as SCENE_MODE,KS as SEGMENT_DEFAULTS,XS as SEGMENT_PRESETS,em as SHORTCUT_SECTIONS,Ju as Scene,_f as SceneManager,yp as ScenePopup,Ru as SceneSearchEngine,uS as ScriptLoader,Lu as SearchOverlay,Iy as ServiceComponent,Tc as Shape,sA as Sphere,iA as Sphere3D,cA as Sprite,ky as Star,VS as StarExtrude,tb as TRANSFER_SLOT_KEY,Uc as TableLayout,oy as Text,qf as ThreeCapability,hE as ThreeContainer,Ry as ThreeDOnly,Nu as Tracker,qu as Transfer,nh as TransitionEffect,xy as Triangle,GS as TriangleExtrude,su as UNIT_DIMENSION,au as UNIT_ROTATE,ru as UNIT_SCALE,ou as UNIT_TRANSLATE,yk as UNTOKENED_COLOR,Dy as ValueHolder,Bf as VertexGizmoManager,qy as VolumeStacking,OA as Wall,TA as Wall3D,gu as Z_PRIORITY,FE as acquireFigureGeometry,mk as activePalette,fk as activePaletteName,h_ as addressOfSlotId,hM as allDestinations,xw as anchorsConnect,Sa as animate,nu as applyAlpha,Rd as applyMaterial3dProps,pM as applyPolicy,Zy as applySeatingRotation,Xy as applyStackLayout,bu as applyZPriorityToMaterials,vw as arcSegmentTopology,Yy as autoWireBackPressure,Wp as buildArrow3D,eS as buildContractInspector,of as buildCoordinateGround,$E as buildFigureGeometry,Ew as buildFlowGraph,VM as buildNavGraph,HS as buildShapeFromPolygonPath,cp as buildTether,Jr as bulgeFromDrag,Qr as bulgeHandlePosition,Pw as canReach,qm as capability,LS as centerOnBBox,RM as chooseNearestPickupFrame,hp as clearTether,jw as collectAdjacentSegments,ka as compile,lM as componentForNode,Kr as computeArcParams,Qw as computeFlowMap,Vy as computeStackPositions,to as cornerHandlePosition,eo as cornerRadiusFromDrag,tp as create,Bp as createCanvas,mS as createCanvasTexture,yf as createFloor,tf as createRealObjectFor,zA as createSelectionHandle3D,dh as dataLagTracker,Zi as debug,Sw as deliversInto,wa as delta,hf as disposeCoordinateGround,hu as disposeObject3D,dp as disposeTether,gM as downstream,kS as drawTextTexture,Zr as effectiveCornerRadius,jS as ellipseOutline,$w as enumerateDataScenarios,Qi as error,ik as figureClassFor,aw as figureSectionOutline,eu as fillStyleOpacity,zM as filterByToolType,nm as filterShortcuts,tM as findNearestWithCapability,KM as flattenPolygonPath,aM as flowGraphFor,oM as flowGraphIssues,Jw as flowReverseFor,AS as fontStyle,Ky as footprint2D,Rr as frameClock,Ww as ftId,Uw as ftrace,Jm as getAllCapabilityMeta,Qm as getCapabilityMeta,vE as getFigure,Al as getPose,El as getWorldPose,Dr as globalSimClock,Ly as gltfNatureProperties,_M as graphFor,o_ as gridCellOf,eE as gridPlacements,r_ as gridSlotNo,Xr as hasArc,Wm as hasCapability,$y as hasCapacity,_E as hasFigure,Hy as inferCapacity,Lw as inferDownstreamId,Vw as inferFlowDirections,Js as initFontFamilyWatcher,jd as inspector,nS as installContractInspector,kM as isFlowNode,Ig as isGenericPlaceholder,Zw as isGeometricHost,Su as isParted,eM as isRoutingTarget,eA as isSegmentPreset,mu as isStateDriven,Iu as isThreedEnabled,S_ as judgeItemFit,Xv as layoutIssue,Aw as matchOutbounds,ji as metrics,mM as next,Ow as nextHop,Tw as nextHops,Dw as nextHopsToAny,zw as nextHopsToAnyDetailed,sf as niceGridStep,dM as nodeIdOf,iu as opaqueColor,dk as paletteVersion,Au as partAtByIndex,n_ as persistenceIssues,wM as pickWeightedDestination,UM as planPathAStar,WM as planToReservations,ww as pointInRotatedRect,yu as polygonOffsetForPriority,QM as polygonPathLength,sp as projectToScreen,TM as quatFromYaw,Mw as rayAbsDistanceToRect,kw as reachableByOutbound,yM as reachableDestinations,bM as reachableDestinationsFrom,vM as reachableDestinationsWeightedFrom,Iw as reachableSinks,Uu as receiptToJSON,vf as recommendsLogarithmicDepthForSky,gw as rectFaceAnchors,RS as rectOutline,IM as rectangularFootprintFrames,Km as registerCapabilityMeta,Zp as registerDefaultRealObjectFactory,bE as registerFigure,pE as registerFigureType,uk as registerPalette,Jp as registerRealObjectFactory,Rl as registerTypeResolver,NE as releaseFigureGeometry,gS as renderCanvasTexture,Cg as renderPlaceholder,HM as reservationTable,sk as resetFigureClasses,wE as resetFigures,bk as resetPalettes,ap as resolveAnchorWorldPosition,tA as resolveHeightSegments,Id as resolveMaterial3d,fM as resolveNextHop,ZS as resolveSegments,c_ as resolveSlot,gk as resolveToken,Ll as resolveUnknownTypes,Qd as resolveVariant,g_ as rotatedFootprint,Ny as sceneComponent,y_ as seatInSlot,b_ as seatTransform,pk as setActivePalette,kl as setPose,Du as setThreedEnabled,Cl as setWorldPose,cM as sinksForDestination,d_ as slotAddresses,i_ as slotCount,p_ as slotFrame,l_ as slotIdOf,s_ as slotNumbers,M_ as slotSpaceWarnings,ek as slotsFromBindings,v_ as stackSeatTransforms,NM as standardYieldPolicy,Np as stopFPSMeasure,bw as straightSegmentEndpoints,_w as straightSegmentMultiInbound,yw as straightSegmentTopology,OS as textBounds,CS as textTexture,zd as toThreeSide,DM as topApproachFrame,Xu as transferLog,Gu as transferTracer,no as uniformZ,wk as unitFigurePartGeometry,jl as unknownTypesOf,xE as unregisterFigure,Dl as unresolvedReasonOf,Qs as updateDefaultFontFamily,lp as updateTether,uE as useFigureComponent,xM as validate,Rw as validateFlowGraph,e_ as validateSlotLayout,pS as version,Ji as warn};
50
+ `,this.element)}catch(t){}}onchangeMinimized(){const{minimized:t}=this.state;t?this.setState("height",24):this.setState("height",this.get("height"))}}rg=new WeakMap,Cc.memoize(lg.prototype,"bounds",!0),Cc.register("container",lg);const hg=Math.sqrt(3),dg=2;function ug(t,e,n,i,s){const r=5+s,o=n.x,a=n.y,c=i.x,l=i.y;if(Math.abs(o-c)>r&&Math.abs(a-l)>r){const n=(l-a)/(c-o),i=a-n*o;if(Math.abs(e-(n*t+i))>r)return!1}let h,d,u,p;return o>c?(d=o,h=c):(d=c,h=o),a>l?(p=a,u=l):(p=l,u=a),!(d+5<t)&&(!(h-5>t)&&(!(p+5<e)&&!(u-5>e)))}function pg(t,e,n,i=2){for(let s=0;s<n.length-1;s++)if(ug(t,e,n[s],n[s+1],i))return!0;return!1}function fg(t,e,n,i){if("arrow"!=t.slice(-5))return n;const s=Math.atan2(i.y-n.y,i.x-n.x),r=1.5*e;return{x:n.x+Math.cos(s)*r,y:n.y+Math.sin(s)*r}}function mg(t,e,n){let{lineWidth:i=dg,strokeStyle:s="#000000",lineCap:r=!1,alpha:o=1,begin:a="none",end:c="none",beginSize:l="size5",endSize:h="size5"}=n;if(("none"!=a||"none"!=c)&&(i=Number(i)||dg,t.lineCap=r,t.lineWidth=i,t.strokeStyle=s,t.fillStyle=s,t.globalAlpha*=o,"none"!=a&&gg(t,e[0],e[1],i,a,yg(l,i)),"none"!=c)){const n=e.length;gg(t,e[n-1],e[n-2],i,c,yg(h,i))}}function gg(t,e,n,i,s,r){const{x:o,y:a}=e,c=Math.atan2(n.y-a,n.x-o);switch(t.beginPath(),t.translate(o,a),t.rotate(c),s){case"oval":t.ellipse(0,0,r.X,r.Y,0,0,2*Math.PI),t.fill();break;case"diamond":t.moveTo(-r.X,0),t.lineTo(0,-r.Y),t.lineTo(r.X,0),t.lineTo(0,r.Y),t.fill();break;case"arrow":t.moveTo(0,0),t.lineTo(hg*r.X,-r.Y),t.lineTo(hg*r.X,r.Y),t.fill();break;case"sharp-arrow":t.moveTo(0,0),t.lineTo(hg*r.X,-r.Y),t.lineTo(-r.X/1.5+hg*r.X,0),t.lineTo(hg*r.X,r.Y),t.fill();break;case"open-arrow":t.moveTo(hg*r.X+i,-r.Y),t.lineTo(i,0),t.lineTo(hg*r.X+i,r.Y),t.stroke();break;case"cross":t.moveTo(-r.X,-r.Y),t.lineTo(r.X,r.Y),t.moveTo(r.X,-r.Y),t.lineTo(-r.X,r.Y),t.stroke()}t.rotate(-c),t.translate(-o,-a),t.closePath()}function yg(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 bg="N",vg="S",_g="E",xg="W";class wg{constructor({component:t,anchor:e,position:n,self:i}){this.component=t,this._anchorName=e,this._position=n,this.self=i}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 _g;const n=e.position;return n.y<=t.top?bg:n.y>=t.top+t.height?vg:n.x<=t.left?xg:_g}get boundaryPosition(){const t=this.anchor;if(t){let{position:e}=t,n=0,i=0;switch(this.direction){case vg:i=20;break;case bg:i=-20;break;case xg:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+i};const s=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(s.x,s.y)}}}class Mg extends Cc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const i=t.get(n.component)||n.component;this.set(e,{...n,component:i})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const i=this.root?.findByRefid?.(t);if(!i)return;this._fromEnd=new wg({component:i,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 i=this.root?.findByRefid?.(t);if(!i)return;this._toEnd=new wg({component:i,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:i,round:s=0}=this.state;let r=this.drawPath;mg(t,r,this.state),t.beginPath();const o=fg(e,i,r[0],r[1]),a=fg(n,i,r[r.length-1],r[r.length-2]),c=r[0];r=[o,...r.slice(1,-1),a];let l={x:o.x,y:o.y};if(t.moveTo(o.x,o.y),r.length>=2&&Xr(c)){const e=r[1],n=Zr(e,s),i=Math.sqrt((o.x-e.x)**2+(o.y-e.y)**2),a=0!==i?Math.atan2(o.x-e.x,o.y-e.y):0,l=Math.sin(a)*Math.min(n,i/2)+e.x,h=Math.cos(a)*Math.min(n,i/2)+e.y,d=Kr({x:o.x,y:o.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<r.length;e++){const n=l;l=r[e];const i=r[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!i){t.lineTo(l.x,l.y);break}const o=Zr(l,s);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(o,a/2)+l.x,d=Math.cos(c)*Math.min(o,a/2)+l.y;const u=o>0||0!==a?{x:h,y:d}:l;a=Math.sqrt((i.x-l.x)*(i.x-l.x)+(i.y-l.y)*(i.y-l.y)),c=0!==a?Math.atan2(i.x-l.x,i.y-l.y):0,h=Math.sin(c)*Math.min(o,a/2)+l.x,d=Math.cos(c)*Math.min(o,a/2)+l.y;const p=o>0||0!==a?{x:h,y:d}:l;if(t.lineTo(u.x,u.y),o>0&&t.quadraticCurveTo(l.x,l.y,p.x,p.y),Xr(l)){const e=Zr(i,s),n=Math.sqrt((l.x-i.x)**2+(l.y-i.y)**2),r=0!==n?Math.atan2(l.x-i.x,l.y-i.y):0,o=Math.sin(r)*Math.min(e,n/2)+i.x,a=Math.cos(r)*Math.min(e,n/2)+i.y,c=Kr({x:p.x,y:p.y},{x:o,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 pg(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:i,x2:s,y2:r}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:i},this.toEnd?.position||e?.position||{x:s,y:r}]}set path(t){const[e,n]=t,{from:i,to:s}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...i,position:e},to:{...s,position:n}})}get textBounds(){const t=this.drawPath;let e,n,i=0;for(let s=1;s<t.length;s++){const r=t[s-1],o=t[s],a=(r.x-o.x)*(r.x-o.x)+(r.y-o.y)*(r.y-o.y);a>i&&(i=Math.ceil(a),e=r,n=o)}let{paddingTop:s,paddingLeft:r,paddingRight:o,paddingBottom:a}=this.state;return a||=0,s||=0,r||=0,o||=0,{left:Math.min(e.x,n.x)+r,top:Math.min(e.y,n.y)+s,width:Math.max(Math.abs(e.x-n.x)-r-o,0),height:Math.max(Math.abs(e.y-n.y)-s-a,0)}}get decorators(){return this.app.isEditMode?["decotag"]:[]}}Mg.getTipNeckPos=fg,Mg.containedInPath=pg,Mg.drawEndTips=mg,Cc.register("line",Mg);const Sg={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 Ag extends(lm(Tc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:i,ry:s,startAngle:r,endAngle:o,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(i),Math.abs(s),0,r||0,o||2*Math.PI,a),void 0!==r&&void 0!==o&&(t.lineTo(e,n),t.closePath())}get path(){const{cx:t,cy:e,rx:n,ry:i}=this.state;return[{x:t-n,y:e-i},{x:t+n,y:e-i},{x:t+n,y:e+i},{x:t-n,y:e+i}]}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:i,rx:s,ry:r}=this.state,o=(t-n)/(2*s-.5),a=(e-i)/(2*r-.5);return o*o+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:i,rx:s,ry:r}=t.model,o=2*Math.PI*e,a=n+s*Math.cos(o),c=i+r*Math.sin(o);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:i,height:s}=t.bounds,r=e+i/2,o=n+s/2;return[{name:"TOP",position:{x:r,y:n}},{name:"RIGHT",position:{x:e+i,y:o}},{name:"BOTTOM",position:{x:r,y:n+s}},{name:"LEFT",position:{x:e,y:o}}]}(this)}get nature(){return Sg}}Cc.memoize(Ag.prototype,"path",!1),Cc.register("ellipse",Ag);const Eg={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"}},kg=[{type:"string",label:"placeholder-label",name:"placeholderLabel",description:'사용자에게 표시할 추가 라벨 (예: "Stocker A1")'},{type:"string",label:"hint",name:"placeholderHint",description:"구체화 시 참고 — 도면의 원본 식별자 / VLM 라벨 등"}];function Cg(t,e,n,i,s){const{left:r,top:o,width:a,height:c}=e,l=Math.max(a,1),h=Math.max(c,1);t.save(),t.fillStyle=n.fill,t.fillRect(r,o,l,h),t.strokeStyle=n.stroke,t.lineWidth=1.5,t.setLineDash([4,3]),t.strokeRect(r,o,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,r+l/2,o+h/2),t.restore());const d=i?`${n.label}: ${i}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,r+l/2,o+h-4),t.restore()),s&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${s}`,r+l-4,o+4),t.restore())}const Tg={mutable:!1,resizable:!0,rotatable:!0,properties:[...kg,{type:"placeholder-convert",label:"",name:"_convert"}],help:"scene/component/placeholder"};class Og extends(Pc(Tc)){get nature(){return Tg}render(t){const{placeholderLabel:e,placeholderHint:n}=this.state;Cg(t,this.bounds,Eg.object,e,n)}}Cc.register("placeholder",Og);const Pg=["placeholder"];function Ig(t,e=[]){return!!t&&(!!Pg.includes(t)||e.includes(t))}const Dg={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 i=n[e+1];n[e+1]={...i||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},zg={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 Rg extends Tc{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 i=!1;return n.forEach((s,r)=>{const o=(r+n.length+1)%n.length,a=s.x,c=s.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(i=!i)}),i}get controls(){const t=this.path;return t.map((e,n)=>{const i=t[n+1>=t.length?0:n+1];return{x:(e.x+i.x)/2,y:(e.y+i.y)/2,handler:Dg}})}get nature(){return zg}}Cc.memoize(Rg.prototype,"controls",!1),Cc.register("polygon",Rg);const jg=[];class Lg extends(ih(Rg)){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 Lc.get(this.get("layout"))||Nc}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:i=!1}="boolean"==typeof e?{ghost:e}:e,s=t.parent;if(s){if(this===s)return;s.removeComponent(t,n||i)}const r=this._components.push(t)-1;i&&(t._silentAdd=!0),t.parent=this,t.added(this),n||i||this.trigger("add",this,t,r),t.delegate_on(this),i?(s&&this.root?._removeTraverse?.(t),this.trigger("add",this,t,r),t.trigger("added",this,t,r),delete t._silentAdd):n||t.trigger("added",this,t,r),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 i=t.parent;i&&i.removeComponent(t,n);const s=this._components.splice(0,e);this._components=s.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||jg).indexOf(t)}size(){return(this._components||jg).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let i=this._components.splice(0,n);const s=this._components.splice(1);this._components=i.concat(s),t=Math.max(0,t),t=Math.min(t,this._components.length),i=this._components.splice(0,t),this._components=i.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),i=this._components.splice(1);this._components=n.concat(i,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),i=this._components.splice(1);this._components=this._components.concat(n,i)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return ec(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let i=this.components.length-1;i>=0;i--){const s=this.components[i].findAll(t,...e);s&&(n=n.concat(s))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return ec(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const i=this.components[n].findFirst(t,...e);if(null!=i)return i}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 i=this.fromParent(t,e);if(!this.contains(i.x,i.y))return!1;const s=this.bounds;i.x-=s.left,i.y-=s.top;const r=this.layout.capturables(this);for(let s=r.length-1;s>=0;s--){const o=r[s];let a;if(a="static"==o.position?o.capture(i.x,i.y,n):o.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:i,top:s,width:r,height:o}=this.bounds;for(let e=0;e<t.length;e++){const a=this.fromParent(t[e].x,t[e].y);if(a.x<i||a.x>i+r||a.y<s||a.y>s+o)return!1;a.x-=i,a.y-=s,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const i=a[t];if(!i.isContainer())continue;const s=i.capturePath(n,e);if(s)return s}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:i=0,width:s,height:r}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,i,s,r),t.clip(),t.closePath()),t.translate(n,i),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,-i),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>Cc.memoize(Lg.prototype,t,!1));const Fg={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 i=n[e];n[e]={...i||{},x:t.x,y:t.y}})},ondragend:function(t,e,n){}},Ng={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 $g extends Mg{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 i=t[n],s=t[n+1];0==n&&e.push({x:i.x,y:i.y,handler:Fg}),e.push({x:(i.x+s.x)/2,y:(i.y+s.y)/2,handler:Fg}),n==t.length-2&&e.push({x:s.x,y:s.y,handler:Fg})}return e}get nature(){return Ng}}Cc.register("polyline",$g);const Hg={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 Bg extends Mg{get pathExtendable(){return!1}get drawPath(){const t=this.path[0],e=this.path[1],{component:n,direction:i,boundaryPosition:s=t}=this.fromEnd||{},{component:r,direction:o,boundaryPosition:a=e}=this.toEnd||{},c=[s,a],l=[];s&&l.push(s);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:s.x,top:s.y,width:0,height:0};d=d||u;let p=r?.bounds;p&&(h=r.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,E,k,C,T=0,O=0;d.left+d.width<p.left?(w=0,M=1,k=i,C=o,v=(d.left+d.width+p.left)/2,T=p.left-v):p.left+p.width<d.left&&(w=1,M=0,k=o,C=i,v=(d.left+p.width+p.left)/2,T=d.left-v),d.top+d.height<p.top?(x=0,S=1,A=i,E=o,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,A=o,E=i,_=(d.top+p.height+p.top)/2,O=d.top-_);const P=[];if(v&&T>O){let t,e,n;switch(C){case xg:switch(k){case _g:P.push({x:v,y:c[w].y}),P.push({x:v,y:c[M].y});break;case xg: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 bg:case vg:e=k===vg?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 _g:switch(k){case _g: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 xg:e=void 0!==_?_:c[w].y<c[M].y?b.top-.5*T:b.top+b.height+.5*T,n=e;break;case vg:e=void 0!==_?Math.max(_,c[w].y):b.top+b.height,n=e;break;case bg: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 vg:switch(k){case _g:e=c[w].y,n=c[w].y>c[M].y?c[w].y:m[M].top+m[M].height;break;case xg:e=_?Math.max(_,m[M].top+m[M].height):b.top+b.height,n=e;break;case vg:e=b.top+b.height,n=e;break;case bg: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 bg:switch(k){case _g:e=c[w].y,n=c[w].y<c[M].y?c[w].y:m[M].top;break;case xg:e=_?Math.min(_,m[M].top):b.top,n=e;break;case vg:e=void 0!==_?Math.max(_,c[w].y):c[w].y,n=void 0!==_?Math.min(_,c[M].y):c[M].y;break;case bg: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(E){case bg:switch(A){case vg:P.push({x:c[x].x,y:_}),P.push({x:c[S].x,y:_});break;case bg: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 xg: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 _g: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 vg:switch(A){case xg:e=b.left,n=e;break;case _g:e=void 0!==v?Math.max(v,c[x].x):b.left+b.width,n=e;break;case bg: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 vg: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 _g:switch(A){case xg: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 _g:e=b.left+b.width,n=e;break;case bg:e=void 0!==v?Math.max(v,c[S].x):b.left+b.width,n=e;break;case vg: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 xg:switch(A){case xg:e=b.left,n=e;break;case _g: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 bg:e=b.left,n=e;break;case vg: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(i){case bg:switch(o){case bg:e=b.top,l.push({x:c[0].x,y:e}),l.push({x:c[1].x,y:e});break;case vg: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 _g: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 xg: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 vg:switch(o){case bg: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 vg:case _g:case xg: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 xg:switch(o){case bg: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 vg: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 _g: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 xg: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 _g:switch(o){case bg: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 vg: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 _g:case xg: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 i=n[e-1];return t.x!==i.x||t.y!==i.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const i=n[e-1],s=n[e+1];return!(t.x===i.x&&t.x===s.x||t.y===i.y&&t.y===s.y)})}get nature(){return Hg}}Cc.register("ortholine",Bg);const Yg={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 Gg extends(Pc(Tc)){static get noimage(){return Gg.NOIMAGE||(Gg.NOIMAGE=new Image,Gg.NOIMAGE.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABIBAMAAAD7Se1QAAAAIVBMVEUAAABHcEwBAQEREREBAQEEBAQGBgYLCwsDAwMDAwMICAi6HF9tAAAAC3RSTlNNAEAERiMYCS41Eac10lYAAAEgSURBVHhe7dY9asQwEAXgh7DNertNiJy48pIitY3SB7bYdk0ukL1BDDmA9gZecoH4pmFQ3MQayUMguPBrNPD4wD9TCMvJmt3M/AtYwXOlXiWgqADVCUBD46MAnGhMBaCiUQmAm8VA/Eh/eWl9Fn5WcxD+OLuRrUYJDKLluwH2InACUgkoACSdADxQc50Bytadb9RkM0CT13TcvlCT1HFg8UTHvasuUVACCa3El6u2UdD8LFTlKhUFFgA+d3dj10aABkUN72N3jAADCrJq7PIIsPidcxBoTHIIAjMFmyCwmGYIAA1P9gFgfCANAOsDSccCDW+uLDB+kLGg94OkZoAGkwsDDAe2DOg5oPxAg03rBR88OHpBz4N8UVeHFSwma74BTW6Ge4rIRa4AAAAASUVORK5CYII="),Gg.NOIMAGE}dispose(){super.dispose(),this._offcanvas=null,this._image=null}render(t){const{left:e,top:n,width:i,height:s,isGray:r=!1,alpha:o=1,src:a}=this.state;if(this.prepareIf(!this._image&&a),t.beginPath(),t.globalAlpha*=o,this._image&&this._image.complete)if(r&&this._offcanvas)t.drawImage(this._offcanvas,e,n,i,s);else try{t.drawImage(this._image,e,n,i,s)}catch(r){t.drawImage(Gg.noimage,e,n,i,s)}else!this.app.isViewMode&&t.drawImage(Gg.noimage,e,n,i,s)}get nature(){return Yg}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:i}=this.state;if(n){this._image=new Image;try{i&&(this._image.crossOrigin=i),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=Cc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const i=function(t,e,n){let i;try{i=t.getImageData(0,0,e,n)}catch(t){return Qi("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const s=i.data;for(let t=0;t<e*n*4;t+=4){const e=s[t],n=s[t+1],r=s[t+2],o=Math.floor((e+n+r)/3);i.data[t]=o,i.data[t+1]=o,i.data[t+2]=o}return i}(n,t,e);n.putImageData(i,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])}}Cc.register("image-view",Gg);class Vg extends(sg(Pc(Cc))){is3dish(){return!0}prerender(){}}var Ug,Wg,qg={},Xg={},Kg={};function Qg(){if(Wg)return Xg;Wg=1,Object.defineProperty(Xg,"__esModule",{value:!0});var t=function(){if(Ug)return Kg;Ug=1,Object.defineProperty(Kg,"__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,i,s=0,r=function(t){for(var n=0,i=0;i<t;i++)e.charCodeAt(s>>3)&1<<(7&s)&&(n|=1<<i),s++;return n},o=[],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(i=n,(n=r(l))!==a){if(n===c)break;if(n<h.length)i!==a&&h.push(h[i].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[i].concat(h[i][0]))}o.push.apply(o,h[n]),h.length===1<<l&&l<12&&l++}else d();return o},t}();return Kg.SuperGifUtils=t,Kg}(),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 i=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=i.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(i.splice(0,3)),e.userInput=i.shift(),e.transparencyGiven=i.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 i=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,i),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),i=t.length/e,s=function(i,s){var r=t.slice(s*e,(s+1)*e);n.splice.apply(n,[i*e,e].concat(r))},r=[0,4,2,1],o=[8,8,4,2],a=0,c=0;c<4;c++)for(var l=r[c];l<i;l+=o[c])s(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 Xg.SuperGifParser=e,Xg}var Jg,Zg,ty={};var ey=function(){if(Zg)return qg;Zg=1,Object.defineProperty(qg,"__esModule",{value:!0});var t=Qg(),e=function(){if(Jg)return ty;Jg=1,Object.defineProperty(ty,"__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 ty.SuperGifStream=t,ty}(),n=function(){function n(t,e){var n=this;for(var i 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[i]=e[i];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,i=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 s=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(s.data[4*n+0]=i[t][0],s.data[4*n+1]=i[t][1],s.data[4*n+2]=i[t][2],s.data[4*n+3]=255)}),this.frame.putImageData(s,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 i=this;if(this.loadSetup(n)){var s=new XMLHttpRequest;s.open("GET",t,!0),"overrideMimeType"in s?s.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in s?s.responseType="arraybuffer":s.setRequestHeader("Accept-Charset","x-user-defined"),s.onloadstart=function(){i.initialized||i.init()},s.onload=function(){if(200===s.status){var t=s.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){i.parseStream(n)},0)}else i.handleError("xhr - response")},s.onerror=function(){i.handleError("xhr")},s.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return qg.SuperGif=n,qg}();const ny={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 iy extends Vg{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 ey.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 ny}get tagName(){return"div"}}Cc.register("gif-view",iy);const sy={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 ry extends(Pc(Tc)){static get image(){return ry.IMAGE||(ry.IMAGE=new Image,ry.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="),ry.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:i,height:s}=this.state;t.beginPath(),this.drawImage(t,ry.image,e,n,i,s)}get nature(){return sy}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 Qi(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])}}Cc.register("audio",ry);class oy extends(Pc(Cc)){is3dish(){return!0}}Cc.register("text",oy);const ay=["refid","left","top","width","height","rotation","animation","zPos"];class cy extends lg{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=ay.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{});return super.set(n,void 0)}capture(t,e,n){const i=super.capture(t,e,n);if(i!==this)return i}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,i=t.height/e.height;this.path=this.path.map(s=>({x:t.left+(s.x-e.left)*n,y:t.top+(s.y-e.top)*i})),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*i}})});else{const e=t.bounds,s=t.center,r={x:s.x*(1-n),y:s.y*(1-i)},o=e.width*(1-n),a=e.height*(1-i),c=-(r.x-o/2),l=-(r.y-a/2);t.bounds={left:e.left+c,top:e.top+l,width:e.width*n,height:e.height*i}}})}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=Cc.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)}}Cc.memoize(cy.prototype,"bounds",!0),Cc.register("group",cy);const ly={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 hy extends(Pc(Tc)){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,i=n.width/e.width,s=n.height/e.height;return"both"===this.model.fit?{x:i,y:s}:{x:Math.min(i,s),y:Math.min(i,s)}}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,i=this.refScale;t.translate(n.x,n.y),t.scale(i.x,i.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:i,height:s}=this.bounds;t.beginPath(),t.rect(e,n,i,s)}get nature(){return ly}get hasTextProperty(){return!1}}Cc.memoize(hy.prototype,"ref",!1),Cc.memoize(hy.prototype,"refScale",!1),Cc.register("local-ref",hy);class dy extends(sg(rh)){render(t){}is3dish(){return!0}get layout(){return Lc.get(this.get("layout"))||Fc}}const uy={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 py extends dy{dispose(){this._releaseRef(),super.dispose()}get nature(){return uy}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 i=(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,i);try{await i}catch(t){Qi(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})}}Cc.register("global-ref",py);const fy="center-middle",my={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",fy,"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 gy extends(Pc(Tc)){static get image(){return gy._image||(gy._image=new Image,gy._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"),gy._image}async ready(){await super.ready(),this.show&&this.onchangeShow(!0)}render(t){const{left:e,top:n,width:i,height:s}=this.bounds;t.beginPath(),this.drawImage(t,gy.image,e,n,i,s)}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"),i=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;yp.show(this,this.getState("board"),{origin:this.getState("origin")||fy,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:i,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(){yp.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 my}}Cc.register("popup",gy);const yy={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 by extends lg{get nature(){return yy}isPopupContainer(){return!0}}Cc.register("popup-container",by);class vy extends Cc{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 i=!1;return n.forEach((s,r)=>{const o=(r+n.length+1)%n.length,a=s.x,c=s.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(i=!i)}),i}}Cc.register("path",vy);const _y={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 xy extends Tc{is3dish(){return!0}contains(t,e){const{x1:n,y1:i,x2:s,y2:r,x3:o,y3:a}=this.state,c=[n,i,s,r,o,a];let l=!1;for(let n=0;n<c.length;n+=2){const i=(n+2)%c.length,s=c[n],r=c[n+1],o=c[i+1];r>e!=o>e&&t<(c[i]-s)*(e-r)/(o-r)+s&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:i,x3:s,y3:r}=this.state;return[{x:t,y:e},{x:n,y:i},{x:s,y:r}]}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 _y}}Cc.memoize(xy.prototype,"path",!1),Cc.register("triangle",xy);const wy={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"ratio",name:"ratio",property:"ratio"}],help:"scene/component/donut"},My={ondragmove:function(t,e,n){let{cx:i,rx:s}=n.model;s=Math.abs(s);let r=(n.fromParent(t.x,t.y).x-i)/s*100;r=r>=100||r<=-100?100:Math.abs(r),n.set({ratio:r})}};class Sy extends Ag{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:i,rx:s,ry:r,startAngle:o,endAngle:a,anticlockwise:c}=this.state;s=Math.abs(s),r=Math.abs(r),t.beginPath(),t.ellipse(n,i,s,r,0,o||0,a||2*Math.PI,c),t.moveTo(n+s/100*e,i),t.ellipse(n,i,s/100*e,r/100*e,0,o||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:i,rx:s,ry:r,ratio:o}=this.state;s=Math.abs(s),r=Math.abs(r);const a=(t-n)/(2*s-.5),c=(e-i)/(2*r-.5),l=(t-n)/(s/100*o*2-.5),h=(e-i)/(r/100*o*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:i}=this.state;return n=Math.abs(n),[{x:t+n/100*i,y:e,handler:My}]}get nature(){return wy}}Cc.memoize(Sy.prototype,"controls",!1),Cc.register("donut",Sy);const Ay={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"},Ey={ondragmove:function(t,e,n){const{cy:i,ry:s}=n.model;let r=(n.fromParent(t.x,t.y).y-i)/s*100+100;r>=100?r=100:r<=0&&(r=0),n.set({ratio:r})}};class ky extends Ag{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:i,cy:s,rx:r,ry:o}=this.state;if(n<3)return;const a=1.5707963267948966,c=2*Math.PI/n,l=r-e/100*r,h=o-e/100*o;t.save(),t.beginPath(),t.translate(i,s),t.moveTo(r*Math.cos(-a),o*Math.sin(-a)),t.lineTo((r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let e=1;e<n;e++)t.lineTo(r*Math.cos(c*e-a),o*Math.sin(c*e-a)),t.lineTo((r-l)*(Math.cos(c*(e+1)-a)+Math.cos(c*e-a))/2,(o-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:i}=this.state;return[{x:t,y:e-n+n*(i/100),handler:Ey}]}get nature(){return Ay}}Cc.memoize(ky.prototype,"controls",!1),Cc.register("star",ky);const Cy={mutable:!1,resizable:!1,rotatable:!1,properties:[]};class Ty extends(lm(Tc)){is3dish(){return!1}isDescendible(){return!1}render(t){const{cx:e,cy:n,anticlockwise:i}=this.state,s=this.app?.scale||1;t.beginPath(),t.scale(1/s,1/s),t.ellipse(e,n,Math.abs(Ty.RADIUS),Math.abs(Ty.RADIUS),0,0,2*Math.PI,i),t.scale(s,s),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-Ty.RADIUS,y:e-Ty.RADIUS},{x:t+Ty.RADIUS,y:e-Ty.RADIUS},{x:t+Ty.RADIUS,y:e+Ty.RADIUS},{x:t-Ty.RADIUS,y:e+Ty.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:i}=this.state,s=(t-n)/(2*Ty.RADIUS-.5),r=(e-i)/(2*Ty.RADIUS-.5);return s*s+r*r<.25}outline(t){const{cx:e,cy:n}=this.state;return this.toScene(e,n)}get nature(){return Cy}}Ty.RADIUS=5,Cc.memoize(Ty.prototype,"path",!1),Cc.register("node",Ty);class Oy extends Mu{getObject3dInstance(){return new t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds,i=this.component.state.depth||.5*Math.min(e,n),s=.15*Math.min(e,n,i),r=new R(1,1,1,4,s/Math.min(e,n,i));r.scale(e,i,n),this.object3d.geometry=r,this.object3d.material=new t.MeshStandardMaterial({color:"#5090d0",transparent:!0,opacity:.35,roughness:.6,metalness:.1,side:t.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 i=this.object3d.geometry.boundingBox;if(i){const s=i.max.x-i.min.x,r=i.max.y-i.min.y,o=i.max.z-i.min.z;this.setDimensionScale(t/s,n/r,e/o)}}updateFillStyle(){}updateStrokeStyle(){}updateText(){}clear(){return hu(this.object3d),super.clear()}}const Py="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 Iy extends(Pc(Cc)){static get icon(){return Iy._defaultIcon||(Iy._defaultIcon=new Image,Iy._defaultIcon.src=Py),Iy._defaultIcon}get serviceName(){}get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Oy(this)}render(t){if(this.app?.isViewMode)return;const{left:e,top:n,width:i,height:s}=this.bounds,r=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,r,e,n,i,s),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 Dy(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 i;i=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-i,this.animate({step:t=>{this._anim_alpha=i*(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=Vr(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(xi(t)))}}}function zy(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 Ry(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 jy="$base_url",Ly=[{type:"gltf-preset",label:"preset",name:"preset"},{type:"gltf-selector",label:"url",name:"src",property:{displayField:"id",displayFullUrl:!0,baseUrlAlias:jy,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 i=this.parentNode?.querySelector("[name=playTargets]");i&&(i.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 Fy(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:i,height:s}=this.bounds;t.beginPath();const r=this._topViewSnapshot;if(r)return void t.drawImage(r,e,n,i,s);this._ensureTopViewSnapshot(),t.rect(e,n,i,s),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const o=this.getState("src"),a=o&&o.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(i,s));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+i/2,n+s/2,.9*i)}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=Ou.getTopViewCache(t);if(e)return this._topViewSnapshot=e,void this.invalidate();this._snapshotLoading=!0;const n=this.app.url(t);Ou.loadGLTF(n).then(e=>{if(this._snapshotLoading=!1,this.getState("src")!==t)return;const n=Ou.getTopViewCache(t);if(n)return this._topViewSnapshot=n,void this.invalidate();const i=Ou.renderTopView(e.scene);Ou.setTopViewCache(t,i),this._topViewSnapshot=i,this.invalidate()}).catch(()=>{this._snapshotLoading=!1})}buildRealObject(){return new Ou(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:i=1}=t;this.setState({width:e,height:n,depth:i}),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,i=this.state.depth||1,s=Of([(t.width??e)/e,(t.height??n)/n,(t.depth??i)/i]);return s?{...t,width:Math.round(e*s),height:Math.round(n*s),depth:Math.round(i*s)}: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 Ny(t){return function(e){return Array.isArray(t)?t.forEach(t=>{Cc.register(t,e)}):Cc.register(t,e),e}}function $y(t){return!!t&&"function"==typeof t.capacity&&"function"==typeof t.available}function Hy(t){if($y(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 By{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 Yy(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()),i=e.onAvailable(()=>t.resumeEmit());return Hy(e).isFull&&t.pauseEmit(),()=>{n?.(),i?.()}}class Gy{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,i){const s=e.maxCount??1/0;if(t<0||t>=s)return null;const r=this.owner?.state?.width??0,o=this.owner?.state?.height??0,a=i?.state?.width??0,c=i?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(o-c)/2),z:0}:{x:Math.max(0,(r-a)/2),y:t*this.itemSpacing,z:0}}capacity(t){return t.maxCount??1/0}}function Vy(t,e,n,i,s,r,o){const a=n.w,c=n.h,l=i.w,h=i.h,d=i.d,u=[],p=l+s,f=h+s,m=Math.max(1,Math.floor((a+s)/p)),g=Math.max(1,Math.floor((c+s)/f)),y=m*g,b=r&&r>0?Math.floor(r):4;if("row"===t||"column"===t){const n=o?.advanceAlongX??!1,i=o?.reverse??!1,s=n?m:g,r=n?g:m,l=(t,e,i)=>((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,i);let h=0;for(let n=0;n<s&&h<e;n++){const o=i?s-1-n:n;if("column"===t)for(let t=0;t<r&&h<e;t++)for(let n=0;n<b&&h<e;n++)l(o,t,n),h++;else for(let t=0;t<b&&h<e;t++)for(let n=0;n<r&&h<e;n++)l(o,n,t),h++}return u}if("pyramid"===t){let t=e,n=0;for(;t>0;){const e=Math.max(1,m-n),i=Math.max(1,g-n),s=e*i,o=Math.min(t,s);for(let t=0;t<o;t++){const s=t%e,r=Math.floor(t/e),o=-a/2+(s+(m-e)/2+.5)*p,l=-c/2+(r+(g-i)/2+.5)*f;u.push({x:o,y:n*d+d/2,z:l})}if(t-=o,n++,1===e&&1===i){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(r&&n>=r)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),i=n%y,s=i%m,o=Math.floor(i/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(s+.5)*p+g,_=-c/2+(o+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),r&&e>=r-1&&i===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(r&&e>=r)break;const i=n%y,s=i%m,o=Math.floor(i/m);let l=-a/2+(s+.5)*p;const h=-c/2+(o+.5)*f;"staggered"===t&&e%2==1&&(l+=p/2),u.push({x:l,y:e*d+d/2,z:h})}return u}class Uy{constructor(t,e={}){this.pattern=t,this.defaults=e}layout(t,e,n,i={}){const s=i.gap??this.defaults.gap??0,r=i.heightLimit??this.defaults.heightLimit,o=i.fill??this.defaults.fill;return Vy(this.pattern,t,e,n,s,r,o).map(t=>({position:t}))}}class Wy{constructor(t,e,n={}){this.cols=t,this.rows=e,this.defaults=n}layout(t,e,n,i={}){const s=Math.max(1,this.cols),r=Math.max(1,this.rows),o=s*r,a=i.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/o),i=e%o,a=i%s,d=Math.floor(i/s);h.push({position:{x:(a-(s-1)/2)*c,z:(d-(r-1)/2)*l,y:t*n.d+n.d/2}})}return h}}class qy{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,i=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-i)/(e.h+i))),pitchX:e.w+n,pitchZ:e.h+i}}capacity(t,e,n){const{cols:i,rows:s}=this.grid(t,e);return i*s*Math.max(1,Math.floor(n))}layout(t,e,n,i={}){const{cols:s,rows:r,pitchX:o,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=i.heightLimit?Math.max(1,Math.floor(i.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=s*r,p=s*(h?l:1),f=s*r*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,i,l;if(d){const n=Math.floor(t/p),r=t%p;e=r%s,l=Math.floor(r/s),i=n}else{l=Math.floor(t/u);const n=t%u;e=n%s,i=Math.floor(n/s)}this.fillFromFar&&(i=r-1-i),g.push({position:{x:(e-(s-1)/2)*o,z:(i-(r-1)/2)*a,y:l*c+n.d/2}})}return g}}function Xy(t,e,n,i=0){for(let s=0;s<e.length;s++){const r=e[s],o=n[s];r&&o&&(r.parent!==t&&t.attach(r),r.position.set(o.position.x,i+o.position.y,o.position.z),o.rotation?r.quaternion.set(o.rotation.x,o.rotation.y,o.rotation.z,o.rotation.w):r.quaternion.identity())}}function Ky(t,e,n,i=.12){const s=e.left+e.width/2,r=e.top+e.height/2,o=Math.min(n.w,n.h)*i,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let i=a.get(t);i||(i={x:s+e.position.x-n.w/2+o,y:r+e.position.z-n.h/2+o,w:n.w-2*o,h:n.h-2*o,count:0},a.set(t,i)),i.count++}return[...a.values()]}function Qy(t){return{id:t?.state?.id??t?.id??t?.refid,type:t?.state?.type??t?.type}}const Jy=new t.Euler;function Zy(e,n){Jy.setFromQuaternion(new t.Quaternion(n.x,n.y,n.z,n.w),"YXZ"),e.rotationX=Jy.x,e.rotation=-Jy.y,e.rotationY=Jy.z}const tb="_transferSlotId",eb=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 nb(t){return class extends t{async ready(){await super.ready();const t=this.state?.data;Array.isArray(t)&&0===this._items.length&&!this.isRecordStorage&&this._reconcileItems(t)}set data(t){if(Array.isArray(t)){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.isRecordStorage)return this.state?.data??[];const t=this._exportSlotRecords();return 0===t.length?this.state?.data:t}_reconcileItems(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=t[tb];null!=e&&n.set(String(e),t)}for(const[t,i]of n)if(!e.has(t)){try{this.removeItem(i,!0)}catch{}try{i?.dispose?.()}catch{}}for(const[t,i]of e){if(n.has(t))continue;if(null==i.itemId)continue;const e=this._createItemFromRecord(i);if(e){e[tb]=t;try{this.handoverIn(e)}catch{}}}for(const[t,i]of e){const e=n.get(t);if(e&&(i.itemState&&"function"==typeof e.setState))try{e.setState(i.itemState)}catch{}}}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,i=[];for(const t of this._items){const e=t[tb];null!=e?n.set(String(e),t):i.push(t)}for(const i of t){const t=n.get(i)??null;e.push(this._slotRecordOf(i,t))}for(const t of i)e.push(this._slotRecordOf("",t));for(const[i,s]of n)t.includes(i)||e.push(this._slotRecordOf(i,s));return e}_recordKey(t){return 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 i of n)i in e&&void 0!==e[i]&&(t[i]=e[i]);return Object.keys(t).length>0?t:void 0}const i={};for(const t of Object.keys(e))eb.has(t)||t.startsWith("_")||(i[t]=e[t]);return Object.keys(i).length>0?i:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=Cc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}class ib{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const sb=new ib,rb=["x","y","z"],ob=["Capacity","Holdable","Transferable","FlowNode"],ab=Object.freeze({Transferable:["Capacity","FlowNode"]}),cb=["S","M","L","XL"],lb=[8,12,16,24,32,48],hb=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function db(t,e){const n="shape"in t?t.shape:void 0,i=n?.extrusion?.section,s="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===i?.kind||"rectangle"===i?.kind&&Object.values(i.corner??{}).some(t=>t>0));if(!s||"full"===e)return t.segments;const r=t.segments??12,o=Math.ceil(r/("medium"===e?2:4));return Math.min(r,lb.find(t=>t>=o)??r)}function ub(t,e){if("full"===e)return t;let n=!1;const i=t.geometry.map(t=>{const i=db(t,e);return i===t.segments?t:(n=!0,{...t,segments:i})});return n?{...t,geometry:i}:t}class pb extends Error{code;path;details;constructor(t,e,n,i){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==i&&(this.details=i)}}const fb=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),mb=1e-6,gb=256,yb=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function bb(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const vb=t=>fb[t],_b=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function xb(t,e){const[n,i]=vb(e);if("rectangle"===t.kind){const e=[];for(const s of[n,i]){const n=t.size[s];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:s}):e.push({code:"NON_FINITE",at:`size.${s}`})}if(!t.corner)return e;for(const s of[n,i]){const n=t.corner[s];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:s}):Number.isFinite(t.size[s])&&n>t.size[s]/2+mb&&e.push({code:"CORNER_TOO_LARGE",axis:s,max:t.size[s]/2}):e.push({code:"NON_FINITE",at:`corner.${s}`})}return e.length||t.corner[n]>0==t.corner[i]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:i}),e}if("ellipse"===t.kind){const e=[];for(const s of[n,i]){const n=t.radius[s];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:s}):e.push({code:"NON_FINITE",at:`radius.${s}`})}return e}return function(t,e){const[n,i]=vb(e),s=[],r=new Set;for(const e of t){"string"==typeof e.id&&yb.test(e.id)?r.has(e.id)?s.push({code:"DUPLICATE_POINT_ID",point:e.id}):r.add(e.id):s.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,i])"number"==typeof e[t]&&Number.isFinite(e[t])||s.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&s.push({code:"TOO_FEW_POINTS",count:t.length});t.length>gb&&s.push({code:"TOO_MANY_POINTS",count:t.length,limit:gb});if(s.length)return s;const o=t.length,a=function(t,e){const[n,i]=vb(e);return t.map(t=>[t[n],t[i]])}(t,e),c=e=>bb(t[e].id,t[(e+1)%o].id),l=mb,h=a.map((t,e)=>Math.hypot(a[(e+1)%o][0]-t[0],a[(e+1)%o][1]-t[1]));if(h.forEach((t,e)=>{t<=l&&s.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),s.length)return s;for(let t=0;t<o;t++){const e=a[t],n=a[(t+1)%o],i=a[(t+2)%o],r=(n[0]-e[0])*(i[1]-n[1])-(n[1]-e[1])*(i[0]-n[0]),d=(n[0]-e[0])*(i[0]-n[0])+(n[1]-e[1])*(i[1]-n[1]);Math.abs(r)<=l*h[t]&&d<0&&s.push({code:"SIDES_FOLD",sides:[c(t),c((t+1)%o)]})}for(let t=0;t<o;t++)for(let e=t+1;e<o;e++){if(e===t+1||0===t&&e===o-1)continue;const n=Sb(a[t],a[(t+1)%o],a[e],a[(e+1)%o],l);n&&s.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(s.length)return s;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[i,s]=t[n],[r,o]=t[(n+1)%t.length];e+=i*o-r*s}return e}(a))/2<=l&&s.push({code:"ZERO_AREA"});return s}(t.points,e)}const wb=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function Mb(t,e,n){const i=n[0]-e[0],s=n[1]-e[1],r=i*i+s*s,o=r?Math.max(0,Math.min(1,((t[0]-e[0])*i+(t[1]-e[1])*s)/r)):0;return Math.hypot(t[0]-e[0]-o*i,t[1]-e[1]-o*s)}function Sb(t,e,n,i,s){const r=wb(n,i,t),o=wb(n,i,e),a=wb(t,e,n),c=wb(t,e,i),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>s*n&&e<-s*n||t<-s*n&&e>s*n;if(h(r,o,Math.hypot(i[0]-n[0],i[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(Mb(t,n,i),Mb(e,n,i),Mb(n,t,e),Mb(i,t,e))<=s?"touch":null}function Ab(t,e){const[n,i]=vb(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,s]=[n,i].sort(),r=[e,s].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!_b(t))return r;const o=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${s}${n}`,shape:"curved"})));return[...r,...o]}const s=t.points;return s.map((t,e)=>{const n=s[(e+1)%s.length];return{id:bb(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function Eb(t,e,n){const[i,s]=vb(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const r=[i,s].flatMap(t=>[`${t}-`,`${t}+`]);for(const t of r){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 o=t=>n[t],a=(t,e)=>e-o(`${t}-`)-o(`${t}+`),c={[i]:(o(`${i}-`)-o(`${i}+`))/2,[s]:(o(`${s}-`)-o(`${s}+`))/2};if("rectangle"===t.kind){const e={[i]:a(i,t.size[i]),[s]:a(s,t.size[s])};if(!(e[i]>0&&e[s]>0))return{refused:"NO_ROOM_INSIDE"};if(!_b(t))return{section:{kind:"rectangle",size:e},centre:c};const n=e=>Math.max(t.corner[e]-Math.max(o(`${e}-`),o(`${e}+`)),0),r={[i]:n(i),[s]:n(s)};return{section:{kind:"rectangle",size:e,...r[i]>0&&r[s]>0?{corner:r}:{}},centre:c}}const l={[i]:a(i,2*t.radius[i])/2,[s]:a(s,2*t.radius[s])/2};return l[i]>0&&l[s]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const kb=(t,e)=>Object.fromEntries(rb.map(n=>[n,n===t?e:0]));function Cb(t,e,n){const[i,s]=fb[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return kb(t,n.id.endsWith("+")?1:-1)}const r=t.points.find(t=>t.id===n.from),o=t.points.find(t=>t.id===n.to),a=o[i]-r[i],c=o[s]-r[s],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[i]=c/l||0,h[s]=-a/l||0,h}const Tb=(t,e,n)=>{throw new pb(t,e,n)},Ob=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],Pb=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),Ib=["rectangle","ellipse","polygon","portal"],Db=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function zb(t,e){const n=t??{},i=n.axis;rb.includes(i)||Tb("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const s=n.section;Ib.includes(s)||Tb("PARAM",e,`section is ${Ib.join(", ")}, not ${String(n.section)}`);const r=[...fb[i]].sort(),[o,a]=r,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===s||Tb("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===s?String(n.points??"").split("."):[];"polygon"===s?((l.length<3||l.some(t=>!Db.test(t)))&&Tb("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&Tb("PARAM",e,"a point is named twice")):void 0!==n.points&&Tb("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==s&&"ellipse"!==s&&"portal"!==s||(u.across={[o]:d(),[a]:d()}),c&&(u.corner={[o]:d(),[a]:d()}),"portal"===s&&(u.jamb=d(),u.head=d()),"polygon"===s&&(u.point=Object.fromEntries(l.map(t=>[t,{[o]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==s&&"ellipse"!==s&&Tb("SECTION_KIND",e,`a ${s} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const i=n[t];return"open"!==i&&"closed"!==i&&Tb("PARAM",e,`${t} is open or closed`),i};p={id:n.cavity,start:t("cavity-start"),end:t("cavity-end")},u.wall=Object.fromEntries([o,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"]||Tb("PARAM",e,"the ends of an inside need the inside");return{axis:i,plane:r,section:s,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const Rb=(t,e=1)=>[{arg:t,k:e}];function jb(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const i=t.args?.[0],s=t.args?.[1],r=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(i));return"mul@1"!==r?.op||2!==r.args.length||r.args[0]!==s||-.5!==e.constants.find(t=>t.id===r.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function Lb(t,e){const n=zb(t.params,t.id),[i,s]=n.plane,r={},o={},a={},[c,l]=Pb[n.axis],h=jb(t,e);if(r[n.axis]=Rb(1),o[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[i,s])r[t]="profile",o[t]={refused:"SECTION_CORNERS"};return{measure:r,edit:o,faces:a,kind:"polygon"}}const d=n.arg.across,u="ellipse"===n.section?2:1;for(const t of[i,s])r[t]=Rb(d[t],u),o[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[i]]&&t.args[d[i]]===t.args[d[s]]&&(o[s]={arg:d[s],k:u,sameAs:i}),"portal"===n.section){const[t,e]=Pb[i],[c,l]=Pb[s];return a[t]={axis:i,normal:-1,plane:[{arg:d[i],k:-.5}]},a[e]={axis:i,normal:1,plane:[{arg:d[i],k:.5}]},a[c]={axis:s,normal:-1,plane:[]},a[l]={axis:s,normal:1,plane:[{arg:d[s],k:1}]},a[`opening-${t}`]={axis:i,normal:1,plane:[{arg:d[i],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:i,normal:-1,plane:[{arg:d[i],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:s,normal:-1,plane:[{arg:d[s],k:1},{arg:n.arg.head,k:-1}]},{measure:r,edit:o,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[i,s]){const[e,n]=Pb[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[i,s]){const[n,i]=Pb[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${i}`]={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:r,edit:o,faces:a,kind:n.section}}function Fb(t,e){const n=t??{},i=n.axis;return rb.includes(i)||Tb("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&Tb("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:i,profile:n.profile,count:"taper"===n.profile?4:2}}function Nb(t,e){const n=Fb(t.params,t.id),[i,s]=[...fb[n.axis]].sort(),r={},o={};if("half-ellipse"===n.profile)return r[n.axis]=Rb(1,2),o[n.axis]={arg:1,k:2},r[i]=r[s]=Rb(0,2),o[i]={arg:0,k:2},o[s]={arg:0,k:2,sameAs:i},{measure:r,edit:o,faces:{},kind:"sphere"};const[a,c]=Pb[n.axis];r[n.axis]=Rb(1),o[n.axis]={arg:1,k:1};r[i]=r[s]=[{arg:2,k:2},{arg:3,k:2}],o[i]={arg:3,k:2,with:[2]},o[s]={arg:3,k:2,with:[2],sameAs:i};const l=jb(t,e);return{measure:r,edit:o,faces:{[a]:{axis:n.axis,normal:-1,plane:l.lo},[c]:{axis:n.axis,normal:1,plane:l.hi}},kind:"taper"}}function $b(t,e){const n=t??{};"polygon"!==n.section&&Tb("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||Tb("PARAM",e,"a loft has no corners and no inside");const i=zb(n,e),[s,r]=i.plane;return{...i,apex:{[s]:i.count,[r]:i.count+1},count:i.count+2}}function Hb(t,e){const n=$b(t.params,t.id),i={},s={},[r]=Pb[n.axis];i[n.axis]=Rb(1),s[n.axis]={arg:1,k:1};for(const t of n.plane)i[t]="profile",s[t]={refused:"SECTION_CORNERS"};return{measure:i,edit:s,faces:{[r]:{axis:n.axis,normal:-1,plane:jb(t,e).lo}},kind:"pyramid"}}function Bb(t,e){return"extrude@1"===t?.op?Lb(t,e):"revolve@1"===t?.op?Nb(t,e):"loft@1"===t?.op?Hb(t,e):void 0}const Yb=(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 Gb(t,e,n){const i=rb.find(t=>t!==e&&t!==n),[s,r]=fb[i];let o=0;for(let e=0;e<t.length;e++){const n=t[e],i=t[(e+1)%t.length];o+=n[s]*i[r]-i[s]*n[r]}return o>0?t:[t[0],...t.slice(1).reverse()]}function Vb(t,e){const[n,i]=fb[e];let s=0;const r=t.points;for(let t=0;t<r.length;t++){const e=r[t],o=r[(t+1)%r.length];s+=e[n]*o[i]-o[n]*e[i]}return s}function Ub(t,e,n){const i=zb(n.params,e),[s,r]=i.plane,o=t[0],a=t[1];a>0||Tb("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:o,length:a};let l;if("polygon"===i.section){const e=i.points.map(e=>({id:e,[s]:t[i.arg.point[e][s]],[r]:t[i.arg.point[e][r]]}));e.forEach(t=>{c[`point.${t.id}.${s}`]=t[s],c[`point.${t.id}.${r}`]=t[r]}),l={kind:"polygon",points:e}}else if("portal"===i.section){const n=t[i.arg.across[s]],o=t[i.arg.across[r]],a=t[i.arg.jamb],h=t[i.arg.head];n>0&&o>0&&a>0&&h>0&&2*a<n&&h<o||Tb("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${s}`]:n,[`size.${r}`]:o,jamb:a,head:h}),l=function(t,e,n,i,s,r){const o=-n/2,a=n/2,c=o+s,l=a-s,h=i-r,d=(n,i,s)=>({id:n,[t]:i,[e]:s});return{kind:"polygon",points:Gb([d("p1",o,0),d("p2",o,i),d("p3",a,i),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(s,r,n,o,a,h)}else{const e={[s]:t[i.arg.across[s]],[r]:t[i.arg.across[r]]},n="ellipse"===i.section?"radius":"size";if(c[`${n}.${s}`]=e[s],c[`${n}.${r}`]=e[r],"ellipse"===i.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},i.rounded){const n={[s]:t[i.arg.corner[s]],[r]:t[i.arg.corner[r]]};c[`corner.${s}`]=n[s],c[`corner.${r}`]=n[r],(n[s]>0||n[r]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=xb(l,i.axis);h.length&&Tb("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`),"polygon"!==l.kind||"polygon"!==i.section||Vb(l,i.axis)>0||Tb("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:i.axis,section:l,start:o,end:o+a};let u;if(i.cavity){const n=Object.fromEntries(Object.entries(i.arg.wall).map(([e,n])=>[e,t[n]]));u={id:i.cavity.id,wall:n,start:"open"===i.cavity.start?"open":{closed:t[i.arg.startClosed]},end:"open"===i.cavity.end?"open":{closed:t[i.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 s=function(t,e=[]){const{axis:n,section:i,start:s,end:r}=t;if(!(r-s>0))return{refused:{code:"SPAN_NOT_POSITIVE"}};if(e.length>1)return{refused:{code:"CAVITY_COUNT",count:e.length}};const o=e[0];let a;if(o){const t=Eb(i,n,o.wall);if("refused"in t)return{refused:{code:"CAVITY",cavity:o.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=o[t];if("open"!==e&&!(e.closed>0))return{refused:{code:"CAVITY_END_NOT_POSITIVE",cavity:o.id,end:t}}}if(!(r-s-e(o.start)-e(o.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:o.id}}}const c=Ab(i,n),l=[{id:"start-face",kind:"plane",normal:kb(n,-1),..."open"===o?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:kb(n,1),..."open"===o?.end?{open:!0}:{}}];for(const t of c)l.push("flat"===t.shape?{id:`side-face:${t.id}`,kind:"plane",normal:Cb(i,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"===i.kind)for(const t of i.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===i.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...fb[n]].sort();for(const n of["-","+"])for(const i of["-","+"])l.push({id:`edge:${t}${n}${e}${i}`,kind:"edge"})}if(o&&a){for(const t of Ab(a,n)){const e=`cavity-wall:${o.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const i=Cb(a,n,t);l.push({id:e,kind:"plane",normal:{x:-i.x||0,y:-i.y||0,z:-i.z||0}})}}"open"!==o.start&&l.push({id:`cavity-start:${o.id}`,kind:"plane",normal:kb(n,1)}),"open"!==o.end&&l.push({id:`cavity-end:${o.id}`,kind:"plane",normal:kb(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in s&&Tb("GEOMETRY_DOMAIN",e,`the inside is not valid: ${s.refused.code}${"refused"in s.refused?` ${s.refused.refused}`:""}`)}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:Yb(Lb(n).faces,t)}}function Wb(t,e,n){const i=Fb(n.params,e),s=Yb(Nb(n).faces,t);if("half-ellipse"===i.profile){const[n,r]=t;return n>0&&r>0||Tb("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:r},revolution:{axis:i.axis,profile:{kind:"half-ellipse",radial:n,axial:r}},faces:s}}const[r,o,a,c]=t;return o>0&&a>=0&&c>=0&&a+c>0||Tb("GEOMETRY_DOMAIN",e,"a positive length and radii of 0 or more, not both 0, required"),{provider:"revolve",dimensions:{start:r,length:o,startRadius:a,endRadius:c},revolution:{axis:i.axis,profile:{kind:"taper",start:r,end:r+o,startRadius:a,endRadius:c}},faces:s}}function qb(t,e,n){const i=$b(n.params,e),[s,r]=i.plane,o=t[0],a=t[1];a>0||Tb("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:o,length:a},l=i.points.map(e=>({id:e,[s]:t[i.arg.point[e][s]],[r]:t[i.arg.point[e][r]]}));l.forEach(t=>{c[`point.${t.id}.${s}`]=t[s],c[`point.${t.id}.${r}`]=t[r]});const h={kind:"polygon",points:l},d=xb(h,i.axis);d.length&&Tb("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`),Vb(h,i.axis)>0||Tb("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[s]:t[i.apex[s]],[r]:t[i.apex[r]]};return Number.isFinite(u[s])&&Number.isFinite(u[r])||Tb("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${s}`]=u[s],c[`apex.${r}`]=u[r],{provider:"loft",dimensions:c,loft:{axis:i.axis,section:h,start:o,end:o+a,apex:u},faces:Yb(Hb(n).faces,t)}}function Xb(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 Kb={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const i=zb(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a ${i.section} push takes ${i.count} lengths, not ${t.length}`),[Xb("extrude",n,Lb(n).faces)]},run:(t,e,n)=>[Ub(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const i=Fb(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a ${i.profile} turn takes ${i.count} lengths, not ${t.length}`),[Xb("revolve",n,Nb(n).faces)]},run:(t,e,n)=>[Wb(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const i=$b(n.params,e);return t.length===i.count&&t.every(Ob)||Tb("TYPE",e,`a loft of ${i.points.length} points takes ${i.count} lengths, not ${t.length}`),[Xb("loft",n,Hb(n).faces)]},run:(t,e,n)=>[qb(t,e,n)]}};function Qb(t){const e={};if(t.extrusion){const n=t.extrusion,[i,s]=fb[n.axis];e[n.axis]={min:n.start,max:n.end};const r=n.section;for(const t of[i,s])if("rectangle"===r.kind)e[t]={min:-r.size[t]/2,max:r.size[t]/2};else if("ellipse"===r.kind)e[t]={min:-r.radius[t],max:r.radius[t]};else{const n=r.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 fb[n.axis]){const i=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...i),max:Math.max(...i)}}return e}const n=t.revolution,[i,s]=fb[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[i,s])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[i,s])e[n]={min:-t,max:t}}return e}function Jb(t,e){"string"!=typeof t&&Zb("PARAM",e,"layout required"),t.startsWith("L")||Zb("PARAM",e,"layout starts with L");const n=t.slice(1).split(".").map(t=>""===t?[]:t.split("_").map(Number));return(6!==n.length||n.some(t=>!t.length||t.some(t=>!Number.isSafeInteger(t)||t<0)))&&Zb("PARAM",e,"layout is six groups of term counts, each with one candidate or more"),n}const Zb=(t,e,n)=>{throw new pb(t,e,n)},tv={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]},ev=[1,0,0],nv=[0,0,0],iv=[0,1,0],sv={kind:"count"},rv={kind:"flag"};tv.count=[sv,1];const ov=(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 av(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||Zb("SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||Zb("SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||Zb("SCHEMA",i,`unknown ${s}`)}function cv(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||Zb("ID",e,"invalid id"),t}function lv(t,e){return"number"==typeof t&&Number.isFinite(t)||Zb("NON_FINITE",e,String(t)),t}function hv(t,e){return Object.hasOwn(tv,t)||Zb("UNIT",e,String(t)),tv[t]}function dv(t,e,n){(t.length!==e.length||t.some((t,n)=>!ov(t,e[n])))&&Zb("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}const uv={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&ov(t[0],t[1])||Zb("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)||Zb("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)||Zb("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&Zb("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>(dv(t,[iv],e),[nv]),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=>ov(e,t[0])))&&Zb("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&Zb("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))&&Zb("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)ov(t[n],t[0])||Zb("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),ov(t[n+1],t[2])||Zb("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],i=(t.length-1)/2,s=e=>t[1+2*e],r=e=>t[2+2*e];for(let t=1;t<i;t++)s(t)>s(t-1)||Zb("DOMAIN",e,`keys out of order: at[${t}] = ${s(t)} is not after at[${t-1}] = ${s(t-1)}`);if(n<=s(0))return[r(0)];if(n>=s(i-1))return[r(i-1)];let o=0;for(;o<i-2&&s(o+1)<=n;)o++;const a=(n-s(o))/(s(o+1)-s(o));return[r(o)+(r(o+1)-r(o))*a]}},"at-least@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&ov(t[0],t[1])||Zb("TYPE",e,"at-least compares two scalars of the same dimension"),[rv]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>ov(e,t[0])))&&Zb("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.max(...t)]},"min@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>ov(e,t[0])))&&Zb("TYPE",e,"two or more scalars of the same dimension"),[t[0]]),run:t=>[Math.min(...t)]},"affine-bounds@1":{ports:["xmin","xmax","ymin","ymax","zmin","zmax"],params:["layout"],types(t,e,n){const i=Jb(n.params.layout,e);let s=0;for(const n of i)for(const i of n){ov(t[s++],ev)||Zb("TYPE",e,`candidate constant ${s-1} is a length`);for(let n=0;n<i;n++)ov(t[s++],ev)||Zb("TYPE",e,`term value ${s-1} is a length`),ov(t[s++],nv)||Zb("TYPE",e,`term ratio ${s-1} is a ratio`)}return s!==t.length&&Zb("TYPE",e,`the layout takes ${s} arguments; ${t.length} were given`),Array(6).fill(ev)},run:(t,e,n)=>{const i=Jb(n.params.layout,e);let s=0;return i.map((e,n)=>{const i=e.map(e=>{let n=t[s++];for(let i=0;i<e;i++)n+=t[s++]*t[s++];return n});return n%2==0?Math.min(...i):Math.max(...i)})}},"between@1":{ports:["length","center"],types:(t,e)=>(dv(t,[ev,ev,ev,ev],e),[ev,ev]),run:([t,e,n,i],s)=>{(n<0||i<0)&&Zb("DOMAIN",s,"negative margin");const r=e-t-n-i;return r>0||Zb("NO_SPACE",s,`available=${e-t}; margins=${n+i}; deficit=${Math.max(0,-r)}; positive length required`),[r,(t+e+n-i)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>(dv(t,[ev,ev,ev],e),Array(6).fill(ev)),run:([t,e,n],i)=>([t,e,n].some(t=>!(t>0))&&Zb("GEOMETRY_DOMAIN",i,"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)=>(dv(t,[ev,ev],e),Array(4).fill(ev)),run:([t,e],n)=>(t>0&&e>0||Zb("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}})}},pv=(t,e)=>({kind:"transform",from:t,to:e}),fv=()=>[[1,0,0],[0,1,0],[0,0,1]],mv=t=>t[0].map((e,n)=>t.map(t=>t[n])),gv=(t,e)=>t.reduce((t,n,i)=>t+n*e[i],0),yv=(t,e,n,i)=>0+t[0]*e+t[1]*n+t[2]*i,bv=(t,e)=>3===t.length&&3===e.length?[yv(t[0],e[0],e[1],e[2]),yv(t[1],e[0],e[1],e[2]),yv(t[2],e[0],e[1],e[2])]:t.map(t=>gv(t,e)),vv=(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=>mv(e).map(e=>gv(t,e)));const[n,i,s]=e;return t.map(t=>[yv(t,n[0],i[0],s[0]),yv(t,n[1],i[1],s[1]),yv(t,n[2],i[2],s[2])])},_v=(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]),xv=(t,e)=>({r:vv(t.r,e.r),t:_v(bv(t.r,e.t),t.t)}),wv=t=>{const e=mv(t.r);return{r:e,t:bv(e,t.t.map(t=>-t))}};function Mv(t,e,n=[]){av(t.params,e,n,t.id);for(const i of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])cv(t.params[i],t.id)}function Sv(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&Zb("TYPE",e,"rigid transforms required")}Object.assign(uv,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>(dv(t,[ev,ev,ev,ev,ev,nv,sv],e),[{kind:"layout"}]),run:([t,e,n,i,s,r,o],a)=>{t>=0&&e>=0&&n>=0&&i>0&&s>0&&r>=0&&r<=1&&Number.isSafeInteger(o)&&o>=0&&o<=1e4||Zb("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<i?0:1+Math.floor((c-i)/s);l>o&&Zb("RESOURCE_LIMIT",a,`count=${l}, limit=${o}`);const h=l?c-i-(l-1)*s:0;return[{centers:Array.from({length:l},(t,n)=>e+i/2+r*h+n*s),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>(dv(t,[sv,ev,ev,ev,ev,nv,sv],e),[{kind:"layout"}]),run:([t,e,n,i,s,r,o],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(o)&&o>=0&&o<=1e4&&e>=0&&n>=0&&i>=0&&s>0&&r>=0&&r<=1||Zb("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>o&&Zb("RESOURCE_LIMIT",a,"fixed count exceeds limit"),!t)return[{centers:[],count:0}];const c=e-n-i-s;return(c<0||t>1&&c/(t-1)<s)&&Zb("NO_SPACE",a,"fixed count non-overlapping items do not fit"),[{centers:1===t?[n+s/2+r*c]:Array.from({length:t},(e,i)=>n+s/2+i*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)||Zb("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)||Zb("AXIS",e,n.params.axis);const i=4===t.length;return!i||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&ov(t[3],ev)||Zb("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!i||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&Zb("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,i],s,r)=>{t.count*e.members.length>1e4&&Zb("RESOURCE_LIMIT",s,"expanded geometry count > 10000");const o=["x","y","z"].indexOf(r.params.axis),a=["x","y","z"].indexOf(r.params.riseAxis),c=[];for(let s=0;s<t.count;s++)for(const l of e.members){const e=[0,0,0];e[o]=t.centers[s],void 0!==i&&(e[a]=s*i);const h=[r.id,s,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:s,shape:l.shape,pose:xv(xv(n,{r:fv(),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&&ov(t[1],sv)||Zb("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,i)=>{const s=t.items.find(t=>t.index===e&&t.key===i.params.member);return s||Zb("TARGET_ABSENT",n,`${i.params.member}[${e}]`),[{shape:s.shape,pose:s.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(dv(t,[ev,ev,ev,iv,iv,iv],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i,s,r])=>{const o=Math.cos(i),a=Math.sin(i),c=Math.cos(s),l=Math.sin(s),h=Math.cos(r),d=Math.sin(r);return[{r:vv(vv([[1,0,0],[0,o,-a],[0,a,o]],[[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)=>(dv(t,[nv,nv,nv,iv],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i],s)=>{const r=Math.hypot(t,e,n);Math.abs(r-1)>1e-6&&Zb("AXIS",s,"unit axis required");const o=t/r,a=e/r,c=n/r,l=Math.cos(i),h=Math.sin(i),d=1-l;return[{r:[[l+o*o*d,o*a*d-c*h,o*c*d+a*h],[a*o*d+c*h,l+a*a*d,a*c*d-o*h],[c*o*d-a*h,c*a*d+o*h,l+c*c*d]],t:[0,0,0]}]}},"axis-slide@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(dv(t,[nv,nv,nv,ev],e),[pv(n.params.from,n.params.to)]),run:([t,e,n,i],s)=>{const r=Math.hypot(t,e,n);return Math.abs(r-1)>1e-6&&Zb("AXIS",s,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/r*i,e/r*i,n/r*i]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(Sv(t,e,2),t[1].to!==t[0].from&&Zb("FRAME_TYPE",e,"composition intermediate frame mismatch"),[pv(t[1].from,t[0].to)]),run:([t,e])=>[xv(t,e)]},"attach@1":{ports:["pose"],types(t,e){Sv(t,e,3);const[n,i,s]=t;return n.from===i.to&&i.from===s.from||Zb("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[pv(s.to,n.to)]},run:([t,e,n])=>[xv(xv(t,e),wv(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>(dv(t,[ev,ev,ev],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||Zb("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[_v(bv(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&ov(t[0],t[1])||Zb("FRAME_TYPE",e,"distance requires points in same frame"),[ev]),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||Zb("TYPE",e,"shape required");const i=Object.keys(t[0].faces);return[...i,"centre",..."revolve"!==t[0].provider||i.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||Zb("UNKNOWN_FEATURE",e,n.params.name),[pv(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const i=function(t,e){const n=Qb(t),i=rb.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return i;const s=t.faces[e],r={x:0,y:1,z:2};if(s){const n=[...i];if(n[r[s.axis]]=s.at,t.loft)for(const e of fb[t.loft.axis]){const i=t.loft.section.points.map(t=>t[e]);n[r[e]]=(Math.min(...i)+Math.max(...i))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,o=t.cavity,a=o.wall;for(const t of fb[e.axis])t!==s.axis&&(n[r[t]]=i[r[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(s.axis!==e.axis){const t=e.start+("open"===o.start?0:o.start.closed),i=e.end-("open"===o.end?0:o.end.closed);n[r[e.axis]]=(t+i)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(Pb).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]).find(([t])=>t===e);if(!t)return;const s=[...i];return s[r[t[1]]]=t[2]<0?n[t[1]].min:n[t[1]].max,s}}(t,n.params.name);return i||Zb("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:i}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||Zb("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})}}),uv["member@1"]={...uv["place@1"],geometry:void 0},Object.assign(uv,Kb);for(const[t,e]of Object.entries(uv))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const Av=[];for(const[t,e]of Object.entries(uv))e.pure=!Av.includes(t);const Ev=["add@1","mul@1","div@1","sin@1","geomean@1","curve@1","at-least@1","max@1","min@1","affine-bounds@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(uv))e.pure&&Ev.includes(t)&&(e.poseForm="run");function kv(t,e,n){return Array.isArray(e)?lv(t,n):"flag"===e.kind?("boolean"!=typeof t&&Zb("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&Zb("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&Iv(t)?zv(t,n):"placed"===e.kind&&Pv(t,"shape","pose")&&jv.has(t.shape)&&Iv(t.pose)?zv(t.pose,n):(Rv(t,n),"shape"===e.kind&&t&&"object"==typeof t&&jv.add(t)),t)}function Cv(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++)Cv(t[e]);else for(const e in t)Cv(t[e]);return t}function Tv(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(Iv(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 i=0;i<t.length;i++)n[i]=Tv(t[i],e)}else{n={};for(const i in t)n[i]=Tv(t[i],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(uv).filter(t=>!uv[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(uv).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(uv).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(uv));const Ov=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],Pv=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let i=0;for(const s in t)if(Object.hasOwn(t,s)){if(i>1||s!==(0===i?e:n))return!1;i++}return 2===i},Iv=t=>Pv(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function Dv(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const i=t[n];"number"==typeof i?Number.isFinite(i)||Zb("NON_FINITE",e,String(i)):Rv(i,e)}}function zv(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const i=t.r[n];Array.isArray(i)?Dv(i,e):Rv(i,e)}Dv(t.t,e)}function Rv(t,e){if("number"==typeof t)Number.isFinite(t)||Zb("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&Rv(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]])))&&jv.has(t))return;for(let i=0;i<n.length;i++)Rv(t[n[i]],e)}}const jv=new WeakSet,Lv=["transform","placed","assembly","collection","point"],Fv=t=>Array.isArray(t)||Lv.includes(t?.kind)?void 0:String(t?.kind??"value");function Nv(t){return function(t){av(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||Zb("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||Zb("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,i=new Map,s=new Map,r=new Map,o=[],a=[],c=(t,e)=>{cv(t,e),n.has(t)&&Zb("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)av(t,["id","unit","min","max"],["role"],"input"),c(t.id,"input"),i.set(t.id,hv(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&Zb("SCHEMA",t.id,"unknown input role"),"state"===t.role&&s.set(t.id,new Set([t.id])),lv(t.min,t.id)>lv(t.max,t.id)&&Zb("RANGE",t.id,"min > max"),"count"===t.unit&&(kv(t.min,sv,t.id),kv(t.max,sv,t.id));for(const t of e.constants)av(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),i.set(t.id,hv(t.unit,t.id)[0]),kv(t.value,i.get(t.id),t.id);for(const t of e.nodes){av(t,["id","op","args","outputs"],["params"],"node"),cv(t.id,"node"),r.has(t.id)&&Zb("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(uv,t.op)||Zb("OPERATOR",t.id,t.op),uv[t.op].params?Mv(t,uv[t.op].params,uv[t.op].optionalParams):Object.hasOwn(t,"params")&&Zb("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||Zb("SCHEMA",t.id,"args array required"),t.args.forEach(e=>cv(e,t.id)),av(t.outputs,uv[t.op].ports,[],t.id);for(const e of Object.values(t.outputs))c(e,t.id);r.set(t.id,t)}const l=new Set,h=new Set,d=[],u=t=>{h.has(t)&&Zb("CYCLE",t,[...a,t].join(" -> ")),a.push(t),h.add(t),d.push({n:r.get(t),at:0,inputTypes:[]})};for(const t of r.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 s=e.args[t.at];if(n.has(s)||Zb("UNKNOWN_REFERENCE",e.id,s),!i.has(s)){u(n.get(s));continue}t.inputTypes.push(i.get(s)),t.at++;continue}const r=uv[e.op],c=r.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of s.get(t)??[])p.add(e);p.size&&(void 0===r.state&&Zb("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===r.state&&Zb("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),r.ports.forEach((t,n)=>i.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>s.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),o.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)||Zb("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||Zb("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||Zb("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=lv(e,t.id);return(n<t.min||n>t.max)&&Zb("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`),kv(n*hv(t.unit,t.id)[1],i.get(t.id),t.id)}function b(t,n){g(t);const s=new Map,r=[],a=new Map,c=new Set;for(const n of e.inputs)s.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)s.set(t.id,lv(t.value*hv(t.unit,t.id)[1],t.id));for(const t of o){const e=uv[t.op],n=t.args.map(t=>s.get(t)),o=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{s.set(t.outputs[e],kv(o[n],i.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const i=Ov(e.geometry(n,o,t),t.id);a.set(t.id,i),r.push(...i)}}return{result:{values:Object.fromEntries(s),geometry:r},kept:{input:{...t},values:s,bodies:a}}}return{outputTypes:Object.fromEntries([...i].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...s].map(([t,e])=>[t,[...e].sort()])),order:o.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,i=0,s=[],r=0;const o=(t,e)=>{const n=e||t.length!==s.length||t.some((t,e)=>t!==s[e]);return n&&i++,s=t,n},a=(t,e)=>(o(t.geometry.map(t=>t.id),e),t),c=t=>{r++;const n=e;if(e=void 0,!n)return e=_(b(t).kept),a({values:{...e.values},geometry:e.geometry.slice()},!0);const i=A(t,n,!0);return e=n,a(i,!1)},l=(t,n)=>{const s=++r,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=o(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 E=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[E]=g[t]+n,S[E]=e.shape??null;const i=12*E;if(e.pose){const t=e.pose.r,n=e.pose.t;M[i]=t[0][0],M[i+1]=t[0][1],M[i+2]=t[0][2],M[i+3]=t[1][0],M[i+4]=t[1][1],M[i+5]=t[1][2],M[i+6]=t[2][0],M[i+7]=t[2][1],M[i+8]=t[2][2],M[i+9]=n[0],M[i+10]=n[1],M[i+11]=n[2]}else M.fill(NaN,i,i+12);E++});const k=d.epoch,C=()=>{r!==s&&Zb("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:i,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{C();const e=h().slot.get(t);return void 0===e&&Zb("TARGET_ABSENT",t,"no such value"),Tv(d.slots[e],new Map)},changed:t=>{C();const e=h().slot.get(t);return void 0!==e&&(y||d.mark[e]===k||!!c?.moved.has(e))}}},h=()=>v();return{evaluate:c,advance(s,o){if(e&&!o){const o=++r,a=e;e=void 0;const h=S(s,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{r!==o&&Zb("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:i,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(s,h.why);return{kind:"evaluation",result:c(s),generation:i,why:h.why}}const a={code:!!e?o:"NOT_BOUND"};if(t.changes)return l(s,a);return{kind:"evaluation",result:c(s),generation:i,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||Zb("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&Zb("TARGET_ABSENT",t,"no such value");const i=e.fast;if(!i)return Tv(e.slots[n],new Map);const s=h().nodes.find(t=>t.outs.includes(n));if(s&&i.wrote.has(s.index)&&!i.moved.has(n)){return Tv(s.op.run(s.args.map(t=>i.slots[t]),s.n.id,s.n)[s.outs.indexOf(n)],new Map)}return Tv(i.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],s=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>s(t.id)),e.constants.forEach(t=>s(t.id));const r=o.map((e,n)=>{const r=uv[e.op];return r.ports.forEach(t=>s(e.outputs[t])),{n:e,op:r,index:n,args:e.args.map(e=>t.get(e)),outs:r.ports.map(n=>t.get(e.outputs[n])),types:r.ports.map(t=>i.get(e.outputs[t]))}}),a=n.map(()=>[]);for(const t of r)for(const e of t.args)a[e].push(t.index);const c=t=>{const e=new Uint8Array(r.length),n=[...t];for(;n.length;){const t=n.pop();for(const i of a[t])e[i]||(e[i]=1,n.push(...r[i].outs))}const i=[];return e.forEach((t,e)=>t&&i.push(e)),i},l=r.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:r,readers:a,reach:e.inputs.map((t,e)=>c([e])),always:h,shapes:r.filter(t=>t.op.geometry).map(t=>t.index),shapeSlot:n.map(t=>"shape"===i.get(t)?.kind)},p}function _(t,n=!0){const i=v(),s=i.keys.map(e=>t.values.get(e));s.forEach((t,e)=>i.shapeSlot[e]&&Cv(t));const r=i.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of i.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:s,bodies:r,shown:r.map(()=>{}),values:n,geometry:[],mark:new Int32Array(i.keys.length),ran:new Int32Array(i.nodes.length),epoch:0,pending:{nodes:new Set(i.shapes.filter(t=>r[t])),slots:new Set(i.keys.keys())}}}const o=new Map,a=r.map(t=>t?.map(t=>Tv(t,o))),c={};i.keys.forEach((t,e)=>c[t]=Tv(s[e],o));const l=[];for(const t of i.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:s,bodies:r,shown:a,values:c,geometry:l,mark:new Int32Array(i.keys.length),ran:new Int32Array(i.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),s=f.get(n);if(s)return s;const r=v(),o=t.forbidden??{},a=new Set(t.external??[]),c={inputs:e.inputs.map((t,e)=>{const n=Fv(i.get(t.id));if(n)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:n};if(Object.hasOwn(o,t.id))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:t.id,reaches:o[t.id]};for(const n of r.reach[e]){const e=r.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,i]of e.outs.entries()){const s=Fv(e.types[n]);if(s)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:s};const a=r.keys[i];if(Object.hasOwn(o,a))return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:o[a]}}}return{fast:!0}}),terminal:r.nodes.map(t=>"repeat@1"===t.n.op&&!t.n.params?.within&&t.outs.every(t=>!r.readers[t].length&&!a.has(r.keys[t]))),visits:new Map};return f.set(n,c),c}function w(t,e){const n=v();if(1===t.length)return n.reach[t[0]];const i=t.join();let s=e.visits.get(i);if(!s){const r=new Set;for(const e of t)for(const t of n.reach[e])r.add(t);s=[...r].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(i,s)}return s}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let i=0;for(const s of e.shapes)n[s]=i,i+=t.bodies[s]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:i,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,i){const s=v();g(t);const r=n.fast?.raw??n.raw,o=[],a=[];for(let n=0;n<e.inputs.length;n++){const i=e.inputs[n],s=t[i.id];s!==r[n]&&(a.push(y(i,s)),o.push(n))}for(const t of o)if(!i.inputs[t].fast)return{why:i.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;o.forEach((n,i)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[i],c.mark[n]=l});const h=w(o,i),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,i=e.t,s=12*p;d[p++]=t,u[s]=n[0][0],u[s+1]=n[0][1],u[s+2]=n[0][2],u[s+3]=n[1][0],u[s+4]=n[1][1],u[s+5]=n[1][2],u[s+6]=n[2][0],u[s+7]=n[2][1],u[s+8]=n[2][2],u[s+9]=i[0],u[s+10]=i[1],u[s+11]=i[2]};for(const t of h){const e=s.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const r=new Array(e.args.length);for(let t=0;t<e.args.length;t++)r[t]=c.slots[e.args[t]];if(i.terminal[t]){const[n,i,s,o]=r,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!==o&&(e[h]=t*o),d.push(xv(s,{r:fv(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of i.members){const i=xv(d[t],n.pose);Rv(i,e.n.id),f(u++,i)}c.wrote.add(t);continue}const o=e.op.run(r,e.n.id,e.n);if(e.outs.forEach((t,n)=>{c.slots[t]=kv(o[n],e.types[n],e.n.id),c.mark[t]=l,c.moved.add(t)}),e.op.geometry){const n=e.op.geometry(r,o,e.n),i=Array.isArray(n)?n:[n];let s=c.start[t];for(const t of i)f(s++,t.pose);c.wrote.add(t)}}return{result:{kind:"poses",generation:0,bodies:d.slice(0,p),poses:u.slice(0,12*p),read:t=>{const e=s.slot.get(t);return void 0===e&&Zb("TARGET_ABSENT",t,"no such value"),Tv(c.slots[e],new Map)},changed:t=>{const e=s.slot.get(t);return void 0!==e&&c.mark[e]===l}}}}function A(t,n,i){const s=v();g(t),n.fast=void 0;const r=++n.epoch,o=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,i)=>{const s=t[e.id];s!==n.raw[i]&&(n.slots[i]=y(e,s),n.raw[i]=s,n.mark[i]=r,o.push(i),c>=0&&(l=!0),c=i)}),l||s.always.length){const t=[];for(const e of[...o.map(t=>s.reach[t]),s.always])for(const i of e)n.ran[i]!==r&&(n.ran[i]=r,t.push(i));a=t.sort((t,e)=>t-e)}else a=c>=0?s.reach[c]:[];const h=[];for(const t of a){const e=s.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===r))continue;const i=e.args.map(t=>n.slots[t]),a=e.op.run(i,e.n.id,e.n);e.outs.forEach((t,i)=>{n.slots[t]=kv(a[i],e.types[i],e.n.id),s.shapeSlot[t]&&Cv(n.slots[t]),n.mark[t]=r,o.push(t)}),e.op.geometry&&(n.bodies[t]=Ov(e.op.geometry(i,a,e.n),e.n.id),n.pending.nodes.add(t),h.push(t))}for(const t of o)n.pending.slots.add(t);if(!i){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of o)n.values[s.keys[t]]=void 0;return h}return E(n),{values:{...n.values},geometry:n.geometry.slice()}}function E(t){const e=v(),{nodes:n,slots:i}=t.pending;if(!n.size&&!i.size)return;const s=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>Tv(t,s));for(const n of i)t.values[e.keys[n]]=Tv(t.slots[n],s);if(n.size){const n=[];for(const i of e.shapes){const e=t.shown[i];e&&n.push(...e)}t.geometry=n}n.clear(),i.clear()}}(t)}function $v(t,e,n){const i=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 i=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return i(n.min)&&i(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(i)throw new pb(i.code,n,i.message)}const Hv="0.5.0",Bv=(t,e,n)=>{throw new pb(t,e,n)},Yv={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 Gv(t,e,n){const{types:i,writers:s,model:r,assetFrame:o}=t;e&&"object"==typeof e&&!Array.isArray(e)||Bv("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||Bv("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||Bv("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||Bv("SCHEMA",n,"nonempty string required"),Object.hasOwn(i,t)||Bv("TARGET_ABSENT",n,t),i[t]),c=a(e.placement),l=a(e.feature),h=s.get(e.placement),d=s.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=s.get(h.args[0]),e="repeat@1"===t?.op?s.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||Bv("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=s.get(h.params.member),"member@1"!==p?.op&&Bv("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),r.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&Bv("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&&Bv("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required");"feature@1"!==d?.op&&Bv("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===o&&"transform"===l.kind||Bv("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&Bv("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=i[d.args[0]].provider,m=d.params.name,g=i[d.args[0]].faces,y=g?.[m];y||Bv("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&Bv("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 Vv(t,e,n,i,s={}){const[r,o]=fb[e],a=(t,i)=>{const a={x:0,y:0,z:0};return a[e]=n,a[r]=t+(s[r]??0),a[o]=i+(s[o]??0),[a.x,a.y,a.z]};if("polygon"===t.kind)return t.points.map(t=>a(t[r],t[o]));if("ellipse"===t.kind)return Array.from({length:i},(e,n)=>{const s=2*Math.PI*n/i;return a(t.radius[r]*Math.cos(s),t.radius[o]*Math.sin(s))});const c=t.size[r]/2,l=t.size[o]/2,h=t.corner?.[r]??0,d=t.corner?.[o]??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 i=0;i<=8;i++){const s=n+i/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(s),e*(l-d)+d*Math.sin(s)))}return u}function Uv(t,e){return function(t,e){const n=t.extrusion;if(n){const i=[...Vv(n.section,n.axis,n.start,e),...Vv(n.section,n.axis,n.end,e)],s=t.cavity;if(s){const t=Eb(n.section,n.axis,s.wall);if("section"in t){const r=n.start+("open"===s.start?0:s.start.closed),o=n.end-("open"===s.end?0:s.end.closed);i.push(...Vv(t.section,n.axis,r,e,t.centre),...Vv(t.section,n.axis,o,e,t.centre))}}return i}const i=t.loft;if(i){const t={x:0,y:0,z:0,...i.apex,[i.axis]:i.end};return[...Vv(i.section,i.axis,i.start,e),[t.x,t.y,t.z]]}const s=t.revolution,[r,o]=fb[s.axis],a=(t,n)=>Vv({kind:"ellipse",radius:{[r]:n,[o]:n}},s.axis,t,e);if("taper"===s.profile.kind)return[...a(s.profile.start,Math.max(s.profile.startRadius,1e-9)),...a(s.profile.end,Math.max(s.profile.endRadius,1e-9))];const{radial:c,axial:l}=s.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 Wv(t,e,n){return t.map(([t,i,s])=>[e[0][0]*t+e[0][1]*i+e[0][2]*s+n[0],e[1][0]*t+e[1][1]*i+e[1][2]*s+n[1],e[2][0]*t+e[2][1]*i+e[2][2]*s+n[2]])}function qv(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 Xv=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function Kv(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const Qv="holder",Jv=t=>"number"==typeof t&&Number.isFinite(t),Zv=t=>Jv(t)&&t>0,t_=t=>Number.isSafeInteger(t)&&t>0;function e_(t,e,n){const i=t?.allowed;if(i&&"object"==typeof i)for(const t of["width","depth","height"])Zv(i[t])||n.push(Kv("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(Kv("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||t_(t.stackLimit)||t.stackLimit===1/0||n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||Jv(t.rotation)||n.push(Kv("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(Kv("ARRAY_REQUIRED",`${e}.accepts`))}function n_(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[Kv("TIERS_REQUIRED","tiers")];const i=e.anchors?new Set(e.anchors):null,s=new Set;return t.tiers.forEach((t,e)=>{const r=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(Kv("OBJECT_REQUIRED",r));if(t_(t.tierNo)?s.has(t.tierNo)?n.push(Kv("TIER_NUMBER_DUPLICATE",`${r}.tierNo`,{tierNo:t.tierNo})):s.add(t.tierNo):n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${r}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?i&&!i.has(t.anchorId)&&n.push(Kv("ANCHOR_UNKNOWN",`${r}.anchorId`,{anchorId:t.anchorId})):n.push(Kv("ANCHOR_REQUIRED",`${r}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(Kv("MOUNT_INVALID",`${r}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])Jv(t.position[e])||n.push(Kv("FINITE_NUMBER_REQUIRED",`${r}.position.${e}`));else n.push(Kv("OBJECT_REQUIRED",`${r}.position`));Jv(t.rotation)||n.push(Kv("FINITE_NUMBER_REQUIRED",`${r}.rotation`));const o=t.layout;switch(o?.pattern){case"SINGLE":e_(o.slot,`${r}.layout.slot`,n);break;case"ROW":t_(o.count)||n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.count`)),Zv(o.pitch)||n.push(Kv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch`)),"X"!==o.axis&&"Z"!==o.axis&&n.push(Kv("AXIS_INVALID",`${r}.layout.axis`)),e_(o.slot,`${r}.layout.slot`,n);break;case"GRID":t_(o.rows)||n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.rows`)),t_(o.cols)||n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${r}.layout.cols`)),Zv(o.pitch?.x)||n.push(Kv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.x`)),Zv(o.pitch?.z)||n.push(Kv("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.z`)),e_(o.slot,`${r}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(o.slots)){n.push(Kv("ARRAY_REQUIRED",`${r}.layout.slots`));break}o.slots.length||n.push(Kv("SLOTS_REQUIRED",`${r}.layout.slots`));const t=new Set;o.slots.forEach((e,i)=>{const s=`${r}.layout.slots[${i}]`;t_(e?.slotNo)?t.has(e.slotNo)?n.push(Kv("SLOT_NUMBER_DUPLICATE",`${s}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(Kv("POSITIVE_INTEGER_REQUIRED",`${s}.slotNo`)),Jv(e?.offset?.x)&&Jv(e?.offset?.z)||n.push(Kv("FINITE_NUMBER_REQUIRED",`${s}.offset`)),e_(e,s,n)});break}default:n.push(Kv("PATTERN_INVALID",`${r}.layout.pattern`))}}),n}function i_(t,e=""){const n=[],i=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>i(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,s]of Object.entries(t))i(s,e?`${e}.${n}`:n)}else n.push(Kv("NOT_PERSISTABLE",e,{value:String(t)}))};return i(t,e),n}function s_(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 r_(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:s_(t)},(t,e)=>e+1)}function o_(t,e,n,i,s="ROW_MAJOR"){switch(s){case"ROW_MAJOR":return(n-1)*e+i;case"COL_MAJOR":return(i-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?i:e-i+1);case"SERPENTINE_COL":return(i-1)*t+(i%2==1?n:t-n+1)}}function a_(t,e,n,i="ROW_MAJOR"){const s=n-1;switch(i){case"ROW_MAJOR":return{r:Math.floor(s/e)+1,c:s%e+1};case"COL_MAJOR":return{r:s%t+1,c:Math.floor(s/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(s/e)+1,n=s%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(s/t)+1,n=s%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const c_=(t,e)=>e&&0!==t?-t:t;function l_(t,e,n={}){const i=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!i||!t_(e.slot))return null;const s=i.layout;let r,o,a;switch(s.pattern){case"SINGLE":if(1!==e.slot)return null;r=s.slot,o={x:0,z:0};break;case"ROW":{if(e.slot>s.count)return null;const t=c_((e.slot-1-(s.count-1)/2)*s.pitch,"MAX"===s.origin);r=s.slot,o="X"===s.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>s.rows*s.cols)return null;const{r:t,c:n}=a_(s.rows,s.cols,e.slot,s.order),i=s.origin??{x:"MIN",z:"MIN"};r=s.slot,o={x:c_((n-1-(s.cols-1)/2)*s.pitch.x,"MAX"===i.x),z:c_((t-1-(s.rows-1)/2)*s.pitch.z,"MAX"===i.z)};break}case"CUSTOM":{const t=s.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:i.tierNo,slotNo:e.slot,name:a,anchorId:i.anchorId,mount:i.mount,tierPosition:{...i.position},tierRotation:i.rotation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function h_(t){return`t${t.tier}_s${t.slot}`}function d_(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*u_(t){for(const e of t?.tiers??[])for(const t of r_(e.layout))yield{tier:e.tierNo,slot:t}}function p_(t,e,n){if(!n)return{x:t,z:e};const i=n*Math.PI/180,s=Math.cos(i),r=Math.sin(i),o=t=>Math.round(1e9*t)/1e9;return{x:o(t*s+e*r),z:o(-t*r+e*s)}}function f_(t){const e=p_(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 m_=.05,g_=t=>!!t&&Zv(t.width)&&Zv(t.depth)&&Zv(t.height);function y_(t,e){const n=e*Math.PI/180,i=Math.abs(Math.cos(n)),s=Math.abs(Math.sin(n)),r=t=>Math.round(1e9*t)/1e9;return{width:r(t.width*i+t.depth*s),depth:r(t.width*s+t.depth*i)}}function b_(t,e,n=0,i=.05){if(!g_(t))return null;if(!Jv(n)||!Jv(i)||i<0||i>=1)return null;const s=y_(t,e.rotation),r=Math.min(1,Math.min(e.allowed.width/s.width,e.allowed.depth/s.depth)*(1-i)),o=t.height*r;return{position:{x:0,y:("HANG"===e.mount?-1:1)*(n+o/2),z:0},rotation:0,scale:r}}function v_(t,e,n=0,i=.05){const s=b_(t,e,n,i);if(!s)return null;const r=f_(e);return{position:{x:r.position.x,y:r.position.y+s.position.y,z:r.position.z},rotation:r.rotation,scale:s.scale}}function __(t,e,n=.05){let i=0;return t.map(t=>{const s=t?v_(t,e,i,n):null;return s&&(i+=t.height*s.scale),s})}const x_=1e-6;function w_(t,e){const n=f_(t),i=t.allowed.width/2,s=t.allowed.depth/2,r=[[-i,-s],[i,-s],[i,s],[-i,s]].map(([t,e])=>{const i=p_(t,e,n.rotation);return{x:n.position.x+i.x,z:n.position.z+i.z}}),o=p_(1,0,n.rotation),a=p_(0,1,n.rotation),c="HANG"===t.mount?-1:1,l=[n.position.y,n.position.y+c*t.allowed.height],h=r.map(t=>t.x);return{tierIndex:e,tier:t.tier,slot:t.slotNo,corners:r,axes:[o,a],y0:Math.min(...l),y1:Math.max(...l),minX:Math.min(...h),maxX:Math.max(...h)}}function M_(t,e){for(const n of[...t.axes,...e.axes]){const i=t.corners.map(t=>t.x*n.x+t.z*n.z),s=e.corners.map(t=>t.x*n.x+t.z*n.z);if(Math.min(Math.max(...i),Math.max(...s))-Math.max(Math.min(...i),Math.min(...s))<=x_)return!1}return!0}function S_(t,e={}){const n=[],i=new Map;t.tiers.forEach((e,n)=>{const s=i.get(e.anchorId)??[];i.set(e.anchorId,s);for(const i of r_(e.layout))s.push(w_(l_(t,{tier:e.tierNo,slot:i}),n))});for(const[t,s]of i){const i=e.anchorFaces?.[t];if(i)for(const t of s)t.corners.some(t=>Math.abs(t.x)-i.width/2>x_||Math.abs(t.z)-i.depth/2>x_)&&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 r=[...s].sort((t,e)=>t.minX-e.minX);for(let t=0;t<r.length;t++){const e=r[t];for(let i=t+1;i<r.length&&r[i].minX<e.maxX-x_;i++){const t=r[i];if(Math.min(e.y1,t.y1)-Math.max(e.y0,t.y0)<=x_)continue;if(!M_(e,t))continue;const[s,o]=e.tierIndex<t.tierIndex||e.tierIndex===t.tierIndex&&e.slot<t.slot?[e,t]:[t,e];n.push({code:"SLOT_OVERLAP",path:`tiers[${o.tierIndex}]`,params:{tier:o.tier,slot:o.slot,otherTier:s.tier,otherSlot:s.slot}})}}}return n}function A_(t,e,n=[],i={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const s=i.normalizeType??(t=>null==t?"":String(t)),r=[];let o=!1;if(t.accepts){const n=s(e.type);n?t.accepts.map(s).includes(n)||r.push("TYPE_NOT_ACCEPTED"):o=!0}if(n.length+1>t.stackLimit&&r.push("STACK_LIMIT_EXCEEDED"),g_(e.dims)){const i=y_(e.dims,t.rotation);if(i.width>t.allowed.width&&r.push("WIDTH_EXCEEDED"),i.depth>t.allowed.depth&&r.push("DEPTH_EXCEEDED"),n.every(t=>g_(t.dims))){n.reduce((t,e)=>t+e.dims.height,e.dims.height)>t.allowed.height&&r.push("HEIGHT_EXCEEDED")}else o=!0}else o=!0;return r.length?{verdict:"NG",reasons:o?[...r,"SPEC_UNKNOWN"]:r}:o?{verdict:"UNKNOWN",reasons:["SPEC_UNKNOWN"]}:{verdict:"OK",reasons:[]}}function E_(t){if(!t?.layout||!Array.isArray(t.anchors))return[];const e=new Map(t.anchors.map(t=>[t.id,t])),n=[];for(const i of u_(t.layout)){const s=l_(t.layout,i),r=s&&e.get(s.anchorId);if(!s||!r)continue;const o=h_(i);n.push({id:o,label:`${t.label} ${o}`,role:t.role,frame:r.frame,pose:{...r.pose},anchorId:r.id,accepts:[...s.accepts??[]],capacity:s.stackLimit,tier:s.tier,slot:s.slotNo,...s.name?{name:s.name}:{},tierPosition:{...s.tierPosition},tierRotation:s.tierRotation,offset:{...s.offset},rotation:s.rotation,mount:s.mount,allowed:{...s.allowed}})}return n}const k_=["floor","ceiling","center","wall"];function C_(t){return String(t??"").trim().toUpperCase()}const T_=t=>"number"==typeof t&&Number.isFinite(t)&&t>0;function O_(t,e="carrier"){const n=function(t,e="carrier"){if(!t||"object"!=typeof t||Array.isArray(t))return{code:"ASSET_SCHEMA",path:e,message:"object required"};const n=t;for(const t of Object.keys(n))if("type"!==t&&"dimensions"!==t)return{code:"ASSET_SCHEMA",path:e,message:`unknown ${t}`};const i=n.type;if("string"!=typeof i||!C_(i))return{code:"CARRIER_TYPE",path:`${e}.type`,message:"a CARRIERTYPE code is required"};if(i!==C_(i))return{code:"CARRIER_TYPE",path:`${e}.type`,message:`${i} is not written as compared; ${C_(i)}`};if(i.length>64)return{code:"CARRIER_TYPE",path:`${e}.type`,message:"at most 64 characters"};const s=n.dimensions;if(!s||"object"!=typeof s||Array.isArray(s))return{code:"ASSET_SCHEMA",path:`${e}.dimensions`,message:"object required"};for(const t of Object.keys(s))if("width"!==t&&"length"!==t&&"height"!==t)return{code:"ASSET_SCHEMA",path:`${e}.dimensions`,message:`unknown ${t}`};for(const t of["width","length","height"]){const n=s[t];if(!T_(n))return{code:"CARRIER_DIMENSIONS",path:`${e}.dimensions.${t}`,message:"a finite positive length in mm is required"}}return null}(t,e);if(n)throw new pb(n.code,n.path,n.message)}const P_=(t,e,n)=>{throw new pb(t,e,n)},I_={left:"x",right:"x",bottom:"y",top:"y",back:"z",front:"z"},D_=["fixed","revolute","prismatic"],z_={left:-1,right:1,bottom:-1,top:1,back:-1,front:1};function R_(t){const e=t.mimic;return e&&"object"==typeof e?Object.hasOwn(e,"sum")?Array.isArray(e.sum)?e.sum:[]:[{joint:e.joint,multiplier:e.multiplier}]:[]}function j_(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 L_={joint:((...t)=>t)("id","type","body0","body1","origin","axis","lowerLimit","upperLimit","travel","state","mimic","repeat"),body0:((...t)=>t)("part","face","plane"),body1:((...t)=>t)("part","face"),origin:((...t)=>t)("facing","gap","align","turn","twist"),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)("joint","multiplier","offset","sum"),leader:((...t)=>t)("joint","multiplier"),repeat:((...t)=>t)("axis","pitch","count","rise"),rise:((...t)=>t)("axis","mm")};const F_=(t,e)=>t.nodes.find(t=>t.id===e),N_=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function $_(t,e,n){const i=F_(t,e),s="member@1"===i?.op&&(!!F_(t,`${e}.repeat`)||void 0!==function(t,e){const n=F_(t,e);if("member@1"!==n?.op||F_(t,`${e}.repeat`))return;const i=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return i?String(i.id).replace(/\.assembly$/,""):void 0}(t,e));i&&("place@1"===i.op||s)||P_("TARGET_ABSENT",n,`${e} is not a placed part`);const r=N_(t,i.args[0]);r||P_("TARGET_ABSENT",n,`${e} has no shape`);const o=F_(t,`${e}.pose`);return o&&"rigid@1"===o.op||P_("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:i,shape:r,pose:o}}function H_(t,e,n,i){return $_(t,n,i).pose.args.slice(3,6).map(n=>function(t,e,n){const i=t.constants.find(t=>t.id===n);if(i)return i.value;const s=t.inputs.find(t=>t.id===n);return s&&"state"!==s.role?e.designInputs[n]??null:null}(t,e,n))}const B_=t=>rb.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", ");function Y_(t,e,n,i,s){const r=H_(t,e,n,i);if(r.every(t=>0===t))return[[1,0,0],[0,1,0],[0,0,1]];r.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&P_("EDIT_TARGET",i,`${n} is turned (${B_(r)}); only quarter turns keep its faces level with the axes`);const o=G_(r);{const s=$_(t,n,i).pose,o=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...r.map(e=>ex(t,"deg",e,"a"))];for(const i of o)ux(e,i,cx(t,n,i)?i:void 0)}return o}function G_(t){const[e,n,i]=t.map(t=>t*Math.PI/180),s=t=>Math.round(Math.cos(t)),r=t=>Math.round(Math.sin(t)),o=[[1,0,0],[0,s(e),-r(e)],[0,r(e),s(e)]],a=[[s(n),0,r(n)],[0,1,0],[-r(n),0,s(n)]],c=[[s(i),-r(i),0],[r(i),s(i),0],[0,0,1]];return V_(V_(o,a),c)}const V_=(t,e)=>t.map(t=>e[0].map((n,i)=>t.reduce((t,n,s)=>t+n*e[s][i],0))),U_=t=>t.map(t=>({ref:t.ref,k:-t.k})),W_=t=>t.map(t=>({ref:t.ref,k:t.k/2})),q_={x:["left","right"],y:["bottom","top"],z:["back","front"]};function X_(t,e,n){const{shape:i}=$_(t,e,n),s=function(t,e){const n=Bb(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}(i,t);return s||P_("EDIT_TARGET",n,`${e} is a ${i.op}; it has no flat face to fasten by`),{shape:i,faces:s}}function K_(t,e){if("centre"!==e.body1.face)return e.body1.face;const n=`joints.${e.id}.body1.face`;"part"in e.body0||P_("JOINT_SCHEMA",n,"a part stands on the mounting plane by a face of its own, not by its centre");const i=e.body0.face;if(Object.hasOwn(I_,i))return Object.keys(I_).find(t=>I_[t]===I_[i]&&z_[t]===-z_[i]);const s=X_(t,e.body0.part,n).faces[e.body0.face];return s||P_("JOINT_SCHEMA",n,`${e.body0.part} has no face ${e.body0.face}`),Object.keys(I_).find(t=>I_[t]===s.axis&&z_[t]===-s.normal)}const Q_=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function J_(t,e,n){const{shape:i,faces:s}=X_(t,e,n),r={},o=Bb(i,t).measure;for(const t of rb){const[e,n]=q_[t].map(t=>s[t]),a=o[t],c=a&&"profile"!==a?Q_(i,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?Q_(i,e):[...Q_(i,n),...U_(c)],h=n?Q_(i,n):[...Q_(i,e),...c];r[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(U_(h))}}return r}function Z_(t,e,n,i){const s=J_(t,n,i),r=Y_(t,e,n,i),o={};return rb.forEach((t,e)=>{const n=r[e].findIndex(t=>0!==t),i=s[rb[n]];i&&(o[t]=r[e][n]>0?i:{lo:U_(i.hi),hi:U_(i.lo),centred:i.centred})}),o}function tx(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 i=`${e}.${t}`;for(let s=2;n.has(i)||n.has(`${i}.value`);s++)i=`${e}.${t}.${s}`;return n.add(i),n.add(`${i}.value`),i}}function ex(t,e,n,i){const s=t.constants.find(t=>t.unit===e&&t.value===n);if(s)return s.id;const r=`${i}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:r,unit:e,value:n}),r}function nx(t,e,n,i,s,r){let o=n;if(1!==i){const n=e(`${r}.times`);t.nodes.push({id:n,op:"mul@1",args:[o,ex(t,"ratio",i,"k")],outputs:{value:`${n}.value`}}),o=`${n}.value`}if(0!==s){const n=e(`${r}.plus`);t.nodes.push({id:n,op:"add@1",args:[o,ex(t,"mm",s,"d")],outputs:{value:`${n}.value`}}),o=`${n}.value`}return o}function ix(t,e,n,i,s,r){if(void 0===i)return ex(t,"mm",0,"d");if("number"==typeof i)return Number.isFinite(i)||P_("SCHEMA",r,"a finite length is required"),ex(t,"mm",i,"d");i&&"object"==typeof i&&(Object.hasOwn(i,"sum")||i.from)||P_("SCHEMA",r,"a length is a number of millimetres, or something to follow");const{terms:o,plus:a,sum:c}=j_(i),l=sx(t,e,o,a,r);return c?nx(t,n,rx(t,n,l,`${s}.sum`),1,a,s):nx(t,n,l[0].ref,l[0].k,a,s)}function sx(t,e,n,i,s){return Array.isArray(n)&&n.length||P_("SCHEMA",s,"a sum has one term or more"),Number.isFinite(i)||P_("SCHEMA",s,"finite times and plus required"),n.map((i,r)=>{const o=n.length>1?`${s}.sum.${r}`:s;return i&&"object"==typeof i&&i.from||P_("SCHEMA",o,"a length is a number of millimetres, or something to follow"),Number.isFinite(i.times??1)||P_("SCHEMA",o,"finite times and plus required"),{ref:ox(t,e,i.from,o),k:i.times??1}})}function rx(t,e,n,i){const s=n.filter(t=>0!==t.k);if(!s.length)return ex(t,"mm",0,"d");let r="";for(const[n,o]of s.entries()){const s=nx(t,e,o.ref,o.k,0,`${i}.${n}`);if(r){const o=e(`${i}.${n}.sum`);t.nodes.push({id:o,op:"add@1",args:[r,s],outputs:{value:`${o}.value`}}),r=`${o}.value`}else r=s}return r}function ox(t,e,n,i){if(n&&"object"==typeof n||P_("SCHEMA",i,"a dimension source is required"),"instance"===n.of){const s=`size.${n.axis}`;return t.inputs.some(t=>t.id===s)||P_("TARGET_ABSENT",i,`the instance has no ${s}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const i=F_(t,`sizing.size.${e}`);return i||P_("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),i.outputs.value}(t,n.axis,i):s}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||P_("TARGET_ABSENT",i,`${n.input} is not an input of this asset`),"state"===e.role&&P_("EDIT_TARGET",i,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?ax(t,n.part,n.axis,i):P_("SCHEMA",i,`${String(n.of)} is not a dimension source`)}function ax(t,e,n,i){const s=$_(t,e,i).shape,r=Bb(s);if(r){const o=r.edit[n];if("refused"in o)return P_("EDIT_TARGET",i,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(o.sameAs)return ax(t,e,o.sameAs,i);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(F_(t,a))return c;const l=s.args[o.arg],h=ex(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),s.args=s.args.map(t=>t===l?c:t);const d=F_(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return P_("EDIT_TARGET",i,`${e} is a ${s.op}; it is not a shape with measures`)}const cx=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role),lx=t=>new Set([...Bx(t.occupancy),...Bx(t.document.capabilities),...Bx(t.joints)]);let hx;const dx=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function ux(t,e,n){const i=t.document.model,s=hx&&hx.asset===t?hx.declared:void 0,r=s??lx(t);if(s&&dx){const n=lx(t);if(n.size!==s.size||[...n].some(t=>!s.has(t)))throw new Error(`the names held for the joint rewrite went stale at ${e}`)}const o=t=>i.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||r.has(t);if(o(e))return;const a=i.inputs.findIndex(t=>t.id===e);if(a>=0){if(e!==n)return;return i.inputs.splice(a,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const c=N_(i,e);if(c&&"place@1"!==c.op&&!Object.values(c.outputs).some(t=>t!==e&&o(t))){i.nodes=i.nodes.filter(t=>t!==c);for(const e of c.args)ux(t,e)}}function px(t,e){if(!F_(t,`${e}.chain`)&&!F_(t,`${e}.repeat`))return null;const n=F_(t,`${e}.seat.rigid`)??F_(t,`${e}.motion`),i=/^(.*)\.local$/.exec(String(n?.params?.to));return i&&i[1]!==e?i[1]:null}function fx(t,e,n){const i=t.document.model,s=e.to,r=`${e.part} to ${s?.plane??s?.part}`;if(s&&"object"==typeof s||P_("SCHEMA",r,"a target face, or the plane the figure is mounted on, is required"),void 0!==s.plane)return function(t,e,n){const i=t.document.model,s=e.to;"mounting-plane"!==s.plane&&P_("SCHEMA",n,`${String(s.plane)} is not a plane a part can stand on`);void 0!==e.facing&&"meet"!==e.facing&&P_("SCHEMA",n,"a part standing on the plane meets it; flush says nothing here");const r=function(t){return t.placement??"floor"}(t),o=function(t){return"wall"===t?["back"]:["bottom","top"]}(r),a="wall"===r?"z":"y";o.includes(e.face)||P_("ATTACH_FACE",n,"wall"===r?`${String(e.face)} faces along ${I_[e.face]??"no axis"}; the figure hangs on a wall, the plane Z = 0, so a part is fastened to it by its back`:`${String(e.face)} faces along ${I_[e.face]??"no axis"}; the plane faces along y, so a part stands on it by its bottom or hangs from it by its top`);px(i,e.part)&&!e.replace&&P_("ATTACH_REPLACED",n,`${e.part} is already fastened to ${px(i,e.part)}; pass replace to stand it on the plane instead`);const c=Z_(i,t,e.part,n);c[a]&&Object.hasOwn(X_(i,e.part,n).faces,e.face)||P_("EDIT_TARGET",n,`${e.part} has no flat ${e.face} face`);const l=tx(i,`${e.part}.on.plane`),h="top"===e.face?-1:1,d=ix(i,t,l,e.gap,`gap.${a}`,n),u={x:"",y:"",z:""};u[a]=rx(i,l,[...U_(h>0?c[a].lo:c[a].hi),{ref:d,k:h}],`stand.${a}`);const p=ex(i,"mm",0,"d"),f={x:p,y:p,z:p};f[a]=u[a];for(const s of rb.filter(t=>t!==a)){const r=e.align?.[s]??"centre",o=c[s];if("centre"===r)u[s]=ex(i,"mm",0,"d");else if("object"==typeof r&&r&&Object.hasOwn(r,"mm"))u[s]=ix(i,t,l,r.mm,`align.${s}`,n);else{if(("min"===r||"max"===r)&&yx(i,s)){o||P_("ATTACH_FACE",n,`${e.part} has no edges along ${s} to line up with the figure's side`);const a="min"===r?-1:1;u[s]=rx(i,l,[{ref:ox(i,t,{of:"instance",axis:s},n),k:.5*a}],`figure-edge.${s}`),f[s]=rx(i,l,U_("min"===r?o.lo:o.hi),`own-edge.${s}`);continue}P_("SCHEMA",n,`the plane has no edges to line ${e.part} up with on ${s}; declare the figure's size, or give the centre or a measured offset`)}o&&!o.centred&&(f[s]=rx(i,l,U_([...W_(o.lo),...W_(o.hi)]),`own-centre.${s}`))}const m=rb.map(t=>t===a?p:u[t]);return gx(t,e.part,t.document.capabilities.assetFrame,{seat:[m[0],m[1],m[2]],pose:[f.x,f.y,f.z]}),t}(t,e,r);e.part===s.part&&P_("ATTACH_CYCLE",r,"a part cannot be fastened to itself");const o="centre"===e.face;o||Object.hasOwn(I_,String(e.face))||P_("SCHEMA",r,`${String(e.face)} is not a face`);const a=X_(i,s.part,r),c=Object.hasOwn(a.faces,String(s.face))?a.faces[s.face]:void 0;c||P_("SCHEMA",r,`${s.part} has no face ${String(s.face)}; it has ${Object.keys(a.faces).join(", ")}`);const l=e.facing??"meet";"meet"!==l&&"flush"!==l&&P_("SCHEMA",r,`${String(l)} is neither meet nor flush`);const h=c.axis,d=c.normal;o&&"meet"!==l&&P_("ATTACH_FACE",r,`${e.part} fastened by its centre sits on ${s.face}; flush has no meaning for a centre`),o&&(e={...e,face:Object.keys(I_).find(t=>I_[t]===h&&z_[t]===-d)}),I_[e.face]!==h&&P_("ATTACH_FACE",r,`${e.face} faces along ${I_[e.face]} and ${s.face} along ${h}; fastening them would need a turn, which this command does not do`);const u=Object.keys(I_).find(t=>I_[t]===h&&z_[t]===("meet"===l?-d:d));"meet"===l&&e.face!==u&&P_("ATTACH_FACE",r,`to meet ${s.face}, ${e.part} offers its ${u}; pass flush to lay ${e.face} in the same plane instead`),"flush"===l&&e.face!==u&&P_("ATTACH_FACE",r,`to lie flush with ${s.face}, ${e.part} offers its ${u}`),px(i,e.part)&&!e.replace&&P_("ATTACH_REPLACED",r,`${e.part} is already fastened to ${px(i,e.part)}; pass replace to move it, or detach it first`);for(let t=s.part;t;t=px(i,t))t===e.part&&P_("ATTACH_CYCLE",r,`${s.part} already hangs from ${e.part}`);const p=J_(i,s.part,r),f=Z_(i,t,e.part,r),m=f[h];m&&Object.hasOwn(X_(i,e.part,r).faces,e.face)||o||P_("EDIT_TARGET",r,`${e.part} has no flat ${e.face} face`);const g=tx(i,`${e.part}.on.${s.part}`),y="meet"===l?d:-d,b=ix(i,t,g,e.gap,`gap.${h}`,r),v=ex(i,"mm",0,"d"),_={x:"",y:"",z:""},x={x:v,y:v,z:v};_[h]=rx(i,g,[...Q_(a.shape,c),...o?[{ref:b,k:y}]:[]],`seat.${h}`);const w=o?m&&!m.centred?[...W_(m.lo),...W_(m.hi)]:[]:z_[e.face]>0?m.hi:m.lo;x[h]=o?w.length?rx(i,g,U_(w),`along.${h}`):v:rx(i,g,[...U_(w),{ref:b,k:y}],`along.${h}`);for(const n of rb.filter(t=>t!==h)){const o=e.align?.[n]??"centre",a=p[n],c=f[n],l=t=>t&&!t.centred?[...W_(t.lo),...W_(t.hi)]:[],h=(t,e)=>l(t).length?rx(i,g,l(t),e):ex(i,"mm",0,"d"),d=()=>l(c).length?rx(i,g,U_(l(c)),`own-centre.${n}`):v;if("centre"===o)_[n]=h(a,`centre.${n}`),x[n]=d();else if("object"==typeof o&&o&&Object.hasOwn(o,"mm")){const e=ix(i,t,g,o.mm,`align.${n}`,r);_[n]=l(a).length?rx(i,g,[...l(a),{ref:e,k:1}],`align.${n}.from-centre`):e,x[n]=d()}else"min"===o||"max"===o?(a||P_("ATTACH_FACE",r,`${s.part} has no edges along ${n} to line ${e.part} up with; give the centre or a measured offset`),c||P_("ATTACH_FACE",r,`${e.part} has no edges along ${n} to line up; give the centre or a measured offset`),_[n]=rx(i,g,"min"===o?a.lo:a.hi,`edge.${n}`),x[n]=rx(i,g,U_("min"===o?c.lo:c.hi),`own-edge.${n}`)):P_("SCHEMA",r,`${String(o)} is not an alignment`)}if(n&&n.deg){const[o,a]=Ox[h];for(const t of[o,a]){const i=e.align?.[t]??"centre";"min"!==i&&"max"!==i||P_("ATTACH_FACE",r,`${e.part} is twisted ${mx(n.deg)}° about ${h}; its sides are not level with ${s.part}'s edges -- place it by the centre or a distance`)}const c=n=>{const s=e.align?.[n]??"centre",o=f[n],a=o&&!o.centred?U_([...W_(o.lo),...W_(o.hi)]):[];return"object"==typeof s&&s&&Object.hasOwn(s,"mm")?[{ref:ix(i,t,g,s.mm,`twist.${n}`,r),k:1},...a]:a},[l,d]=[c(o),c(a)],u=t=>{const e=Math.round(1e12*t)/1e12;return 0===e?0:e},m=String(mx(n.deg)).replace("-","m").replace(".","_"),y=t=>{const e=`twist.${t}.${m}`,s=n.deg*Math.PI/180;return i.constants.some(t=>t.id===e)||i.constants.push({id:e,unit:"ratio",value:u("cos"===t?Math.cos(s):"sin"===t?Math.sin(s):-Math.sin(s))}),e},b=(t,e,n)=>{const s=g(n);return i.nodes.push({id:s,op:"mul@1",args:[t,e],outputs:{value:`${s}.value`}}),`${s}.value`},v=(t,e,n)=>{const s=g(n);return i.nodes.push({id:s,op:"add@1",args:[t,e],outputs:{value:`${s}.value`}}),`${s}.value`};for(const t of[o,a]){const e=p[t];_[t]=e&&!e.centred?rx(i,g,[...W_(e.lo),...W_(e.hi)],`twist-centre.${t}`):ex(i,"mm",0,"d")}const w=rx(i,g,l,`twist-own.${o}`),M=rx(i,g,d,`twist-own.${a}`);x[o]=v(b(w,y("cos"),`twisted.${o}.cos`),b(M,y("nsin"),`twisted.${o}.sin`),`twisted.${o}`),x[a]=v(b(w,y("sin"),`twisted.${a}.sin`),b(M,y("cos"),`twisted.${a}.cos`),`twisted.${a}`)}return gx(t,e.part,`${s.part}.local`,{seat:[_.x,_.y,_.z],pose:[x.x,x.y,x.z]}),t}const mx=t=>Math.round(1e6*t)/1e6;function gx(t,e,n,i){const s=t.document.model,{place:r,pose:o}=$_(s,e,e),a=i?o.args.slice(0,3):[];i&&(o.args=[...i.pose,...o.args.slice(3)]),o.params={...o.params,to:`${e}.seat`};const c=F_(s,`${e}.motion`),l=ex(s,"mm",0,"d"),h=ex(s,"deg",0,"a");let d=F_(s,`${e}.seat.rigid`);d||(d={id:`${e}.seat.rigid`,op:"rigid@1",args:[l,l,l,h,h,h],outputs:{pose:`${e}.seat.value`},params:{}},s.nodes.push(d));const u=i?d.args.slice(0,3):[];i&&(d.args=[...i.seat,...d.args.slice(3)]),d.params={from:c?`${e}.joint`:`${e}.seat`,to:n};let p=F_(s,`${e}.turned`);c?(c.params={...c.params,from:`${e}.seat`,to:`${e}.joint`},p?p.args=[c.outputs.pose,o.outputs.pose]:(p={id:`${e}.turned`,op:"compose@1",args:[c.outputs.pose,o.outputs.pose],outputs:{pose:`${e}.turned.value`}},s.nodes.push(p))):p&&(s.nodes=s.nodes.filter(t=>t!==p));let f=F_(s,`${e}.chain`);f||(f={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},s.nodes.push(f)),f.args=[d.outputs.pose,c?p.outputs.pose:o.outputs.pose];const m=/^(.*)\.local$/.exec(n);let g=F_(s,`${e}.world`);if(m&&m[1]!==e){const t=F_(s,`${m[1]}.world`)?.outputs?.pose??F_(s,`${m[1]}.chain`)?.outputs?.pose??F_(s,`${m[1]}.turned`)?.outputs?.pose??F_(s,`${m[1]}.pose`).outputs.pose;g?g.args=[t,f.outputs.pose]:(g={id:`${e}.world`,op:"compose@1",args:[t,f.outputs.pose],outputs:{pose:`${e}.world.value`}},s.nodes.push(g)),r.args=[r.args[0],g.outputs.pose]}else g&&(s.nodes=s.nodes.filter(t=>t!==g)),r.args=[r.args[0],f.outputs.pose];for(const n of[...a,...u])ux(t,n,cx(s,e,n)?n:void 0)}const yx=(t,e)=>t.inputs.find(t=>t.id===Xv[e]),bx=t=>t.state?.id??t.id;function vx(t,e){const n=t.document.model,i=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||P_("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[i,s]of Object.entries(t))void 0===s||e.includes(i)||P_("JOINT_SCHEMA",n,`${i} is a field this kernel does not know`)},i=(t,e)=>n(t,L_.source,e),s=(t,e)=>{if(t&&"object"==typeof t&&(n(t,L_.measure,e),i(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[s,r]of t.sum.entries())n(r,L_.term,`${e}.sum.${s}`),i(r?.from,`${e}.sum.${s}.from`)};n(t,L_.joint,e),n(t.body0,L_.body0,`${e}.body0`),n(t.body1,L_.body1,`${e}.body1`);const r=t.origin;if(n(r,L_.origin,`${e}.origin`),r&&"object"==typeof r){s(r.gap,`${e}.origin.gap`),n(r.turn,L_.axes,`${e}.origin.turn`),n(r.align,L_.axes,`${e}.origin.align`);for(const[t,i]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(i,L_.alignment,`${e}.origin.align.${t}`),s(i?.mm,`${e}.origin.align.${t}.mm`)}if(t.travel&&"object"==typeof t.travel&&(n(t.travel,L_.travel,`${e}.travel`),i(t.travel.source,`${e}.travel.source`),Array.isArray(t.travel.sum)&&s({sum:t.travel.sum},`${e}.travel`)),n(t.state,L_.state,`${e}.state`),n(t.mimic,L_.mimic,`${e}.mimic`),Array.isArray(t.mimic?.sum))for(const[i,s]of t.mimic.sum.entries())n(s,L_.leader,`${e}.mimic.sum.${i}`);n(t.repeat,L_.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(s(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,L_.rise,`${e}.repeat.rise`))}(e,i),D_.includes(e.type)||P_("JOINT_SCHEMA",i,`${String(e.type)} is not a joint type; ${D_.join(", ")}`),e.body1&&"string"==typeof e.body1.part||P_("JOINT_SCHEMA",i,"a joint carries a part (body1)"),$_(n,e.body1.part,i),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||P_("JOINT_SCHEMA",i,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&$_(n,e.body0.part,i);const s=(t.joints??[]).filter(t=>t.id!==e.id),r=s.find(t=>t.body1.part===e.body1.part);if(r&&P_("JOINT_TREE",i,`${e.body1.part} already hangs from ${"part"in r.body0?r.body0.part:"the mounting plane"} by ${r.id}; a part has one joint above it`),"part"in e.body0){const t=t=>s.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&P_("ATTACH_CYCLE",i,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const s=t(n);n=s&&"part"in s?s.part:void 0}}const o="fixed"!==e.type,a=void 0!==e.lowerLimit||void 0!==e.upperLimit;if(o&&!["X","Y","Z"].includes(e.axis)&&P_("JOINT_SCHEMA",i,`a ${e.type} joint has an axis, X, Y or Z`),o||void 0===e.axis&&!a&&void 0===e.mimic&&void 0===e.travel||P_("JOINT_SCHEMA",i,"a fixed joint has no axis, limits, mimic or travel"),void 0!==e.travel&&"prismatic"!==e.type&&P_("JOINT_SCHEMA",i,"only a prismatic joint travels a length"),"prismatic"===e.type&&e.travel&&!a&&(e.lowerLimit=0,e.upperLimit=1),o&&!e.mimic&&(a||"prismatic"===e.type)){const[t,n]=[e.lowerLimit,e.upperLimit];Number.isFinite(t)&&Number.isFinite(n)&&t<n||P_("JOINT_SCHEMA",i,`a ${e.type} joint has both limits, lower below upper`)}if(e.mimic){!Object.hasOwn(e.mimic,"sum")||Array.isArray(e.mimic.sum)&&e.mimic.sum.length||P_("JOINT_SCHEMA",i,"a mimic sum follows one joint or more");const t=new Set;for(const n of R_(e)){const r=s.find(t=>t.id===n?.joint);r&&"fixed"!==r.type||P_("JOINT_SCHEMA",i,`${String(n?.joint)} is not a moving joint to follow`),t.has(r.id)&&P_("JOINT_SCHEMA",i,`${r.id} is followed twice; a sum names each joint once`),t.add(r.id),r.mimic&&P_("JOINT_SCHEMA",i,`${r.id} follows another joint; follow the one it follows`),"prismatic"===r.type!=("prismatic"===e.type)&&P_("JOINT_SCHEMA",i,`${r.id} ${"prismatic"===r.type?"slides":"turns"}; a joint follows ones that move the same way: a slide a slide, a turn a turn`),Number.isFinite(n.multiplier)||P_("JOINT_SCHEMA",i,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||P_("JOINT_SCHEMA",i,"a mimic's offset is a number in the joint's unit")}void 0===e.origin?.twist||Number.isFinite(e.origin.twist)||P_("JOINT_SCHEMA",`${i}.origin.twist`,"a twist is a number of degrees"),e.origin?.turn&&Object.values(e.origin.turn).some(t=>!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&P_("JOINT_SCHEMA",`${i}.origin.turn`,"a turn is in quarter turns; an angle about the face's normal is its twist");const c=[...s,e],l=t=>c.find(e=>e.body1.part===t&&"part"in e.body0),h=t=>{for(let e=l(t);e;e=l(e.body0.part))if(e.repeat)return e};if(e.repeat){const t=e=>c.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?h(e.body0.part):void 0);t;t="part"in t.body0?h(t.body0.part):void 0)n.push(t);const s=t(e.body1.part).map(t=>c.find(e=>e.body1.part===t)).filter(t=>t.repeat),r=[...n,...s].find(t=>t.repeat.axis===e.repeat.axis);r&&P_("JOINT_SCHEMA",`${i}.repeat`,`${r.body1.part}'s row runs along ${r.repeat.axis} too; a row inside a row runs along another axis`)}if(e.repeat){const n=e.repeat,s=`${i}.repeat`;"part"in e.body0||P_("JOINT_SCHEMA",s,"a row fills the part it is fastened to; the mounting plane has no length to fill"),["X","Y","Z"].includes(n.axis)||P_("JOINT_SCHEMA",s,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===I_[K_(t.document.model,e)]&&P_("JOINT_SCHEMA",s,`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:(t=>{const e=j_(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)})(n.pitch))||P_("GEOMETRY_DOMAIN",s,"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<=100||P_("GEOMETRY_DOMAIN",s,"a row has 1 to 100 copies"),void 0!==n.rise&&(n.rise&&["X","Y","Z"].includes(n.rise.axis)&&n.rise.axis!==n.axis||P_("JOINT_SCHEMA",`${s}.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||P_("GEOMETRY_DOMAIN",`${s}.rise`,"a rise is a length in mm, not zero"))}}function _x(t,e){const n=t.document.model,i=e.body1.part,{pose:s}=$_(n,i,i),r="part"in e.body0?e.body0.part:void 0,o=`joints.${e.id}`,a=r?Mx(kx(t,r,o)):xx,c=!wx(a),l=rb.map(t=>e.origin?.turn?.[t]??0),h=K_(n,e),d=I_[h],u=e.origin?.twist?V_(Px(d,e.origin.twist),G_(l)):G_(l),p=V_(a,u),f=Ix(Sx(a,Ax[h]),`${e.body1.part}'s ${h}`,r??"",a,o),m=Sx(a,rb.map(t=>t===d?1:0)),g=(e.origin?.twist??0)*Math.sign(m[rb.indexOf(f.axis)]),{quarter:y,deg:b}=function(t,e,n,i){const s=rb.indexOf(e),[r,o]=Ox[e].map(t=>rb.indexOf(t));let a;for(const e of Dx){const i=V_(t,Mx(e));if(Math.abs(i[s][s]-1)>1e-9)continue;const c=180*Math.atan2(i[o][r],i[r][r])/Math.PI,l=Math.abs(((c-n)%360+540)%360-180);(!a||l<a.off-1e-9)&&(a={quarter:e,deg:Math.abs(c)<1e-9?0:c,off:l})}a||P_("ATTACH_FACE",i,`the part would stand turned about more than the face's normal (${B_(zx(t))})`);return{quarter:a.quarter,deg:a.off<1e-6?n:mx(a.deg)}}(p,f.axis,g,o),v=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...(c||e.origin?.twist?Tx(y):l).map(t=>ex(n,"deg",t,"a"))];for(const e of v)ux(t,e,cx(n,i,e)?e:void 0);const _=t=>c&&Object.hasOwn(Ax,t)?Ex(Ix(Sx(a,Ax[t]),t,r??"",a,o).vector):t;if(fx(t,{kind:"attach",part:i,face:_(e.body1.face),to:"plane"in e.body0?{plane:"mounting-plane"}:{part:e.body0.part,face:_(e.body0.face)},...e.origin?.facing?{facing:e.origin.facing}:{},...void 0!==e.origin?.gap?{gap:e.origin.gap}:{},...e.origin?.align?{align:c?Rx(r?Mx(Cx(t,r,o)):a,e.origin.align,o):e.origin.align}:{},replace:!0},b?{deg:b}:void 0),b){const e=s.args.slice(3,6);s.args=[...s.args.slice(0,3),...zx(p).map(t=>ex(n,"deg",t,"a"))];for(const n of e)ux(t,n)}if(e.repeat&&c&&P_("JOINT_SCHEMA",`joints.${e.id}.repeat`,`${r} stands turned; a row across a turned part is not covered yet`),"fixed"===e.type)return void(e.repeat&&jx(t,e));const x="prismatic"===e.type?"slide":"turn",w="prismatic"===e.type?e.travel?"ratio":"mm":"deg",M=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},S=R_(e).map(e=>({leader:(t.joints??[]).find(t=>t.id===e.joint),k:e.multiplier})),A=Sx(a,rb.map(t=>t===e.axis.toLowerCase()?1:0)),E=A.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);E<0&&P_("JOINT_SCHEMA",o,`${r} stands twisted; the axis ${e.axis} is not level with an axis in it`),function(t,e,n,i=1){const s=t.document.model,r=e.part;$_(s,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&P_("SCHEMA",r,"a slide or a turn is required");rb.includes(e.motion.axis)||P_("SCHEMA",r,`${String(e.motion.axis)} is not an axis`);F_(s,`${e.part}.motion`),0;F_(s,`${e.part}.motion`)&&Hx(t,{part:e.part});const o=e.motion.frame??"attachment",a=$x(t,e.part);"asset"===o&&a!==t.document.capabilities.assetFrame?P_("MOTION_FRAME",r,`${e.part} is fastened into ${a}; an axis in the asset frame would have to be re-expressed there, which this command does not do`):"attachment"!==o&&"asset"!==o&&P_("SCHEMA",r,`${String(o)} is not a frame for the axis`);const c=e.state,l=tx(s,`${e.part}.motion`);let h=c?.id;if(n){if(n.sum)for(const[t,e]of n.terms.entries()){const n=l(`mimic.${t}`);if(s.nodes.push({id:n,op:"mul@1",args:[e.of,ex(s,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=l(`mimic.${t}.sum`);s.nodes.push({id:e,op:"add@1",args:[h,`${n}.value`],outputs:{value:`${e}.value`}}),h=`${e}.value`}else h=`${n}.value`}else{const t=l("mimic");s.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,ex(s,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),h=`${t}.value`}if(n.c){const t=l("mimic.offset"),i="slide"===e.motion.kind?"mm":"deg";s.nodes.push({id:t,op:"add@1",args:[h,ex(s,i,n.c,"d")],outputs:{value:`${t}.value`}}),h=`${t}.value`}}else{c&&"string"==typeof c.id&&c.id.trim()||P_("SCHEMA",r,"a state input id is required");const n=s.inputs.find(t=>t.id===c.id&&"state"===t.role&&t.unit===c.unit&&t.min===c.min&&t.max===c.max);if(n);else if(s.inputs.some(t=>t.id===c.id)){if((s.nodes.some(t=>t.args.includes(c.id))||(t.drivers??[]).some(t=>t.state===c.id)||t.appearance.some(t=>t.visibility===c.id))&&P_("DUPLICATE_WRITER",r,`${c.id} already exists`),s.inputs=s.inputs.filter(t=>t.id!==c.id),delete t.stateDefaults[c.id],t.stateInputs?.[c.id]){const{[c.id]:e,...n}=t.stateInputs;t.stateInputs=n}}const i="turn"===e.motion.kind?["deg"]:["mm","ratio"];i.includes(c.unit)||P_("SCHEMA",r,`a ${e.motion.kind} takes a ${i.join(" or ")} control, not ${String(c.unit)}`),Number.isFinite(c.min)&&Number.isFinite(c.max)&&c.max>c.min||P_("SCHEMA",r,"a range with max above min is required");const o=c.start??c.min;o>=c.min&&o<=c.max||P_("SCHEMA",r,"the starting value is outside the range"),n||(s.inputs.push({id:c.id,unit:c.unit,min:c.min,max:c.max,role:"state"}),t.stateDefaults[c.id]=o),void 0===c.label&&void 0===c.sweep||(t.stateInputs={...t.stateInputs??{}},t.stateInputs[c.id]={...void 0!==c.label?{label:c.label}:{},...void 0!==c.sweep?{sweep:c.sweep}:{}})}if("slide"===e.motion.kind&&"ratio"===c.unit){e.travel||P_("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let i;if(Object.hasOwn(n,"sum")){const e=n.plus??0;i=nx(s,l,rx(s,l,sx(s,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?ox(s,t,n.source,r):ex(s,"mm",n.plus??0,"d");i=n.source?nx(s,l,e,n.times??1,n.plus??0,"travel"):e}const o=l("distance");s.nodes.push({id:o,op:"mul@1",args:[h,i],outputs:{value:`${o}.value`}}),h=`${o}.value`}else"slide"===e.motion.kind&&e.travel&&P_("SCHEMA",r,"a mm control is the distance; travel would say it twice");const d=rb.map(t=>ex(s,"ratio",t===e.motion.axis?i:0,"axis"));if(s.nodes.push({id:`${e.part}.motion`,op:"slide"===e.motion.kind?"axis-slide@1":"axis-turn@1",args:[...d,h],outputs:{pose:`${e.part}.motion.value`},params:{from:`${e.part}.seat`,to:a}}),gx(t,e.part,a),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||P_("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||P_("SCHEMA",r,"a clip runs for a positive number of seconds"),t.drivers=[...t.drivers??[],{id:`${e.part}/${n.name}`,clip:n.name,state:c.id,time:{unit:"s",duration:n.duration},keys:structuredClone(n.keys),interpolation:"linear",loop:n.loop??"wrap",accumulates:n.accumulates??!1}]}}(t,{part:i,motion:{kind:x,axis:rb[E]},state:{id:bx(e),unit:w,min:M.min,max:M.max,start:e.state?.start??Math.min(M.max,Math.max(M.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:S.map(({leader:t,k:e})=>({of:F_(n,`${t.body1.part}.motion`)?.args[3]??bx(t),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,A[E]>0?1:-1),e.repeat&&jx(t,e)}const xx=[[1,0,0],[0,1,0],[0,0,1]],wx=t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)),Mx=t=>t[0].map((e,n)=>t.map(t=>t[n])),Sx=(t,e)=>t.map(t=>t.reduce((t,n,i)=>t+n*e[i],0)),Ax={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]},Ex=t=>Object.keys(Ax).find(e=>Ax[e].every((e,n)=>e===t[n]));function kx(t,e,n){const i=(t.joints??[]).find(t=>t.body1.part===e),s=i?rb.map(t=>i.origin?.turn?.[t]??0):H_(t.document.model,t,e,n);s.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&P_("EDIT_TARGET",n,`${e} is turned (${B_(s)}); fastening to a turned part by its faces is covered only for quarter turns`);const r=s.every(t=>0===t)?xx:G_(s);return i?.origin?.twist?V_(Px(I_[K_(t.document.model,i)],i.origin.twist),r):r}function Cx(t,e,n){const i=(t.joints??[]).find(t=>t.body1.part===e);if(!i?.origin?.twist)return kx(t,e,n);const s=rb.map(t=>i.origin?.turn?.[t]??0);return s.every(t=>0===t)?xx:G_(s)}function Tx(t){const e=t=>{const e=90*Math.round(180*t/Math.PI/90);return 0===e?0:e},n=Math.abs(t[0][2])<1?[e(Math.atan2(-t[1][2],t[2][2])),e(Math.asin(t[0][2])),e(Math.atan2(-t[0][1],t[0][0]))]:[e(Math.atan2(Math.sign(t[0][2])*t[1][0],t[1][1])),e(Math.asin(t[0][2])),0];return G_(n).every((e,n)=>e.every((e,i)=>e===t[n][i]))||P_("EDIT_TARGET","turn",`${JSON.stringify(t)} is not a quarter turn; a fastening is covered only for quarter turns`),n}const Ox={x:["y","z"],y:["z","x"],z:["x","y"]};function Px(t,e){const n=Math.cos(e*Math.PI/180),i=Math.sin(e*Math.PI/180),[s,r]=Ox[t].map(t=>rb.indexOf(t)),o=[[1,0,0],[0,1,0],[0,0,1]];return o[s][s]=n,o[s][r]=-i,o[r][s]=i,o[r][r]=n,o}function Ix(t,e,n,i,s){const r=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);return r<0&&P_("ATTACH_FACE",s,`${n} stands twisted (${B_(zx(Mx(i)))}); ${e} is not level with an axis in it`),{axis:rb[r],vector:t.map(t=>Math.abs(t)<1e-9?0:Math.sign(t))}}const Dx=(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const i of[0,90,180,270]){const s=G_([e,n,i]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===s[e][n])))||t.push(s)}return t})();function zx(t){const e=t=>{const e=mx(180*t/Math.PI);return 0===e?0:e},n=Math.max(-1,Math.min(1,t[0][2]));return Math.abs(n)<1-1e-12?[e(Math.atan2(-t[1][2],t[2][2])),e(Math.asin(n)),e(Math.atan2(-t[0][1],t[0][0]))]:[e(Math.atan2(t[1][0],t[1][1])),e(Math.asin(n)),0]}function Rx(t,e,n){const i={};for(const[s,r]of Object.entries(e)){const e=Sx(t,rb.map(t=>t===s?1:0)),o=e.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);o<0&&P_("ATTACH_FACE",n,`the parent stands twisted; placing along ${s} is not level with an axis in it -- place it by the centre`);const a=Math.sign(e[o]),c=rb[o];"centre"===r||a>0?i[c]=r:"min"===r||"max"===r?i[c]="min"===r?"max":"min":"number"==typeof r.mm?i[c]={mm:-r.mm}:P_("SCHEMA",n,`an offset that follows another value cannot be turned over onto ${c}; give it as a number`)}return i}function jx(t,e){const n=t.document.model,i=e.body1.part,s=e.body0.part,r=`joints.${e.id}.repeat`,o=e.repeat.axis.toLowerCase(),a=rb.indexOf(o),c=J_(n,s,r)[o];c||P_("EDIT_TARGET",r,`${s} has no two faces along ${o}; there is no length to fill`);const l=Z_(n,t,i,r)[o],h=l?void 0:function(t,e,n,i,s){const{shape:r}=$_(t,n,s),o="revolve@1"===r.op&&"taper"===r.params?.profile?{along:r.params.axis,radii:[r.args[3],r.args[2]]}:void 0;if(!o)return;const a=Y_(t,e,n,s),c=rb[a[rb.indexOf(i)].findIndex(t=>0!==t)];if(c===o.along)return;const l=`${n}.width.${c}`;if(!F_(t,l)){const e=ex(t,"mm",0,"d"),n=ex(t,"ratio",2,"k"),[i,s]=o.radii;t.nodes.push({id:l,op:"affine-bounds@1",args:[e,e,i,n,e,s,n,e,e,e,e],outputs:{xmin:`${l}.unused.xmin`,xmax:`${l}.value`,ymin:`${l}.unused.ymin`,ymax:`${l}.unused.ymax`,zmin:`${l}.unused.zmin`,zmax:`${l}.unused.zmax`},params:{layout:"L0.1_1.0.0.0.0"}})}return`${l}.value`}(n,t,i,o,r);l||h||P_("EDIT_TARGET",r,`${i} has no two faces along ${o}; its copies cannot be spaced`);const{place:d,pose:u}=$_(n,i,r),p=F_(n,`${i}.seat.rigid`),f=tx(n,`${i}.row`),m=ex(n,"mm",0,"d");p.args=p.args.map((t,e)=>e===a?rx(n,f,c.lo,"start"):t);const g=h||l.centred?m:rx(n,f,U_([...W_(l.lo),...W_(l.hi)]),"own-centre");u.args=u.args.map((t,e)=>e===a?g:t);const y=rx(n,f,[...c.hi,...U_(c.lo)],"length"),b=h??rx(n,f,[...l.hi,...U_(l.lo)],"extent"),v=ex(n,"ratio",.5,"k"),_=ex(n,"count",100,"limit"),x=e.repeat.count;n.nodes.push(void 0===x?{id:`${i}.layout`,op:"fit-pitch@1",args:[y,m,m,b,ix(n,t,f,e.repeat.pitch,"pitch",r),v,_],outputs:{layout:`${i}.layout.value`}}:{id:`${i}.layout`,op:"fixed-count@1",args:[ex(n,"count",x,"count"),y,m,m,b,v,_],outputs:{layout:`${i}.layout.value`}}),d.op="member@1",d.args=[d.args[0],F_(n,`${i}.turned`)?.outputs?.pose??u.outputs.pose],n.nodes.push({id:`${i}.assembly`,op:"assembly@1",args:[d.outputs.placed],outputs:{assembly:`${i}.assembly.value`}});const w=F_(n,`${s}.world`)?.outputs?.pose??F_(n,`${s}.chain`)?.outputs?.pose??F_(n,`${s}.turned`)?.outputs?.pose??F_(n,`${s}.pose`)?.outputs?.pose;let M=p.outputs.pose;w&&(n.nodes.push({id:`${i}.row`,op:"compose@1",args:[w,p.outputs.pose],outputs:{pose:`${i}.row.value`}}),M=`${i}.row.value`),n.nodes=n.nodes.filter(t=>t.id!==`${i}.chain`&&t.id!==`${i}.world`);const S=e.repeat.rise;n.nodes.push({id:`${i}.repeat`,op:"repeat@1",args:[`${i}.layout.value`,`${i}.assembly.value`,M,...S?[ex(n,"mm",S.mm,"rise")]:[]],outputs:{collection:`${i}.repeat.value`},params:{axis:o,...S?{riseAxis:S.axis.toLowerCase()}:{}}})}function Lx(t,e){const n=t.document.model,i=e.body1.part;!function(t,e){const n=t.document.model,i=F_(n,e);if("member@1"!==i?.op||!F_(n,`${e}.repeat`))return;const s=F_(n,`${e}.layout`),r=F_(n,`${e}.repeat`)?.args[3],o=new Set([`${e}.layout`,`${e}.assembly`,`${e}.repeat`,`${e}.row`]),a=n.nodes.filter(t=>o.has(t.id)||t.id.startsWith(`${e}.row.`));n.nodes=n.nodes.filter(t=>!a.includes(t)),i.op="place@1";for(const e of[...s?.args??[],...r?[r]:[]])ux(t,e)}(t,i),F_(n,`${i}.motion`)&&Hx(t,{part:i});const{pose:s,place:r}=$_(n,i,i),o=new Set([`${i}.seat.rigid`,`${i}.chain`,`${i}.world`,`${i}.turned`]);n.nodes=n.nodes.filter(t=>!o.has(t.id)&&!t.id.startsWith(`${i}.on.`));const a=ex(n,"mm",0,"d"),c=s.args.slice(0,3);s.args=[a,a,a,...s.args.slice(3)],s.params={...s.params,to:t.document.capabilities.assetFrame};for(const e of c)ux(t,e,cx(n,i,e)?e:void 0);r.args=[r.args[0],s.outputs.pose]}function Fx(t){const e=[];if(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}),t.travel){const n=t.travel;e.push({at:"travel",get:()=>Object.hasOwn(n,"sum")?{sum:n.sum,...void 0!==n.plus?{plus:n.plus}:{}}:n.source?{from:n.source,...void 0!==n.times?{times:n.times}:{},...void 0!==n.plus?{plus:n.plus}:{}}:n.plus??0,set:e=>{const n=j_(e);t.travel=n?n.sum?{sum:n.terms,...n.plus?{plus:n.plus}:{}}:{source:n.terms[0].from,...void 0!==n.terms[0].times?{times:n.terms[0].times}:{},...void 0!==e.plus?{plus:e.plus}:{}}:{plus:e}}})}for(const n of Object.keys(t.origin?.align??{})){const i=t.origin.align[n];i&&"object"==typeof i&&Object.hasOwn(i,"mm")&&e.push({at:`align.${n}`,get:()=>i.mm,set:t=>i.mm=t})}return e}function Nx(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:i}of Fx(n))for(const s of j_(i())?.terms??[])"part"===s?.from?.of&&ax(t.document.model,s.from.part,s.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],i=new Map(t.map(t=>[t.body1.part,t]));for(;n.length<t.length;){const s=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?i.get(t.body0.part):void 0;return(!n||e.has(n.id))&&R_(t).every(t=>e.has(t.joint))});s.length||P_("JOINT_TREE","joints","the joints do not make a tree");for(const t of s)e.add(t.id),n.push(t)}return n}(e),i={...t.stateDefaults},s=hx;hx={asset:t,declared:lx(t)};try{for(const e of t.document.model.nodes)"member@1"!==e.op||F_(t.document.model,`${e.id}.repeat`)||(e.op="place@1");for(const e of[...n].reverse())Lx(t,e);for(const e of n)_x(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const i=F_(n,`${t.body1.part}.assembly`),s=r=>{for(const o of e.filter(t=>"part"in t.body0&&t.body0.part===r)){if(o.repeat){const e=F_(n,`${o.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},i.args.push(e.outputs.collection);continue}const e=F_(n,o.body1.part);e.op="member@1",i.args.push(e.outputs.placed),s(o.body1.part)}};s(t.body1.part)}}(t,e);for(const e of n)"fixed"===e.type||e.mimic||void 0===i[bx(e)]||(t.stateDefaults[bx(e)]=i[bx(e)])}finally{hx=s}}const $x=(t,e)=>{const n=px(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame};function Hx(t,e){const n=t.document.model,i=F_(n,`${e.part}.motion`);i||P_("EDIT_TARGET",e.part,`${e.part} does not move`);const s=i.args[3],r=F_(n,`${e.part}.seat.rigid`)?.params?.to??i.params.to,o=n.inputs.find(t=>t.id===s&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(N_(n,s)?.args??[]).includes(t.id));return n.nodes=n.nodes.filter(t=>t!==i),gx(t,e.part,r),ux(t,s,s),o&&!n.nodes.some(t=>t.args.includes(o.id))&&(n.inputs=n.inputs.filter(t=>t!==o),delete t.stateDefaults[o.id],t.stateInputs&&delete t.stateInputs[o.id],t.drivers&&(t.drivers=t.drivers.filter(t=>t.state!==o.id)),t.drivers&&!t.drivers.length&&delete t.drivers,t.stateInputs&&!Object.keys(t.stateInputs).length&&delete t.stateInputs),t}const Bx=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};function Yx(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,i=t.document.capabilities.bindings.map(t=>{const i="string"==typeof t.pose?null:t.pose,s=i?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===i.placement):null,r=i?N_(e,i.feature):null,o=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:s?.id??null,face:r?.params?.name??null,accepts:[...t.accepts],capacity:t.capacity,region:3===o.length&&o.every(t=>"number"==typeof t)?{x:o[0],y:o[1],z:o[2]}:null}}),s=E_(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),i=N_(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:i?.params?.name??null,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[...i,...s]}const Gx=(t,e,n)=>{throw new pb(t,e,n)};function Vx(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||Gx("SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||Gx("SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||Gx("SCHEMA",i,`unknown ${s}`)}const Ux=(t,e)=>{"string"==typeof t&&t.trim()||Gx("SCHEMA",e,"nonempty string required")};function Wx(t,e){return function(t,e){const n=Nv(t),i=structuredClone(e),s=n.outputTypes,r=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),o=new Map;Vx(i,["version","assetFrame","bindings"],["names","slotLayout"],"capabilities"),"r3-capability-3"!==i.version&&Gx("VERSION","capabilities",i.version);if(Ux(i.assetFrame,"assetFrame"),void 0!==i.names){Array.isArray(i.names)||Gx("SCHEMA","names","array required");for(const t of i.names)ob.includes(t)||Gx("CAPABILITY_NAME","names",`${String(t)} is not one of ${ob.join(", ")}`);new Set(i.names).size!==i.names.length&&Gx("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(ab))i.names.includes(t)&&!e.some(t=>i.names.includes(t))&&Gx("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}Array.isArray(i.bindings)||Gx("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(Ux(t,e),Object.hasOwn(s,t)||Gx("TARGET_ABSENT",e,t),s[t]),l=(t,e,n)=>{const s=c(t,e);("transform"!==s.kind||s.to!==i.assetFrame||void 0!==n&&s.from!==n)&&Gx("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>Gv({types:s,writers:r,model:t,assetFrame:i.assetFrame},e,n),d=new Map;for(const t of i.bindings){Vx(t,["id","label","role","frame","pose","accepts","capacity"],["region","contacts"],"binding");for(const e of["id","label","frame"])Ux(t[e],e);if(a.has(t.id)&&Gx("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||Gx("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&&Gx("FRAME_TYPE",t.id,"binding frame must be the selected feature frame"),d.set(t.id,e)}if(Array.isArray(t.accepts)&&t.accepts.length||Gx("SCHEMA",t.id,"nonempty accepts required"),t.accepts.forEach(e=>Ux(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&Gx("SCHEMA",t.id,"duplicate accepted type"),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&Gx("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){Vx(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&Gx("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||Gx("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&Gx("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||Gx("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const i of t.contacts){const s=h(i,t.id),r=JSON.stringify([i.placement,i.feature]);e.has(r)&&Gx("DUPLICATE_CONTACT",t.id,r),e.add(r),n.push(s)}o.set(t.id,n)}}const u=[];if(void 0!==i.slotLayout){const t=i.slotLayout;Vx(t,["label","role","anchors","layout"],[],"slotLayout"),Ux(t.label,"slotLayout.label"),["seat","grip"].includes(t.role)||Gx("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),Array.isArray(t.anchors)&&t.anchors.length||Gx("SCHEMA","slotLayout.anchors","at least one anchor required");const e=new Map;t.anchors.forEach((t,n)=>{const i=`slotLayout.anchors[${n}]`;Vx(t,["id","frame","pose"],[],i),Ux(t.id,`${i}.id`),Ux(t.frame,`${i}.frame`),e.has(t.id)&&Gx("SCHEMA",`${i}.id`,`duplicate anchor ${t.id}`),"string"==typeof t.pose&&Gx("SLOT_LAYOUT_FACE",`${i}.pose`,"an anchor is a face of a part");const s=h(t.pose,i);s.frame!==t.frame&&Gx("FRAME_TYPE",i,"anchor frame must be the selected feature frame");const r=s.normal[1];r||Gx("SLOT_LAYOUT_FACE",`${i}.pose`,"an anchor is a horizontal face (its normal along Y)"),e.set(t.id,{surface:s,up:r})});const n=n_(t.layout,{anchors:e.keys()}),s=n.length?n:i_(t.layout);s.length&&Gx("SLOT_LAYOUT",`slotLayout.layout.${s[0].path}`,s.map(t=>`${t.code} at ${t.path}`).join("; "));for(const n of E_(t)){n.accepts.length||Gx("SCHEMA",n.id,"nonempty accepts required"),n.accepts.forEach(t=>Ux(t,n.id)),new Set(n.accepts).size!==n.accepts.length&&Gx("SCHEMA",n.id,"duplicate accepted type"),(!Number.isSafeInteger(n.capacity)||n.capacity<1)&&Gx("CAPACITY",n.id,"positive integer capacity required"),a.has(n.id)&&Gx("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=[...i.bindings,...u];function f(t,e){const n=t.pose.r,i=f_(e),s=[i.position.x,i.position.y*e.up,i.position.z],r=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*s[n],0)),o=i.rotation*Math.PI/180,a=Math.cos(o),c=Math.sin(o),l=[[a,0,c],[0,1,0],[-c,0,a]],h=n.map(t=>l[0].map((e,n)=>t.reduce((t,e,i)=>t+e*l[i][n],0)));return{...t,pose:{r:h,t:r}}}function m(t,e,n){const i=t=>function(t,e){const n=t[e.placement],i=t[e.feature],s=n.pose.r,r=s.map(t=>t.reduce((t,n,i)=>t+n*e.normal[i],0)),o=s.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*i.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,i=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);i||Bv("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=i.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:s.map(t=>[...t]),t:o},normal:r,provenance:"verified-planar-surface"}}(e,t);let s=null;if(t.allowed)s={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)&&Gx("REGION_DOMAIN",t.id,"positive region dimensions required"),s={kind:t.region.kind,dimensions:n}}let r={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];Vx(e,["type","occupied"],[],t.id+".request"),Ux(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&Gx("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const i=[];t.accepts.includes(e.type)||i.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&i.push("CAPACITY_FULL"),r={status:i.length?"failed":"satisfied",reasons:i}}const a=(o.get(t.id)??[]).map(i),c=d.has(t.id)?i(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:s,contacts:a,checks:{declaration:{status:"satisfied"},eligibility:r,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 Vx(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)),...(o.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(s),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={})=>{Vx(n,[],[...a],"requests");const i=Object.keys(n).length>0,s=e.advance(t,i?"REQUESTS":void 0);if("evaluation"===s.kind)return{...s,result:y(s.result,n)};if("changes"===s.kind){const t=p.filter(t=>i||s.structure||v.get(t.id).some(t=>s.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,s.read(t)])),n));return{...s,places:t}}const r=p.filter(t=>v.get(t.id).some(t=>s.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,s.read(t)])),n));return{kind:"poses",generation:s.generation,bodies:s.bodies,poses:s.poses,places:r}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const i=p.find(e=>e.id===t);return i||Gx("TARGET_ABSENT",t,"no such place"),Vx(n,[],[...a],"requests"),m(i,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const qx=1048576;function Xx(t,e){throw new pb(t,"document",e)}function Kx(t){return(new TextEncoder).encode(t).byteLength}function Qx(t){const e=new Set;!function t(n,i){if(i>64&&Xx("DOCUMENT_LIMIT","nesting exceeds 64"),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||Xx("JSON_VALUE","nonfinite number"));"object"!=typeof n&&Xx("JSON_VALUE","only JSON values are allowed"),e.has(n)&&Xx("JSON_VALUE","cycle");const s=Array.isArray(n);s||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||Xx("JSON_VALUE","plain objects required"),e.add(n);const r=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(r)){if(s&&"length"===e)continue;"string"!=typeof e&&Xx("JSON_VALUE","symbols unsupported");const o=r[e];o.enumerable&&Object.hasOwn(o,"value")||Xx("JSON_VALUE","hidden properties and accessors unsupported"),!s||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||Xx("JSON_VALUE","extra array property"),t(o.value,i+1)}s&&Object.keys(n).length!==n.length&&Xx("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function Jx(t){if(Qx(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new pb("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new pb("VERSION","document","unsupported document version");if(Kx(JSON.stringify(t))>qx)throw new pb("DOCUMENT_LIMIT","document","over 1 MiB");const e=t;if(!Array.isArray(e.model?.nodes)||e.model.nodes.length>8192)throw new pb("DOCUMENT_LIMIT","document","maximum 8192 nodes");return Wx(e.model,e.capabilities)}const Zx=(t,e,n)=>{throw new pb(t,e,n)};function tw(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function ew(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const i=n[n.length-1];if(e>=i.at)return i.value;let s=0;for(;s<n.length-2&&n[s+1].at<=e;)s++;const r=n[s],o=n[s+1];if("step"===t.interpolation)return r.value;const a=o.at-r.at;return r.value+(e-r.at)/a*(o.value-r.value)}function nw(t,e,n="other"){Number.isFinite(e)||Zx("DRIVER_TIME",t.id,"finite time required");const i=Math.max(0,e),s=t.time.duration,r=t.keys[0].value,o=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=ew(t,Math.min(i/s,1));else{const e=Math.floor(i/s);a=ew(t,(i-e*s)/s),t.accumulates&&(a+=e*(o.value-r))}return t.accumulates?"deg"===n||"rad"===n?function(t,e){const n="deg"===e?360:2*Math.PI,i=n/2,s=((t+i)%n+n)%n-i;return s===i?-i:s}(a,n):Zx("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}const iw=(t,e,n)=>{throw new pb(t,e,n)};function sw(t,e,n,i){t&&"object"==typeof t&&!Array.isArray(t)||iw("ASSET_SCHEMA",i,"object required");for(const n of e)Object.hasOwn(t,n)||iw("ASSET_SCHEMA",i,`missing ${n}`);for(const s of Object.keys(t))[...e,...n].includes(s)||iw("ASSET_SCHEMA",i,`unknown ${s}`)}function rw(t){return function(t,e,n=!1){const i=t&&"object"==typeof t?t:void 0,s=i?aw.get(i):void 0;if(s&&s.kernel===Hv&&(s.joints||!e))return s.compiled;Qx(t);const r=ow(t);Kx(JSON.stringify(r))>qx&&iw("DOCUMENT_LIMIT","asset","over 1 MiB");sw(r,["version","name","document","designInputs","stateDefaults","palette","appearance"],["occupancy","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs","carrier"],"asset"),void 0!==r.carrier&&O_(r.carrier);void 0===r.placement||k_.includes(r.placement)||iw("ASSET_SCHEMA","placement",`one of ${k_.join(", ")} required`);"figure-asset-1"!==r.version&&iw("VERSION","asset",r.version);"string"==typeof r.name&&r.name.trim()||iw("ASSET_SCHEMA","name","nonempty name required");const o=structuredClone(r),a=Jx(o.document),c=o.document.model,l=c.inputs.filter(t=>"state"!==t.role).map(t=>t.id),h=c.inputs.filter(t=>"state"===t.role).map(t=>t.id);sw(o.designInputs,l,[],"designInputs"),void 0===o.detailLevel||(t=>cb.includes(t))(o.detailLevel)||iw("ASSET_SCHEMA","detailLevel",`${String(o.detailLevel)} is not a detail level; ${cb.join(", ")}`);if(void 0!==o.sizing){"uniform"!==o.sizing&&iw("ASSET_SCHEMA","sizing",`${String(o.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])c.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||iw("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(sw(o.stateDefaults,h,[],"stateDefaults"),void 0!==o.publicInputs){Array.isArray(o.publicInputs)||iw("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,n]of o.publicInputs.entries()){const i=`publicInputs[${e}]`;sw(n,["input","label"],["hint"],i),$v(c.inputs,n.input,`${i}.input`),"string"==typeof n.label&&n.label.trim()||iw("ASSET_SCHEMA",`${i}.label`,"a name shown on the board"),void 0!==n.hint&&"string"!=typeof n.hint&&iw("ASSET_SCHEMA",`${i}.hint`,"one line"),t.has(n.input)&&iw("PUBLIC_INPUT",`${i}.input`,`${n.input} is listed twice`),t.add(n.input)}}o.palette&&"object"==typeof o.palette&&!Array.isArray(o.palette)||iw("ASSET_SCHEMA","palette","token to hex color map required");for(const[t,e]of Object.entries(o.palette))t.trim()&&"string"==typeof e&&/^#[0-9a-f]{6}$/i.test(e)||iw("PALETTE","palette","six digit hex color required");const d=t=>{"string"==typeof t&&Object.hasOwn(o.palette,t)||iw("PALETTE",String(t),"unresolved color token")},u=new Map(c.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),p=new Map(c.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),f=new Map;Array.isArray(o.appearance)||iw("ASSET_SCHEMA","appearance","array required");for(const t of o.appearance){if(sw(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=a.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||iw("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(p.has(t.target)&&!f.has(t.target)||iw("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),sw(t.material,["token"],["preset","transparent","emissive"],"material"),d(t.material.token),void 0===t.material.preset||["default","metal","glass","plastic","wood","ceramic","rubber"].includes(t.material.preset)||iw("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&iw("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;sw(e,["token","intensity","on"],[],"emissive"),d(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&iw("MATERIAL","emissive","invalid intensity or switch")}const e=u.get(p.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)||iw("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&iw("QUALITY","segments","segments unsupported on this provider"),f.set(t.target,t)}f.size!==p.size&&iw("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==o.occupancy){if(sw(o.occupancy,["bounds"],["contact"],"occupancy"),void 0!==o.occupancy.contact){const t=o.occupancy.contact;sw(t,["plane","surface"],[],"occupancy.contact"),"mounting-plane"!==t.plane&&iw("OCCUPANCY","occupancy.contact",`${String(t.plane)} is not a plane the figure can be mounted on`),Gv({types:a.outputTypes,writers:u,model:c,assetFrame:o.document.capabilities.assetFrame},t.surface,"occupancy.contact.surface")}sw(o.occupancy.bounds,["x","y","z"],[],"occupancy.bounds");const t=JSON.stringify([1,0,0]);for(const e of["x","y","z"]){sw(o.occupancy.bounds[e],["min","max"],[],`occupancy.bounds.${e}`);for(const n of["min","max"]){const i=`occupancy.bounds.${e}.${n}`,s=o.occupancy.bounds[e][n];"string"==typeof s&&JSON.stringify(a.outputTypes[s])===t||iw("OCCUPANCY",i,`${String(s)} is not a length value in the graph`),a.dependence[s]?.length&&iw("OCCUPANCY_STATE",i,`${s} depends on state input ${a.dependence[s].join(", ")}; the occupancy is state-independent`)}}}(function(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||Zx("DRIVER","drivers","array required");const n=tw(t),i=new Set,s=new Set,r=new Map;for(const t of e){const e=`drivers.${String(t?.id??"?")}`,o=t=>t&&"object"==typeof t?Object.keys(t).sort():null;JSON.stringify(o(t))!==JSON.stringify(["accumulates","clip","id","interpolation","keys","loop","state","time"])&&Zx("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||Zx("DRIVER",e,"id required"),i.has(t.id)&&Zx("DRIVER",e,"duplicate driver id"),i.add(t.id),"string"==typeof t.clip&&t.clip.trim()||Zx("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||Zx("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`),s.has(t.state)&&Zx("DRIVER_STATE",e,`two drivers write ${t.state}; one writer per state`),s.add(t.state),JSON.stringify(o(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||Zx("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||Zx("DRIVER_TIME",e,"positive duration in seconds required");const a=r.get(t.clip);void 0===a?r.set(t.clip,t.time.duration):a!==t.time.duration&&Zx("DRIVER_TIME",e,`clip "${t.clip}" already runs for ${a} s; one clip is one clock, so every driver in it shares a duration`),(!Array.isArray(t.keys)||t.keys.length<2)&&Zx("DRIVER_KEYS",e,"at least two keys required");let c=-1/0;for(const n of t.keys)JSON.stringify(o(n))!==JSON.stringify(["at","value"])&&Zx("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||Zx("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>c||Zx("DRIVER_KEYS",e,"key at values must strictly increase"),c=n.at,Number.isFinite(n.value)||Zx("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&Zx("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||Zx("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||Zx("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&Zx("DRIVER",e,"accumulates must be a boolean");const l=n.get(t.state);t.accumulates&&"deg"!==l&&"rad"!==l&&Zx("DRIVER_STATE",e,`an accumulating driver writes an angle; ${t.state} is in ${l}`)}})(o),function(t){const e=t.stateInputs;if(void 0===e)return;e&&"object"==typeof e&&!Array.isArray(e)||Zx("STATE_INPUT","stateInputs","object required");const n=tw(t);for(const[t,i]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||Zx("STATE_INPUT",e,`${t} is not a state input of this asset`),i&&"object"==typeof i&&!Array.isArray(i)||Zx("STATE_INPUT",e,"object required");for(const t of Object.keys(i))"label"!==t&&"sweep"!==t&&Zx("STATE_INPUT",e,`unknown ${t}`);void 0===i.label||"string"==typeof i.label&&i.label.trim()||Zx("STATE_INPUT",e,"label must be a nonempty string"),void 0===i.sweep||Number.isFinite(i.sweep)&&i.sweep>=0||Zx("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(o),void 0===o.joints||Array.isArray(o.joints)||iw("ASSET_SCHEMA","joints","joints is a list");function m(t={}){sw(t,[],h,"state overrides");const e={...o.designInputs,...o.stateDefaults,...t},n=a.evaluate(e),i=t=>t.key?u.get(t.key)?.id:t.id,s=new Map(o.appearance.map((t,e)=>[t.target,e])),r=n.geometry.map((t,e)=>({g:t,i:e,at:s.get(i(t))??Number.MAX_SAFE_INTEGER})).sort((t,e)=>t.at-e.at||t.i-e.i).map(t=>t.g).map(t=>{const e=i(t),s=f.get(e);return s||iw("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(s.material),visible:void 0===s.visibility||n.values[s.visibility],...void 0!==s.segments?{segments:s.segments}:{}}});return{...n,geometry:r,inputs:e,palette:structuredClone(o.palette)}}(function(t){const e=t.joints;if(!e?.length)return;const n=structuredClone(t);for(const t of e)vx({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);Nx(n);const i=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)});i(n.document.model)!==i(t.document.model)&&P_("JOINT_DRIFT","joints","the joints' nodes are not what their records make; the asset was edited apart from its joints")})(o),m();const g={evaluate:m};i&&n&&(aw.set(i,{kernel:Hv,joints:e,compiled:g}),cw&&lw(i));return g}(t,!0)}function ow(t){const e=t,n=e?.occupancy&&"object"==typeof e.occupancy?e.occupancy.placement:void 0;if(void 0===n)return t;void 0!==e.placement&&e.placement!==n&&iw("PLACEMENT_CONFLICT","placement",`the asset says ${String(e.placement)} and its room says ${String(n)}; keep one`);const{placement:i,...s}=e.occupancy;return{...e,placement:n,occupancy:s}}const aw=new WeakMap,cw=(()=>{try{return"1"===process.env.FIGURE_FREEZE_COMPILED}catch{return!1}})();function lw(t){if(t&&"object"==typeof t&&!Object.isFrozen(t)){Object.freeze(t);for(const e of Object.values(t))lw(e)}}function hw(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 dw=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"]:null,t.segments??null,hw(t),!1!==t.visible]);function uw(t,e){const n=function(t,e){const n=e??Jx(t.document).dependence,i=new Map(t.document.model.nodes.map(t=>[t.id,t])),s=qv(t),r=t=>{const e=void 0===t?void 0:i.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!r("string"==typeof n?.[0]?n[0]:t.id)||!!e&&r(s.get(e))}}(t,e),i=qv(t),s=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target));return t=>{const e=new Set;for(const r of t){if(!("pose"in r)||n(r))continue;const t=r.key?i.get(r.key):r.id;void 0!==t&&s.has(t)||e.add(r.id)}return e}}const pw=t=>`${hw(t)}|${!1!==t.visible?"shown":"hidden"}`;function fw(t,e={}){const n=[],i=new Map;for(const e of t){if(!("pose"in e))continue;const t="key"in e&&"string"==typeof e.key?e.key:void 0;if(!t){n.push(e.id);continue}const s=i.get(t)??[];s.push(e),i.set(t,s)}const s=[],r=[];for(const[t,e]of i){const i=new Map;for(const t of e){const e=dw(t),n=i.get(e);n?n.push(t.id):i.set(e,[t.id])}for(const[o,a]of i)a.length>1?s.push({key:`${t}|${o}`,member:t,ids:a}):(n.push(...a),r.push({member:t,ids:a,reason:1===e.length?"one-copy":"copies-differ"}))}const o=[];if(e.still?.size){const i=new Map(t.map(t=>[t.id,t])),s=new Map;for(const t of n){const n=i.get(t);if(!n||!e.still.has(t)||n.material.transparent)continue;const r=pw(n),o=s.get(r);o?o.push(t):s.set(r,[t])}const r=new Set;for(const[t,e]of s)e.length<2||(o.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 a=[];if(e.carried?.size){const i=new Map(t.map(t=>[t.id,t])),s=new Map;for(const t of n){const n=i.get(t),r=e.carried.get(t);if(!n||void 0===r||e.still?.has(t)||n.material.transparent)continue;const o=`${r}|${pw(n)}`,a=s.get(o);a?a.ids.push(t):s.set(o,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of s)n.length<2||(a.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)))}return{batches:s,merged:o,carried:a,alone:n,unbatched:r}}const mw=lb[0];function gw(t,e,n,i={}){const[s,r]=fb[e],o=i[s]??0,a=i[r]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[s],t[r]]);else if("ellipse"===t.kind){const e=t.radius[s],i=t.radius[r];c=Array.from({length:n},(t,s)=>{const r=2*Math.PI*s/n;return[e*Math.cos(r),i*Math.sin(r)]})}else{const e=t.size[s]/2,n=t.size[r]/2,i=t.corner?.[s]??0,o=t.corner?.[r]??0;if(i>0&&o>0){c=[];for(const[t,s,r]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=mw;a++){const l=r+a/mw*(Math.PI/2);c.push([t*(e-i)+i*Math.cos(l),s*(n-o)+o*Math.sin(l)])}}else c=[[-e,-n],[e,-n],[e,n],[-e,n]]}return c=c.map(([t,e])=>[t+o,e+a]),yw(c)<0?c.reverse():c}const yw=t=>t.reduce((e,n,i)=>e+n[0]*t[(i+1)%t.length][1]-t[(i+1)%t.length][0]*n[1],0)/2;function bw(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]),i=[];for(const t of e){for(;i.length>=2&&n(i[i.length-2],i[i.length-1],t)<=1e-9;)i.pop();i.push(t)}const s=[];for(let t=e.length-1;t>=0;t--){const i=e[t];for(;s.length>=2&&n(s[s.length-2],s[s.length-1],i)<=1e-9;)s.pop();s.push(i)}return i.slice(0,-1).concat(s.slice(0,-1))}const vw=t=>"shape"in t&&"pose"in t&&!!t.shape;function _w(t,e,n,i={}){const[s,r]=fb.y;return gw(t,"y",n,i).map(([t,n])=>{const i={x:0,y:e,z:0};return i[s]=t,i[r]=n,[i.x,i.y,i.z]})}const xw=[{id:"__default__",maxCount:1/0}];function ww(t){const e={id:h_({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function Mw(t,e){const n=e?.state?.type??e?.type;return t.accepts?!!n&&t.accepts.includes(n):!t.allowedTypes?.length||!!n&&t.allowedTypes.includes(n)}function Sw(e){var n;return n=class extends e{get slotLayout(){}get slots(){const t=this.slotLayout;if(!t)return[];const e=[];for(const n of u_(t)){const i=l_(t,n);i&&e.push(ww(i))}return e}slotById(t){const e=this.slotLayout;if(e){const n=d_(t),i=n?l_(e,n):null;return i?ww(i):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,i){const s=this.slotLayout,r=s?d_(t):null,o=r?l_(s,r):null,a=o?v_(e,o,n,i):null;return a?{...a,anchorId:o.anchorId}:null}get arrangementStrategy(){return sb}canReceive(t,e){const n=null!==(void 0!==e?.slotId?this._slotIfAvailable(this.slotById(e.slotId),t):this.findSlot(t));return Gu.log({role:"target",contract:"canReceive",component:this,args:{carrier:Qy(t)},result:n}),n}findSlot(t){const e=this.slots.length?this.slots:xw;for(const n of e){if(!Mw(n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),i=this._countOccupied(n.id);if(!(i>=e))return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:{slotId:n.id,occupied:i,max:e}}),n}return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:null}),null}acceptanceRotation(t,e){}deliveryWorldRotation(e){const n=this.acceptanceRotation?.(e);if(!n)return;const i=this._realObject?.object3d;if(!i)return;i.updateWorldMatrix(!0,!1);const s=new t.Quaternion;i.getWorldQuaternion(s);const r=new t.Quaternion(n.x,n.y,n.z,n.w);return s.clone().multiply(r)}deliveryWorldPosition(e){const n=this._realObject,i=n?.object3d;if(!i)return;i.updateWorldMatrix(!0,!1);const s=new t.Vector3;i.getWorldPosition(s);const r=this._receivingSurfaceLocalY();if(null!==r){const e=new t.Vector3(0,r,0);return i.localToWorld(e),{x:s.x,y:e.y,z:s.z}}return{x:s.x,y:s.y,z:s.z}}attachPointFor(t){const e=t?.[tb];if(!e)return null;const n=this.slots.find(t=>t.id===e);return n?{position:n.localPosition??{x:0,y:0,z:0},rotation:n.localRotation??{x:0,y:0,z:0},slotId:n.id}:null}placementFor(t,e={}){const n=t&&"object"==typeof t&&"state"in t?t:void 0,i=n?n.state??{}:t??{},s={width:Number(i.width)||0,height:Number(i.height)||0,depth:Number(i.depth)||0},r=e.slot??this.slots.find(t=>{const e=t.maxCount??this.arrangementStrategy.capacity(t);return this._countOccupied(t.id)<e});if(!r)return null;const o=e.index??this._countOccupied(r.id),a=e.occupantCount??o,c=this.arrangementStrategy.positionAt(o,r,a,n??{state:{...s}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+s.width/2-l/2,u=c.y+s.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-s.depth/2:s.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:r.localPosition&&Number.isFinite(r.localPosition.z)?r.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??s,r)??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 i=this._realObject,s=i?.receivingSurfaceY??0,r=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===s&&!r)return null;const o=Number(e)||0,a=i?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-o/2:o/2)+(i?.geometricOffsetY??0)-s}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!Mw(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?.[tb]===t).length;const n=this.components;return n?n.filter(e=>e.parent===this&&e[tb]===t).length:0}},n.__hasCapacity=!0,n}function Aw(t,e){const n=t.left??0,i=t.top??0,s=t.width??0,r=t.height??0;if(s<=0||r<=0)return[];const o="number"==typeof t.rotation?t.rotation:0,a=Math.cos(o),c=Math.sin(o),l=n+s/2,h=i+r/2,d="inbound"===e?-1:1;return[{lx:-s/2,lz:0,odx:-1,odz:0},{lx:s/2,lz:0,odx:1,odz:0},{lx:0,lz:-r/2,odx:0,odz:-1},{lx:0,lz:r/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?r/2:s/2}})}function Ew(t,e){const n=t.left??0,i=t.top??0,s=t.width??0,r=t.height??0;if(s<=0||r<=0)return{inbounds:[],outbounds:[]};const o="number"==typeof t.rotation?t.rotation:0,a=e??"reverse"===t.status,c="vertical"===t.orientation||"horizontal"!==t.orientation&&s<r,l=n+s/2,h=i+r/2,d=c?r/2:s/2,u=c?0:1,p=c?1:0,f=Math.cos(o),m=Math.sin(o),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?s:r)/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 kw(t){const e=t.left??0,n=t.top??0,i=t.width??0,s=t.height??0;if(i<=0||s<=0)return null;const r="number"==typeof t.rotation?t.rotation:0,o="vertical"===t.orientation||"horizontal"!==t.orientation&&i<s,a=e+i/2,c=n+s/2,l=o?s/2:i/2,h=Math.cos(r),d=Math.sin(r),u=(t,e)=>({x:a+t*h-e*d,z:c+t*d+e*h});return{start:o?u(0,-l):u(-l,0),end:o?u(0,l):u(l,0)}}function Cw(t){const e=t.cx??0,n=t.cy??0,i=Math.abs(t.rx??100),s=Math.abs(t.ry??100),r=t.ratio??50,o=(i+i*r/100)/2,a=(s+s*r/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(i<=0||s<=0)return{inbounds:[],outbounds:[]};const d={x:e+o*Math.sin(c),z:n-a*Math.cos(c)},u={x:e+o*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 Tw(t){const e=Ew(t),n=e.outbounds[0];if(!n)return{inbounds:Aw(t,"inbound"),outbounds:[]};const i=Aw(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,i=t.worldPos.z-n.worldPos.z;return Math.hypot(e,i)>1}),s=n.direction,r=[];for(const t of i){const e=t.direction.x*s.x+t.direction.z*s.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+s.x,i=t.direction.z+s.z,o=Math.hypot(n,i)||1;r.push({worldPos:t.worldPos,direction:{x:n/o,z:i/o},halfSpan:t.halfSpan})}return{inbounds:[...i,...r],outbounds:e.outbounds}}function Ow(t,e,n={}){const i=n.distance??5,s=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<s)return!1;const r=t.worldPos.x-e.worldPos.x,o=t.worldPos.z-e.worldPos.z;if("number"==typeof t.halfSpan&&"number"==typeof e.halfSpan){const n=t.direction.x,s=t.direction.z;if(Math.abs(r*n+o*s)>i)return!1;const a=Math.abs(r*-s+o*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(r,o)<=i}function Pw(t,e,n,i=0){const s=n.width??0,r=n.height??0;if(s<=0||r<=0)return!1;const o=(n.left??0)+s/2,a=(n.top??0)+r/2,c="number"==typeof n.rotation?n.rotation:0,l=Math.cos(-c),h=Math.sin(-c),d=t-o,u=e-a,p=d*l-u*h,f=d*h+u*l;return Math.abs(p)<=s/2+i&&Math.abs(f)<=r/2+i}function Iw(t,e,n){const i=n.width??0,s=n.height??0;if(i<=0||s<=0)return 1/0;const r=(n.left??0)+i/2,o=(n.top??0)+s/2;let a=t.x-r,c=t.z-o,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,i=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=i}const u=i/2,p=s/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 Dw(t,e,n,i=6){return!!Pw(t.worldPos.x,t.worldPos.z,e,i)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function zw(t,e,n){return t.outbounds.map(t=>{const i=[];for(const s of e){let e=null;for(const i of s.topology.inbounds){if(!Ow(t,i,n))continue;const s=t.worldPos.x-i.worldPos.x,r=t.worldPos.z-i.worldPos.z,o=Math.hypot(s,r);(null===e||o<e)&&(e=o)}if(null===e&&s.bounds){const i=s.topology.outbounds[0]?.direction,r=!(s.topology.outbounds&&s.topology.outbounds.length)?n?.sinkMargin??30:6;if(Dw(t,s.bounds,i,r)){const n=Iw(t.worldPos,t.direction,s.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(s.bounds.left??0)+(s.bounds.width??0)/2,i=(s.bounds.top??0)+(s.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-i)+1e3}}}null!==e&&i.push({id:s.id,dist:e})}return 0===i.length?null:(i.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),i[0].id)})}function Rw(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const i=new Map,s=new Set;for(const n of t){const r=t.filter(t=>t.id!==n.id),o=zw(n.topology,r,e);i.set(n.id,o);for(const t of o)null!=t&&s.add(t)}const r=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const r=i.get(t)??[];r.includes(e)||(r.push(e),i.set(t,r),s.add(e))};for(const e of t)if(e.links){for(const t of e.links.downstream??[])r(e.id,t);for(const t of e.links.upstream??[])r(t,e.id)}const o=new Set,a=new Set;for(const e of t){(i.get(e.id)??[]).some(t=>null!=t)||o.add(e.id),s.has(e.id)||a.add(e.id)}return{nodes:n,out:i,sinks:o,sources:a}}function jw(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const i=new Set([e]);for(const s of function(t,e,n){const i=n.get(e);if(i)return i;const s=new Set,r=[e],o=new Set([e]);for(;r.length;){const e=r.shift();for(const n of t.out.get(e)??[])null!=n&&(s.add(n),o.has(n)||(o.add(n),r.push(n)))}return n.set(e,s),s}(t,e,n))i.add(s);return i})}function Lw(t,e,n,i){return e===n?0:function(t,e,n){const i=n.get(e);if(i)return i;const s=new Map([[e,0]]),r=[e];for(;r.length;){const e=r.shift(),n=s.get(e);for(const i of t.out.get(e)??[])null==i||s.has(i)||(s.set(i,n+1),r.push(i))}return n.set(e,s),s}(t,e,i).get(n)??1/0}function Fw(t,e,n){const i=t.out.get(e)??[],s=new Map,r=[];for(let e=0;e<i.length;e++){const o=i[e];if(null==o)continue;const a=o===n?0:Lw(t,o,n,s);a!==1/0&&r.push({i:e,hops:1+a})}return r.sort((t,e)=>t.hops-e.hops||t.i-e.i),r.map(t=>t.i)}function Nw(t,e,n){const i=Fw(t,e,n);return i.length?i[0]:-1}function $w(t,e,n){return e===n||Fw(t,e,n).length>0}function Hw(t,e){const n=new Set;for(const i of jw(t,e))for(const e of i)t.sinks.has(e)&&n.add(e);return n}function Bw(t,e,n){return Yw(t,e,n).map(t=>t.index)}function Yw(t,e,n){const i=n instanceof Set?n:new Set(n);if(0===i.size)return[];const s=t.out.get(e)??[],r=new Map,o=[...i].sort(),a=[];for(let e=0;e<s.length;e++){const n=s[e];if(null==n)continue;let i=1/0,c="";for(const e of o){const s=1+(n===e?0:Lw(t,n,e,r));s<i&&(i=s,c=e)}i!==1/0&&a.push({index:e,hops:i,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function Gw(t,e={}){const n=[],i=e.loopCapableIds??new Set,s=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const i=t.nodes.get(e);if(!i||!i.topology.outbounds?.length)continue;(t.out.get(e)??[]).some(t=>null!=t)||n.push({severity:"error",code:"orphan-source",nodeId:e,message:`source 노드 "${e}" 가 outgoing edge 0 — 아무 데도 carrier 를 보낼 수 없음`})}for(const e of[...t.nodes.keys()].sort()){(t.out.get(e)??[]).some(t=>null!=t)||(s.has(e)||t.sources.has(e)||n.push({severity:"error",code:"dead-end",nodeId:e,message:`노드 "${e}" 가 outgoing 0 인데 RoutingTarget 자격 없음 — routing 미정의 종착`}))}const r=function(t){const e=[],n=[...t.nodes.keys()].sort(),i=new Set,s=[],r=new Set,o=n=>{i.add(n),s.push(n),r.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(r.has(a)){const t=s.indexOf(a),n=s.slice(t),i=n.indexOf([...n].sort()[0]),r=[...n.slice(i),...n.slice(0,i)],o=r.join("→");e.some(t=>t.join("→")===o)||e.push(r)}else i.has(a)||o(a);s.pop(),r.delete(n)};for(const t of n)i.has(t)||o(t);return e.sort((t,e)=>t[0].localeCompare(e[0])||t.length-e.length),e}(t);for(const t of r){const e=t.some(t=>i.has(t));e||n.push({severity:"error",code:"cycle",cycle:t,message:`의도 cycle 자격 (isLoop) 없는 cycle: ${t.join(" → ")} → ${t[0]}`})}const o=e.routingWeights;if(o)for(const[t,e]of[...o].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[...s].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 Vw(t,e){if(!t)return[];const n=[],i=new Set,s=t=>{if(!t||i.has(t))return;if(i.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,i=t.refid??t.state?.refid,s="string"==typeof e&&e.length>0?e:null!=i?String(i):void 0;if(s)try{const e=t.getSegmentTopology(),i=t.state??{},r={left:i.left,top:i.top,width:i.width,height:i.height,rotation:i.rotation};e&&n.push({id:s,topology:e,bounds:r})}catch{}}const r=t?.components;if(Array.isArray(r))for(const t of r)s(t)};return s(t),n}function Uw(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 i=t.getSegmentTopology();if(!i||0===i.outbounds.length)return null;const s=zw(i,Vw(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),e);for(const t of s)if(t)return t;return null}function Ww(t){return!!t&&"function"==typeof t.routingConstraints}function qw(t){return!!t&&"function"==typeof t.acceptedCarrierData}function Xw(t,e=16){const n=[],i=t.parent??t.rootModel??t.root;if(!i)return n;const s=Uw(t);if(!s)return n;const r=Jw(i,s);if(!r)return n;const o=[{segment:r,accumulated:{},pathIds:[s],visited:new Set([s])}];for(;o.length>0;){const t=o.shift();if(t.pathIds.length>e)continue;const s=Ww(t.segment)?t.segment.routingConstraints():null;if(s&&s.length>0)for(const e of s)for(const s of e.candidates){const r=Kw(t.accumulated,s);if(!r)continue;const a=Qw(t.segment,e.portId,i);a&&!t.visited.has(a.state?.id??"")?o.push({segment:a,accumulated:r,pathIds:[...t.pathIds,a.state?.id??"?"],visited:new Set([...t.visited,a.state?.id??""])}):n.push({data:r,weight:1,pathIds:[...t.pathIds,`${e.portId}`],destination:e.portId})}else{if(qw(t.segment)){const e=t.segment.acceptedCarrierData(),i=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:i});else for(const s of e){const e=Kw(t.accumulated,s);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:i})}continue}const e=Uw(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 s=Jw(i,e);if(!s)continue;o.push({segment:s,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function Kw(t,e){const n={...t};for(const[t,i]of Object.entries(e)){if(t in n&&n[t]!==i)return null;n[t]=i}return n}function Qw(t,e,n){if("straight"===e&&t.state?.downstreamRef)return Jw(n,t.state.downstreamRef);const i=Jw(n,e);if(i)return i;const s=Uw(t);return s?Jw(n,s):null}function Jw(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,i=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const s=t.components;if(Array.isArray(s))for(const t of s){const e=i(t);if(e)return e}return null};return i(t)}function Zw(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function tM(t,e,n=5,i=[],s=n){const r=t.length,o=new Array(r).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 i){const e=Array.isArray(t),n=e?t:t.positions,i=e?void 0:t.kind;if(!n.length)continue;const s=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:s});i&&u.set(s,i)}const p=(t,e)=>{const i=c(t,e),s=h.get(`${t}:${"end"===e?"start":"end"}`),r=[];for(const t of d)Zw(t.pos,i)<=n&&!r.includes(t.pt)&&r.push(t.pt);for(let t=0;t<l.length;t++)Zw(l[t].pos,i)<=n&&!r.includes(t)&&r.push(t);let o=r.find(t=>t!==s)??-1;o<0&&(o=l.length,l.push({pos:i,members:[]})),l[o].members.push({seg:t,end:e}),h.set(`${t}:${e}`,o)};for(let t=0;t<r;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 i=0;i<l.length;i++){const s=Zw(l[i].pos,t);s<n&&(n=s,e=i)}for(const i of d){const s=Zw(i.pos,t);s<n&&(n=s,e=i.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:i}=t(n.pos);e>=0&&i<=s&&(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!==o[t],b=[],v=(e,n)=>{if(void 0===o[e])return o[e]=n,void b.push(e);o[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 i=l[n];if(2!==i.members.length||f.has(n))continue;const s=i.members[0],r=s.seg===t&&s.end===e?i.members[1]:s;if(r.seg===t)continue;const a="end"===e!==o[t],c="end"===r.end!==!a;v(r.seg,c)}},x=()=>{for(;b.length;)_(b.shift())},w=t=>{let e=-1,n="start",i=1/0;for(let s=0;s<r;s++)for(const r of["start","end"]){const o=Zw(c(s,r),t.pos);o<i&&(i=o,e=s,n=r)}if(e<0||i>s)return;const o="source"===t.kind?"end"===n:"start"===n;v(e,o)};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===o[t.seg]);if(1!==e.length)continue;let n=0,i=0;for(const e of t.members)void 0!==o[e.seg]&&(y(e.seg,e.end)?n++:i++);const s=e[0];let r;0===i&&n>0?r="end"===s.end:0===n&&i>0&&(r="start"===s.end),void 0!==r&&(o[s.seg]=r,b.push(s.seg),x(),M=!0)}}if(o.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 i of t)e[i]=0,n.push(i);for(;n.length;){const t=n.shift();for(const i of l[t].members){const s=h.get(`${i.seg}:${"start"===i.end?"end":"start"}`);void 0!==s&&e[s]>e[t]+1&&(e[s]=e[t]+1,n.push(s))}}return e},e=t(m),n=t(g);for(let t=0;t<r;t++){if(void 0!==o[t])continue;const i=h.get(`${t}:start`),s=h.get(`${t}:end`);if(void 0===i||void 0===s)continue;if(l[i].members.length<2||l[s].members.length<2)continue;if(e[i]===1/0||e[s]===1/0||n[i]===1/0||n[s]===1/0)continue;let r;e[i]!==e[s]?r=e[i]<e[s]:n[i]!==n[s]&&(r=n[s]<n[i]),void 0!==r&&(o[t]=!r,b.push(t))}x()}const S=new Map;for(let e=0;e<r;e++)S.set(t[e].id,void 0===o[e]?"unknown":o[e]?"reverse":"forward");return{directions:S,conflicts:[...a]}}function eM(...t){}function nM(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function iM(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*sM(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*sM(t)}function rM(t,e,n){const i=e.width??0,s=e.height??0;if(i<=0||s<=0)return!1;const r=(e.left??0)+i/2,o=(e.top??0)+s/2,a="number"==typeof e.rotation?e.rotation:0,c=t.x-r,l=t.z-o,h=Math.cos(-a),d=Math.sin(-a),u=c*h-l*d,p=c*d+l*h;return Math.abs(u)<=i/2+n&&Math.abs(p)<=s/2+n}function oM(t){const e=[],n=[],i=[],s=[];for(const r of sM(t)){const t=iM(r);if(!t)continue;if(r.flowOrientable){const n=kw(r.state??{});n&&e.push({id:t,start:n.start,end:n.end});continue}if("function"==typeof r.openings){const t=r.state??{};(t.width??0)>0&&(t.height??0)>0&&s.push(t);continue}let o;try{o=r.getSegmentTopology()}catch{continue}if(!o)continue;const a=o.inbounds??[],c=o.outbounds??[],l="function"==typeof r.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&&i.push({positions:t})}}for(const t of s){const s=[];for(const n of e)for(const e of[n.start,n.end])rM(e,t,16)&&s.push(e);let r=!1,o=!1;for(const e of n)rM(e.pos,t,16)&&("sink"===e.kind?r=!0:o=!0);const a=r&&!o?"sink":o&&!r?"source":void 0;(s.length>=2||a&&s.length>=1)&&i.push({positions:s,kind:a})}if(0===e.length||0===n.length)return new Map;return tM(e,n,8,i,60).directions}function aM(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:oM(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const i=iM(t),s=i?n.map.get(i):void 0;return"reverse"===s||"forward"!==s&&void 0}function cM(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function lM(t,e,n,i){if(!t||!e)return null;const s=[],r=t=>{if(!t||t===i)return;if(Wm(t,e)&&cM(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&&s.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const o=t.components;if(Array.isArray(o))for(const t of o)r(t)};return r(t),0===s.length?null:(s.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),s[0])}function hM(t){return!!t&&"function"==typeof t.routingDestination}function dM(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*uM(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*uM(t)}function pM(t){const e=[],n=new Map,i=new Map,s=new Set,r=[];for(const o of uM(t)){"function"==typeof o?.registerWithHost&&r.push(o);const t="function"==typeof o?.getSegmentTopology,a="function"==typeof o?.routingLinks?o.routingLinks():void 0,c=!(!a||!((a.downstream?.length??0)>0||(a.upstream?.length??0)>0));if(!(t||hM(o)||c||cM(o)))continue;const l=dM(o);if(!l)continue;let h={inbounds:[],outbounds:[]};if(t){try{h=o.getSegmentTopology()}catch{continue}if(!h)continue}const d=o.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}),i.set(l,o),hM(o)){s.add(l);const t=o.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:i,routingTargetIds:s,stationClients:r}}function fM(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:i,components:s,routingTargetIds:r,stationClients:o}=pM(t),a=Rw(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 i=[...e].sort((t,e)=>{const n=dM(t)??"",i=dM(e)??"";return n.localeCompare(i)});for(const e of i){const n=e.declaredHostRef?.();let i=null;if(n&&(i=t.findById?.(n)??null),!i){const n=e.hostCapability?.(),s=e.hostFacingPoint?.();n&&s&&(i=lM(t,n,s,e)?.component??null)}i&&"function"==typeof e.registerWithHost&&e.registerWithHost(i)}const s=e=>{if(!e)return;if(cM(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const i=t.findById?.(n);i&&e.registerDivertStation(n,i)}const n=e.components;if(Array.isArray(n))for(const t of n)s(t)};s(t)}(t,o);const c=new Set;for(const[t,e]of s){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of r){const e=s.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=Gw(a,{routingTargetIds:r,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:i,components:s,issues:h},t.__flowGraph=e}return e}function mM(t){return fM(t)?.issues??[]}function gM(t){const e=fM(t);return e&&e.graph.nodes.size>0?e.graph:null}function yM(t,e){return fM(t)?.destToSinks.get(e)??[]}function bM(t,e){return fM(t)?.components.get(e)}function vM(t){const e=fM(t);return e?[...e.destToSinks.keys()]:[]}function _M(t){return dM(t)}function xM(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 wM(t,e,n,i,s){if(1===i.length)return i[0];switch(t){case"index":default:return i[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),i[t%i.length]}case"weight":{const t=i.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}(s.get(t.target))),r=t.reduce((t,e)=>t+e,0);if(r<=0)return i[0];const o=n.counters.get(e)??0;n.counters.set(e,o+1);let a=o%r;for(let e=0;e<i.length;e++){if(a<t[e])return i[e];a-=t[e]}return i[i.length-1]}case"utilization":{let t=1/0,e=i[0];for(const n of i){const i=xM(s.get(n.target));i<t&&(t=i,e=n)}return e}}}function MM(t,e,n){const i=t?.root;if(!i)return null;const s=e?.state?.meta?.destination;if("string"!=typeof s||0===s.length)return null;const r=fM(i);if(!r||0===r.graph.nodes.size)return null;const o=dM(t);if(!o)return null;let a=r.destToSinks.get(s)??[];0===a.length&&(a=[s]);const c=Yw(r.graph,o,a);if(0===c.length)return null;const l=r.graph.out.get(o)??[],h=c.filter(t=>{const n=l[t.index],i=n?r.components.get(n):null;return!i||"function"!=typeof i.canReceive||i.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 i=e?.state?.routingBalancingPolicy;return i||"round-robin"}(t,i),u=wM(d,o,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(i),h,r.components);return l[u.index]??null}Km({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"}),Km({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,gM(t)}catch{return null}}}catch{}function SM(t,e,n){const i=MM(t,e,n);if(null==i)return null;const s=t?.root,r=bM(s,i)??s?.findById?.(i)??null;return r?{targetId:i,component:r,origin:"explicit"}:null}function AM(t){const e=t?.root,n=gM(e),i=_M(t);if(!n||!i)return null;const s=(n.out.get(i)??[]).find(Boolean);if(!s)return null;const r=bM(e,s)??e?.findById?.(s)??null;return r?{id:s,component:r}:null}function EM(t){const e=_M(t);return e?kM(t?.root,e):[]}function kM(t,e){if(!t||!e)return[];const n=gM(t);if(!n)return[];const i=new Set;for(const s of Hw(n,e)){const e=bM(t,s);if(hM(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&i.add(t)}}return[...i]}function CM(t,e){if(!t||!e)return[];const n=gM(t);if(!n)return[];const i=new Map;for(const t of n.out.values())for(const e of t)null!=e&&i.set(e,(i.get(e)??0)+1);const s=new Map;for(const r of Hw(n,e)){const e=bM(t,r);if(!hM(e))continue;const n=e.routingDestination();if("string"!=typeof n||0===n.length)continue;let o=null;if("function"==typeof e.routingWeight){const t=e.routingWeight();"number"==typeof t&&Number.isFinite(t)&&t>0&&(o=t)}null===o&&(o=i.get(r)??0,0===o&&(o=1)),s.set(n,(s.get(n)??0)+o)}return[...s].map(([t,e])=>({value:t,weight:e}))}function TM(t){return gM(t)}function OM(t){const e=gM(t);if(!e)return[];const n=new Set,i=new Set,s=t=>{if(!t)return;const r=_M(t);if(r&&e.nodes.has(r)){hM(t)&&n.add(r);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&i.add(r)}const o=t.components;if(Array.isArray(o))for(const t of o)s(t)};return s(t),Gw(e,{routingTargetIds:n,loopCapableIds:i})}function PM(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 i=0;for(const e of t)if(i+=e.weight,n<i)return e.value;return t[t.length-1].value}const IM={next:SM,downstream:AM,reachableDestinations:EM,reachableDestinationsFrom:kM,reachableDestinationsWeightedFrom:CM,pickWeightedDestination:PM,graphFor:TM,validate:OM};function DM(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 i=t.prototype?.attachPointFor;return"function"==typeof i?i.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,!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&&(this._items.splice(n,1),t.parent=null,!e)){if("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=t.parent;n&&("function"==typeof n.removeComponent&&-1!==n._components?.indexOf?.(t)&&n.removeComponent(t,!0),n!==this&&"function"==typeof n.removeItem&&-1!==n._items?.indexOf?.(t)&&n.removeItem(t,!0));const i=-1===this._items.indexOf(t);if(i&&this._items.push(t),t.parent=this,i&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}const s=t._realObject,r=s?.object3d;if(r){let n,i,o=e?.toParent3D,a="world-preserve";if(!o){const s=this.attachPointFor?.(t,{slotId:e?.slotId});s?.attach&&(o=s.attach,n=s.localPosition,i=s.localRotation,a=s.carryPolicy??"world-preserve")}o&&r.parent!==o&&(o.updateWorldMatrix?.(!0,!1),r.updateWorldMatrix?.(!0,!1),o.attach(r),s.suppressTransform=!0),o&&(n&&r.position.set(n.x,n.y,n.z),"world-preserve"!==a?i?r.rotation.set(i.x,i.y,i.z):r.quaternion.identity():i&&r.rotation.set(i.x,i.y,i.z),s?.setTransientPlacement?.({policy:"carried",meta:{carryPolicy:a}}))}t.held?.(this),this._bumpReceived?.(t)}handoverOut(t){this.removeItem(t),this._bumpDispatched?.(t)}dispose(){const t=this._items.slice();this._items.length=0;for(const e of t)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,i,s){for(let r=this._items.length-1;r>=0;r--){const o=this._items[r],a="static"===o.position?o.capture?.(t,e,s):o.capture?.(n,i,s);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 i=e.bounds;!e.showOverflow&&i&&(t.beginPath(),t.rect(i.left,i.top,i.width,i.height),t.clip(),t.closePath());const{left:s=0,top:r=0}=e.state??{};t.translate(s,r),this._drawItems(t),t.translate(-s,-r),t.restore()}capture(t,e,n){const i=this,s=this._items;if(s&&s.length>0&&(!i.app||i.app.isEditMode||!i.hidden)){const s=i.fromParent?.(t,e);if(s&&i.contains?.(s.x,s.y)){const r=i.bounds,o=this._captureItems(s.x-r.left,s.y-r.top,t,e,n);if(o)return o}}return super.capture?.(t,e,n)}},e.capabilities=Object.freeze([...t.capabilities??[],"Holdable"]),e}function zM(e){var n;return(n=class extends e{reserve(t,e){const n=this.findSlot(t);return n?{slot:n,token:Symbol("slot-reservation")}:null}release(t){}async receive(t,e={}){Gu.log({role:"target",contract:"receive:enter",component:this,args:{carrier:Qy(t),options:e}});const n=this.reserve(t,e);if(!n){Gu.log({role:"target",contract:"receive:reject",component:this,args:{carrier:Qy(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(e,n,i={}){const s=e.slot,r=this._countOccupied(s.id),o=this.arrangementStrategy.positionAt(r,s,r,n);Gu.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:r,slotId:s.id,occupantCount:r,carrier:Qy(n)},result:o}),n[tb]=s.id;const a=n._realObject;let c,l;a?.object3d&&(a.object3d.updateWorldMatrix(!0,!1),c=new t.Vector3,l=new t.Quaternion,a.object3d.getWorldPosition(c),a.object3d.getWorldQuaternion(l));const{animated:h=!1,duration:d,ease:u}=i;"function"==typeof this.handoverIn?this.handoverIn(n,{slotId:s.id}):this.reparent?.(n,{animated:h,duration:d,ease:u}),!h&&n._realObject&&(n._realObject.suppressTransform=!1);{const t={},e=this.placementFor?.(n,{slot:s,index:r,occupantCount:r})??null;if(Gu.log({role:"target",contract:"placementFor",component:this,args:{carrier:Qy(n),slotId:s.id,index:r},result:e}),e){const i=n.state??{},r=this.state??{};t.left=e.position.x-(Number(i.width)||0)/2+(Number(r.width)||0)/2,t.top=e.position.z-(Number(i.height)||0)/2+(Number(r.height)||0)/2;const o=this._zPosFromSeatY(e.position.y,i.depth,s);null!==o&&(t.zPos=o),e.rotation&&Zy(t,e.rotation)}else{o&&(t.left=o.x,t.top=o.y);if(0!==(this._realObject?.receivingSurfaceY??0))t.zPos=0;else if(s.localPosition&&Number.isFinite(s.localPosition.z)){const e=this._realObject?.geometricOffsetY??0;t.zPos=s.localPosition.z+e}const e=this.acceptanceRotation?.(n,s);Gu.log({role:"target",contract:"acceptanceRotation",component:this,args:{carrier:Qy(n),slotId:s.id},result:e}),e&&Zy(t,e)}const i=this.normalizePose?.(n,s);"function"==typeof this.normalizePose&&Gu.log({role:"target",contract:"normalizePose",component:this,args:{carrier:Qy(n),slotId:s.id},result:i}),i&&Object.assign(t,i),Object.keys(t).length&&(n.setState?.(t),Gu.log({role:"target",contract:"receive:setState",component:this,args:{carrier:Qy(n),keys:Object.keys(t)}}))}this.trigger("transfer-received",{type:"transfer-received",component:n,container:this,slotId:s.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),Gu.log({role:"target",contract:"receive:done",component:this,args:{carrier:Qy(n),slotId:s.id}})}async dispatch(t,e,n={}){const i=new qu({source:this,target:e,carrier:t,options:n,physical:async()=>{delete t[tb]}}),s=await i.execute();"rolled-back"!==s.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:s.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){const e=(()=>{const e=this.slots;if(!e.length)return{ok:!1,reason:"no-slots-defined"};const n=this.findSlot(t);if(!n){const n=t?.state?.type??t?.type;for(const t of e)if(!t.allowedTypes?.length||!n||t.allowedTypes.includes(n))return{ok:!1,reason:"all-slots-full"};return{ok:!1,reason:"type-not-accepted"}}return{ok:!0,slot:n}})();return Gu.log({role:"target",contract:"canAccept",component:this,args:{carrier:Qy(t)},result:e.ok?{ok:!0,slotId:e.slot.id}:{ok:!1,reason:e.reason}}),e}accept(t,e){return this.receive(t,e)}}).__hasTransferable=!0,n}function RM(t){var e;const n=!!t.__hasCapacity,i=!!t.__hasTransferable,s=n?t:Sw(t),r=i?s:zM(s),o=[...t.capabilities??[]];n||o.push("Capacity","PlacementSurface"),i||o.push("Transferable"),o.push("Holdable","FlowNode");const a=(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=class extends(DM(r)){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()}}},"FlowNodeMixed"),e.capabilities=Object.freeze(o),e.isFlowNode=!0,e);return nb(a)}function jM(t){return!!t&&!0===t.isFlowNode}Km({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"}),Km({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"}),Km({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 LM={x:0,y:0,z:0,w:1};function FM(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function NM(t,e){const n=t.rotation,i=e.rotation,s=e.position,r=n.w*s.x+n.y*s.z-n.z*s.y,o=n.w*s.y+n.z*s.x-n.x*s.z,a=n.w*s.z+n.x*s.y-n.y*s.x,c=-n.x*s.x-n.y*s.y-n.z*s.z,l=r*n.w+c*-n.x+o*-n.z-a*-n.y,h=o*n.w+c*-n.y+a*-n.x-r*-n.z,d=a*n.w+c*-n.z+r*-n.y-o*-n.x,u={x:n.w*i.x+n.x*i.w+n.y*i.z-n.z*i.y,y:n.w*i.y-n.x*i.z+n.y*i.w+n.z*i.x,z:n.w*i.z+n.x*i.y-n.y*i.x+n.z*i.w,w:n.w*i.w-n.x*i.x-n.y*i.y-n.z*i.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const $M={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 HM(t){const{carrierWorld:e,width:n,depth:i,entryHeight:s,mountLocalY:r,approachDistance:o,sides:a,toolType:c,tolerance:l,priority:h}=t,d="number"==typeof r?{position:{x:0,y:r,z:0},rotation:{...LM}}:void 0,u=n/2,p=i/2;return a.map(t=>{const n=$M[t],i="string"==typeof c?c:c[t]??"unknown",r={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:s,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:FM(n.yaw)},a={position:{x:r.position.x+n.axis.x*o,y:s,z:r.position.z+n.axis.z*o},rotation:FM(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:i,approach:NM(e,a),engage:NM(e,r),...d?{mount:d}:{},tolerance:l,priority:h}})}function BM(t){const{carrierWorld:e,topY:n,approachDistance:i,toolType:s,mountLocalY:r,tolerance:o,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...LM}};return{id:c??"top",toolType:s,approach:NM(e,{position:{x:0,y:n+i,z:0},rotation:{...LM}}),engage:NM(e,l),..."number"==typeof r?{mount:{position:{x:0,y:r,z:0},rotation:{...LM}}}:{},tolerance:o,priority:a}}function YM(t,e){return t.filter(t=>t.toolType===e.toolType)}function GM(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,i=t.approach.position.y-e.y,s=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+i*i+s*s)}});return n.sort((t,e)=>{const n=t.f.priority??0,i=e.f.priority??0;return n!==i?n-i:t.dist-e.dist}),n[0].f}class VM{constructor(t){this.owner=t}positionAt(t,e,n,i){if(0!==t)return null;const s=this.owner?.state?.width??0,r=this.owner?.state?.height??0,o=i?.state?.width??0,a=i?.state?.height??0;return{x:Math.max(0,(s-o)/2),y:Math.max(0,(r-a)/2),z:0}}capacity(t){return t.maxCount??1}}let UM=1;function WM(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const qM={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class XM{constructor(t=qM){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-"+UM++},n=(this._byResource.get(e.resource)??[]).filter(t=>WM(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const i=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}});if(i.every(t=>"b-yields"===t.decision)){const i=n.slice();for(const t of i)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:i,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:i}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:i}}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=>WM(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 i=this._byReserver.get(t.reserverId);i||(i=[],this._byReserver.set(t.reserverId,i)),i.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 i=this._byReserver.get(t.reserverId);if(i){const e=i.findIndex(e=>e.id===t.id);e>=0&&i.splice(e,1),0===i.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const KM=new XM;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=KM);class QM{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 i of this.nodes.values()){const s=JM(i.position,t);s<n&&(n=s,e=i)}return e}}function JM(t,e){const n=t.x-e.x,i=t.y-e.y,s=t.z-e.z;return n*n+i*i+s*s}function ZM(t,e){return Math.sqrt(JM(t,e))}function tS(t,e,n={}){const i=new QM,s=n.defaultSpeed??100;for(const e of t){const t=e.geometry.centerPoints;if(t.length<2)continue;const n=`${e.id}:start`,r=`${e.id}:end`;i.addNode({id:n,position:t[0],type:"lane-start"}),i.addNode({id:r,position:t[t.length-1],type:"lane-end"}),i.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:r});let o=0;for(let e=1;e<t.length;e++)o+=ZM(t[e-1],t[e]);const a=o/(e.speedLimit??s)*1e3;i.addEdge({fromNode:n,toNode:r,resource:e.id,distance:o,durationMs:a,forward:!0}),"twoway"===e.direction&&i.addEdge({fromNode:r,toNode:n,resource:e.id,distance:o,durationMs:a,forward:!1})}for(const t of e){if(t.lanes.length<2)continue;const e=[];for(const n of t.lanes){const s=i.laneEndpoints.get(n);if(!s)continue;const r=i.nodes.get(s.startNodeId).position,o=i.nodes.get(s.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=i.laneEndpoints.get(e);if(!t)continue;const s=i.nodes.get(t.startNodeId).position,h=i.nodes.get(t.endNodeId).position;a+=Math.min(JM(r,s),JM(r,h)),c+=Math.min(JM(o,s),JM(o,h)),l++}if(0===l)continue;const h=a<c?s.startNodeId:s.endNodeId;e.push({laneId:n,nodeId:h,pos:i.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let s=0;s<e.length;s++){if(n===s)continue;const r=e[n],o=e[s],a=ZM(r.pos,o.pos);i.addEdge({fromNode:r.nodeId,toNode:o.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return i}function eS(t,e,n,i={}){const s=t.nodes.get(e),r=t.nodes.get(n);if(!s||!r)return null;const o=i.speed?.max??100,a=e=>{const n=t.nodes.get(e);var i,s;return(i=n.position,s=r.position,Math.sqrt(function(t,e){const n=t.x-e.x,i=t.y-e.y,s=t.z-e.z;return n*n+i*i+s*s}(i,s)))/o*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=i.startSimMs??0,p=i.deadlineSimMs;for(;l.size>0;){let e=null,i=null;for(const t of l){const n=c.get(t);(!i||n.fScore<i.fScore||n.fScore===i.fScore&&t<e)&&(i=n,e=t)}if(!i||!e)return null;if(e===n){const t=[];let e=i,n=0;for(;e&&e.cameFromEdge;){const i=e.cameFromEdge,s=u+(e.gScore-i.durationMs);t.unshift({resource:i.resource,timeWindow:{startSimMs:s,endSimMs:s+i.durationMs},fromPos:i.fromPos,toPos:i.toPos}),n+=i.distance,e=c.get(i.fromNodeId)}const s=i.gScore;return void 0!==p&&u+s>p?null:{segments:t,totalDurationMs:s,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=i.gScore+n.durationMs,s=c.get(n.toNode);if(!s||e<s.gScore){const i=t.nodes.get(n.fromNode),s=t.nodes.get(n.toNode),r={nodeId:n.toNode,gScore:e,fScore:e+a(n.toNode),cameFromEdge:{fromNodeId:n.fromNode,resource:n.resource,distance:n.distance,durationMs:n.durationMs,fromPos:i.position,toPos:s.position}};c.set(n.toNode,r),l.add(n.toNode)}}}return null}function nS(t,e,n=0,i){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:i}))}const iS={closed:!0,round:0,divisions:24};class sS{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const i=t[e].x-t[e-1].x,s=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(i*i+s*s))}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 i=this.cumulative;let s=0,r=i.length-2;for(;s<r;){const t=s+r>>1;i[t+1]<=n?s=t+1:r=t}const o=i[s+1]-i[s],a=o>0?(n-i[s])/o:0,c=this.points[s],l=this.points[s+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 rS(t,e={}){const n={...iS,...e},i=t.length;if(0===i)return new sS([],n.closed);if(1===i)return new sS([{x:t[0].x,y:t[0].y}],n.closed);const s=[],r=(t,e)=>{if(s.length>0){const n=s[s.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}s.push({x:t,y:e})},o=(n.closed,i);for(let e=0;e<o;e++){const s=0===e?n.closed?i-1:-1:e-1,o=e===i-1?n.closed?0:-1:e+1,a=s>=0?t[s]:null,c=t[e],l=o>=0?t[o]:null;if(a&&a.x===c.x&&a.y===c.y)continue;const h=a&&l?Zr(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(r(d,u),h>0&&a&&l)for(let t=1;t<=n.divisions;t++){const e=t/n.divisions,i=1-e;r(i*i*d+2*i*e*c.x+e*e*p,i*i*u+2*i*e*c.y+e*e*f)}else d===p&&u===f||r(p,f);if(l&&Xr(c)){const t=Zr(l,n.round),e=Math.sqrt((c.x-l.x)**2+(c.y-l.y)**2),i=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,s=Math.min(t,e/2),o=Kr({x:p,y:f},{x:Math.sin(i)*s+l.x,y:Math.cos(i)*s+l.y},c.bulge);if(o){let t=o.endAngle-o.startAngle;if(o.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 i=e/n.divisions,s=o.startAngle+t*i;r(o.cx+o.radius*Math.cos(s),o.cy+o.radius*Math.sin(s))}}}}if(n.closed&&s.length>0){const t=s[0],e=s[s.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&s.push({x:t.x,y:t.y})}return new sS(s,n.closed)}function oS(t,e){return rS(t,e).length}function aS(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 cS(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 lS(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",i={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:aS(n),parentId:t.parent?.state?.id,parentPath:cS(t)},s=t._realObject?.object3d;if(s){s.updateWorldMatrix?.(!0,!1);const t=s.matrixWorld?.elements;t&&(i.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(i.isItem=!0),!0===t.isMover&&(i.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(i.isHolder=!0),"function"==typeof t.pickupFrames)try{i.isPickable=t.pickupFrames().length>0}catch{i.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?i.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(i.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,i]of Object.entries(t.state))"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i&&null!==i||(e[n]=i);i.state=e}if(e){const e=t.components??[];i.childIds=e.map(t=>t.state?.id).filter(Boolean)}return i}function hS(t){function e(t,n){if(!t)return;n.push(lS(t));const i=t.components??[];for(const t of i)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const i=e.components??[];for(const e of i){const i=n(t,e);if(i)return i}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const i=n(e,t?.rootModel??t);if(!i)return null;const s={...lS(i)};if("function"==typeof i.pickupFrames)try{s.pickupFrames=i.pickupFrames()}catch{}if("object"==typeof i.slots)try{s.slots=Array.isArray(i.slots)?i.slots:"function"==typeof i.slots?i.slots():[]}catch{}if("function"==typeof i.acceptanceRotation)try{s.acceptanceWorldQuat=i.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof i.deliveryWorldPosition)try{s.deliveryWorldPosition=i.deliveryWorldPosition(null)}catch{}return s},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 i=t.components??[];for(const t of i)n.push(t)}return{simTime:Dr.now,realTime:"undefined"!=typeof performance?performance.now():Date.now(),speed:Dr.speed,paused:Dr.isPaused,carrierCount:e}},transferLog(){const t={};Xu.flows().forEach((e,n)=>{t[n]=e});const e={};Xu.targetCounts().forEach((t,n)=>{e[n]=t});const n={};return Xu.rejectReasonCounts().forEach((t,e)=>{n[e]=t}),{entries:Xu.toJSON(),stats:Xu.stats(),flows:t,targetCounts:e,rejectReasonCounts:n}},reservations(){const t=[...KM.all()],e={},n={};for(const i of t)(e[i.resource]??=[]).push(i),(n[i.reserverId]??=[]).push(i);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:Dr.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=KM.conflictLog(),e={},n={};let i=0,s=0;for(const r of t)e[r.resource]=(e[r.resource]??0)+1,n[r.proposed.reserverId]=(n[r.proposed.reserverId]??0)+1,"rejected"===r.outcome?i++:s++;return{simTime:Dr.now,log:[...t],total:t.length,rejected:i,preempted:s,byResource:e,byReserver:n}}}}function dS(t){const e=hS(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let uS=0;const pS=new FinalizationRegistry(()=>{uS--});class fS{static get residents(){return uS}static get residentsCount(){return uS}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,uS++,pS.register(this,uS)}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,Zi("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,i)=>{const s=this.references[t];if(s)s===e?i(Error("Reference ID and target duplicate")):e?i(Error("Reference ID duplicate")):n(s);else{const s=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)s(e);else{if(!this.creator)return void i(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,s,i)}}});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 Qi("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,Zi("RELEASED",e)))}}const mS={},gS={};let yS=[];function bS(t){const e=t.target,n="SCRIPT"===e.tagName?mS:gS,i=e.src||e.href;n[i]=!0,yS.forEach((t,e)=>{if(!t)return;const{resolve:s,scripts:r,styles:o}=t;if(n===mS){const t=r.indexOf(i);t>-1&&t<r.length-1&&_S(r[t+1])}r.some(t=>!mS[t])||o?.some(t=>!gS[t])||(s(),yS[e]=null)}),yS=yS.filter(Boolean)}function vS(t){if("string"==typeof t)return;const e=t.target,n=e.src,i="SCRIPT"===e.tagName?mS:gS;yS.forEach((e,s)=>{if(!e)return;const{reject:r,scripts:o,styles:a}=e;(i===mS&&o.includes(n)||i===gS&&!!a?.includes(n))&&(r(t),yS[s]=null)}),yS=yS.filter(Boolean),delete i[n],document.head.removeChild(e)}function _S(t){mS[t]=!1;const e=document.createElement("script");e.onload=bS,e.onerror=vS,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class xS{static load(t,e){const n="string"==typeof t?[t]:t,i="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||i&&!Array.isArray(i))return void e(new Error("invalid sources for load"));let s,r=!0;if(i?.forEach(t=>{t in gS||function(t){gS[t]=!1;const e=document.createElement("link");e.onload=bS,e.onerror=vS,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),gS[t]||(r=!1)}),n&&n.length>0)for(const t of n)t in mS?mS[t]||(r=!1):s??=t;if(s)_S(s);else if(r)return void t();yS.push({resolve:t,reject:e,scripts:n,styles:i})})}}const wS="0.0.0";function MS(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 SS(e){const{lineWidth:n=0}=e.state;let{width:i,height:s}=e.bounds;i+=n,s+=n;const r=MS(2*i),o=MS(2*s),a=Bp(r,o),c=new t.CanvasTexture(a);return AS(a,e,2),c.needsUpdate=!0,c.wrapS=t.RepeatWrapping,c.wrapT=t.RepeatWrapping,c.offset.set(0,1-2*s/o),c.repeat.set(2*i/r,2*s/o),c.magFilter=t.NearestFilter,c.minFilter=t.LinearFilter,c.colorSpace=t.SRGBColorSpace,c}function AS(t,e,n){const{lineWidth:i=0}=e.state;let{left:s,top:r}=e.bounds;s-=i/2,r-=i/2;const o=t.getContext("2d");o.scale(n,n),o.translate(-s,-r),e.render(o),e.postrender(o)}function ES(t,e,n=2){const i=t.getContext("2d");i&&(i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,t.width,t.height),AS(t,e,n))}const kS=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class CS extends Mu{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 t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds;if(!e||!n)return;const i=Id(this.component.state.material3d),s=new t.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const r=SS(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,i),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.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;nu(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&&(ES(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(!kS.has(e)){this._debouncedRebuild();break}}updateMaterial3d(){super.updateMaterial3d();const t=this.object3d.material;if(!t)return;const e=Id(this.component.state.material3d);Rd(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),hu(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 TS=new Map;function OS(t){return Math.round(1e3*t)/1e3}function PS(e){return new t.Color(e).getHexString()}const IS={material(e,n,i){const s=e+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+PS(t.color)),null!=t.metalness&&e.push("m"+OS(t.metalness)),null!=t.roughness&&e.push("r"+OS(t.roughness)),null!=t.opacity&&e.push("o"+OS(t.opacity)),null!=t.emissive&&e.push("E"+PS(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+OS(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+OS(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("|")}(n);let r=TS.get(s);return r||TS.set(s,r=function(e){const n=new t.MeshStandardMaterial;return n.userData.__bankOwned=!0,null!=e.color&&n.color.set(e.color),null!=e.emissive&&n.emissive.set(e.emissive),null!=e.metalness&&(n.metalness=e.metalness),null!=e.roughness&&(n.roughness=e.roughness),null!=e.emissiveIntensity&&(n.emissiveIntensity=e.emissiveIntensity),null!=e.envMapIntensity&&(n.envMapIntensity=e.envMapIntensity),null!=e.side&&(n.side=e.side),null!=e.map&&(n.map=e.map),null!=e.flatShading&&(n.flatShading=e.flatShading),null!=e.depthWrite&&(n.depthWrite=e.depthWrite),null!=e.opacity&&(n.opacity=e.opacity),null!=e.transparent?n.transparent=e.transparent:null!=e.opacity&&e.opacity<1&&(n.transparent=!0),n}(n)),null==i?r:Qd(r,{color:i})},get size(){return TS.size},has(t){const e=t+"::";for(const t of TS.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of TS.values())Zd(t),t.dispose();TS.clear()}};class DS extends Mu{getObject3dInstance(){return new t.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;nu(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 i=Mu.buildFillStyleTexture(this.component);i?(n.map&&n.map.dispose(),i.needsUpdate=!0,n.map=i,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(iu(t))),nu(n,0,t)}updateStrokeStyle(){const e=this.object3d.getObjectByName("__edgeLines__");e&&(this.object3d.remove(e),hu(e));const{strokeStyle:n}=this.component.state;if(!n||"transparent"===n||"none"===n)return;const i=this.object3d.geometry;if(!i?.getAttribute("position"))return;const s=new t.EdgesGeometry(i),r=new t.LineBasicMaterial({color:n}),o=new t.LineSegments(s,r);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 i=this.object3d.geometry.boundingBox;if(i){const s=i.max.x-i.min.x,r=i.max.y-i.min.y,o=i.max.z-i.min.z;this.setDimensionScale(t/s,n/r,e/o)}}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,i={shared:e,required:n,violated:n&&!e};return void 0!==t&&(i.reason=t),e&&(i.bankKey=this.materialBankKey),i}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=Id(this.component.state.material3d),e=eu(this.component.state.fillStyle);return{metalness:t.metalness,roughness:t.roughness,emissive:t.emissive,emissiveIntensity:t.emissiveIntensity,envMapIntensity:t.envMapIntensity,side:zd(t.side),flatShading:t.flatShading,opacity:e,transparent:e<1}}buildMaterial(){if(!this.canShareMaterial){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial({transparent:!0});return Rd(n,e),void(this.object3d.material=n)}this.applyBankMaterial()}applyBankMaterial(){const{fillStyle:t}=this.component.state,e=eu(t)>0&&"string"==typeof t?iu(t):void 0;Jd(this.object3d),this.object3d.material=IS.material(this.materialBankKey,this.materialSpec(),e)}updateMaterial3d(){if(super.updateMaterial3d(),this.canShareMaterial)return this.applyBankMaterial(),void this.applyMaterialOpacity();const t=this.object3d.material;t&&Rd(t,Id(this.component.state.material3d))}clear(){return Jd(this.object3d),hu(this.object3d),super.clear()}}function zS(t,e,n,i){return[["bold",t],["italic",e],[n+"px",!0],[i,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function RS(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 jS(t,e,n){const{bold:i=!1,italic:s=!1,fontFamily:r="Serif",fontSize:o=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=zS(i,s,o,r),"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*o,b=String(e).split("\n"),v=y*b.length;g="top"===l||"hanging"===l?p+.1*o:"bottom"===l||"alphabetic"===l?p+d-v+.1*o:p+(d-v)/2+.1*o,f.textBaseline="top";for(const t of b)f.fillText(t,m,g),g+=y}function LS(e,n,i,s){const r=RS(2*n),o=RS(2*i),a=Bp(r,o),c=a.getContext("2d"),{fillStyle:l}=s||{};if(l&&"object"==typeof l&&l.colorStops?.length){const t=du(l,2*n,2*i);t&&c.drawImage(t,0,0)}c.scale(2,2),"string"==typeof l&&""!==l&&"transparent"!==l&&(c.fillStyle=l,c.fillRect(0,0,n,i)),jS(a,e,s);const h=new t.CanvasTexture(a);return h.needsUpdate=!0,h.wrapS=t.RepeatWrapping,h.wrapT=t.RepeatWrapping,h.offset.set(0,1-2*i/o),h.repeat.set(2*n/r,2*i/o),h.minFilter=t.LinearFilter,h.colorSpace=t.SRGBColorSpace,h}function FS(e,n,i,s,r,o,a){const c=new Image;c.crossOrigin="anonymous",c.onload=()=>{const e=2*i,l=2*s,h=RS(e),d=RS(l),u=Bp(h,d),p=u.getContext("2d");if(o.color&&(p.fillStyle=o.color,p.fillRect(0,0,e,l)),o.fitPattern)p.drawImage(c,0,0,e,l);else{const t=2*(o.width||c.naturalWidth),n=2*(o.height||c.naturalHeight),i=2*(o.offsetX||0),s=2*(o.offsetY||0);let r=0,a=0;switch(o.align){case"center":r=(e-t)/2,a=(l-n)/2;break;case"left-top":break;case"left-bottom":a=l-n;break;case"right-top":r=e-t;break;case"right-bottom":r=e-t,a=l-n;break;case"left":a=(l-n)/2;break;case"right":r=e-t,a=(l-n)/2;break;case"top":r=(e-t)/2;break;case"bottom":r=(e-t)/2,a=l-n}const h=i+r,d=s+a;if(o.noRepeat)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,h,d,t,n);else{p.save(),p.rect(0,0,e,l),p.clip();const i=h>0?h-Math.ceil(h/t)*t:h;for(let s=d>0?d-Math.ceil(d/n)*n:d;s<l;s+=n)for(let r=i;r<e;r+=t)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,r,s,t,n);p.restore()}}n&&(p.scale(2,2),jS(u,n,r));const f=new t.CanvasTexture(u);f.needsUpdate=!0,f.wrapS=t.RepeatWrapping,f.wrapT=t.RepeatWrapping,f.offset.set(0,1-l/d),f.repeat.set(e/h,l/d),f.minFilter=t.LinearFilter,f.colorSpace=t.SRGBColorSpace,a(f)},c.onerror=()=>{const t=LS(n,i,s,r);a(t)},c.src=e}function NS(t,e){let{bold:n=!1,italic:i=!1,fontFamily:s="Serif",fontSize:r=10,lineHeight:o="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=zS(n,i,r,s),a.style.lineHeight=String(o),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 $S extends DS{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){this.updateDimension()}updateStrokeStyle(){}updateFillStyle(){this.updateText()}updateDimension(){const{width:e,height:n}=this.component.state,i=Math.abs(e)||1,s=Math.abs(n)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const r=new t.PlaneGeometry(i,s);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:i=!1,italic:s=!1,fontFamily:r="Serif",fontSize:o=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:i,italic:s,fontFamily:r,fontSize:o,fontColor:a,textAlign:c,textBaseline:l,width:d,height:u,fillStyle:f};if("object"==typeof f&&"pattern"===f?.type&&f.image){return void FS(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=LS(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(iu(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}Jp("text",t=>new $S(t));const HS={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function BS(t){const e=t.model?.type??"";return"texture"===(HS[e]??"css3d")?new CS(t):new Xp(t)}Jp("html-overlay-element",BS),Jp("html-overlay-container",BS);class YS{setShape({extrudedShape:e,extrudedOptions:n}){this.extrudedShape=e,this.bb=new t.Box2,this.bb.setFromPoints(this.extrudedShape?.extractPoints(0).shape),this.extrudedOptions=n}generateTopUV(e,n,i,s,r){const o=n[3*i],a=n[3*i+1],c=n[3*s],l=n[3*s+1],h=n[3*r],d=n[3*r+1],u=this.bb,p=u.max.x-u.min.x,f=u.max.y-u.min.y;return[new t.Vector2((o-u.min.x)/p,1-(a-u.min.y)/f),new t.Vector2((c-u.min.x)/p,1-(l-u.min.y)/f),new t.Vector2((h-u.min.x)/p,1-(d-u.min.y)/f)]}generateSideWallUV(e,n,i,s,r,o){const a=n[3*i],c=n[3*i+1],l=n[3*i+2],h=n[3*s],d=n[3*s+1],u=n[3*s+2],p=n[3*r],f=n[3*r+1],m=n[3*r+2],g=n[3*o],y=n[3*o+1],b=n[3*o+2],v=this.extrudedOptions?.depth||100,_=this.bb,x=_.max.x-_.min.x,w=_.max.y-_.min.y;return Math.abs(c-d)<.01?[new t.Vector2(a/x,1-l/v),new t.Vector2(h/x,1-u/v),new t.Vector2(p/x,1-m/v),new t.Vector2(g/x,1-b/v)]:[new t.Vector2(c/w,1-l/v),new t.Vector2(d/w,1-u/v),new t.Vector2(f/w,1-m/v),new t.Vector2(y/w,1-b/v)]}}function GS(t,e){const n=t/2,i=e/2;return{points:[{x:-n,y:-i},{x:n,y:-i},{x:n,y:i},{x:-n,y:i}]}}function VS(t,e,n){const i=Math.max(3,Math.floor(n)),s=[];for(let n=0;n<i;n++){const r=n/i*Math.PI*2;s.push({x:t*Math.cos(r),y:e*Math.sin(r)})}return{points:s,segments:i}}function US(t){if(0===t.length)return[];let e=1/0,n=1/0,i=-1/0,s=-1/0;for(const r of t)r.x<e&&(e=r.x),r.x>i&&(i=r.x),r.y<n&&(n=r.y),r.y>s&&(s=r.y);const r=(e+i)/2,o=(n+s)/2,a=t.map(t=>({x:t.x-r,y:t.y-o})),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 WS extends Mu{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 i=US(n);return i.length<3?null:{points:i}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new YS),this._boundUVGenerator}build(){super.build();const e=this.effectiveDepth,n=this.shape;if(!n)return;const i=this.boundUVGenerator;i&&i.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const s=this.createGeometry(n),r=this.createMaterials();this._mesh=new t.Mesh(s,r),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(e){const n=this.effectiveDepth,{lineWidth:i=0}=this.component.state,s={steps:1,depth:n,bevelEnabled:i>0,bevelThickness:0,bevelSize:i,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,s);return r.center(),r}createMaterials(){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial;Rd(n,e);const i=new t.MeshStandardMaterial;return Rd(i,e),[n,i]}createTexture(){const{width:e,height:n}=this.component.bounds,i=RS(e),s=RS(n),r=Bp(i,s);this.component.render(r.getContext("2d"));const o=new t.CanvasTexture(r);return o.needsUpdate=!0,o.wrapS=t.RepeatWrapping,o.wrapT=t.RepeatWrapping,o.offset.set(0,1-n/s),o.repeat.set(e/i,n/s),o.minFilter=t.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=Id(this.component.state.material3d);for(const n of t)Rd(n,e)}updateAlpha(){const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,i=this.getMaterials();i&&(nu(i[0],0,e),nu(i[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(iu(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,i=this.component.hasTextProperty?this.component.text:"";if(!i){const t=Mu.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(iu(n))),void(e.needsUpdate=!0)}const{bold:s=!1,italic:r=!1,fontFamily:o="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:s,italic:r,fontFamily:o,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 FS(this.component.app.url(n.image),i,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 _=LS(i,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 qS extends WS{get shape(){const{cx:e=0,cy:n=0,rx:i=1,ry:s=1,startAngle:r=0,endAngle:o=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=new t.EllipseCurve(e,n,Math.abs(i),Math.abs(s),r,o,a,0);return new t.Shape(c.getPoints(50))}}Jp("ellipse",t=>new qS(t));class XS extends WS{get shape(){const{width:e,height:n,round:i=0}=this.component.state,s=Oc(i,e,n);if(s>0){const i=s,r=new t.Path;return r.moveTo(i,0),r.lineTo(e-i,0),r.quadraticCurveTo(e,0,e,i),r.lineTo(e,n-i),r.quadraticCurveTo(e,n,e-i,n),r.lineTo(i,n),r.quadraticCurveTo(0,n,0,n-i),r.lineTo(0,i),r.quadraticCurveTo(0,0,i,0),new t.Shape(r.getPoints(12))}const r=new t.Shape;return r.moveTo(0,0),r.lineTo(e,0),r.lineTo(e,n),r.lineTo(0,n),r.lineTo(0,0),r}}function KS(e,n={}){const i=n.round??0,s=n.divisions??24;if(!e||0===e.length)return new t.Shape;const r=e.some(t=>Xr(t)),o=i>0||e.some(t=>Zr(t,0)>0);if(r||o){const n=new t.Path;for(let t=0;t<e.length;t++){const s=e[(t-1+e.length)%e.length],r=e[t],o=e[(t+1)%e.length];if(s.x===r.x&&s.y===r.y)continue;const a=Zr(r,i);let c=Math.sqrt((s.x-r.x)**2+(s.y-r.y)**2),l=0!==c?Math.atan2(s.x-r.x,s.y-r.y):0;const h=Math.sin(l)*Math.min(a,c/2)+r.x,d=Math.cos(l)*Math.min(a,c/2)+r.y;c=Math.sqrt((o.x-r.x)**2+(o.y-r.y)**2),l=0!==c?Math.atan2(o.x-r.x,o.y-r.y):0;const u=Math.sin(l)*Math.min(a,c/2)+r.x,p=Math.cos(l)*Math.min(a,c/2)+r.y;if(0===t?n.moveTo(h,d):n.lineTo(h,d),a>0&&n.quadraticCurveTo(r.x,r.y,u,p),Xr(r)){const t=Zr(o,i),e=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),s=0!==e?Math.atan2(r.x-o.x,r.y-o.y):0,a=Kr({x:u,y:p},{x:Math.sin(s)*Math.min(t,e/2)+o.x,y:Math.cos(s)*Math.min(t,e/2)+o.y},r.bulge);a&&n.absarc(a.cx,a.cy,a.radius,a.startAngle,a.endAngle,a.clockwise)}}return new t.Shape(n.getPoints(s))}const a=new t.Shape;for(let t=0;t<e.length;t++)0===t?a.moveTo(e[t].x,e[t].y):a.lineTo(e[t].x,e[t].y);return a}Jp("rect",t=>new XS(t));class QS extends WS{get shape(){const{path:t=[],round:e=0}=this.component.state;return KS(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(WS.prototype).build.call(this);const e=this.effectiveDepth,n=this.shape;if(!n)return;const i=this.boundUVGenerator,s=this.minMax;if(i&&void 0!==s.minX&&void 0!==s.maxX&&void 0!==s.minY&&void 0!==s.maxY){const n=new t.Shape;n.moveTo(s.minX,s.minY),n.lineTo(s.maxX,s.minY),n.lineTo(s.maxX,s.maxY),n.lineTo(s.minX,s.maxY),n.closePath(),i.setShape({extrudedShape:n,extrudedOptions:{depth:e}})}else i&&i.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const r=this.createGeometry(n),o=this.createMaterials();this._mesh=new t.Mesh(r,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(e){const n=this.effectiveDepth,{lineWidth:i=0}=this.component.state,s={steps:1,depth:n,bevelEnabled:i>0,bevelThickness:0,bevelSize:i,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,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;r.translate(-t,-e,0),r.computeBoundingBox();const n=r.boundingBox;n&&r.translate(0,0,-(n.min.z+n.max.z)/2)}else r.center();return r}get minMax(){if(!this._minMax){const{path:t}=this.component.state;let e,n,i,s;t.forEach((t,r)=>{if(0==r)return e=i=t.x,void(n=s=t.y);e=Math.min(e,t.x),i=Math.max(i,t.x),n=Math.min(n,t.y),s=Math.max(s,t.y)}),this._minMax={minX:e,minY:n,maxX:i,maxY:s}}return this._minMax}}Jp("polygon",t=>new QS(t));class JS extends WS{get shape(){const{cx:e=0,cy:n=0,rx:i=1,ry:s=1,ratio:r=50,startAngle:o=0,endAngle:a=2*Math.PI,anticlockwise:c=!1}=this.component.state,l=Math.abs(i),h=Math.abs(s),d=new t.EllipseCurve(e,n,l,h,o,a,c,0),u=new t.Shape(d.getPoints(50)),p=l/100*r,f=h/100*r;if(p>0&&f>0){const i=new t.EllipseCurve(e,n,p,f,o,a,c,0),s=new t.Path(i.getPoints(50));u.holes.push(s)}return u}}Jp("donut",t=>new JS(t));class ZS extends WS{get shape(){const{x1:e=0,y1:n=0,x2:i=0,y2:s=0,x3:r=0,y3:o=0,round:a=0}=this.component.state,c=[{x:e,y:n},{x:i,y:s},{x:r,y:o}];if(a>0){const e=new t.Path;for(let t=0;t<c.length;t++){const n=c[(t-1+c.length)%c.length],i=c[t],s=c[(t+1)%c.length];let r=Math.sqrt((n.x-i.x)**2+(n.y-i.y)**2),o=0!==r?Math.atan2(n.x-i.x,n.y-i.y):0;const l=Math.sin(o)*Math.min(a,r/2)+i.x,h=Math.cos(o)*Math.min(a,r/2)+i.y;r=Math.sqrt((s.x-i.x)**2+(s.y-i.y)**2),o=0!==r?Math.atan2(s.x-i.x,s.y-i.y):0;const d=Math.sin(o)*Math.min(a,r/2)+i.x,u=Math.cos(o)*Math.min(a,r/2)+i.y;0===t?e.moveTo(l,h):e.lineTo(l,h),e.quadraticCurveTo(i.x,i.y,d,u)}return new t.Shape(e.getPoints(12))}const l=new t.Shape;return l.moveTo(e,n),l.lineTo(i,s),l.lineTo(r,o),l.closePath(),l}}Jp("triangle",t=>new ZS(t));class tA extends WS{get shape(){const{ratio:e=30,wing:n=5,cx:i=0,cy:s=0,rx:r=1,ry:o=1}=this.component.state;if(n<3)return null;const a=Math.PI/2,c=2*Math.PI/n,l=r-e/100*r,h=o-e/100*o,d=new t.Shape;d.moveTo(i+r*Math.cos(-a),s+o*Math.sin(-a)),d.lineTo(i+(r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,s+(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let t=1;t<n;t++)d.lineTo(i+r*Math.cos(c*t-a),s+o*Math.sin(c*t-a)),d.lineTo(i+(r-l)*(Math.cos(c*(t+1)-a)+Math.cos(c*t-a))/2,s+(o-h)*(Math.sin(c*(t+1)-a)+Math.sin(c*t-a))/2);return d.closePath(),d}}Jp("star",t=>new tA(t));const eA=new Map;function nA(t){return t.userData.__bankOwned=!0,t}const iA={primitive(e){const n="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}}(e);let i=eA.get(n);return i||eA.set(n,i=nA(function(e){switch(e.kind){case"box":return new t.BoxGeometry(1,1,1);case"plane":return new t.PlaneGeometry(1,1);case"cylinder":return new t.CylinderGeometry(.5,.5,1,e.segments??16);case"sphere":return new t.SphereGeometry(.5,e.segments??16,e.heightSegments??Math.max(2,Math.round((e.segments??16)/2)))}}(e))),i},shaped(t,e){const n="shaped::"+t;let i=eA.get(n);return i||eA.set(n,i=nA(e())),i},owns:t=>!0===t.userData?.__bankOwned,get size(){return eA.size},has:t=>eA.has("primitive::"+t)||eA.has("shaped::"+t),dispose(){for(const t of eA.values())t.dispose();eA.clear()}},sA=[8,12,16],rA={cylinder:25,sphere:32},oA=3,aA=128;function cA(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(aA,Math.max(3,Math.floor(t))):e}function lA(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(aA,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function hA(t){return sA.includes(t)}const dA={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 uA extends DS{buildGeometry(){const t=this.component.state,e=cA(t.segments,rA.sphere),n=lA(t.heightSegments,e);this.object3d.geometry=iA.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,i=n??t;this.setDimensionScale(2*t,2*i,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 VS(t,e,cA(this.component.state.segments,rA.sphere))}}let pA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new uA(this)}get nature(){return dA}};pA=tg([Ny("sphere")],pA);class fA extends Mu{getObject3dInstance(){return new t.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(),i=this.component.parent?._realObject;return t+n+e/2-(i?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;nu(this.object3d.material,0,e)}updateFillStyle(){const{fillStyle:t}=this.component.state,e=this.object3d.material;if(!e)return;const n=Mu.buildFillStyleTexture(this.component);n?(e.map&&e.map.dispose(),n.needsUpdate=!0,e.map=n):"string"==typeof t&&("transparent"!==t?e.color.set(iu(t)):e.opacity=0)}}class mA extends fA{buildMaterial(){const e=this.object3d.material;e&&e.dispose(),this.object3d.material=new t.SpriteMaterial({map:SS(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:i=1,height:s=1}=n?.bounds??{},{scale:r=1}=this.component.state;return{x:r*t/i,y:r*e/s,z:r}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const gA={mutable:!1,resizable:!0,rotatable:!0,properties:[]};let yA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new mA(this)}get nature(){return gA}};yA=tg([Ny("sprite")],yA);const bA={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class vA extends DS{buildGeometry(){this.object3d.geometry=iA.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?GS(t,e):null}}let _A=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new vA(this)}get nature(){return bA}};_A=tg([Ny("cube")],_A);const xA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class wA extends DS{buildGeometry(){const t=cA(this.component.state.segments,rA.cylinder);this.object3d.geometry=iA.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 VS(t,e,cA(this.component.state.segments,rA.cylinder))}}let MA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new wA(this)}get nature(){return xA}};MA=tg([Ny("cylinder")],MA);const SA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class AA extends Mu{get zPriority(){return gu.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 i=this.createTextureBoard(t,n);i.position.set(0,0,.5*e+1),this.object3d.add(i)}createCube(e,n,i){const{boxColor:s="#ccaa76"}=this.component.state,r=Id(this.component.state.material3d),o=new t.BoxGeometry(e,i,n),a=new t.MeshStandardMaterial({color:s,side:t.FrontSide});Rd(a,r);const c=new t.Mesh(o,a);return c.castShadow=r.castShadow,c.receiveShadow=r.receiveShadow,c}createTextureBoard(e,n){const i=Id(this.component.state.material3d),{fillStyle:s="#ccaa76"}=this.component.state,r=Mu.buildFillStyleTexture(this.component),o=new t.MeshStandardMaterial(r?{map:r}:{color:s||"#ccaa76",side:t.FrontSide});Rd(o,i);const a=new t.PlaneGeometry(e,n,1,1),c=new t.Mesh(a,o);return c.castShadow=i.castShadow,c.receiveShadow=i.receiveShadow,c}updateMaterial3d(){super.updateMaterial3d();const t=Id(this.component.state.material3d);this.object3d.traverse(e=>{if(e.isMesh){const n=e.material;n&&Rd(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()}}let EA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return SA}buildRealObject(){return new AA(this)}};var kA;EA=tg([Ny("banner")],EA);const CA={far:1e5,fov:80,near:1,zoom:1},TA={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 OA extends Mu{getObject3dInstance(){return new t.Mesh}updateCamera(){const{near:e=CA.near,far:n=CA.far,fov:i=CA.fov,zoom:s=CA.zoom,showHelper:r}=this.component.state;this.camera.far=n,this.camera.fov=i,this.camera.near=e,this.camera.zoom=s,r?this.helper||(this.helper=new t.CameraHelper(this.camera),this.object3d.add(this.helper)):this.helper&&(this.object3d.remove(this.helper),delete this.helper)}build(){super.build();const{width:e=0,height:n=0,depth:i=0,fillStyle:s="lightgray"}=this.component.state;this.object3d.geometry=new t.BoxGeometry(e,i,n);const r=Id(this.component.state.material3d),o=new t.MeshStandardMaterial({color:s});Rd(o,r),this.object3d.material=o,this.object3d.castShadow=r.castShadow,this.object3d.receiveShadow=r.receiveShadow,this.camera=new t.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=Id(this.component.state.material3d);Rd(t,e),this.object3d.castShadow=e.castShadow,this.object3d.receiveShadow=e.receiveShadow}}let PA=kA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return kA._image||(kA._image=new Image,kA._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=="),kA._image}render(t){const{left:e,top:n,width:i,height:s}=this.bounds;t.beginPath(),this.drawImage(t,kA.image,e,n,i,s)}buildRealObject(){return new OA(this)}get nature(){return TA}};PA=kA=tg([Ny("camera")],PA);const IA={mutable:!1,resizable:!0,rotatable:!0,properties:[...Ly],"value-property":"source",help:"scene/component/gltf-object"};let DA=class extends(Fy(Pc(Tc))){get nature(){return IA}};DA=tg([Ny("gltf-object")],DA);const zA={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 RA extends Mu{updatePointLight(){const{lightType:e="point",distance:n=0,intensity:i=10,decay:s=1,fillStyle:r="white",castShadow:o,near:a=.5,far:c=1e3,fov:l=90,zoom:h=1,showHelper:d}=this.component.state;if(this.object3d.color=new t.Color(r),"point"==e&&(this.object3d.distance=n,this.object3d.decay=s),this.object3d.intensity=i,this.object3d.castShadow=o,o){const t=this.object3d.shadow?.camera;t.far=c,t.near=a,t.fov=l,t.zoom=h}if(d){const e=this.object3d.shadow?.camera;this.helper||(this.helper=new t.CameraHelper(e),this.object3d.add(this.helper))}else this.helper&&(this.object3d.remove(this.helper),delete this.helper)}getObject3dInstance(){const{lightType:e="point"}=this.component.state;return"point"==e?new t.PointLight:new t.DirectionalLight}update(){this.clear(),this.build(),this.updateDimension(),this.updateHidden(),this.updatePointLight()}}let jA=class extends Ag{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new RA(this)}get anchors(){return[]}get nature(){return zA}};jA=tg([Ny("light")],jA);const LA={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class FA extends DS{buildGeometry(){this.object3d.geometry=iA.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?GS(t,e):null}}let NA=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new FA(this)}get nature(){return LA}};NA=tg([Ny("wall")],NA);const $A={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 HA extends Mu{get zPriority(){return gu.FLOOR}get receivingSurfaceY(){return this.placementSurfaceY()}resolveShadow(){const t=this.component.state,e=t.material3d,{alpha:n=1,fillStyle:i}=t,s=n>=.9&&"none"!==i;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??s}}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:e,height:n,depth:i=1}=this.component.state;if(!e||!n)return;const s=Math.abs(e),r=Math.abs(n),o=Math.max(i,.5),a=new t.BoxGeometry(s,o,r),c=this._buildTopMaterial(),l=this._buildSideMaterial(),h=[l,l,c,l,l,l];this._mesh=new t.Mesh(a,h),this._mesh.position.y=0;const{cast:d,receive:u}=this.resolveShadow();this._mesh.castShadow=d,this._mesh.receiveShadow=u,this.object3d.add(this._mesh)}_buildTopMaterial(){const{alpha:e=1,fillStyle:n}=this.component.state,i=Id(this.component.state.material3d),s=Mu.buildFillStyleTexture(this.component);if(s){this._topTexture=s;const e=new t.MeshStandardMaterial({map:s,side:t.DoubleSide});return nu(e,0,n),e.depthWrite=e.opacity>=.9,Rd(e,i),e}const r="string"==typeof n&&"none"!==n?iu(n):"#e0e0e0",o=new t.MeshStandardMaterial({color:r,side:t.DoubleSide});return nu(o,0,n),o.depthWrite=o.opacity>=.9,Rd(o,i),o}_buildSideMaterial(){const{strokeStyle:e,alpha:n=1}=this.component.state,i="string"==typeof e&&e?iu(e):"#999999",s=Id(this.component.state.material3d),r=new t.MeshStandardMaterial({color:i});return Rd(r,s),r.side=t.DoubleSide,nu(r,0,e),r.depthWrite=r.opacity>=.9,r}updateAlpha(){if(!this._mesh)return;const{alpha:t=1,fillStyle:e,strokeStyle:n}=this.component.state,i=this._mesh.material;for(let t=0;t<i.length;t++){const s=i[t];nu(s,0,2===t?e:n),s.depthWrite=s.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)}}let BA=class extends rh{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new HA(this)}get nature(){return $A}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}};BA.requires3d=!0,BA=tg([Ny("floor-plate")],BA);function YA(e,n={}){const i=n.size??5,s=n.color??4500172,r=n.emissive??2245734,o=new t.SphereGeometry(i,16,12),a=new t.MeshStandardMaterial({color:s,emissive:r,emissiveIntensity:.15,metalness:.3,roughness:.4,transparent:!0,opacity:.35}),c=new t.Mesh(o,a);n.position&&c.position.set(n.position[0],n.position[1],n.position[2]),c.userData.alwaysRaycast=!0,c.scale.setScalar(1),c.visible=n.visible??!(!0===e.app?.isViewMode);const l=()=>{a.emissiveIntensity=.9,a.opacity=.95,c.scale.setScalar(1.35),e.invalidate?.()},h=()=>{a.emissiveIntensity=.15,a.opacity=.35,c.scale.setScalar(1),e.invalidate?.()};return e.on("mouseenter",l),e.on("mouseleave",h),c.userData.dispose=()=>{e.off("mouseenter",l),e.off("mouseleave",h)},c}class GA extends DS{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:e,height:n}=this.component.state,i=Math.abs(e)||1,s=Math.abs(n)||1,r=new t.PlaneGeometry(i,s);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateDimension(){this.update()}build(){super.build();const{width:t,height:e}=this.component.state,n=Math.abs(t)||1,i=Math.abs(e)||1,s=Math.max(2,.04*Math.min(n,i));this.object3d.add(YA(this.component,{size:s,position:[n/2-s,s,-i/2+s]}))}}const VA={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let UA=class extends(Ry(Pc(Tc))){buildRealObject(){return new GA(this)}get nature(){return VA}};UA=tg([Ny("decal")],UA);class WA extends Mu{getObject3dInstance(){return new t.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const qA="#dde2e8",XA="#9c9c9c",KA="#e8e8ec",QA=.35;function JA(e,n,i,s,r){if(!n.visible)return new t.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=n.alpha*i,a="wall"===s?qA:"floor"===s?XA:KA,c=new t.MeshStandardMaterial({metalness:0,roughness:"wall"===s?.6:.85,transparent:o<1,opacity:o,side:r?t.BackSide:t.DoubleSide});return function(t,e,n,i,s,r){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const i=!r,o=Mu.buildFillStyleTexture(e,n,{mirror:i,rotation:s});if(o)return t.map&&t.map.dispose(),t.map=o,void t.color.set("#ffffff")}t.color.set(i)}}(c,e,n.fillStyle,a,n.rotation,n.mirror),c}class ZA extends WA{get zPriority(){return gu.BACKDROP}get position(){if(this.component.state.fitToBoard){return{x:0,y:super.position.y,z:0}}return super.position}build(){super.build();const e=this.component.state;let n=e.width,i=e.height;if(e.fitToBoard){const t=this.component.rootModel,e=t?.state;e&&Number.isFinite(e.width)&&Number.isFinite(e.height)&&(n=e.width,i=e.height)}const s=this.effectiveDepth||Math.min(n,i)||200,r=e.alpha??1,o=!1!==e.seeThrough,a={east:this._resolveFace("east",qA,!0,QA),west:this._resolveFace("west",qA,!0,QA),north:this._resolveFace("north",qA,!0,QA),south:this._resolveFace("south",qA,!0,QA),floor:this._resolveFace("floor",XA,!0,1),ceiling:this._resolveFace("ceiling",KA,!0,1)},c=[JA(this.component,a.east,r,"wall",o),JA(this.component,a.west,r,"wall",o),JA(this.component,a.ceiling,r,"ceiling",o),JA(this.component,a.floor,r,"floor",o),JA(this.component,a.south,r,"wall",o),JA(this.component,a.north,r,"wall",o)],l=new t.BoxGeometry(n,s,i),h=new t.Mesh(l,c);if(h.receiveShadow=!0,this.object3d.add(h),this.component.app?.isEditMode){const e=new t.LineBasicMaterial({color:4473941,transparent:!0,opacity:.7}),n=new t.LineSegments(new t.EdgesGeometry(l),e);this.object3d.add(n)}const d=Math.max(2,.04*Math.min(n,i,s));this.object3d.add(YA(this.component,{size:d,position:[n/2,s/2+d,-i/2]}))}_resolveFace(t,e,n,i){const s=this.component.state,r=s.faces?.[t]??{},o=r.visible,a=r.alpha,c=r.rotation,l=90===c||180===c||270===c?c:0;return{fillStyle:r.fillStyle??e,visible:"boolean"==typeof o?o:n,alpha:"number"==typeof a&&Number.isFinite(a)?a:i,rotation:l,mirror:!0===r.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 tE={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 eE=class extends(Ry(Pc(Tc))){buildRealObject(){return new ZA(this)}get nature(){return tE}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 i={},s=Number.isFinite(n.width)?n.width:this.state.width,r=Number.isFinite(n.height)?n.height:this.state.height;s!==this.state.width&&(i.width=s),r!==this.state.height&&(i.height=r);const o=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(o!==this.state.left&&(i.left=o),a!==this.state.top&&(i.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(s,r);e!==t&&(i.depth=e)}}Object.keys(i).length>0&&this.set(i)}_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 nE(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function iE(e,n,i,s){const r=[];for(let o=1;o<=s;o++){const a=o/s,c=1-a;r.push(new t.Vector3(c*c*e.x+2*c*a*n.x+a*a*i.x,c*c*e.y+2*c*a*n.y+a*a*i.y,c*c*e.z+2*c*a*n.z+a*a*i.z))}return r}eE=tg([Ny("backdrop")],eE);class sE extends Mu{getObject3dInstance(){return new t.Group}get gizmoTransformable(){return!0}get syncZPosOffset(){return 0}get geometricOffsetY(){return 0}syncFromObject3D(){}applyDimensionFromGizmo(t){}build(){super.build(),this._buildLine()}get smoothedPath(){const e=this.worldPath;if(e.length<2)return e;const{round:n=0}=this.component.state;if(n<=0||e.length<3)return e;const i=[];i.push(e[0]);for(let s=1;s<e.length;s++){const r=e[s-1],o=e[s],a=e[s+1];if(!a){i.push(o);break}const c=r.x-o.x,l=r.y-o.y,h=r.z-o.z,d=Math.sqrt(c*c+l*l+h*h),u=Math.min(n,d/2),p=a.x-o.x,f=a.y-o.y,m=a.z-o.z,g=Math.sqrt(p*p+f*f+m*m),y=Math.min(n,g/2),b=d>0?new t.Vector3(o.x+c/d*u,o.y+l/d*u,o.z+h/d*u):o.clone(),v=g>0?new t.Vector3(o.x+p/g*y,o.y+f/g*y,o.z+m/g*y):o.clone();i.push(b),i.push(...iE(b,o,v,8))}return i}_buildLine(){const e=this.smoothedPath;if(e.length<2)return;const{strokeStyle:n,lineWidth:i=2,alpha:s=1,lineDash:r,begin:o="none",beginSize:a="size5",end:c="none",endSize:l="size5"}=this.component.state,h=Math.max(i,1),d="string"==typeof n&&"transparent"!==n?iu(n):"#000000",u=new t.Color(d),p=this._getResolution(),f=o,m=c,g=nE(f,h),y=nE(m,h),b=e[0],v=e[e.length-1],_=(new t.Vector3).subVectors(e[1],b).normalize(),x=(new t.Vector3).subVectors(e[e.length-2],v).normalize(),A=[...e];g>0&&(A[0]=b.clone().add(_.clone().multiplyScalar(g))),y>0&&(A[A.length-1]=v.clone().add(x.clone().multiplyScalar(y)));const E=new S;E.setPositions(A.flatMap(t=>[t.x,t.y,t.z]));const k=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}}(r,h),C=new M({color:u.getHex(),linewidth:h,worldUnits:!0,transparent:s<1,opacity:s,resolution:p,dashed:!!k,dashSize:k?.dashSize??1,gapSize:k?.gapSize??1,dashScale:1});if(this._line2=new w(E,C),this._line2.computeLineDistances(),this.object3d.add(this._line2),"none"!==f){const e=Vp(f,Gp(a,h));if(e){const n=(new t.Quaternion).setFromUnitVectors(new t.Vector3(1,0,0),_.clone().negate());this._placeTip(e,b,n,u,s,p)}}if("none"!==m){const e=Vp(m,Gp(l,h));if(e){const n=(new t.Quaternion).setFromUnitVectors(new t.Vector3(1,0,0),x.clone().negate());this._placeTip(e,v,n,u,s,p)}}}_placeTip(t,e,n,i,s,r){const o=t.mesh||t.line2||t.group;if(o){if(o.position.copy(e),o.setRotationFromQuaternion(n),t.mesh){const e=t.mesh.material;e.color.copy(i),e.transparent=s<1,e.opacity=s}else if(t.line2){const e=t.line2.material;e.color.copy(i),e.transparent=s<1,e.opacity=s,e.resolution.copy(r)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(i),e.transparent=s<1,e.opacity=s,e.resolution&&e.resolution.copy(r)}});this.object3d.add(o)}}_getResolution(){const e=this.threeContainer?.renderer3d;if(e){return e.getSize(new t.Vector2)}return new t.Vector2(window.innerWidth,window.innerHeight)}onGizmoDragEnd(t){const e=this._component,n=e.path;if(!n||n.length<2)return;const i=this.object3d,{width:s=0,height:r=0}=e.parent?.bounds??{},{x:o,y:a}=e.center,c=i.position,l=i.rotation,h=i.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=sE.computeBakedPath(n,{x:o,y:a},{width:s,height:r},i);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(e,n,i,s){const r=i.width,o=i.height,a=n.x,c=n.y;return s.updateMatrixWorld(!0),e.map(e=>{const n=new t.Vector3(e.x-a,e.z||0,e.y-c).applyMatrix4(s.matrixWorld),i={x:n.x+r/2,y:n.z+o/2};return Math.abs(n.y)>.001&&(i.z=n.y),i})}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),hu(t)}return this._line2=void 0,super.clear()}}class rE extends sE{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center,s=this.component,r=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((s,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(s.x-n,s.z||r+(o-r)*c,s.y-i)})}}Jp("line",t=>new rE(t));class oE extends sE{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center;return e.map(e=>new t.Vector3(e.x-n,e.z||0,e.y-i))}}Jp("polyline",t=>new oE(t));class aE extends sE{get worldPath(){const e=this.component.drawPath;if(!e||e.length<2)return[];const{x:n,y:i}=this.component.center,s=this.component,r=s.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=s.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((s,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(s.x-n,s.z||r+(o-r)*c,s.y-i)})}}function cE(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}Jp("ortholine",t=>new aE(t)),Jp("group",t=>new WA(t));class lE{constructor(e){this._count=0,this._placements=[],this._geometry=e.geometry,this._material=e.material,this._capacity=Math.max(1,e.capacity??16),this._name=e.name??"instanced",this._castShadow=e.castShadow??!0,this._receiveShadow=e.receiveShadow??!1,this.object3d=new t.Group,this.object3d.name=this._name,this._mesh=this._makeMesh(this._capacity),this.object3d.add(this._mesh)}_makeMesh(e){const n=new t.InstancedMesh(this._geometry,this._material,e);return n.name=this._name+"__instances",n.castShadow=this._castShadow,n.receiveShadow=this._receiveShadow,n.instanceMatrix.setUsage(t.DynamicDrawUsage),n.count=0,n}get mesh(){return this._mesh}get count(){return this._count}get capacity(){return this._capacity}place(t){const e=t.length;if(e>this._capacity){const t=cE(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=cE(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=lE;n._p.set(e.position.x,e.position.y,e.position.z);const i=e.rotation;n._e.set(i?.x??0,i?.y??0,i?.z??0),n._q.setFromEuler(n._e);const s=e.scale;"number"==typeof s?n._s.set(s,s,s):n._s.set(s?.x??1,s?.y??1,s?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){lE._c.set(e),this._mesh.setColorAt(t,lE._c)}}function hE(t,e,n){const i=Math.max(1,Math.floor(t.x??1)),s=Math.max(1,Math.floor(t.y??1)),r=Math.max(1,Math.floor(t.z??1)),o=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<s;t++)for(let e=0;e<r;e++)for(let n=0;n<i;n++)u.push({position:{x:l+n*o,y:h+t*a,z:d+e*c}});return u}lE._m=new t.Matrix4,lE._p=new t.Vector3,lE._q=new t.Quaternion,lE._e=new t.Euler,lE._s=new t.Vector3,lE._c=new t.Color;class dE extends Mu{build(){super.build()}update(){}}const uE={far:1e5,fov:80,near:1,zoom:1};class pE extends Mu{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new t.PerspectiveCamera}updateCamera(){const{near:t=uE.near,far:e=uE.far,fov:n=uE.fov,zoom:i=uE.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=i}}class fE extends DS{buildGeometry(){const{width:e,height:n}=this.component.state.dimension;this.object3d.geometry=new t.PlaneGeometry(e,n)}buildMaterial(){this.object3d.material=new t.MeshStandardMaterial({opacity:0,side:t.DoubleSide,blending:t.NoBlending})}}class mE extends Mu{getObject3dInstance(){return new t.Scene}dispose(){for(const t of this.object3d.children)hu(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=yf(this.component)}updateTransform(){}updateDimension(){}updatePosition(){}updateRotate(){}updateScale(){}updateAlpha(){}updateHidden(){}get animationMixer(){return this._animationMixer||(this._animationMixer=new t.AnimationMixer(this.object3d)),this._animationMixer}}const gE=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class yE extends Mu{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 t.Mesh}build(){super.build();const{width:e,height:n}=this.component.bounds;if(!e||!n)return;const i=Id(this.component.state.material3d),s=new t.PlaneGeometry(1,1);s.rotateX(-Math.PI/2),this.object3d.geometry=s;const r=SS(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,i),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=i.castShadow,this.object3d.receiveShadow=i.receiveShadow}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;nu(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&&(ES(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(!gE.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=Id(this.component.state.material3d);Rd(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),hu(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 bE={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"};let vE=class extends lg{constructor(){super(...arguments),this._capability=new qf}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:i,threed:s}=this.state;let{width:r,height:o}=this.bounds;if(r=Math.floor(r),o=Math.floor(o),s){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 s=this._capability.domElement;if(!s||!s.width||!s.height)return;t.drawImage(s,0,0,s.width,s.height,e,n,r,o),i&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return Lc.get("three")}get nature(){return bE}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()}};vE=tg([Ny("3d-container")],vE),Zp(t=>new CS(t));let _E=null;function xE(t){_E=t}function wE(t,e=[],n){_E?.registerType?.(t,e,n)}function ME(t){if(Array.isArray(t))return`[${t.map(ME).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${ME(e[t])}`).join(",")}}`}return JSON.stringify(t)}const SE=new Map;function AE(t){const e=function(t){const e=ME(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}|${Hv}`,i=SE.get(n);if(i)return SE.delete(n),SE.set(n,i),i;const s=ow(structuredClone(t)),r=new Map;for(const t of s.document.model.nodes)for(const e of Object.values(t.outputs))r.set(e,t.id);const o={key:n,fingerprint:e,kernel:Hv,compiled:rw(s),document:Jx(s.document),looks:new Map(s.appearance.map(t=>[t.target,t])),writers:r,asset:s};return SE.set(n,o),SE.size>256&&SE.delete(SE.keys().next().value),o}const EE=new Map;function kE(t,e){rw(e);const n={type:t,compiled:AE(e)};return EE.set(t,n),wE(t,e.document.capabilities.names??[],ow(e).placement),n}function CE(t){return EE.get(t)??null}function TE(t){return EE.has(t)}function OE(t){return EE.delete(t)}function PE(){EE.clear()}const IE=["x","y","z"],DE=new WeakMap;function zE(t){let e=DE.get(t);return e||DE.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,i=IE.every(t=>"number"==typeof n[hb[t]]&&e.some(e=>e.id===hb[t])),s={};if(i)for(const t of IE){const n=e.find(e=>e.id===hb[t]);s[t]={min:n.min??0,max:n.max??1/0}}const r=Nv(t.document.model),o=t.occupancy?.bounds,a=e=>{if(!o)return{x:1,y:1,z:1};const n={...t.designInputs,...t.stateDefaults};if(e)for(const t of IE)n[hb[t]]=e[t];const i=r.evaluate(n).values,s=t=>Math.max((i[o[t].max]??0)-(i[o[t].min]??0),1e-6);return{x:s("x"),y:s("y"),z:s("z")}},c=i?{x:n[hb.x],y:n[hb.y],z:n[hb.z]}:null,l=!i||"uniform"===t.sizing,h=a(c),d={};if(c&&l){const t=Math.min(2,...IE.map(t=>s[t].max/c[t])),e=Math.max(.5,...IE.map(t=>s[t].min/c[t])),n=t>1?t:e<1?e:1;if(1!==n){const t=a({x:c.x*n,y:c.y*n,z:c.z*n});for(const e of IE)d[e]=(t[e]-h[e])/(c[e]*(n-1))}}else if(c)for(const t of IE){const{min:e,max:n}=s[t],i=c[t],r=n>i?Math.min(n,2*i):e<i?Math.max(e,i/2):i;if(r===i)continue;const o=a({...c,[t]:r});d[t]=(o[t]-h[t])/(r-i)}return{evaluated:i,proportional:l,limits:s,authoredInputs:c,authored:h,occupancyAt:a,inputFor:(t,e)=>{if(!c)return e;const n=d[t]??0;return Math.abs(n)>1e-9?c[t]+(e-h[t])/n:c[t]}}}(t)),e}function RE(t){return zE(t).proportional}function jE(t,e,n=[]){const i=zE(t),s=n.find(t=>void 0!==e[t])??"x",r=(t,e)=>{const n=i.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!i.evaluated){const t=Math.max(e[s]/i.authored[s],1e-6);return{inputs:null,scale:t,occupancy:{x:i.authored.x*t,y:i.authored.y*t,z:i.authored.z*t}}}const o=i.authoredInputs;let a;if(i.proportional){let t=Math.max(i.inputFor(s,e[s])/o[s],1e-6);for(const e of IE){const n=i.limits[e];n&&(t=Math.min(Math.max(t,n.min/o[e]),n.max/o[e]))}a={x:o.x*t,y:o.y*t,z:o.z*t}}else a={x:r("x",i.inputFor("x",e.x)),y:r("y",void 0!==e.y?i.inputFor("y",e.y):o.y),z:r("z",i.inputFor("z",e.z))};return{inputs:a,scale:1,occupancy:i.occupancyAt(a)}}const LE=Math.cos(40*Math.PI/180);function FE(e){const[n,i]=fb[e];return([s,r],o)=>{const a={x:0,y:0,z:0};return a[n]=s,a[i]=r,a[e]=o,new t.Vector3(a.x,a.y,a.z)}}class NE{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,i,s,r){for(const[o,a]of[[t,i],[e,s],[n,r]])this.positions.push(o.x,o.y,o.z),this.normals.push(a.x,a.y,a.z)}facing(e,n,i,s){(new t.Vector3).subVectors(n,e).cross((new t.Vector3).subVectors(i,e)).dot(s)<0?this.tri(e,i,n,s,s,s):this.tri(e,n,i,s,s,s)}geometry(){const e=new t.BufferGeometry;return e.setAttribute("position",new t.Float32BufferAttribute(this.positions,3)),e.setAttribute("normal",new t.Float32BufferAttribute(this.normals,3)),e}}function $E(e,n,i,s,r,o){const a=FE(i),c=n.length,l=n.map((t,e)=>{const i=n[(e+1)%c],s=i[0]-t[0],r=i[1]-t[1],a=Math.hypot(s,r)||1;return[o*r/a,-o*s/a]}),h=t=>a(t,0),d=(t,e)=>{const n=l[t],i=l[e];return n[0]*i[0]+n[1]*i[1]<LE?h(n):h([n[0]+i[0],n[1]+i[1]]).normalize()};for(let i=0;i<c;i++){const o=n[i],u=n[(i+1)%c],p=d(i,(i-1+c)%c),f=d(i,(i+1)%c),m=a(o,s),g=a(u,s),y=a(u,r),b=a(o,r),v=h(l[i]);(new t.Vector3).subVectors(g,m).cross((new t.Vector3).subVectors(y,m)).dot(v)>=0?(e.tri(m,g,y,p,f,f),e.tri(m,y,b,p,f,p)):(e.tri(m,y,g,p,f,f),e.tri(m,b,y,p,p,f))}}function HE(e,n,i,s,r,o){const a=FE(i),c=a([0,0],r),l=n.map(([e,n])=>new t.Vector2(e,n)),h=o?[o.map(([e,n])=>new t.Vector2(e,n))]:[],d=t.ShapeUtils.triangulateShape(l,h),u=[...n,...o??[]];for(const[t,n,i]of d)e.facing(a(u[t],s),a(u[n],s),a(u[i],s),c)}const BE=new Map;let YE=0,GE=67108864;function VE(){return{entries:BE.size,bytes:YE,limit:GE}}function UE(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),i=t.extrusion,s=t.cavity,r=t.revolution,o=t.loft,a=i?`${i.axis}:${i.section.kind}:${s?`${"open"===s.start?"o":"c"}${"open"===s.end?"o":"c"}`:"-"}`:r?`${r.axis}:${r.profile.kind}`:o?`${o.axis}:point`:"";return`${t.provider}|${a}|${n}|s${e}|p1`}function WE(t,e=12,n=1/0){const i=UE(t,e),s=BE.get(i);if(s)return s.users++,s.geometry;const r=XE(t,e),o=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(r);if(YE+o>GE||o>n)throw r.dispose(),new Error("figure: geometry bank budget exceeded");return r.userData.figureKey=i,BE.set(i,{geometry:r,users:1,bytes:o}),YE+=o,r}function qE(t){const e=t.userData.figureKey;if(!e)return;const n=BE.get(e);n&&--n.users<=0&&(BE.delete(e),YE-=n.bytes,n.geometry.dispose())}function XE(e,n=12){if("extrude"===e.provider&&e.extrusion)return function(t,e){const n=t.extrusion,i=gw(n.section,n.axis,e),s=new NE;$E(s,i,n.axis,n.start,n.end,1);const r=t.cavity,o=r&&Eb(n.section,n.axis,r.wall);if(!r||!o||!("section"in o))return HE(s,i,n.axis,n.start,-1),HE(s,i,n.axis,n.end,1),s.geometry();const a=gw(o.section,n.axis,e,o.centre),c=n.start+("open"===r.start?0:r.start.closed),l=n.end-("open"===r.end?0:r.end.closed);return $E(s,a,n.axis,c,l,-1),"open"===r.start?HE(s,i,n.axis,n.start,-1,a):(HE(s,i,n.axis,n.start,-1),HE(s,a,n.axis,c,1)),"open"===r.end?HE(s,i,n.axis,n.end,1,a):(HE(s,i,n.axis,n.end,1),HE(s,a,n.axis,l,-1)),s.geometry()}(e,n);if("revolve"===e.provider&&e.revolution)return function(e,n){const i=e.profile;let s;return"half-ellipse"===i.kind?s=new t.SphereGeometry(1,n,Math.max(2,Math.round(n/2))).scale(i.radial,i.axial,i.radial):(s=new t.CylinderGeometry(i.endRadius,i.startRadius,i.end-i.start,n),s.translate(0,(i.start+i.end)/2,0)),"x"===e.axis&&s.rotateZ(-Math.PI/2),"z"===e.axis&&s.rotateX(Math.PI/2),s}(e.revolution,n);const i=e.loft;return"loft"===e.provider&&i?function(e){const[n,i]=fb[e.axis],s=FE(e.axis),r=gw(e.section,e.axis,0),o=s([e.apex[n],e.apex[i]],e.end),a=new NE;HE(a,r,e.axis,e.start,e.end>e.start?-1:1);const c=r.length;for(let n=0;n<c;n++){const i=s(r[n],e.start),l=s(r[(n+1)%c],e.start),h=(new t.Vector3).subVectors(l,i).cross((new t.Vector3).subVectors(o,i)).normalize();a.tri(i,l,o,h,h,h)}return a.geometry()}(i):new t.BufferGeometry}const KE=new Map;let QE=0,JE=0,ZE=67108864;function tk(e,n=1/0){const i=(t=>t.map(t=>UE(t.shape,t.segments)).join(";"))(e),s=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const i=t.pose.r,s=t.pose.t;e.set([i[0][0],i[0][1],i[0][2],i[1][0],i[1][1],i[1][2],i[2][0],i[2][1],i[2][2],s[0],s[1],s[2]],12*n)}),e}(e),r=KE.get(i),o=r?.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 a=e.map(t=>WE(t.shape,t.segments));try{const o=a.map(t=>t.getAttribute("position")?.count??0),c=o.reduce((t,e)=>t+e,0),l=6*c*4;if(l>n)throw new Error("figure: LOD transition budget exceeded");if(JE+l>ZE)return null;const h=new Float32Array(3*c),d=new Float32Array(3*c),u=new Int32Array(e.length+1),p=new t.Matrix4,f=new t.Matrix3;let m=0;e.forEach((t,e)=>{u[e]=m/3;const{r:n,t:i}=t.pose;p.set(n[0][0],n[0][1],n[0][2],i[0],n[1][0],n[1][1],n[1][2],i[1],n[2][0],n[2][1],n[2][2],i[2],0,0,0,1),f.getNormalMatrix(p);const s=p.elements,r=f.elements,c=a[e].getAttribute("position"),l=a[e].getAttribute("normal");for(let t=0;t<o[e];t++,m++){const e=c.getX(t),n=c.getY(t),i=c.getZ(t);if(h[3*m]=s[0]*e+s[4]*n+s[8]*i+s[12],h[3*m+1]=s[1]*e+s[5]*n+s[9]*i+s[13],h[3*m+2]=s[2]*e+s[6]*n+s[10]*i+s[14],!l)continue;const o=l.getX(t),a=l.getY(t),u=l.getZ(t),p=r[0]*o+r[3]*a+r[6]*u,f=r[1]*o+r[4]*a+r[7]*u,g=r[2]*o+r[5]*a+r[8]*u,y=Math.hypot(p,f,g)||1;d[3*m]=p/y,d[3*m+1]=f/y,d[3*m+2]=g/y}}),u[e.length]=m/3;const g=new t.BufferGeometry;g.setAttribute("position",new t.BufferAttribute(h,3)),g.setAttribute("normal",new t.BufferAttribute(d,3)),g.computeBoundingSphere(),g.computeBoundingBox();const y={geometry:g,starts:u,users:1,bytes:l,poses:s};return g.userData.figureMergedKey=i,g.userData.figureMergedEntry=y,r?r.push(y):KE.set(i,[y]),QE++,JE+=l,y}finally{for(const t of a)qE(t)}}function ek(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,i=void 0===e?void 0:KE.get(e);!n||!i?.includes(n)||--n.users>0||(i.splice(i.indexOf(n),1),i.length||KE.delete(e),QE--,JE-=n.bytes,n.geometry.dispose())}function nk(){let t=0;for(const e of KE.values())for(const n of e)t+=n.users;return{entries:QE,users:t,bytes:JE,limit:ZE}}const ik=t=>1e-9*Math.round(t/1e-9)+0;class sk{static carrierJudgeOf(t){let e=sk.carrierJudges.get(t);return e||sk.carrierJudges.set(t,e=function(t,e){const n=e??Jx(t.document).dependence,i=new Map(t.document.model.nodes.map(t=>[t.id,t])),s=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))s.set(t,e);const r=new Set(t.appearance.filter(t=>void 0!==t.visibility).map(t=>t.target)),o=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=s.get(t),i="compose@1"!==n?.op||"string"!=typeof n.args[0]||o(n.args[1])?t:c(n.args[0]);return a.set(t,i),i};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||r.has(n.id))continue;const t=i.get(n.id),s="place@1"===t?.op?t.args[1]:void 0;"string"==typeof s&&o(s)&&!o(t.args[0])&&e.set(n.id,c(s))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=sk.stillJudges.get(t);return e||sk.stillJudges.set(t,e=uw(t.asset,t.document.dependence)),e}constructor(e,n={}){this._lodRevision=0,this._lodGeometryRevision=0,this.boundsAt=-1,this.semanticBounds=new t.Box3,this.group=new t.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.flags=new Map,this.materials=new Map,this.dressed=new Map,this.drawnWith=new Map,this.lastDrawn=null,this.slots=[],this.generation=-1,this.clamped=[],this.compiled=AE(e),this.theme=n.theme??{},this.merge=!1!==n.merge,this._renderLevel=n.renderLevel??"full",this.group.name=`figure:${e.name}`}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 i=this.slots[t];if(i&&"mesh"in i)return n.copy(i.mesh.matrix);if(i&&"entry"in i)return i.entry.set.mesh.getMatrixAt(i.index,n),n;if(i&&"rides"in i){const t=i.rides,s=12*t.ids.indexOf(e.id),r=t.relative;return n.set(r[s],r[s+1],r[s+2],r[s+9],r[s+3],r[s+4],r[s+5],r[s+10],r[s+6],r[s+7],r[s+8],r[s+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(sk.matrixOf(e.pose)):n.identity()}lodBounds(e){if(this.boundsAt!==this._lodRevision){this.semanticBounds.makeEmpty();const e=new t.Matrix4,n=new t.Box3;this.lastDrawn?.geometry.forEach((i,s)=>{if(!("shape"in i)||!("pose"in i)||!1===i.visible)return;let r=sk.shapeBounds.get(i.shape);if(!r){const e=Qb(i.shape);r=new t.Box3(new t.Vector3(e.x.min,e.y.min,e.z.min),new t.Vector3(e.x.max,e.y.max,e.z.max)),sk.shapeBounds.set(i.shape,r)}this.semanticBounds.union(n.copy(r).applyMatrix4(this.bodyMatrix(s,i,e)))}),this.boundsAt=this._lodRevision}return e.copy(this.semanticBounds)}setRenderLevel(e){if(!["full","medium","coarse"].includes(e))throw new Error(`figure: unknown render level ${e}`);if(e===this._renderLevel)return!0;const n=this._renderLevel,i=this.lastDrawn;if(this.lastLodError=void 0,!i||i.geometry.every(t=>db(t,n)===db(t,e)))return this._renderLevel=e,!0;const s=new t.Matrix4,r=i.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={...i,geometry:r},a=ub(o,e),c=[],l=[],h=VE().bytes+nk().bytes,d=()=>sk.LOD_TRANSITION_LIMIT_BYTES-(VE().bytes+nk().bytes-h);try{const e=new Set;for(const t of a.geometry){if(!("shape"in t))continue;const n=UE(t.shape,t.segments);e.has(n)||(e.add(n),c.push(WE(t.shape,t.segments,d())))}const n=fw(a.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf}:{}),i=new Map(a.geometry.map(t=>[t.id,t]));for(const e of[...n.merged,...n.carried]){let n=e.ids.map(t=>i.get(t));if("carrier"in e){const e=(new t.Matrix4).copy(sk.matrixOf(n[0].pose)).invert(),i=new t.Matrix4;n=n.map(t=>{const n=i.multiplyMatrices(e,sk.matrixOf(t.pose)).elements,s=t=>ik(n[t]);return{...t,pose:{r:[[s(0),s(4),s(8)],[s(1),s(5),s(9)],[s(2),s(6),s(10)]],t:[s(12),s(13),s(14)]}}})}const s=tk(n,d());s&&l.push(s.geometry)}if(VE().bytes+nk().bytes-h>sk.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 l)ek(t);for(const t of c)qE(t);return!1}try{return this._renderLevel=e,this.draw(o,this.generation),!0}finally{for(const t of l)ek(t);for(const t of c)qE(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(hb.x)&&e(hb.y)&&e(hb.z)?{x:t[hb.x],y:t[hb.y],z:t[hb.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const i of["x","y","z"]){const s=e.find(t=>t.id===hb[i]);if(!s)continue;const r=t[i],o=Math.min(Math.max(r,s.min??-1/0),s.max??1/0);o!==r&&this.clamped.push({axis:i,asked:r,used:o,bound:o>r?"min":"max"}),n[i]=o}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)),i=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),s={};for(const[r,o]of Object.entries(t??{})){const t=i.get(r);let a;n.has(r)&&t?"number"==typeof o&&Number.isFinite(o)?(o<t.min||o>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:r,value:o,reason:a}),r in this.design&&(s[r]=this.design[r])):s[r]=o}try{this.compiled.document.evaluate({...this.evaluationInputs(),...s}),this.design=s}catch(t){for(const[n,i]of Object.entries(s))e.push({input:n,value:i,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=>sk.clipOf(t)))]}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{units:t,states:e}=this.inputsRead(),n={};for(const e of this.asset.drivers??[]){if(e.state in this.external)continue;const i=t.get(e.state);n[e.state]=nw(e,this.clipTime(sk.clipOf(e)),"deg"===i||"rad"===i?i:"other")}for(const[t,i]of Object.entries(this.external))e.has(t)&&(n[t]=i);return n}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 i="changes"===e.kind?this.fromChanges(e,t):null;this.draw(i??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const i=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||i.has(n)||!t.structure&&!t.changed(n))continue;const s=!0===t.read(n);this.flags.get(n)!==s&&i.add(n),this.flags.set(n,s)}const s=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),r=new Int32Array(s.length).fill(-1);for(let e=0;e<t.bodies.length;e++){if(!t.shapes[e])return null;r[t.bodies[e]]=e}for(let e=0;e<s.length;e++){const n=r[e],o=s[e];if(n<0&&!(o&&i.size&&void 0!==this.flagOf(o)&&i.has(this.flagOf(o))))continue;const a=t.structure?t.structure.ids[e]:o.id,c=t.structure?t.structure.keys[e]:o.key,l={id:a},h=t.structure?t.structure.paths[e]:o.path;void 0!==h&&(l.path=h),void 0!==c&&(l.key=c);const d=t.structure?t.structure.indexes[e]:o.index;if(void 0!==d&&(l.index=d),n>=0){const e=t.poses,i=12*n;l.shape=t.shapes[n],l.pose={r:[[e[i],e[i+1],e[i+2]],[e[i+3],e[i+4],e[i+5]],[e[i+6],e[i+7],e[i+8]]],t:[e[i+9],e[i+10],e[i+11]]}}else l.shape=o.shape,l.pose=o.pose;s[e]=this.dressBody(l)}const o=new Map((t.structure?[]:n.bindings).map(t=>[t.id,t]));for(const e of t.places)o.set(e.id,e);return{geometry:s,bindings:[...o.values()],inputs:e,palette:{...this.asset.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,i=this.compiled.looks.get(n);if(!i)throw new Error(`figure: no appearance for ${n}`);const s=void 0===i.visibility||e(i.visibility);let r=this.materials.get(n);r||this.materials.set(n,r=structuredClone(i.material));const o={...t,material:r,visible:s};return void 0!==i.segments&&(o.segments=i.segments),{dressed:o,visible:s,ref:i.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=sk.matrix,n=new Set;for(let i=0;i<t.bodies.length;i++){const s=this.slots[t.bodies[i]];if(!s)continue;const r=t.poses,o=12*i;if(e.set(r[o],r[o+1],r[o+2],r[o+9],r[o+3],r[o+4],r[o+5],r[o+10],r[o+6],r[o+7],r[o+8],r[o+11],0,0,0,1),!("merged"in s)&&!("rides"in s))if("mesh"in s){s.mesh.matrix.copy(e),s.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(s.id);t&&(t.pose=void 0)}else s.entry.set.setMatrix(s.index,e),n.add(s.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&&sk.pose(t,e.pose)}}draw(e,n){this.lastDrawn=e,this._lodRevision++,this._lodGeometryRevision++,e=ub(e,this._renderLevel);const i=this.planOf(e.geometry),s=new Map(e.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),r=this.drawCarried(i,s,this.drawMerged(i,s)),o=new Set;for(const e of r){const n=s.get(e);if(!("pose"in n))continue;o.add(e);let i=this.meshes.get(e);const r=!1!==n.visible,a=this.drawnWith.get(e);if(!i||!a||a.shape!==n.shape||a.segments!==n.segments){const s=WE(n.shape,n.segments);i?i.geometry!==s?(qE(i.geometry),i.geometry=s):qE(s):(i=new t.Mesh(s,this.materialFor(n)),i.name=e,i.matrixAutoUpdate=!1,this.meshes.set(e,i),r&&this.group.add(i))}a&&a.pose===n.pose||sk.pose(i,n.pose),this.drawnWith.set(e,{shape:n.shape,segments:n.segments,pose:n.pose}),i.castShadow=r,r&&i.parent!==this.group?this.group.add(i):r||i.parent!==this.group||this.group.remove(i)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),qE(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const a=new Set;for(const t of i.batches){a.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 i=WE(e.shape,e.segments);n={set:new lE({geometry:i,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:i},this.batches.set(t.key,n)}const{set:i}=n,r=i.count!==t.ids.length;i.setCount(t.ids.length);const o=i.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=s.get(t);if(!("pose"in n))return;sk.matrixOf(n.pose);const r=sk.matrix.elements;for(let t=0;t<16&&!c;t++)o[16*e+t]!==Math.fround(r[t])&&(c=!0);i.setMatrix(e,sk.matrix)}),n.ids=t.ids,r||!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)a.has(t)||(e.set.object3d.parent===this.group&&this.group.remove(e.set.object3d),e.set.dispose(),qE(e.geometry),this.batches.delete(t));for(const t of e.bindings){const e=this.places.get(t.id);e&&sk.pose(e,t.pose)}const c=new Map;for(const t of this.batches.values())t.ids.forEach((e,n)=>c.set(e,{entry:t,index:n}));for(const t of this.merged.values())for(const e of t.ids)c.set(e,{merged:t});const l=new Map;for(const t of this.carried.values())t.ids.forEach((e,n)=>0===n?l.set(e,t.mesh):c.set(e,{rides:t}));this.slots=e.geometry.map(t=>{const e=this.meshes.get(t.id)??l.get(t.id);return e?{mesh:e,id:t.id}:c.get(t.id)??null}),this.generation=n}drawMerged(e,n){const i=[...e.alone],s=new Set;for(const r of e.merged){const e=r.ids.map(t=>n.get(t));let o=this.merged.get(r.key);if(!(o&&o.ids.length===e.length&&e.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))){const n=tk(e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!n){i.push(...r.ids);continue}if(o)ek(o.mesh.geometry),o.mesh.geometry=n.geometry,o.ids=r.ids,o.starts=n.starts;else{const i=new t.Mesh(n.geometry,this.materialFor(e[0]));i.name=`figure-merged:${this.merged.size}`,i.matrixAutoUpdate=!1,i.castShadow=!0,o={mesh:i,ids:r.ids,starts:n.starts,made:[]},this.merged.set(r.key,o)}o.made=e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose}))}s.add(r.key);const a=!1!==e[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),ek(e.mesh.geometry),this.merged.delete(t));return i}drawCarried(e,n,i){const s=new Set,r=new t.Matrix4,o=new t.Matrix4;for(const a of e.carried){const e=a.ids.map(t=>n.get(t));r.copy(sk.matrixOf(e[0].pose)).invert();const c=e.map(t=>{const e=o.multiplyMatrices(r,sk.matrixOf(t.pose)).elements,n=t=>ik(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)]}}),l=new Float64Array(c.flatMap(t=>[...t.r.flat(),...t.t]));let h=this.carried.get(a.key);if(!(h&&h.ids.length===e.length&&e.every((t,e)=>t.id===h.ids[e]&&t.shape===h.made[e].shape&&t.segments===h.made[e].segments)&&l.every((t,e)=>t===h.relative[e]))){const n=tk(e.map((t,e)=>({shape:t.shape,segments:t.segments,pose:c[e]})));if(!n){i.push(...a.ids);continue}if(h)ek(h.mesh.geometry),h.mesh.geometry=n.geometry,h.ids=a.ids,h.starts=n.starts;else{const i=new t.Mesh(n.geometry,this.materialFor(e[0]));i.name=`figure-carried:${this.carried.size}`,i.matrixAutoUpdate=!1,i.castShadow=!0,h={mesh:i,ids:a.ids,starts:n.starts,made:[],relative:l},this.carried.set(a.key,h)}h.made=e.map(t=>({shape:t.shape,segments:t.segments})),h.relative=l}sk.pose(h.mesh,e[0].pose),s.add(a.key);const d=!1!==e[0].visible;d&&h.mesh.parent!==this.group?this.group.add(h.mesh):d||h.mesh.parent!==this.group||this.group.remove(h.mesh)}for(const[t,e]of this.carried)s.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),ek(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),i}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(e){let n=this.places.get(e);if(n)return n;if(!Yx(this.asset).some(t=>t.id===e))return null;n=new t.Object3D,n.name=`place:${e}`,n.matrixAutoUpdate=!1,this.places.set(e,n),this.group.add(n);const i=this.evaluator&&this.lastDrawn?this.placeNow(e):this.evaluation().bindings.find(t=>t.id===e);return i&&sk.pose(n,i.pose),n}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(sk.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 i=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===i.length&&i.every((t,n)=>t===e.ids[n])||(this.stillOf=sk.stillJudgeOf(this.compiled)(t),this.carriedOf=sk.carrierJudgeOf(this.compiled)(t));const s=this.merge?this.stillOf:void 0,r=fw(t,s?{still:s,carried:this.carriedOf}:{});return this.planned={ids:i,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:r,still:s},r}static matrixOf(t){const e=t.r,n=t.t;return sk.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:i}=e;if(n<0||n>=i[i.length-1])return;let s=0,r=e.ids.length-1;for(;s<r;){const t=s+r+1>>1;i[t]<=n?s=t:r=t-1}return e.ids[s]}}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[hb.x]=this.size.x,t[hb.y]=this.size.y,t[hb.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;return{geometry:e.geometry.map(t=>this.dressOne(t,t=>!0===n[t]).dressed),bindings:e.bindings,inputs:t,palette:{...this.asset.palette}}}dress(t,e){const n=this.dressed,i=new Map,s=t.geometry.map(e=>{const s=n.get(e.id),r=this.dressOne(e,e=>!0===t.values[e]);return void 0!==r.ref&&this.flags.set(r.ref,r.visible),s&&s.body===e&&s.visible===r.visible?(i.set(e.id,s),s.dressed):(i.set(e.id,{body:e,visible:r.visible,dressed:r.dressed}),r.dressed)});return this.dressed=i,{geometry:s,bindings:t.bindings,inputs:e,palette:{...this.asset.palette}}}colourOf(t){return this.theme[t]??this.asset.palette[t]??"#9a9a9a"}materialFor(t){const e=t.material,n=Pd[e.preset??"default"]??Pd.default,i=!!e.emissive?.on,s=i&&e.emissive?this.colourOf(e.emissive.token):this.colourOf(e.token),r=i&&e.emissive?e.emissive.intensity:0,o=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${i?"on":"off"}|${s}|${r}`;return IS.material(o,{color:s,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:e.transparent??!1,opacity:e.transparent?n.opacity??.3:1,emissive:s,emissiveIntensity:r})}meshOf(t){return this.meshes.get(t)}drawnIds(){return[...[...this.meshes.values()].filter(t=>t.parent===this.group).map(t=>t.name),...[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).flatMap(t=>t.ids),...[...this.merged.values(),...this.carried.values()].filter(t=>t.mesh.parent===this.group).flatMap(t=>t.ids)]}dispose(){for(const t of this.meshes.values())t.parent===this.group&&this.group.remove(t),qE(t.geometry);this.meshes.clear(),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(),qE(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),ek(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),ek(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}sk.shapeBounds=new WeakMap,sk.LOD_TRANSITION_LIMIT_BYTES=16777216,sk.matrix=new t.Matrix4,sk.carrierJudges=new WeakMap,sk.stillJudges=new WeakMap;class rk extends Mu{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 CE(this.component.state.type)}getObject3dInstance(){return new t.Group}build(){super.build();const t=this.figure;t&&(this.rig=new sk(t.compiled.asset),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.update(),this.startTicking())}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()}applied(){const t=this.figure?.compiled.asset;if(!t)return null;const{width:e,height:n}=this.component.bounds,i=this.component.state.depth;return jE(t,{x:e,z:n,y:"number"==typeof i&&Number.isFinite(i)&&i>0?i:void 0})}instanceSize(){return this.applied()?.inputs??null}get effectiveDepth(){return this.applied()?.occupancy.y??super.effectiveDepth}get effectiveZPos(){const t=this.component.state.zPos;return"number"==typeof t&&Number.isFinite(t)?t:"ceiling"!==this.figure?.compiled.asset.placement?super.effectiveZPos:function(t,e,n){switch(t){case"inverted":return e;case"space":return e-n/2;default:return e-n}}(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)}seat(){if(!this.rig)return;const t=this.figure?.compiled.asset.placement;if("wall"===t)return this.rig.group.position.y=0,void(this.rig.group.position.z=-this.component.bounds.height/2);this.rig.group.position.z=0;const e=this.effectiveDepth,n=this.effectiveDepth-e,i="ceiling"===t?n:"center"===t?n/2:0;this.rig.group.position.y=-this.effectiveDepth/2+i}get sizeClamps(){return this.rig?.clamped??[]}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.drivers??[];this.unsubscribe||0===t.length||(this.unsubscribe=Rr.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 i=!1;for(const s of e.clips){const r=n[s]??0;Number.isFinite(r)&&0!==r&&(e.setClipTime(s,e.clipTime(s)+t/1e3*r),i=!0)}i&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,i=n?.placeNode(t);if(!n||!i)return;const s=Yx(n.asset).find(e=>e.id===t)?.face,r=s&&Yv[s]||[0,0,0],o=t=>{const n=Number(e?.state?.[t]);return Number.isFinite(n)&&n>0?n/2:0};return{attach:i,localPosition:{x:r[0]*o("width"),y:r[1]*o("depth"),z:r[2]*o("height")}}}clear(){return this.unsubscribe?.(),this.unsubscribe=void 0,this.rig?.dispose(),this.rig=null,super.clear()}}function ok(t,e,n=1){const i=new sk(t.compiled.asset);i.setSize(e);const s=i.evaluateOnce(),r=function(t,e){const n=[];for(const i of t){if(!1===i.visible||!vw(i))continue;let t;try{t=Wv(Uv(i.shape,i.segments),i.pose.r,i.pose.t)}catch{continue}if(t.length<3)continue;const s=t=>t.map(t=>[t[0],t[2]]),r=Math.abs(i.pose.r[1][1]-1)<1e-6,o=i.shape.extrusion;let a;const c=[];if(r&&"y"===o?.axis){const t=(t,e)=>s(Wv(_w(t,o.end,i.segments??12,e),i.pose.r,i.pose.t));a=t(o.section);const e=i.shape.cavity;if(e&&"open"===e.end){const n=Eb(o.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=bw(s(t));const l=i.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:i.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)}(s.geometry,s.palette);return{shapes:1===n?r:r.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]))})),size:i.drawnSize}}const ak=ob,ck=Object.freeze({Capacity:t=>Sw(t),Holdable:t=>DM(t),Transferable:t=>zM(t),FlowNode:t=>RM(t)}),lk=Object.freeze({Capacity:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",Holdable:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",Transferable:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",FlowNode:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다"});function hk(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:[...t.accepts]}))}const dk=new Map;function uk(t,e=[],n){const i=new Set(e),s=[...i].filter(t=>!ak.includes(t));if(s.length>0)throw new Error(`모르는 능력이다: ${s.join(" · ")} — 쓸 수 있는 것은 ${ak.join(" · ")}`);for(const[t,e]of Object.entries(ab))if(i.has(t)&&!e.some(t=>i.has(t)))throw new Error(`${t} 은 혼자 설 수 없다 — ${e.join(" 이나 ")} 가 함께 있어야 한다`);const r=`${[...i].sort().join("+")}|${n??""}`,o=dk.get(r);if(o)return o;const a=0===i.size?t:(c=function(t,e){const n=t.capabilities??[],i=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(i),configurable:!0}),t}(function(t,e){if(e.has("FlowNode"))return ck.FlowNode(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=ck[t](n));return n}(t,i),i),class extends c{get _places(){const t=CE(this.state?.type)?.compiled.asset;return t?Yx(t):null}get slots(){const t=this._places;return t?.length?hk(t):super.slots??[]}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,i=e?.slotId??t?.[tb],s=this._places;return s&&i&&s.some(t=>t.id===i)?this._realObject?.placeAttachment?.(i,t)??n():n()}});var c;const l=void 0===n?a: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}(a,n);return dk.set(r,l),l}function pk(){dk.clear()}const fk={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 mk extends(Pc(Tc)){static registerType(t,e=[],n){const i=Cc.register(t);if(i&&!(i===mk||i.prototype instanceof mk))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const s=uk(mk,e,n);Cc.register(t,s)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=CE(this.state.type);if(!t)return fk;const e=t.compiled.asset,n=e.document.model.inputs,i=(e.publicInputs??[]).flatMap(t=>{const i=n.find(e=>e.id===t.input);return i?[{key:t.input,label:t.label,unit:i.unit,min:i.min,max:i.max,default:e.designInputs[t.input]}]:[]}),s=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]})),r=[...new Set((e.drivers??[]).map(t=>t.clip))].map(t=>({key:t,label:t,min:0,max:3})),o=[...fk.properties];return i.length&&o.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:i}}),s.length&&o.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:s}}),r.length&&o.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),o.length===fk.properties.length?fk:{...fk,properties:o}}buildRealObject(){return TE(this.state.type)?new rk(this):void 0}render(t){const{left:e=0,top:n=0,width:i=0,height:s=0}=this.state,r=CE(this.state.type);if(!r)return void this.renderPlace(t,e,n,i,s);const o=this.topView(r,i,s),a=e+i/2,c="wall"===r.compiled.asset.placement?n:n+s/2;for(const e of o.shapes)if(!(e.outline.length<3)){t.save(),t.fillStyle=e.color,e.transparent&&(t.globalAlpha=.35),t.beginPath();for(const n of[e.outline,...e.holes])if(!(n.length<3)){t.moveTo(a+n[0][0],c+n[0][1]);for(let e=1;e<n.length;e++)t.lineTo(a+n[e][0],c+n[e][1]);t.closePath()}t.fill("evenodd"),t.restore()}}topView(t,e,n){const i=jE(t.compiled.asset,{x:e,z:n,y:this.askedDepth}),s=i.inputs,r=`${t.compiled.fingerprint}|${s?`${s.x}|${s.y}|${s.z}`:`x${i.scale}`}`;return this._top?.key!==r&&(this._top={key:r,view:ok(t,s,i.scale)}),this._top.view}get askedDepth(){const t=this.state.depth;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:void 0}adjustResize(t,e,n){const i=CE(this.state.type);if(!i)return super.adjustResize(t,e,n);const s=i.compiled.asset,r=RE(s),o=super.adjustResize(t,e,n),a=this.bounds,c=[];Math.abs(o.width-a.width)>1e-6&&c.push("x"),Math.abs(o.height-a.height)>1e-6&&c.push("z");const{occupancy:l}=jE(s,{x:o.width,z:o.height,y:r?void 0:this.askedDepth},c);return{left:Math.abs(o.left-a.left)>1e-6?o.left+o.width-l.x:o.left,top:Math.abs(o.top-a.top)>1e-6?o.top+o.height-l.z:o.top,width:l.x,height:l.z}}added(t){super.added(t),this.fitBoxToFigure([])}onchange(t,e){super.onchange(t,e);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)}fitBoxToFigure(t){const e=CE(this.state.type);if(!e)return;const n=e.compiled.asset,i=RE(n),{width:s=0,height:r=0}=this.state,{occupancy:o}=jE(n,{x:s,z:r,y:this.askedDepth},t),a={};Math.abs(o.x-s)>1e-6&&(a.width=o.x),Math.abs(o.z-r)>1e-6&&(a.height=o.z);const c=this.askedDepth;(void 0!==c&&Math.abs(o.y-c)>1e-6||i&&void 0===c&&t.includes("y"))&&(a.depth=o.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,i,s){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,i,s),t.stroke(),t.restore()}postrender(t){Cc.prototype.postrender.call(this,t)}}xE(mk);const gk={"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"},yk=new Map([["default",gk]]);let bk="default",vk=0;function _k(){return vk}function xk(t,e){yk.set(t,e),t===bk&&vk++}function wk(t){if(!yk.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...yk.keys()].join(", ")}`);t!==bk&&(bk=t,vk++)}function Mk(){return bk}function Sk(){return yk.get(bk)}function Ak(t){const e=Sk()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${bk}'). 쓸 수 있는 것 — ${Object.keys(Sk()).join(", ")}`);return e}const Ek=gk["palette.neutral"];function kk(){yk.clear(),yk.set("default",gk),bk="default",vk++}const Ck={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},Tk=["shape","segments"],Ok=["color","preset","transparent","glow"];function Pk(e,n){let i;try{i=XE(e,n)}catch{return null}if(!i?.getAttribute("position"))return null;const s=i.clone();i.dispose(),s.computeBoundingBox();const r=s.boundingBox,o=r.getCenter(new t.Vector3),a=r.getSize(new t.Vector3);return s.translate(-o.x,-o.y,-o.z),s.scale(1/(a.x||1),1/(a.y||1),1/(a.z||1)),s.computeBoundingBox(),s.getAttribute("normal")||s.computeVertexNormals(),{geometry:s,extent:a,centre:o}}class Ik extends Mu{build(){super.build();const e=this.component.state,n=e.shape?Pk(e.shape,e.segments):null;if(!n)return;const i=new t.Mesh(n.geometry,this.material());i.castShadow=!0,i.receiveShadow=!0,this.object3d.add(i),this.mesh=i,this.updateDimension()}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(Tk)?this.update():(super.onchange(t,e),n(Ok)&&this.mesh&&(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=Pd[t.preset??"default"]??Pd.default,n=t.color??"#9a9a9a",i=t.transparent??!1,s=t.glow,r=s?s.color:n,o=s?s.intensity:0;return IS.material(`figure-part|${n}|${t.preset??"default"}|${i}|${s?`${s.color}:${o}`:"-"}`,{color:r,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:i,opacity:i?e.opacity??.3:1,emissive:r,emissiveIntensity:o})}}class Dk extends(Pc(Tc)){static registerType(){Cc.register("figure-part",Dk)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return Ck}buildRealObject(){return new Ik(this)}render(t){const{left:e=0,top:n=0,width:i=0,height:s=0}=this.state;t.beginPath(),t.rect(e,n,i,s),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var zk;Dk.registerType(),function(t){t.compile=Bl,t.duplicate=Yl,t.select=ec,t.match=Ja}(zk||(zk={})),ji.registerResidents(()=>({componentResidentsCount:Cc.residentsCount,sceneResidentsCount:Ju.residentsCount,referenceMapResidentsCount:fS.residentsCount,sceneResidents:Cc.residents}));var Rk=Object.freeze({__proto__:null,AbsoluteLayout:Nc,Animation:Aa,AudioPlayer:ry,BULGE_EPSILON:qr,get Banner(){return EA},Banner3D:AA,BoxSelectionManager:Lf,CAPABILITY_MIXINS:ck,COMMON_PLACEHOLDER_PROPERTIES:kg,CORE_PLACEHOLDER_TYPES:Pg,get Camera(){return PA},Camera3D:OA,CameraBookmarkManager:jf,CameraManager:xf,Capacity:Sw,CapacityEventTracker:By,CardLayout:Hc,CenteringQueueStrategy:Gy,CenteringSlotStrategy:VM,Component:Cc,Connectable:lm,Container:lg,ContainerAbstract:rh,ControlsManager:Af,get Cube(){return _A},Cube3D:vA,get Cylinder(){return MA},Cylinder3D:wA,DEFAULT:Ks,DEFAULT_CEILING:_u,DEFAULT_PALETTE:gk,DEFAULT_PLACEMENT:fu,DEFAULT_SEAT_MARGIN:m_,DPPX:Ws,DataLagTracker:hh,DataSource:zy,DefaultLoadingOverlayRenderer:Vd,Donut:Sy,DonutExtrude:JS,Ellipse:Ag,EllipseExtrude:qS,EventManager3D:Ef,EventMap:fl,FIGURE_CAPABILITIES:ak,FIGURE_CAPABILITY_NOTES:lk,FPS:$p,FigureInstance:mk,FigurePart:Dk,FigurePartRealObject:Ik,FixedSlotStrategy:ib,get FloorPlate(){return BA},FlowEngine:IM,FlowNode:RM,GESTURES:qs,get GLTFObject(){return DA},GLTF_BASE_URL_ALIAS:jy,GenericObject:Og,GeometryBank:iA,GifView:iy,GizmoManager:Cf,GizmoOperationManager:Pf,GlobalRef:py,GltfComponent:Fy,GridStacking:Wy,Group:cy,HOLDER_ANCHOR:Qv,HTMLAbsoluteLayout:Fc,HTMLOverlayContainer:dy,HTMLOverlayElement:Vg,Holdable:DM,ImageView:Gg,InfoWindow:Rc,InstancedSet:lE,InteractionManager:If,ItemsDataBinding:nb,KEYEVENTS:Xs,Layer:bp,Layout:Lc,LightManager:Mf,LightObject:RA,Line:Mg,Line3D:rE,LinearHorizontalLayout:Yc,LinearVerticalLayout:Vc,LoadTracker:ph,LoadingOverlay:Ld,LocalRef:hy,MATERIAL_PRESETS:Pd,MAX_SEGMENTS:aA,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:IS,get Model(){return zk},MoveHandle:ih,NOTHING:Fs,NavGraph:QM,Node:Ty,OrthoLine:Bg,OrthoLine3D:aE,PIXEL_RATIO:Hp,PLACEHOLDER_THEMES:Eg,Path:vy,PatternStacking:Uy,PlacementManager:Df,get PointLight(){return jA},Polygon:Rg,PolygonContainer:Lg,PolygonExtrude:QS,PolygonPathPolyline:sS,Polyline:$g,Polyline3D:oE,Popup:gy,PopupContainer:by,Pose6DOF:_l,RealObject:Mu,RealObjectCamera:pE,RealObjectDomElement:Xp,RealObjectDomTexture:CS,RealObjectDummy:dE,RealObjectExternalModel:Eu,RealObjectExtrude:WS,RealObjectGLTF:Ou,RealObjectGroup:WA,RealObjectLine:sE,RealObjectMesh:DS,RealObjectPlane:fE,RealObjectPlane2D:yE,RealObjectScene:mE,RealObjectService:Oy,RealObjectSprite:fA,RealObjectSprite2D:mA,RealObjectText:$S,Rect:um,RectExtrude:XS,RectPath:Pc,ReferenceMap:fS,RendererManager:wf,ReservationTable:XM,RootContainer:lh,Ruler:fm,SCALE_MIN:tu,SCENE_MODE:Vs,SEGMENT_DEFAULTS:rA,SEGMENT_PRESETS:sA,SHORTCUT_SECTIONS:em,Scene:Ju,SceneManager:_f,ScenePopup:yp,SceneSearchEngine:Ru,ScriptLoader:xS,SearchOverlay:Lu,ServiceComponent:Iy,Shape:Tc,get Sphere(){return pA},Sphere3D:uA,get Sprite(){return yA},Star:ky,StarExtrude:tA,TRANSFER_SLOT_KEY:tb,TableLayout:Uc,Text:oy,ThreeCapability:qf,get ThreeContainer(){return vE},ThreeDOnly:Ry,Tracker:Nu,Transfer:qu,TransitionEffect:nh,Triangle:xy,TriangleExtrude:ZS,UNIT_DIMENSION:su,UNIT_ROTATE:au,UNIT_SCALE:ru,UNIT_TRANSLATE:ou,UNTOKENED_COLOR:Ek,ValueHolder:Dy,VertexGizmoManager:Bf,VolumeStacking:qy,get Wall(){return NA},Wall3D:FA,Z_PRIORITY:gu,acquireFigureGeometry:WE,activePalette:Sk,activePaletteName:Mk,addressOfSlotId:d_,allDestinations:vM,anchorsConnect:Ow,animate:Sa,applyAlpha:nu,applyMaterial3dProps:Rd,applyPolicy:wM,applySeatingRotation:Zy,applyStackLayout:Xy,applyZPriorityToMaterials:bu,arcSegmentTopology:Cw,autoWireBackPressure:Yy,buildArrow3D:Wp,buildContractInspector:hS,buildCoordinateGround:of,buildFigureGeometry:XE,buildFlowGraph:Rw,buildNavGraph:tS,buildShapeFromPolygonPath:KS,buildTether:cp,bulgeFromDrag:Jr,bulgeHandlePosition:Qr,canReach:$w,capability:qm,centerOnBBox:US,chooseNearestPickupFrame:GM,clearTether:hp,collectAdjacentSegments:Vw,compile:ka,componentForNode:bM,computeArcParams:Kr,computeFlowMap:oM,computeStackPositions:Vy,cornerHandlePosition:to,cornerRadiusFromDrag:eo,create:tp,createCanvas:Bp,createCanvasTexture:SS,createFloor:yf,createRealObjectFor:tf,createSelectionHandle3D:YA,dataLagTracker:dh,debug:Zi,deliversInto:Dw,delta:wa,disposeCoordinateGround:hf,disposeObject3D:hu,disposeTether:dp,downstream:AM,drawTextTexture:jS,effectiveCornerRadius:Zr,ellipseOutline:VS,enumerateDataScenarios:Xw,error:Qi,figureClassFor:uk,figureSectionOutline:gw,fillStyleOpacity:eu,filterByToolType:YM,filterShortcuts:nm,findNearestWithCapability:lM,flattenPolygonPath:rS,flowGraphFor:gM,flowGraphIssues:mM,flowReverseFor:aM,fontStyle:zS,footprint2D:Ky,frameClock:Rr,ftId:nM,ftrace:eM,getAllCapabilityMeta:Jm,getCapabilityMeta:Qm,getFigure:CE,getPose:Al,getWorldPose:El,globalSimClock:Dr,gltfNatureProperties:Ly,graphFor:TM,gridCellOf:a_,gridPlacements:hE,gridSlotNo:o_,hasArc:Xr,hasCapability:Wm,hasCapacity:$y,hasFigure:TE,inferCapacity:Hy,inferDownstreamId:Uw,inferFlowDirections:tM,initFontFamilyWatcher:Js,inspector:jd,installContractInspector:dS,isFlowNode:jM,isGenericPlaceholder:Ig,isGeometricHost:cM,isParted:Su,isRoutingTarget:hM,isSegmentPreset:hA,isStateDriven:mu,isThreedEnabled:Iu,judgeItemFit:A_,layoutIssue:Kv,matchOutbounds:zw,metrics:ji,next:SM,nextHop:Nw,nextHops:Fw,nextHopsToAny:Bw,nextHopsToAnyDetailed:Yw,niceGridStep:sf,nodeIdOf:_M,opaqueColor:iu,paletteVersion:_k,partAtByIndex:Au,persistenceIssues:i_,pickWeightedDestination:PM,planPathAStar:eS,planToReservations:nS,pointInRotatedRect:Pw,polygonOffsetForPriority:yu,polygonPathLength:oS,projectToScreen:sp,quatFromYaw:FM,rayAbsDistanceToRect:Iw,reachableByOutbound:jw,reachableDestinations:EM,reachableDestinationsFrom:kM,reachableDestinationsWeightedFrom:CM,reachableSinks:Hw,receiptToJSON:Uu,recommendsLogarithmicDepthForSky:vf,rectFaceAnchors:Aw,rectOutline:GS,rectangularFootprintFrames:HM,registerCapabilityMeta:Km,registerDefaultRealObjectFactory:Zp,registerFigure:kE,registerFigureType:wE,registerPalette:xk,registerRealObjectFactory:Jp,registerTypeResolver:Rl,releaseFigureGeometry:qE,renderCanvasTexture:AS,renderPlaceholder:Cg,reservationTable:KM,resetFigureClasses:pk,resetFigures:PE,resetPalettes:kk,resolveAnchorWorldPosition:ap,resolveHeightSegments:lA,resolveMaterial3d:Id,resolveNextHop:MM,resolveSegments:cA,resolveSlot:l_,resolveToken:Ak,resolveUnknownTypes:Ll,resolveVariant:Qd,rotatedFootprint:y_,sceneComponent:Ny,seatInSlot:b_,seatTransform:v_,setActivePalette:wk,setPose:kl,setThreedEnabled:Du,setWorldPose:Cl,sinksForDestination:yM,slotAddresses:u_,slotCount:s_,slotFrame:f_,slotIdOf:h_,slotNumbers:r_,slotSpaceWarnings:S_,slotsFromBindings:hk,stackSeatTransforms:__,standardYieldPolicy:qM,stopFPSMeasure:Np,straightSegmentEndpoints:kw,straightSegmentMultiInbound:Tw,straightSegmentTopology:Ew,textBounds:NS,textTexture:LS,toThreeSide:zd,topApproachFrame:BM,transferLog:Xu,transferTracer:Gu,uniformZ:no,unitFigurePartGeometry:Pk,unknownTypesOf:jl,unregisterFigure:OE,unresolvedReasonOf:Dl,updateDefaultFontFamily:Qs,updateTether:lp,useFigureComponent:xE,validate:OM,validateFlowGraph:Gw,validateSlotLayout:n_,version:wS,warn:Ji});const jk=globalThis;"undefined"==typeof globalThis||jk.scene||(jk.scene=Rk);export{Nc as AbsoluteLayout,Aa as Animation,ry as AudioPlayer,qr as BULGE_EPSILON,EA as Banner,AA as Banner3D,Lf as BoxSelectionManager,ck as CAPABILITY_MIXINS,kg as COMMON_PLACEHOLDER_PROPERTIES,Pg as CORE_PLACEHOLDER_TYPES,PA as Camera,OA as Camera3D,jf as CameraBookmarkManager,xf as CameraManager,Sw as Capacity,By as CapacityEventTracker,Hc as CardLayout,Gy as CenteringQueueStrategy,VM as CenteringSlotStrategy,Cc as Component,lm as Connectable,lg as Container,rh as ContainerAbstract,Af as ControlsManager,_A as Cube,vA as Cube3D,MA as Cylinder,wA as Cylinder3D,Ks as DEFAULT,_u as DEFAULT_CEILING,gk as DEFAULT_PALETTE,fu as DEFAULT_PLACEMENT,m_ as DEFAULT_SEAT_MARGIN,Ws as DPPX,hh as DataLagTracker,zy as DataSource,Vd as DefaultLoadingOverlayRenderer,Sy as Donut,JS as DonutExtrude,Ag as Ellipse,qS as EllipseExtrude,Ef as EventManager3D,fl as EventMap,ak as FIGURE_CAPABILITIES,lk as FIGURE_CAPABILITY_NOTES,$p as FPS,mk as FigureInstance,Dk as FigurePart,Ik as FigurePartRealObject,ib as FixedSlotStrategy,BA as FloorPlate,IM as FlowEngine,RM as FlowNode,qs as GESTURES,DA as GLTFObject,jy as GLTF_BASE_URL_ALIAS,Og as GenericObject,iA as GeometryBank,iy as GifView,Cf as GizmoManager,Pf as GizmoOperationManager,py as GlobalRef,Fy as GltfComponent,Wy as GridStacking,cy as Group,Qv as HOLDER_ANCHOR,Fc as HTMLAbsoluteLayout,dy as HTMLOverlayContainer,Vg as HTMLOverlayElement,DM as Holdable,Gg as ImageView,Rc as InfoWindow,lE as InstancedSet,If as InteractionManager,nb as ItemsDataBinding,Xs as KEYEVENTS,bp as Layer,Lc as Layout,Mf as LightManager,RA as LightObject,Mg as Line,rE as Line3D,Yc as LinearHorizontalLayout,Vc as LinearVerticalLayout,ph as LoadTracker,Ld as LoadingOverlay,hy as LocalRef,Pd as MATERIAL_PRESETS,aA as MAX_SEGMENTS,Us as MAX_UNDO_SIZE,oA as MIN_SEGMENTS,Bs as MODE_ADD,$s as MODE_EDIT,Gs as MODE_PASTE_DATABIND,Ys as MODE_PASTE_STYLE,Hs as MODE_SHIFT,Ns as MODE_VIEW,IS as MaterialBank,zk as Model,ih as MoveHandle,Fs as NOTHING,QM as NavGraph,Ty as Node,Bg as OrthoLine,aE as OrthoLine3D,Hp as PIXEL_RATIO,Eg as PLACEHOLDER_THEMES,vy as Path,Uy as PatternStacking,Df as PlacementManager,jA as PointLight,Rg as Polygon,Lg as PolygonContainer,QS as PolygonExtrude,sS as PolygonPathPolyline,$g as Polyline,oE as Polyline3D,gy as Popup,by as PopupContainer,_l as Pose6DOF,Mu as RealObject,pE as RealObjectCamera,Xp as RealObjectDomElement,CS as RealObjectDomTexture,dE as RealObjectDummy,Eu as RealObjectExternalModel,WS as RealObjectExtrude,Ou as RealObjectGLTF,WA as RealObjectGroup,sE as RealObjectLine,DS as RealObjectMesh,fE as RealObjectPlane,yE as RealObjectPlane2D,mE as RealObjectScene,Oy as RealObjectService,fA as RealObjectSprite,mA as RealObjectSprite2D,$S as RealObjectText,um as Rect,XS as RectExtrude,Pc as RectPath,fS as ReferenceMap,wf as RendererManager,XM as ReservationTable,lh as RootContainer,fm as Ruler,tu as SCALE_MIN,Vs as SCENE_MODE,rA as SEGMENT_DEFAULTS,sA as SEGMENT_PRESETS,em as SHORTCUT_SECTIONS,Ju as Scene,_f as SceneManager,yp as ScenePopup,Ru as SceneSearchEngine,xS as ScriptLoader,Lu as SearchOverlay,Iy as ServiceComponent,Tc as Shape,pA as Sphere,uA as Sphere3D,yA as Sprite,ky as Star,tA as StarExtrude,tb as TRANSFER_SLOT_KEY,Uc as TableLayout,oy as Text,qf as ThreeCapability,vE as ThreeContainer,Ry as ThreeDOnly,Nu as Tracker,qu as Transfer,nh as TransitionEffect,xy as Triangle,ZS as TriangleExtrude,su as UNIT_DIMENSION,au as UNIT_ROTATE,ru as UNIT_SCALE,ou as UNIT_TRANSLATE,Ek as UNTOKENED_COLOR,Dy as ValueHolder,Bf as VertexGizmoManager,qy as VolumeStacking,NA as Wall,FA as Wall3D,gu as Z_PRIORITY,WE as acquireFigureGeometry,Sk as activePalette,Mk as activePaletteName,d_ as addressOfSlotId,vM as allDestinations,Ow as anchorsConnect,Sa as animate,nu as applyAlpha,Rd as applyMaterial3dProps,wM as applyPolicy,Zy as applySeatingRotation,Xy as applyStackLayout,bu as applyZPriorityToMaterials,Cw as arcSegmentTopology,Yy as autoWireBackPressure,Wp as buildArrow3D,hS as buildContractInspector,of as buildCoordinateGround,XE as buildFigureGeometry,Rw as buildFlowGraph,tS as buildNavGraph,KS as buildShapeFromPolygonPath,cp as buildTether,Jr as bulgeFromDrag,Qr as bulgeHandlePosition,$w as canReach,qm as capability,US as centerOnBBox,GM as chooseNearestPickupFrame,hp as clearTether,Vw as collectAdjacentSegments,ka as compile,bM as componentForNode,Kr as computeArcParams,oM as computeFlowMap,Vy as computeStackPositions,to as cornerHandlePosition,eo as cornerRadiusFromDrag,tp as create,Bp as createCanvas,SS as createCanvasTexture,yf as createFloor,tf as createRealObjectFor,YA as createSelectionHandle3D,dh as dataLagTracker,Zi as debug,Dw as deliversInto,wa as delta,hf as disposeCoordinateGround,hu as disposeObject3D,dp as disposeTether,AM as downstream,jS as drawTextTexture,Zr as effectiveCornerRadius,VS as ellipseOutline,Xw as enumerateDataScenarios,Qi as error,uk as figureClassFor,gw as figureSectionOutline,eu as fillStyleOpacity,YM as filterByToolType,nm as filterShortcuts,lM as findNearestWithCapability,rS as flattenPolygonPath,gM as flowGraphFor,mM as flowGraphIssues,aM as flowReverseFor,zS as fontStyle,Ky as footprint2D,Rr as frameClock,nM as ftId,eM as ftrace,Jm as getAllCapabilityMeta,Qm as getCapabilityMeta,CE as getFigure,Al as getPose,El as getWorldPose,Dr as globalSimClock,Ly as gltfNatureProperties,TM as graphFor,a_ as gridCellOf,hE as gridPlacements,o_ as gridSlotNo,Xr as hasArc,Wm as hasCapability,$y as hasCapacity,TE as hasFigure,Hy as inferCapacity,Uw as inferDownstreamId,tM as inferFlowDirections,Js as initFontFamilyWatcher,jd as inspector,dS as installContractInspector,jM as isFlowNode,Ig as isGenericPlaceholder,cM as isGeometricHost,Su as isParted,hM as isRoutingTarget,hA as isSegmentPreset,mu as isStateDriven,Iu as isThreedEnabled,A_ as judgeItemFit,Kv as layoutIssue,zw as matchOutbounds,ji as metrics,SM as next,Nw as nextHop,Fw as nextHops,Bw as nextHopsToAny,Yw as nextHopsToAnyDetailed,sf as niceGridStep,_M as nodeIdOf,iu as opaqueColor,_k as paletteVersion,Au as partAtByIndex,i_ as persistenceIssues,PM as pickWeightedDestination,eS as planPathAStar,nS as planToReservations,Pw as pointInRotatedRect,yu as polygonOffsetForPriority,oS as polygonPathLength,sp as projectToScreen,FM as quatFromYaw,Iw as rayAbsDistanceToRect,jw as reachableByOutbound,EM as reachableDestinations,kM as reachableDestinationsFrom,CM as reachableDestinationsWeightedFrom,Hw as reachableSinks,Uu as receiptToJSON,vf as recommendsLogarithmicDepthForSky,Aw as rectFaceAnchors,GS as rectOutline,HM as rectangularFootprintFrames,Km as registerCapabilityMeta,Zp as registerDefaultRealObjectFactory,kE as registerFigure,wE as registerFigureType,xk as registerPalette,Jp as registerRealObjectFactory,Rl as registerTypeResolver,qE as releaseFigureGeometry,AS as renderCanvasTexture,Cg as renderPlaceholder,KM as reservationTable,pk as resetFigureClasses,PE as resetFigures,kk as resetPalettes,ap as resolveAnchorWorldPosition,lA as resolveHeightSegments,Id as resolveMaterial3d,MM as resolveNextHop,cA as resolveSegments,l_ as resolveSlot,Ak as resolveToken,Ll as resolveUnknownTypes,Qd as resolveVariant,y_ as rotatedFootprint,Ny as sceneComponent,b_ as seatInSlot,v_ as seatTransform,wk as setActivePalette,kl as setPose,Du as setThreedEnabled,Cl as setWorldPose,yM as sinksForDestination,u_ as slotAddresses,s_ as slotCount,f_ as slotFrame,h_ as slotIdOf,r_ as slotNumbers,S_ as slotSpaceWarnings,hk as slotsFromBindings,__ as stackSeatTransforms,qM as standardYieldPolicy,Np as stopFPSMeasure,kw as straightSegmentEndpoints,Tw as straightSegmentMultiInbound,Ew as straightSegmentTopology,NS as textBounds,LS as textTexture,zd as toThreeSide,BM as topApproachFrame,Xu as transferLog,Gu as transferTracer,no as uniformZ,Pk as unitFigurePartGeometry,jl as unknownTypesOf,OE as unregisterFigure,Dl as unresolvedReasonOf,Qs as updateDefaultFontFamily,lp as updateTether,xE as useFigureComponent,OM as validate,Gw as validateFlowGraph,n_ as validateSlotLayout,wS as version,Ji as warn};
51
51
  //# sourceMappingURL=things-scene.mjs.map